code:
from __future__ import print_function
import random as rand

def ex_game():
    print('Instructions:','\n','Your job is to try to figure out a number of problems by your choosing and get the progress bar all GREEN, YELLOW means its there, but wrong spot, RED means its not there and there are no more of that left. After a light turns GREEN you do not have to get it right again. Trust me its easy.(Press enter to get started)')
    raw_input()
    ex_secret(int(raw_input('Number of items you would like to TRY to solve(WARNING: GAME GETS HARDER THE LARGER THE NUMBER YOU CHOOSE):')),int(raw_input('At what level would you like to play at.(1-5)')))
def ex_guess(l_sec,tries,cheat,number_items,level):
    #This is the guess choice I separated it so that I could rerun it as pleased, to put a special code in, and show the progression table
    guess_ex = []
    colors = ['yellow', 'blue', 'black', 'green', 'red']

    if level >= 2:
        colors.append('white')
    if level >= 3:
        colors.append('orange')
    if level >= 4:
        colors.append('purple')
    if level >= 5:
        colors.append('brown')

    for loop in range(number_items):
         append_guess = 'What do you beleive the solution is?(One at a time | choices: ' + str(colors) + '):'
         input = raw_input(append_guess).lower()

         if input == 'quit':
            return 'quit'
         guess_ex.append(input)

    return guess_ex
def ex_secret(number_items,level):
    secret_ex = []
    optionalColors = []
    if level >= 2:
        optionalColors.append('white')
    if level >= 3:
        optionalColors.append('orange')
    if level >= 4:
        optionalColors.append('purple')
    if level >= 5:
        optionalColors.append('brown')

    for loop in range(number_items):
        secret_ex.append(rand.choice(['yellow','blue','black','green','red']+optionalColors))

    report(secret_ex,[],0,False,number_items,level,False)
def report(secret,progress,tries,cheat,number_items,level,correct):
    #The "game"
    safe_secret = []
    for record in secret:
        safe_secret.append(record)
    if correct == True:
        print('YOU WON!')
        end = True
    if tries > 0 and cheat == False or tries > 4 and cheat:
        print(progress)
        progress = []
    while not correct:
        if tries == 5 and not correct:
            print('YOU LOST?!?!')
            raw_input('Thanks for Playing!')
            return
        guess = ex_guess(len(secret),tries,cheat,number_items,level)
        super_secret = 'up up down down left right left right b a start'
        if 'give' in guess:
            tries = 4
        if super_secret in guess and not cheat:
            print('The deal has been made. Now make your "new" choices.')
            cheat = True
            tries += 6
            guess = ex_guess(len(secret),progress,tries,cheat,number_items,level)
        elif super_secret in guess and cheat:
            print('I said the deal was made now go make your new choices and leave me alone you prick.')
            guess = ex_guess(len(secret),progress,tries,cheat,number_items,level)
        elif 'stop_cheat' in guess and cheat:
            if tries > 8:
                return 'YOU LOST, thank you for admitting to cheating though.'
            else:
                cheat = False
                tries -= 6
        if guess == 'quit':
            raw_input('Thanks for Playing!')
            return
        list_counter_in = 0
        list_counter_out = 0
        list_counter_incor = 0
        while list_counter_in <= number_items - 1:
            if guess[list_counter_in] == secret[list_counter_in] and '_g' not in guess[list_counter_in]:
                secret[list_counter_in] += ('_g')
                guess[list_counter_in] += ('_g')
            list_counter_in += 1
        while list_counter_out <= number_items - 1:
            if guess[list_counter_out] in secret and '_g' not in guess[list_counter_out]:
                secret_yellow_check = secret[secret.index(guess[list_counter_out])]
                if '_y' not in secret_yellow_check:
                    secret[secret.index(guess[list_counter_out])] += '_y'
                    guess[list_counter_out] += '_y'
            list_counter_out += 1
        while list_counter_incor <= number_items - 1:
            if '_g' not in guess[list_counter_incor] and '_y' not in guess[list_counter_incor]:
                guess[list_counter_incor] += '_r'
            list_counter_incor += 1
        for check_status in guess:
            if '_g' in check_status:
                progress.append('GREEN')
            if '_y' in check_status:
                progress.append('YELLOW')
            if '_r' in check_status:
                progress.append('RED')
        if 'RED' not in progress and 'YELLOW' not in progress:
            correct = True
        if 'RED' in progress or 'YELLOW' in progress:
            tries +=1
            print('Not quite right...Lets try again!')
ex_game()

rawDescription: Python 2.7, Having problems with having iteration


code:
g = testGen([1,2],4)
g.next()
g.next()
g.next()
g.next()
g.next()

rawDescription: Scope of Python Recursive Generators

description: Scope of Python Recursive Generators


code:
port_list = []
if struct.contents.ports:
  i = 0
  while True:
    port_ptr = struct.contents.ports[i]
    # NULL pointer terminates the array
    if port_ptr:
      port_struct = port_ptr.contents
      port_list.append(port_struct.name)
      i += 1
    else:
      break

rawDescription: Convert C array of pointers to Python array of structures


code:
class EventLoop(object):
    def __init__(self):
        self.exit = False

    def run(self):
        while not self.exit:
            do_something()

    def handler(self):
        self.exit = True

# It's up to you if you want an EventLoop instance
# as an argument, or just a reference to the instance's
# handler method.
def setup_handler(event_loop):
    signal.signal(signal.SIGTERM, event_loop.handler)

if __name__ == '__main__':
   loop = EventLoop()
   setup_handler(loop)
   loop.run()

rawDescription: What is Pythonic way to share state inside one module?


code:
class MessageUpdatesHandler(BaseHandler):
    @tornado.web.authenticated
    @gen.coroutine
    def post(self):
        cursor = self.get_argument("cursor", None)
        messages = yield gen.Task(global_message_buffer.wait_for_messages, cursor=cursor)

        if self.request.connection.stream.closed():
            return

        self.finish(dict(messages=messages))

rawDescription: Tornado Chatdemo to work with Coroutines


rawDescription: Django: manually create imagefield in model from existing file on server


code:
simplestack = list()
simplestack.append(1)  # [1]
simplestack.append(2)  # [1, 2]
top = simplestack.pop()  # 2

rawDescription: Why does the 'pop' method exist?

description: Why does the 'pop' method exist


rawDescription: Shorter version for a series of list comprehension instructions


code: jsonData = [{k: d[k] for k in (d.keys() & {'b', 'c'})} for d in jsonData if d['c'] != '3c']

rawDescription: Double filter for a list of dictionaries in Python


rawDescription: numpy.oldnumeric.float32 overflowing for small numbers (1e39 ---> inf) python

description: Numpy.oldnumeric.float32 overflowing for small numbers (1e39 ---> inf) python


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent, borderwidth=1, relief="sunken")
        b = tk.Button(self, text="search", command=self.add_one)

        self.lb = tk.Listbox(self, borderwidth=0)
        self.lb.pack(fill="both", expand=True)
        vsb = tk.Scrollbar(self, orient="vertical", command=self.lb.yview)
        hsb = tk.Scrollbar(self, orient="horizontal", command=self.lb.xview)
        self.lb.configure(yscrollcommand=vsb.set, xscrollcommand=hsb.set)

        b.grid(row=0, column=0, columnspan=2)
        vsb.grid(row=1, column=1, sticky="ns")
        self.lb.grid(row=1, column=0, sticky="nsew")
        hsb.grid(row=2, column=0, sticky="ew")
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(0, weight=1)

    def add_one(self):
        self.lb.insert("end", "hello world!")

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Tkinter window changing size becuase items in listbox


code:
# class attributes:

class Cluster(object):
    members = {} # this will be shared by all instances

# solution:

class Cluster(object):
    def __init__(self):
        self.members = {} # this will be per instance

# default mutable argument:

class Cluster(object):
    def __init__(self, members={}):
        # this one is well known gotcha:
        # the default for the `members` arg is eval'd only once
        # so all instances created without an explicit
        # `members` arg will share the same `members` dict
        self.members = members

# solution:

class Cluster(object):
    def __init__(self, members=None):
        if members is None:
            members = {}
        self.members = members

rawDescription: Adding element to dictionary inside object inside dictionary


code:
class TransferableImage(Transferable) :

     def __init__(self, image) :
             if not isinstance(image, Image) :
                      raise IllegalArgumentException("Parameter must be of type java.awt.Image")
             self.image = image

     def getTransferData(self, flavor) :
             if not isinstance(flavor, DataFlavor) :
                      raise IllegalArgumentException("Parameter must be of type java.awt.datatransfer.DataFlavor")
             if not flavor.equals(DataFlavor.imageFlavor) :
                      raise UnsupportedFlavorException(flavor)
             return self.image

     def getTransferDataFlavors(self) :
             return [DataFlavor.imageFlavor];

     def isDataFlavorSupported(self, flavor) :
             if not isinstance(flavor, DataFlavor) :
                      raise IllegalArgumentException("Parameter must be of type java.awt.datatransfer.DataFlavor")
             return flavor in getTransferFlavors()

class ClipboardImage(ClipboardOwner) :

     def __init__(self) :
             robot = Robot()
             toolkit = Toolkit.getDefaultToolkit()
             screenSize = toolkit.getScreenSize()
             screen = Rectangle(screenSize)
             image = robot.createScreenCapture(screen)
             trans = TransferableImage(image)
             clipboard = toolkit.getSystemClipboard()
             clipboard.setContents(trans, self)

     def lostOwnership(self, clip, trans) :
             print("Lost Clipboard Ownership")

ci = ClipboardImage()

rawDescription: Translate Java code into Jython code

description: Translate Java code into Jython code


code:
subprocess.call([path_to_vlc,
                 mms_url,
                 '--sout',
                 'file/avi:'+target_file,
                 'vlc://quit'])

rawDescription: python wmv stream download

description: Python wmv stream download


code: movie += data

rawDescription: How do I work with large data streams in python?

description: Work with large data streams in python


code:
self.client = Client()
self.user = User.objects.create_user('test_user', password='test_user')
self.client.login(username='test_user', password='test_user')

rawDescription: Django tests returning login redirect 302, even though user is logged in


code:
d = shelve.open(filename) # open -- file may get suffix added by low-level
                          # library
# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.
d.close()       # close it

rawDescription: Shelve, Python, updating a dictionary

description: Shelve, Python, updating a dictionary


code:
class SaveQueryPage(webapp2.RequestHandler):
  def post(self):
    user = users.get_current_user()
    user_nickname = user.nickname()
    user_email = user.email()

    query_name = self.request.get('queryName')
    query_description = self.request.get('queryDescription')

    query_collab = self.request.get('queryCollab')
    logging.info('Data read for query_collab is %s', query_collab)

    query_collab_re = re.split(r'\s*[,;]\s*', query_collab.strip())
    logging.info('Data read for query_collab_re is %s', query_collab_re)

    query_collab_decode = []
    for item in query_collab_re:
      item = str(item)
      query_collab_decode.append(item)
    logging.info('Data read for query_collab_decode is %s', query_collab_decode)

    query_collab_decode.append(user_nickname)
    logging.info('Data read for query_collab_append is %s', query_collab_decode)

    query_collab_filter = filter(None, query_collab_decode)
    logging.info('Data read for query_collab_filter is %s', query_collab_filter)

    query_value = self.request.get('queryValue') # query_value
    date_created = datetime.today()
    date_lastupdated = datetime.today()
    active_flag = "true"
    random_id = random.randint(1000000000000, 9999999999999)
    unique_query_id = user_nickname + "_" + str(random_id)

    conn = rdbms.connect(instance=_INSTANCE_NAME, database='userPrefs')
    cursor = conn.cursor()
    cursor.execute('INSERT INTO queries (userNickname, queryName, queryDescription, queryValue, dateCreated, dateLastUpdated, activeFlag, uniqueId) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', (user_nickname, query_name, query_description, query_value, date_created, date_lastupdated, active_flag, unique_query_id))
    conn.commit()

    try:
      for item in query_collab_filter:
        cursor = conn.cursor()
        cursor.execute('INSERT INTO collaborators (uniqueId, userNickname) VALUES (%s, %s)', (unique_query_id, item))
        conn.commit()
    except:
      logging.error('There was an error inserting the values into the collaborators table. query_collaborators =' + str(query_collaborators))

    conn.close()

