code:
import datetime

def get_year(date):
    my_date = datetime.datetime.strptime(date, "%d-%b-%y")
    now = datetime.datetime.now()

    if my_date > now:
        my_date = my_date.replace(year=my_date.year - 100)
    return my_date.year

print get_year('07-JUL-50')  # prints 1950
print get_year('07-JUL-13')  # prints 2013
print get_year('07-JUL-14')  # prints 1914

rawDescription: get year from string '07-JUL-50'

description: Get year from string '07-JUL-50'


code:
input='adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0'

result={}
for pair in input.split(';'):
    (key,value) = pair.split(':')
    result[key] = value

print result['adId']
print result['siteId']
print result['userId']

rawDescription: parsing in python

description: Parsing in python


code:
import socket, select
serverSocket = socket.socket()
serverSocket.bind(('0.0.0.0',8080))
serverSocket.listen(10)
open_client_sockets = []

while True:
    rlist, wlist, xlist = select.select([serverSocket] + open_client_sockets, open_client_sockets, [])
    for currentSocket in rlist:
        if currentSocket is serverSocket:
            newSocket, addr = serverSocket.accept()
            open_client_sockets.append(newSocket)
        else:
            data = currentSocket.recv(2048)
            if data == "":
                open_client_sockets.remove(currentSocket)
                print 'Conn is closed'
            else:
                print data
                content_to_send = "The content that you want to send"
                currentSocket.send("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length:"+str(len(content_to_send))+"\r\n\r\n"+content_to_send)

rawDescription: Python proxy - Need help to send HTTP header to the browser


code:
fname = input('enter file name:')
ifile = open(fname, 'r')
list1 = []
list2 = []

for line in ifile.readlines():
    for word in line.split(' '):
        word = word.strip()
        if word in list1:
            list2[list1.index(word)] += 1
        else:
            list1.append(word)
            list2.append(1)

for item in list1:
    print item, list2[list1.index(item)]

rawDescription: Python: count frequency of words in a txt file


code:
num = 42 # or whatever default you want to use
while True:
    try:
        num = int(raw_input('Enter the number > ') or num)
        break
    except ValueError:
        print 'Invalid number; please try again'

rawDescription: Checking for empty number as input

description: Checking for empty number as input


code:
#!/usr/local/bin/Python
"""                       Example showing use of a callback shim"""
import Tkinter

def doButton(buttonName):
    """                   My desired callback.
                          I'll need a callback shim
                          because Button command callbacks receive no arguments.
    """
    print buttonName, "pressed"

class SimpleCallback:
    """                   Create a callback shim.
                          Based on code by Scott David Daniels
                          (which also handles keyword arguments).
    """
    def __init__(self, callback, *firstArgs):
        self.__callback = callback
        self.__firstArgs = firstArgs

    def __call__(self, *args):
        return self.__callback (*(self.__firstArgs + args))

root = Tkinter.Tk()

buttonNames = ( "Button 1", "Button 2", "Button 3" )
for name in buttonNames:
    callback = SimpleCallback( doButton, name )
    Tkinter.Button( root, text = name, command = callback ).pack()

root.mainloop()

rawDescription: Python Tkinter: How to recognize a button from its command?


code:
def foo(l=[]):
    if any(l):
        print 'List is not empty'
    else:
        print 'List is empty'

foo([''])
# List is empty

rawDescription: python how to check list does't contain any value

description: Python how to check list does't contain any value


code:
import pydbfrw
d = pydbfrw.DBFreader('/devel/dbf/all_files/del.dbf')
list(d)
d.get_field_names()
d = pydbfrw.DBFreader('/devel/dbf/all_files/del.dbf', include_deleted=True)
list(d)
d.get_field_names()
for rowdict in d.get_dicts():
    print rowdict
for rowtup in d.get_namedtuples():
    print rowtup

rawDescription: Visual Fox Pro and Python

description: Visual Fox Pro and Python


code:
import pygame
from pygame.locals import *
import time

if __name__ == "__main__":
    pygame.init()
    size = (700, 700)
    screen = pygame.display.set_mode(size)
    font = pygame.font.SysFont('Impact',20,16)

    title = font.render(('SQUASH!'), True, (255,255,255))
    play = font.render(('PLAY'), True, (255,255,255))
    play_r = play.get_rect()
    play_r.x, play_r.y = 300,300

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        screen.fill((0,255,0,))
        screen.blit(title, (400, 400))
        screen.blit(play, (300,300))
        if play_r.collidepoint(pygame.mouse.get_pos()):
            print 'Detected'
        time.sleep(0.000000000000000000000000000000000000000000000000000000001)
        pygame.display.flip()

rawDescription: Mouseover in Pygame

description: Mouseover in Pygame


code:
i = 0
words = set()
for word in tokens:
    words.add(word)
    i += 1
    print i, len(words)

rawDescription: Heaps law in Python

description: Heaps law in Python


code:
from operator import itemgetter
with open('file.csv') as fin:
    csvin = csv.reader(fin)
    print max(csvin, key=itemgetter(1))

rawDescription: Print smaller/bigger value cell from csv using python


code:
v = 12
d = {k:v for k in 'abfhp'}
print d

rawDescription: Creating a dictionary with same values

description: Creating a dictionary with same values


code:
import dpkt

from dpkt.ip import IP

from dpkt.ethernet import Ethernet

import struct

import socket

import csv

def ip_to_str(address):
    return socket.inet_ntoa(address)

f = open('ipp.pcap', 'rb')

pcap = dpkt.pcap.Reader(f)

print("your options are:")

print()

print ("1) Ver")

print ("2) HeaderLength")

print ("3) Total Length")

print()

loop = 1

while loop ==1:
    choice = input("Choose your option:")

    choice = int(choice)

    for ts, buf in pcap:

        eth = dpkt.ethernet.Ethernet(buf)

        if eth.type != dpkt.ethernet.ETH_TYPE_IP:
            continue

        ip = eth.data

        Length = "%d" % (ip.len)

        TTL = "%d" % (ip.ttl)

        ver = ip.v

        hdrlen = dpkt.ip.IP_HDR_LEN

        if choice == 1:

            print ver,

        if choice == 2:

            print hdrlen,

        if choice == 3:

            print Length,

            loop = 0
        print

rawDescription: Want to execute more than one option or choice in menu driven at same time


code:
if __name__ == '__main__':
   #Thread(target = robot).start()
   t1 = Thread(target = getCPUtemperature)
   t1.daemon = True  # in daemon mode
   t1.start()
   t2 = Thread(target = robot)
   t2.daemon = True
   t2.start()

   try:
       while threading.active_count() > 1:
           time.sleep(1)

   except KeyboardInterrupt:
            # CTRL+C exit, turn off the drives and release the GPIO pins
            print 'Terminated'
            stop_movement()
            raw_input("Turn the power off now, press ENTER to continue")
            GPIO.cleanup()
            quit()

rawDescription: how to break a thread function in python

description: Break a thread function in python


code:
def m2m_changed_labs(sender, **kwargs):  # notice sender instead of *args
    print "signal received"

rawDescription: Signal m2m_changed never triggered

description: Signal m2m_changed never triggered


code:
from collections import deque
class rewindable_iterator(object):
    not_started = object()

    def __init__(self, filename,deque_max_length=2):
        self._f=open(filename,'r')
        self._iter = iter(self._f)
        self._use_save = False
#        self._use_save2 = False
        self._save = self.not_started
        self._use_num=0
        self._deque=deque([],deque_max_length)

    def __iter__(self):
        return self
    def __enter__(self):
        return self
    def readline(self):
        return self._iter.readline()

    def __exit__(self,exc_type, exc_value, traceback):
        if exc_type is not None:
            print exc_type, exc_value, traceback
        self._f.close()

    def next(self):
        if self._use_save:
            self._use_num -= 1
            if not self._use_num:
                self._use_save = False
            return self._deque[-self._use_num-1]
        else:
            self._save = self._iter.next()
            self._deque.append(self._save)
            return self._save

    def backup(self,num=2):

        if self._use_num+num>len(self._deque):
            raise RuntimeError("Tried to backup more than the available lines")
        elif self._save is self.not_started:
            raise RuntimeError("Can't backup past the beginning.")
        self._use_save = True
        self._use_num+=num

rawDescription: rewinding multiple lines when iterating with f.next()

description: Rewinding multiple lines when iterating with f.next()


code:
import sys         # top-level

3 + 4              # top-level

x = 0              # top-level

def f():           # top-level
    import os      # not top-level!
    return 3       # not top-level

if x:              # top-level
    print 3        # not top-level
else:
    print 4        # not top-level, but executes as part of an if statement
                   # that is top-level

class TopLevel(object): # top-level
    x = 3          # not top-level, but executes as part of the class statement
    def foo(self): # not top-level, but executes as part of the class statement
        print 5    # not top-level

rawDescription: What is a top-level statement in Python?

description: What is a top-level statement in Python


code:
from django.utils.importlib import import_module
from django.conf import settings
from django.contrib.auth import get_user
from django.contrib.auth.models import AnonymousUser
from django.contrib.auth import SESSION_KEY, BACKEND_SESSION_KEY, load_backend

engine = import_module(settings.SESSION_ENGINE)
session = engine.SessionStore(YOUR_SESSION_KEY)

try:
    user_id = session[SESSION_KEY]
    backend_path = session[BACKEND_SESSION_KEY]
    backend = load_backend(backend_path)
    user = backend.get_user(user_id) or AnonymousUser()
except KeyError:
    user = AnonymousUser()

if user.is_authenticated():
    print "User"
else:
    print "Guest"

rawDescription: Manually validate a django session id is currently authenticated


rawDescription: Weird for loop statment

description: Weird for loop statment


code:
hand = open ('sample.txt')
print sum([int(i) for i in re.findall(r'\d+', hand.read())])
hand.close()

rawDescription: Why both of the method go wrong in extracting and sum the numbers in a text?


code:
from xml.parsers.xmlproc import dtdparser

attr_separator = '_'
child_separator = '_'

dtd = dtdparser.load_dtd('schedule.dtd')

for name, element in dtd.elems.items():
    for attr in element.attrlist:
        output = '%s%s%s = ' % (name, attr_separator, attr)
        print output
    for child in element.get_valid_elements(element.get_start_state()):
        output = '%s%s%s = ' % (name, child_separator, child)
        print output

rawDescription: Reading XML DOCTYPE info with Python

description: Reading XML DOCTYPE info with Python


code:
from functools import partial
import maya.cmds as cmds

def one (*args):
    print '1'

def two (*args):
    print '2'

def radioSwitch (a, state, *args):
    if state:
        cmds.radioButtonGrp(a, e=True, enable=False)
    else:
        cmds.radioButtonGrp(a, e=True, enable=True)

winID = 'xx'
if cmds.window(winID, exists=True):
    cmds.deleteUI(winID)

window = cmds.window(winID, sizeable = False, title="Resolution Switcher", widthHeight=(300, 100) )

cmds.columnLayout( )
cmds.text (label = '')
cmds.text (label = '')
cb_disable = cmds.checkBoxGrp( cat = (1,'left', 20), ncb = 1, l1='  DISABLE', offCommand = "" , onCommand = "" )
a = cmds.radioButtonGrp( cat = [(1,'left', 90),(2, 'left', 100)], enable=True, numberOfRadioButtons=2,   on1 = one , on2 = two )
cmds.checkBoxGrp(cb_disable, e=1, offCommand = partial(radioSwitch, a, False))
cmds.checkBoxGrp(cb_disable, e=1, onCommand = partial(radioSwitch, a, True))
cmds.text (label = '')
cmds.showWindow( window )

rawDescription: Switchable Radio Buttons (editing a command)


code:
from igraph import *
from random import *
from time import *

def countSimilarNeigh(g,v):
    return float(g.vs(g.neighbors(v))['state'].count(True))/g.degree(v)

def contagion(g):
    contagious = True
    while contagious:
        for v in g.vs():
            contagious = False
            if v['contagious'] == False:
                if countSimilarNeigh(g,v.index) > 0.1:
                    v['state'] = True
                    v['contagious'] = True
                    contagious = True

