code:
s = """
    def find_nodes(graph):
        # get the distinct nodes from the edges
        nodes = []
        l = len(graph)
        for i in range(l):
            edge = graph[i]
            n1 = edge[0]
            n2 = edge[1]
            if n1 not in nodes:
                    nodes.append(n1)
            if n2 not in nodes:
                    nodes.append(n2)
            return nodes

    graph = ((1,2),(2,3), (3,1))
    print find_nodes(graph)

"""

rawDescription: Python: Why is one element in this list not being printed?


code:
parts = line.strip.split(", ") #each item in the line
obj = Object(parts[0], parts[1]) #like doing Objects(item1, item2) from the line.
objects.append(obj) #add the object to the list

rawDescription: getting strings from files split

description: Getting strings from files split


code:
closes = resampledData['close'].fillna(method='pad')
resampledData.apply(lambda x: x.fillna(closes))

rawDescription: Resampling OHLC tick data and filling gaps in Pandas


code:
def removeMag():

    countMag = 0
    for mag in kept:
        if to_float(mag['M_P']) > -4.5:
            kept.remove(mag)
            countMag += 1

rawDescription: Python ignoring command to remove items from list


code:
# Pass 1 - raw load

for row in csv.reader:
    new= NewModel.create( **row )

# Pass 2 - resolve FK's

for nm in NewModel.objects.all():
    ref1= OtherModel.objects.get( old_id=nm.old_at_fk )
    nm.properfk = ref1
    nm.save()

rawDescription: Fill Django application with data using very large Python script


code:
def foo(x):
    print(x)

rawDescription: Can a python module read variables from the main program


code: cd /path/to/something

rawDescription: What is IPython automagic?

description: What is IPython automagic


code:
s = "foo0?"
re.search(r'[a-zA-Z\d]', s)
s = "???"
re.search(r'[a-zA-Z\d]', s)
s = "???0"
re.search(r'[a-zA-Z\d]', s)

rawDescription: Check if one character in string is numeric or is a letter [Python]


code:
keyword = 'user'
newuser = 'PeterB'
with open('test.txt') as infile, open('updated.txt', 'w') as outfile:
    for line in infile.readlines():
        words = line.split()
        try:
            index = words.index(keyword) + 1
            words[index] = newuser
            outfile.write('{}\n'.format(' '.join(words)))
        except (ValueError, IndexError):
            outfile.write(line)    # no keyword, or keyword at end of line

rawDescription: Change log file with index

description: Change log file with index


code:
from collections import OrderedDict

keyvals = OrderedDict([
    ('taxdec','landproperty__ctaxdec'),
    ('brgy', 'ssectionid__sbrgyid__cbrgyname')
])

m = ButuanMaps.objects.filter(clandpin=getpin).values_list(*keyvals.values())
result = dict(zip(keyvals, zip(*m)))

rawDescription: Passing multiple value_list in Django

description: Passing multiple value_list in Django


code: my_insort_left(data, ('brown', 7), key=lambda v: v[1])

rawDescription: Python: Using bisect.insort with key

description: Python: Using bisect.insort with key


code:
from scaly.all import *

Packets = rdpcap("pcapfile")
srcList = [pkt[1].src for pkt in Packets]

rawDescription: Speed up python loop processing packets

description: Speed up python loop processing packets


code:
class Foo(wamp.ApplicationSession):
    @subscribe_coro('wamp.metaevent.session.on_join')
    @coroutine
    def bar(self):
        baz = yield from self.call('baz')

    @register('baz')
    def baz(self):
        return 'baz'

rawDescription: Calling a remote procedure from a subscriber and resolving the asyncio promise


code:
def foo(var1, var2):
    global bar
    from mainmodule import fubar
    bar = fubar(var1)

rawDescription: Python - Assign global variable to function return requires function to be global?


code: import regex

rawDescription: How to split string by space and treat special characters as a separate word in Python?

description: Split string by space and treat special characters as a separate word in Python


code:
n=0
for whatever in whatever: # e.g. your for loops
    # do stuff with whatever
    if n==0:
        plt.plot(sorted_data,cdf,color='r',marker='o',label='set 1')
    else:
        plt.plot(sorted_data,cdf,color='r',marker='o')
    n += 1

rawDescription: Multiple legends and multiple colors/shapes matplotlib


code: sorted([int(raw_input().split()[0]) for _ in range(int(raw_input()))])

rawDescription: Python taking paired string and integer input


code:
with gzip.GzipFile('data.gz', 'w') as datafile:
    datafile.write(', '.join(a.dtype.names) + '\n')
    numpy.savetxt(datafile, a, '%i, %s, %s')

rawDescription: Using python dtype as headers for compressed csv


code: returns = df.pct_change()

rawDescription: I want to find the Covariance between 1 column with all the other columns in a dataframe in pandas


code:
f = lambda obj: set(obj[['C', 'D']].values.ravel())
df.groupby(['B', 'A']).apply(f).unstack()

rawDescription: Pandas DataFrame column to cell in pivot table


code:
color_map_name = "spectral"
color_func = getattr(matplotlib.cm, color_map_name)
color = color_func(np.linspace(0,1,100))

rawDescription: How to let user pick colormap?

description: Let user pick colormap


code:
import tkinter as tk

filename = "test.txt"

class Text(tk.Text):
    def destroy(self):
        global ending_text
        ending_text = self.get("1.0","end-1c")
        super(Text,self).destroy()
try:
    with open(filename) as f:
        text = f.read()
except IOError:
    text = ""

root = tk.Tk()

textbox = Text(root)
textbox.insert("1.0",text)
textbox.grid()

#this would probably just be put in the destroy method
def finish(event=None):
    with open(filename,"w") as f:
        f.write(ending_text)

textbox.bind("<Destroy>",finish) #this will happen after Text.destroy() so textbox.get() fails if used from this point
root.mainloop()

rawDescription: Integrating file and text widget python/tkinter


code:
import numpy as np
def erat2(n):
    ar = np.ones(n, dtype=bool)
    ar[0] = ar[1] = False
    ar[4::2] = False
    for j in xrange(3, n, 2):
            if ar[j]:
                    ar[j**2::2*j] = False
    return ar.nonzero()[0]

timeit.timeit('erat2(10000)', 'from __main__ import erat2', number=1000)

rawDescription: Is this more efficient than Sieve of Eratosthenes?


code:
type('')
from __future__ import unicode_literals
type('')

rawDescription: (unicode error) 'unicodeescape' codec can't decode bytes - string with '\u'


code: next((suffix for suffix in suffix_tuple if input_string.endswith(suffix)), None)

rawDescription: Python: Check which tuple item string ends with, if it ends with one at all


rawDescription: Un-"jQuery $.param" in Server Side Python (GAE)


code:
import pyperclip
fo = open(path, 'r').read()
pyperclip.copy(fo)

rawDescription: How to copy content inside of a txt file to clipboard?

description: Copy content inside of a txt file to clipboard


code:
from django import template
from accounts.forms import AuthenticationForm

register = template.Library()

@register.inclusion_tag('_tag_auth_form.html')
def authentication_form():
    return {'form': AuthenticationForm(), 'action': '/some/url'}

rawDescription: In Django how to create a template tag that renders a login form?


rawDescription: Unpacking a list / tuple of pairs into two lists / tuples


code:
import requests
from bs4 import BeautifulSoup
for i in range(0, 3339, 48):
    r = requests.get("http://www.snapdeal.com/acors/json/product/get/search/175/{}/48".format(i))
    print([a["href"] for a in BeautifulSoup(r.content).select("div.product-desc-rating.title-section-expand a")])

rawDescription: Get complete source code from a website generated on clicking a button


code:
prices = []
for item in world_dict:
     if item[1] == 'House':
       price = float(item[2])
       prices.append(price)

print(price)

rawDescription: Python - Store a value in an array inside one for loop


rawDescription: python 2.4 sorting a text file by specific column

description: Python 2.4 sorting a text file by specific column


code:
codes = sorted( d['code'] for d in L )
codes

rawDescription: How to create list based on elements from dictionary?

description: Create list based on elements from dictionary


code: marks

rawDescription: Replacing values in csv by using python

description: Replacing values in csv by using python


code:
mapped_and_filtered = [x*2 for x in lst if x < 5]
# compare to:
mapped_and_filtered = map(lambda y: y*2, filter(lambda x: x < 5, lst))

rawDescription: Python equivalent of Ruby's .select

description: Python equivalent of Ruby's .select


code: yield Request(url, callback=self.detail, meta={'item': item})

rawDescription: Scrapy: Passing item between methods

description: Scrapy: Passing item between methods


code:
if not any(s in item for s in ("string1", "string2", "string3", "string4")):
    doSomething(item)

rawDescription: How to break the line in a python if statement without a syntax error?

description: Break the line in a python if statement without a syntax error


code: literal_eval("import os; os.system('rm -rf somepath')")

rawDescription: Converting ConfigParser values to python data types


code:
for obj in qs:
    obj._timedelta = timedelta(microseconds=obj.sum)

rawDescription: Using django 1.8 duration field to annotate a set of django objects


code: '[%s]' % ','.join(test.splitlines())

rawDescription: pandas - reading multiple JSON records into dataframe

description: Pandas - reading multiple JSON records into dataframe


code:
import commands
output = commands.getstatusoutput('lsusb')

rawDescription: What is the easiest way to get an usb-drive unique id with python on linux?


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

