Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 18 total  RSS 

Ruby method to determine if a string would look more readable on black vs. white.

// description of your code here

def self.ideal_font_color_for(hex_str)
	hex_str = hex_str.split('#').last

	threshold = 105

	r = hex_str[0..1].hex
	g = hex_str[2..3].hex
	b = hex_str[4..5].hex

	delta = (r*0.299) + (g*0.587) + (b*0.114)

	255 - delta < threshold ? "#000000" : "#FFFFFF"
end

Print color highlighted strings to unix terminal

Sample of escape sequences needed to print in color to unix/linux terminal.

print x.replace('toostis', '\033[0;31mtoostis\033[m')


This will highlight all 'toostis' instances in x with red.

Retrieve the color from an SVG shape

    <rect id="c1" x="510"
y="120" width="20px" height="20px" fill="pink" stroke="blue" onclick="setPenColour(evt)"/>
  <![CDATA[
  function setPenColour(evt) {
    m_pen_colour = evt.target.getAttribute('fill');
  }
  ]]>

Reference:
Tutorials - SVG [kevlindev.com]
Tutorials - SVG - Events [kevlindev.com]

Unix Console Styler

This modue can be used to apply many style on Unix* terminals

# Unix Console Style
# You can use this module to apply a style on the terminal
#
# <b>DON'T WORK ON WINDOWS (Only on Unix* Terminal)</b>

module UnixConsoleStyle
  # Availables Styles
  STYLE = {
      :default    =>    "\033[0m",
    	# styles
    	:bold       =>    "\033[1m",
    	:underline  =>    "\033[4m",
    	:blink      =>    "\033[5m",
    	:reverse    =>    "\033[7m",
    	:concealed  =>    "\033[8m",
    	# font colors
    	:black      =>    "\033[30m", 
    	:red        =>    "\033[31m",
    	:green      =>    "\033[32m",
    	:yellow     =>    "\033[33m",
    	:blue       =>    "\033[34m",
    	:magenta    =>    "\033[35m",
    	:cyan       =>    "\033[36m",
    	:white      =>    "\033[37m",
    	# background colors
    	:on_black   =>    "\033[40m", 
    	:on_red     =>    "\033[41m",
    	:on_green   =>    "\033[42m",
    	:on_yellow  =>    "\033[43m",
    	:on_blue    =>    "\033[44m",
    	:on_magenta =>    "\033[45m",
    	:on_cyan    =>    "\033[46m",
    	:on_white   =>    "\033[47m" }
  
  # Methods to use if you want to apply a style
  def UnixConsoleStyle::apply_style(style)
    STDOUT.write STYLE[style]
  end
  
end

Gradient in an applet

import java.awt.*;
import java.applet.*;
import javax.swing.*;

public class JavaAppDe extends JApplet {
	
    public void init() {
    }
	
    public void paint (Graphics g) {
        super.paint(g);
	int base = 0;
	while(base<255) {
		g.setColor(new Color(base,base,base));
		g.drawLine(0,base,255,base);
		base++;
	}
    }
}

Linux - command ls without color

// Elimina tutti i caratteri speciali che portano il colore

ls --color=never

Colorize Function

/*
I don't use the flash colorize function much so this is an example of how to colorize a movieclip with a supplied hexnumber

colorize(0xff0000,my_movieClip);

//will turn my_movieClip bright red.
*/
function colorize(c:Number,mc:MovieClip){
  var tf:Transform = new Transform(mc);
  var color_tf:ColorTransform = new ColorTransform();
  color_tf.rgb = c;
  tf.colorTransform = color_tf;
};

Color Picker drop-down box helper

// description of your code here
This helper will generate a whole bunch o' colors in a drop down box, which which you can do whatever with. Currently I am allowing users to change certain colors of the page.
     def color_picker(name)
       #build the hexes
      hexes = []
       (0..15).step(3) do |one|
         (0..15).step(3) do |two|
           (0..15).step(3) do |three|
            hexes << "#" + one.to_s(16) + two.to_s(16) + three.to_s(16)
           end
         end
       end
       arr = []
       10.times { arr << "&nbsp;" }
         returning html = '' do
        html << "<select name=#{name}>"
        html << hexes.collect {|c|
          "<option value='#{c}' style='background-color: #{c}'>#{arr.join}</option>" }.join("\n")
        html << "</select>"
      end
     end

Python - change_color_entry

// Cambia il colore di sfondo di una gtk.Entry, ma il discorso vale anche
// per la gtk.TextView...

import gtk

def change_color_entry(entry, color):
    entry.modify_base(gk.STATE_NORMAL, gtk.gdk.color_parse(color))

Using &lt;font> (font tag) within pys60 Text widget

The Text widget allow rich text. However, it's quite
difficult to use. You need to set each attribute
(font, style, highlight, color) of the widget
before adding more text with differert style.

So, I make a function that make it a bit easier.
The font tag (<font></font>) is used (borrowed from HTML).
Attributes allowed are
- color ( #RRGGBB or 0xRRGGBB or color name)
- face ( both font and size eg. albi17b )
- style ( bold, italic, underline or strikethrough )
(styles can be combined using comma)
- highlight ( standard, rounded, shadow)
- hcolor ( highlight color )
from appuifw import *

def process_color(color):
    color_name = {
        'red': 0xff0000, 'green': 0x008000, 'blue':0x0000ff,       
        'black': 0,      'white':0xffffff,      'yellow': 0xffff00
        }
    if color.startswith('#'):   # HTML format #000000
        return int(color[1:], 16)
    if color.startswith('0x'):  # pys60 format 0x000000
        return int(color, 16)
    return color_name[color]

def set_ml(t, s):
    stack = []
    t.clear()
    t.font = 'normal'
    i = 0
    while i < len(s):
        if s.startswith('<', i):  # tag end or tag begin
            j = s.find('>', i) + 1
            if s[i:i+7] == '</font>' or s[i:i+3] == '</>':
                t.color, t.font, t.style, t.highlight_color = stack.pop()
            else:
                stack.append([t.color, t.font, t.style, t.highlight_color])
                to_style = 0
                for attr_val in s[i:j-1].split(' '):
                    if '=' in attr_val:
                        attr, val = attr_val.split('=')
                        if attr == 'color':
                            t.color = process_color(val)
                        elif attr == 'face':
                            t.font = unicode(val)
                        elif attr == 'hcolor':
                            t.highlight_color = process_color(val)
                        elif attr == 'style':   # style and highlight go together
                            to_style |= eval('|'.join(['STYLE_' + st.upper() for st in val.split(',')]))
                        elif attr == 'highlight':
                            to_style |= eval("HIGHLIGHT_" + val.upper())
                if to_style:
                    t.style = to_style
        else:    # normal text
            j = s.find('<', i)
            if j == -1: j = len(s)
            text = u'' + s[i:j].replace('&lt;', '<')
            t.add(text)
        i = j      # go next chunk


Now you can use it easily
>>> t = app.body   # use the default Text widget that start pys60
>>> set_ml(t, '<font color=red>Hello</font> <font style=bold>World</font>.')
>>>  # a stylish 'Hello World' is displayed

Notice:
- Quotation marks are not used to specify attribute values.
- A </> shorthand can be used for </font>
- <font> can be nested.
« Newer Snippets
Older Snippets »
Showing 1-10 of 18 total  RSS