rawDescription: Inserting list items into database as separate entries


code:
import functools # python3 compatibility (for reduce function)

# unsorted - see 3,4 are swaped!
masterVars = ["1", "2", "4", "3", "5", "6", "7", "8", "9", "10"]

input_dict=dict(headerGroup1 = ["1", "2", "3", "4", "5"],headerGroup2 = ["6", "7", "8", "9", "10"],headerGroup3 = ["1", "2", "3", "4", "5"])

# used builtins sorted function for sorting
new_master_file=[' '.join(j[0])+' '+j[1] for j in [functools.reduce(lambda a,b:(i in input_dict[b] and a[0]+[b] or a[0],i),input_dict,[[],i]) for i in sorted(masterVars,key=int)]]

for i in new_master_file:
    print (i)

rawDescription: Python append to label from multiple lists


code:
#!/usr/bin/env python

import pip
import imp

def install_and_load(package):
    pip.main(['install', package])

    path = '/usr/local/lib/python2.7/dist-packages'
    if path not in sys.path:
        sys.path.append(path)

    f, fname, desc = imp.find_module(package)
    return imp.load(package, f, fname, desc)

if __name__ == "__main__":
    try:
        import pexpect
    except:
        pexpect = install_and_load('pexpect')

    # More code...

rawDescription: How to install and import Python modules at runtime?

description: Install and import Python modules at runtime


code:
datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds=1e16)
_.isoformat()

rawDescription: Convert Chrome history date/time stamp to readable format


code:
average_diff = ts.groupby([ts.index.month, ts.index.day]).apply(
    lambda g: g - g.mean()
)

rawDescription: Difference between multi year timeseries and it's 'standard year'


code:
from django.views.generic.list_detail import object_list

url('^URL_HERE/(?P<object_id>\d+)$', lambda request, *a, **k: object_detail(request, *a,
                       queryset=MyModel.objects.filter(user=request.user),
                       template="myapp/mytmplate.html", **k) )

rawDescription: How to access HttpRequest from urls.py in Django 1.2

description: Access HttpRequest from urls.py in Django 1.2


code:
string = 'bcdaba'
string.replace('a', '', 1)

rawDescription: Remove only one character from a string which has that character repeated more times


code: zipped.sort(key = lambda t: t[1])

rawDescription: How do I sort a zipped list in Python?

description: Sort a zipped list in Python


code:
import re
bytes = bytearray('\x01\x02\x03\x04\x05')
re.search(b'\x02.\x04',bytes).group(0)

rawDescription: find bytearray in bytearray with wildcards

description: Find bytearray in bytearray with wildcards


code: [u['word'] for u in x['tokens'] for x in d]

rawDescription: Extracting parts of JSON from json.loads list in python


code:
import re
with open('Reutput.csv') as reuf, open('Put.csv', 'w') as putuf:
    text = str(reuf.read())
    d = re.findall('".*?Direc',text,re.DOTALL|re.MULTILINE)
    if d is not None:
        for elements in d:
            elements = str(elements)
            if not 'https' in elements:
                    s = re.compile('".*?Direc',re.DOTALL)
                    replace = re.sub(s,'",Direc',text)
    h = re.findall('".*?https',text,re.DOTALL|re.MULTILINE)
    if h is not None:
        for elements in h:
            if not 'Direc' in elements:
                s = re.compile('".*?https',re.DOTALL)
                replace = re.sub(s,'"\nhttps',text)
        replace = str(replace)
        putuf.write(replace)

rawDescription: Python for re.match re.sub

description: Python for re.match re.sub


code:
class Book(Base):
    __tablename__ = 'books'
    title = Column(String(20), primary_key=True)
    author_firstName = Column(String(20))
    author_lastName = Column(String(20))
    __table_args__ = (ForeignKeyConstraint([author_firstName, author_lastName],
                                           [Author.firstName, Author.lastName]),
                      {})

rawDescription: Relations on composite keys using sqlalchemy


code:
def LoadTimeFiles(i):
   from pandas import read_csv
   import h5py as h5
   dataFile = h5.File('data.h5','r+')
   rFile = dataFile['files'][i]
   data = dataFile['data']
   lheader = len(data[0,:,0])
   numPts = len(data[0,0,:])
   allData = read_csv(rFile,delimiter="\t",skiprows=2,header=None,low_memory=False).T
   for j in range(0,lheader):
      data[i,j,:] = allData[0][j*numPts:(j+1)*numPts]
   del allData
   dataFile.close()

def LoadTimeFilesParallel(np):
   from multiprocessing import Pool, freeze_support
   import h5py as h5
   files = h5.File('data.h5','r')
   numFiles = len(files['data'][:,0,0])
   files.close()
   pool = Pool(np)
   freeze_support
   pool.map(LoadTimeFiles,range(numFiles))

if __name__ == '__main__':
   np = 5
   LoadTimeFilesParallel(np)

rawDescription: Python multiprocessing with arrays and multiple arguments


code:
username = 'jimjam@gmail.com'
password = 'bwdfsdfsafadlhsw'
sheetname = "Reassessment Requesttemp"

client = gspread.login(username, password)
spreadsheet = client.open(sheetname)

worksheet = spreadsheet.sheet1
contents = worksheet.get_all_values()

rawDescription: Using googlecl inside Python script to d/l Google doc


code:
def start(seconds):
    import time, _thread
    def stop(seconds):
        time.sleep(seconds)
        _thread.interrupt_main()
    total = 0
    _thread.start_new_thread(stop, (seconds,))
    try:
        while True:
            total += 1
    except:
        return total

if __name__ == '__main__':
    print('Testing the CPU speed ...')
    print('Relative speed:', start(60))

rawDescription: Can this loop be sped up in pure Python?

description: Can this loop be sped up in pure Python


code:
import numpy as np
from itertools import groupby
x = np.array([10., 20., np.nan, 40., 50., np.nan, np.nan, np.nan, 10.,0.,-10.])
y = np.zeros_like(x, dtype=int)
y[np.where(np.isnan(x))] = 1 # Locate where the array is nan
y
z = []
for a, b in groupby(y, lambda x: x == 0):
    if a: # Where the value is 0, simply append to the list
        z.extend(list(b))
    else: # Where the value is one, replace 1 with the number of sequential 1's
        l = len(list(b))
        z.extend([l]*l)
z

rawDescription: identifying gap size in 1D numpy array

description: Identifying gap size in 1D numpy array


code:
import glob
resultsdir = "blah"

files = sorted(glob.glob(resultsdir+'/*.csv'))
while len(files) >= 3:
     file1 = open(files.pop(0))
     file2 = open(files.pop(0))
     file3 = open(files.pop(0))
     # Do something
# if the number of files can't be divided by 3 do something
# with the 1 or 2 files which are left

rawDescription: Python: loop through several csv files

description: Python: loop through several csv files


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import EllipseCollection

x, y = 1500 * np.random.rand(2, 100)
size = 50 + 10 * np.random.randn(100)
color = np.random.rand(100)
cmap = plt.cm.hsv

fig, ax = plt.subplots(1, 2, figsize=(16, 6),
                       sharex=True, sharey=True)
ax[0].scatter(x, y, s=size, c=color, cmap=cmap)

offsets = list(zip(x, y))
ax[1].add_collection(EllipseCollection(widths=size, heights=size, angles=0, units='xy',
                                       facecolors=plt.cm.hsv(color),
                                       offsets=offsets, transOffset=ax[1].transData))
ax[1].axis('equal') # set aspect ratio to equal
ax[1].axis([-400, 1800, -200, 1600])

rawDescription: Correct Sizing of Markers In Scatter Plot to a Radius R in Matplotlib


code:
funcs = dict(
    func1=func1,
    func2=func2,
    func3=func3
)

funcs[funcName](p1, p2, p3)

rawDescription: Can I conditionally change which function I'm calling?

description: Conditionally change which function I'm calling


code:
from collections import Counter
counts = Counter(time[:2]+'00' for time in times)

rawDescription: count occurrences of timeframes in a list

description: Count occurrences of timeframes in a list


code:
with open("Input.txt", "r") as infile, open("Output.txt", "w") as outfile:
    for line in infile:
        outfile.write(line.split("<_|_>")[0])

rawDescription: Python - reading, parsing and writing back to a file


code:
def __init__(self, argument='' ,*a, **kw):
    super(MySpider, self).__init__(*a, **kw)
    # set your pattern here to what you need it
    MySpider.rules = rules = [ Rule(LinkExtractor(allow=[pattern] , restrict_xpaths=('//*[@id = "imgholder"]/a', )), callback='parse_items', follow=True), ]
    # now it is time to compile the new rules:
    super(MySpider, self)._compile_rules()

rawDescription: scrapy recursive crawl upto a user defined page

description: Scrapy recursive crawl upto a user defined page


code:
import random
random.sample(zip(list_a,list_b), 10)

rawDescription: randomly selecting items from an array python

description: Randomly selecting items from an array python


code:
import HTMLParser
s= HTMLParser.HTMLParser().unescape(s)

rawDescription: Remove html formating ">" from text file using Python csv.reader


code:
import asyncio

async def f(n):
    return n

async def main():
    (done, pending) = await asyncio.wait([f(1), f(2), f(3)], return_when=asyncio.FIRST_COMPLETED)
    print(done)     # prints set of 3 futures
    print(pending)  # prints empty set

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

rawDescription: Is asyncio.wait order guaranteed?

description: Is asyncio.wait order guaranteed


code:
# download to temporary directory
(temp_path, _headers) = urllib.urlretrieve(url)

# move to final directory, preserving file name
dest_path = os.path.join('temp', os.path.basename(temp_path))
shutil.move(temp_path, dest_path)

mylog.info('%s: done', url)
return dest_path

rawDescription: Methods for downloading multiple large files using python on a limited network


code:
import csv

with open(outputfilename, 'wb') as outfile:
    writer = csv.writer(outfile)
    # to get tabs use csv.writer(outfile, dialect='excel-tab')
    writer.writerows(your_dictionary.iteritems())

rawDescription: Python outputting a dictionary into excel file


code:
im=Image.open("file.png")
draw  = ImageDraw.Draw(im)
font=ImageFont.truetype("/usr/share/fonts/gnu-free/FreeSerifBold.ttf",12)
by = font.getsize("S")[1]
col = [240,480]
px = []

for y in range(0,im.size[1],by+5):
    for x in col:
        draw.text((x,y),"QQ",font=font,fill=0)
im=im.resize((im.size[0]*2,im.size[1]*2))
im.save("res-file.png")
im.show()

rawDescription: tesseract reading values from a table

description: Tesseract reading values from a table


code: values_list('id', flat=True)

rawDescription: How to get the Ids from a django model

description: Get the Ids from a django model


code:
SPIDER_MIDDLEWARES = {
'scrapy.contrib.spidermiddleware.referer.RefererMiddleware': True,
}