fig = plt.figure()
x = np.linspace(-1, 1, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()

rawDescription: Keeping multiple figures open with matplotlib after script is executed


code: my_xaxis.set_major_locator(FixedLocator([x * 1E13 for x in range(1,10)]))

rawDescription: Set ticks that aren't at powers of some base on a loglog plot


code:
def function_to_test():
    def inner_func():
        return open('/tmp/somefile').read()
    return True, inner_func

rawDescription: Mocking not working with pytest and flexmock


code:
with open("example.txt","r") as first, open("output.txt","r") as second:
    result = [(word1, word2) for line1, line2 in zip(first, second) for word1, word2 in zip(line1.split(), line2.split())]

rawDescription: How to approach for a list comprehension solution?

description: Approach for a list comprehension solution


code: df.fillna('', downcast='infer')

rawDescription: Pandas Pivot table converts float to int


rawDescription: How to split dictionary into multiple dictionaries fast

description: Split dictionary into multiple dictionaries fast


code:
d = {('i2', 'i3'): '4', ('i1',): '1',('i1', 'i3', 'i4'): '6.5', ('i3',): '3',
     ('i1', 'i2', 'i3'): '4.5', ('i2',): '2', ('i4',): '4'}
from itertools import combinations
combos = list(combinations(d, 4)) # you should try combos of different lenghts,
                                  # from 1 to the number of desired items

rawDescription: Optimized output from the python dictionary


code: vars(object())

rawDescription: How can I create a separate namespace within a Python script?

description: Create a separate namespace within a Python script


rawDescription: Stripping text from one point to another in python


code:
def make_server(
    host, port, app, server_class=WSGIServer, handler_class=WSGIRequestHandler):
    """Create a new WSGI server listening on `host` and `port` for `app`"""
    server = server_class((host, port), handler_class)
    server.set_app(app)
    return server

rawDescription: Control wsgiref simple_server log

description: Control wsgiref simple_server log


rawDescription: Extend index on business day range

description: Extend index on business day range


code: all_tds = [td for td in soup.findAll("table", bgcolor="#ffffff")]

rawDescription: "td" before "for" loop

description: "td" before "for" loop


code:
import csv

filter_string = self.delName.get("1.0","end-1c")

with open("userDatabase.csv", "r", newline='') as myFile:
    with open("newFile.csv", "w", newline='') as newFile:
        writer = csv.writer(newFile)
        for row in csv.reader(myFile):
            # row is now a list of strings, like ['lukefinney', '0000000', '0000000', 'a']

            if filter_string != row[0]:  # test against the first column
                # copied across if the first column does not match exactly.
                writer.writerow(row)

rawDescription: Python 3.4 CSV Deleting items using the in function


code: test = ts.groupby([ts.index.month, ts.index.day]).mean()

rawDescription: Get the average year (mean of days over multiple years) in Pandas


code:
def filterAcceptsRow(self, row, parent):
    if not self.filterActive or '_B_' in self.sourceModel().data(self.sourceModel().index(row, 0), Qt.DisplayRole).toPyObject():
        return True
    return False

rawDescription: How to select QTableView index or row from inside of Model

description: Select QTableView index or row from inside of Model


code:
for token in tokenize(string):
    ...

rawDescription: Match open and close brackets in garbled string


code:
phone = models.CharField(max_length=20, blank=False)
mobile = models.CharField(max_length=20, blank=False)

rawDescription: Multiple User types with Django 1.5, custom fields and shared auth


code: [(c, d.get(c)) if d.get(c) else c for c in s]

rawDescription: Get ALL results of a word mapping with a dictionary


code:
np.put(b, a, a)
#      ^  ^  ^
#      |  |  |
# Target  |  |
#   Indices  |
#       Values

rawDescription: inserting numpy data into a bigger array of zeros

description: Inserting numpy data into a bigger array of zeros


code:
for letter in 'hello':
  print(letter)

rawDescription: If I use a for loop with a string, will it check character by character?


code: unique = set(map(set, list_of_lists))

rawDescription: Deleting duplicates from a list of lists if some duplicates do not have the same order


code:
while alive == True:
    p = input("Type w")
    rollA = randomA()
    if p == "w":
        print(rollA)

rawDescription: Python random variable not working

description: Python random variable not working


code:
import cv2
import numpy as np
img = cv2.imread('img.png')
vis = np.concatenate((img1, img2), axis=1)
cv2.imwrite('out.png', vis)

rawDescription: Combining Two Images with OpenCV

description: Combining Two Images with OpenCV


code:
def getLog(timestamp):
    dummy_entry = LogEntry(timestamp, '')
    index = bisect.bisect_right(logs, dummy_entry)
    return logs[index:]

rawDescription: simple way to search a list ordered by integer timestamps

description: Simple way to search a list ordered by integer timestamps


code:
t = ['2925729', 'Patrick did not shake our hands nor ask our names. He greeted us promptly and politely, but it seemed routine.']
[ [t[0], a + '.'] for a in t[1].rstrip('.').split('.')]

rawDescription: Python break list values into sub-components and maintain key


code:
data = f.read()
process(data)

rawDescription: Process large data in python

description: Process large data in python


code:
old_df.registerTempTable('old_df')
new_df = sqlContext.sql('SELECT *, col_1 - col_2 AS col_n FROM old_df')

rawDescription: Adding a new column in Data Frame derived from other columns (Spark)


code:
import requests

response = requests.head("http://www.example.com/")
if response.status_code == 200:
    print(response.elapsed)
else:
    print("did not return 200 OK")

rawDescription: HTTping in python

description: HTTping in python


rawDescription: PyGTK: When filtering keyboard input to an Entry widget, can't correctly set the cursor position while opening a large buffer


rawDescription: How to determine pid of process started via os.system

description: Determine pid of process started via os.system


code:
from itertools import count
numbers = []
c = count(0.0, 0.0001)
how_many = 10
while len(numbers) != how_many:
  numbers.append(round(next(c), 4))

numbers

rawDescription: Rounding values for normalised variables


code: send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, [self.user.email])

rawDescription: send activate-email with django-registration

description: Send activate-email with django-registration


rawDescription: How to shift bits in a 2-5 byte long bytes object in python?

description: Shift bits in a 2-5 byte long bytes object in python


code:
from scrapy.contrib.loader import ItemLoader
from scrapy.contrib.loader.processor import TakeFirst, MapCompose

class TargetLoader(ItemLoader):
    default_output_processor = TakeFirst()

rawDescription: curly bracket issue when inserting scrapy crawler results to postgresql

description: Curly bracket issue when inserting scrapy crawler results to postgresql


rawDescription: Contour plot in Python importing txt table file


rawDescription: Understanding numpy "void" dtype and generic arrays


code:
a = ['jhfewrgjhdfjhgsufgssdfjgh;NR;3243;fgjdsgfjsdfkjgdf', 'dsafjhsafjkhefhajwejh;NR;123;dfgdsrhgjhdfgjhdsfjhg']
a.sort(key=lambda x: x.split(';')[2])
a

rawDescription: Python sort list by regular expression

description: Python sort list by regular expression


code:
from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

rawDescription: Python - from . import

description: Python - from . import


code:
totals = (pattern.match(key) for key in cgi_keys)
totals = [match.groups() for match in totals if match]

rawDescription: Can this python code be expressed with list comprehension?


code:
def convert(d):
    res = {}
    for x in d:
        key = (x['user'], x['id'])
        if key in res:
            res[key]['key'].append(x['key'])
            res[key]['value'].append(x['value'])
        else:
            x['key'] = [x['key']]
            x['value'] = [x['value']]
            res[key] = x

    return res.values()

rawDescription: Merge dicts from a list of dicts based on some key/value pair


code: my_func_vec(a, b)

rawDescription: vectorize a function for numpy, that correlates each element of one vector with each element of another

description: Vectorize a function for numpy, that correlates each element of one vector with each element of another


rawDescription: Python: How to return list of booleans to see if elements of one list in another list


code:
themap={"one":1, "two":2}   # make a dictionary
themap["one"]    # evaluates to the number 1

rawDescription: A map of string replacements in Python2.7


code:
expand_ranges("1-5")
expand_ranges("1,3")
expand_ranges("1")
expand_ranges("1,3-5")
expand_ranges("1-3,5,7-8")
expand_ranges("0,2-5,7-8,10,14-18")

rawDescription: How to interpret a list of numbers from a string?

description: Interpret a list of numbers from a string


code:
mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
    my_string = my_string.replace(k, v)

rawDescription: A list of string replacements in Python

description: A list of string replacements in Python


code:
# Read the file into an array
filedata = np.loadtxt('filename')

# Build a list with all the Prisms
models = []
for x1, x2, y1, y2, z1, z2, ρ in filedata:
    models.append(Prism(x1, x2, y1, y2, z1, z2, {'density': ρ}))

rawDescription: How to correctly call variables from a txt file into my python code?

description: Correctly call variables from a txt file into my python code


code:
bool(b)
True >= 0

rawDescription: iterating over lists finding standard deviation of each point

description: Iterating over lists finding standard deviation of each point


code:
result = {}
for key, lst in data.items():
    result[key] = [lst[0], {k: (lst[0], float(v)/lst[0]) for k, v in lst[1].items()}]

rawDescription: Divide dictionary values by another value in the same key in Python


code: [open(str(found.index(f)+1)+'.txt', 'w').write(f) for f in found]

rawDescription: How can I split a text file into multiple text files using python?

description: Split a text file into multiple text files using python


code:
def pretty_print(item_list, indentation = ""):

        temp = []
        for items in item_list:
            if isinstance(items, list):
                temp.append( pretty_print(items, indentation = indentation+"  "))
            else:
                temp.append( indentation + str(items) + '\n')

        return ( ''.join(temp ) )

rawDescription: pretty print a list using recurison returning single item in a list

description: Pretty print a list using recurison returning single item in a list


rawDescription: Can you get a guest OS using PySphere?

description: Get a guest OS using PySphere


code:
# Took a page out of TokenMacGuy, credit to him
distribution = []
distribution.append(0.00)
total = 0.0 # Create a float here

for entry in my_list:
    distribution.append(entry[1])
    total += frequency
    total = round(total, 3) # Rounding to 2 decimal points

distribution.append(1.00) # Missing the 1.00 value
print(distribution) # Print to check

rawDescription: what is a good way of setting up ranges on a number line?

description: What is a good way of setting up ranges on a number line


code: return '', 204

rawDescription: Flask appropriate response for POST without template?


code:
def gematric_value(word):
    """Sum of numerical values of word's characters.

    a -> 1, b -> 2, c -> 3; A -> 1, B -> 2, etc
    """
    # word is a string; iterating over it produces individual "characters"
    # iterate over lowercased version of the word (due to A == a == 1)
    return sum(ord(c) - ord('a') + 1 for c in word.lower())

rawDescription: Gematria with a list of words

description: Gematria with a list of words


code:
import numpy as np
a = np.array([True, False])
b = np.array([True, True])

np.logical_and(a,b)
np.logical_and(b,a)

rawDescription: Boolean list operation in python

description: Boolean list operation in python


code: mask

rawDescription: trying to mask 2D numpy arrays based on values in one column

description: Trying to mask 2D numpy arrays based on values in one column


code:
l = ['a\n', 'b\n', 'c\n']
no_ns = [var.rstrip() for var in l]
no_ns

rawDescription: Importing file as list. \n after every item


code:
import os
import subprocess

cmd = [os.path.realpath('./sa.py'), '--track', '12']

print('shell False')
subprocess.call(cmd)
print()
print('shell True')
subprocess.call(cmd, shell=True)

rawDescription: python 3: subprocessing a python script that uses argparse

description: Python 3: subprocessing a python script that uses argparse


code:
import base64

def num_to_alpha(num):
    num = hex(num)[2:].rstrip("L")

    if len(num) % 2:
        num = "0" + num

    return base64.b64encode(num.decode('hex'))

rawDescription: Encoding a numeric string into a shortened alphanumeric string, and back again


code:
def mult(mtx_a,mtx_b):
    tpos_b = zip( *mtx_b)
    rtn = [[ sum( ea*eb for ea,eb in zip(a,b)) for b in tpos_b] for a in mtx_a]
    return rtn

rawDescription: matrix using python

description: Matrix using python


code:
DATABASES = {
    'default': {},
    'master': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': 5432,
    },
    'slave': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '',
        'USER': '',
        'PASSWORD': '',
        'HOST': '',
        'PORT': 5432,
    }
}
SLAVE_DATABASES = ['slave']

DATABASE_ROUTERS = ['path.to.your.routers.MasterSlaveRouter']

rawDescription: Django multiple DB how to write router

description: Django multiple DB how to write router


code: ls -l /usr/local/bin/python

rawDescription: Python installation missing a lot of things on Mountain Lion


code:
x = 42
def wont_work():
    x = x + 1
wont_work()

rawDescription: How can I insert all the variable in a function automatically in python?

description: Insert all the variable in a function automatically in python


code: tsod.to_html(open('my_file.html', 'w'))

rawDescription: save pandas' to_html' as a file

description: Save pandas' to_html' as a file


code:
data=json.load(urllib2.urlopen("http://eu.battle.net/api/wow/realm/status"))
type(data)
data.keys()
type(data['realms'])
type(data['realms'][0])
data['realms'][0].keys()
data['realms'][0]['name']
[realm['name'] for realm in data['realms']].index('Silvermoon')
silvermoon= data['realms'][212]
silvermoon['population']
type(silvermoon['wintergrasp'])
silvermoon['wintergrasp'].keys()
silvermoon['wintergrasp']['controlling-faction']
silvermoon['population']

rawDescription: Navigating Multi-Dimensional JSON arrays in Python


code:
for a,b,c in itertools.product((0,1), repeat=3):
    print(f"[({a},{b}),({c},{a})]")

rawDescription: plugging in values for each variable in a string

description: Plugging in values for each variable in a string


code: y = [doc[-1] for doc in training_data] # ['POS', 'NEG', 'NEU']

rawDescription: How to vectorize labeled bigrams with scikit learn?

description: Vectorize labeled bigrams with scikit learn


