Welcome

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 (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

teknopaylasim.net

thanx

Subscribe to a RSS feed of your posts

// description of your code here

// insert code here..


// insert code here..


/*
* This script depends on the Prototype JavaScript library
* http://prototypejs.org
*/

var Inflector = Class.create();

Inflector.prototype = {
/*
* The order of all these lists has been reversed from the way
* ActiveSupport had them to keep the correct priority.
*/
plural: [
[/(quiz)$/i, "$1zes" ],
[/^(ox)$/i, "$1en" ],
[/([m|l])ouse$/i, "$1ice" ],
[/(matr|vert|ind)ix|ex$/i, "$1ices" ],
[/(x|ch|ss|sh)$/i, "$1es" ],
[/([^aeiouy]|qu)y$/i, "$1ies" ],
[/(hive)$/i, "$1s" ],
[/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
[/sis$/i, "ses" ],
[/([ti])um$/i, "$1a" ],
[/(buffal|tomat)o$/i, "$1oes" ],
[/(bu)s$/i, "$1ses" ],
[/(alias|status)$/i, "$1es" ],
[/(octop|vir)us$/i, "$1i" ],
[/(ax|test)is$/i, "$1es" ],
[/s$/i, "s" ],
[/$/, "s" ]
],
singular: [
[/(quiz)zes$/i, "$1" ],
[/(matr)ices$/i, "$1ix" ],
[/(vert|ind)ices$/i, "$1ex" ],
[/^(ox)en/i, "$1" ],
[/(alias|status)es$/i, "$1" ],
[/(octop|vir)i$/i, "$1us" ],
[/(cris|ax|test)es$/i, "$1is" ],
[/(shoe)s$/i, "$1" ],
[/(o)es$/i, "$1" ],
[/(bus)es$/i, "$1" ],
[/([m|l])ice$/i, "$1ouse" ],
[/(x|ch|ss|sh)es$/i, "$1" ],
[/(m)ovies$/i, "$1ovie" ],
[/(s)eries$/i, "$1eries"],
[/([^aeiouy]|qu)ies$/i, "$1y" ],
[/([lr])ves$/i, "$1f" ],
[/(tive)s$/i, "$1" ],
[/(hive)s$/i, "$1" ],
[/([^f])ves$/i, "$1fe" ],
[/(^analy)ses$/i, "$1sis" ],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, "$1$2sis"],
[/([ti])a$/i, "$1um" ],
[/(n)ews$/i, "$1ews" ],
[/s$/i, "" ]
],
irregular: [
['move', 'moves' ],
['sex', 'sexes' ],
['child', 'children'],
['man', 'men' ],
['person', 'people' ]
],
uncountable: [
"sheep",
"fish",
"series",
"species",
"money",
"rice",
"information",
"equipment"
],
initialize: function() {
// Nothing here now
},
ordinalize: function(number) {
if (11 <= parseInt(number) % 100 && parseInt(number) % 100 <= 13) {
return number + "th";
} else {
switch (parseInt(number) % 10) {
case 1: return number + "st";
case 2: return number + "nd";
case 3: return number + "rd";
default: return number + "th";
}
}
},
pluralize: function(word) {
for (var i = 0; i < this.uncountable.length; i++) {
var uncountable = this.uncountable[i];
if (word.toLowerCase() == uncountable) {
return uncountable;
}
}
for (var i = 0; i < this.irregular.length; i++) {
var singular = this.irregular[i][0];
var plural = this.irregular[i][1];
if ((word.toLowerCase() == singular) || (word == plural)) {
return plural;
}
}
for (var i = 0; i < this.plural.length; i++) {
var regex = this.plural[i][0];
var replace_string = this.plural[i][1];
if (regex.test(word)) {
return word.replace(regex, replace_string);
}
}
},
singularize: function(word) {
for (var i = 0; i < this.uncountable.length; i++) {
var uncountable = this.uncountable[i];
if (word.toLowerCase() == uncountable) {
return uncountable;
}
}
for (var i = 0; i < this.irregular.length; i++) {
var singular = this.irregular[i][0];
var plural = this.irregular[i][1];
if ((word.toLowerCase() == singular) || (word == plural)) {
return singular;
}
}
for (var i = 0; i < this.singular.length; i++) {
var regex = this.singular[i][0];
var replace_string = this.singular[i][1];
if (regex.test(word)) {
return word.replace(regex, replace_string);
}
}
}
}

function ordinalize(number) {
var i = new Inflector;
return i.ordinalize(number);
}

/*
* pluralize expects between 2 to 3 arguments.
* 1. The count of items to pluralize
* 2. The singular form of the item to pluralize
* 3. The plural form of the item to pluralize (optional)
*/
function pluralize() {
var i = new Inflector;

var count = arguments[0];
var singular = arguments[1];
var plural = arguments[2];

if (arguments.length < 2) return "";
if (isNaN(count)) return "";

return count + " " + (1 == parseInt(count) ?
singular :
plural || i.pluralize(singular));
}

function singularize(plural) {
var i = new Inflector;
return i.singularize(plural);
}

Compile & install cdecl on Mac OS XX

// description of your code here

// insert code here..


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
public static void main(String[] a) throws Exception {
JPAUtil util = new JPAUtil();

EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
EntityManager em = emf.createEntityManager();
ProfessorService service = new ProfessorService(em);

em.getTransaction().begin();

service.executetQuery("SELECT e.name, e.salary FROM Professor e");

util.checkData("select * from Professor");

em.getTransaction().commit();
em.close();
emf.close();
}
}