rawDescription: How to add Headers to Scrapy CrawlSpider Requests?

description: Add Headers to Scrapy CrawlSpider Requests


code:
import collections

def friendslike(network,user):
    games = collections.Counter()
    for friend in get_connections(network, user):
        games.update(get_games_liked(network, friend))
    return [game for game, count in games.items() if count >= 2]

rawDescription: Python: Returning items common to two or more lists


rawDescription: python url fetch help - regex

description: Python url fetch help - regex


code:
osuser = "nodermatt"
ospassword = "feelfree"
ostenant = "4"

d = {"auth":
        {"passwordCredentials": {"username": osuser, "password": ospassword},
         "tenantId": ostenant}}
params = json.dumps(d)

rawDescription: Python variable value in quotes

description: Python variable value in quotes


code: ws_temp.Range("A5:AF16").Copy(ws_pwr.Range("A%s:AF%s" % (chart_first_row, chart_last_row)))

rawDescription: Python copying one work sheet to another in excel


code:
import optparse

parser = optparse.OptionParser()
parser.add_option("-f", "--filename", metavar="FILE", dest="input_file", action="append")
options, args = parser.parse_args()
if options.input_file:
    args.extend(options.input_file)

for arg in args:
    process_file(arg)

rawDescription: optparse: No option string

description: Optparse: No option string


code:
contact_object = Contact.query \
    .filter(Contact.user_id == user_id) \
    .filter(Contact.contact_id == contact_id) \
    .first()

rawDescription: SQLAlchemy filter() return value

description: SQLAlchemy filter() return value


code:
class UserSerializer(serializers.ModelSerializer):
    """serializes a user"""
    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name',)

class SheetSerializer(serializers.ModelSerializer):
    """serializes a sheet, and nests user relationship"""
    user = UserSerializer(read_only=True)

    class Meta:
        model = Sheet
        fields = ('id', 'sheet_name', 'user',)

rawDescription: How to think about Django's normal class based views vs. using a REST API

description: Think about Django's normal class based views vs. using a REST API


rawDescription: Add legend or background image to Igraph 0.6 (for python) plot


code:
data_groups = df.groupby(df.columns.tolist())
size = data_groups.size().reset_index()
size[size[0] > 1]        # DATAFRAME OF DUPLICATES

len(size[size[0] > 1])   # NUMBER OF DUPLICATES

rawDescription: Find duplicates with groupby in Pandas

description: Find duplicates with groupby in Pandas


code:
class BlogPost(mongoengine.Document):
    create_date = mongoengine.DateTimeField()
    mod_date = mongoengine.DateTimeField()

    title = mongoengine.StringField()

    meta = {
        'abstract': True,
    }

    def save(self):
        if not self.pk:
            self.create_date = datetime.utcnow()
        self.mod_date = datetime.utcnow()

        super(BlogPost, self).save()

class TextBlogPost(BlogPost):
    body = mongoengine.StringField()

class ImageBlogPost(BlogPost):
    image = mongoengine.FileField()
    caption = mongoengine.StringField()

rawDescription: Any Python ORM make full use of NoSQL's schema-less feature?


rawDescription: Convert a list to a string list python

description: Convert a list to a string list python


code:
from collections import defaultdict
import datetime

class ElectricVehicle(object):
    ev_by_id = {}
    ev_by_battery = defaultdict(list)

    @classmethod
    def find(cls, id=None, battery=None):
        if id is not None:
            return [cls.ev_by_id[id]]
        elif battery is not None:
            return cls.ev_by_battery[battery]
        else:
            return []

    def __init__(self, id, battery, states):
        self.id = id
        ElectricVehicle.ev_by_id[id] = self

        self.battery = battery
        ElectricVehicle.ev_by_battery[battery].append(self)

        self.states = list(states)

    def state_at(self, time):
        return self.states[(time.hour*60 + time.minute)/5]

ElectricVehicle(12345, 24, [0.99, 0.99, 0.99])
ElectricVehicle(12346, 30, [0.90, 0.90, 0.89])

evs = ElectricVehicle.find(battery=24)
for ev in evs:
    time = datetime.time(0,3,0)    # 00:03:00
    print("{}: {}".format(ev.id, ev.state_at(time)))

# will print "12345: 0.99"

rawDescription: Python data structure advice

description: Python data structure advice


rawDescription: Compute values in vector with NumPy

description: Compute values in vector with NumPy


code:
class ChildForm(BaseForm):
    def __init__(self, *args, **kwargs):
        super(ChildForm, self).__init__(*args, **kwargs)
        self.fields['userid'].required = False

rawDescription: Overriding a parent's form field with options?


code:
def word_hex(w):
    a = int(w / 256)
    b = w % 256
    return "{0:#0{1}x}{2:#0{3}x}".format(a,4,b,4).replace("0x", "")

b='5:240'
b = b.split(':')
for i in b:
    print(word_hex(int(i)).decode("hex"))

rawDescription: Convert string into hex to send for serial communication


code:
import pickle

class ContextAwarePickler(pickle.Pickler):
    def persistent_id(self, obj):
        # if this is a context, return the key
        if isinstance(obj, Context):
            return ("Context", context.key)

        # pickle as usual
        return None

class ContextAwareUnpickler(pickle.Unpickler):
    def recover_context(self, key_id):
        ...

    def persistent_load(self, pid):
        type_tag, key_id = pid
        if type_tag == "Context":
            return self.recover_context(key_id)
        else:
            raise pickle.UnpicklingError("unsupported persistent object")

rawDescription: How to load a pickle object and resolve certain references

description: Load a pickle object and resolve certain references


code:
fname = "gettysburg.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += line.count(".")
        num_words += len(words)
        num_chars += len(line.replace(' ', ''))

rawDescription: determing the number of sentences, words and letters in a text file

description: Determing the number of sentences, words and letters in a text file


code:
from itertools import islice

def get_it(list2):
    moves = []
    buffer = []
    prev = list2[0]

    for current in islice(list2, 1, None):
        el = 2 * (current > prev) - 1
        if buffer and el != buffer[0]:
            moves.append(sum(buffer))
            buffer = []
        buffer.append(el)
        prev = current

    if buffer:
        moves.append(sum(buffer))

    return moves

rawDescription: Python traverse through list and count items based on conditions


rawDescription: Assign fixed number of variables to elements in variable length list


rawDescription: Deleting duplicates in list of lists in Python 2.7


code:
from ctypes import windll
if windll.user32.OpenClipboard(None):
    windll.user32.EmptyClipboard()
    windll.user32.CloseClipboard()

rawDescription: Clear Clipboard?

description: Clear Clipboard


code:
env = os.environ.copy()
env['LANG'] = 'en_US.UTF-8'
subprocess.check_output( ..., env = env)

rawDescription: Set locale encoding in python

description: Set locale encoding in python


rawDescription: Map-summing items in a multidimensional array


code:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(style="white", color_codes=True)

x, y = np.random.multivariate_normal([2, 3], [[0.3, 0], [0,  0.5]], 1000).T
g = sns.jointplot(x=x, y=y, kind="hex", stat_func=None, marginal_kws={'color': 'green'})
plt.setp(g.ax_marg_y.patches, color="r")

rawDescription: python's seaborn jointplot, different colors for each histograms

description: Python's seaborn jointplot, different colors for each histograms


code:
import matplotlib.pyplot as plt
x = [0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.65]
y = [0, 0.15, 0.3, 0.35, 0.4, 0.55, 0.57, 0.58]
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax3 = ax2.twiny()
ax3.set_xlabel('2nd x-axis label')
ax2.set_ylabel('2nd y-axis label')
ax1.set_xlim([0,1])
ax1.plot(x, y)

rawDescription: matplotlib 2nd axis label not showing

description: Matplotlib 2nd axis label not showing


code:
import Cocoa
manager = Cocoa.NSFontManager.sharedFontManager()
font_families = list(manager.availableFontFamilies())

rawDescription: List of installed fonts OS X / C

description: List of installed fonts OS X / C


code:
with open(x, "rb") as zfile:
    data = zfile.read()

rawDescription: How to read zip file content without unzipping (in compressed format) using Python

description: Read zip file content without unzipping (in compressed format) using Python


code:
class Test:
    def cached_method(self, x):
         return x + 5
    def __init__(self):
         self.cached_method = lru_cache(maxsize=16)(self.cached_method)

rawDescription: Python LRU Cache Decorator Per Instance

description: Python LRU Cache Decorator Per Instance


code:
class Test(object):
  def __init__(self, x, y):
    self.x = x
    self.y = y

x = (i for i in range(10))
y = iter(range(10))

t = Test(x,y)

import dill
dill.detect.errors(t)
dill.detect.badobjects(t)
dill.detect.badobjects(t, 1)
dill.detect.trace(True)
dill.dumps(t)

rawDescription: Python pickle: Unclear "AttributeError: can't set attribute"


code:
import re
re.sub(r'((?:He|well.*?made|Italian.*?American).*?)(\s)', r'[\1]\2', string)

rawDescription: Python Search the specific word sequence from the pos sequence and highlight it


code:
def Find(event=None):
    def find_button_pressed():
        start = "1.0"
        end = "end"
        start = textPad.index(start)
        end = textPad.index(end)
        count= Tkinter.IntVar()
        count=count
        textPad.mark_set("matchStart", start)
        textPad.mark_set("matchEnd", start)
        textPad.mark_set("searchLimit", end)
        targetfind = e1.get()
        if targetfind:
            while True:
                where = textPad.search(targetfind, "matchEnd", "searchLimit",
                                       count=count)
                if where == "": break
                elif where:
                    pastit = where + ('+%dc' % len(targetfind))
                    textPad.mark_set("matchStart", where)
                    textPad.mark_set("matchEnd", "%s+%sc" % (where, count.get()))
                    textPad.tag_add(SEL, where, pastit)
                    textPad.see(INSERT)
                    textPad.focus()
        win.destroy()
    textPad.tag_remove(SEL, '1.0', END)
    win = Toplevel()
    Label(win, text="Find:").pack()
    e1 = Entry(win)
    e1.pack()
    Button(win, text="Find Me!!!!", command=find_button_pressed).pack()
    textPad.focus()

rawDescription: Cannot get find function to highlight all instances of the target (text editor)


code:
class ProxyReview(Review):
    class Meta:
        proxy = True
        # If you're define ProxyReview inside review/models.py,
        #  its app_label is set to 'review' automatically.
        # Or else comment out following line to specify it explicitly
        # app_label = 'review'

        # set following lines to display ProxyReview as Review
        # verbose_name = Review._meta.verbose_name
        # verbose_name_plural = Review._meta.verbose_name_plural

# in admin.py
admin.site.register(ProxyReview)

rawDescription: How to group models in django admin?

description: Group models in django admin


code: pd.merge(df1, df2, how='outer', on=['Progcode', 'Season'])

rawDescription: Mapping a a column of data frame to Another existing data frame DataFrame


code:
f_in=open("file_in.txt", "r")       #opens a file in the reading mode
in_lines=f_in.readlines()           #reads it line by line
out=[]
for line in in_lines:
    list_values=line.split()        #separate elements by the spaces, returning a list with the numbers as strings
    for i in range(len(list_values)):
        list_values[i]=eval(list_values[i])     #converts them to floats
#       print list_values[i],
        if list_values[i]<0.05:     #your condition
#           print ">>", 1
            list_values[i]=1
        else:
#           print ">>", 0
            list_values[i]=0
    out.append(list_values)         #stores the numbers in a list, where each list corresponds to a lines' content
f_in.close()                        #closes the file