code:
import datetime as DT
import dateutil.parser as DP

today = DT.datetime(2016, 4, 13)
for text in ('today', 'tomorrow', 'this Sunday', 'Wednesday next week',
             'next week Wednesday',
             'next thursday', 'next tuesday in June', '11/28',
             'Concert this Saturday'
             "lunch with Andrew @ Mon Mar 7, 2016",
             'meeting on Tuesday, 3/29'):
    dp_date = DP.parse(text, default=today, fuzzy=True)
    print('{:35} --> {}'.format(text, dp_date))

rawDescription: python - extract dates from text by giving as parameter the date of reference which is not the current date

description: Python - extract dates from text by giving as parameter the date of reference which is not the current date


code:
f = open("file.txt",'r')
lines = f.readlines()
f.close()

excludedWord = "whatever you want to get rid of"

newLines = []
for line in lines:
    newLines.append(' '.join([word for word in line.split() if word != excludedWord]))

f = open("file.txt", 'w')
for line in lines:
    f.write("{}\n".format(line))
f.close()

rawDescription: Deleting a specific word from a file in python


code: import simplejson as json

rawDescription: Very simple JSON decoding

description: Very simple JSON decoding


code:
from decimal import *
x = Decimal('2606.8950000000001')
'{}'.format(x.quantize(Decimal('.01'), rounding=ROUND_HALF_EVEN))

rawDescription: Rounding a number in python but keeping ending zeros


code:
def describe(obj):
    for key in dir(obj):
        try:
            val = getattr(obj, key)
        except AttributeError:
            continue
        if callable(val):
            help(val)
        else:
            print('{k} => {v}'.format(k = key, v = val))
        print('-'*80)

pixmap = QtGui.QPixmap(FILENAME)
describe(pixmap)

rawDescription: How to load and show a rescaled image with pyqt4

description: Load and show a rescaled image with pyqt4


code:
def nested(flat, level=0):
    for k, it in itertools.groupby(flat, lambda x: x.split("-")[level]):
        yield next(it)
        remainder = list(nested(it, level + 1))
        if remainder:
            yield remainder

rawDescription: How to build a nested list from a flat one in Python?

description: Build a nested list from a flat one in Python


code:
update_task_state = DDL('''\
CREATE TRIGGER update_task_state UPDATE OF state ON obs
  BEGIN
    UPDATE task SET state = 2 WHERE (obs_id = old.id) and (new.state = 2);
  END;''')
event.listen(Obs.__table__, 'after_create', update_task_state)

rawDescription: Trigger in sqlachemy

description: Trigger in sqlachemy


code: norm = 1

rawDescription: How to update 3D arrow animation in matplotlib

description: Update 3D arrow animation in matplotlib


code:
def remove(self, tabToAdd, name):
    self.removeTab(0)
    self.addTab(tabToAdd, "%s" %(name))

rawDescription: Get the value from a variable

description: Get the value from a variable


code:
data['people']
data['ldap_data']

rawDescription: dict.update overwrites existing keys, how to avoid?

description: Dict.update overwrites existing keys, how to avoid


code: CONST_NAME = "Name"

rawDescription: How to create a constant in Python

description: Create a constant in Python


code: fact = lambda x: 1 if x == 0 else x * fact(x-1)

rawDescription: Can a lambda function call itself recursively in Python?


rawDescription: Select specified month date from numpy array (datetime object)


code:
class myset(MutableSet):
    def __init__(self, iterable=()):
        self.dictset = {}
        self.dictset.update(iterable)

    def __bomb__(s, *a, **k): raise NotImplementedError
    add = discard = __contains__ = __iter__ = __len__ = __bomb__

rawDescription: How to avoid rehashing dict keys?

description: Avoid rehashing dict keys


rawDescription: Python: most efficient way to convert date to datetime