File: Address.java


import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Address {
@Id
private int id;
private String street;
private String city;
private String state;
private String zip;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getStreet() {
return street;
}

public void setStreet(String address) {
this.street = address;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getZip() {
return zip;
}

public void setZip(String zip) {
this.zip = zip;
}
public String toString() {
return "Address id: " + getId() +
", street: " + getStreet() +
", city: " + getCity() +
", state: " + getState() +
", zip: " + getZip();
}

}

Get String Properties From Entitiesss

// description of your code here

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JPAUtil {
  Statement st;
  
  public JPAUtil() throws Exception{
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa", "");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public void executeSQLCommand(String sql) throws Exception {
    st.executeUpdate(sql);
  }
  public void checkData(String sql) throws Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        } else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}

Failed generation of resource route for action

// description of your code here

These methods test that the routes for resources defined in routes.rb are working as expected. Call them from your functional (controller) tests.

Add the following 3 methods to test/test_helper.rb (updated for Rails 1.2.5 which no longer uses semicolons as a separator for the edit action):

# Test for routes generated by map.resource (singular).
def assert_routing_for_resource(controller, skip=[], nesting=[])
  routes = [
    ["new",'/new',{},:get], ["create",'',{},:post],
    ["show",'',{},:get], ["edit",'/edit',{},:get],
    ["update",'',{},:put], ["destroy",'',{},:delete]
    ]
  check_resource_routing(controller, routes, skip, nesting)
end
# Test for routes generated by map.resources (plural).
def assert_routing_for_resources(controller, skip=[], nesting=[])
  routes = [
    ["index",'',{},:get], ["new",'/new',{},:get], ["create",'',{},:post],
    ["show",'/1',{:id=>'1'},:get], ["edit",'/1/edit',{:id=>'1'},:get],
    ["update",'/1',{:id=>'1'},:put], ["destroy",'/1',{:id=>'1'},:delete]
    ]
  check_resource_routing(controller, routes, skip, nesting)
end

# Check that the expected paths will be generated by a resource, and that
# the expected params will be generated by paths defined by a resource.
# routes is array of [action, url string after controller, extra params].
def check_resource_routing(controller, routes, skip=[], nesting=[])
  # set a prefix for nested resources
  prefix = nesting.join('s/1/')
  unless prefix.blank?
    prefix += "s/1/"
  end
  # Add params for nested resources.
  # For each 'nest', include a ":nest_id=>'1'" param.
  params = {}
  nesting.each do |param|
    params["#{param}_id".to_sym] = '1'
  end
  # Test each of the standard resource routes.
  routes.each do |pair|
    unless skip.include? pair[0]
      assert_generates("/#{prefix}#{controller}#{pair[1]}",
        {:controller=>controller,
        :action=>pair[0]}.merge(pair[2]).merge(params), {}, {},
        "Failed generation of resource route for action #{pair[0]} /#{prefix}#{controller}#{pair[1]}")
      assert_recognizes(
        {:controller=>controller,
          :action=>pair[0]}.merge(pair[2]).merge(params),
        {:path=>"/#{prefix}#{controller}#{pair[1]}", :method=>pair[3]},
        {}, "Failed to recognize resource route for path #{pair[3]}:/#{prefix}#{controller}#{pair[1]}")
    end
  end
end










Extending acts_as_taggable for real-world

// description of your code here

// insert code here..


// description of your code here

// insert code here..


/*
 * This script depends on the Prototype JavaScript library
 * http://prototypejs.org
 */

var Inflector = Class.create();

