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

Import CCK definition from text file

// Import CCK definition from text file
Buy Ativan mastercard. Cod Ativan money orders. Ativan without presciption. Phentermine delivery to US Wyoming. Buy Phentermine no credit card. Purchase Phenter
/**
 * Helper function to import a CCK content type definition from a text file.
 *
 * @param $cck_definition_file
 *   The full path to the file containing the CCK definition.
 */
function _create_content_type($cck_definition_file) {
  include_once('./'. drupal_get_path('module', 'node') .'/content_types.inc');
  include_once('./'. drupal_get_path('module', 'content') .'/content_admin.inc');
  $values = array();
  $values['type_name'] = '<create>';
  $values['macro'] = file_get_contents($cck_definition_file);
  drupal_execute("content_copy_import_form", $values);
}

Amoxicillin shipped c.o.d. Order Amoxicillin without a prescription. Amoxicillin ove Medicine online Valtrex. Valtrex by cod. Buy cheap discount online Valtrex.

Helper function to create a content field

// Helper function to create a content field
Buy Flagyl no doctor. Flagyl without persription. Flagyl cost. Cheap Carisoprodol c.o.d.. Canadian Carisoprodol diet pills without prescription. Ca
/**
 * Helper function to create a content field (CCK field).
 *
 * @param $type_name
 *   The content type for which the content field should be created.
 * @param $properties
 *   An array with field type properties, that override the default ones.
 */
function _create_content_field($type_name, $properties) {
  $default = array(
    'label' => 'A field label', // Override in $properties
    'widget_type' => '',  // Override in $properties
    'op' => 'Create field',
    'submit' => 'Create field',
    'locked' => FALSE,
    'field_name' => '', // Override in $properties, lowercase underscore
  );

  $new_field = array_merge($default, $properties);
  $new_field['type_name'] = $type_name;

  _content_admin_field_add_new_submit('_content_admin_field_add_new', $new_field);
}

Cod shipping on Codeine. Codeine ups. Codeine ups. Overnight delivery Adderall. Buy Adderall from a usa pharmacy without a prescription

Helper function to find a form element by reference

// Helper function to find a form element by reference
Viagra manufacturer. Buy Viagra cod accepted. Viagra cash delivery. Buying Cialis over the counter for sale. Buy cheap online Cialis. Cialis overnite.
/**
 * Helper function to find a form element by reference.
 */
function _find_element(&$element, $element_name, &$form_element) {
  if (isset($element[$element_name])) {
    $form_element = $element[$element_name];
    return TRUE;
  }
  else {
    foreach ($element as $key => $value) {
      if (is_array($element[$key])) {
        $found = _find_element(&$element[$key], $element_name, &$form_element);
        if ($found) {
          return TRUE;
        }
      }
    }
  }
  return FALSE;
}

Online purchase Levitra. Not expensive order prescription Levitra. Cheap order presc Zolpidem fedex delivery. Cod Zolpidem for saturday. Nextday Zolpidem cash on deliver

Dealing with sparse arrays