code: {'BOB': [['AUDI', 'BLACK', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}], ['MINI', 'PINK', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}], ['VW', 'BLUE', 'DIESEL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}]], 'DAVE': [['BMW', 'PURPLE', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}], ['VOLVO', 'GREY', 'PETROL', {'ALLOY': 17, 'SUNROOF': 'YES', 'TYRE': 'RUBBER'}]]}

rawDescription: Append a Dict to a Dict

description: Append a Dict to a Dict


code: from pygal import *

rawDescription: Include a library in python application

description: Include a library in python application


code:
s = set()
s.add(a)
s.add(b)
for i in s:
    i()

rawDescription: Can I add function references to a list, and iterate over this list calling each in succession?

description: Add function references to a list, and iterate over this list calling each in succession


code:
states
cities

rawDescription: Python read file and assign split list data to dictionary


rawDescription: Locating index of item via REGEX in Python


code:
from string import digits
from random import choice

def digit_string(length):
    return "".join(choice(digits) for _ in range(length))

rawDescription: Typo - For loop not working correctly with argument


code:
def f1(mList):
    mList.append('BLAH' + str(len(mList)))
    f2(mList)

def f2(mList):
    for item in mList:
        print ('Printing from f2')
        print (item)
    print()

myList = []
f1(myList)
f1(myList)
f1(myList)

for item in myList:
    print ('Printing from MAIN')
    print (item)

rawDescription: Reusing a list in a new function

description: Reusing a list in a new function


code: get_rank(y, value_to_check)

rawDescription: Finding where a value lands between two numbers in Python


code:
def split_string(source,separators):
    return re.split('|'.join(re.escape(x) for x in separators),source)

split_string("the;foo: went to the store",':;')
split_string("the;foo: went to the store",['foo','st'])

rawDescription: Splitting Strings in Python with Separator variable


code:
s = ttk.Style()
s.theme_use('clam')
s.configure('TMenubutton', background='white')

rawDescription: Modify Default Ttk Clam Widget Colors

description: Modify Default Ttk Clam Widget Colors


code:
node_names = ['IntDir', 'Outputs', ...]
nodes = []
for node_name in node_names:
    nodes += dom.getElementsByTagName(node_name)

for node in nodes:
    ...

rawDescription: getElementsByTagName code optimization

description: GetElementsByTagName code optimization


code: lo, hi = heapq.heappop(tree), heapq.heappop(tree)

rawDescription: Why does a label permutation produce a different Huffman code?


code:
data['ok'] = True
data['component_list'] = component_list
return HttpResponse(json.dumps(data, cls=MyEncoder),  content_type='application/json')

rawDescription: Django: Serialize to JSON a dictionary with items that can include querysets


code:
def chunkIt(seq, num):
  avg = len(seq) / float(num)
  out = []
  last = 0.0

  while last < len(seq):
    out.append(seq[int(last):int(last + avg)])
    last += avg

  return out

rawDescription: splitting a list of arbitrary size into only roughly N-equal parts

description: Splitting a list of arbitrary size into only roughly N-equal parts


code:
from Crypto.Cipher import AES
import base64
obj = AES.new('yoursecretkeyABC')
x = base64.encodestring(obj.encrypt("%016d"%1))
x

rawDescription: How to calculate a short fixed length obfuscated ID similar to YouTube (e.g. 2WNrx2jq184)

description: Calculate a short fixed length obfuscated ID similar to YouTube (e.g. 2WNrx2jq184)


code:
jvmData = "..." #the string holding the data
jvmLines = jvmData.split("\n") #a list of the lines in the string
lines = [l.strip() for l in jvmLines if "name=" in l] #filter all data lines
result = {}
for line in lines:
    data = dict(s.split("=") for s in line.split(", "))
    #the value is in "current" for HeapSize or in "count" otherwise
    value = data["current"] if data["name"] == "HeapSize" else data["count"]
    result[data["name"]] = value

rawDescription: Create name value pairs in python

description: Create name value pairs in python


rawDescription: Python 3 string formatting with filler more than one character long


code:
class ClientList(Resource):
    def get(self):
       return [client_marshal(client) for client in model.Client.query.all()]

rawDescription: Flask-RESTful - don't return object property instead of returning null


rawDescription: How to convert a for loop output into a list (python)

description: Convert a for loop output into a list (python)


code: {k:[x[0] for x in foo[k]] for k in foo}

rawDescription: Accessing nested tupels in dictionary values


code:
import numpy as np

# a simple linear relationship: y = mx + c with m=0.5 and c=2
x = np.arange(50)
y = x * 0.5 + 2
y += np.random.randn(50) * 5    # add some noise

# we can rewrite the line equation as y = Ap, where A=[[x, 1]] and p=[[m], [c]]
A = np.c_[x, np.ones(50)]

# solving for p gives us the slope and intercept
p, residuals, rank, svals = np.linalg.lstsq(A, y)

rawDescription: Scipy.optimization linear function approximation


code:
soup = BeautifulSoup(html)

print([a["href"] for a in soup.select("a[href^=http]")])

rawDescription: Python: searching through html file grabbing <a> tags with the href and text content


code: from functools import reduce

rawDescription: Python: Functionally Merging Two Iterators Where One is Recursive


code:
a = 1
b = a
a = 2
b

rawDescription: Types for which "is" keyword may be equivalent to equality operator in Python


code:
data = bytes([154, 155, 156, 157])
print (data.decode('cp437')) # use decode for printing
with open('output.dat', 'wb') as f:
    f.write(data) # but not for writing to a file
with open('output.dat', 'rb') as f:
    data = f.read()
    print(data)
    print(data.decode('cp437'))

rawDescription: encrypting a string via binary manipulation

description: Encrypting a string via binary manipulation


code: import sys

rawDescription: How to use import statement for custom modules in Python

description: Use import statement for custom modules in Python


code:
shuffle(df.columns.values)
df
new_order = preordered + list(df.columns - preordered)
new_order

rawDescription: how to sort only some of the columns in a data frame in pandas?

description: Sort only some of the columns in a data frame in pandas


code:
import csv

with open(newfile, "wb") as csvfile:
    writer = csv.writer(csvfile)
    for field, court in zip(Field, Court):
        writer.writerow([FileName, TypeName, field, court])

rawDescription: write zip array vertical in csv

description: Write zip array vertical in csv


rawDescription: Why does multiprocessing use only a single core after I import numpy?


code: total = sum(x[1] for x in bets.values());

rawDescription: Algorithm for betting and particularly winning the bet?


code:
photo1=Photo(name="photo number 1")
photo2=Photo(name="photo number 2")
photo1.save()
photo2.save()
album=Album(name="album1")
album.save()
album.photoItems.add(photo1,photo2)
photo1.albums.get().name

rawDescription: Connect one model's ManyToManyField with another model's ForeignKey


code:
# Pad the right-hand side with the edge values
# Use [(0, 0), (1, 0)] to pad the left instead.
xpad = np.pad(x, [(0, 0), (0, 1)], mode='edge')

edges = np.abs(np.diff(xpad, axis=1)) > 0

rawDescription: Find adjacent elements in a 2D numpy grid


code:
list_of_dicts = [{'hello': 'goodbye'}, {'yes': 'no'}]
out_path= "/docs/outfile.txt"

fieldnames = sorted(list(set(k for d in list_of_dicts for k in d)))

with open(out_path, 'wb') as out_file:
    writer = csv.DictWriter(out_file, fieldnames=fieldnames, dialect='excel')
    writer.writeheader()
    writer.writerows(list_of_dicts)

rawDescription: Write Python dictionary to CSV where where keys= columns, values = rows


code:
X = "This is a String I want to log to many lines"
log.info("".join([X[i:i+10]+"\n\t" for i in xrange(0, len(X), 10)]))

rawDescription: Python: wrapping log file text in logging module


code:
a = np.asarray(g)
a

rawDescription: Numpy: Transform sparse matrix to ndarray


rawDescription: Why is numpy vectorized function apparently called an extra time?


rawDescription: How do I use a database that I have in my backup on Cubicweb?

description: Use a database that I have in my backup on Cubicweb


rawDescription: generating all permutations of 2 ones and 3 zeroes with itertools

description: Generating all permutations of 2 ones and 3 zeroes with itertools


code:
import it

th = 200
it.itime.itimes(th)

rawDescription: Subroutine argument not passed correctly from Python to Fortran


rawDescription: Decimal precision in Python Scipy lfilter?


code:
df['b'] = df.a.shift()
x = df[df.a != df.b]
df.replace(*x.values.T)

rawDescription: How to shift entire groups in pandas groupby

description: Shift entire groups in pandas groupby


code:
import os

config_value = 'Foo=Bar'  # Temporary placeholder
config_file_path = os.path.join('/tmp/a/b/c', 'config')

with OpenCreateDirs(config_file_path, 'w') as f:
    f.write(config_value)

rawDescription: Recursively create directories prior to opening file for writing


code:
column_names = ['col1', 'col2', 'col3']
columns = (Column(name, Integer) for name in column_names)
table = Table('data', metadata, Column('id', Integer, primary_key=True), *columns)
class Data(object):
     def __init__(self, *args):
         for name, arg in zip(column_names, args):
             setattr(self, name, arg)

mapper(Data, table)
data = Data(1, 2, 3)
[x for x in dir(data) if x.startswith('col')] # see if all of our columns are there
data.col3 # great!

rawDescription: Creating MySql Table from a python list

description: Creating MySql Table from a python list


rawDescription: Unpack a given number of items in Python?


code:
def per_section(it, is_delimiter=lambda x: x.isspace()):
    ret = []
    for line in it:
        if is_delimiter(line):
            if ret:
                yield ret  # OR  ''.join(ret)
                ret = []
        else:
            ret.append(line.rstrip())  # OR  ret.append(line)
    if ret:
        yield ret

rawDescription: Splitting textfile into section with special delimiter line - python


code: l1 = [hand for hand in l1 if all(subhand not in l2_set for subhand in hand)]

rawDescription: Python, removing whole list if it contains a matching tuple


code:
def add( self, node, port=None, intfName=None, mode=None, out_mobilityhelper=None):
    ...
    if hasattr(out_mobilityhelper, "append"):
        out_mobilityhelper.append(mobilityhelper)
    return tb

rawDescription: How to add a variable of a method of a class in aonther program in python?

description: Add a variable of a method of a class in aonther program in python


rawDescription: loop in tuple until a certain index is reach

description: Loop in tuple until a certain index is reach


rawDescription: Filter objects with a datetime range (00:00 to 23:59:99) in Django


code:
class CustomTestRunner(DiscoverRunner):

    def setup_databases(self, **kwargs):
        # your code goes here
        bash_cmd = "createdb -T zippymeals_template test_zippymeals"
        process = subprocess.Popen(bash_cmd.split(), stdout=subprocess.PIPE)
        process.communicate()[0]

        # force Django to connect to the correct db for tests
        connection = db.connections['default']
        db_conf = connection.settings_dict
        db_conf['NAME'] = db_conf['TEST']['NAME']
        connection.connect()

rawDescription: Django test database not being used with custom test runner


code: re.search(r'(.+) \1', 'the the' )

rawDescription: Python regex does not search with group numbering


code:
import telnetlib
from telnetlib import IAC, DO, DONT, WILL, WONT, SE, NOOPT

def _process_rawq(self):
    """Alteração da implementação desta função necessária pois telnetlib suprime 0x00 e \021 dos dados lidos
    """
    buf = ['', '']
    try:
        while self.rawq:
            c = self.rawq_getchar()
            if not self.iacseq:
#                if c == theNULL:
#                    continue
#                if c == "\021":
#                    continue
                if c != IAC:
                    buf[self.sb] = buf[self.sb] + c
                    continue
                else:
                    self.iacseq += c
            elif len(self.iacseq) == 1:
                # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
                if c in (DO, DONT, WILL, WONT):
                    self.iacseq += c
                    continue

                self.iacseq = ''
                if c == IAC:
                    buf[self.sb] = buf[self.sb] + c
                else:
                    if c == SB: # SB ... SE start.
                        self.sb = 1
                        self.sbdataq = ''
                    elif c == SE:
                        self.sb = 0
                        self.sbdataq = self.sbdataq + buf[1]
                        buf[1] = ''
                    if self.option_callback:
                        # Callback is supposed to look into
                        # the sbdataq
                        self.option_callback(self.sock, c, NOOPT)
                    else:
                        # We can't offer automatic processing of
                        # suboptions. Alas, we should not get any
                        # unless we did a WILL/DO before.
                        self.msg('IAC %d not recognized' % ord(c))
            elif len(self.iacseq) == 2:
                cmd = self.iacseq[1]
                self.iacseq = ''
                opt = c
                if cmd in (DO, DONT):
                    self.msg('IAC %s %d',
                        cmd == DO and 'DO' or 'DONT', ord(opt))
                    if self.option_callback:
                        self.option_callback(self.sock, cmd, opt)
                    else:
                        self.sock.sendall(IAC + WONT + opt)
                elif cmd in (WILL, WONT):
                    self.msg('IAC %s %d',
                        cmd == WILL and 'WILL' or 'WONT', ord(opt))
                    if self.option_callback:
                        self.option_callback(self.sock, cmd, opt)
                    else:
                        self.sock.sendall(IAC + DONT + opt)
    except EOFError: # raised by self.rawq_getchar()
        self.iacseq = '' # Reset on EOF
        self.sb = 0
        pass
    self.cookedq = self.cookedq + buf[0]
    self.sbdataq = self.sbdataq + buf[1]
telnetlib.Telnet.process_rawq = _process_rawq

rawDescription: Python reading until null character from Telnet


rawDescription: Numpy matrices - how to handle arbitrary size


code:
from sys import stdin, stdout
import queue
import math
from collections import OrderedDict

#Vertex Class Definition
class Vertex:
    def __init__(self, name):
        self.name = int(name)
        self.neighbors = OrderedDict()

    def add_neighbor(self, neigh):
        assert(isinstance(neigh, Vertex))
        if neigh.get_name() not in self.neighbors:
            self.neighbors[neigh.get_name()] = neigh

    def get_neighbours(self):
        return list(self.neighbors.values())

    def get_name(self):
        return self.name

    def get_neighbours_names(self):
        return [n.get_name() for n in self.get_neighbours()]

#Graph Class definition
class Graph:
    def __init__(self):
        self.verts = []
        self.num = 0

    def add_vert(self, node):
        self.verts.append(Vertex(node))

    def add_edge(self, fro, to):
        print('%s -> %s' % (fro, to))
        self.verts[fro-1].add_neighbor(self.verts[to-1])
        self.verts[to-1].add_neighbor(self.verts[fro-1])

def bfs(g,s):

    q= queue.Queue(maxsize=0)
    q.put(g.verts[s-1])
    cost= [-1 for yy in range(g.num)]
    cost[s-1]=0

    print('g.verts[s-1] is ', g.verts[s-1].get_name())
    print('g.verts[s-1] neigh ', g.verts[s-1].get_neighbours_names())
    print('g.verts[s-1] neigh[0] -> neigh', g.verts[s-1].get_neighbours()[0].get_neighbours_names())
    print('------------')

    while(not q.empty()):

        p=q.get()

        """If I check for p.get_neighbours() here, only the neigbors of
        source element s are returned. Otherwise, the loop stops
        after calling the first neighbor of s. However, if I
        explicitly call g.verts and check for neighbors, the list
        is complete."""

        print('p is ', p)
        print('p name is ', p.get_name())
        print('p nei ', p.get_neighbours_names())
        if len(p.get_neighbours()) > 0:
            print('p nei -> nei ', p.get_neighbours()[0].get_neighbours_names())
        print('------------')

        for vex in p.get_neighbours():
            if cost[vex.name-1]==-1:
                q.put(vex)
                cost[vex.name-1]= cost [p.name-1]+6

    return cost

t= 1
for hehe in range (t):
    n, e= 10, 6

    g= Graph()
    #add n vertices
    for i in range (1, n+1):
        g.add_vert(i)
        g.num+=1
    arr= [ [3, 1], [10, 1], [10, 1] , [3, 1] , [1, 8], [5, 2]]
    for i in range(e):
        x,y = arr[i][0], arr[i][1]
        g.add_edge(x, y)

    s= 3
    #s is the start node of the graph
    c=bfs(g,3)

    c=bfs(g,1)

    del c[s-1]

    for yoy in c:
        stdout.write(str(yoy))
        stdout.write(" ")
    stdout.write("\n")

"""
       3  5   6  4 7 8 9
      /    \
10 - 1      2
     |
     8
"""

rawDescription: Object details don't get passed into another object pointer [Python 3]


rawDescription: python - 2 lists, and finding maximum product from 2 lists

description: Python - 2 lists, and finding maximum product from 2 lists


code:
from collections import OrderedDict

T1 = (('a', 'b', 2), ('a', 'c', 4), ('b', 'c', 1), ('a', 'b', 8),)

d = OrderedDict()

for x, y, z in T1:
    d[(x, y)] = d[(x, y)] + z if (x, y) in d else z

T2 = tuple((*k, v) for k, v in d.items())

print(T2)

rawDescription: Summing similar elements within a tuple-of-tuples


code:
def Print(self, age, *args):
    if args:
        name, age = args + (age,)
    else:
        name = None
    if name is not None:
        print(name)
    print(age)

rawDescription: type function overloading in python

description: Type function overloading in python


code:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Unicode, DateTime, Integer, create_engine
from sqlalchemy.orm import sessionmaker, relationship, backref
import datetime

engine = create_engine('sqlite:///:memory:')
Base = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()

rawDescription: SqlAlchemy filter by time difference

description: SqlAlchemy filter by time difference


code:
for line in infile:
    # make only_callers
    count=Counter(only_callers)

rawDescription: Accessing key/value pairs in a dictionary created by the built-in counter function (python 3.4)


rawDescription: Summation of only consecutive values in a python array


code:
def maxspaces(x):
    max_count = count = 0

    for character in x:
        if character == ' ':
            count += 1
            if count > max_count:
                max_count = count
        else:
            count = 0

    return max_count

rawDescription: Loop Issue with Local Variable

description: Loop Issue with Local Variable


rawDescription: string replacement in python

description: String replacement in python


code:
#!coding:utf8
from __future__ import print_function
import re
def tokenize(string):
    return re.split(r"(\W+)(?<!')",string,flags=re.UNICODE)

print(tokenize(u'perché.'))

rawDescription: Regex unicode in python 2.x vs 3.x

description: Regex unicode in python 2.x vs 3.x


code:
import ast
temp = "'mycode':['1','2','firstname','Lastname']"
key,value = map(ast.literal_eval, temp.split(':'))
status = {key: value}

rawDescription: extract a dictionary key value from a string

description: Extract a dictionary key value from a string


rawDescription: How to read a dictionary from a file in Python 2.7?

description: Read a dictionary from a file in Python 2.7


code:
from collections import defaultdict
d = defaultdict(list)
for k,v in succeeded-failed:
    d[k].append(v)
for k in d:
    print(k + ': ' + ', '.join(d[k]))

rawDescription: Python: iterate over a list of list

description: Python: iterate over a list of list


code: records.update((k, 0) for k,v in records.iteritems() if v is None)

rawDescription: how to traverse through dict?

description: Traverse through dict


code:
a = 3
lst = [[] for _ in xrange(a)]
lst
a = 10
lst = [[] for _ in xrange(a)]
lst
# This is to prove that each of the lists in lst is unique
lst[0].append(1)
lst

rawDescription: How to create a number of empty nested lists in python

description: Create a number of empty nested lists in python


code:
from dis import dis
dis(compile('print outer', '<string>', 'exec'))

rawDescription: What method does Python 2 use to print tuples?


code:
dbModule = testspec['db']
global db
db = imp.load_source('db', 'config/'+dbModule+'.py')

rawDescription: Is there a Python test framework suitable to run simulations


rawDescription: Prossing Very Ugly Multi-line Json Object with Python


rawDescription: In Python and numpy, How do I replace missing values in an array with the previous element? (Masked array?)


code: sum(B.sum() for B in A) / sum(len(B) for B in A)

rawDescription: Mean of object variables in a python array


code:
s = "I bought a boat for $5000 and it's awesome"
[i[1:] for i in s.split() if i.startswith('$')]

rawDescription: How to return a word in a string if it starts with a certain character? (Python)

description: Return a word in a string if it starts with a certain character? (Python)


code: (a, a*2) if return_two else a             #This can return a tuple if return_two is True otherwise a single value `a` .

rawDescription: Unexpected python function return behavior


code: YouTubeVideo("Pi9NpxAvYSs", start=timedelta(hours=1, minutes=47, seconds=3))

rawDescription: Can the ipython notebook YouTubeVideo class play from time offset


code: sorted(alarm_list, key=lambda alarm: alarm.severity)

rawDescription: Custom sort by property

description: Custom sort by property


code:
s = 'abc0efg'
s.replace('0', 'd')

rawDescription: Alternative to python string item assignment


code:
1
2
3
Exit
4
5
6
Exit
7
8
9
Exit
0

rawDescription: Break from array and run another function in python


code: np.allclose(OP(cords, atoms, atom_proj), project_atom(cords, atoms, atom_proj))

rawDescription: Projecting Coordinates in Numpy array

description: Projecting Coordinates in Numpy array


code:
from threading import Thread

def GetDict():
    return {'foo':'bar'}

# imports ...
# from Worker import GetDict

class WorkerThread(Thread):

    def __init__(self, fnc, *args, **kwargs):
        super(WorkerThread, self).__init__()
        self.fnc = fnc
        self.args = args
        self.kwargs = kwargs

    def run(self):
        self.result = self.fnc(*self.args, **self.kwargs)

def ThreadStart():
    jobs = [WorkerThread(GetDict) for i in range(10)]
    for j in jobs:
        j.start()
    for j in jobs:
        j.join()
        print(j.result)

if __name__ == '__main__':
    ThreadStart()

rawDescription: Python threading: how to use return values of external scripts?


code: from io import StringIO

rawDescription: Loading a generic Google Spreadsheet in Pandas


code:
quotes_to_remove = [u"'", u"\u2019", u"\u2018"]
new_s = []
for line in s:
    new_line = []
    for word in line:
        for quote in quotes_to_remove:
            word = word.replace(quote, "")
        new_line.append(word)
    new_s.append(new_line)
print(new_s)

rawDescription: Why is re not working on my file?

description: Why is re not working on my file


code:
import json

# loading data
try:
    with open("data") as a:
        b = json.load(a) # b is dict
except FileNotFoundError:
    b = {}

# user
name = input("What's your name? ")
score = int(input("What's your high score? "))

# manipulating data
b[name] = score

# writing back
with open("data", "w") as a:
    json.dump(b, a)

rawDescription: Deleting File Lines in Python

description: Deleting File Lines in Python


code: dates.groupby('client')['date'].apply(lambda x: [i / np.timedelta64(1, 'D') for i in np.diff([pd.to_datetime(c) for c in x])[0]])

rawDescription: Finding Date difference in list of dates [Pandas]


code:
lst = ['blabla', 10, 'something']
# Open the file with a context manager
with open("/path/to/file", "a+") as myfile:
    # Convert all of the items in lst to strings (for str.join)
    lst = map(str, lst)
    # Join the items together with commas
    line = ",".join(lst)
    # Write to the file
    myfile.write(line)

rawDescription: Python - how to write strings to file without quotes and spaces?


code:
frame4 = Frame(window)
frame4.grid(row=2, column=0, sticky='E', padx=5, pady=5, columnspan=3)

rawDescription: How to expand widgets size in a frame with respect to other frames in Tkinter (Help on:Tkinter grid management)

description: Expand widgets size in a frame with respect to other frames in Tkinter (Help on:Tkinter grid management)


code:
foo = no.ones((3,3))
np.linalg.qr(foo)

rawDescription: python multidimensional list.. how to grab one dimension?

description: Python multidimensional list.. how to grab one dimension


code: stacked_result = np.hstack([pca_transformed, data[:, [special_axis]]])

rawDescription: Retain specific component in PCA

description: Retain specific component in PCA


code:
def regex(jsonstring):
    return ", ".join(re.findall(r'": "(.*?)"',jsonstring)).replace(";",",")

rawDescription: Using regex in jinja

description: Using regex in jinja


code:
def access(d):
    if type(d) == list:
        for f, v in enumerate(d):
            for r in access(v):
                yield [f] + r
    else:
        yield [d]

rawDescription: Iterating through multi-dimentional lists while remembering indices


rawDescription: Squeezing characters with python

description: Squeezing characters with python


code:
"Date","Information","Type"
"2015-12-07","First: Jim, Last: Jones, School: MCAA; First: Jane, Last: Jones,  School: MCAA;","Old"
"2015-12-06","First: Tom, Last: Smith, School: MCAA; First: Tammy, Last: Smith, School: MCAA;","New"

rawDescription: Python/ Pandas CSV Parsing

description: Python/ Pandas CSV Parsing


code:
import heapq

def iter_linear_merge(*args):
  """Yield non-decreasing items from sorted a and b."""
  # Technically, [1, 1, 2, 2] isn't an "increasing" sequence,
  # but it is non-decreasing.

  nexts = []
  for x in args:
    x = iter(x)
    for n in x:
      heapq.heappush(nexts, (n, x))
      break

  while len(nexts) >= 2:
    n, x = heapq.heappop(nexts)
    yield n
    for n in x:
      heapq.heappush(nexts, (n, x))
      break

  if nexts:  # Degenerate case of the heap, not strictly required.
    n, x = nexts[0]
    yield n
    for n in x:
      yield n

rawDescription: Question on a solution from Google python class day


code: ewmas = [pd.ewma(df[['PX_LAST']].resample(w), span=10) for w in lista4]

rawDescription: Ewma in pandas but over rolling weekly data.


rawDescription: How to turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)