f_out=open("file_out.txt", "w")     #opens a new file in the writing mode
for cur_list in out:
    for i in cur_list:
        f_out.write(str(i)+"\t")    #writes each number, plus a tab
    f_out.write("\n")               #writes a newline
f_out.close()                       #closes the file

rawDescription: Python: read a file and replace it line by line with a certain condition


code:
a = np.zeros((4,4))
b = np.arange(4).reshape(2,2)+1
ind = [0,3]
np.ix_(ind, ind)
a[np.ix_(ind, ind)] += b
a

rawDescription: How to add a 2D subarray in an existing 2D array using numpy?

description: Add a 2D subarray in an existing 2D array using numpy


code:
from main.foo import names
import os

names_pickle = os.path.join(os.path.dirname(names.__file__), 'names.pickle')

rawDescription: Loading data via a module and a text file in another directory


code:
# assuming your original list is called biglist
Mainlist = []
sublist = []
for item in biglist:
    if item == 'foo':
        Mainlist.append(sublist)
        sublist = []
    else:
        sublist.append(item)

rawDescription: How to make list with sublists based on pattern(word) from a input list?

description: Make list with sublists based on pattern(word) from a input list


code:
from glob import glob
glob('*.jpg')

rawDescription: Python-read files from current folder

description: Python-read files from current folder


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

p=.3

bins=np.arange(0,50,1)

r=np.random.rand( 1000 )
gen=np.floor(np.log(r)/np.log(1-p))
plt.hist(gen,bins=bins,alpha=.8)

N=5
gen_trunc=np.floor(np.log(1-r*(1-(1-p)**N))/np.log(1-p))
plt.hist(gen_trunc,bins=bins,alpha=.8)

plt.show()

rawDescription: Sample integers from truncated geometric distribution


code:
from itertools import accumulate
from random import uniform

class ProbItem(object):
    def __init__(self, value, prob):
        self.value = value
        self.prob = prob

def pick(items):
    accum = list(accumulate(item.prob for item in items))
    rand = uniform(0, accum[-1])
    for i, prob in enumerate(accum):
        if rand < prob:
            return items.pop(i).value

drivers = [
    ProbItem("John Doe", 23.7),
    ProbItem("Bill Smith", 17),
    ProbItem("Trent Baxter", 12.43),
    ProbItem("Ray Olson", 9.99),
]

while (drivers):
    print(pick(drivers))

rawDescription: Choosing items from a list on a percent basis


code:
import numpy as nx
import pylab as px

def half_brace(x, beta):
    x0, x1 = x[0], x[-1]
    y = 1/(1.+nx.exp(-1*beta*(x-x0))) + 1/(1.+nx.exp(-1*beta*(x-x1)))
    return y

xmax, xstep = 20, .01
xaxis = nx.arange(0, xmax/2, xstep)
y0 = half_brace(xaxis, 10.)
y = nx.concatenate((y0, y0[::-1]))

px.plot(nx.arange(0, xmax, xstep), y)
px.show()

rawDescription: Drawing braces with Pyx

description: Drawing braces with Pyx


code:
def ask():
    return int(input("Enter a number between 0 and 1000, inclusive: "))

def inclusive():
    i = -1
    while i < 0 or i > 1000:
        print("Out of range, my boy. Try again!")
        i = ask()
    return i

def main():
    m = inclusive()
    print(m)

rawDescription: How to write a program that asks the user to enter a number between 0 and 1000, inclusive....continued

description: Write a program that asks the user to enter a number between 0 and 1000, inclusive....continued


code:
class Norf(Models.model):
    BOOLS = [None, 'foo', 'bar']
    foo = models.BooleanField(default=False)
    bar = models.BooleanField(default=False)

    def get_bool(self, n):
        return getattr(self, self.BOOLS[n])

rawDescription: How to return own field by attribute in python?

description: Return own field by attribute in python


code:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(111)
fig2 = plt.figure()
ax2 = fig2.add_subplot(111, sharex=ax1)

rawDescription: link axis between different plot (no subplots) using matplotlib

description: Link axis between different plot (no subplots) using matplotlib


code:
def disc(a, b, c):
    return b ** 2 - 4 * a * c

a = raw_input("Please enter the value of A: ")
b = raw_input("Please enter the value of B: ")
c = raw_input("Please enter the value of C: ")

val = disc(int(a), int(b), int(c))

print ("The discriminant is: %s") % (val)

if val == 0:
    print ("The conic is a Parabola!")
elif val > 0:
    print ("The conic is a Hyperbola!")
elif a != c:
    print ("The conic is an Ellipse!")
else:
    print ("The conic is a Circle!")

rawDescription: Looking for a more efficient way to write my python program


code: 'The hex value of {0:d} is {0:02x}'.format(42)

rawDescription: What is global format() function meant for?


code:
import __builtin__
builtin_types= [t
 for t in __builtin__.__dict__.itervalues()
 if isinstance(t, type)]
import pprint
pprint.pprint(sorted(builtin_types, key=repr))

rawDescription: How do I get list of all Python types (programmatically)?

description: Get list of all Python types (programmatically)


code:
result = []
for i in range(0, max(len(ls1),len(ls2)), 2):
    result.append(tuple(ls1[i:i+2] + ls2[i:i+2]))

rawDescription: Merge two list by selecting 2 element each


code:
import numpy as np
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

from PySide.QtGui import QImage
from PySide.QtGui import QPainter
from PySide.QtCore import QSize
from PySide.QtWebKit import QWebPage

arrays = [np.hstack([ ['one']*3, ['two']*3]), ['Dog', 'Bird', 'Cat']*2]
columns = pd.MultiIndex.from_arrays(arrays, names=['foo', 'bar'])
df =pd.DataFrame(np.zeros((3,6)),columns=columns,index=pd.date_range('20000103',periods=3))

h = "<!DOCTYPE html> <html> <body> <p> " + df.to_html() + " </p> </body> </html>";
page = QWebPage()
page.setViewportSize(QSize(5000,5000))

frame = page.mainFrame()
frame.setHtml(h, "text/html")

img = QImage(1000,700, QImage.Format(5))
painter = QPainter(img)
frame.render(painter)
painter.end()
a = img.save("html.png")

pp = PdfPages('html.pdf')
fig = plt.figure(figsize=(8,6),dpi=1080)
ax = fig.add_subplot(1, 1, 1)
img2 = plt.imread("html.png")
plt.axis('off')
ax.imshow(img2)
pp.savefig()
pp.close()

rawDescription: Save the "Out[]" table of a pandas dataframe as a figure


