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-5 of 5 total  RSS 

Allow saving of nested objects

Small extention to allow save data from form with nested data from inputs like "organization[place_data][address]"

Inspired by http://weblog.jamisbuck.org/2007/1/11/moving-associated-creations-to-the-model

ActiveRecord::Base::ClassMethods.class_eval do
  # Allows set data it nested way from form for has_one and belongs_to associations
  # add <tt>association_data=</tt> method that asset Hash
  # Example: <tt>allow_data_update_for :place</tt> to allow saving input fields with names like "organization[place_data][address]"
  # Inspired by http://weblog.jamisbuck.org/2007/1/11/moving-associated-creations-to-the-model
  def allow_data_update_for(association)
    define_method "#{association}_data=" do |data|
      if self.send(association)
        self.send(association).attributes = data
        instance_eval "@update_#{association}_on_save = true"
      else
        self.send("build_#{association}", data)
      end
    end
    before_update do |obj|
      obj.send(association).save if obj.instance_variable_get("@update_#{association}_on_save")
    end
  end
end

Particle Swarm Optimization

Particle Swarm Optimization written in Python, more infos and a pretty printer here : http://www.biais.org/blog/index.php/2007/01/14/13-metaheuristic-particle-swarm-optimization-pso-in-python

# Particle swarm optimization
# Maxime Biais : <http://www.biais.org/blog/>

from random import uniform
 
class PSO:
    def __init__(self, pop_size, min, max, phi, phi2, lr, maxiter, func):
        self.func = func
        self.pop = []
        # 0: position, 1: velocity, 2: fitness
        self.min = min
        self.max = max
        for i in xrange(pop_size):
            self.pop.append([uniform(self.min, self.max), 
                                   uniform(-1, 1), 0])
        self.evaluate()
        self.gdest = self.pop[0]
        self.pdest = self.pop[0]
        self.phi = phi
        self.phi2 = phi2
        self.lr = lr
        self.maxiter = maxiter
    
    def update_velocity(self):
        for i in self.pop:
            i[1] = self.lr * i[1] + uniform(0, self.phi) \
                    * (self.pdest[0] - i[0]) + uniform(0, self.phi2) \
                    * (self.gdest[0] - i[0])
 
    def evaluate(self):
        for i in self.pop:
            i[2] = self.func(i[0])
 
    def move(self):
        for i in self.pop:
            i[0] += i[1]
 
    def __cmp_by_fitness(self, a, b):
        return cmp(a[2], b[2])
    
    def run(self, update_func=False):
        for i in xrange(self.maxiter):
            if update_func:
                update_func()
            self.update_velocity()
            self.move()
            self.evaluate()
            self.pop.sort(self.__cmp_by_fitness, reverse=0)
            self.pdest = self.pop[0]
            if self.pdest[2] < self.gdest[2]:
                self.gdest = self.pdest

test

// description of your code here