description: Turn this simple 5 bytes back into 4 bytes ? (algorithm to convert 4 bytes into 5 bytes is known)


code: all(u'\u4e00' <= c <= u'\u9fff' for c in name.decode('utf-8'))

rawDescription: Python 2.7: test if characters in a string are all Chinese characters


code:
import pandas
df = pandas.read_table("Scoring Matrix", delim_whitespace = True)

rawDescription: how to skip the first line of a file in python

description: Skip the first line of a file in python


code:
def countmatching(iterable, *predicates):
    v = [0] * len(predicates)
    for e in iterable:
        for i,p in enumerate(predicates):
            if p(e):
                v[i] += 1
    return tuple(v)

rawDescription: Most pythonic way of counting matching elements in something iterable


code:
with open(filename) as f:
    for line in f:
        print(line)

rawDescription: Printing a .txt File Python

description: Printing a .txt File Python


rawDescription: converting time to Hz in python

description: Converting time to Hz in python


code:
str = """http://www.test.com/aa4
bx2 vq9
http://www.bh9.com/cj3
"""
re.findall(r'(?<![./])[a-z][a-z][0-9]',str)

rawDescription: Equivalent to (.*) in negative look behind assertion Regex Python


code: call_attrs(a, ['method1', 'method2', 'method3'], arg1, arg2)

rawDescription: Nested try statements in python?

description: Nested try statements in python


rawDescription: How can I make a django query-set that uses two classes?

description: Make a django query-set that uses two classes


code:
results['moments'][0][5]
results['moments'][1][5]
results['moments'][2][5]
results['moments'][3][5]

rawDescription: getting JSON data from python several levels deep without names

description: Getting JSON data from python several levels deep without names


code: 'How are you?'.upper()

rawDescription: How To Add List Elements and Convert Them To A String


code:
def add_squares(x, y):
    return x*x + y*y

xs = np.array([0, 0, 1, 1])
ys = np.array([0, 1, 1, 0])

res = add_squares(x, y)

rawDescription: Evaluating a multivariable function on an array with python/numpy


code:
from collections import Counter

vocab = ["foo bar", "baz"]
r = re.compile("|".join(r"\b%s\b" % w for w in vocab))
wordcount = Counter(re.findall(r, s))

rawDescription: Count occurrences of a couple of specific words


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

mean, amp = 40000, 20000
t = np.arange(50)
s1 = np.sin(t)*amp + mean #synthetic ts, but closer to my data

fig, ax1 = plt.subplots()
ax1.plot(t, s1, 'b-')

ax1.set_xlabel('time')
mn, mx = ax1.set_ylim(mean-amp, mean+amp)
ax1.set_ylabel('km$^3$/year')

km3yearToSv = 31.6887646e-6

ax2 = ax1.twinx()
ax2.set_ylim(mn*km3yearToSv, mx*km3yearToSv)
ax2.set_ylabel('Sv')

rawDescription: Plot single data with two Y axes (two units) in matplotlib


code: req1 = requests.post(url=Server.My_server, data=p_c)

rawDescription: Convert curl command into python code

description: Convert curl command into python code


code: readableMACaddress = '-'.join('%02X' % ((myMAC >> 8*i) & 0xff) for i in reversed(xrange(6)))

rawDescription: Python get normal HEX format for MAC-Adress


rawDescription: Inspect import path string from object

description: Inspect import path string from object


code:
df
cols = [x for x in df.columns if 'abc' in x]
df['newcol'] = df[cols].apply(lambda x: x.str.contains('r'),axis=0).any(axis=1)
df['newcol'] = df['newcol'].map({True:'r',False:'np.nan'})
df

rawDescription: pandas dataframe: return column that is a compression of other columns

description: Pandas dataframe: return column that is a compression of other columns


code:
from tkinter import *
from tkinter.ttk import *
import time
import threading

class Interface:
    def __init__(self, master):
        self.master = master
        self.browse_button= Button (master, text="Browse", command=self.browser)
        self.browse_button.pack()
        self.progressbar = Progressbar(mode="determinate", maximum=75)

    def browser (self):
        t = threading.Thread(target=self.read_file, args=("filename",))
        self.progressbar.pack()
        self.browse_button.config(state="disabled")
        self.master.config(cursor="wait")
        self.master.update()

        t.start()
        while t.is_alive():
            self.progressbar.step(1)
            self.master.update_idletasks()  # or try self.master.update()
            t.join(0.1)

        self.progressbar.config(value="0")
        self.progressbar.pack_forget()
        self.browse_button.config(state="enabled")
        self.master.config(cursor="")

    def read_file (self, filename):
        time.sleep(7)  # actually do the read here

window = Tk()
starter = Interface(window)
window.mainloop()

rawDescription: Blocking Tkinter interface until thread finishes its task


code:
class A(object):
    def test_a(self):
        return "A"

class B1(A):
    def test_b(self):
        return self.test_a() + "B"

class B2(A):
    def test_b(self):
        return super().test_a() + "B"

class C1(B1):
    def test_a(self):
        return "C"

class C2(B2):
    def test_a(self):
        return "C"

rawDescription: Should I use super() every time I call parent function or only inside overridden functions?


code:
def isSorted(L):
    if len(L) < 2:
        return True
    return L[0] <= L[1] and isSorted(L[1:])

rawDescription: check if sorted using recursion in python

description: Check if sorted using recursion in python


code:
doc = docx.Document('/some/path/example.docx')
doc_body = doc._document_part._element.body
#print(docx.oxml.xmlchemy.serialize_for_reading(doc_body))