def init_graph(n = 60, p = .1):
    g = Graph.Erdos_Renyi(n,p)
    while g.is_connected == False:
        g = Graph.Erdos_Renyi(n,p)
    g.simplify(multiple=True, loops=True)
    return g

def score(g,repl = 200):
    for c in range(repl):
        cc = 0
        for i in g.vs():
            i['contagious'] = False
            i['state'] = False
            if random() < .1 and cc < 4:
                i['state'] = True
                i['contagious'] = True
                cc += 1
        contagion(g)

t0 = time()
score(init_graph())
print time()-t0

rawDescription: Fastest possible contagion algorithm with iGraph


code:
def main():
    fileName= raw_input('Please enter the file name: ')

    validate_file(fileName)
    new_lines = convert_file(fileName)
    for line in new_lines:
        print line

def validate_file(fileName):
    try:
        inputFile= open(fileName, 'r')
        inputFile.close()
    except IOError:
        print('File not found.')

def strip_punctuation(line):
    punctuation = ''
    line = line.strip()
    if len(line)>0:
        if line[-1] in ('.','!','?'):
            punctuation = line[-1]
            line = line[:-1]
    return line, punctuation

def convert_file(fileName):
    inputFile= open(fileName, 'r')
    converted_lines = []
    for line in inputFile:
        line, punctuation = strip_punctuation(line)
        line = line.split()
        new_words = []
        for word in line:
            endString= str(word[1:])
            them=endString, str(word[0:1]), 'ay'
            new_word="".join(them)
            new_words.append(new_word)
        new_sentence = ' '.join(new_words)
        new_sentence = new_sentence.lower()
        if len(new_sentence):
            new_sentence = new_sentence[0].upper() + new_sentence[1:]
        converted_lines.append(new_sentence + punctuation)
    return converted_lines

rawDescription: python pig latin converter

description: Python pig latin converter


code:
import sys

fileInput=open(sys.argv[1],'r')

for line in fileInput:
    print line.rstrip('\n')

rawDescription: how to remove end of line in Python?

description: Remove end of line in Python


code:
import cgi
with open('save.aln') as f:
    for line in f:
        print cgi.escape(line) # escape <, >, &
        print '<br/>'

rawDescription: Reading lines including space

description: Reading lines including space


rawDescription: Precision in python

description: Precision in python


code:
for line in fh:
    line = line.rstrip()
    if line.startswith("my_pattern") :
        count = count + 1
        sb = line.split()
        sc = sb[1]    # this gaves me the numbers only from eavh line #
        value = float(sc)
        total = total + value

if count:
    average = total / count
    print average

rawDescription: average computing without using sum function in python?

description: Average computing without using sum function in python


code:
from django.template import Template, Context
t = Template("{{ text }}")
c = Context({'text': 'Vancouver marketing extraordinaire Bob Rennie asks “What if it’s not a bubble?'})
print t.render(c)
t.render(c)

rawDescription: Django - text input resulting in wierd characters when rendering template


code:
def mapper(obj):
    yield obj
    yield operation.counters.Increment("process-obj")

class Test(base_handler.PipelineBase):
    """A pipeline to ingest log as CSV in Google Storage
    """

    output_names = ['counters']

    def run(self, setting_id):
        results = yield mapreduce_pipeline.MapperPipeline(
          "test",
          "mapper",
          "mapreduce.input_readers.DatastoreInputReader",
          output_writer_spec="mapreduce.output_writers.FileOutputWriter",
          params={

          },
          shards=10
        )
        yield MapreduceResult(results.counters)

    def finalized(self):
        print 'Counters here: ', self.outputs.counters

class MapreduceResult(base_handler.PipelineBase):

    def run(self, counters):
        self.fill(self.outputs.counters, counters)

rawDescription: How to get counter results in AppEngine MapReduce?

description: Get counter results in AppEngine MapReduce


code:
while 1:

    socket_list = [sys.stdin, s]
    #read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
    #for sock in read_sockets:
    #if sock == s:

    # read from stdin
    msg = sys.stdin.readline()

    # send string to the server
    s.send(msg)

    # Read from server (it should have data now)
    data = sock.recv(4096)
    if not data:
        sys.exit()

    dec = map(ord,data)
    res = max(dec) + min(dec)
    print data+'\n(^min_max value in ascii: '+str(res)+')'

rawDescription: Python: multiple sockets in a client script?


code:
import msgpack
x=msgpack.dumps({1:'aaa',2:'bbb'})
x
len(x)
print msgpack.loads(x)

rawDescription: Fast Perl<->Python serialization that supports integer dictionary keys


code:
for url in apache_status_dict.keys():
  for req in apache_status_dict[url]:
      print apache_status_dict[url][req]

rawDescription: Iter through defaultdict of defaultdict on Python 2.6


code:
def compose(current_value, *args):
    for func in args:
        current_value = func(current_value)
    return current_value

def double(n):
    return 2*n

print compose(5, double, double) # prints 20

rawDescription: Clojure style function "threading" in Python


code:
import pygame
import random

pygame.init()

BRICK_HEIGHT = 48
BRICK_WIDTH = 64

class Block(object):
    def __init__(self, x=0, y=0, num=0, width=0, color=(122, 122, 122)):
        # w_x and w_y represents the world coordinates
        # that means the 'column' and 'row' in the 'grid'
        self.w_x, self.w_y = x, y
        # to calculate the absolute (screen) position,
        # simply multiply x, y with BRICK_WIDTH, BRICK_HEIGHT
        self.rect = pygame.rect.Rect(x*BRICK_WIDTH, y*BRICK_HEIGHT, BRICK_WIDTH, BRICK_HEIGHT)
        self.width = width
        self.color = color

    def draw(self, surface):
        pygame.draw.rect(surface, self.color, self.rect, self.width)

    def move(self, global_pos):
        # to translate the absolute (screen) position
        # back to the world coordinates, simply divide
        # with BRICK_WIDTH, BRICK_HEIGHT
        x, y = global_pos
        self.w_x = (x / BRICK_WIDTH)
        self.w_y = (y / BRICK_HEIGHT)
        # recalculate the absolute (screen) position,
        # so the cursor "snaps" to the grid
        self.rect.x = self.w_x * BRICK_WIDTH
        self.rect.y = self.w_y * BRICK_HEIGHT

screen = pygame.display.set_mode((10*BRICK_WIDTH, 10*BRICK_HEIGHT))
clock = pygame.time.Clock()

c = Block(width=4, color=(200, 255, 200))

def r_color():
    return (random.randint(30, 255),
            random.randint(30, 255),
            random.randint(30, 255))

# blocks maps (column, row) to a block
# note that this keeps the information of the
# position of a block at *two* places, which needs
# to be in sync. That's a drawback, but the
# lookup is fast!
blocks = {}
for x in xrange(10):
    for y in xrange(10):
        if random.randint(0, 100) < 33:
            blocks[(x, y)] = Block(x, y, color=r_color())

while True:
    pos = pygame.mouse.get_pos()
    c.move(pos)

    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            raise Exception()
        if e.type == pygame.MOUSEBUTTONDOWN:
            # finding the tile under the mouse is as easy as:
            block = blocks.get((c.w_x, c.w_y))
            # and since it's a dict, the lookup is very fast.
            print 'Selected block color: {}'.format(block.color) if block else 'No block selected'

    screen.fill((0, 30, 30))
    for b in blocks.values():
        # The blocks calculated their absolute position by themself.
        # That may or may not what you want. Another way is to calculate
        # their absolute position here, so the blocks only needs to
        # know about their world coordinates
        b.draw(screen)
    c.draw(screen)

    # run at 60 FPS
    clock.tick(60)
    pygame.display.flip()

rawDescription: How to improve performance when dealing with Cursor-Movement within a Grid? (Pygame)

description: Improve performance when dealing with Cursor-Movement within a Grid? (Pygame)


code:
from collections import Counter

# initial values
c=Counter({("Mumbai", 1, 2):5, ("San Francisco", 3,4): 4})

#adding entries
c.update([('Mumbai', 1, 2)])
print c  # Counter({('Mumbai', 1, 2): 6, ('San Francisco', 3, 4): 4})

c.update([('Mumbai', 1, 2), ("San Diego", 5,6)])
print c  #Counter({('Mumbai', 1, 2): 7, ('San Francisco', 3, 4): 4, ('San Diego', 5, 6): 1})

rawDescription: Python list help (incrementing count, appending)


code:
from timeit import Timer

setstr="""import numpy as np
import itertools
import random

Nlists = 1000
total_lists = 5000
outsz = 100
maxsublistsz = 100

# create random list of lists
list_range_values = random.sample(xrange(total_lists),Nlists)
list_list_values = [random.sample(xrange(outsz),np.random.randint(1,maxsublistsz)) for k in xrange(total_lists)]

list_comp_values = 10*np.random.uniform(size=(total_lists,))

v = np.zeros((outsz,))

def indices(start, end):
    lens = end - start
    np.cumsum(lens, out=lens)
    i = np.ones(lens[-1], dtype=int)
    i[0] = start[0]
    i[lens[:-1]] += start[1:]
    i[lens[:-1]] -= end[:-1]
    np.cumsum(i, out=i)
    return i

def sum_by_group(values, groups):
    order = np.argsort(groups)
    groups = groups[order]
    values = values[order]
    values.cumsum(out=values)
    index = np.ones(len(groups), 'bool')
    index[:-1] = groups[1:] != groups[:-1]
    values = values[index]
    groups = groups[index]
    values[1:] = np.diff(values)
    return values, groups

"""

method1="""
list_list_lens = np.array(map(len, list_list_values))
comp_vals_expanded = np.repeat(list_comp_values, list_list_lens)

list_vals_flat = np.fromiter(itertools.chain.from_iterable(list_list_values),dtype=int)
list_list_starts = np.concatenate(([0], np.cumsum(list_list_lens)[:-1]))

toadd = indices(list_list_starts[list_range_values],(list_list_starts + list_list_lens)[list_range_values])

v[list_vals_flat[toadd]] += comp_vals_expanded[toadd]
"""

method2="""
for k in list_range_values:
    v[list_list_values[k]] += list_comp_values[k]

"""

method3="""
llv = [list_list_values[i] for i in list_range_values]
lcv = [list_comp_values[i] for i in list_range_values]
counts = map(len, llv)
indices = np.concatenate(llv)
values = np.repeat(lcv, counts)

totals, indices_unique = sum_by_group(values, indices)
v[indices_unique] += totals
"""

t1 = Timer(method1,setup=setstr).timeit(100)
print t1

t2 = Timer(method2,setup=setstr).timeit(100)
print t2

t3 = Timer(method3,setup=setstr).timeit(100)
print t3

rawDescription: Eliminate for-loop in Python and Numpy construct


rawDescription: python print like this

description: Python print like this


code:
1 == 1 # true
1 != 1 # false
1 <> 1 # false
[] is [] # false (distinct objects)
a = b = []; a is b # true (same object)

rawDescription: Is there a "not equal" operator in Python?


code:
import yum

yb = yum.YumBase()
if yb.rpmdb.searchNevra(name='make'):
   print "installed"
else:
   print "not installed"

rawDescription: Determine if package installed with Yum Python API?


code:
req = requests.get('http://localhost/bigfile.bin', stream=True)
print "File is {} bytes long.".format(req.headers['Content-Length'])

while True:
    chunk = req.raw.read(1024)
    print "Chunk Length: {}".format(len(chunk))

rawDescription: Library for reading an HTTP response in a file-like manner?


code:
lamp = 0
rooms = ["hallEnt", "hallMid", "snowRoom", "giantNature", "strangeWall", "riverBank"]
room = rooms[0]

if lamp == 1:
        connected_room = ["hallMid", "snowRoom"]
        print "You are currently inside the " + room + "."
        print "You can see " + connected_room[0] + " and " + connected_room[1] + " in the distance."