code:
def cb(n,k):
    if n < k:
        return [n]
    else:
        return cb(n//k,k) + [n%k]

print(cb(22,3))

rawDescription: changing base of a number to a given number

description: Changing base of a number to a given number


code:
def chunkify(chunk_size):
    df['chunk'] = (df.index.values - 1) / chunk_size
    df['E'] = df.groupby('chunk').apply(lambda x: x.B - pd.expanding_min(x.C)).values.flatten()

rawDescription: In Pandas/Numpy, How to implement a rolling function inside each chunk using 2 different columns?


code:
def party_generator(size=1, chars=string.ascii_uppercase):
    parties = []
    for y in range(2):
        party = ''.join(random.choice(chars) for x in range(size))
        parties.append(''.join(['Party ',party]))
    return parties

rawDescription: why function returns a list with only one member?

description: Why function returns a list with only one member


code:
channel.basic_publish(exchange=self.exchange,
                      routing_key=self.routing_key,
                      properties=pika.BasicProperties(
                          headers={'key': 'value'} # Add a key/value header
                      ),
                      body=message)

rawDescription: How to add a header key:value pair when publishing a message with pika

description: Add a header key:value pair when publishing a message with pika


code:
proc = subprocess.Popen([executable, arg1, arg2],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = proc.communicate()
status_code = proc.returncode

rawDescription: Can we send a tuple as an argument to sys.exit() in python


code:
INSTALLED = ['syncronous', 'alternative']

for mod_name in INSTALLED:
    try:
        module = importlib.import_module('servicelibrary.simple.' + mod_name)
        Publisher = getattr(module, 'Publisher')

        if Publisher:
            break  # found, what we needed

    except ImportError:
        continue

rawDescription: Choose adapter dynamically depending on librarie(s) installed


code:
row = soup.find("tr", class_="soup-target")
for text_node in row.find_all(text=True, recursive=False):
    text_node.extract()

rawDescription: Remove spaces between/after td elements using BeautifulSoup


code:
pattern = "|".join(re.escape(s) for s in subList)
crexp = re.compile(pattern)
if any(crexp.search(s) for s in strList):
    ...

rawDescription: matching list of substrings to a list of strings in Python

description: Matching list of substrings to a list of strings in Python


code:
import simplejson as json
import requests

def jsonize(req):
     try:
         data = json.loads(req.content)
     except json.JsonDecodeError:
         data = {'error': req.status_code}
     except Exception:
         data = {}
     return data

def __init__(self, id):
     req = requests.get('http://api.example/%i?api_key=foo' % id)
     data = jsonize(req)
     if data and not 'error' in data:
         self.name = data.get('name', "")

rawDescription: Is it a good way to make a JSON Request?

description: Is it a good way to make a JSON Request


code:
intab = ['TBA', 'RIP', 'TGIF', 'FAQ']
outtab = ['To Be Announced', 'Rest In Peace',
                     'Thank God It\'s Friday', 'Frequently Asked Questions']

translationtable = dict(zip(intab, outtab))
# {'TBA': 'To Be Announced', 'TGIF': "Thank God It's Friday", 'FAQ': 'Frequently Asked Questions', 'RIP': 'Rest In Peace'}

rawDescription: What is the equivalent of string.makestrans() for lists or dictionaries?


code: n = struct.unpack('>I', read_bytes)[0]

rawDescription: How can i convert binary data from a file to readable base two binary in python?

description: Convert binary data from a file to readable base two binary in python


code:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.resources import resource_find
from kivy.graphics.transformation import Matrix
from kivy.graphics import *
from kivy.graphics.opengl import *
import random

class Root(Widget):
    def __init__(self, *larg, **kw):
        super(Root, self).__init__(*larg, **kw)
        self.vertices = [[-1,-1, 0,    1,-1, 0,    1, 1, 0,   -1, 1, 0]]
        with self.canvas:
             self.fbo = Fbo(with_depthbuffer = True, size = Window.size)
             Rectangle(size=Window.size, texture=self.fbo.texture)

        kw['shader_file'] = 'shaders.glsl'
        shader_file = kw.pop('shader_file')
        self.fbo.shader.source = resource_find(shader_file)
        with self.fbo:
            self.cb = Callback(self.setup_gl_context)
            PushMatrix()
            Translate(0, 0, -5)
            for i in xrange(10):
                Translate(.5, 0, -.5)
                self.render(self.vertices, (random.random(), random.random(), random.random()))
            PopMatrix()
            self.cb = Callback(self.reset_gl_context)

        asp = float(Window.width) / Window.height / 2.0
        proj = Matrix().view_clip(-asp, asp, -0.5, 0.5, 1, 100, 1)
        self.fbo['projection_mat'] = proj

    def setup_gl_context(self, *args):
        glEnable(GL_DEPTH_TEST)

    def reset_gl_context(self, *args):
        glDisable(GL_DEPTH_TEST)

    def render(self, vertices, color):
        for i in xrange(len(vertices)):
            ChangeState(Kd=color, Ka=color, Ks=(.3, .3, .3), Tr=1., Ns=1., intensity=1.)
            Mesh(vertices=vertices[i], indices=[0, 1, 2, 3, 0, 2], fmt=[('v_pos', 3, 'float')], mode='triangles')

class TestApp(App):
    def build(self):
        return Root()

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

rawDescription: Depth buffer does not work on Android, but does work on Linux (using Kivy)


code:
import pandas as pd
import re

## data in 'myfile.csv' looks like this##
##column1,column2,column3,column.4
##375,"string1","string.2",["string3"]
##320,"string4, string5","string6",500
##345,"string7",["string8", "string9"],"string10"

new_data = []
with open(r'C:\Users\Owner\Downloads\myfile.csv') as f:
  f_as_string = f.read()
  res = re.sub(',(?!\s)', '|', f_as_string)
  for i in res.split('\n'):
    new_data.append(i.split('|'))

df = pd.DataFrame(data=new_data[1:], columns=new_data[0])

## Produces this dataframe literally retaining quotes
##  column1             column2                 column3     column.4
##0     375           "string1"              "string.2"  ["string3"]
##1     320  "string4, string5"               "string6"          500
##2     345           "string7"  ["string8", "string9"]   "string10"

rawDescription: Python: Load a csv file in a DataFrame with exception for string and list comma separator


code:
if all(key in request.session for key in ['a', 'b', ...]):
   ...

rawDescription: Better Way to Check for Keys in Python Django Sessions?


code:
with open('data.csv') as f:
    headers = f.readline().strip().split(',') # get years
    headers[:3] = f.readline().strip().split(',') # update first three columns
    data = pd.read_csv(f, names=headers)

rawDescription: Complicated csv format: columns in two lines


code: output = subprocess.check_output(['/usr/bin/python', 'test.py'] + argument_list, stderr=subprocess.STDOUT)

rawDescription: passing a list to subprocess.check_output

description: Passing a list to subprocess.check_output


code:
df
df.iloc[:,:-1] = df.iloc[:, :-1].mul(df["pop"], axis=0)
df

rawDescription: Working with samples, applying a function to a large subset of columns


code:
from itertools import islice
with open("t.txt") as f:
    for ind, sli in enumerate(iter(lambda:list(islice(f,filesize)),[]),1):
        with open("{}.txt".format(ind),"w") as out:
            out.writelines(sli)

rawDescription: Writing and naming multiple files in python


code:
import numpy
import matplotlib
from matplotlib import pylab, mlab, pyplot
np = numpy
plt = pyplot

from IPython.core.pylabtools import figsize, getfigs

from pylab import *
from numpy import *

rawDescription: IPYTHON code using numpy arrays and %pylab inline


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

def plot_confusion_matrix(cm, target_names, title='Confusion matrix', cmap=plt.cm.Blues):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    tick_marks = np.arange(len(target_names))
    plt.xticks(tick_marks, target_names, rotation=45)
    plt.yticks(tick_marks, target_names)
    plt.tight_layout()

    width, height = cm.shape

    for x in xrange(width):
        for y in xrange(height):
            plt.annotate(str(cm[x][y]), xy=(y, x),
                        horizontalalignment='center',
                        verticalalignment='center')
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

cm = np.array([[13,  0,  0],[ 0, 10,  6],[ 0,  0,  9]])
plot_confusion_matrix(cm, ['A', 'B', 'C'])

rawDescription: python tabulating confusion matrix

description: Python tabulating confusion matrix


code:
dic = {'Mr A':[1200,1500,1100], 'Mr B':[2200, 3000, 1200]}
[key for key, value in dic.iteritems() if 1200 in value]
[key for key, value in dic.iteritems() if 3000 in value]

rawDescription: Look up array of values as the value of a key of a dictionary in Python


code:
for func in [foo, bar, baz]:
    __builtins__[func.__name__] = func

rawDescription: Auto-imports or other code-less way of using custom functions


code:
results = [] # This is what you will send to the template

for location in address.objects.select_related():
    data = {} # an empty dictionary
    localized_data = location.address_localisation_set.first()
    data['lat'] = localized_data.latitude
    data['lon'] = localized_data.longitude
    data['id'] = location.id
    results.append(data)

return JsonResponse(json.dumps(results), safe=False)

rawDescription: Django / views- add field to model and return to template


code:
from django.contrib import admin
from myproject.myapp.models import Author

class AuthorAdmin(admin.ModelAdmin):
    pass
admin.site.register(Author, AuthorAdmin)

rawDescription: How to add HTML content editor in Django admin view?

description: Add HTML content editor in Django admin view


code:
lst = [[1,2,3], [2,3,4], [4,5,6]]
sorted([sorted(sublst, reverse=True) for sublst in lst], reverse=True)

rawDescription: How to sort ANY list in Python 2.7 in DESCENDING order?

description: Sort ANY list in Python 2.7 in DESCENDING order


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.edit1 = QtGui.QTextEdit(self)
        self.edit2 = QtGui.QTextEdit(self)
        layout = QtGui.QHBoxLayout(self)
        layout.addWidget(self.edit1)
        layout.addWidget(self.edit2)
        self.edit1.horizontalScrollBar().valueChanged.connect(
            self.edit2.horizontalScrollBar().setValue)
        self.edit1.verticalScrollBar().valueChanged.connect(
            self.edit2.verticalScrollBar().setValue)
        self.edit2.horizontalScrollBar().valueChanged.connect(
            self.edit1.horizontalScrollBar().setValue)
        self.edit2.verticalScrollBar().valueChanged.connect(
            self.edit1.verticalScrollBar().setValue)
        text = '\n'.join(name for name in dir(QtCore))
        self.edit1.setText(text)
        self.edit2.setText(text)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 600, 400)
    window.show()
    sys.exit(app.exec_())

rawDescription: one single scroll bar for two QTextEdit, pyqt4, python

description: One single scroll bar for two QTextEdit, pyqt4, python


code:
user_name = '1'  #something that doesn't validate
while not re.match("^[A-Za-z]*$", user_name):
    user_name = raw_input("Please enter your name: ")
    print ("Error! Make sure you only use letters in your name")
else:
    print("Hello! "+ user_name)

rawDescription: Validate user input using regular expressions


rawDescription: extended slicing with string in python

description: Extended slicing with string in python


rawDescription: How to see new results in console after updating imported module in PythonAnywhere

description: See new results in console after updating imported module in PythonAnywhere


rawDescription: Adding elements of lists in Python

description: Adding elements of lists in Python


code: c = [item for pair in zip(a, b) for item in pair]

rawDescription: Python: Intertwining two lists

description: Python: Intertwining two lists


code:
dir(type)
import sys
dir(type(sys))

rawDescription: Built-in magic variable names/attributes


code:
from urllib2 import urlparse

url = 'http://www.example.com/example:8080'
parsedURL = urlparse.urlparse(url)
port = url.split(':')[2]
fixedURL = parsedURL.scheme + '://' + parsedURL.netloc + ':' + port

rawDescription: Edit the string from particular character to a particular character


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.graphics import Color
from kivy.uix.boxlayout import BoxLayout

gui = '''
<MyWidget>:
    canvas:
        Rotate:
            axis: 0,0,1
            angle: 45
            origin: self.center
        Color:
            rgba: 0.4, 0.4, 0.4, 1
        Rectangle:
            pos: root.center
            size: (32, 32)
'''

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(MyWidget, self).__init__(**kwargs)
    Builder.load_string(gui)

class MyJB(App):
    def build(self):
        parent = MyWidget()
        return parent

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

rawDescription: Is it possible to turn a widget [Kivy]

description: Is it possible to turn a widget [Kivy]


rawDescription: How to format to a string to a fixed length which stores in a variable?

description: Format to a string to a fixed length which stores in a variable


code:
import sys;
sys.path.insert(0, '/path/to/application/app(folder)')

import urlregister

rawDescription: Python import file from app

description: Python import file from app


code:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB

data = [['this is about dogs', 'dogs are really great'],
        ['this is about cats', 'cats are evil']]
labels = ['dogs',
          'cats']

vec = CountVectorizer()  # count word occurrences
X = vec.fit_transform([' '.join(row) for row in data])

clf = MultinomialNB()  # very simple model for word counts
clf.fit(X, labels)

new_data = ['this is about cats too', 'I think cats are awesome']
new_X = vec.transform([' '.join(new_data)])

print(clf.predict(new_X))
# ['cats']

rawDescription: classification of data where attribute values are strings

description: Classification of data where attribute values are strings


code:
class Animal(object):

    @staticmethod
    def get_animal_which_makes_noise(noise):
        if noise == 'meow':
            return Cat()
        elif noise == 'woof':
            return Dog()

class Cat(Animal):
    ...

class Dog(Animal):
    ...

rawDescription: pick a subclass based on a parameter

description: Pick a subclass based on a parameter


code:
class FlowQuerySets(models.QuerySet):
    def top_app(self):
        import socket
        for obj in self.values('dst_port')\
            .annotate(traffic=Sum('bytes')).order_by('-traffic')[:10]:
            if obj['dst_port']:
                obj['dst_port'] = socket.getservbyport(int(obj['dst_port']))
            yield obj

rawDescription: Django. Apply function to queryset

description: Django. Apply function to queryset


code:
from itertools import chain, combinations, product

lengths = (3, 2, 1, 4)
for L in product(*(combinations(range(5), length) for length in lengths)):
    print(list(chain.from_iterable(L)))

rawDescription: How can I take multiple combinations of the different lengths from the same list in python?

description: Take multiple combinations of the different lengths from the same list in python


code:
import os
print(u"current directory: %s" % os.getcwdu())

rawDescription: In python, when using sqlite3 where are databases stored physically?


code:
import platform

setup_requires = ['foo', 'bar']

if platform.system() == 'Windows':
    setup_requires.append('pyreadline')

setup(
    # ...
    setup_requires=setup_requires,
)

rawDescription: Setuptools platform specific dependencies


code:
from threading import Thread
from time import sleep
from random import randint

class XProcesStarter:
  def __init__(self, thread_count):
    print ("starting new process...")
    self._i = 0
    for i in range(thread_count):
      t = Thread(
        target=XProcess,
        args=(self.get_proxy_list(), self.get_url())
      )
      t.start()

  def get_proxy_list(self):
    self._i += 1
    return "Proxy list #%s" % self._i

  def get_url(self):
    self._i += 1
    return "URL #%d" % self._i

class XProcess():
  def __init__(self, proxy_list, url, browser_show=False):
    r = 0.001 * randint( 1, 5000)
    sleep(r)
    print (proxy_list)
    print (url)

def main():
  t = Thread( target=XProcesStarter, args=(4, ) )
  t.start()

if __name__ == '__main__':
  main()

rawDescription: Python GUI stays frozen waiting for thread code to finish running


code:
try:
    import Tkinter
except ImportError:
    import tkinter as Tkinter
import sys
from math import floor

master = Tkinter.Tk()

xboxes = int(sys.argv[1])
yboxes = int(sys.argv[2])

winx = 800
winy = 600

w = Tkinter.Canvas(master, width=winx, height=winy)

squares = [[None]*xboxes for i in range(yboxes)] # <-- changed hard-coded 5; to use passed argument
w.pack()
for i in range(yboxes):
    for j in range(xboxes):
        initx = floor(winx / xboxes * j) # <--
        inity = floor(winy / yboxes * i) # <--
        endx = floor(winx / xboxes * (j+1)) # <-- with `j`, It draw dot instead of rectangle.
        endy = floor(winy / yboxes * (i+1)) # <--
        squares[i][j] = w.create_rectangle(initx, inity, endx, endy, fill="red")

master.mainloop()

rawDescription: Tkinter won't draw rectangles on Canvas

description: Tkinter won't draw rectangles on Canvas


code:
import sys
getattr(sys.modules[__name__], 'A')

rawDescription: How can I dynamically get the set of classes from the current python module?

description: Dynamically get the set of classes from the current python module


code:
import re
new_list = sorted(l, key=lambda s: re.sub('[aioue]', '', s))

rawDescription: Python 3.3.2 - Sorting a List, While Disregarding Vowels


code:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

def create_product_id(apps, schema_editor):
    Product = apps.get_model("yourappname", "Product")
    for product in Product.objects.all():
        p_id = str(product.product_number)
        if product.experimental:
            p_id = "X" + p_id
        product.product_id = p_id
        product.save()

class Migration(migrations.Migration):
    initial = True

    dependencies = [
        ('yourappname', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(create_product_id),
    ]

rawDescription: Django database migration: merging two fields into one


code:
from __future__ import print_function
from time import sleep
from random import random
from threading import Timer

def timeout():
    print("Alarm!")

t = Timer(10.0, timeout)
t.start()              # After 10 seconds, "Alarm!" will be printed

sleep(5.0)
if random() < 0.5:     # But half of the time
     t.cancel()        # We might just cancel the timer
     print('Canceling')

rawDescription: How to set a timer & clear a timer in python?

description: Set a timer & clear a timer in python


code:
BLOCK_SIZE_BYTES = 512 # usually?  always?  *shrug*

def get_disk_size(blockdev):
    blocks = int(open('/sys/block/{blockdev}/size'.format(**locals())).read())
    return blocks * BLOCK_SIZE_BYTES

rawDescription: Read size of linux disk with python

description: Read size of linux disk with python


code:
list1 = range(100)
list2 = range(10)

pos = 0
for item in list2:
    list1.insert(pos, item)
    pos += 7

rawDescription: How can I insert a list into a list at certain intervals?

description: Insert a list into a list at certain intervals


rawDescription: Plot a scatter plot in python with matplotlib with dictionary


code:
import threading, urllib2
import Queue

urls_to_load = [
'http://stackoverflow.com/',
'http://slashdot.org/',
'http://www.archive.org/',
'http://www.yahoo.co.jp/',
]

def read_url(url, queue):
    data = urllib2.urlopen(url).read()
    print('Fetched %s from %s' % (len(data), url))
    queue.put(data)

def fetch_parallel():
    result = Queue.Queue()
    threads = [threading.Thread(target=read_url, args = (url,result)) for url in urls_to_load]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return result

def fetch_sequencial():
    result = Queue.Queue()
    for url in urls_to_load:
        read_url(url,result)
    return result

rawDescription: Python urllib2.urlopen() is slow, need a better way to read several urls


code:
class AbstractModel(Base):
    type = Column(String())
    __mapper_args__ = {"polymorphic_on": type}

class ModelA(AbstractModel):
    __mapper_args__ = {"polymorphic_identity": "model_a"}

class FlaskModel(ModelA):
    pass

##Event listeners are requireed for the inherited polymorphic relationships
##If additional work needs to be done with different aspect, including after_delete and after_update
##They can als be added here
@event.listens_for(FlaskModel, 'init')
def receive_label_init(target, args, kwargs):
    kwargs["type"] = "model_a"

@event.listens_for(FlaskModel, 'mapper_configured')
def receive_label_mapper_configured(mapper, class_):
    mapper.polymorphic_identity = "model_a"

rawDescription: Same Polymorphic Identity for Different Models


code:
class UserProfile(models.Model):
    objects = UserProfileManager()
    organization = models.CharField(max_length=100)
    country = CountryField()
    is_verified = models.BooleanField(default=False)
    blocked = models.BooleanField(default=False)
    anonymous = models.BooleanField(default=False)
    user = models.OneToOneField(auth_models.User)

rawDescription: Inheritance in Django: child class updates parent with empty fields


code:
def f(a,b):
   print(a,b)

f("Hello", "World!")

args = ["Hello", "World!"]
f(*args)

rawDescription: Arguments accepted by range() function in python3


code:
vel = [4, 3]
lst = [[4, 5]  # changed this identifier. Don't shadow Python built-ins
       [6, 4]
       [7, 5]
       [3, 4]]

lst = [[vel[0]+sublst[0], vel[1]+sublst[1]] for sublst in lst]

rawDescription: How to add the int elements of 2 lists python

description: Add the int elements of 2 lists python


rawDescription: Communicating with the outside world from within an atomic database transaction


code: table = [[{} for _ in range(len(words)+1)] for _ in range(len(words))]

rawDescription: Python - Is this the correct way to initalize a matrix of empty sets?


rawDescription: Extract from last element of a list to a certain string


code:
from django.db.models import Max

X.objects.annotate(max_z=Max('y__zs__number')).order_by('max_z')

rawDescription: Django - difficult order by (two M2M relations)


rawDescription: regular expressions emoticons

description: Regular expressions emoticons


code:
class A(object):
    def say_hi(self):
        print('hi, I am A')
class B(object):
    def say_hi(self):
        print('hi, I am B')
class F(object):
    def __init__(self, name):
        self.name = name
    def create(self):
        return globals()[self.name]()
f = F('B')
b = f.create()
b.say_hi()

rawDescription: python how to create classes in the same file dynamically with name

description: Python how to create classes in the same file dynamically with name


code:
# Test data
np.random.seed(1234)
test = pd.DataFrame({'week':[1,1,1,1,1,1,2,2,2,2,2,2],
                     'score':np.random.uniform(0,1,12),
                    'type': [0,1,0,1,0,1,0,1,0,1,0,1],
                     'type2':[3,3,4,4,5,5,3,3,4,4,5,5]})
grouped = test.groupby(['type','week','type2']).agg('sum')

# Preparing plots
fig, axes = plt.subplots(nrows=2)

for group_name, group in grouped.groupby(level=0):
    group.index = group.index.droplevel(0)
    group = group.unstack(1)
    group.columns = group.columns.droplevel()
    group.plot(kind='bar', stacked=True, ax=axes[group_name], title='type: ' + str(group_name))

rawDescription: How to create stacked subplots with pandas

description: Create stacked subplots with pandas


code:
'''
Copyright (c) 2015
Dhanushka Dangampola <dhanushkald@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
'''

import numpy as np
from math import atan2
from numpy import cos, sin, conjugate, sqrt

def _slow_zernike_poly(Y,X,n,l):
    def _polar(r,theta):
        x = r * cos(theta)
        y = r * sin(theta)
        return 1.*x+1.j*y

    def _factorial(n):
        if n == 0: return 1.
        return n * _factorial(n - 1)
    y,x = Y[0],X[0]
    vxy = np.zeros(Y.size, dtype=complex)
    index = 0
    for x,y in zip(X,Y):
        Vnl = 0.
        for m in range( int( (n-l)//2 ) + 1 ):
            Vnl += (-1.)**m * _factorial(n-m) /  \
                ( _factorial(m) * _factorial((n - 2*m + l) // 2) * _factorial((n - 2*m - l) // 2) ) * \
                ( sqrt(x*x + y*y)**(n - 2*m) * _polar(1.0, l*atan2(y,x)) )
        vxy[index] = Vnl
        index = index + 1

    return vxy

def zernike_reconstruct(img, radius, D, cof):

    idx = np.ones(img.shape)

    cofy,cofx = cof
    cofy = float(cofy)
    cofx = float(cofx)
    radius = float(radius)

    Y,X = np.where(idx > 0)
    P = img[Y,X].ravel()
    Yn = ( (Y -cofy)/radius).ravel()
    Xn = ( (X -cofx)/radius).ravel()

    k = (np.sqrt(Xn**2 + Yn**2) <= 1.)
    frac_center = np.array(P[k], np.double)
    Yn = Yn[k]
    Xn = Xn[k]
    frac_center = frac_center.ravel()

    # in the discrete case, the normalization factor is not pi but the number of pixels within the unit disk
    npix = float(frac_center.size)

    reconstr = np.zeros(img.size, dtype=complex)
    accum = np.zeros(Yn.size, dtype=complex)

    for n in range(D+1):
        for l in range(n+1):
            if (n-l)%2 == 0:
                # get the zernike polynomial
                vxy = _slow_zernike_poly(Yn, Xn, float(n), float(l))
                # project the image onto the polynomial and calculate the moment
                a = sum(frac_center * conjugate(vxy)) * (n + 1)/npix
                # reconstruct
                accum += a * vxy
    reconstr[k] = accum
    return reconstr

if __name__ == '__main__':

    import cv2
    import pylab as pl
    from matplotlib import cm

    D = 12

    img = cv2.imread('fl.bmp', 0)

    rows, cols = img.shape
    radius = cols//2 if rows > cols else rows//2

    reconst = zernike_reconstruct(img, radius, D, (rows/2., cols/2.))

    reconst = reconst.reshape(img.shape)

    pl.figure(1)
    pl.imshow(img, cmap=cm.jet, origin = 'upper')
    pl.figure(2)
    pl.imshow(reconst.real, cmap=cm.jet, origin = 'upper')

rawDescription: Image reconstruction based on Zernike moments using mahotas and opencv


code:
PROJECT_ROOT = '/path/to/project'
sys.path.insert(0, '%s' % PROJECT_ROOT)
sys.path.insert(1, '%s/module_name' % PROJECT_ROOT)

rawDescription: Relative import creates different class object?


code:
def find_locks(item, ids):
    if item.video_id:
        yield (item.video_id, ids)
    for i in CatalogItem.objects.filter(parent=item):
        nxt = ids + [i.id] if i.is_lock else ids
        for x in find_locks(i, nxt):
            yield x

rawDescription: Get list of data after recursion function


code:
for line in f:
    while True:
        # do stuff
        if condition:
            break
        # do more stuff

rawDescription: How do I reiterate over the last iteration?

description: Reiterate over the last iteration


code:
from tkinter import *

class Application:

    def __init__(self, master):
        self.master = master

        self.new_switch_on = False
        self.main_switch_on = False

        self.create_main_frame()

    def create_main_frame(self): # new name
        if self.new_switch_on == True:
            self.new_frame.destroy()

        self.new_switch_on = False
        self.main_switch_on = True

        self.main_frame = Frame(self.master, width = 200, height = 100)

        Label(self.main_frame, text = 'Main Frame').pack()
        Button(self.main_frame, text = 'Next', command = self.create_new_frame).pack()  # new name

        self.main_frame.pack()

    def create_new_frame(self): # new name
        if self.main_switch_on == True:
            self.main_frame.destroy()

        self.main_switch_on = False
        self.new_switch_on = True

        self.new_frame = Frame(self.master, width = 400, height = 200)

        Label(self.new_frame, text='New Frame').pack()
        Button(self.new_frame, text='Back', command=self.create_main_frame).pack()  # new name

        self.new_frame.pack()

root = Tk()
root.geometry('-1+1')

app = Application(root)

root.mainloop()

rawDescription: Clearing frames in tkinter

description: Clearing frames in tkinter


code:
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'standard': {
            'format': '%(asctime)s [%(levelname)s] %(name)s: %(message)s'
        },
    },
    'handlers': {
        'default': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': 'logs/mylog.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'standard',
        },
        'request_handler': {
            'level':'DEBUG',
            'class':'logging.handlers.RotatingFileHandler',
            'filename': 'logs/django_request.log',
            'maxBytes': 1024*1024*5, # 5 MB
            'backupCount': 5,
            'formatter':'standard',
        },
    },
    'loggers': {
        '': {
            'handlers': ['default'],
            'level': 'DEBUG',
            'propagate': True
        },
        'django.request': {
            'handlers': ['request_handler'],
            'level': 'DEBUG',
            'propagate': False
        },
    }
}

rawDescription: Django Setup Default Logging

description: Django Setup Default Logging


code:
s = "Onehundredthousand"
s.replace('hundred', '_hundred_').split('_')

rawDescription: String Split into separate Strings in python


code:
def get_number_of_visitors(site, start_date, end_date=None):
    """
    start_date and end_date should be datetime.datetime instances or
    timestamps like those returned from time.time().
    """
    if end_date is None:
        end_date = datetime.datetime.now()
    pool = ConnectionPool('Logs', timeout = 2)
    col_fam = ColumnFamily(pool, 'sessions')
    return col_fam.get_count(site, column_start=start_date, column_finish=end_date)

rawDescription: Get range of columns from Cassandra based on TimeUUIDType using Python and the datetime module


code:
#config.py

import sys

from common_config import *

if sys.platform == 'darwin':
    from mac_config import *
elif sys.platform == 'win32':
    from win32_config import *
else:
    from linux_config import *

rawDescription: Accessing a global module in python

description: Accessing a global module in python


code:
from my_app import User
from flask_sqlalchemy import get_debug_queries
User.query.filter_by(display_name='davidism').all()
info = get_debug_queries()[0]
print(info.statement, info.parameters, info.duration, sep='\n')

rawDescription: Show the SQL generated by Flask-SQLAlchemy


code:
#Get the repository from the event and show its git clone URL
repository = event['Records'][0]['eventSourceARN'].split(':')[5]

rawDescription: Get name of Amazon Web Services Codecommit Repository in triggered Lambda function


rawDescription: Sum then average values in a string of strings using Python


code:
def grabFiles(source,ext):
    import fnmatch
    import os

    matches = []
    for root, dirnames, filenames in os.walk(source):
        for filename in fnmatch.filter(filenames, '*' + ext):
            matches.append(os.path.join(root, filename))
    return matches

rawDescription: Return() from functions - Im doin it wrong?


code:
#!/usr/bin/env python
import socket
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW)
s.bind(("ethX", 0))

blocksize = 100;
with open('filename.txt') as fh:
    while True:
        block = fh.read(blocksize)
        if block == "": break  #EOF
        s.send(block)

rawDescription: Writing raw IP data to an interface (linux)


code:
class SystemAdmin(ModelAdmin):
    form = SystemAdminForm

    def __init__(self, *args, **kwargs):
        super(SystemAdmin,self).__init__(*args, **kwargs)
        self.refresh()

    def refresh(self, request, obj):
        avahi = AvahiServiceDetector(self.update)

    def update(self, name, address, port):
        ip = IP.objects.get_or_create(address=address)

rawDescription: How to call some method every time user enters some model admin in django?

description: Call some method every time user enters some model admin in django


code:
#! /usr/bin/env python

from xlrd import open_workbook
from tempfile import TemporaryFile
from xlwt import Workbook
import copy

wb = open_workbook('C:\\Temp\\test.xls')
wk = wb.sheet_by_index(0)

# you need to put e=[] outside the loop in case they are reset to empty list every loop
# e is used to store final result
e = []
# f is used to store value in Col A which means we only record value once
f = []

for i in range(wk.nrows):

    b = []
    temp = None

    a = str(wk.cell(i,0).value)

    #here we only record value once
    if a in f:
        continue

    #here you should start from i+1 to avoid double counting
    for j in range(i+1, wk.nrows):
        c = str(wk.cell(j,0).value)

        if a == c:
            # you can put operations here in order to make sure they are executed only when needed

            d = str(wk.cell(j,4).value)
            k = str(wk.cell(i,4).value)

            f.append(a)

            # record all the value in Col E
            b.append(k)
            b.append(d)

            # you need to use deepcopy here in order to get accurate value
            temp = copy.deepcopy(b)

    # in your case, row 5 has no duplication, temp for row 5 will be none, we need to avoid adding none to final result
    if temp:
        e.append(temp)

book = Workbook()
sheet1 = book.add_sheet('sheet1')

n = 0
for n, item in enumerate(e):
    sheet1.write(n,0,item)
    # you don't need n+=1 here, since n will increase itself

book.save('C:\\Temp\\res.xls')
book.save(TemporaryFile())

rawDescription: Writing a list to excel

description: Writing a list to excel


code:
def say_bye(x, y):
    bye()

scrn.onclick(say_bye)

for i in range(4):
    trtl.forward(100)
    trtl.left(90)

rawDescription: Python: turtle - (exit)onclick while in infinite loop?


code:
import socket
import urllib2

try:
    handle = urllib2.urlopen(req, timeout = timeout)
except TypeError:
    socket.setdefaulttimeout(timeout)
    handle = urllib2.urlopen(req)

rawDescription: How to support multiple versions of python for urllib2?

description: Support multiple versions of python for urllib2


code:
class MyClass(object):
    def __init__(self, val):
        self.x = val   # note, this will access the property too

    @property          # use property as a decorator of the getter method
    def x(self):
        return self._x

    @x.setter          # use the "setter" attribute of the property as a decorator
    def x(self, value):
        if isinstance(value, (float, int, str)):  # accept only these types
            self._x = val
        else:
            self._x = "Error" # it might be more "Pythonic" to raise an exception here

rawDescription: Automatically update some "private" attribute whenever some other instance attribute is modified


code:
import pandas as pd
import numpy as np

# your DataFrame; df = ...

pd.rolling_apply(df, 12, lambda x: np.prod(1 + x) - 1)

rawDescription: How to calculate rolling cumulative product on Pandas DataFrame

description: Calculate rolling cumulative product on Pandas DataFrame


code:
#!/usr/bin/python

# Load the JSON module and use it to load your JSON file.
# I'm assuming that the JSON file contains a list of objects.
import json
obj  = json.load(open("file.json"))

# Iterate through the objects in the JSON and pop (remove)
# the obj once we find it.
for i in xrange(len(obj)):
    if obj[i]["ename"] == "mark":
        obj.pop(i)
        break

# Output the updated file with pretty JSON
open("updated-file.json", "w").write(
    json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
)

rawDescription: how to delete json object using python?

description: Delete json object using python


code:
import random

for pixel in pic.get_pixels(): # Replace with appropiate way of getting the pixels
    if random.random() < 0.25:
        pixel.red = random.randint(256)
        pixel.green = random.randint(256)
        pixel.blue = random.randint(256)

rawDescription: Setting the RGB levels of pixels (Python, Jython)


code:
import webapp2

class MainHandler(webapp2.RequestHandler):
  def get(self):
    self.response.headers['Content-Type'] = "text/html"
    self.response.write('''
      <form action="/upload" enctype="multipart/form-data" method="post">
        <input type="file" name="file">
        <input type="submit">
      </form>
    ''')

class UploadHandler(webapp2.RequestHandler):
  def post(self):
    file = self.request.POST['file']
    self.response.headers['Content-Type'] = "text/plain"
    self.response.write(file.value)

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/upload', UploadHandler)
  ], debug=True)

