working on it ...

Filters

Explore Public Snippets

Sort by

Found 60 snippets

    public by mprisznyak  5000  3  5  4

    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  2929  9  6  2

    Counting specific elements in a list

    The Bad, Ugly One and the Good, Beautiful One
    # data
    test = [1,3, 'a', 'a', 1, 1, 'b', 'a']            
    
    # the wrong way
    count = 0
    for item in test:
        if item == 'a': count += 1
    print("The number of 'a's is {}".format(count)) 
    
    # the right way
    print("The number of 'a's is {}".format(test.count('a'))) 

    public by mprisznyak  4132  4  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  3275  0  6  2

    Tell it in code

    Descriptive code, please, instead of descriptions in comments
    # Not so good
    class BadWidget(object):
      """
      A Widget which draws itself
      """
      def __init__(self, **params):
        self.params = params
        self.flags = 0b0000
    
      def set_flags(self, new_value):
        self.flags |= new_value
    
      def draw(self):
        if self.flags & 0b1000:  # Am I visible?
          print ("You can see a real BadWidget!")
    
    
    # Better
    class GoodWidget(BadWidget):
    
      @property
      def is_visible(self):
        return self.flags & 0b1000
    
      def draw(self):
        if self.is_visible:
          print ("You can see a real GoodWidget!")
    
                

    public by mprisznyak  2688  1  6  2

    Do something until you find a specific value in a sequence

    The Bad, Ugly Villain and the Good, Handsome Hero
    # test.txt contains this:
    # 1
    # 344
    # END
    # ff
    # and you want to count how many lines there are before "END"
    
    # the ugly way
    with open("test.txt") as f:
        counter = 0
        while True:
            line = f.readline()
            if line == 'END':
                break
            counter += 1
    print counter, "lines before END"
    
    # the cool way                   
    with open("test.txt") as f:
        counter = 0
        # https://docs.python.org/2/library/functions.html#iter
        for line in iter(f.readline, 'END'):
            counter += 1
    print counter, "lines before END"
                                        

    public by mprisznyak  2767  2  5  4

    Reverse a dictionary

    How to swap keys and values easily
    # you have some data mapped onto each other 
    d = {"one": 1, "two": 2, "three": 3}
    # if you want the reverse map
    # then use a dictionary comprehension from Python 2.7 onwards
    d_reversed =  {value:key for key, value in d.items()}
    # or use a list comprehension for earlier Python versions:
    d_reversed_old = dict([(value,key) for key, value in d.items()])
    print d, d_reversed, d_reversed_old            

    public by mprisznyak  3769  1  8  6

    How to add Cookies and Headers in HTTP requests in Python

    Let's say I have an HTTP GET request and I want to decorate it with some Headers (e.g. "Accept" or "Authorization") and with some Cookies. What's the best way to do this in Python?
    #  The standard library stuff (urllib, etc.) is very cumbersome.
    # I myself would use the 'requests' library.
    # Here's the docs showing what you need to do 
    # http://docs.python-requests.org/en/latest/user/advanced/
    
    import requests
    
    def myauth(req):
        req.headers['Accept'] = 'money'
        return req
    
    r = requests.get('http://www.example.com', auth=myauth)
    
    # or do some extra work before you send the request
    
    my_headers = dict(Accept='cash')
    my_cookies = {'taste': 'crunchy'}
    r = requests.get('http://www.example.com', headers=my_headers, cookies=my_cookies)

    public by marksimon232  11149  82  6  3

    How to add Cookies and Headers in HTTP requests in Python

    Let's say I have an HTTP GET request and I want to decorate it with some Headers (e.g. "Accept" or "Authorization") and with some Cookies. What's the best way to do this in Python?
    => According to the api - http://docs.python-requests.org/en/latest/api/, the headers can all be passed in using requests.get:
    r=requests.get("http://www.example.com/", headers={"content-type":"text"});
    
    
    => Response Headers:
    We can view the server’s response headers using a Python dictionary:
    >>> r.headers
    {
        'status': '200 OK',
        'content-encoding': 'gzip',
        'transfer-encoding': 'chunked',
        'connection': 'close',
        'server': 'nginx/1.0.4',
        'x-runtime': '148ms',
        'etag': '"e1ca502697e5c9317743dc078f67693f"',
        'content-type': 'application/json; charset=utf-8'
    }
    
    
    => HTTP Headers are case-insensitive, so we can access the headers using any
    capitalization we want.
    >>> r.headers['Content-Type']
    'application/json; charset=utf-8'
    
    >>> r.headers.get('content-type')
    'application/json; charset=utf-8'
    
    # If a header doesn’t exist in the Response, its value defaults to None:
    >>> r.headers['X-Random']
    None
    
    
    => Cookies
    If a response contains some Cookies, you can get quick access to them:
    >>> url = 'http://http.org/cookies/set/requests-is/awesome'
    >>> r = requests.get(url)
    
    >>> r.cookies['requests-is']
    'awesome'
    # To send your own cookies to the server, you can use the cookies parameter:
    
    >>> url = 'http://http.org/cookies'
    >>> cookies = dict(cookies_are='working')
    
    >>> r = requests.get(url, cookies=cookies)
    
    >>> r.text
    '{"cookies": {"cookies_are": "working"}}'
    

    public by mprisznyak  3428  2  6  3

    Exceptions

    The Bad, Ugly Villain and the Good, Handsome Hero
    countries = {"Hungary": 10,
                 "UK": 65,
                 "USA": 314,
                 "Russia": 144
                }
    
    # nested exception handling...
    # BAD, BAD!
    for country in ["Hungary", "Germany"]:
        try:
            people = countries[country]
            try:
                people *= 1.0e6
            except TypeError:
                people = "Unknown number of"
                print "cannot convert"
        except KeyError:
            people = "N/A"
    
        print "{0} people live in {1}\n".format(people, country)
        print "*"*80
    
    # sequential, separate exception handling...
    # BAD!
    for country in ["Hungary", "Germany"]:
        try:
            people = countries[country]
        except KeyError:
            people = "N/A"
    
        try:
            people *= 1.0e6
        except TypeError:
            people = "Unknown number of"
            print "cannot convert"
    
        print "{0} people live in {1}\n".format(people, country)
        print "*"*80
    
    # exception handling for chunks of code as large as possible
    # GOOD!
    for country in ["Hungary", "Germany"]:
        try:
            people = countries[country]
            people *= 1.0e6
        # handle specific error conditions
        except KeyError:
            # no data for this country
            people = "N/A"
        except TypeError:
            # invalid conversion
            people = "Unknown number of"
            print "cannot convert"
        except: # catch all
            people = "No"
    
        print "{0} people live in {1}\n".format(people, country)
        print "*"*80

    public by marksimon232  4228  8  6  1

    How to get the seconds between two dates in Python

    To get the seconds between two dates in Python you can use the following snippet.
    import datetime
    import time
     
    def DateDiffSeconds(dateOlder, dateNewer):
      timedelta = dateNewer - dateOlder
      return timedelta.days*24*3600 + timedelta.seconds
     
    dateOlder = datetime.datetime(2014,07,01,00,00,00)
    dateNewer = datetime.datetime(2014,07,02,11,30,00)
    print DateDiffSeconds(dateOlder,dateNewer)
    
    • Public Snippets
    • Channels Snippets