else:
        connected_room = ["snowRoom"]
        print "You are currently inside the " + room + "."
        print "You can see the " + connected_room[0] +  " in the distance."

rawDescription: How to code item interaction in text adventure

description: Code item interaction in text adventure


code:
class a:

    def __init__(self):
        self.__variable = 6

    def b(self, value=None):
        if value is None:
            value = self.__variable
        print value

rawDescription: Using class variable as non-default argument in python


rawDescription: multiple group matches for single regex

description: Multiple group matches for single regex


code:
def play_game(player1, player2, beats):

    if (player1 == player2):
        return ("Tie")
    elif (player1 == beats[player2]):
        return ("Player 1 wins.")
    elif (player2 == beats[player1]):
        return ("Player 2 wins.")

beats = {
    'scissors': 'rock',
    'rock': 'paper',
    'paper': 'scissors',
 }

player1 = input("Please enter either rock, paper, or scissors: ")
while player1 not in beats.keys():
    player1 = input("That isn't an option. Please try again.")

player2 = input("Please enter either rock, paper, or scissors: ")
while player2 not in beats.keys():
    player2 = input("That isn't an option. Please try again.")

message = play_game(player1, player2, beats)
print message

rawDescription: Rock, Paper, Scissors Game in Python

description: Rock, Paper, Scissors Game in Python


code:
def retrive(directory, a_regex):
    for filename in glob.glob(os.path.join(directory, '*.txt')):
        with open(filename, 'r') as file:
            important_stuff = re.findall(a_regex, file.read(), re.S)
            my_list = [tuple([j.split()[0] for j in i]) for i in important_stuff]
            # print my_list # old line
            print str(my_list).strip('[]') + filename.split('/')[-1]

lists_per_file = retrive(directory,regex_)

rawDescription: How to carry in a list the name each file from a directory with python?

description: Carry in a list the name each file from a directory with python


code:
import sys
from urllib import unquote_plus

from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

class MyWebPage(QWebPage):
    formSubmitted = pyqtSignal(QUrl)

    def acceptNavigationRequest(self, frame, req, nav_type):
        if nav_type == QWebPage.NavigationTypeFormSubmitted:
            self.formSubmitted.emit(req.url())
        return super(MyWebPage, self).acceptNavigationRequest(frame, req, nav_type)