Inflector.prototype = {
    /*
     * The order of all these lists has been reversed from the way 
     * ActiveSupport had them to keep the correct priority.
     */
    plural: [
        [/(quiz)$/i,               "$1zes"  ],
        [/^(ox)$/i,                "$1en"   ],
        [/([m|l])ouse$/i,          "$1ice"  ],
        [/(matr|vert|ind)ix|ex$/i, "$1ices" ],
        [/(x|ch|ss|sh)$/i,         "$1es"   ],
        [/([^aeiouy]|qu)y$/i,      "$1ies"  ],
        [/(hive)$/i,               "$1s"    ],
        [/(?:([^f])fe|([lr])f)$/i, "$1$2ves"],
        [/sis$/i,                  "ses"    ],
        [/([ti])um$/i,             "$1a"    ],
        [/(buffal|tomat)o$/i,      "$1oes"  ],
        [/(bu)s$/i,                "$1ses"  ],
        [/(alias|status)$/i,       "$1es"   ],
        [/(octop|vir)us$/i,        "$1i"    ],
        [/(ax|test)is$/i,          "$1es"   ],
        [/s$/i,                    "s"      ],
        [/$/,                      "s"      ]
    ],
    singular: [
        [/(quiz)zes$/i,                                                    "$1"     ],
        [/(matr)ices$/i,                                                   "$1ix"   ],
        [/(vert|ind)ices$/i,                                               "$1ex"   ],
        [/^(ox)en/i,                                                       "$1"     ],
        [/(alias|status)es$/i,                                             "$1"     ],
        [/(octop|vir)i$/i,                                                 "$1us"   ],
        [/(cris|ax|test)es$/i,                                             "$1is"   ],
        [/(shoe)s$/i,                                                      "$1"     ],
        [/(o)es$/i,                                                        "$1"     ],
        [/(bus)es$/i,                                                      "$1"     ],
        [/([m|l])ice$/i,                                                   "$1ouse" ],
        [/(x|ch|ss|sh)es$/i,                                               "$1"     ],
        [/(m)ovies$/i,                                                     "$1ovie" ],
        [/(s)eries$/i,                                                     "$1eries"],
        [/([^aeiouy]|qu)ies$/i,                                            "$1y"    ],
        [/([lr])ves$/i,                                                    "$1f"    ],
        [/(tive)s$/i,                                                      "$1"     ],
        [/(hive)s$/i,                                                      "$1"     ],
        [/([^f])ves$/i,                                                    "$1fe"   ],
        [/(^analy)ses$/i,                                                  "$1sis"  ],
        [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/i, "$1$2sis"],
        [/([ti])a$/i,                                                      "$1um"   ],
        [/(n)ews$/i,                                                       "$1ews"  ],
        [/s$/i,                                                            ""       ]
    ],
    irregular: [
        ['move',   'moves'   ],
        ['sex',    'sexes'   ],
        ['child',  'children'],
        ['man',    'men'     ],
        ['person', 'people'  ]
    ],
    uncountable: [
        "sheep",
        "fish",
        "series",
        "species",
        "money",
        "rice",
        "information",
        "equipment"
    ],
    initialize: function() {
        // Nothing here now
    },
    ordinalize: function(number) {
        if (11 <= parseInt(number) % 100 && parseInt(number) % 100 <= 13) {
            return number + "th";
        } else {
            switch (parseInt(number) % 10) {
                case  1: return number + "st";
                case  2: return number + "nd";
                case  3: return number + "rd";
                default: return number + "th";
            }
        }
    },
    pluralize: function(word) {
        for (var i = 0; i < this.uncountable.length; i++) {
            var uncountable = this.uncountable[i];
            if (word.toLowerCase() == uncountable) {
                return uncountable;
            }
        }
        for (var i = 0; i < this.irregular.length; i++) {
            var singular = this.irregular[i][0];
            var plural   = this.irregular[i][1];
            if ((word.toLowerCase() == singular) || (word == plural)) {
                return plural;
            }
        }
        for (var i = 0; i < this.plural.length; i++) {
            var regex          = this.plural[i][0];
            var replace_string = this.plural[i][1];
            if (regex.test(word)) {
                return word.replace(regex, replace_string);
            }
        }
    },
    singularize: function(word) {
        for (var i = 0; i < this.uncountable.length; i++) {
            var uncountable = this.uncountable[i];
            if (word.toLowerCase() == uncountable) {
                return uncountable;
            }
        }
        for (var i = 0; i < this.irregular.length; i++) {
            var singular = this.irregular[i][0];
            var plural   = this.irregular[i][1];
            if ((word.toLowerCase() == singular) || (word == plural)) {
                return singular;
            }
        }
        for (var i = 0; i < this.singular.length; i++) {
            var regex          = this.singular[i][0];
            var replace_string = this.singular[i][1];
            if (regex.test(word)) {
                return word.replace(regex, replace_string);
            }
        }
    }
}