rawDescription: python-docx insertion point

description: Python-docx insertion point


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

a = np.random.normal(0,2,1000)
b = np.random.normal(-2,7,100)
data = [a,b]

plt.boxplot(data) # Or you can use the boxplot from Pandas

for i in [1,2]:
    y = data[i-1]
    x = np.random.normal(i, 0.02, len(y))
    plt.plot(x, y, 'r.', alpha=0.2)

rawDescription: Dot-boxplots from DataFrames

description: Dot-boxplots from DataFrames


code:
global storage_i
storage_i = i

rawDescription: Python Global Variable: sharing between function class then function


code:
def bisect_left(a, x, lo=0, hi=None):
    if lo < 0:
        raise ValueError('lo must be non-negative')
    if hi is None:
        hi = len(a)
    while lo < hi:
        mid = (lo+hi) // 2
        if a[mid][0] < x:
            lo = mid+1
        else: hi = mid
    return lo

def get_bis(key, d):
    h = hash(key)
    ind = bisect_left(d, h)
    if ind == -1:
        raise KeyError()
    for i in xrange(ind, len(d)):
        if d[i][0] != h:
            raise KeyError()
        if d[i][1] == key:
            return d[i][2]
    raise KeyError()

rawDescription: Efficient way of searching a list of lists according to their hash value?


code:
class DatacenterViewSet(viewsets.ModelViewSet):

    queryset = Datacenter.objects.all()
    serializer_class = DatacenterSerializer

    @detail_route(methods=['get'], permission_classes=[permissions.IsAdminUser])
    def servers(self, request, pk=None):
        servers = Server.objects.filter(datacenter__id=pk)
        serializer = ServerSerializer(servers, many=True, context={'request': request})
        return Response(serializer.data)

rawDescription: Clean way to implement views or methods with Django Rest Framework


code:
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
    done = True

rawDescription: Keyboard Event - Pygame

description: Keyboard Event - Pygame


code:
from apscheduler.schedulers.background import BackgroundScheduler

scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(yout_routine, 'interval', days=1)

rawDescription: Pause Python For Loop for a day

description: Pause Python For Loop for a day


code: summary

rawDescription: Summarizing Dataframes with ambiguous columns with apply function


rawDescription: Python CSV file manipulation

description: Python CSV file manipulation


code: base_path = '["results", 0, "locations"]'

rawDescription: How to Create a Dynamic Path for Grabbing Variables from JSON in Python


rawDescription: How to dynamically pass predicates to filter function?

description: Dynamically pass predicates to filter function


code: keys = [k for k,v in Arr]

rawDescription: How to implement associative array (not dictionary) in Python?

description: Implement associative array (not dictionary) in Python


code:
blank
blank.flatten()

rawDescription: Double loops for "concatenation of subarrays in bigger array"


code:
class ContentTypeField(serializers.WritableField):
    def field_from_native(self, data, files, field_name, into):
        into[field_name] = self.from_native(data[field_name])

    def from_native(self, data):
        app_label, model = data.split('.')
        return ContentType.objects.get(app_label=app_label, model=model)

    # If content_type is write_only, there is no need to have field_to_native here.
    def field_to_native(self, obj, field_name):
        if self.write_only:
            return None
        if obj is None:
            return self.empty
        ct = getattr(obj, field_name)
        return '.'.join(ct.natural_key())

class FooSerializer(serializers.ModelSerializer):
    content_type = ContentTypeField()
    # ...

rawDescription: set contenttype by name in generic relation in django rest framework

description: Set contenttype by name in generic relation in django rest framework


code: [k for k,v in sorted_pairs]

rawDescription: Sorting a dictionary by its value, and then its key if values are equal then outputting a list


code:
bdict = {'fred':"6.56",'paul':"47.91",'george':"2.59",'ringo':"11.50",'john':"1.57"}
sorted(bdict.items(), key=lambda i: float(i[1]), reverse=True)

rawDescription: Casting a dictionary value to decimal or float before sorting


code:
class Foo(object):
    def __init__(self, x, y):
       self.x = x
       self.y = y
    def __iter__(self):
       return vars(self).iteritems()

rawDescription: Extend python's dict functionality to user created classes


code:
from itertools import product

def nodes_iter(n, k):
    """ returns generator (lazy iterator) rather than creating whole list """
    return product(range(k+1),repeat=n)

rawDescription: python, elegant way of creating vectors

description: Python, elegant way of creating vectors


code:
def anydigit(text):
    find_digit = re.search(r'\d+', text)
    if find_digit:
        return find_digit.start()
    else:
        return 0

df = pd.DataFrame({'DPID': ['A1', 'A2'], 'NAME': ['John Doe', 'Jane Doe'],
                   'addr_1': ['123 MAIN ST', 'ATTN: JOHN DOE'], 'addr_2': ['', 'P O BOX 123456']})
df['addr_ad1'] = df['addr_1'].apply(anydigit)
df['addr_ad2'] = df['addr_2'].apply(anydigit)
df['aux_addr_line'] = ''

rawDescription: Edit column values based on other column values


code:
class Model(model.Model):
    name = models.CharField(primary_key=True, max_length=16)

    # This should touch before saving
    def save(self, *args, **kwargs):
        self.name = re.sub(r'(.*)\({1}(.*)\){1}(.*)', r'\1\2\3', self.name)
        super(Model, self).save(*args, **kwargs)

rawDescription: Django - How can i modify text before save them to database?


code:
from collections import Counter
a = Counter()
a['word'] += 1
a['word'] += 1
a['test'] += 1
a.most_common()

rawDescription: Determining the most common word from a user's input. [Python]


rawDescription: Remove numbers from a numpy array

description: Remove numbers from a numpy array


rawDescription: Finding various string repeats in python in next 10 characters


code:
L2 = leg.get_lines()[1]
L2.set_ydata(np.array(L2.get_ydata())-2) # move down of 2 units the line (in the legend based coordinates)

rawDescription: offset one of matplotlib's legend items

description: Offset one of matplotlib's legend items


code:
# list of tags = ['comedy','80s']
qs = Item.objects.all( Q(brand__iexact="brand name") | Q(tags__name__in=[tag for tag in list_of_tags]) )

rawDescription: Django Combine a Variable Number of QuerySets


code: now = dt.datetime.now()

rawDescription: Get system date/time in Python after changing time zone


code:
from collections import defaultdict
d = defaultdict(list)
for i, j in L:
    d[i].append(j)

[[i, sum(j)] for i, j in d.items()]

rawDescription: Sum a multidimensional list in python

description: Sum a multidimensional list in python


code:
from subprocess import check_call

check_call(cmd) # start, wait until it is done, raise on non-zero exit status

rawDescription: How to add to VLC playlist queue using Python subprocess

description: Add to VLC playlist queue using Python subprocess


rawDescription: How to use the variable from the python in rpy2?

description: Use the variable from the python in rpy2


code:
def find_all_primefactors(list_with_numbers):
    all_factors = []
    for number in list_with_numbers:
        prime_factors = primefactors_of_number(number)
        for x in set(prime_factors): # loop over factors without duplicates
            in_all = all_factors.count(x) # how many x are already in all_factors
            in_p = prime_factors.count(x) # how many x are in prime_factors
            diff = in_p - in_all
            all_factors.extend([x]*diff) # extend all_factors based on difference
                                         # note that [x]*diff is [] for diff <= 0
    return all_factors

rawDescription: Update list to include new elements of another list (primefactor computation)


code:
for line in old_file:
    new_file.write(subst if pattern in line else line)

rawDescription: Python find pattern and replace entire line


code:
from plone.app.controlpanel.security import ISecuritySchema
# Fetch the adapter
security_adapter =  ISecuritySchema(portal)
security_adapter.set_enable_user_folders(True)

rawDescription: How to add Members folder in plone.app.testing?

description: Add Members folder in plone.app.testing


rawDescription: Initializing 2D lists in Python: How to make deep copies of each row?


code:
def organization_wall_post(request, organization):
    organization = Organization.objects.get_object_or_404(organization)
    if request.method == 'POST':
        form = MessageForm(request.POST)
        if form.is_valid():
             post_on_organization_wall(request.user.subprofile, message, organisation)
    else:
        form = MessageForm()
    return render(request, 'organisation/wall_post.html', {'form': form})

rawDescription: Python: How to "fork" a session in django


code: ~x & 0xffff

rawDescription: Doing bitwise complement on a 16-bit signal (Python) operator ^


code: keys = [k for k in bucket]

rawDescription: Boto S3 API does not return full list of keys


code:
{'City': [u'Seattle, WA, USA', u'Kirkland, WA, USA'],
 'CompanyName': 'Google',
 'Description': [u"Google's software engineers develop the next-generation technologies that change how millions of users connect, explore, and interact with information and one another. Our ambitions reach far beyond just Search. Our products need to handle information at the the scale of the web. We're looking for ideas from every area of computer science, including information retrieval, artificial intelligence, natural language processing, distributed computing, large-scale system design, networking, security, data compression, and user interface design; the list goes on and is growing every day. As a software engineer, you work on a small team and can switch teams and projects as our fast-paced business grows and evolves. We need our engineers to be versatile and passionate to tackle new problems as we continue to push technology forward.?\nWith your technical expertise you manage individual projects priorities, deadlines and deliverables. You design, develop, test, deploy, maintain, and enhance software solutions.\n\nSeattle/Kirkland engineering teams are involved in the development of several of Google?s most popular products: Cloud Platform, Hangouts/Google+, Maps/Geo, Advertising, Chrome OS/Browser, Android, Machine Intelligence. Our engineers need to be versatile and willing to tackle new problems as we continue to push technology forward."],
 'JobDetailUrl': 'https://www.google.com/about/careers/search?_escaped_fragment_=t%3Djo%26jid%3D34154%26',
 'Jobtype': [],
 'State': [u'Seattle, WA, USA', u'Kirkland, WA, USA'],
 'Title': [u'Software Engineer']}

rawDescription: How to write rejax and xpath for the below link?

description: Write rejax and xpath for the below link


code:
hashed = df.apply(lambda x: hash(str(x.values)), axis=1)
hashed

rawDescription: How many times is a particular row present?


code:
particle.py
import pygame,random

def ascending(speed):
    def _ascending(particle):
        particle.y -= speed
    return _ascending

def kill_at(max_x, max_y):
    def _kill_at(particle):
        if particle.x < -max_x or particle.x > max_x or particle.y < -max_y or particle.y > max_y:
            particle.kill()
    return _kill_at

def age(amount):
    def _age(particle):
        particle.alive += amount
    return _age

def fan_out(modifier):
    def _fan_out(particle):
        d = particle.alive / modifier
        d += 1
        particle.x += random.randint(-d, d)
    return _fan_out

def wind(direction, strength):
    def _wind(particle):
        if random.randint(0,100) < strength:
            particle.x += direction
    return _wind

class Particle():
    def __init__(self, col, size, *strategies):
        self.x, self.y = 0, 0
        self.col = col
        self.alive = 0
        self.strategies = strategies
        self.size = size

    def kill(self):
        self.alive = -1 # alive -1 means dead

    def move(self):
        for s in self.strategies:
            s(self)

black = (0,0,0)
grey = (145,145,145)
light_grey = (192,192,192)
dark_grey = (183, 183, 183)

def smoke_machine():
    colors = {0: grey,
              1: dark_grey,
              2: light_grey}
    def create():
        for _ in xrange(random.choice([0,0,0,0,0,0,0,1,2,3])):
            behaviour = ascending(1), kill_at(1000, 1000), fan_out(400), wind(1, 15), age(1)
            p = Particle(colors[random.randint(0, 2)], random.randint(10, 15), *behaviour)
            yield p

    while True:
        yield create()