class Window(QWidget):
    def __init__(self, html):
        super(Window, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        view = QWebView(self)
        layout = QVBoxLayout(self)
        layout.addWidget(view)
        layout.setContentsMargins(0, 0, 0, 0)
        view.setPage(MyWebPage())
        view.setHtml(html)
        view.page().formSubmitted.connect(self.handleFormSubmitted)

    def handleFormSubmitted(self, url):
        self.close()
        elements = {}
        for key, value in url.encodedQueryItems():
            key = unquote_plus(bytes(key)).decode('utf8')
            value = unquote_plus(bytes(value)).decode('utf8')
            elements[key] = value
        # do stuff with elements...
        for item in elements.iteritems():
            print '"%s" = "%s"' % item
        qApp.quit()

# setup the html form
html = """
<form action="" method="get">
Like it?
<input type="radio" name="like" value="yes"/> Yes
<input type="radio" name="like" value="no" /> No
<br/><input type="text" name="text" value="" />
<input type="submit" name="submit" value="Send"/>
</form>
"""

def main():
    app = QApplication(sys.argv)

    window = Window(html)
    window.show()
    app.exec_()

if __name__ == "__main__":
    main()

rawDescription: PyQt Webkit and html forms: Fetching output and closing window


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import collections

def hcl_to_rgb(hue=0, chroma=0, luma=0) :
    # Notes:
    #   coded from http://en.wikipedia.org/wiki/HSL_and_HSV#From_luma.2Fchroma.2Fhue
    #   with insights from gem.c in MagickCore 6.7.8
    #   http://www.imagemagick.org/api/MagickCore/gem_8c_source.html
    # Assume:
    #   h, c, l all in range 0 .. 1 (cylindrical coordinates)
    # Returns a tuple:
    #   r, g, b all in the range 0 .. 1 (cubic cartesian coordinates)

    # sanity checks
    hue = math.modf(float(hue))[0]
    if hue < 0 or hue >= 1 :
        raise ValueError('hue is a value greater than or equal to 0 and less than 1')
    chroma = float(chroma)
    if chroma < 0 or chroma > 1 :
        raise ValueError('chroma is a value between 0 and 1')
    luma = float(luma)
    if luma < 0 or luma > 1 :
        raise ValueError('luma is a value between 0 and 1')

    # do the conversion
    _h = hue * 6.0
    x = chroma * ( 1 - abs((_h % 2) - 1) )

    c = chroma
    if   0 <= _h and _h < 1 :
        r, g, b = (c, x, 0.0)
    elif 1 <= _h and _h < 2 :
        r, g, b = (x, c, 0.0)
    elif 2 <= _h and _h < 3 :
        r, g, b = (0.0, c, x)
    elif 3 <= _h and _h < 4 :
        r, g, b = (0.0, x, c)
    elif 4 <= _h and _h < 5 :
        r, g, b = (x, 0.0, c)
    elif 5 <= _h and _h <= 6 :
        r, g, b = (c, 0.0, x)
    else :
        r, g, b = (0.0, 0.0, 0.0)

    m = luma - (0.298839*r + 0.586811*g + 0.114350*b)
    z = 1.0
    if m < 0.0 :
        z = luma/(luma-m)
        m = 0.0
    elif m + c > 1.0 :
        z = (1.0-luma)/(m+c-luma)
        m = 1.0 - z * c
    (r, g, b) = (z*r+m, z*g+m, z*b+m)

    # clipping ...
    (r, g, b) = (min(r, 1.0), min(g, 1.0), min(b, 1.0))
    (r, g, b) = (max(r, 0.0), max(g, 0.0), max(b, 0.0))
    return (r, g, b)

def ggColorSlice(n=12, hue=(0.004,1.00399), chroma=0.8, luma=0.6, skipHue=True) :
    # Assume:
    #   n: integer >= 1
    #   hue[from, to]: all floats - red = 0; green = 0.33333 (or -0.66667) ; blue = 0.66667 (or -0.33333)
    #   chroma[from, to]: floats all in range 0 .. 1
    #   luma[from, to]: floats all in range 0 .. 1
    # Returns a list of #rgb colour strings:

    # convert stand alone values to ranges
    if not isinstance(hue, collections.Iterable):
        hue = (hue, hue)
    if not isinstance(chroma, collections.Iterable):
        chroma = (chroma, chroma)
    if not isinstance(luma, collections.Iterable):
        luma = (luma, luma)

    # convert ints to floats
    hue = [float(hue[y]) for y in (0, 1)]
    chroma = [float(chroma[y]) for y in (0, 1)]
    luma = [float(luma[y]) for y in (0, 1)]

    # some sanity checks
    n = int(n)
    if n < 1 or n > 360 :
        raise ValueError('n is a value between 1 and 360')
    if any([chroma[y] < 0.0 or chroma[y] > 1.0 for y in (0, 1)]) :
        raise ValueError('chroma is a value between 0 and 1')
    if any([luma[y] < 0.0 or luma[y] > 1.0 for y in (0, 1)]) :
        raise ValueError('luma is a value between 0 and 1')

    # generate a list of hex colour strings
    x = n + 1 if n % 2 else n
    if n > 1 :
        lDiff = (luma[1] - luma[0]) / float(n - 1.0)
        cDiff = (chroma[1] - chroma[0]) / float(n - 1.0)
        if skipHue :
            hDiff = (hue[1] - hue[0]) / float(x)
        else :
            hDiff = (hue[1] - hue[0]) / float(x - 1.0)
    else:
        hDiff = 0.0
        lDiff = 0.0
        cDiff = 0.0

    listOfColours = []
    for i in range(n) :
        c = chroma[0] + i * cDiff
        l = luma[0] + i * lDiff
        h = math.modf(hue[0] + i * hDiff)[0]
        h = h + 1 if h < 0.0 else h
        (h, c, l) = (min(h, 0.99999999999), min(c, 1.0), min(l, 1.0))
        (h, c, l) = (max(h, 0.0), max(c, 0.0), max(l, 0.0))
        (r, g, b) = hcl_to_rgb(h, c, l)
        listOfColours.append( '#%02x%02x%02x' % (int(r*255), int(g*255), int(b*255)) )
    return listOfColours

for i in range(1, 20) :
    # made up data
    x = np.array(range(20))
    d = {}
    for j in range(1, i+1) :
        y = x * (1.0 + j/10.0) + j/10.0
        d['y'+'%03.0d' % j] = pd.Series(data=y , index=x)
    df = pd.DataFrame(d)

    # plot example
    plt.figure(num=1, figsize=(10,5), dpi=100) # set default image size
    colours = ggColorSlice(n=i)
    if len(colours) == 1:
        colours = colours[0] # kludge
    df.plot(linewidth=4.0, color=colours)
    fig = plt.gcf()
    f = 'test-'+str(i)+'.png'
    print f
    plt.title(f)
    fig.savefig(f)
    plt.close()

rawDescription: replicating R/ggplot2 colours in python

description: Replicating R/ggplot2 colours in python


code:
import pydot
pydot.find_graphviz()
print pydot.find_graphviz.__doc__

rawDescription: Python graphviz - pydot.Dot.write_png doesnt work (windows)


code:
# template for "Guess the number" mini-project
# input will come from buttons and an input field
# all output for the game will be printed in the console

import simplegui
import random

# helper function to start and restart the game
def new_game():
    # initialize global variables used in your code here
    global secret_number
    global number_of_guesses
    secret_number = random.randrange(0, 101)
    print secret_number
    number_of_guesses = 7
    print ""
    print "New Game! Current range is set to 0 - 100!"

# define event handlers for control panel
def range100():
    # button that changes the range to [0,100) and starts a new game
    global secret_number
    global number_of_guesses
    secret_number = random.randrange(0, 101)
    number_of_guesses = 7
    print secret_number
    print "New Game! Current range is set to 0 - 1000!"

def range1000():
    # button that changes the range to [0,1000) and starts a new game
    global secret_number
    global number_of_guesses
    secret_number = random.randrange(0, 1001)
    number_of_guesses = 10
    print secret_number
    print "New Game! Current range is set to 0 - 1000!"

def input_guess(guess):
    # main game logic goes here
    global number_of_guesses
    guess = int(guess)
    print ""
    print "Guess was: ", guess
    print ""

    if guess > secret_number:
        print "Lower!"
        print ""
        number_of_guesses -= 1
        print "Guesses Remaining: ", number_of_guesses
        print ""

        if number_of_guesses == 0:
            print "Game Over! You Ran Out Of Guesses!"
            new_game()

    elif guess < secret_number:
        print "Higher!"
        print ""
        number_of_guesses -= 1
        print "Guesses Remaining: ", number_of_guesses
        print ""

        if number_of_guesses == 0:
            print "Game Over! You Ran Out Of Guesses!"
            new_game()

    elif number_of_guesses == secret_number:
        print "Correct!"
        new_game()

    else:
        print "S**t, something's broken."
        new_game()

# create frame
frame = simplegui.create_frame("Guess The Number", 175, 175)

# register event handlers for control elements and start frame
frame_input = frame.add_input("Your Guess: ", input_guess, 100)
range_100 = frame.add_button("Range 1 - 100", range100, 100)
range_1000 = frame.add_button("Range 1- 1000", range1000, 100)
frame.start()

# call new_game
new_game()

# always remember to check your completed program against the grading rubric

rawDescription: Python: How to end game if number_of_guesses is 0?


code:
parts = s.split(designatedstring)
num = len(parts) - 1
replacements = itertools.product([designatedstring, replacerstring], repeat=num)
replacements = list(replacements)
replacements.remove((designatedstring,) * num)
for r in replacements:
    print ''.join(itertools.chain(*zip(parts, r + ('',))))

rawDescription: Python replacing characters selectively from a string


code:
""" Partition a list into sublists whose sums don't exceed a maximum
    using a First Fit Decreasing algorithm. See
    http://www.ams.org/new-in-math/cover/bins1.html
    for a simple description of the method.
"""

class Bin(object):
    """ Container for items that keeps a running sum """
    def __init__(self):
        self.items = []
        self.sum = 0

    def append(self, item):
        self.items.append(item)
        self.sum += item

    def __str__(self):
        """ Printable representation """
        return 'Bin(sum=%d, items=%s)' % (self.sum, str(self.items))

def pack(values, maxValue):
    values = sorted(values, reverse=True)
    bins = []

    for item in values:
        # Try to fit item into a bin
        for bin in bins:
            if bin.sum + item <= maxValue:
                #print 'Adding', item, 'to', bin
                bin.append(item)
                break
        else:
            # item didn't fit into any bin, start a new bin
            #print 'Making new bin for', item
            bin = Bin()
            bin.append(item)
            bins.append(bin)

    return bins

if __name__ == '__main__':
    import random

    def packAndShow(aList, maxValue):
        """ Pack a list into bins and show the result """
        print 'List with sum', sum(aList), 'requires at least', (sum(aList)+maxValue-1)/maxValue, 'bins'

        bins = pack(aList, maxValue)

        print 'Solution using', len(bins), 'bins:'
        for bin in bins:
            print bin

        print

    aList = [10,9,8,7,6,5,4,3,2,1]
    packAndShow(aList, 11)

    aList = [ random.randint(1, 11) for i in range(100) ]
    packAndShow(aList, 11)

rawDescription: Python Implementations of Packing Algorithm


code:
import os
your_dir = '/home/...' # Dir path

for filename in os.listdir(your_dir):
    if os.path.isfile(filename):
        print filename
        do_something(filename)

rawDescription: Python - loop through a directory and set a variable to a filename to be manipulated


code:
re.compile('[0-9]+').split("hel2l3o")

re.compile('cut').split("hellocutworldcutpython")
l=re.compile('cut').split("hellocutworldcutpython")
print l[0], string.join([l[i] for i in range(1, len(l))], "")

rawDescription: Split text using Python

description: Split text using Python


code:
from sklearn import linear_model
from sklearn import datasets
from sklearn import metrics
boston = datasets.load_boston()

X_train = boston.data[:450]  #define training X set
y_train = boston.target[:450] #define training y set

X_test = boston.data[450:]  #define test X set
y_test = boston.target[450:] #define test y set

lin = linear_model.LinearRegression() #initialize regressor

lin.fit(X_train, y_train) #fit training data
preds = lin.predict(X_test) #make prediction on X test set

print metrics.mean_absolute_error(y_test, preds) #evaluate performance

rawDescription: Unknown label type error when Sklearn naive bayes used with floating point numbers


code:
from bs4 import BeautifulSoup as Soup
from urllib import urlopen

url = "http://www.darlighting.co.uk/"
html = urlopen(url).read()
soup = Soup(html)

# find image tag with specific source
the_image_tag = soup.find("img", src='/images/dhl_logo.png')
print type(the_image_tag), the_image_tag
# >>> <class 'bs4.element.Tag'> <img src="/images/dhl_logo.png"/>

# find all image tags
img_tags = soup.find_all("img")
for img_tag in img_tags:
    print img_tag['src']

rawDescription: How to search html for a link and print the link using python?

description: Search html for a link and print the link using python


code:
results = list(unique_service_query)

for outer_service in results:
    for inner_service in results:
        print outer_service.service,inner_service.service

rawDescription: Python peewee iterate over SelectQuery

description: Python peewee iterate over SelectQuery


code:
import signal
import sys
import time

def main_function():

    data_for_signal_handler = 10

    def signal_handler(*args):
        print data_for_signal_handler
        sys.exit()

    signal.signal(signal.SIGINT, signal_handler) # Or whatever signal

    while True:
        data_for_signal_handler += 1
        time.sleep(0.5)

if __name__ == '__main__':
    main_function()

rawDescription: Using variables in signal handler - require global?


code:
import re

functions = ["details", "nvp_add"]
caselines_index = []
cases = []
readlines = []

def read(in_file):
  global cases
  global caselines_index
  global readlines
  with open(in_file, 'r') as file:
    for line in file.readlines():
      readlines.append(line.strip())
    for line in readlines:
      case_search = re.search("case\s\".+?\"\:\s", line)
      if case_search:
        caselines_index.append(readlines.index(line))
    print caselines_index
    caselines_index_iter = iter(caselines_index)
    int_line_index = int(next(caselines_index_iter))
    int_next_index = int(next(caselines_index_iter))
    while True:
      try:
        case_text = ' '.join(readlines[int_line_index:int_next_index]).strip()
        case = [readlines[int_line_index].strip(), case_text]
        cases.append(case)
        int_line_index = int_next_index
        int_next_index = int(next(caselines_index_iter))
      except StopIteration:
        case_text = ' '.join(readlines[int_line_index:len(readlines) - 1]).strip()
        case = [readlines[int_line_index].strip(), case_text]
        cases.append(case)
        break

def work():
  for func in functions:
    with open(func+".txt", 'w+') as result_file:
      for case_list in cases:
        caseline = case_list[0].strip()
        result_file.write(caseline + "\n")
        nvp = re.findall(func+"\(.+?\)", case_list[1].strip())

        for item in nvp:
          result_list = re.findall("(\$.+?)[\,\)]", item)

          for result in result_list:
            if "$*" not in result:
              result_file.write(result + "\n")

def main():
  global functions
  in_file = "input.txt"
  read(in_file)
  work()

if __name__=="__main__":
  main()

rawDescription: Extract all strings start from $ from 2 different functions under on plain text input file


code:
d = {'name': 'user'}
print d['name']
user

rawDescription: python get elements in array by column name like in php

description: Python get elements in array by column name like in php


code:
import dis
def do_stuff(q):
  while True:
    print q.get()
    q.task_done()

dis.dis(do_stuff)

rawDescription: Why does this multithreaded python program print from 0 to 99 CORRECTLY?


code:
s = 'banana'
print s.replace('a', '\\x' + format(ord('a'), 'x'))
print s.replace('a', '\\x' + format(ord('a'), 'x')).decode('string-escape')

rawDescription: Encode/decode specific character in string with hex notation using Python 2.7


code: print dict.get("name", "<default name>")

rawDescription: How to properly handle simplejson errors?

description: Properly handle simplejson errors


code:
import HTMLParser
h = HTMLParser.HTMLParser()
print h.unescape('£682m')
import html.parser
h = html.parser.HTMLParser()
print(h.unescape('£682m'))

rawDescription: Decoding HTML Entities using Bottle for Python


code:
import glob
import pefile

for filename in glob.iglob('C:\Documents and Settings\Zha\Desktop\\test\*.exe'):
    pe =  pefile.PE(filename)
    pe.parse_data_directories()
    print '%x' % pe.FILE_HEADER.NumberOfSections

rawDescription: How to make pefile python module read multiple executable file in a directory

description: Make pefile python module read multiple executable file in a directory


code:
from pyparsing import *

def p(s,l,t):
    print 'Location of %s: %s' % (s, l,)

Z = Literal('0')
POINT = Literal('.')
BIN_DIGITS = Word('01')
OCT_DIGITS = Word('01234567')
DEC_DIGITS = Word('0123456789')
HEX_DIGITS = Word('0123456789abcdefABCDEF')
DEC_INT = DEC_DIGITS.copy().setParseAction(lambda t: int(t[0]))
BIN_INT = Combine(Z + ((Literal('b') | 'B')) + BIN_DIGITS).\
        setParseAction(lambda t: int(t[0], 2))
OCT_INT = Combine(Z + ((Literal('o') | 'O')) + OCT_DIGITS).\
        setParseAction(lambda t: int(t[0], 8))
HEX_INT = Combine(Z + ((Literal('x') | 'X')) + HEX_DIGITS).\
        setParseAction(lambda t: int(t[0], 16))
INTEGER = HEX_INT | OCT_INT | BIN_INT | DEC_INT
EXP = Combine(CaselessLiteral('E') + Optional(Literal('+') | Literal('-')) + DEC_DIGITS)
POINT_FLOAT = Combine(Optional(DEC_DIGITS) + POINT + DEC_DIGITS) | \
        Combine(DEC_DIGITS + POINT)
EXP_FLOAT = Combine(DEC_DIGITS + EXP) | Combine(POINT_FLOAT + EXP)
FLOAT = (EXP_FLOAT | POINT_FLOAT).setParseAction(lambda t: float(t[0]))
NUMBER = (FLOAT | INTEGER).setParseAction(p)
NUMBER2 = Combine(ZeroOrMore(White(exact=1)).suppress() + NUMBER)

NUMBER2.parseString('    12345')

rawDescription: How to get location of matched tokens using pyparsing?

description: Get location of matched tokens using pyparsing


code:
f = open("practice.txt", "r")

list = []

while True:
    q = f.read(1)
    if not q:
        break
    list.append(ord(q))

print list

rawDescription: ASCII Encryption

description: ASCII Encryption


code:
for a in soup.findAll("a", "title"):
    print a.get_text()

rawDescription: HTML parse with python and bs

description: HTML parse with python and bs


code:
#!/usr/bin/env python
import datetime

# http://www.feedparser.org/
import feedparser
# http://www.dalkescientific.com/Python/PyRSS2Gen.html
import PyRSS2Gen

# Get the data
parsed_feed = feedparser.parse('http://reddit.com/.rss')

# Modify the parsed_feed data here

items = [
    PyRSS2Gen.RSSItem(
        title = x.title,
        link = x.link,
        description = x.summary,
        guid = x.link,
        pubDate = datetime.datetime(
            x.modified_parsed[0],
            x.modified_parsed[1],
            x.modified_parsed[2],
            x.modified_parsed[3],
            x.modified_parsed[4],
            x.modified_parsed[5])
        )

    for x in parsed_feed.entries
]

# make the RSS2 object
# Try to grab the title, link, language etc from the orig feed

rss = PyRSS2Gen.RSS2(
    title = parsed_feed['feed'].get("title"),
    link = parsed_feed['feed'].get("link"),
    description = parsed_feed['feed'].get("description"),

    language = parsed_feed['feed'].get("language"),
    copyright = parsed_feed['feed'].get("copyright"),
    managingEditor = parsed_feed['feed'].get("managingEditor"),
    webMaster = parsed_feed['feed'].get("webMaster"),
    pubDate = parsed_feed['feed'].get("pubDate"),
    lastBuildDate = parsed_feed['feed'].get("lastBuildDate"),

    categories = parsed_feed['feed'].get("categories"),
    generator = parsed_feed['feed'].get("generator"),
    docs = parsed_feed['feed'].get("docs"),

    items = items
)

print rss.to_xml()

rawDescription: How do I turn an RSS feed back into RSS?

description: Turn an RSS feed back into RSS


code:
from Tkinter import *

root=Tk()
frame=Frame(root)
frame.pack()
update_label = StringVar()  # Made a StringVar so you don't get new labels every time a key is pressed.
update_label.set("entry:")
entry=Entry(frame)
entry.pack()

label=Label(frame,textvariable=update_label)  # Used textvariable= instead of text=
label.pack()

def updatelabel(event):
    update_label.set("entry:" + entry.get())  # Setting the variable used in textvariable=
    print "called"

root.bind("<Key>", updatelabel)  # Changed entry.bind to root.bind

root.mainloop()

rawDescription: Python 2.7 Tkinter Entry widget requires two events to update


code:
s = '| | +-out\windows-x86-MD-mbcs-vs2008-rel\bin\VisualStudio08-32bit.exe'
print s.split('-', 1)[1]
# out\windows-x86-MD-mbcs-vs2008-relin\VisualStudio08-32bit.exe

rawDescription: python: removing first instance of a specific character using regex

description: Python: removing first instance of a specific character using regex


code:
import sys
from BeautifulSoup import BeautifulSoup as Soup

def parseLog(file):
    file = sys.argv[1]
    handler = open(file).read()
    soup = Soup(handler)
    for message in soup.findAll('message'):
        msg_attrs = dict(message.attrs)
        f_user = message.find('from').user
        f_user_dict = dict(f_user.attrs)
        print "%s: %s [%s @ %s]" % (f_user_dict[u'friendlyname'],
                                    message.find('text').decodeContents(),
                                    msg_attrs[u'date'],
                                    msg_attrs[u'time'])

if __name__ == "__main__":
    parseLog(sys.argv[1])

rawDescription: Python BeautifulSoup XML Parsing

description: Python BeautifulSoup XML Parsing


code:
import sys
import multiprocessing
from kivy.app import App
from kivy.lang import  Builder
from time import sleep#, localtime, time

def str_to_class(str):
    return reduce(getattr, str.split("."), sys.modules[__name__])

class App1(App):
    def build(self):
        return Builder.load_string("BoxLayout:\n    Button:\n       text: \"hello 1\"")

class App2(App):
    def build(self):
        return Builder.load_string("BoxLayout:\n    Button:\n       text: \"hello 2\"")

class Wrapper(object):
    def __init__(self, *kargs, **kwargs):
        super(Wrapper, self).__init__()
        self.running_app = None
        self.next_app = 'App1'

    def change_running_app(self, name='App1'):
        if self.running_app is not None:
            self.running_app.terminate()
        self.running_app = multiprocessing.Process(target=self.run_app, kwargs={'name':name})
        self.running_app.start()

    def run_app(self, name='App1'):
        app = str_to_class(name)()
        app.run()

    def swap(self):
        self.change_running_app(name=self.next_app)
        self.next_app = ['App1', 'App2']['App1' is self.next_app]

if __name__ == '__main__':
    counter = 0
    w = Wrapper()
    while True:
        counter += 1
        print "Started App instance {}".format(counter)
        w.swap()
        sleep(5)

rawDescription: Nested / alternating apps with Kivy

description: Nested / alternating apps with Kivy


code:
for line in open("file.txt", 'r').readlines():
    line = line.strip().split(" ")
    lineName = line.pop(0)
    arr = [0.0] * int(line[-1].split(":")[0])  # fills the array with zeros

    for element in line:
        index,value = element.split(":")
        arr[int(index)-1] = float(value)

    print lineName + " " + " ".join(map(str, arr))  # /questions/6507431

rawDescription: how to load a libsvm file using python ( fill missing values)

description: Load a libsvm file using python ( fill missing values)


code:
con=ldap.initialize('ldap://192.168.16.12:38')

user_dn = r"Administrator@foo.com"
password = "bar"

criteria = "(&(objectClass=user)(sAMAccountName=username))"
attributes = ['displayName', 'company']

try:
    con.simple_bind_s(user_dn, password)
    res =con.search_s("CN=Users,DC=foo,DC=com", ldap.SCOPE_SUBTREE,'(objectClass=User)')
    for dn, entry in res:
        print dn
except Exception, error:
    print error

rawDescription: Using LDAP to find Users in Active Directory - no Users?


code:
import re

a = [
    ['^/ungrad/info.cfm$', '/ungrad/info'],
    ['^/admiss/testing.cfm$', '/admiss/testing'],
    ['^/ungrad/testing/$', '/ungrad/info.cfm']
]

def matchingfun(b):
    for list1 in a: # iterating the main list
        for reglist in list1: # iterating the inner lists
            count  = 0
            matchedurl = []
            for innerlist in reglist[:1]: # iterating the inner list items
                c = b.match(innerlist) # matching the regx
                if c:
                    count = count+1
                    if count > 0:
                        matchedurl.append(reglist)
    return matchedurl

result1 = []
for list1 in a:
    for reglist in list1:
        b = re.compile(reglist[0])
        result = matchingfun(b)
        result1.extend(result)

bs = list(set(result1))

print "matched url is", bs

rawDescription: Matching regex to list items in Python

description: Matching regex to list items in Python


code:
import os
place = 'C:\\Users\\Me\\Documents\\Python Programs\\'
for root, dirs, files in os.walk(place):
    for f in files:
        file_path = os.path.join(root, f) #Full path to the file
        size = os.path.getsize(file_path) #pass the full path to getsize()
        if size == 0:
            print f, file_path

rawDescription: Finding and printing file name of zero length files in python


code:
for lines in fp:
    temp = lines.split(",")[:-1]
    print temp

rawDescription: How do i check/validate existing file with my requirement in python

description: Check/validate existing file with my requirement in python


code:
import os
for file in os.listdir("C:\Temp\My Pictures"):
    if file.endswith(".gif"):
        print file

rawDescription: How do you get the names of all gif images in a folder in python 2?

description: Get the names of all gif images in a folder in python 2


code:
import itertools

# this list of languages could be longer and should read from a file
languages = ["English", "Spanish", "Italian", "Japanese", "French",
             "Standard Chinese", "Chinese", "Hindi", "Standard Arabic", "Russian"]

languages = [language.lower() for language in languages]

# Loop through US.txt and format it. Download from geonames.org.
cities = []
with open('US.txt', 'r') as us_data:
    for line in us_data:
        line_split = line.split("\t")
        cities.append("{}:{}".format(line_split[4], line_split[2]))

# This is the dataset
with open('state-teachers.txt', 'r') as teachers:
    next(teachers)  # skip header

    for line in teachers:
        # Replace all double spaces with single spaces
        while line.find("  ") != -1:
            line = line.replace("  ", " ")

        line_split = line.split(" ")

        # Lat/Lon are the last 2 items
        longitude = line_split.pop().strip()
        latitude = line_split.pop().strip()

        # Search for potential languages and trim off the line as we find them
        teacher_languages = []

        while True:
            language_check = line_split[-1]
            if language_check.lower().replace(",", "").strip() in languages:
                teacher_languages.append(language_check)
                del line_split[-1]
            else:
                break

        # Rejoin everything and then use phone number as the special key to split on
        line = " ".join(line_split)

        phone_start = line.find("(")
        phone = line[phone_start:phone_start+14].strip()

        after_phone = line[phone_start+15:]

        # Certifications can be recognized as acronyms
        # Anything else is assumed to be an area of practice
        certifications = []
        areas_of_practice = []

        specialties = after_phone.split(",")
        for specialty in specialties:
            specialty = specialty.strip()
            if specialty[0:2].upper() == specialty[0:2]:
                certifications.append(specialty)
            else:
                areas_of_practice.append(specialty)

        before_phone = line[0:phone_start-1]
        line_split = before_phone.split(" ")

        # State is the last column before phone
        state = line_split.pop()

        # Name should be the first 2 columns, at least. This is a basic guess.
        name = line_split[0] + " " + line_split[1]

        line_split = line_split[2:]

        # Add initials
        if len(line_split[0].strip()) == 1:
            name += " " + line_split[0].strip()
            line_split = line_split[1:]

        # Combo of all potential word combinations to see if we're dealing with a city or a name
        combos = [" ".join(combo) for combo in set(itertools.permutations(line_split))] + line_split

        line = " ".join(line_split)
        city = ""

        # See if the state:city combo is valid. If so, set it and let everything else be the name
        for combo in combos:
            if "{}:{}".format(state, combo) in cities:
                city = combo
                line = line.replace(combo, "")
                break

        # Remaining data must be a name
        if line.strip() != "":
            name += " " + line

        # Clean up names
        last_name, first_name = [piece.strip() for piece in name.split(",")]

        print first_name, last_name

rawDescription: Extracting name from line

description: Extracting name from line


code:
import operator
ops = {'==' : operator.eq,
       '!=' : operator.ne,
       '<=' : operator.le,
       '>=' : operator.ge,
       '>'  : operator.gt,
       '<'  : operator.lt}

maths_operator = "=="

if ops[maths_operator]("test", "test"):
    print "match found"

maths_operator = "!="

if ops[maths_operator]("test", "test"):
    print "match found"
else:
    print "match not found"

rawDescription: python if statement with variable mathematical operator

description: Python if statement with variable mathematical operator


code:
import numpy as np
import matplotlib.pyplot as plt

data = np.random.uniform(0, 5, size=(24,30,30))
data[3,:,:]=np.random.uniform(1,3,size=(30,30))  # example of bad plot
fgsize=(12,4)
numrecs = np.size(data,axis=0)
cbar_min = np.min(data)
cbar_max = np.max(data)
cbarlabels = np.linspace(np.floor(cbar_min), np.ceil(cbar_max), num=5, endpoint=True)

# Set the normalisation for 35 levels (as in your example)
import matplotlib.colors as mc
levels = np.linspace(np.floor(cbar_min), np.ceil(cbar_max), 35) # to draw 35 levels
norm = mc.BoundaryNorm(levels, 256)

for tt in range(0, numrecs):
    print cbar_min, cbar_max
    plt.figure(figsize=fgsize, dpi=80)
    plt.title('this is a title')

    # Draw those levels, with proper normalisation, here:
    plt.contourf(data[tt, :, :], levels, vmin=cbar_min, vmax=cbar_max, cmap='coolwarm', levels=levels, norm=norm)

    cbar = plt.colorbar()
    cbar.set_ticks(cbarlabels)
    cbar.set_ticklabels(cbarlabels)
    cbar.set_label('my data has units')
    plt.show()

rawDescription: How do I set limits on ticks, colors, and labels for colorbar contourf matplotlib

description: Set limits on ticks, colors, and labels for colorbar contourf matplotlib


code:
from functools import wraps

def decobj(func):
    @wraps(func)
    def wrapper(self, *args, **kwards):
        with self.lock:
            print 'Got the lock'
            func(self, *args, **kwards)
    return wrapper

rawDescription: What is the best way to decorate methods of a Python class?


code:
string = "How are you?"
print "\033[34m" + string + "\033[0m"

rawDescription: Python: How to print the value of variable in color


code:
def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
    n = 2    # put `n` label on `2` balloon
    x.append(4) # call `append` method of whatever object `x` is referring to.
    print 'In f():', n, x
    x = []   # put `x` label on `[]` ballon
    # x = [] has no effect on the original list that is passed into the function

rawDescription: In Python, why can a function modify some arguments as perceived by the caller, but not others?


code:
print "hello!"
print "I\'m Charlie and I\'m going to test the security of your password!"

print "first I\'d like to know a bit about you! What is your name? (No data is stored!!)"
name = raw_input()
print "Nice to meet you, %s!" % (name)

print "What is your date of birth?"
dob = raw_input()

print "OK! Those answers are used to help me but are forgotten when you close the window!"
print "Now %s, are you ready for your password to be tested?" % (name)

# I fixed the indentation below:

if raw_input() == "yes": #<-- fixed comparison operator here and added colon
    print "what is your password?"
if raw_input() == "no": #<-- fixed comparison operator here and added colon
    print "Suit yourself, %s!" % (name)

rawDescription: indentation error python 1

description: Indentation error python 1


code:
import collections

ring_buf = collections.deque(maxlen=17)

with open(file, 'r') as f:
    for line in f:
        ring_buf.append([line]) # append the new line and overwrite the last one
                              # FIFO style

        timestampline = None
        timestamp = None

        for word in searchstringsFilter1:
            if word in line:
                #print line
                timestampline = ring_buf[-16]
                #print timestampline
                keyline = line
                Rline = ring_buf[-10]
                print Rline

                Rline = re.sub('[()]', '', Rline)
                SNline = ring_buf[-4]
                SNline = re.sub('[()]', '', SNline)

rawDescription: Using Python to re-write my code from 'readlines' to 'for line in file' format


code:
class MyButton(Button):

    x = NumericProperty(-1)
    y = NumericProperty(-1)

class MyGrid(GridLayout):

    cols = NumericProperty(1)

    def add_buttons(self):
        for i in xrange(10):
            button = MyButton(x=i, y=i)
            self.add_widget(button)

    def print_children(self):
        for child in self.children:
            print 'button coords:', child.x, child.y

rawDescription: Kivy: programmatically create widget IDs


code:
import numpy as np
import theano
import theano.tensor as T

minibatchsize = 2
numfilters = 3
numsamples = 4
upsampfactor = 5

totalitems = minibatchsize * numfilters * numsamples

code = np.arange(totalitems).reshape((minibatchsize, numfilters, numsamples))

auxpos = np.arange(totalitems).reshape((minibatchsize, numfilters, numsamples)) % upsampfactor
auxpos += (np.arange(4) * 5).reshape((1,1,-1))

# first in numpy
shp = code.shape
upsampled_np = np.zeros((shp[0], shp[1], shp[2] * upsampfactor))
upsampled_np[np.arange(shp[0]).reshape(-1, 1, 1), np.arange(shp[1]).reshape(1, -1, 1), auxpos] = code

print "numpy output:"
print upsampled_np

# now the same idea in theano
encoded = T.tensor3()
positions = T.tensor3(dtype='int64')
shp = encoded.shape
upsampled = T.zeros((shp[0], shp[1], shp[2] * upsampfactor))
upsampled = T.set_subtensor(upsampled[T.arange(shp[0]).reshape((-1, 1, 1)), T.arange(shp[1]).reshape((1, -1, 1)), positions], encoded)

print "theano output:"
print upsampled.eval({encoded: code, positions: auxpos})

rawDescription: Theano: how to efficiently undo/reverse max-pooling


code:
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
from BeautifulSoup import BeautifulSoup as bs
import requests

def getImages(url):
    #Download the images
    r = requests.get(url)
    html = r.text
    soup = bs(html)
    output_folder = '~/amazon'
    #extracting the images that in div(s)
    for div in soup.findAll('div', attrs={'class':'image'}):
        modified_file_name = None
        try:
            #getting the data div using findNext
            nextDiv =  div.findNext('div', attrs={'class':'data'})
            #use findNext again on previous object to get to the anchor tag
            fileName = nextDiv.findNext('a').text
            modified_file_name = fileName.replace(' ','-') + '.jpg'
        except TypeError:
            print 'skip'
        imageUrl = div.find('img')['src']
        outputPath = os.path.join(output_folder, modified_file_name)
        urlretrieve(imageUrl, outputPath)

if __name__=='__main__':
    url = r'http://www.amazon.com/s/ref=sr_pg_1?rh=n%3A172282%2Ck%3Adigital+camera&keywords=digital+camera&ie=UTF8&qid=1343600585'
    getImages(url)

rawDescription: Python: BeautifulSoup extract text from anchor tag


code:
def is_base_pair(x, y):
    return (x=='a' and y=='u' or
            x=='u' and y=='a' or
            x=='c' and y=='g' or
            x=='g' and y=='c' or
            x=='g' and y=='u' or
            x=='u' and y=='g' )

# start and end are the inclusive range of places in which to look for pairs
def opt(rna, start, end):
    # if the range is too small, give up
    if start + 4 > end:
        return

    # the next left side to try to match
    nextLeft = start

    while nextLeft + 4 <= end:
        # find the right nucleobase to match the one at nextLeft
        #   start looking at the minimal distance and incrementally get bigger
        potentialRight = nextLeft + 4
        while not is_base_pair (rna[nextLeft], rna[potentialRight]) and potentialRight <= end:
            potentialRight += 1

        if is_base_pair (rna[nextLeft], rna[potentialRight]):
            print nextLeft, potentialRight
            # recursively search for pairs between the elements of this pair
            opt(rna, nextLeft + 1, potentialRight - 1)
            nextLeft = potentialRight + 1
        else:
            nextLeft += 1

rawDescription: base pairing within a section of RNA sequence using python

description: Base pairing within a section of RNA sequence using python


code:
import time

print 1
time.sleep(1)
print 2
time.sleep(0.45)
print 3
time.sleep(3)
print 4

rawDescription: can the execution of statements in Python be delayed?

description: Can the execution of statements in Python be delayed


rawDescription: python: how to merge a list into clusters?

description: Python: how to merge a list into clusters


code:
import ConfigParser
import StringIO

s_config = """
[example]
is_real: False
"""
buf = StringIO.StringIO(s_config)
config = ConfigParser.ConfigParser()
config.readfp(buf)
print config.getboolean('example', 'is_real')

rawDescription: How to read config from string or list?

description: Read config from string or list


code:
print "started"
self.SendCommand(kEdsCameraCommand_PressShutterButton, kEdsCameraCommand_ShutterButton_Completely_NonAF)
sleep(2)
self.SendCommand(kEdsCameraCommand_PressShutterButton)
print "finished"

rawDescription: Canon SDK bulb_mode command throws error 44313 (0xAD19)


code:
import datetime as dt
import numpy as np
import matplotlib.pyplot as plt

def main():
    data = generate_data()
    hour, minute, sec, temp = data.T

    # For timedeltas, we need to convert to fractional seconds in a day
    seconds = hour * 3600 + minute * 60 + sec

    # Now we'll convert to "full" datetimes
    day = dt.datetime(2016, 01, 01)
    times = [day + dt.timedelta(0, second) for second in seconds]

    fig, ax = plt.subplots()
    ax.plot_date(times, temp, color='lightblue', linestyle='-', marker='')
    fig.autofmt_xdate()
    plt.show()

def generate_data():
    """Generate data similar to yours."""
    num = 50000
    t = np.linspace(3, 22, num)
    minute = (t * 60) % 60
    second = (minute * 60) % 60
    hour = t.astype(int)
    minute = minute.astype(int)

    temp = np.random.normal(0, 1, num).cumsum()

    data = np.column_stack([hour, minute, second, temp])
    return data

main()

rawDescription: Time plotting in Python

description: Time plotting in Python


code:
for row in result:
  print row[0]

rawDescription: Python and MySQL print results

description: Python and MySQL print results


code:
from datetime import datetime, timedelta, date
import dateutil
st_date = '2016-11-01'
dt = dateutil.parser.parse(st_date).date()
tm_diff = dt - date(2016, 1, 1);
print tm_diff.days

rawDescription: Convert datetime (e.g. 2016-01-01, 2016-01-11) to integer days (e.g. 0, 11) in Python


code:
from ftplib import FTP
import sys, os

#######if you have proxy

####fill in you proxy ip here
#site = FTP('1.1.1.1')

#site.set_debuglevel(1)
#msg = site.login('anonymous@ftp.patricbrc.org')

site = FTP("ftp.patricbrc.org")
site.login()
site.cwd('/patric2/current_release/ec/')

bacteria_list = []
site.retrlines('LIST', bacteria_list.append)

output = sys.argv[1]
if not output.endswith("/"):
    output += "/"

print "bacteria_list: ", len(bacteria_list)

for c in bacteria_list:

    path_name = c.strip(" ").split()[-1]

    if "PATRIC.ec" in path_name:

        filename = path_name.split("/")[-1]
        site.retrbinary('RETR ' + path_name, open(output + filename , 'w').write)

rawDescription: Downloading Protein Sequences of multiple Organisms


code:
from collections import defaultdict # a mapping for station number to points

class Point(object):
    # der punkt mit xCoor yCoor
    pass

class SN:
    # the SN object in text file
    node = defaultdict(Point)

# read the text file
textFileContent = open('IDoNotKnowYourTextFileName.txt').read()

# in the next line you need to trust the other person - it executes the textfile
# but only knowing SN
exec textFileContent in {'SN': SN}

# in the following lines you can output the html file you need:
print '''
<title>MAP</title>

'''

rawDescription: Dynamically loading x & y coordinates from text file into html page as pixels for some points locations


code:
r = requests.get('http://www.crunchyroll.com/i-cant-understand-what-my-husband-is-saying')
soup = BeautifulSoup(r.text)
print soup.title
subtitles = soup.findAll('div',{'class':'wrapper container-shadow hover-classes'})

with open("BatchLinks.txt","w") as file:

    for episode in subtitles:
        x = episode.find_all('a')
        for a in x:

            z = a['href']

            link = 'http://www.crunchyroll.com'+ z
            print link
            file.write(link)

rawDescription: how to write multiple lines in a file using python

description: Write multiple lines in a file using python


code:
import kivy
kivy.require('1.0.8')

from kivy.core.window import Window
from kivy.app import App
from kivy.clock import Clock
from functools import partial

class MyMouse(App):

    def __init__(self, **kwargs):
        super(MyMouse, self).__init__(**kwargs)
        Clock.schedule_interval(partial(self.my_callback), 0.05)

    def my_callback(self, dt):
        print Window.mouse_pos

if __name__ == '__main__':
    MyMouse().run()

rawDescription: moving a Image with mouse cursor in Kivy

description: Moving a Image with mouse cursor in Kivy


code:
from dateutil import parser
import pytz
UTC = pytz.timezone('UTC')
date = parser.parse("2013-08-23T15:23:03+05:30")
dateutc = date.astimezone(UTC)
print dateutc.isoformat()
# or user strptime to have in the format you want (without time zone)
print dateutc.strftime("%Y-%m-%dT%H:%M:%S")

rawDescription: Local Time To UTC time pytz

description: Local Time To UTC time pytz


code:
import random

LENGTH = 30
NUMGUESSES = 20

def guess():
    return [random.randint(0, 1) for i in range(LENGTH)]

SEQUENCE = guess()
GUESSES = [guess() for i in range(NUMGUESSES)]

def hamming(a, b):
    return sum(aelem != belem for aelem, belem in zip(a, b))

# Flip if hamming > LENGTH / 2
mid = LENGTH / 2
for i in range(NUMGUESSES):
    if hamming(SEQUENCE, GUESSES[i]) > mid:
        GUESSES[i] = [1 - g for g in GUESSES[i]]

HAMMINGS = [hamming(SEQUENCE, g) for g in GUESSES]

print "Sequence:", SEQUENCE
print
for h, g in zip(HAMMINGS, GUESSES):
    print "Guess and hamming:", g, h
print

def compatible_sequences(guesses, hammings):
    # Use a stack instead of recursion, so we can make this a generator.
    stack = []
    # Start: we have chosen nothing yet, and the hammings have start values
    stack.append(([], hammings))

    while stack:
        so_far, hammingsleft = stack.pop()

        if -1 in hammingsleft:
            # Skip, choices so far are incompatible with the guesses
            continue

        if len(so_far) == LENGTH:
            # Success if all the Hamming distances were exactly correct
            if all(h == 0 for h in hammingsleft):
                yield so_far
            continue

        # Not done yet, add choices 0 and 1 to the queue
        place_in_guess = len(so_far)
        for choice in (1, 0):
            stack.append(
                (so_far + [choice],
                 [h - (g[place_in_guess] != choice)
                  for h, g in zip(hammingsleft, guesses)]))

print "Compatible sequences:"
for nr, sequence in enumerate(compatible_sequences(GUESSES, HAMMINGS), 1):
    print nr, sequence

rawDescription: How to speed up exponential time code

description: Speed up exponential time code


code:
import os, sys

# No other fds have been opened, so the lowest available are used (3, 4)
read, write = os.pipe()

# We want the child to write into fd#3, but right now that's the read
# end of the pipe, so do a little switching around:
temp = os.dup(read)
os.dup2(write, read)
os.dup2(temp, write)
os.close(temp)
read, write = write, read # swap actual values to avoid confusion

pid = os.fork()
if pid == 0: # child
   os.close(read)
   try:
       os.execl('/bin/bash', 'bash', '-c', 'echo testing...>&3')
   except OSError:
       sys.exit(1)
else: # parent
   os.close(write)
   progress = os.fdopen(read)
   print progress.read()
   os.wait()

rawDescription: Reading from fd#3 in python subprocess

description: Reading from fd#3 in python subprocess


code:
import re
lists = [
    [int(i) for i in match.split()]
    for match in re.findall(r'{(.*?)}', s)
]

print lists

rawDescription: String parsing with Python

description: String parsing with Python


code:
collect_tweet = {}

with open('time_short.txt') as file:
        for line in file.readlines():
                vals = line.rstrip().split()
                if vals[0] not in collect_tweet:
                        collect_tweet[vals[0]] = {}
                if vals[1] not in collect_tweet[vals[0]]:
                        collect_tweet[vals[0]][vals[1]] = {}
                if vals[2] not in collect_tweet[vals[0]][vals[1]]:
                        collect_tweet[vals[0]][vals[1]][vals[2]] = 1
                else:
                        collect_tweet[vals[0]][vals[1]][vals[2]] += 1

print collect_tweet

rawDescription: How to build a nested Dictionary type datastructure for a time series like data in python?

description: Build a nested Dictionary type datastructure for a time series like data in python


code:
def high_bit(num, lst=None):
    if lst == None:
        toplevel = True
        lst = []
    else:
        toplevel = False
    for i in range(0,100):
        if (num/(pow(2,i)))==1:
            lst.append(i)
            num = (num - (pow(2,i)))
            high_bit(num, lst)
    if toplevel:
        print lst

high_bit(85) # prints [6, 4, 2, 0]

rawDescription: How do you print the output this [6,4,2,0] in a single row rather that sequence

description: Print the output this [6,4,2,0] in a single row rather that sequence


code:
print s
print s.to_frame().T

rawDescription: How do I view a series into table form in Python

description: View a series into table form in Python


code:
class MyWidget(QtGui.QWidget):
      def keyPressEvent(self, event):
          if event.nativeScanCode() == 52:
              print "Pressed!"

rawDescription: How to get a the actual keyname from hardware key-number/scancode in pure python OR: How to bind the key left of the [1] to a shortcut in Qt

description: Get a the actual keyname from hardware key-number/scancode in pure python OR: How to bind the key left of the [1] to a shortcut in Qt


code:
import numpy as np
a1 = np.arange(1,11)
a2 = np.arange(101,111)
class Combiner():
    def __init__(self, *args):
        self.arrays = [arg for arg in args]
        self.lens = [len(arg) for arg in args]
    def __getitem__(self,i):
        if i >=0:
            shift = 0
            acc = 0
            for j,l in enumerate(self.lens):
                acc += l
                if i<acc:
                    return self.arrays[j][i-shift]
                shift += l
        if i<0:
            shift = 0
            acc = 0
            for j in xrange(len(self.lens)-1,-1,-1):
                l = self.lens[j]
                acc -= l
                if i>=acc:
                    return self.arrays[j][i+shift]
                shift += l

    def __setitem__(self,i,v):
        if i >=0:
            shift = 0
            acc = 0.
            for j,l in enumerate(self.lens):
                acc += l
                if i<acc:
                    self.arrays[j][i-shift] = v
                    return
                shift += l
        if i<0:
            shift = 0
            acc = 0
            for j in xrange(len(self.lens)-1,-1,-1):
                l = self.lens[j]
                acc -= l
                if i>=acc:
                    self.arrays[j][i+shift] = v
                    return
                shift += l

a3 = Combiner(a1,a2)
print a3[-10]
# 101
a3[-2] = 22222
a3[ 4] = 11111
print a1
#[    1     2     3     4 11111     6     7     8     9    10]
print a2
#[  101   102   103   104   105   106   107   108 22222   110]

rawDescription: Combine NumPy Arrays by Reference

description: Combine NumPy Arrays by Reference


code:
data = []
user_input = int(raw_input('How many Subject do you wish to add? : '))

for i in range (0, user_input):
    x = raw_input('Enter Subject: ')
    data.append(x)

while True:
    print ("would you like to add/remove any items in list")
    print ("1: yes")
    print ("2: remove")
    print ("3: exit")
    edit_input = int(raw_input('choose?: '))
    if edit_input == 1:
        edit_data = raw_input('Enter a new Subject: ')
        data.append(edit_data)
    elif edit_input == 2:
        edit_data = raw_input('Enter a Subject you want to remove: ')
        if edit_data in data:
            data.remove(edit_data)
        else:
            print('Subject not found!')
    else:
        # breaking off the loop here
        break

print data

rawDescription: How to write a function to edit raw input in an array?

description: Write a function to edit raw input in an array


code:
class SSSRequest(univ.SequenceOf):
    componentType = univ.Sequence()

class SSSRequestSequence(univ.Sequence):
    componentType = namedtype.NamedTypes(
        namedtype.NamedType('attributeType', univ.OctetString()),
    )

class SSS_CONTROL_REQUEST(LDAPControl):
    def __init__(self,controlType,criticality,controlValue=None,encodedControlValue=None):
        LDAPControl.__init__(self,controlType,criticality,controlValue,encodedControlValue)

    def encodeControlValue(self):
        sss = SSSRequest()

        for k in self.controlValue:
            Skey = SSSRequestSequence()
            Skey.setComponentByName('attributeType', k)
            sss.setComponentByPosition(0, Skey)
        return encoder.encode(sss)

    def decodeControlValue(self,encodedValue):
        sssr = decoder.decode(encodedValue)[0]
        rsp = SSSResponse()
        for n, v in enumerate(sssr):
            try:
                rsp.setComponentByPosition(n, int(v))
            except Exception, e:
                print str(e)
        if rsp.success:
            return True
        return rsp.error

if __name__ == '__main__':
    SSSREQUEST_OID = '1.2.840.113556.1.4.473'
    sss = SSS_CONTROL_REQUEST(SSSREQUEST_OID, False, ['cn'])
    srv = ldap.open('localhost')
    srv.simple_bind_s()
    id = srv.search_ext('ou=people,dc=example,dc=com', ldap.SCOPE_SUBTREE, filterstr='(objectClass=user)', serverctrls=[sss])
    print srv.result3(id)

rawDescription: Create a "sequence of sequence" ldap.controls.RequestControl object


code:
d = datetime.now(pytz.timezone('UTC'))   # get date in UTC format - you'll be getting it from the database
local = d.astimezone('Asia/Kolkata')
print local.strftime("%Y-%m-%d %H:%M:%S %z")

rawDescription: How to convert the data and time according to given UTC offset using Pytz in python & django?

description: Convert the data and time according to given UTC offset using Pytz in python & django


code:
import urllib

s = u"ó"
print urllib.quote(s.encode("utf-8"))

rawDescription: Python encoding characters with urllib.quote


rawDescription: Fetching HTTP GET variables in Python

description: Fetching HTTP GET variables in Python


code: print ', '.join(str(x) for x in list_of_ints)

rawDescription: Joining List has integer values with python


code:
class GenericComponent:
    def __init__(self, ID):
        self.ID = ID
    def addMethod(self, func):
        return setattr(self, func.__name__, types.MethodType(func, self))

def toString(target):
    print "toString: ", target
    attrs = vars(target)
    print ', '.join("%s: %s" % item for item in attrs.items())
ID = 'some ID'
obj = GenericComponent(ID)
obj.name = "some random name"
obj.addMethod(toString)
obj.toString()

rawDescription: How to have a dynamically added function access dynamically added properties

description: Have a dynamically added function access dynamically added properties


code:
from sklearn.svm import LinearSVC
from sklearn.datasets import load_iris
import numpy as np

iris = load_iris()
X, y = iris.data, iris.target
print X.shape

lsvc = LinearSVC(C=0.01, penalty="l1", dual=False)
X_new = lsvc.fit_transform(X, y)
print X_new.shape

print lsvc.coef_

newData = np.random.rand(100,4)
newData_X = lsvc.transform(newData)
print newData_X.shape

rawDescription: Identifying filtered features after feature selection with scikit learn


code:
import subprocess
task = subprocess.Popen("avconv -i video.mp4 2>&1 | grep Duration | cut -d ' ' -f 4 | sed -r 's/([^\.]*)\..*/\1/'", shell=True, stdout=subprocess.PIPE)
time = task.communicate()[0]
print time

rawDescription: Get Video-Duration with avconv via Python


code:
if opt_dict:
    for key, value in opt_dict.items():
        if "nonanswer" in key:
            print "nonanswer", value
        elif "answer" in key:
            print "answer", value
        else:
            raise Exception( "invalid key" )
else:
    print "empty dict"

rawDescription: Pattern matching using python

description: Pattern matching using python


code: print '.{0,3}'.join(re.escape(part) for part in s.split('?')) + '.*'

rawDescription: python+postgresql: Convert string literal to regex

description: Python+postgresql: Convert string literal to regex


code:
import Tkinter
root = Tkinter.Tk()
root.geometry("500x500")
def clicked(event):
    print "The user clicked at coordinates", event.x, event.y
root.bind("<Button-1>", clicked)
root.mainloop()

rawDescription: mouseclick gui to return row and column

description: Mouseclick gui to return row and column


code:
values = [1,1,1,2]
print [(x,values.count(x)) for x in set(values)]

rawDescription: Can Python's list comprehensions (ideally) do the equivalent of 'count(*)...group by...' in SQL?


rawDescription: Using re.sub() in python to replace html code


code:
import sys
import tty
tty.setcbreak(sys.stdin)
while True:
    print ord(sys.stdin.read(1))

rawDescription: How to obtain the keycodes in Python

description: Obtain the keycodes in Python


code:
class Instrument:

  def play(self):
    pass

class Guitar(Instrument):

  def play(self):
    print 'brau dau'

class Drum(Instrument):

  def play(self):
    print 'dum dum'

guitar = Guitar()
guitar.play()

drum = Drum()
drum.play()

rawDescription: Variable function calling in Python

description: Variable function calling in Python


code:
s =  "fish 14~ reel 14 rod B14"

import re

words = re.finditer('\S+', s)
has_digits = re.compile(r'\d').search
print [word.start() for word in words if has_digits(word.group())]
# [5, 14, 21]

rawDescription: Python Regex Search string for all substrings having one or more numbers


code:
import regex
s = """accounts
Bank
Credit
 good value
 money
Amount
Amount"""
m = regex.findall(r'(?s)(?<=Credit\s*\b).*?(?=Amount)', s)
for i in m:
    print i

rawDescription: print lines between 2 recurring words of text

description: Print lines between 2 recurring words of text


code:
import hashlib
# you're sampling a string so you need sample, not 'choice'
from random import sample
import multiprocessing
# use a thread to synchronize writing to file
import threading

# open up to 4 processes per cpu
processes_per_cpu = 4
processes = processes_per_cpu * multiprocessing.cpu_count()
print "will use %d processes" % processes
longitud = 8
valores = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
# check on smaller ranges to compare before trying your range... :-)
RANGE = 200000
def enc(string):
    m = hashlib.md5()
    m.update(string.encode('utf-8'))
    return m.hexdigest()

# we synchronize the results to be written using a queue shared by processes
q = multiprocessing.Manager().Queue()

# this is the single point where results are written to the file
# the file is opened ONCE (you open it on every iteration, that's bad)
def write_results():
    with open('datos.txt', 'w') as f:
        while True:
            msg = q.get()
            if msg == 'close':
                break;
            else:
                f.write(msg)

# this is the function each process uses to calculate a single result
def calc_one(i):
    s = ''.join(sample(valores, longitud))
    md = enc(s)
    q.put("%s %s\n" % (s, md))

# we start a process pool of workers to spread work and not rely on
# a single cpu
pool = multiprocessing.Pool(processes=processes)

# this is the thread that will write the results coming from
# other processes using the queue, so it's execution target is write_results
t = threading.Thread(target=write_results)
t.start()
# we use 'map_async' to not block ourselves, this is redundant here,
# but it's best practice to use this when you don't HAVE to block ('pool.map')
pool.map_async(calc_one, xrange(RANGE))
# wait for completion
pool.close()
pool.join()
# tell result-writing thread to stop
q.put('close')
t.join()

rawDescription: Looping Efficiency in Python

description: Looping Efficiency in Python


code:
import re
string = "blabla Oxygen:      10.10 blabla"
regex_oxygen = re.compile('''Oxygen:\W+([0-9.]*)''')
result = re.findall(regex_oxygen,string)
print result

rawDescription: regular expression search in python

description: Regular expression search in python


code:
p.add_option("--from", dest="foo")

print options.foo

rawDescription: Using "from" as a script argument in Python


code:
input_string = "Ask not what your country can do for you ask what you can do for your country"

# Split sentence into words
words = input_string.split(" ")

wordMap = {}
indices = [None]*len(words)
for idx, word in enumerate(words):
    word = word.lower()
    if word not in wordMap:
        wordMap[word] = idx

    indices[idx] = wordMap[word]+1 # using +1 here to get a one-based index

print indices
# prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 3, 9, 6, 7, 8, 4, 5]

rawDescription: Python controlled assessment - Task 2

description: Python controlled assessment - Task 2


code:
from thread import start_new_thread as thread
from time import sleep
# Get only one character from stdin without echoing it to stdout
import termios
import fcntl
import sys
import os
fd = sys.stdin.fileno()
oldterm, oldflags = None, None

def prepareterm ():
    """Turn off echoing"""
    global oldterm, oldflags
    if oldterm!=None and oldflags!=None: return
    oldterm = termios.tcgetattr(fd)
    newattr = oldterm[:] # Copy of attributes to change
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)
    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

