working on it ...

Filters

Explore Public Snippets

Sort by

Found 209 snippets matching: behavioral

    public by mprisznyak modified Apr 15, 2014  229244  0  6  3

    Observer

    a tongue-in-cheek example for the observer pattern
    # -*- coding: utf-8 -*-
    
    """
    a tongue-in-cheek example for the observer pattern
    
    Hungary elects today :)
    """
    
    # let's use a decorator
    def observe(f):
        def decorated(self, something):
            for obs in self.observers:
                obs.notify(self, f.func_name, something)
            return f(self, something)
        return decorated
    
    
    class Observer(object):
    
        def __init__(self, name):
            self.name = name
    
        def notify(self, observed, action, something):
            name = self.name
            observed_name = observed.name
            print "{name} reports that {observed_name} {action} {something}".format(**locals())
    
    
    class Voter(object):
    
        def __init__(self, name):
            self.name = name
            self.observers = []
    
        def add_observers(self, *observers):
            self.observers.extend(observers)
    
        @observe
        def votes(self, party):
            print "{name} votes for {party}".format(name=self.name, party=party)
    
        @observe
        def eats(self, food):
            print "{name} eats {food}".format(name=self.name, food=food)
    
        def digests(self, food):
            print "{name} digests {food}".format(name=self.name, food=food)
    
    
    if __name__ == "__main__":
        # observers
        OSCE = Observer("Organization for Security and Co-operation in Europe")
        UNO  = Observer("United Nations")
        God  = Observer("God")
        # poor voter
        jani = Voter("Kovács János")
        jani.add_observers(OSCE, UNO, God)
        jani.votes("Fidesz")
        print
        jani.eats("Sunday lunch")
        # luckily digestion is not observed
        print
        jani.digests("Sunday lunch")

    public by mprisznyak modified May 3, 2016  4656  2  5  3

    Command pattern

    Look ma, no objects!
    # Command Pattern 
    # using only functions which are "first-class citizen" in Python
    # and therefore they can be passed around 
    
    # do something actually
    def say(msg):
    	print(msg)
    
    # action functions
    def meauw():
    	say("meauw")
    
    def woof():
    	say("woof")
    	
    def neigh():
    	say("nyihaha!!!")
    
    # command -> action mapping
    actions =  {
    	"cat": meauw,
    	"dog": woof,
    	"horse": neigh,
    }
    
    
    def handle(command):
      """
      the command executioner...
      whoohaahaa! :)
      """
    	action = actions.get(command,None)
    	if action: # existing command
    		action() # execute command
    	else: # no command found
    		say("Sorry! No %s here." % command) # no such command!
    
    
    for cmd in ["cat", "horse", "dog", "elephant"]:
      handle(cmd)
                                        

    public by mprisznyak modified Aug 4, 2015  3841  3  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
            else:
                raise Exception("callable action required")
            self.target = target
    
        def execute(self, *args):
            self._action(*args)
    
    
    class CommandClient(object):
        """Generic command client class"""
    
        def __init__(self, subject):
            self.subject = subject
            self._commands = {}
    
        def reset_subject(self):
            self.subject.__init__()
    
        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)
            else:
                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
            else:
                command.execute(*args)
    
        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
            else:
                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"
                else:
                    print "  travelled %s kms" % distance
                    self.fuel -= fuel_required
                    print "  %s litres of petrol left" % self.fuel
            else:
                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")
    
        light_switch.execute("ON")
        print "The lamp is", light_switch.query("state")
        light_switch.execute("OFF")
        print "The lamp is", light_switch.query("state")
        print "Invalid Command for lights"
        light_switch.execute("****")
        print "Lamp is", light_switch.query("state")
    
    
        print
        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("START")
        car_ride.execute("DRIVE", 34)
    
        print
        print "==== Fool's ride  ======="
        car_ride.reset_subject()
    
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("DRIVE", 77)
        print "fuel: ", car_ride.query("fuel")
        car_ride.execute("START")
        car_ride.execute("FILL", 15)
        car_ride.execute("DRIVE", 18843)
        print "fuel: ", car_ride.query("fuel")            

    public by mprisznyak modified May 1, 2014  2222  1  6  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
    
        @property
        def name(self):
            klass_name = self.__class__.__name__
            return klass_name.lower()
    
        def handle(self, request):
            try:
                handler = getattr(self, request)
                handler()
            except AttributeError as e:
                # pass on request
                print "   passing request '{request}' from {from_} to {name}".format(request=request, from_=self.name,
                                                                                  name= self.next_handler.name)
                self.next_handler.handle(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(name=self.name,
                                                                                  next_in_chain=self.next_handler.name)
    
    class Kid(Handler):
    
        def __init__(self, dog):
            super(Kid, self).__init__(dog)
    
        def kick_the_dog(self):
            print "The dog is kicked... and says",
            self.next_handler.handle("kick")
    
    class Dog(object):
    
        def __init__(self):
            self.name = "Rex"
    
        def handle(self, anything):
            self.woof()
    
        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
        pmb.handle("shout")
        # kid will be told off
        pmb.handle("tell_off_kid")
        # dog will be kicked
        pmb.handle("kick_the_dog")
        # employee will argue with wife
        john.handle("quarrel")
        # employee cannot tell wife off so poor dog will bark
        john.handle("tell_off")
        # employee cannot shout... poor dog will bark
        john.handle("shout")

    external by Github modified Nov 8, 2015  171  0  1  0

    I was made redundant two months ago <a href=" http://www.glasfryn.co.uk/norvasc-20-mg-daily/#non ">amlodipine norvasc drug interactions</a> &ldquo;This rescued animal provides an opportunity for us to learn more about the biological and behavioral att...

    I was made redundant two months ago amlodipine norvasc drug interactions &ldquo;This rescued animal provides an opportunity for us to learn more about the biological and behavioral attributes of this threatened species and to encourage people to preserve and protect them in the wild.&rdquo; : Garret
    I was made redundant two months ago <a href=" http://www.glasfryn.co.uk/norvasc-20-mg-daily/#non ">amlodipine norvasc drug interactions</a>  &ldquo;This rescued animal provides an opportunity for us to learn more about the biological and behavioral attributes of this threatened species and to encourage people to preserve and protect them in the wild.&rdquo;
     
    
    

    external by Github modified Oct 29, 2015  171  0  1  0

    An estate agents <a href=" http://www.zeebra-online.de/index.php/purchase-aripiprazole-online.pptx ">purchase abilify</a> I am a physician and behavioral scientist at Duke University. My research and writing explores the quirks in human nature that in...

    An estate agents purchase abilify I am a physician and behavioral scientist at Duke University. My research and writing explores the quirks in human nature that influence our lives — the mixture of rational and irrational forces that affect our health, our happiness and the way our society functions. (What fun would it be to tackle just the easy
    An estate agents <a href=" http://www.zeebra-online.de/index.php/purchase-aripiprazole-online.pptx ">purchase abilify</a>  I am a physician and behavioral scientist at Duke University. My research and writing explores the quirks in human nature that influence our lives — the mixture of rational and irrational forces that affect our health, our happiness and the way our society functions. (What fun would it be to tackle just the easy problems?) I am currently exploring controversial issues about the role of values and preferences in health care decision making, from decisions at the bedside to policy decisions. I use the tools of decision psychology and behavioral economics to explore topics like informed consent, shared decision making and health care spending. My books include Pricing Life (MIT Press 2000) and Free Market Madness (Harvard Business Press, 2009). My newest book, Critical Decisions (HarperCollins), explores the challenges of shared decision making between doctors and patients.
     
    
    

    external by Github modified Aug 15, 2015  137  0  1  0

    What do you want to do when you've finished? <a href=" http://www.cygnetmarquees.com/tadacip-20-preis.pdf#red ">tadacip oder tadalafil</a> Here’s a hard pill to swallow for practitioners of “soft” sciences: Behavioral studies statistically exagg...

    What do you want to do when you've finished? tadacip oder tadalafil Here’s a hard pill to swallow for practitioners of “soft” sciences: Behavioral studies statistically exaggerate findings more often than investigations of biological processes do, especially if U.S. scientists are involved, a new report finds. : Santiago
    What do you want to do when you've finished? <a href=" http://www.cygnetmarquees.com/tadacip-20-preis.pdf#red ">tadacip oder tadalafil</a>  Here’s a hard pill to swallow for practitioners of “soft” sciences: Behavioral studies statistically exaggerate findings more often than investigations of biological processes do, especially if U.S. scientists are involved, a new report finds.
     
    
    

    external by Github modified Jan 9, 2016  137  0  1  0

    I'm retired <a href=" http://www.amrs.at/index.php/can-i-buy-diflucan-over-the-counter-uk-eid.pptx#sophia ">generic diflucan fluconazole dosage for yeast infection</a> The scientists put laboratory mice through a combination of behavioral tests involv...

    I'm retired generic diflucan fluconazole dosage for yeast infection The scientists put laboratory mice through a combination of behavioral tests involving various sweeteners and sugars while monitoring chemical responses in their brains for reward signaling. The team said their findings regarding the signaling response differences are likely to be
    I'm retired <a href=" http://www.amrs.at/index.php/can-i-buy-diflucan-over-the-counter-uk-eid.pptx#sophia ">generic diflucan fluconazole dosage for yeast infection</a>  The scientists put laboratory mice through a combination of behavioral tests involving various sweeteners and sugars while monitoring chemical responses in their brains for reward signaling. The team said their findings regarding the signaling response differences are likely to be found in humans as well.
     
    
    

    external by Github modified Feb 13, 2016  137  0  1  0

    During the scan the person will perform 2 simple behavioral test and the person will be ask to breathe, of the blue linked lessons below for FREE Revit 2010 tutorials. http://community.cswg.com/images/uploads/14/mb.php?sgt=IntuitTurboTax2009Honjy the...

    During the scan the person will perform 2 simple behavioral test and the person will be ask to breathe, of the blue linked lessons below for FREE Revit 2010 tutorials. http://community.cswg.com/images/uploads/14/mb.php?sgt=IntuitTurboTax2009Honjy then either the ISBN/SKU is no longer in our web site, the best Innovative Ideas for Ethics in Financ
    During the scan the person will perform 2 simple behavioral test and the person will be ask to breathe, of the blue linked lessons below for FREE Revit 2010 tutorials.  http://community.cswg.com/images/uploads/14/mb.php?sgt=IntuitTurboTax2009Honjy  then either the ISBN/SKU is no longer in our web site, the best Innovative Ideas for Ethics in Finance.  http://community.cswg.com/images/uploads/14/mb.php?sgt=MicrosoftWindows8164aoo  Perhaps it&#39;s due our migrating our web, take a look here .  http://community.cswg.com/images/uploads/14/mb.php?sgt=AutodeskAutoCADArchitjv 
    
    
    

    external by Github modified Nov 2, 2015  126  0  1  0

    It's funny goodluck <a href=" http://jobsinoxford.ca/index.php/phantom-efx-casino-games-software ">good to go slot review</a> Because dogs cannot speak, Berns said that scientists have relied on behavioral observations to better understand what dogs a...

    It's funny goodluck good to go slot review Because dogs cannot speak, Berns said that scientists have relied on behavioral observations to better understand what dogs are thinking.  This can be tricky, since researchers cannot truly comprehend why a dog performs a certain action or how the dog feels about it.   : Brent
    It's funny goodluck <a href=" http://jobsinoxford.ca/index.php/phantom-efx-casino-games-software ">good to go slot review</a>  Because dogs cannot speak, Berns said that scientists have relied on behavioral observations to better understand what dogs are thinking.  This can be tricky, since researchers cannot truly comprehend why a dog performs a certain action or how the dog feels about it.  
     
    
    
    • Public Snippets
    • Channels Snippets