class Emitter(object):
    def __init__(self, pos=(0, 0)):
        self.particles = []
        self.pos = pos
        self.factories = []

    def add_factory(self, factory, pre_fill=300):
        self.factories.append(factory)
        tmp = []
        for _ in xrange(pre_fill):
            n = next(factory)
            tmp.extend(n)
            for p in tmp:
                p.move()
        self.particles.extend(tmp)

    def update(self):
        for f in self.factories:
            self.particles.extend(next(f))

        for p in self.particles[:]:
            p.move()
            if p.alive == -1:
                self.particles.remove(p)

    def draw(self, screen, position_translater_func):
        for p in self.particles:
            target_pos = position_translater_func(map(sum, zip((p.x, p.y), self.pos)))
            pygame.draw.circle(screen, p.col, target_pos, int(p.size))

rawDescription: How to implement a particle engine

description: Implement a particle engine


code:
from numpy.linalg import inv

def lnprob_trunc_norm(x, mean, bounds, C):
    if np.any(x < bounds[:,0]) or np.any(x > bounds[:,1]):
        return -np.inf
    else:
        return -0.5*(x-mean).dot(inv(C)).dot(x-mean)

rawDescription: Truncated multivariate normal in SciPy?

description: Truncated multivariate normal in SciPy


code:
first,last,age
John,Smith,20
Jane,Smith,19
Frank,Jones,30

rawDescription: Are there a tools that can help to treat files as tables in a database?


rawDescription: get indices of original text from nltk word_tokenize

description: Get indices of original text from nltk word_tokenize


code:
import itertools
a[:1] + list(itertools.starmap("{}:{}".format, enumerate(a[1:], start=1)))

rawDescription: Edit an element in a list - python

description: Edit an element in a list - python


code: pairs = closestPoints(ListA,ListB)

rawDescription: How to find the point pairs in two point lists with min distance in a efficent way?

description: Find the point pairs in two point lists with min distance in a efficent way


code:
'foo'.isspace()
'  foo    '.isspace()
'   '.isspace()
foo = '    '
bar = '  blahblah  '
foo.isspace()
bar.isspace()

rawDescription: Python Jinja2 post

description: Python Jinja2 post


code:
from twisted.internet.task import react
from twisted.internet.defer import Deferred
from twisted.internet.protocol import Protocol
from twisted.internet.endpoints import clientFromString, connectProtocol

class SendBytes(Protocol):
    def __init__(self, data):
        self.data = data
        self.done = Deferred()

    def connectionMade(self):
        self.transport.write(self.data)
        self.transport.loseConnection()

    def connectionLost(self, reason):
        self.done.callback(None)

def main(reactor, description, data):
    endpoint = clientFromString(reactor, description)
    connecting = connectProtocol(endpoint, SendBytes(data))
    def connected(proto):
        print("Successfully connected to {0}".format(proto.transport.getPeer().host))
        return proto.done
    connecting.addCallback(connected)
    return connecting

if __name__ == '__main__':
    react(main, [b"tcp:host=127.0.0.1:port=4444", b"DDDDDD"])

rawDescription: Cant receive Data using Asyncore Python

description: Cant receive Data using Asyncore Python


code: modified_list=[int(i) for  element in c for i in element]

rawDescription: Convert a binary to an array with each binary number


code: prices = [item['Price'] for item in data['results']]

rawDescription: storing data retrieved from REST api into variables in python

description: Storing data retrieved from REST api into variables in python


code:
from collections import defaultdict
import io
import re
import pandas as pd
import pprint as pp

fn = r'D:\temp\.data\36671176.data'

header_pat = r'(TIMESTAMP|TIMEZONE|NAME|MODEL|SERIAL|FIRMWARE_VERSION)\s+([^\r\n]*?)\s*[\r\n]+'

def parse_file(filename):
    with open(fn) as f:
        txt = f.read()

    m = re.search(r'BEGIN\s*[\r\n]+(.*)[\n\r]+END', txt, flags=re.DOTALL|re.MULTILINE)
    if m:
        data = m.group(1)
        df = pd.read_csv(io.StringIO(data), header=None, usecols=[0,1], names=['freq', 'dBm'])
    else:
        df = pd.DataFrame()

    d = defaultdict(list)
    for m in re.finditer(header_pat, txt, flags=re.S|re.M):
        d[m.group(1)] = m.group(2)

    return df, d

df, info = parse_file(fn)
print(df)
pp.pprint(info)

rawDescription: reading a complicated CSV file with python

description: Reading a complicated CSV file with python


code: print(card['ace of hearts'][1])

rawDescription: Assigning multiple values to a dictionary key- Python


code:
from itertools import repeat
repeat([2,3], 3)
list(repeat([2,3], 3))

rawDescription: make a side_effect iterator loop over from "beginning to end" "over and over again"

description: Make a side_effect iterator loop over from "beginning to end" "over and over again"


code:
t = datetime.timedelta(hours=3)
t.total_seconds()

rawDescription: How to extract time and store in an Array/Structure

description: Extract time and store in an Array/Structure


code:
greenwich_date = datetime.now(pytz.timezone('Etc/Greenwich'))
greenwich_date.date()

rawDescription: Change Timezone for Date object Python

description: Change Timezone for Date object Python


code:
class StudentIds(Base):
    __table_args__ = {'extend_existing': True}
    __tablename__ = 'student_ids'
    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    student_id = Column(String(50, convert_unicode=True), nullable=False,unique=False)

    junctionid = relationship("Junction", cascade='save-update',
                                 backref='student_ids', lazy='select', post_update=True)
    marks = relationship("Marks", backref="student")

class Marks(Base):
    __table_args__ = {'extend_existing': True}
    __tablename__ = 'marks'
    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    mark = Column(Integer, nullable=False, unique=False)
    subject_fk = Column(Integer, ForeignKey('subjects.id'))
    subject = relationship('Subjects', foreign_keys=[subject_fk],uselist=False,
                      backref='marks', innerjoin=False, post_update=False)
    student_id = Column(Integer, ForeignKey('student_ids.id'))
    student = relationship('StudentIds', foreign_keys=[student_id])

class Subjects(Base):
    __table_args__ = {'extend_existing': True}
    __tablename__ = 'subjects'
    id = Column(Integer, primary_key=True, nullable=False, autoincrement=True)
    subject = Column(String(10, convert_unicode=True), nullable=False, unique=True)

rawDescription: SQLAlchemy association confusion

description: SQLAlchemy association confusion


code:
from collections import defaultdict
mydata = defaultdict(lambda: defaultdict(list))

rawDescription: How can I create the following data type in Python?

description: Create the following data type in Python


code:
def num(N):
  if N==0:
     return 0
  return 1+num(N/10)

num(100)

rawDescription: How to count the length of integer using recursion

description: Count the length of integer using recursion


code:
import argparse
import os.path

parser = argparse.ArgumentParser()

def file_choices(choices,fname):
    ext = os.path.splitext(fname)[1][1:]
    if ext not in choices:
       parser.error("file doesn't end with one of {}".format(choices))
    return fname

parser.add_argument('fn',type=lambda s:file_choices(("csv","tab"),s))

parser.parse_args()

rawDescription: python argparse file extension checking

description: Python argparse file extension checking


code:
with open(output, 'w') as fp:
   for r in db.hello.find(fields=['text', 'timestamp']):
       print >>fp, '"%s","%s"' % (r['text'], r['timestamp'].strftime('%H:%M:%S'))

rawDescription: Saving entries of Mongo documents into CSV + Formatting ISODate


code:
grb = df.groupby('mac address')
df['origin'] = grb['node name'].transform(pd.Series.shift, 1)
df['departure time'] = grb['datetime'].transform(pd.Series.shift, 1)

rawDescription: How to Efficiently Process Time-Series Data in Pandas


code:
def master():
    s = requests.session()

    # we're now going to use the session in 3 different function calls
    login_to_site(s)
    page1 = scrape_page(s, 'page1')
    page2 = scrape_page(s, 'page2')

    # once this function ends we either need to pass the session up to the
    # calling function or it will be gone forever

def login_to_site(s):
    s.post('http://www.example.com/login')

def scrape_page(s, name):
    page = s.get('http://www.example.com/secret_page/{}'.format(name))
    return page

rawDescription: python-requests keep session between function

description: Python-requests keep session between function


rawDescription: Pandas pivot table Nested Sorting Part 3


code:
full_list = [
{u'rating': 0.0, u'name': u'Samsung NP550P5C-S02IN (3rd Gen Ci7/ 8GB/ 1TB/ Win7 HP/ 2GB Graphics)', u'price': 0.0, u'popularity': 9, u'brand_id': 1, u'category_id': 3, u'id': 3794},
{u'rating': 10.0, u'name': u'Samsung NP300E5A-A08IN Laptop (2nd Gen Pentium Dual Core/ 2GB/ 500GB/ Win7 HB)', u'price': 0.0, u'popularity': 23, u'brand_id': 1, u'category_id': 3, u'id': 3825},
{u'rating': 0.0, u'name': u'Samsung NP-RV515-A02IN Laptop (APU Dual Core/ 2GB/ 500GB/ Win7 HB)', u'price': 0.0, u'popularity': 26, u'brand_id': 1, u'category_id': 3, u'id': 3826},
{u'rating': 9.2, u'name': u'Samsung NP355V5C-S03IN Laptop (APU Quad Core A8/ 6GB/ 750GB/ Win7 HP/ 1GB Graphics)', u'price': 0.0, u'popularity': 17, u'brand_id': 1, u'category_id': 3, u'id': 3889}
]

rawDescription: Creating a dictionary of dictionaries in Python


code:
for key in selected_keys:
    print(g[key])

rawDescription: How to remove large numbers of dictionary entries in python

description: Remove large numbers of dictionary entries in python


code:
lst1=['a','b','c','s']
list(enumerate(lst1))         #default index values, i.e 0
list(enumerate(lst1,1))       #index started at 1

rawDescription: Any built-in do the job `range(len(lst))`?


code:
import comtypes.gen.TaskbarLib as tbl
taskbar = cc.CreateObject(
    "{56FDF344-FD6D-11d0-958A-006097C9A090}",
    interface=tbl.ITaskbarList3)

rawDescription: Using Windows 7 taskbar features in PyQt


code:
y = [[False for _ in range(10)] for _ in range(22)]
y
y[0][0] = True
y

rawDescription: Defining large list-within- list array

description: Defining large list-within- list array


code:
'''
Created on Apr 3, 2016

@author: Bill BEGUERADJ
'''
import cv2
import numpy as np

drawing=False # true if mouse is pressed
mode=True # if True, draw rectangle. Press 'm' to toggle to curve

# mouse callback function
def begueradj_draw(event,former_x,former_y,flags,param):
    global current_former_x,current_former_y,drawing, mode

    if event==cv2.EVENT_LBUTTONDOWN:
        drawing=True
        current_former_x,current_former_y=former_x,former_y

    elif event==cv2.EVENT_MOUSEMOVE:
        if drawing==True:
            if mode==True:
                cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
                current_former_x = former_x
                current_former_y = former_y
                #print former_x,former_y
    elif event==cv2.EVENT_LBUTTONUP:
        drawing=False
        if mode==True:
            cv2.line(im,(current_former_x,current_former_y),(former_x,former_y),(0,0,255),5)
            current_former_x = former_x
            current_former_y = former_y
    return former_x,former_y

im = cv2.imread("darwin.jpg")
cv2.namedWindow("Bill BEGUERADJ OpenCV")
cv2.setMouseCallback('Bill BEGUERADJ OpenCV',begueradj_draw)
while(1):
    cv2.imshow('Bill BEGUERADJ OpenCV',im)
    k=cv2.waitKey(1)&0xFF
    if k==27:
        break
cv2.destroyAllWindows()