rawDescription: Retrieving .txt file contents in Google AppEngine


code:
from collections import OrderedDict
values = (2, 1, 2, 1)
list(OrderedDict.fromkeys(values))
values = (30.0, 30.0, 30.0, 15.0, 30.0)
list(OrderedDict.fromkeys(values))

rawDescription: Tuple unique elements in set changes order in Python


code:
matrix = [[0 for x in range(5)] for x in range(3)]
def my_function(input, idx1, idx2):
    matrix[idx1][idx2] = input

rawDescription: How can I change an element inside my two dimensional array in python?

description: Change an element inside my two dimensional array in python


code:
from bs4 import BeautifulSoup

with open(r'sitelist.txt') as f:
    f = f.read()

soup = BeautifulSoup(f, "html.parser")

while len(soup.find_all('span')) > 0:
    soup.span.extract()

with open(r'sitelist.txt', 'w') as f:
    f.write(str(soup))

rawDescription: Python Remove Span Tags and Overwrite Txt File


code:
def badge(request):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=somefilename.pdf'

    # Create the PDF object, using the StringIO object as its "file."
    pagesize = pagesizes.landscape(letter)
    pagewidth, pageheight = pagesize
    doc = platypus.BaseDocTemplate(filename=response, pagesize=pagesize,
            showBoundary=1)
    newHeight = doc.bottomMargin + doc.topMargin + doc.height
    newWidth = doc.leftMargin + doc.rightMargin + doc.width

    # reset margins
    doc.leftMargin = 0
    doc.bottomMargin = 0
    doc.rightMargin = 0
    doc.topMargin = 0

    # create the frames
    frames = []
    left_frame_1 = Frame(doc.leftMargin,
            doc.bottomMargin,
            newWidth / 3,
            newHeight / 6,
            showBoundary=1,
            id="left_frame_1")
    left_frame_2 = Frame(doc.leftMargin,
            doc.bottomMargin + newHeight / 6,
            newWidth / 3,
            newHeight / 6,
            showBoundary=1,
            id="left_frame_2")
    left_frame_3 = Frame(doc.leftMargin,
            doc.bottomMargin + newHeight / 6 * 2,
            newWidth / 3,
            newHeight / 6,
            showBoundary=1,
            id="left_frame_3")
    left_frame_4 = Frame(doc.leftMargin,
            doc.bottomMargin + newHeight / 6 * 3,
            newWidth / 3,
            newHeight / 6,
            showBoundary=1,
            id="left_frame_4")
    left_frame_5 = Frame(doc.leftMargin,
            doc.bottomMargin + newHeight / 6 * 4,
            newWidth / 3,
            newHeight / 6,
            showBoundary=1,
            id="left_frame_5")
    left_frame_6 = Frame(doc.leftMargin,
            doc.bottomMargin + newHeight / 6 * 5,
            newWidth / 3,
            newHeight / 6,
            showBoundary=1,
            id="left_frame_6")
    mid_frame_1 = Frame(doc.leftMargin + newWidth / 3,
            doc.bottomMargin,
            newWidth / 3,
            newHeight / 6 * 4,
            showBoundary=1,
            id="mid_frame_1")
    mid_frame_2 = Frame(doc.leftMargin + newWidth / 3,
            doc.bottomMargin + newHeight / 6 * 4,
            newWidth / 3,
            newHeight / 6 * 2,
            showBoundary=1,
            id="mid_frame_2")
    right_frame_1 = Frame(doc.leftMargin + newWidth / 3 * 2,
            doc.bottomMargin,
            newWidth / 3,
            newHeight / 6 * 2,
            showBoundary=1,
            id="right_frame_1")
    right_frame_2 = Frame(doc.leftMargin + newWidth / 3 * 2,
            doc.bottomMargin + newHeight / 6 * 2,
            newWidth / 3,
            newHeight / 6 * 3,
            showBoundary=1,
            id="right_frame_2")
    right_frame_3 = Frame(doc.leftMargin + newWidth / 3 * 2,
            doc.bottomMargin + newHeight / 6 * 5,
            newWidth / 3,
            newHeight,
            showBoundary=1,
            id="right_frame_3")

    frames.append(left_frame_1)
    frames.append(left_frame_2)
    frames.append(left_frame_3)
    frames.append(left_frame_4)
    frames.append(left_frame_5)
    frames.append(left_frame_6)
    frames.append(mid_frame_1)
    frames.append(mid_frame_2)
    frames.append(right_frame_1)
    frames.append(right_frame_2)
    frames.append(right_frame_3)

    Elements = []

    styles = getSampleStyleSheet()

    # LEFT COL CONTENT
    Elements.append(Paragraph("LEFT1, " * 10,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph("LEFT2, " * 10,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph("LEFT3, " * 10,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph("LEFT4, " * 10,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph("LEFT5, " * 10,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph("LEFT6, " * 10,
        styles['Normal']))
    Elements.append(FrameBreak())

    # MID COL CONTENT
    Elements.append(Paragraph("MID_2, " * 20,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph('''
    <para>NOTE

    (1) Please check the registration handy kit to ensure you have received
    the item(s) as marked on the cover.

    (2) The official receipt(s) for the payments you have made are enclosed.
    Please check to ensure that it was issued correctly.

    (3) You will be requested to present the appropriate coupon(s)/ ticket (s)
    for admission to lunch, banquet or other events.

    (4) The organizer nor its appointed Professional Conference Organiser shall
    not be responsible for any loss or damage to this kit

    </para>
    ''', styles['Normal']))
    Elements.append(FrameBreak())

    # RIGHT COL CONTENT
    Elements.append(Paragraph("RIGHT_1 " * 30,
        styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph('''
    <para>REGISTRATION Handy Kit

    This kit contains the checked items:

    [] Namebadge

    [] Official Receipt(s)

    [] Lunch Coupon(s)

    [] Banquet Ticket & Reply Slip

    [] Others:

    _________________________________
    _________________________________
    _________________________________
    _________________________________

    If any of the checked items are missing in your kit, please inform the
    registration counter staff
    </para>
    ''', styles['Normal']))
    Elements.append(FrameBreak())
    Elements.append(Paragraph("RIGHT_3, " * 10,
        styles['Normal']))

    doc.addPageTemplates(platypus.PageTemplate(id="TwoCol", frames=frames))
    doc.build(Elements)

    return response

rawDescription: Generating PDF using xhtml2pdf in landscape mode


code:
class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        ...
        self.textedit_desc.installEventFilter(self)
        self.lineedit_ref.installEventFilter(self)

    def eventFilter(self, source, event):
        if event.type() == QtCore.QEvent.FocusIn:
            if source is self.textedit_desc:
                self.lineedit_ref.setCursorPosition(0) # left
                self.textedit_desc.setStyleSheet(
                    "background-color: rgb(255, 255, 240);")
                self.textedit_desc.setCursorWidth(1)
                self.textedit_desc.moveCursor(13) # end of line
        elif event.type() == QtCore.QEvent.FocusOut:
            if source is self.textedit_desc:
                self.MyNeed()
                self.textedit_desc.setStyleSheet(
                    "background-color: rgb(243, 243, 243);")
                self.textedit_desc.setCursorWidth(0)
            elif source is self.lineedit_ref:
                self.MyNeed()
                self.lineedit_ref.setCursorPosition(0) # left
        return super(MainWindow, self).eventFilter(source, event)

rawDescription: Get single caret for QLineEdit and QTextEdit with focus events


code:
c1 = Counter("word")
c2 = Counter("oawrc")
[(k, c2.get(k, 0) - v) for k, v in c1.items()]

rawDescription: Looking for something like subtracting Counters to get negative keys for the difference


code:
from pandas import *
import numpy as np
a = np.array([[1, 1], [2, 3], [1, 1], [5, 4], [2, 3]])
DataFrame(a).drop_duplicates().values

rawDescription: Python: remove duplicates from a multi-dimensional array


code:
import students_code

def run(function_name, module_name):
  getattr(module_name, function_name)()
  #this will call module_name.function_name()

run("question_1", students_code)

rawDescription: Run Python Function within each Python file in a directory


code: combined = {k: Counter(A[k]) + Counter(B[k]) for k in A}

rawDescription: Python: Combine nested dictionaries using add operator


code:
import base64
# Encode password
encoded_pw = base64.b64encode(raw_pw)

# Decode password
decoded_pw = base64.b64decode(encoded_pw)

rawDescription: Obfuscate strings in Python

description: Obfuscate strings in Python


code:
self.bouton.disconnect_by_func(self.fonct)
self.bouton.set_active(False)
self.bouton.connect("clicked", self.fonct)

rawDescription: Python - ToggleButton - Possible to cancel the callback during once time?


code:
def search(search_word):
    # your search function here
    pass

# get input from the user
user_input = raw_input("What would you like to do? ").lower()
# make the code easier to reuse
search_command = "search for"

if len(user_input) > 0:
    if user_input.startswith(search_command):
        # use slices to remove the first part of the input, and then remove all whitepsace
        search_word = user_input[len(search_command):].strip()

        search(search_word)

rawDescription: How to make a the user input a command following a certain form in python?

description: Make a the user input a command following a certain form in python


code:
import sys
sys.platform

rawDescription: How to tell the difference between linux and mac

description: Tell the difference between linux and mac


code:
#!/usr/bin/python

import sys
assert len(sys.argv) > 1

apppath = sys.argv[1]

import os, os.path
assert os.path.splitext(apppath)[1] == ".app"

os.makedirs(apppath + "/Contents/MacOS")

version = "1.0.0"
bundleName = "Test"
bundleIdentifier = "org.test.test"

f = open(apppath + "/Contents/Info.plist", "w")
f.write("""<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>CFBundleDevelopmentRegion</key>
    <string>English</string>
    <key>CFBundleExecutable</key>
    <string>main.py</string>
    <key>CFBundleGetInfoString</key>
    <string>%s</string>
    <key>CFBundleIconFile</key>
    <string>app.icns</string>
    <key>CFBundleIdentifier</key>
    <string>%s</string>
    <key>CFBundleInfoDictionaryVersion</key>
    <string>6.0</string>
    <key>CFBundleName</key>
    <string>%s</string>
    <key>CFBundlePackageType</key>
    <string>APPL</string>
    <key>CFBundleShortVersionString</key>
    <string>%s</string>
    <key>CFBundleSignature</key>
    <string>????</string>
    <key>CFBundleVersion</key>
    <string>%s</string>
    <key>NSAppleScriptEnabled</key>
    <string>YES</string>
    <key>NSMainNibFile</key>
    <string>MainMenu</string>
    <key>NSPrincipalClass</key>
    <string>NSApplication</string>
</dict>
</plist>
""" % (bundleName + " " + version, bundleIdentifier, bundleName, bundleName + " " + version, version))
f.close()

f = open(apppath + "/Contents/PkgInfo", "w")
f.write("APPL????")
f.close()

f = open(apppath + "/Contents/MacOS/main.py", "w")
f.write("""#!/usr/bin/python
print "Hi there"
""")
f.close()

import stat
oldmode = os.stat(apppath + "/Contents/MacOS/main.py").st_mode
os.chmod(apppath + "/Contents/MacOS/main.py", oldmode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)

rawDescription: How to create Mac application bundle for Python script via Python

description: Create Mac application bundle for Python script via Python


code:
import re
with open("giantfile.txt") as infile:
    print(re.findall("[A-Za-z]+", infile.read()))

rawDescription: How to search for characters present in a file in python?

description: Search for characters present in a file in python


code:
viewmodel = MyViewModel()
Messenger.Default.Send[ViewModelBase](viewmodel)

rawDescription: Boxing to type in ironpython

description: Boxing to type in ironpython


code:
import numpy as np
# initialise some data with None in it
a = np.array([1, 2, 3, None])
a = np.where(a == np.array(None), 9999, a)

rawDescription: Recode missing data Numpy

description: Recode missing data Numpy


code:
import re
#Search for numbers
r = re.compile('[0-9]{1,}')
s = 'M 100 200 L 120 180 L 80 140 L 80 180 z'
r.findall(s)
#Returns a list of strings having numbers
['100', '200', '120', '180', '80', '140', '80', '180']
#Map the results to int to get integers
map(int, r.findall(s))
#Returns a list of integers
[100, 200, 120, 180, 80, 140, 80, 180]

rawDescription: Reading and Storing the lines in XML file


code:
another_dict = {}
counters = {}
for key,value in dict.items():
    counter = counters.get(value, 0) + 1
    counters[value] = counter
    another_dict[key] = "%s_%d" % (value, counter)

rawDescription: How to append an increasing number to a dictionary values?

description: Append an increasing number to a dictionary values


code:
a = []
for q in sorted((set(q) for q in sort), key=len, reverse=True):
    if not any(q.issubset(Q) for Q in a):
        a.append(q)
a = [list(q) for q in a] # Back to lists, if you want

rawDescription: Python sort unique list of lists' items

description: Python sort unique list of lists' items


code:
x = re.findall(r'(?s)\$\s*(.*?)(?=\$)', lines)
[i.splitlines() for i in x]

rawDescription: python - find text between two $ and get them into a list

description: Python - find text between two $ and get them into a list


code:
def _foreign_id_rel(Cls):
    return relationship(
        Cls,
        uselist=False,
        lazy=False,  # This is just my use case, not needed
        primaryjoin=lambda: and_(
            Diff.foreign_table == Cls.__tablename__,
            foreign(Diff.foreign_id) == Cls.id,
        ),
        backref=backref(
            'diffs',
            uselist=True,
            lazy=True,  # This is just my use case, not needed
            primaryjoin=lambda: and_(
                Diff.foreign_table == Cls.__tablename__,
                foreign(Diff.foreign_id) == Cls.id,
            ),
        ),
    )

class Diff(Model):
    ...

    foo = _foreign_id_rel(Foo)
    bar = _foreign_id_rel(Bar)
    baz = _foreign_id_rel(Baz)

    @property
    def foreign(self):
        if self.foreign_table:
            return getattr(self, self.foreign_table)

    @foreign.setter
    def foreign(self, value):
        if value is None:
            self.foreign_table = None
            self.foreign_id = None
        else:
            tbl_name = value.__tablename__
            self.foreign_table = tbl_name
            setattr(self, tbl_name, value)

rawDescription: Relationship to different tables in SQLalchemy


code:
float('NaN')
float('Inf')
-float('Inf')
float('Inf') == float('Inf')
float('Inf') == 1

rawDescription: python nan and inf values

description: Python nan and inf values


code:
import codecs
f = codecs.open('/home/portugues/teste.txt', encoding='utf-8')
test = f.read().split(' ')

rawDescription: Program in Python doesn't match equal words


code:
def __contains__(self, e):
    return e in self.segments or any(e in x for x in self.segments)

rawDescription: Element is in container or in a container within the container. (Python)


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

delta_Array = np.array([0.01,0.02,0.03, 0.04, 0.05,
                        0.06,0.07, 0.08, 0.09, 0.10])
#Initialized to 0s. Actual values will be appended to matrix by function
theta_Matrix = np.random.random() * np.random.rand(delta_Array.size, 8)

fig = plt.figure()
p1 = plt.plot(delta_Array, theta_Matrix)
# make a legend for both plots
leg = plt.legend(p1, '', loc=1)

plt.show()

rawDescription: Plotting values in matrix corresponding to the index in an array with Matplotlib in Python


code:
import filters

filter_list = [(2, filters.filterA), (1, filters.filterB)]

data_list = ['A', 'B' , 'C' , 'D']

def nFilter(filters, my_list):
    for _, f in sorted(filters):
        my_list = ifilter(f, my_list)
    return my_list  # or list(my_list) if you actually want a list

rawDescription: How do you design python filter function to be able to sort using addition attribute?

description: Design python filter function to be able to sort using addition attribute


code:
import Tkinter as tk
...
image_link = tk.Label(text_widget, image=my_image, cursor="left_ptr")
image_link.bind("<1>", do_something)
text_widget.window_create("insert", window=image_link)

rawDescription: image as hyperlink in python / Tkinter

description: Image as hyperlink in python / Tkinter