def restoreterm ():
    """Restore terminal to its previous state"""
    global oldterm, oldflags
    if oldterm==None and oldflags==None: return
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
    oldterm, oldflags = None, None

def getchar():
    """Get character from stdin"""
    prepareterm()
    while 1:
        try:
            c = sys.stdin.read(1)
            break
        except IOError:
            try: sleep(0.001)
            except: restoreterm(); raise KeyboardInterrupt
    restoreterm()
    return c

def control ():
    """Waits for keypress"""
    global running, done
    while running:
        c = getchar().lower()
        print "Keypress:", c
        if c=="q": print "Quitting!"; running = 0; break
    done += 1

def work ():
    """Does the server-client part"""
    global done
    while running:
        # Do your stuff here!!!
        # Just to illustrate:
        print "I am protending to work!\nPress Q to kill me!"
        sleep(1)
    print "I am done!\nExiting . . ."
    done += 1

# Just to feel better
import atexit
atexit.register(restoreterm)

# Start the program
running = 1
done = 0
thread(work, ())
thread(control, ())
# Block the program not to close when threads detach from the main one:
while running:
    try: sleep(0.2)
    except: running = 0
# Wait for both threads to finish:
while done!=2:
    try: sleep(0.001)
    except: pass # Ignore KeyboardInterrupt