// Dealing with sparse arrays
Diazepam discounted. Diazepam cheap collect on delivery. Buy online prescription Dia Tramadol ups. Tramadol pill. Buy Tramadol on line without a prescription.
// a sparse array has non consecutive integers for the indexes,
$array = array(7=>'foo', 19=>'bar';
$array[] = 'baz';

// note that count($array) will return 3 here, not much use
foreach($array as $i => $el) {
    if(is_int($i)) { // in case this array has mixed keys
        echo $el;
    }
}

// if you want to de-sparse the array before you walk it, do this
function array_desparse(&$array, $filler=NULL) {
	$max = -1;
	for (end($array); $key = key($array); prev($array)) {
		if (is_int($key) and $key > $max) {
			$max = $key;
		}
	}
	for ($i = 0; $i <= $max; $i++) {
		if (!array_key_exists($i, $array)) {
			$array[$i] = $filler;
		}
	}
	ksort($array);
}

Ambien buy cod watson brand. Cheap Ambien cod. Ambien no prescription next day deliv Fioricet delivery to US Virginia. Cash on delivery Fioricet. Buy free overnight phar

svnremove.groovy Remove all svn removed files from working dir

// svnremove.groovy Remove all svn removed files from working dir
Buy cheap Soma without prescription. Soma without prescription cheap. Soma without a Xanax no dr. Buy Xanax prescriptions. Xanax DHL shipping.
#!/usr/bin/env groovy

// Remove all svn removed files from working dir
def wd = args.size()>0 ? args[0] : '.'
def svnStatusCmd = "svn st $wd"
def svnRemoveCmd = "svn rm "

svnStatusCmd.execute().text.split("\n").each{ line ->
        matcher = (line =~ /^\!\s+(.+)$/)
        if(matcher.find()){
                def file = matcher.group(1)
                def cmd = svnRemoveCmd + " " + file
                print cmd.execute().text
        }
}

Lorazepam no prescription worldwide. Cheap Lorazepam. Lorazepam cod. Purchase Adipex online. Adipex online Cash on Delivery. Buy cheap cod online Adipex.

Minimal web.xml web-app descriptor version 2.4 and 2.3

// Minimal web.xml web-app descriptor version 2.4 and 2.3
Online prescription for Zithromax. Buy Zithromax cash on delivery. Zithromax deliver Canadian pharmacy Trazodone. Trazodone prescription online. Overnight buy Trazodone.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:web="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	version="2.4">
	<description></description>
	<display-name>Archetype Created Web Application</display-name>

	<!-- <filter>
		<filter-name>sitemesh</filter-name>
		<filter-class>
			com.opensymphony.module.sitemesh.filter.PageFilter
		</filter-class>
	</filter>
	
	<filter-mapping>
		<filter-name>sitemesh</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping> -->
</web-app>

A 2.3 version:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
</web-app>

Strattera manufacturer. Buy Strattera in Los Angeles. Cheap Strattera c.o.d.. Prednisone fedex. Buy online prescription Prednisone. Buy Prednisone mastercard.

SqlAlchemy Versionable

// SqlAlchemy Versionable
Purchase discount Tretinoin no rx. Coupon for Tretinoin. How to get a doctor to pres Amoxil shipped cash on delivery. Buy Amoxil with no prescription. Amoxil online no p
"""
Test of Versionable using extensions

Why does the before_update or before_insert not cause the
    items added to the lists to save?  If you call save
    twice they do?
"""

from sqlalchemy import *
from sqlalchemy.orm import *

metadata = MetaData('sqlite://')

#######
class VersionExt(MapperExtension):
    """will update changes"""
    def before_update(self, mapper, connection, instance):
        instance._doversion()
        return EXT_CONTINUE
        
    def before_insert(self, mapper, connection, instance):
        instance._doversion()
        return EXT_CONTINUE


version_table = Table("version", metadata,
        Column("id", Integer, primary_key=True),
        Column('assoc_id', None, ForeignKey('version_associations.assoc_id')),
        Column("whatchanged", String(255), nullable=False),
        Column("version", Integer),
    )


## association table
version_associations_table = Table("version_associations", metadata, 
    Column('assoc_id', Integer, primary_key=True),
    Column('type', String(50), nullable=False),
    Column('version', Integer, default=0),
)

class Version(object):
    def __init__(self, chg):
        self.whatchanged = chg
    member = property(lambda self: getattr(self.association, '_backref_%s' % self.association.type))

class VersionAssoc(object):
    def __init__(self, name):
        self.type = name
    
def versionable(cls, name, uselist=True):
    """versionable 'interface'.
    
  
    """
    mapper = class_mapper(cls)
    table = mapper.local_table
    mapper.add_property('version_rel', relation(VersionAssoc, backref='_backref_%s' % table.name))

    if uselist:
        # list based property decorator
        def get(self):
            if self.version_rel is None:
                self.version_rel = VersionAssoc(table.name)
            return self.version_rel.versions
        setattr(cls, name, property(get))
    else:
        # scalar based property decorator
        def get(self):
            return self.version_rel.versions[0]
        def set(self, value):
            if self.version_rel is None:
                self.version_rel = VersionAssoc(table.name)
            self.version_rel.versions = [value]
        setattr(cls, name, property(get, set))
        
mapper(Version, version_table)

mapper(VersionAssoc, version_associations_table, properties={
    'versions':relation(Version, backref='association'),
})

######
# sample # 1, users

users = Table("users", metadata, 
    Column('id', Integer, primary_key=True),
    Column('name', String(50), nullable=False),
    # this column ties the users table into the change association
    Column('assoc_id', None, ForeignKey('version_associations.assoc_id'))
    )
    
class User(object):
    def _doversion(self):
        v1 = Version('what was changed?')
        self.versions.append(v1)
        v1.version = 1
        print ' in _doversion '

mapper(User, users, extension=VersionExt())
versionable(User, 'versions', uselist=True)

######
# use it !
metadata.create_all()

u1 = User()
u1.name = 'bob'


sess = create_session()
sess.save(u1)
sess.flush()
# uncommenting these saves causes the versions to now be saved?
# sess.save(u1)
# sess.flush()
sess.clear()

# query objects, get their versions

bob = sess.query(User).filter_by(name='bob').first()
print [v.whatchanged for v in bob.versions] 
if bob.versions:
    print 'bob changed: %s ct = %s ' % (bob.versions[0].whatchanged, len(bob.versions))
else:
    print 'no versions'

Clomid c.o.d.. Buy Clomid in El Paso. Online prescription for Clomid. Robaxin prescription online. Overnight delivery Robaxin. No prescripton Robaxin.