working on it ...


Explore Public Snippets

Sort by

Found 1,111 snippets matching: patterns

    public by MarcoDeMagistris modified Apr 5, 2013  1878186  260  5  0

    Java: How to create a log4j Logger Manager using Singleton

    How to create a log4j Logger Manager using Singleton
    * LoggerManager class
    * This class implements log4j using Singleton
    import org.apache.log4j.Logger;
    import org.apache.log4j.xml.DOMConfigurator;
    public class LoggerManager {
    	public enum LogLevel {DEBUG, INFO, WARNING, ERROR, FATAL};
    	private static LoggerManager obj;
    	private Logger oLog;
    	private LoggerManager(){
    		* Config.xml: file path used to configure log4j
    	public LoggerManager(Logger logger) {
    	private void setLogger(Logger _oLog)
    		oLog = _oLog;
    	public static LoggerManager getLogger(){
    		if (obj == null)
    			obj = new LoggerManager(Logger.getLogger(LoggerManager.class));
    		return obj;
    	public void Log(String _sMsg, LoggerManager.LogLevel _eLogLevel){
    			case DEBUG:
    			case INFO:;
    			case WARNING:
    			case ERROR:
    			case FATAL:
    * Main class
    * ex. Logger Manager example
    public class Main {
    	public static void main(String[] args) {
    		LoggerManager.getLogger().Log("Starting Main", LoggerManager.LogLevel.INFO);

    public by SamHall modified Jan 22, 2014  565140  73  6  1

    Amazing - Pure CSS Background Patterns Enjoy !!

    These patterns are simply beautiful, I will give credit back to the author as soon as I find the Link, but be rest assured they do have a full royalty free use license for both commercial and non commercial use
    radial-gradient(hsl(0, 100%, 27%) 4%, hsl(0, 100%, 18%) 9%, hsla(0, 100%, 20%, 0) 9%) 0 0,
    radial-gradient(hsl(0, 100%, 27%) 4%, hsl(0, 100%, 18%) 8%, hsla(0, 100%, 20%, 0) 10%) 50px 50px,
    radial-gradient(hsla(0, 100%, 30%, 0.8) 20%, hsla(0, 100%, 20%, 0)) 50px 0,
    radial-gradient(hsla(0, 100%, 30%, 0.8) 20%, hsla(0, 100%, 20%, 0)) 0 50px,
    radial-gradient(hsla(0, 100%, 20%, 1) 35%, hsla(0, 100%, 20%, 0) 60%) 50px 0,
    radial-gradient(hsla(0, 100%, 20%, 1) 35%, hsla(0, 100%, 20%, 0) 60%) 100px 50px,
    radial-gradient(hsla(0, 100%, 15%, 0.7), hsla(0, 100%, 20%, 0)) 0 0,
    radial-gradient(hsla(0, 100%, 15%, 0.7), hsla(0, 100%, 20%, 0)) 50px 50px,
    linear-gradient(45deg, hsla(0, 100%, 20%, 0) 49%, hsla(0, 100%, 0%, 1) 50%, hsla(0, 100%, 20%, 0) 70%) 0 0,
    linear-gradient(-45deg, hsla(0, 100%, 20%, 0) 49%, hsla(0, 100%, 0%, 1) 50%, hsla(0, 100%, 20%, 0) 70%) 0 0;
    background-color: #300;
    background-size: 100px 100px;
    \* Name says it all on this one *\
    starrynight {
    radial-gradient(white, rgba(255,255,255,.2) 2px, transparent 40px),
    radial-gradient(white, rgba(255,255,255,.15) 1px, transparent 30px),
    radial-gradient(white, rgba(255,255,255,.1) 2px, transparent 40px),
    radial-gradient(rgba(255,255,255,.4), rgba(255,255,255,.1) 2px, transparent 30px);
    background-size: 550px 550px, 350px 350px, 250px 250px, 150px 150px;
    background-position: 0 0, 40px 60px, 130px 270px, 70px 100px;
    \* dark grey with the small dotted holes in a tight pattern well done *\
    CarbomFiber {
    radial-gradient(black 15%, transparent 16%) 0 0,
    radial-gradient(black 15%, transparent 16%) 8px 8px,
    radial-gradient(rgba(255,255,255,.1) 15%, transparent 20%) 0 1px,
    radial-gradient(rgba(255,255,255,.1) 15%, transparent 20%) 8px 9px;
    background-size:16px 16px;
    \* Two shades of gray *\
    Carbon {
    linear-gradient(27deg, #151515 5px, transparent 5px) 0 5px,
    linear-gradient(207deg, #151515 5px, transparent 5px) 10px 0px,
    linear-gradient(27deg, #222 5px, transparent 5px) 0px 10px,
    linear-gradient(207deg, #222 5px, transparent 5px) 10px 5px,
    linear-gradient(90deg, #1b1b1b 10px, transparent 10px),
    linear-gradient(#1d1d1d 25%, #1a1a1a 25%, #1a1a1a 50%, transparent 50%, transparent 75%, #242424 75%, #242424);
    background-color: #131313;
    background-size: 20px 20px;
    \* clean well done notebook paper-narrow ruled *\
    lined Paper {  
    background-color: #fff;
    linear-gradient(90deg, transparent 79px, #abced4 79px, #abced4 81px, transparent 81px),
    linear-gradient(#eee .1em, transparent .1em);
    background-size: 100% 1.2em;

    public by MarcoDeMagistris modified Oct 3, 2013  292201  6  5  0

    Upload File

    Upload File MVC4 patterns
            public ActionResult Index()
                return View();
    		  private HttpPostedFileBase File { get; set; }
            #region PROPERTIES
            [Display(Name = "Upload your .txt File")]
            [FileExtensions(Extensions = "txt", ErrorMessage = "The file you selected is not a valid .txt file")]
            [Required(ErrorMessage = ".txt file not selected")]
            public HttpPostedFileBase File1
                get { return this.File; }
                set { this.File = value; }
    	<div id="Componentsdiv">
        @using (Html.BeginForm(<action>, <Controller>, FormMethod.Post, new { enctype = "multipart/form-data" }))
                <legend>Upload TXT File</legend>
                <div class="editor-label">
                        @Html.TextBoxFor(m => m.File1, "Select new file", new {  id="firstfile", type = "file"})
                        @Html.ValidationMessageFor(m => m.File1)
                    <input type="submit" id="submitbutton" hidden="hidden"/>

    public by MarcoDeMagistris modified Apr 5, 2013  234884  4  4  0

    My First Snippet: How to create a singleton in C#

    This is the first example of a snippet: - the title represents in few words which is the exact issue the snippet resolves; it can be something like the name of a method; - the description (this field) is an optional field where you can add interesting information regarding the snippet; something like the comment on the head of a method; - the c
    public class MyClass 
       private static MyClass s_current; 
       private static object s_objSync = new object(); 
       private MyClass() {} 
       public static MyClass Instance 
               if (s_current == null) 
                   lock (s_objSync) 
                       if (s_current == null) 
                           s_current = new MyClass(); 
               return s_current; 

    public by mike modified Feb 17, 2013  130671  1  4  -1

    A singleton implementation in Java

    Java code for singleton design pattern
    public class SingletonClass {
    	static SingletonClass singleton;
    	static { 
    		singleton = new SingletonClass();
    	private SingletonClass() {
    		//init here...
    	public static SingletonClass get() { 
    		return singleton;

    public by mprisznyak modified Jun 14, 2014  364066  0  6  11


    a tongue-in-cheek example for the adapter pattern
    demonstrate the adapter pattern
    looking up adapters in a registry is also demonstrated
    You really want a Lion because some roaring is needed however your Cat can meow only.
    For animal rights reasons, you cannot change your Cat directly but a Cat2Lion adapter will still do the job.
    class SexError(Exception):
        def __str__(self):
            return "Sorry, try Eurovision instead. All our felines are either males or females."
    class Feline(object):
        cats and lions are felines
        def __init__(self, name, sex="male"):
   = name
            if sex in ["male", "female"]:
        = sex
                raise SexError()
        def groom(self):
            sex2pronoun = {"male": ["he", "him"], "female": ["she", "her"]}
            nominative, objective = sex2pronoun[]        
            print "{name} licks {objective_pronoun}self and {nominative_pronoun} is going to be very well-groomed!".format(
                    name =,
                    objective_pronoun = objective,
                    nominative_pronoun = nominative,
    #  these are protected animals you cannot alter
    class Cat(Feline):
        def meow(self):
            return "Meow, meow!"
    class Lion(Feline):
        def roar(self):
            return "Roar, roar!"
    class Adapter(object):
        a generic object adapter you should derive your own adapters from
        def __init__(self, adaptee):
            self.adaptee = adaptee
        def __getattr__(self, item):
            # delegate attributes
            return getattr(self.adaptee, item)
    class AdapterRegistry(object):
        a singleton which registers adapters and 
        provides an adapter factory method called 'adapt'
        adapters = {}
        def register(klass, from_, to_, adapter):
            klass.adapters[(from_, to_)] = adapter
        def adapt(klass, from_object, to_class):
                from_class = from_object.__class__
                adapter = klass.adapters[(from_class, to_class)]
                return adapter(from_object)
            except KeyError:
                raise Exception("it's impossible to turn a {from_name} into a {to_name}".format(
                            from_name = from_class.__name__),
                            to_name   = to_class.__name__
    # no cat is harmed during this alteration
    class Cat2Lion(Adapter):
         make a kitty roar
        def grooms(self):
        def roar(self):
            print "{name}, the cat says:".format(,
            return self._convert_voice(self.adaptee.meow())
        def _convert_voice(self, voice):
            voice = voice.lower()
            voice = voice.replace("meow", "roar")
            voice = voice.capitalize()
            return voice
    if __name__ == "__main__":
        mici = Cat("Mici", "female")
        AdapterRegistry.register(Cat, Lion, Cat2Lion) # cats may be turned into lions
        pocket_lion = AdapterRegistry.adapt(mici, Lion)
        # in fact pocket_lion, an adapted 'mici' object, is a Cat2Lion but she does behave like a Lion
        print, "is a", pocket_lion.__class__.__name__
        pocket_lion.grooms()  # lions can groom themselves
        print pocket_lion.roar()  # and now Mici, the kitty can roar, too!
        print "*"*80
        mici.groom() # cats can groom themselves
        mici.roar()  # cats just cannot roar properly...

    public by mprisznyak modified Aug 4, 2015  1528  5  6  2

    Command design pattern

    A generic implementation for the Command design pattern It's demonstrated by two toy examples: 1/ a lamp which can be turned on and off 2/ a car which can be started up, filled up with petrol and driven. Some commands have parameters in this example.
    # -*- coding: utf-8 -*-
    Command design pattern
    class Command(object):
        """ generic command class
        def __init__(self, action, target):
            if callable(action):
                self._action = action
                raise Exception("callable action required")
   = target
        def execute(self, *args):
    class CommandClient(object):
        """Generic command client class"""
        def __init__(self, subject):
            self.subject = subject
            self._commands = {}
        def reset_subject(self):
        def add_command(self, command_name, action):
            :param command_name: the name of the command
            :type command_name: string
            :param action: a method of 'subject'
            :type action: string
            command_name = command_name.strip().upper()
            action = getattr(self.subject, action, None)
            if action:
                self._commands[command_name] = Command(action, self.subject)
                raise Exception("invalid action %s" % action)
        def execute(self, cmd, *args):
            :param cmd: command name
            :type cmd: string
            :param args: possible arguments for command
            :type args: optional input parameters for command
            cmd = cmd.strip().upper()
            command = self._commands.get(cmd)
            if command is None:
                print 'Unknown command ', cmd
        def query(self, attr):
            :param attr: name of attribute for 'subject'
            :type attr: string
            return getattr(self.subject, attr, "Undefined")
    class Light(object):
        """An example command receiver class"""
        ON = "ON"
        OFF = "OFF"
        def __init__(self):
            self.state = Light.OFF
        def turn_on(self):
            print "Switching the lights on"
            self.state = Light.ON
        def turn_off(self):
            print "Switching the lights off"
            self.state = Light.OFF
    class Car(object):
        """Another example command receiver class"""
        PETROL_IN_100 = 6.5
        def __init__(self):
            self.engine_running = False
            self.speed = 0.0
            self.fuel = 0.0
        def start(self):
            if self.fuel > 0.0:
                print "The car engine is starting..."
                self.engine_running = True
                print "The car tank is empty"
        def drive(self, distance):
            " drive distance kilometres"
            if self.engine_running:
                fuel_required = distance*self.PETROL_IN_100/100.0
                if self.fuel < fuel_required:
                    print "The car needs fuel"
                    print "  travelled %s kms" % distance
                    self.fuel -= fuel_required
                    print "  %s litres of petrol left" % self.fuel
                print "Car engine hasn't been started..."
        def fill_up_with_petrol(self, amount):
            self.fuel += amount
    if __name__ == "__main__":
        print "========= Lights ==========="
        light_switch = CommandClient(Light())
        light_switch.add_command("ON", "turn_on")
        light_switch.add_command("OFF", "turn_off")
        print "The lamp is", light_switch.query("state")
        print "The lamp is", light_switch.query("state")
        print "Invalid Command for lights"
        print "Lamp is", light_switch.query("state")
        print "====== Fine ride ========"
        car_ride = CommandClient(Car())
        car_ride.add_command("fill", "fill_up_with_petrol")
        car_ride.add_command("Start", "start")
        car_ride.add_command("DRIVE", "drive")
        car_ride.execute("FILL", 15)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 34)
        print "==== Fool's ride  ======="
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 77)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("FILL", 15)
        car_ride.execute("DRIVE", 18843)
        print "fuel: ", car_ride.query("fuel")            

    public by mprisznyak modified Aug 31, 2013  938  10  5  2


    A design pattern which extends the singleton pattern to a map of named singleton instances. The construction of instances (cls() ) is not generic.
    def multiton(cls):
        instances = {}
        def get_instance(name):
            if name not in instances:
                instances[name] = cls()
            return instances[name]
        return get_instance
    class MyClass:
    assert a is b 
    assert not(a is c)

    public by mprisznyak modified May 1, 2014  612  1  5  4

    Chain of responsibility

    a tongue-in-cheek example for the chain of responsibility pattern
    The chain of responsibility pattern aims at minimizing the coupling  between request senders and request receivers.
    The patter provides  more than one object a chance to handle the request. The request travels along the chain until an object is found which can handle it.
    class Handler(object):
        def __init__(self, next_handler):
            self.next_handler = next_handler
        def name(self):
            klass_name = self.__class__.__name__
            return klass_name.lower()
        def handle(self, request):
                handler = getattr(self, request)
            except AttributeError as e:
                # pass on request
                print "   passing request '{request}' from {from_} to {name}".format(request=request,,
    class Boss(Handler):
        def __init__(self, employee):
            super(Boss, self).__init__(employee)
        def shout(self):
            print "Hey!!"
    class Employee(Handler):
        def __init__(self, wife):
            super(Employee, self).__init__(wife)
        def quarrel(self):
            print "you're so nasty, darling!"
    class Wife(Handler):
        def __init__(self, kid):
            super(Wife, self).__init__(kid)
        def tell_off_kid(self):
            print "{name} says to {next_in_chain}... 'you're a bad boy!' ".format(,
    class Kid(Handler):
        def __init__(self, dog):
            super(Kid, self).__init__(dog)
        def kick_the_dog(self):
            print "The dog is kicked... and says",
    class Dog(object):
        def __init__(self):
   = "Rex"
        def handle(self, anything):
        def woof(self):
            print "woof!"
    if __name__ == '__main__':
        # let's build the chain
        pete = Kid(Dog())
        mary = Wife(pete)
        john = Employee(mary)
        pmb  = Boss(john)
        # boss shouts like mad
        # kid will be told off
        # dog will be kicked
        # employee will argue with wife
        # employee cannot tell wife off so poor dog will bark
        # employee cannot shout... poor dog will bark

    public by mprisznyak modified Apr 5, 2014  665  2  5  3

    Hybrid publish-subscribe messaging

    a toy example with media publishers, media channels and viewers
    A somewhat non-trivial toy example for the publish-subscribe messaging pattern
    It demonstrates  hybrid message filtering which combines a topic-based approach  with a content-based one
    Message production and publication are decoupled.
    MediaPublishers create Programmes for Channels and the publish these there.
    Customers subscribe for programmes they are interested in but the Channels 
    also enforce age limit restrictions on these subscribers when they notify them.
    from random import choice, randint
    class Topics(object):
        enumerate programme topics
        SCIFI = "sci-fi films"
        ACTION = "action films"
        FAMILY = "family films"
        ROMANCE = "romantic films and soap operas"
        CARTOON = "cartoons"
        FOOTBALL = "football programmes"
        def all_topics(klass):
            return [getattr(klass, attr) for attr  in klass.__dict__ if attr == attr.upper()]
    class Programme(object):
        these are messages produced by MediaPublishers and received by Customers from Channels
        def __init__(self, topic, description, age_limit, publisher_name):
            self.topic = topic
            self.description = description
            self.age_limit = age_limit
            self.publisher_name = publisher_name
        def __str__(self):
            return """
            Topic: {self.topic}
            Age limit: {self.age_limit}
            produced by {self.publisher_name}
    class Channel(object):
        mediator objects where messages are published by MediaPublishers 
        and where Customers subscribe for notification
        def __init__(self, name):
   = name
            self.programmes = []
            self.customers = []
        def schedule(self, programme):
        def subscribe(self, customer):
            #print "{customer_name} has subscribed to channel {channel_name}".format(,
        def notify_consumers(self):
            notify all interested subscribers provided they are allowed to watch the programme
            for customer in self.customers:        # iterate  over subscribers
                for programme in self.programmes:  # iterate through received messages, that is programmes
                    topic = programme.topic
                    age_limit = programme.age_limit
                    if topic in customer.interests:  # topic-based filtering
                        if age_limit > customer.age: # content-based filtering
                            print "{customer_name} cannot watch {programme.description}".format(, programme=programme)
                        print "    on channel '{name}'\n".format(
    class MediaPublisher(object):
        message publisher
        def __init__(self, name):
   = name
        def get_programme(self, topic ):
            builder method for Programmes
            descriptions = {Topics.CARTOON: ["Tom and Jerry", "The Flintstones"],
                           Topics.FOOTBALL: ["the Champions Leage final", "a boring football match", "the World Cup semifinal"],
                           Topics.ACTION:  ["The Terminator", "Rambo XVIII", "Robocop", "Die hard 8"],
                           Topics.FAMILY:  ["Santa Clause gone mad", "Fishing on the lake", "The return of Easter Bunny"],
                           Topics.ROMANCE: ["Antonio and Cleopatra", "Love till you drop dead", "Never-ending love story"],
                           Topics.SCIFI: ["Star Wars XXVII", "Star Trek", "Andromeda", "Babylon 9"],
            description = choice(descriptions[topic])
            if topic in (Topics.CARTOON, Topics.FOOTBALL, Topics.FAMILY): # kids safe
                age_limit = 0
                if randint(1,3) == 3:
                    age_limit = 0
                    age_limit = 14
            return Programme(topic, description, age_limit, )
        def provide(self, channel, topic):
            MediaPublisher sends a programme to Channel in this topic
            programme = self.get_programme(topic)
    class Customer(object):
        message subscriber
        def __init__(self, name, age):
   = name
            self.age = age
            self.interests = []
        def add_interest(self, interest):
        def subscribe(self, channel):
        def watch(self, programme):
            print "{name} is going to watch a {programme.description} made by {programme.publisher_name}".format(,
        def __str__(self):
            return """
            Customer records:
                name : {}
                age  : {self.age}
                interests: {self.interests}
    if __name__ == "__main__":
        # initialize system
        john = Customer("John Doe", 45)
        mary = Customer("Mary Popkins", 54)
        pete = Customer("Pete Little", 9)
        funcaster = Channel("The Funstatic Caster")
        kill_your_time = Channel("Kill All Your Time with US")
        public_services = Channel("Taxpayer paid")
        channels = [funcaster, kill_your_time, public_services]
        # subscriptions
        doozney_productions = MediaPublisher("Doozney Inc")
        lion_studio   = MediaPublisher("Lions and Lambs Studio")
        def cast_dice():
            return randint(1,6)
        # decide on broadcasting
        for topic in Topics.all_topics():
            if cast_dice() <= 3:
                doozney_productions.provide(public_services, topic)
                doozney_productions.provide(funcaster, topic)
                doozney_productions.provide(kill_your_time, topic)
            if cast_dice() >= 5:
                lion_studio.provide(public_services, topic)
                lion_studio.provide(kill_your_time, topic)
                lion_studio.provide(funcaster, topic)
        for channel in channels:
    • Public Snippets
    • Channels Snippets