restoreterm() # Just in case!

rawDescription: Using Python, how can I implement running a loop in the foreground while waiting in the background for a key-press?


code:
import wmi
comp = wmi.WMI()

for i in comp.Win32_ComputerSystem():
   print i.TotalPhysicalMemory, "bytes of physical memory"

for os in comp.Win32_OperatingSystem():
   print os.FreePhysicalMemory, "bytes of available memory"

rawDescription: Get memory usage of computer in Windows with Python


code:
import re
lines=[]
for l in f_dat:
    if l and l[0]!='#':
        lines.append([float(i) for i in re.findall('[0-9.]+',l)])
print lines

rawDescription: Read list written in different ways from file


code:
dirFile = open('listac.txt','r')
pathFile = open('paths.txt','r')
paths = pathFile.readlines()
dirs = dirFile.readlines()

matches = open('temp.txt','w')

for pline in paths:
    p = pline.rstrip('\n').split(".")[0].replace(" ", "")
    for dline in dirs:
        dd = dline.rstrip('\n').replace(" ", "")
        #print p.lower()
        #print dd.lower()
        if p.lower() == dd.lower():
            print "SUCCESS\n"
            matches.write(str(p).lower() + '\n')

rawDescription: Can't compare strings in Python

description: Can't compare strings in Python