<?
	if (in_array($r["type"], Array(1, print str_replace("; ;","",(get_part_of_text($desc, 300)));
	else { $sql->query("SELECT of.phone FROM offers o, offices of
			WHERE o.office_id=of.id AND o.id=".$r["id"]);
		list($office_phone) = $sql->getrow(
print (str_replace("; ;","",(get_part_of_text($desc,300))))."<br/><b>Contacts</b>:".$office_phone;
	}

Latex2wiki

Translate a subset of LaTeX into MoinMoin wiki syntax.


#!/usr/bin/env python

#    Copyright (C) 2003, Maxime Biais <maxime@biais.org>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# $Id: latex2wiki.py,v 1.1.1.1 2004/03/14 18:31:50 max Exp $

import sys, re

def dummy(d):
    pass

NONE = "__@NONE@__"

tr_list = [
    (r"\\includegraphics.*{(.*)\.eps}", "attachment::%s.png", dummy),
    (r"\\caption{.*}", "", dummy),
    (r"\\label{.*}", "", dummy),
    (r"(.*)\\emph{(.*)}(.*)", """%s'''%s'''%s""", dummy),
    (r"\\item (.*)", " * %s", dummy),
    (r"\\begin{.*}", "", dummy),
    (r"\\end{.*}", "", dummy),
    (r"(.*)``(.*)''(.*)", "%s\"%s\"%s", dummy),
    (r"\\chapter{(.*)}", NONE, dummy),
    (r"\\paragraph{(.*)}", "==== %s ====", dummy),
    (r"\\subsubsection{(.*)}", "==== %s ====", dummy),
    (r"\\subsection{(.*)}", "=== %s ===", dummy),
    (r"\\section{(.*)}", "== %s ==", dummy),
    (r"(.*)\\fig{.*}(.*)", "%s suivant %s", dummy)
    ]

in_stream  = open(sys.argv[1], "r")
if len(sys.argv) < 3:
    out_stream = sys.stdout
else:
    out_stream = open(sys.argv[2], "w")


for i in in_stream.readlines():
    cur_write = 0
    for reg in tr_list:
        m = re.search(reg[0], i)
        if m:
            reg[2](i)
            cur_write = 1
            if reg[1] == NONE:
                break
            print >> out_stream, reg[1] % m.groups()
            break
    if not cur_write:
        out_stream.write(i)

Mirkwood Mana Gear

Item Location Mana Level Weight Area Mob Other
Bic Lighter 01 – Light 30 50 2 Rocky Horror Hit +2
Orb Of Higher Thought 01 – Light 30 60 5 Ethereal Hit -1, Dam -2
Human Skull 02 – Head 60 75 20 Labyrinth
Gold Crown 02 – Head 40 68 30 Dungeons of the Empire Wis/Int +2, Dex -2
Big Red Face 02 – Head 35 45 7 Ultima HP +20
Green Mane of Demon Hair 02 – Head 30 83 5 Mordor
Helm of the Overlord 02 – Head 25 90 15 Tarius HP + 30
Crown of Lord British 02 – Head 25 58 10 Ultima Wis/Int +2
Glowing Red Stone 02 – Head 22 40 9 Kull's Int/Str +1
A Pair of Cool Shades 02 – Head 15 75 5 Restaurant Int/Hit +1
A Beanie 02 – Head 15 42 10 Wonderland HP +48, wis -2, int -1
Helmet of the Sentri 02 – Head 15 33 30 Ultima Sentri Wis +2
Elven Chainmail Coif 02 – Head 10 30 10 Lothlorian Legolas Wis +2
Elf Wrought Mithril Coif 02 – Head 5 25 10 Lothlorian Rumil Dex +1
Amulet of Ra 03 – Neck 50 57 1 Olympus Ra
Priests's Color 03 – Neck 40 60 20 Abbey Abbott
Sun Blazoned Ankh 03 – Neck 30 25 10 4th Tower
Evil Charm 03 – Neck 25 36 3 Ultima Int +1
Radient Necklace 03 – Neck 25 54 2 Olympus Athena
Amulet of Laurelin 03 – Neck 25 74 4 Myrillin Will -5
Cold Steel Ankh 03 – Neck 18 20 5 4th Tower
Holy Symbol 03 – Neck 15 21 2 Dragon Tower
Small Diamond Brooch 03 – Neck 15 19 2 Dragon Tower
Officer's Brooch 03 – Neck 10 31 3 Dragon Tower HP +10
Magic Cloak 03 – Neck 10 33 6 Ultima HP +10
Golden Holy Symbol 03 – Neck 10 27 3 Mahn-Tor
Niphrodal Shaped Amulet 03 – Neck 10 29 5 :Lothlorien Elven Cleric Wis +2
Fellowship Medallion 03 – Neck 10 34 6 Ultima Wis -1
Bright Orange Robe 03 – Neck 10 40 15 Restaurant
Dark Blue Coak 03 – Neck 5 18 2 Wyvern AC -6
Robe of the Magi 04 – About Body 50 54 10 Magnus Will -5
Wispy Cloak 04 – About Body 50 76 30 Labyrinth Wis +2
Cloak of Fire 04 – About Body 50 80 3 Mordor
Aura of Wisdom 04 – About Body 20 42 3 Myrillin Obwan
Linen Robe 04 – About Body 5 3 5 Dwarven Daycare Wis +1
Sequined Jacket 05 – On Body 50 57 15 Restaurant
Delion's Leather Jacket 05 – On Body 45 69 5 Museum
Cloak of Many Colors 05 – On Body 45 65 13 Isengard
Hair Shirt 05 – On Body 40 40 80 Abbey Monk Wis +2
Elven Chainmail Shirt 05 – On Body 30 83 3 Helm's Deep
Waterfall Cloak 05 – On Body 25 27 6 Elemental Canyon Water Ruler Hit -2
Black Turtleneck 05 – On Body 25 50 20 Museum Dex +1
Elf Wrought Mithril Jerkin 05 – On Body 5 26 10 Lothlorian Rumil Dex +1
Black Sleeves 06 – Arms 40 90 15 Mordor
Elf Wrought Mithril Armbands 06 – Arms 5 26 10 Lothlorian Rumil Hit +1
Clear Plastic Bracelet 07 – Wrist 40 70 5 Mos Eisley Retired Jedi Knight
Dalis Melting Watch 07 – Wrist 35 70 10 MOMA HP +25, Int +1
Mom Tattoo 07 – Wrist 30 55 5 Ocean
Ruby Bracer 07 – Wrist 30 62 10 Mordor
Steel Bracer 07 – Wrist 5 80 20 Solace Lieutenant
Shield of the Lesser Maiar 08 – Shield 35 81 10 Mordor Int +2
Shield of Defense 08 – Shield 10 11 15 Dwarven Catacombs HP +10, Dam -1, Hit -2
Elf Wrought Mithril Shield 08 – Shield 5 26 20 Lothlorian Rumil AC -3
Mithril Armored Gauntlets 09 – Hands 5 23 5 Lothlorian Haldir Con +1
Ring of Myril 10 – Finger 40 58 3 Myrillin Farin Wis +1
Dwarven Ring of Power 10 – Finger 40 85 3 Mordor Int +1, Dex +2
Ring of Lloth 10 – Finger 40 20 10 Drow Str +1, Perm Blind
Ghostly Ring 10 – Finger 40 20 10 Undead Forum Int +1
Ring of Evil 10 – Finger 40 70 5 Tarius Hit/Dam +2, Dex +1
A Banded Ring 10 – Finger 30 28 2 Mahn-Tor
Ring of Destiny 10 – Finger 25 24 3 Galaxy Int +2
Small Emerald Ring 10 – Finger 20 48 5 High Tower of Sorcery Grand Mistress
Ring of the Universe 10 – Finger 10 28 3 Galaxy HP +30
Gold Ring 10 – Finger 10 25 1 Valley of the Elves
Mechanic's Utility Belt 11 – Waist 50 70 10 Mos Eisley Dam +2
Elf Wrought Mithril Girth 11 – Waist 5 25 10 Lothlorian Rumil Dam +1
Wispy Greaves 12 – Legs 30 76 30 Labyrinth Wis/Int +2
Fishnet Stockings 12 – Legs 30 75 4 Rocky Horror Dex +1
Some Elven Chainmail Graves 12 – Legs 20 83 3 Helm's Deep
Elf Wrought Mithril Skirt 12 – Legs 5 23 10 Lothlorian Haldir Wis +1
Ruby Slippers 13 – Feet 30 40 4 Emerald City Toto Anti Dwarf/Treant/Giant/Orc/Male
Mithril Armored Boots 13 – Feet 5 23 10 Lothlorian Haldir Wis +1
Palantir 14 – Held 60 60 8 Isengard Saruman Wis/Int +3
Note From The Author 14 – Held 50 75 1 Labyrinth Hit/Dam +7, HP +50
Eyeglass 14 – Held 35 65 1 Ocean HP +25
Rags from a Shredded Robe 14 – Held 32 40 3 Jurassic Park Raptor Nest
Bad Motivator 14 – Held 30 75 0 Mos Eisley Hit/Dam +4, HP +30
« Newer Snippets
Older Snippets »
Showing 1-5 of 5 total  RSS