working on it ...

Filters

Explore Public Snippets

Sort by

Found 204 snippets matching: behavioral

    public by mprisznyak modified Aug 4, 2015  1437  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
            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  561  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
    
        @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")

    public by mprisznyak modified May 3, 2016  292  2  4  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 Apr 15, 2014  490  0  5  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")

    external by forensicgarlic modified Jan 18, 2016  55  0  2  0

    long form behavioral vhdl

    long form behavioral vhdl: euler1_behavioral_process.vhd
    architecture behavioral_process of euler1 is
    
      signal mod3              : integer range 1 to 3;
      signal mod5              : integer range 1 to 5;
      signal number            : integer range 1 to max_count;
      signal accumulate3       : std_logic;
      signal accumulate5       : std_logic;
      signal accumulate_en     : std_logic;
      signal results_int       : unsigned(31 downto 0);
      signal results_valid_int : std_logic;
      
      
    begin  -- behavioral
    
      -- purpose: count to 3, provide enables to the accumulator
      -- type   : sequential
      -- inputs : clk, reset, enable
      -- outputs: mod3
      modulus3 : process (clk, reset)
      begin  -- process mod3
        if reset = '1' then                 -- asynchronous reset (active high)
          mod3 <= 1;
        elsif rising_edge(clk) then         -- rising clock edge
          if enable = '1' then
            if mod3 = 3 then
              mod3 <= 1;
            else
              mod3 <= mod3 + 1;
            end if;  -- mod3 if
          end if;  -- enable
        end if;  -- clk
      end process modulus3;
    
      accumulate3 <= '1' when mod3 = 3 else '0';
    
    
    -- purpose: count to 5, provide enables to the accumulator
      -- type   : sequential
      -- inputs : clk, reset, enable
      -- outputs: mod3
      modulus5 : process (clk, reset)
      begin  -- process mod3
        if reset = '1' then                 -- asynchronous reset (active high)
          mod5 <= 1;
        elsif rising_edge(clk) then         -- rising clock edge
          if enable = '1' then
            if mod5 = 5 then
              mod5 <= 1;
            else
              mod5 <= mod5 + 1;
            end if;  -- mod5 if
          end if;  -- enable
        end if;  -- clk
      end process modulus5;
    
      accumulate5 <= '1' when mod5 = 5 else '0';
    
      accumulate_en <= accumulate5 or accumulate3;
    
      -- purpose: count from 1 to max_count
      -- type   : sequential
      -- inputs : clk, reset, enable
      -- outputs: number
      number_generator : process (clk, reset)
      begin  -- process number_generator
        if reset = '1' then                 -- asynchronous reset (active high)
          number            <= 1;
          results_valid_int <= '0';
        elsif rising_edge(clk) then         -- rising clock edge
          if enable = '1' then
            if number /= max_count then
              number <= number + 1;
            else
              results_valid_int <= '1';
            end if;
          else
            results_valid_int <= '0';
          end if;
        end if;
      end process number_generator;
    
    
      -- purpose: accumulate the numbers divisible by 3 and 5
      -- type   : sequential
      -- inputs : clk, reset, number, accumulate_en
      -- outputs: results
      accumulator : process (clk, reset) is
      begin  -- process accumulator
        if reset = '1' then                 -- asynchronous reset (active high)
          results_int <= (others => '0');
        elsif rising_edge(clk) then         -- rising clock edge
          if accumulate_en = '1' and results_valid_int = '0' then
            results_int <= results_int + number;
          end if;
        end if;
      end process accumulator;
      results <= results_int;
      results_valid <= results_valid_int; 
      
    end behavioral_process;
    
    

    external by forensicgarlic modified Jan 18, 2016  32  0  1  0

    short form behavioral code

    short form behavioral code: euler1_behavioral_compact.vhd
    architecture behavioral_compact of euler1 is
    
      signal mod3              : integer range 1 to 3;
      signal mod5              : integer range 1 to 5;
      signal number            : integer range 1 to max_count;
      signal accumulate3       : std_logic;
      signal accumulate5       : std_logic;
      signal accumulate_en     : std_logic;
      signal results_int       : unsigned(31 downto 0);
      signal results_valid_int : std_logic;
      
    begin  -- architecture behavioral_compact
    
      -- purpose: accumulate 3's and 5's
      -- type   : sequential
      -- inputs : clk, reset, enable
      -- outputs: results
      sequential : process (clk, reset) is
      begin  -- process sequential steps
        if reset = '1' then                 -- asynchronous reset (active high)
          mod5              <= 1;
          mod3              <= 1;
          results_int       <= (others => '0');
          number            <= 1;
          results_valid_int <= '0';
        elsif rising_edge(clk) then         -- rising clock edge
          if enable = '1' then
            if number /= max_count then
              number <= number + 1;
            else
              results_valid_int <= '1';
            end if;
            if mod5 = 5 then
              mod5 <= 1;
            else
              mod5 <= mod5 + 1;
            end if;
            if mod3 = 3 then
              mod3 <= 1;
            else
              mod3 <= mod3 + 1;
            end if;
            if accumulate_en = '1' and results_valid_int = '0' then
              results_int <= results_int + number;
            end if;
          else
            results_valid_int <= '0';
          end if;
        end if;
      end process sequential;
    
      results       <= results_int;
      results_valid <= results_valid_int;
      accumulate5   <= '1' when mod5 = 5 else '0';
      accumulate_en <= accumulate5 or accumulate3;
      accumulate3   <= '1' when mod3 = 3 else '0';
    
    
    end architecture behavioral_compact;
    
    

    external by mrotundo modified Jan 24, 2016  29  0  1  0

    Elasticsearch Behavioral Example Queries

    Elasticsearch Behavioral Example Queries: queries.txt
    #### SETUP INDEX
    PUT /actions
    
    #### SETUP MAPPINGS
    
    PUT /actions/_mapping/view
    # view
    {
    "view":{
          "properties":{
          	"customer_id":    { "type": "integer"  }, 
            "product_id":     { "type": "integer"  },  
            "customer_name":     { "type": "string","index": "not_analyzed"   },
            "customer_email":     { "type": "string"  },
            "product_name":     { "type": "string","index": "not_analyzed"  }, 
            "paid":           { "type": "float"  },
            "timestamp":      { "type": "date" } 
          }
    }}
    
    PUT /actions/_mapping/purchase
    # purchase
    {
    "purchase":
       {
          "properties":{
            "customer_id":    { "type": "integer"  }, 
            "product_id":     { "type": "integer"  },  
            "customer_name":     { "type": "string","index": "not_analyzed"   },
            "customer_email":     { "type": "string"  },
            "product_name":     { "type": "string","index": "not_analyzed"  }, 
            "paid":           { "type": "float"  },
            "timestamp":      { "type": "date" } 
          }
       }
    }
    
    
    #determine amounts paid by customers and order by most frequent amount paid
    
    POST /actions/_query
    {
       "query": {
      	  "bool" : { 
        	"must_not" : {
                "term" : { "paid" : 0 }
            	}  
            }
      },
       "size": 0, 
       "aggregations": {
          "the_name": {
             "terms": {
                "field": "paid"
                
             }
          }
       }
    }
    
    
    #customer id by most active
    {
    "size":0,
       "aggregations": {
          "most_active_customers": {
             "terms": {
                "field": "customer_id"
                
             }
          }
       }
    }
    
    
    
    
    

    external by joyrexus modified Oct 21, 2014  25  0  1  0

    behavioral datasets

    behavioral datasets: README.md
    ## A declarative spec for behavioral datasets
    
    * [behavioral datasets?](https://github.com/rcc-uchicago/cgsl-archive/blob/master/context.md)
    * [data packaging intro](https://github.com/nickstenning/put-it-in-a-box/blob/master/talk.md#introducing-the-data-package)
    
    
    ## Relevant related work
    
    * [CF metadata conventions](http://en.wikipedia.org/wiki/Climate_and_Forecast_Metadata_Conventions) - initial inspiration for this spec
    * [tidy data](https://github.com/hadley/tidyr/blob/master/vignettes/tidy-data.Rmd) - basic vocabulary for talking about tabular data
    * [open data protocols](http://dataprotocols.readthedocs.org/en/latest/) -
      basic protocols and formats for working with open data
    * [tabular datapackage spec](http://dataprotocols.org/tabular-data-package/)
    * [dataset publishing format](https://github.com/cfpb/qu/wiki/Dataset-publishing-format) - json-variant of Google's dataset publishing language designed for publishing data with [qu](https://cfpb.github.io/qu/data_publishing.html)
    * [loopback](http://loopback.io/) [datasource](https://github.com/strongloop/loopback-datasource-juggler/blob/master/docs/datasource-connector.md) and [schema discovery](https://github.com/strongloop/loopback-datasource-juggler/blob/master/docs/datasource-connector.md#discovering-model-definitions-from-the-data-source)
    * [vega](http://trifacta.github.io/vega/) - declarative visualization grammar
    * [swagger](https://helloreverb.com/developers/swagger) - spec and framework
      for describing, producing, consuming, and visualizing web services
    * [hapi-swagger](https://github.com/glennjones/hapi-swagger) - declarative 
      web services the hapi way
    
    
    
    

    external by Github modified Oct 29, 2015  20  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 MudaKaizen modified Sep 24, 2015  14  0  1  0

    Self Defeating Behavioral Devices

    Self Defeating Behavioral Devices: SelfDefeatingBehavioralDevices.md
    In regards to Volkswagon's recent "Defeat Device" controversy, among many other historical bad ideas which lead people to resign in the midst of controversy they build due to bad decisions...
    
    What drives people to say: 
    
    > "Oh, hey, I know this is a bad idea that's going to catch up to us and cause us to lose money. But we'll just go ahead and make the obviously bad decision."
    
    > Tuesday: "I won't resign."
    
    > Wednesday: "I resign."
    
    And that's the CEO. There had to have been A LOT of people involved to get that kind of software embedded in a car. And, among all of them, nobody spoke-up and said: "This is a liability." (Or, maybe more accuratly, anyone who did speak-up was silenced with matters ranging from re-assignment to being fired.)
    
    =====
    
    I've always wondered what it is about people ignoring inconvenient information, leading to bad decision making.
    
    Enron; stock markets &amp; hedge-fund managers before 2007 ignoring Analysts, etc...
    
    You see this repeated behavior, one of greed and stupidity. And yet people do stupid shit like this over and over again. "Oh, not me, it could never be me, and if it is, I'll make some stupid excuse and because of stupidity, everyone will believe me." &mdash; This is, in effect, everyone being called stupid by someone making a stupid decision, and subsequently, no matter how offensive it is to say "YOU'RE STUPID" &mdash; people actually live up to it time &amp; again.
    
    
    
    • Public Snippets
    • Channels Snippets