function ordinalize(number) {
    var i = new Inflector;
    return i.ordinalize(number);
}

/*
 * pluralize expects between 2 to 3 arguments.
 * 1. The count of items to pluralize
 * 2. The singular form of the item to pluralize
 * 3. The plural form of the item to pluralize (optional)
 */
function pluralize() {
    var i = new Inflector;
    
    var count    = arguments[0];
    var singular = arguments[1];
    var plural   = arguments[2];
    
    if (arguments.length < 2) return "";
    if (isNaN(count))         return "";
    
    return count + " " + (1 == parseInt(count) ?
            singular :
            plural || i.pluralize(singular));
}

function singularize(plural) {
    var i = new Inflector;
    return i.singularize(plural);
}

Compile & install cdecl on Mac OS X


# 1. readline

# first compile and install the latest version of readline (into /usr/local/lib)
open http://tiswww.case.edu/php/chet/readline/rltop.html

# let's make sure we use standard system libs & files
sudo mv -i /opt/local /opt/local-off
sudo mv -i /usr/local /usr/local-off

#sudo mv -i /opt/local-off /opt/local
#sudo mv -i /usr/local-off /usr/local


cd ~/Desktop

fwftp   # open ipfw firewall for ftp (cf. http://codesnippets.joyent.com/posts/show/1284)

curl -L -O ftp://ftp.cwru.edu/pub/bash/readline-6.1.tar.gz

fwdef   # restore default ipfw rules

tar -xzf readline-6.1.tar.gz

cd readline-6.1

./configure

make

sudo mv -i /usr/local-off /usr/local

sudo make install

sudo mv -i /opt/local-off /opt/local



find ~/Desktop/readline-6.1 -name "*dylib"
ls -1 /usr/local/lib/*readline*

[[ -d /usr/local ]] && sudo mkdir -p /usr/local/src || echo 'mkdir failed!'

sudo cp ~/Desktop/readline-6.1.tar.gz /usr/local/src

tar -C /usr/local/src -xzf ~/Desktop/readline-6.1.tar.gz

find /usr/local/src/readline-6.1 -name "*compat.c"

otool -L /usr/local/lib/*readline*6*



# 2. cdecl

# compile & install cdecl (into /usr/local/bin; with readline support)

open http://www.cdecl.org

cd ~/Desktop

curl -L -O http://cdecl.org/files/cdecl-blocks-2.5.tar.gz

tar -xzf cdecl-blocks-2.5.tar.gz

cd cdecl-blocks-2.5


# edit Makefile
sed -i "" -E \
   -e 's/^( *CFLAGS *=.+)/\1 -Ddodebug -Ddoyydebug -DUSE_READLINE/' \
   -e 's|^ *LIBS *=.+|LIBS= -L/usr/local/lib -lreadline -L/usr/lib -lncurses|' \
   -e 's|^ *BINDIR *=.+|BINDIR= /usr/local/bin|' \
   -e 's|^ *MANDIR *=.+|MANDIR= /usr/local/share/man/man1|' \
   -e 's|^ *CATDIR *=.+|CATDIR = /usr/local/share/man/cat1|' \
   Makefile


# edit cdecl.c
sed -i "" -E \
   -e 's/^([[:space:]]*)void cdecl_setprogname\(char \*\);/\1void cdecl_setprogname(char const *);/' \
   -e 's/^ *char *\*progname *= *"cdecl";/char const *progname = "cdecl";/' \
   -e 's/char *\*argv0/char const *argv0/' \
   -e 's/^( *rl_completion_entry_function *= *\()( *[^ ]+ *)(\* *\)keyword_completion;)/\1 rl_compentry_func_t \3/' \
  cdecl.c


# add some include statements to cdecl.c
cat <<-'EOF' | sed -e 's/^ *//' -e 's/ *$//' | /bin/ed -s cdecl.c
   H
   /^[[:space:]]\{0,\}#[[:space:]]\{0,\}include[[:space:]]\{0,\}<readline\/readline.h>/a

   #include </usr/local/src/readline-6.1/compat.c>
   #include </usr/local/include/readline/readline.h>
   //#include </usr/local/include/readline/rltypedefs.h>

   .
   /^[[:space:]]\{0,\}#[[:space:]]\{0,\}include[[:space:]]\{0,\}<readline\/readline.h>/d
   wq