code:
import numpy as np

a = np.array([
    [10, -1],
    [ 3,  1],
    [ 5, -1],
    [ 7,  1]])

mask = (a[:, 1] == -1)

arg = np.argmin(a[mask][:, 0])
result = np.arange(a.shape[0])[mask][arg]
print result

rawDescription: Numpy: get index of smallest value based on conditions


code:
l = ["1 12","3 12","2 12"] # space separated
n = [x.split()[0] for x in l]
print sorted(n)

rawDescription: How to sort out first row in a list

description: Sort out first row in a list


code:
d = s.find('div', {'class':'content'}).div

def all_text_after(element):
    for item in element.nextSiblingGenerator():
        if not item:
            continue
        elif hasattr(item, 'contents'):
            for c in item.contents:
                yield c
        else:
            yield item

text_parts = list(all_text_after(d))
# -> [u'\n    19', u'th', u' ~ 21', u'st', u' Apr 2013\n']

print ''.join(text_parts)
# ->     19th ~ 21st Apr 2013

rawDescription: Get String from <div> without tag

description: Get String from <div> without tag


code:
my_pattern = '(?=(a.*?b.*?c))'
my_regex = re.compile(my_pattern, re.DOTALL|re.IGNORECASE)
matches = my_regex.findall(string)
print min(matches, key=len)