rawDescription: How to make a free hand shape(random) on an image in python using opencv

description: Make a free hand shape(random) on an image in python using opencv


rawDescription: Python: Loop Dictionary, Two keys at a time


rawDescription: Finding and Replacing all Values inside of entries within a List


rawDescription: python - Values not being pulled from XML

description: Python - Values not being pulled from XML


code:
for bperm in permutations(list(B) * 2, r=3):
    for cperm in permutations(C):
        res = {''.join([a, b, c]) for a, b, c in zip(A, bperm, cperm)}

rawDescription: Permutation between three sets in python


code:
connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('CREATE TABLE foo (bar INTEGER UNIQUE, baz INTEGER)')

rawDescription: Basic pySQLite example?

description: Basic pySQLite example


rawDescription: How to do multiple arguments to map function where one remains the same in python?

description: Do multiple arguments to map function where one remains the same in python


code: np.take(a, inds, out=a)

rawDescription: Sorting a record array in numpy

description: Sorting a record array in numpy


code:
import itertools
for a, b in itertools.combinations(mylist, 2):
    compare(a, b)

rawDescription: How to compare each item in a list with the rest, only once?

description: Compare each item in a list with the rest, only once


code:
start_points = numpy.array([[1, 0, 0], [0, 1, 0]])
end_points = numpy.array([[10, 0, 0], [0, 10, 0]])
steps = numpy.arange(10)/9.0
start_points.shape
steps.shape
steps[:,numpy.newaxis,numpy.newaxis].shape
(steps[:,numpy.newaxis,numpy.newaxis] * start_points).shape
(steps[:,numpy.newaxis,numpy.newaxis] * (end_points - start_points)) + start_points

rawDescription: Python time optimisation of for loop using newaxis


code:
from itertools import izip

def first_then(first, then):
    yield first
    while True:
        yield then

def tree_lines(x):
    if type(x) is tuple:
        if len(x) == 1:
            # singular tuple
            for p, l in izip(first_then('--', '  '), tree_lines(x[0])):
                yield p + l
        else:
            first, rest, last = x[0], x[1:-1], x[-1]

            # first entry
            for p, l in izip(first_then('T-', '| '), tree_lines(first)):
                yield p + l

            # middle entries
            for y in rest:
                for p, l in izip(first_then('>-', '| '), tree_lines(y)):
                    yield p + l

            # last entries
            for p, l in izip(first_then('L-', '  '), tree_lines(last)):
                yield p + l
    else:
        yield str(x)

x = ((('A','B'),('C','D')),'E')

for l in tree_lines(x):
    print(l)

rawDescription: Visual alternative for hierarchical tree: (((A,B),(C,D)),E)?


code:
d = TwoWayDict()
d['foo'] = 'bar'
d['foo']
d['bar']
len(d)
del d['foo']
d['bar']

rawDescription: Two way/reverse map

description: Two way/reverse map


code:
from collections import defaultdict

final_score = defaultdict(int)

for i in lista[1:]:
    final_score[str(i[0:-2])] += int(i[-2:]) #

rawDescription: How do I create a dictionary where I add points to names form a text file?

description: Create a dictionary where I add points to names form a text file


code:
class Weapon(object):

    def __init__(self, name, beats):
        self.name = name
        self.beats = beats

    def __gt__(self, other):
        return other.name in self.beats

rawDescription: Python. How to make a class so that I can create a set of related objects(like"Rock, Paper, Scissors") with it?


code:
class MyInt(int):
    difference=lambda self, i: self - i

rawDescription: Setting a lambda function as a property

description: Setting a lambda function as a property


code:
# views.py
from django.db.decorators import commit_on_success

@commit_on_success
def hit(request, page_pk):
    page = Page.objects.filter(pk=page_pk)
    page.hits += 1
    page.save()
    return HttpResponse()

rawDescription: Django AJAX increment

description: Django AJAX increment


code:
def collatz(number):
    print(number)
    if number == 1:
        return
    collatz(number // 2 if number % 2 == 0 else number * 3 + 1)

rawDescription: Python, Loop - Do statements until specific answer is given


code:
class Filter(object):

    def __init__(self, name=None, label=None, widget=None, action=None,
        lookup_type='exact', required=False, grouped=False, **kwargs):
        (...)
        self.grouped = grouped

    def filter_grouped(self, qs, value):
        if isinstance(value, (list, tuple)):
            lookup = str(value[1])
            if not lookup:
                lookup = 'exact' # we fallback to exact if no choice for lookup is provided
            value = value[0]
        else:
            lookup = self.lookup_type
        if value:
            return {'%s__%s' % (self.name, lookup): value}
        return {}

rawDescription: Combine several filters into one filter() with django-filters


code:
"a" in "abcde"
"z" in "abcde"
"abcde".__contains__("a")
"abcde".__contains__("z")

rawDescription: find string mathematical operator

description: Find string mathematical operator


code:
# loop over all samples
def samples(app_sink):
    samples = []
    sample = app_sink.pull_sample()
    while sample:
        yield sample
        sample.get_buffer().pts = Gst.CLOCK_TIME_NONE #unset the pts
        samples.append(sample)
        sample = app_sink.pull_sample()
    print('looping')
    for sample in itertools.cycle(samples):
        yield sample

rawDescription: Looping playback of a list of Gst.Sample with GstApp.AppSrc


code:
def factorial(x):
    return x*x-1

rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code: mask = (sizes > 1).all(axis=1)

rawDescription: Objects' sizes along dimension?

description: Objects' sizes along dimension


code:
class A(object):
    def __init__(self):
        self.one_attribute = 'one'
    def add_attr(self):
        self.new_attribute = 'new'
a = A()
a.one_attribute
a.new_attribute
a.add_attr()
a.new_attribute

rawDescription: Python Class Fields

description: Python Class Fields


code:
# make the debug module reusable
import inspect

def _wrapper(func):
    def call(*args, **kwargs):
        print('entering')
        result = func(*args, **kwargs)
        print('exiting')
        return result
    return call

def _wrapFunc(func):
    # find out which module the original function was
    # declared and wrap it.
    module = inspect.getmodule(func)
    wrapped = _wrapper(func)
    setattr(module, func.__name__, wrapped)
    # return the wrapped function so that the module
    # that called this function can have access to the
    # newly created function
    return wrapped

rawDescription: Wrapping a function imported with import *?


code:
input = """Port       Neighbor Device ID             Neighbor Port ID           TTL
Et2/1      CN-Arista2                       Ethernet5/1                120
Et2/2      CN-Arista2                       Ethernet5/2                120
Et2/3      CN-Arista3                       Ethernet5/3                120
Et2/4      CN-Arista                       Ethernet5/4                120
Et64/1     CN-Spine2                      Ethernet64/1               120
Ma1        Arista01.Dmech.rack01             Ethernet1                  120
"""

#create a test file
fn_in = "./testin.txt"
fn_out = "./testout.txt"

with open(fn_in, "w") as fo:
    fo.write(input)

with open(fn_in, "r") as fi, open(fn_out,"w") as fo:

    #drop first line
    for line in fi.readlines()[1:]:
        #split without argument treats consecutive spaces as 1 separator
        #drop last field
        fields = line.split()[:-1]
        fo.write(", ".join(fields)+"\n")

rawDescription: Python reading a file and parsing the required data


code:
def main():
    with get_file('Enter filename: ') as file:
        while True:
            position = file.tell()              # remember beginning of line
            line = file.readline()              # get the next available line
            if not line:                        # check if at end of the file
                break                           # program is finished at EOF
            file.seek(position)                 # go back to the line's start
            file.write(line.upper())            # write the line in uppercase

def get_file(prompt):
    while True:
        try:                                    # run and catch any error
            return open(input(prompt), 'r+t')   # r+t = read, write, text
        except EOFError:                        # see if user if finished
            raise SystemExit()                  # exit the program if so
        except OSError as error:                # check for file problems
            print(error)                        # report operation errors

if __name__ == '__main__':
    main()

rawDescription: Python: Writing to file using for loop

description: Python: Writing to file using for loop


rawDescription: How to generate a dictionary based on a list and dictionaries

description: Generate a dictionary based on a list and dictionaries


code:
from email.utils import parseaddr
realname, emailaddr = parseaddr(return_path)

rawDescription: Parsing "Return-Path:" in Python

description: Parsing "Return-Path:" in Python


code:
import numpy as np
coords

rawDescription: Numpy: How to create a grid-like array?

description: Numpy: How to create a grid-like array


rawDescription: How to split 16-bit unsigned integer into array of bytes in python?

description: Split 16-bit unsigned integer into array of bytes in python


code:
from app.models import GeoModel
from django.forms.widgets import TextInput
from django.contrib.gis.db import models
from django.contrib import admin

class DirectAdmin(admin.ModelAdmin):
    formfield_overrides = {
        models.PointField: {'widget': TextInput }
    }

admin.site.register(GeoModel, DirectAdmin)

rawDescription: Disabling Openlayers map in GeoDjango Admin


code: data = [[i.strip('%') for i in j] for j in data]

rawDescription: Find and Replace Percent Signs - Python

description: Find and Replace Percent Signs - Python


code: writer = UnicodeWriter(response, quoting=csv.QUOTE_ALL, encoding="utf16")

rawDescription: How can i add encoding to the python generated CSV file

description: Add encoding to the python generated CSV file


code: maximum = [l for l in list2 if l[2]==max(zip(*list2)[2])][0]

rawDescription: What am I doing wrong? Python Reading and Distinguishing


code:
scores = [..., ..., ...]

def processScore(score):
    '''Grades on a curve, where top score = 100%'''
    topScore = max(scores)
    return 100-topScore+score

newScores = [processScore(s) for s in scores]

rawDescription: How to change variables fed into a for loop in list form

description: Change variables fed into a for loop in list form


code:
self.pressed = False

if key[pygame.K_z]:
    self.pressed = True

if self.pressed:
    robsHouse.printText(screen)

rawDescription: Pygame - Blitting Text even after the Key is Pressed


code:
line = 'if def word'
set(line)
set(line.split())

rawDescription: Returning lines containing two or more keywords


rawDescription: Get max or min n-elements out of numpy array? (preferably not flattened)


code:
import matplotlib.pyplot as plt
import pickle

ax = pickle.load(file('myplot.pickle'))
plt.show()

rawDescription: Store and reload matplotlib.pyplot object


code:
from itertools import groupby
my_list = ['A > 1', 'B > 2', '\n', 'C > 3', 'D > 4', '\n', 'E > 5', 'F > 6', '\n']
[list(g) for k, g in groupby(my_list, "\n".__ne__) if k]

rawDescription: Split list in and then join elements in sublists


rawDescription: Initializing Python class with array data


rawDescription: Pandas - Remove rows based on combinations of NaN values


rawDescription: Get current time in milliseconds in Python?


code:
def put_to_list(num):
    return (0, list(range(num, 0, -1)))

rawDescription: Appending numbers into a list in reverse


code: re.split('[, ]+?', test)

rawDescription: using non-greedy qualifiers in regular expression '*?'

description: Using non-greedy qualifiers in regular expression '*?'


code:
settings.py
ITEM_PIPELINES = {
    'mybot.pipelines.DedupPipeline': 0
}

DOWNLOADER_MIDDLEWARES = {
    'mybot.middlewares.DedupMiddleware': 0
}

rawDescription: avoid scrapy revisit on a different run

description: Avoid scrapy revisit on a different run


code: self.activation[1] = np.vstack((self.sigmoid(self.sumHidden), np.array([1])))

rawDescription: Simple backpropagation Neural Network algorithm (Python)


code:
import re
re.split(r'\D', a, maxsplit=1)[0]

rawDescription: moving integers from one string to another?

description: Moving integers from one string to another