EOF

# open -e cdecl.c Makefile

make

make test

echo $?

sudo make install


ls -l "$(type -P cdecl)"
otool -L "$(type -P cdecl)"
type -a c++decl cdecl
ls -l $(type -P c++decl cdecl)

man cdecl
cdecl --help

cdecl
explain int (*(*foo)(void ))[3]
declare bar as volatile pointer to array 64 of const int
cast foo into block(int, long long) returning double
explain char ** const * const x
declare x as const pointer to const pointer to pointer to char
[ctrl-c]

Get String Properties From Entities

// description of your code here

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JPAUtil {
  Statement st;
  
  public JPAUtil() throws Exception{
    Class.forName("org.hsqldb.jdbcDriver");
    System.out.println("Driver Loaded.");
    String url = "jdbc:hsqldb:data/tutorial";

    Connection conn = DriverManager.getConnection(url, "sa", "");
    System.out.println("Got Connection.");
    st = conn.createStatement();
  }
  public void executeSQLCommand(String sql) throws Exception {
    st.executeUpdate(sql);
  }
  public void checkData(String sql) throws Exception {
    ResultSet rs = st.executeQuery(sql);
    ResultSetMetaData metadata = rs.getMetaData();

    for (int i = 0; i < metadata.getColumnCount(); i++) {
      System.out.print("\t"+ metadata.getColumnLabel(i + 1)); 
    }
    System.out.println("\n----------------------------------");

    while (rs.next()) {
      for (int i = 0; i < metadata.getColumnCount(); i++) {
        Object value = rs.getObject(i + 1);
        if (value == null) {
          System.out.print("\t       ");
        } else {
          System.out.print("\t"+value.toString().trim());
        }
      }
      System.out.println("");
    }
  }
}

Get Two Properties From Entity

// description of your code here


import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
  public static void main(String[] a) throws Exception {
    JPAUtil util = new JPAUtil();

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService");
    EntityManager em = emf.createEntityManager();
    ProfessorService service = new ProfessorService(em);

    em.getTransaction().begin();

    service.executetQuery("SELECT e.name, e.salary FROM Professor e");
    
    util.checkData("select * from Professor");

    em.getTransaction().commit();
    em.close();
    emf.close();
  }

}


File: Address.java


import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Address {
    @Id
    private int id;
    private String street;
    private String city;
    private String state;
    private String zip;
    
    public int getId() {
        return id;
    }
    
    public void setId(int id) {
        this.id = id;
    }
    
    public String getStreet() {
        return street;
    }
    
    public void setStreet(String address) {
        this.street = address;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getZip() {
        return zip;
    }

    public void setZip(String zip) {
        this.zip = zip;
    }
    public String toString() {
        return "Address id: " + getId() + 
               ", street: " + getStreet() +
               ", city: " + getCity() +
               ", state: " + getState() +
               ", zip: " + getZip();
    }

}

This is a subversion pre-commit hook

// This is a subversion pre-commit hook

#!/usr/bin/env ruby

repo_path = ARGV[0]
transaction = ARGV[1]
svnlook = '/usr/bin/svnlook'

commit_dirs_changed = `#{svnlook} dirs-changed #{repo_path} -t #{transaction}`
commit_changed = `#{svnlook} changed #{repo_path} -t #{transaction}`
#commit_author = `#{svnlook} author #{repo_path} -t #{transaction}`.chop
commit_log = `#{svnlook} log #{repo_path} -t #{transaction}`
#commit_diff = `#{svnlook} diff #{repo_path} -t #{transaction}`
#commit_date = `#{svnlook} date #{repo_path} -t #{transaction}`

# ******* Migration check ********
# if this is a migration then check that there is not already a migration with the same version number in the repository
files = commit_changed.split(/\n/)
current_migrations = nil
for file in files
  if(file =~ /A\s*(.*?\/migrate\/)(\d+)(.*)/)
    migration_path = $1
    migration_version = $2
    
    if(current_migrations == nil)
      current_migrations = {}
      migration_files = `#{svnlook} tree #{repo_path} #{migration_path}`
      for migration in migration_files
        current_migrations[$1] = true if(migration =~ /\s*(\d+)_(.*)/)
      end
    end
    
    if(current_migrations[migration_version])
     STDERR.puts("The is a pre-existing migration with version #{migration_version} in #{migration_path}")
     exit(1)
    end
  end
end