rawDescription: How do I find the shortest overlapping match using regular expressions?

description: Find the shortest overlapping match using regular expressions


code:
from bs4 import BeautifulSoup

html_doc = '''<input type="hidden"
                     name="licence[_csrf_token]"
                     value="SOME RANDOM CHECKSUM"
                     id="licence__csrf_token" />'''

soup = BeautifulSoup(html_doc)
print soup.input['value']

rawDescription: Python Parse single line of XML

description: Python Parse single line of XML


code:
import datetime
import urllib
import string
import random
import os
avatar = urlopen(url)

try:
    profile = Profile.objects.get(user=user)
except:
    profile = Profile.objects.create(user=user)

print profile
print "sdfffffffffffffffffffff"
filename_charset = string.ascii_letters + string.digits
filename_length = 10
file_save_dir = 'media/mugshots/'

filename = ''.join(random.choice(filename_charset)
                   for s in range(filename_length))

urllib.urlretrieve (url, os.path.join(file_save_dir, filename + '.png'))

profile.mugshot = 'mugshots/'+filename + '.png'

profile.save()

rawDescription: django-social-auth : how to get the profile pic of facebook and save it in media/mudshots/ folder

description: Django-social-auth : how to get the profile pic of facebook and save it in media/mudshots/ folder


code:
for dir, subdir, files in os.walk(path):
    for file in files:
        print os.path.join(dir, file)

rawDescription: In python, how to get the path to all the files in a directory, including files in subdirectories, but excluding path to subdirectories


code:
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
import psycopg2
import psycopg2.extensions
import os
from tornado.options import define, options

define("port", default=8000, help="run on the given port", type=int)

io_loop = tornado.ioloop.IOLoop.instance()

connection = psycopg2.connect('dbname=mydb user=myusername password=mypassword')
connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

# This is a global variable to store all connected clients
websockets = []

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html')

class ReceivedDataHandler(tornado.web.RequestHandler):
    def post(self):
        cursor = connection.cursor()

        name=self.get_argument('name', 'No name info received')
        email = self.get_argument('email', 'No email info received')
        self.write("New person with name %s and email %s" %(name, email))

        cursor.execute("INSERT INTO mydata VALUES (%s, %s)" %(name, email))
        cursor.execute("NOTIFY test_channel;")

class EchoHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        self.write_message('connected!')
    def on_message(self, message):
        self.write_message("Received info about new person: "+message)
    def on_close(self):
        print 'connection closed'

def listen():
    cursor = connection.cursor()
    cursor.execute("LISTEN test_channel;")

def receive(fd, events):
    """Receive a notify message from channel I listen."""
    state = connection.poll()
    if state == psycopg2.extensions.POLL_OK:
        if connection.notifies:
            notify = connection.notifies.pop()
            for ws in websockets:
                   ws.write_message("my message")
io_loop.add_handler(connection.fileno(), receive, io_loop.WRITE)

if __name__=="__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        handlers=[
            (r'/', IndexHandler),
            (r'/person-info', ReceivedDataHandler),
            (r'/websocket', EchoHandler)
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=True
    )
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    listen()
    io_loop.start()

rawDescription: Send message from server to client after received notification (Tornado+websockets)


code:
import subprocess

ps = subprocess.Popen('ps -ef', shell=True, stdout=subprocess.PIPE)
print ps.stdout.readlines()

rawDescription: How do I show a list of processes for the current user using python?

description: Show a list of processes for the current user using python


code:
import requests
from bs4 import BeautifulSoup

s = requests.session()
s.headers.update({"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36"})

URL = "https://www.google.dk/search"
images = []

def get_images(query, start):
    screen_width = 1920
    screen_height = 1080
    params = {
        "q": query,
        "sa": "X",
        "biw": screen_width,
        "bih": screen_height,
        "tbm": "isch",
        "ijn": start/100,
        "start": start,
        #"ei": "" - This seems like a unique ID, you might want to use it to avoid getting banned. But you probably still are.
    }

    request = s.get(URL, params=params)
    bs = BeautifulSoup(request.text)

    for img in bs.findAll("div", {"class": "rg_di"}):
        images.append(img.find("img").attrs['data-src'])

#Will get 400 images.
for x in range(0, 5):
    get_images("cats", x*100)

for x in images:
    print x

rawDescription: Can I expand Google Image seach screen by scrolling down programatically?

description: Expand Google Image seach screen by scrolling down programatically


code:
words_list=["hi", "my","name","is"]

subs2=[]
addpair1=input("Enter a symbol you would like to replace:")
addpair2=input("What letter would you like to replace it with:")

for word in words_list:
    tempword = (word)
    tempword = tempword.replace('#','A')
    tempword = tempword.replace('*', 'M')
    tempword = tempword.replace('%', 'N')
    tempword=tempword.replace(addpair1,addpair2)
    print(tempword)
    subs2.append(tempword)
print subs2

#Enter a symbol you would like to replace:"i"
#What letter would you like to replace it with:"j"
#hj
#my
#name
#js
#['hj', 'my', 'name', 'js']

rawDescription: How to reprint codes after a substituiton has been made - python 3.2

description: Reprint codes after a substituiton has been made - python 3.2


code:
d = { 'something': 'completely',
      'something2': 'different' }

def repl(m):
    s = m.group(1)
    return d[s]

s = "/(?P<something>\w+)/whatever/(?P<something2>\w+)"
p = re.compile(r'\(\?P<(.*?)>\\w\+\)')

print p.sub(repl, s)

rawDescription: How to compose string from regex pattern with named groups and datadict in python?

description: Compose string from regex pattern with named groups and datadict in python


code:
while True:
    inp = raw_input("Enter a value between 1 and 10 million: ")

    if not inp.isdigit():
        print "Must be an integer value!"
        continue # each of these continue statements acts like a "failed, try again"

    inp = int(inp)

    if inp < 1:
        print "Must be higher than 1"
        continue # same for this one

    if inp > 10000000:
        print "Must be less than 10.000.000"
        continue # and this one

    # execute the rest of the code

rawDescription: Check for a string in if-statement

description: Check for a string in if-statement


code:
s = '<img src="Controls/RiverLevels/ChartImage.jpg?Id=471&ChartType=Histogram" id="StationDetails_Chart1_chartImage" alt="Current river level" />'

from bs4 import BeautifulSoup
import re
from urlparse import urlsplit, parse_qs

soup = BeautifulSoup(s)
# find the node with a src starting with Controls
node = soup.find('img',{'src': re.compile("^Controls")})
# Break up the url in the src attribute
url_split = urlsplit(node['src'])
# Parse out the query parameter from the url
qs = parse_qs(url_split.query)
# Display the value for `Id`
print qs['Id'][0]

rawDescription: Beautiful soup - how to extract a string from an object


code:
import wx

def ask(parent=None, message='', default_value=''):
    dlg = wx.TextEntryDialog(parent, message, defaultValue=default_value)
    dlg.ShowModal()
    result = dlg.GetValue()
    dlg.Destroy()
    return result

# Initialize wx App
app = wx.App()
app.MainLoop()

# Call Dialog
x = ask(message = 'What is your name?')
print 'Your name was', x

rawDescription: Using wxPython to get input from user

description: Using wxPython to get input from user