code: today = datetime.datetime.now().date()

rawDescription: get time in past from current time

description: Get time in past from current time


rawDescription: How do I test whether an nltk resource is already installed on the machine running my code?

description: Test whether an nltk resource is already installed on the machine running my code


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


rawDescription: split command question

description: Split command question


code:
def poss_comb(coord):
    coord = coord[:]  # use a local copy of the list
    random.shuffle(coord)
    yield coord

rawDescription: Python: How to append generator iteration values to a list


code: files = {'image': ('photo7.jpg', f.seek(0))}

rawDescription: Always empty multipart-encoded files in second POST


code:
def bitstring_to_bytes(s):
    return int(s, 2).to_bytes(len(s) // 8, byteorder='big')

rawDescription: Convert binary string to bytearray in Python 3


rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


code: locale -a

rawDescription: Python - Convert currency code to its sign


code: col_mask = np.isfinite(a).all(axis=0)

rawDescription: Check items in multidimensionaly array in Python


rawDescription: Creating minimal LaTeX syntax from reStructuredText with docutils


code:
def are_int(iterable):
    return all(isinstance(i, int) for i in iterable)

def matrix_dimensions(matrix):
    col = len(matrix[0])
    if not all(len(l) == col and are_int(l) for l in matrix):
        return 'This is not a valid matrix'
    else:
        return len(matrix), col

m = [[1,4,3], [4,0,21], [3,4,[5,7]], [1,2,3], [1,2,3]]
l = [[1,4,3], [4,0,21], [3,4,7], [1,2,3], [1,2,3]]

print(matrix_dimensions(m))
print(matrix_dimensions(l))

rawDescription: validating list as valid Matrix

description: Validating list as valid Matrix


code:
df2 = df.loc[np.repeat(df.index.values,df.n)]
df2

rawDescription: Replicating rows in a pandas data frame by a column value


rawDescription: Sampling with the most recent value

description: Sampling with the most recent value


code:
('BIG Problem Line', 'blah GPS INFO: 238490', 'LONGITUDE: 456', 'LATITUDE: 654')
('BIG Problem Line2', 'GPS INFO: 12343', 'LONGITUDE: 432', 'LATITUDE: 678')

rawDescription: Using Python to run nested string searches


code:
seen = set()
result = []
for d in inputlist:
    representation = set_from_dict(d)
    if representation in seen:
        continue
    result.append(d)
    seen.add(representation)

rawDescription: How make unique a list of nested dictionaries in python


code: coautorshipDictionary = {int(k):int(v) for k,v in json.load(json_data)}

rawDescription: Convert a string key to int in a Dictionary


code:
AUTHENTICATION_BACKENDS = ('project.path.to.MyBackend',
                           'django.contrib.auth.backends.ModelBackend',)

rawDescription: Django: How to override authenticate() method?


code:
unique_list = []
for word in word_list:
    if word not in unique_list:
        unique_list.append(word)
        output_file.write(word + '\n')
output_file.close()

rawDescription: Only Wanting Unique Words in my output file


code:
def combinations(iterable, r):
    # combinations('ABCD', 2) --> AB AC AD BC BD CD
    # combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)

rawDescription: Python: Finding Unique Subsequences of Unique Strings


code: print (datetime.datetime(2012,1,1) + datetime.timedelta(days=299)).month

rawDescription: calculate month out of number of days in year

description: Calculate month out of number of days in year


code:
result = json.loads(ipa)
result[0]
result[1]

rawDescription: Python: print unicode string stored as a variable


code:
def bbox1(img):
    a = np.where(img != 0)
    bbox = np.min(a[0]), np.max(a[0]), np.min(a[1]), np.max(a[1])
    return bbox

def bbox2(img):
    rows = np.any(img, axis=1)
    cols = np.any(img, axis=0)
    rmin, rmax = np.where(rows)[0][[0, -1]]
    cmin, cmax = np.where(cols)[0][[0, -1]]

    return rmin, rmax, cmin, cmax

rawDescription: bounding box of numpy array

description: Bounding box of numpy array


code: cursor = db.test.find(timeout=False)

rawDescription: How to close cursor in MongoKit

description: Close cursor in MongoKit


code:
urlpatterns = [
    url(r'^', include(router.urls)),
]

if settings.DEBUG:
    print_url_pattern_names(urlpatterns)

rawDescription: Add a HyperLink in django-rest-framework to a ModelViewSet


map:
function(doc) {
  emit([doc.prod_id, doc.logtime], doc);
}

rawDescription: How to query a couchdb view using a composite key?

description: Query a couchdb view using a composite key


code:
class MyInt(int):
     pass

print(isinstance(MyInt('3'),int)) #True

rawDescription: Python check if all elements of a list are the same type


code: age = age + 1

rawDescription: How to add on python

description: Add on python


rawDescription: search for before and after values in a long sorted list

description: Search for before and after values in a long sorted list


code:
encoded = pickled_data.decode('latin1')
pickle.loads(encoded)
pickle.loads(encoded.encode('latin1'))

rawDescription: How to pickle unicodes and save them in utf-8 databases

description: Pickle unicodes and save them in utf-8 databases


code: resource_path = os.path.join(app.root_path, 'enltk_data')

rawDescription: Refering to a directory in a Flask app doesn't work unless the path is absolute


code: qry = session.query(A).filter(A.b_s.any(B.flag == False))

rawDescription: SQLAlchemy, select such A that has at least one B with raised flag


rawDescription: Using Django markup in CSS

description: Using Django markup in CSS


code:
pattern=re.compile("[^\w']")
pattern.sub(' ', "doesn't it rain today?")

rawDescription: Python Regex - Remove special characters but preserve apostraphes


rawDescription: Need to aggregate count(rowid, colid) on dataframe in pandas


code:
phone = TextField(label='Phone',
                  validator=twc.Required,
                  css_class='MyTextFieldClass',
                  attrs=dict(style='display:block;width:8em', maxlength='12'))

rawDescription: TurboGears2 - how to customize layout for new user form?


code:
def is_numeric(s):
    s = s.strip()
    parts = s.split('.', 1)
    return all(part.isdigit() for part in parts)

def parse_input(line):
    parts = line.split(',')
    if not all(is_numeric(part) for part in parts):
        return []
    else:
        return [float(part) for part in parts]

while True:
    line = input("You will provide numbers. Provide! Provide! ")
    if not line:
        break
    values = parse_input(line)
    print("Reporting provided numbers:", values)

rawDescription: Check if input is either digits or period


code:
def function(astring):
  astring= 'variable = ' + astring
  exec(astring)
  return eval('variable')

function('42')

rawDescription: Function internally using exec(astring) with a variable definition inside astring can not return the variable in python 3


code:
def app():
    x=5
    exec("x+=1")
    print(x)

app()

rawDescription: using exec() with python 3.2

description: Using exec() with python 3.2


code:
l1 = set(l1)
d2 = {k: [s for s in v if s in l1] for k, v in d1.iteritems()}
d2 = {k: v for k, v in d2.iteritems() if v}

rawDescription: Python dictionary comprehension very slow


code: last_name = getattr(soup.find('last_name'), 'string', None)

rawDescription: Parsing XML with BeautifulSoup and handling missing element


code:
m, _, n = a.shape
chunksize = 10**4
d = np.zeros((n,n))
for i in range(0, m, chunksize):
    b = a[i:i+chunksize]
    d += ((b - b.swapaxes(1,2))**2).sum(axis=0)

rawDescription: Efficient Numpy computation of pairwise squared differences


code:
ORDER = "0123456789aàáäåæbcçdeèéêfghiìíîjklmnñoòóôöøpqrsßtuùúüvwxyzžα"
# associate each char with the index in the string
# this makes sort faster for multiple invocations when compared with
# ORDER.index(c)
POS = {c:p for (p, c) in enumerate(ORDER)}

lst = ['x', 'h', 'ê', 'ø', '5', 'ž', 'z', 'α', '3', '1']

lst.sort(key = lambda c: POS[c])
# or, suggested by wim
lst.sort(key = POS.get)

rawDescription: How to sort a list of strings with a different order?

description: Sort a list of strings with a different order


code:
d, b, a = discrim(1, 0, -4)
the_rest(d, b, a)

rawDescription: Python returning variables from various functions


code:
from django.db.models import F

def thread1():
    update_or_create(SomeModel,
                     {'some_unique_field':1},
                     {'some_field': F('some_field') + 1})

def thread2():
    update_or_create(SomeModel,
                     {'some_unique_field':1},
                     {'some_field': F('some_field') + 2})

rawDescription: Django. Thread safe update or create.

description: Django. Thread safe update or create.


code:
import goslate
gs = goslate.Goslate()
print(gs.translate('hello world', 'de'))

rawDescription: How can I easily machine translate something with python?

description: Easily machine translate something with python


code:
def isperfect(n):
    factors = [1]+[i for i in range(2,n+1) if n%i == 0]
    if sum(factors) == 2*n:
        return True
    return False

for i in range(1000):
    if isperfect(i):
        print(i)

rawDescription: Perfect numbers in python

description: Perfect numbers in python


code:
def get_currency_by_type(curr, curr_type):
    for elem in curr:
        val, val_type = elem['currency'].split(',')
        if val_type == curr_type and float(val) > 0:
            yield float(val)

usd_curr = list(get_currency_by_type(curr, 'USD'))

rawDescription: python 3.4 list comprehension - calling a temp variable within list

description: Python 3.4 list comprehension - calling a temp variable within list


code:
import numpy as np

st = np.mgrid[1:101, 1:101]
s, t = st
cov = st.min(axis=0) - s * t

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
books = [a.book_set.latest('pub_date') for a in Author.objects
                   .annotate(latest=Max('book__pub_date'))
                   .order_by('-latest')[:5]]

rawDescription: How to retrieve the first X objects with unique attribute value

description: Retrieve the first X objects with unique attribute value


code:
limit = 100
prev_items = []

# Open file and iterate over lines.
with open('names.txt') as f:
    for line in f:
        # Add the current line to the list.
        prev_items.append(line)
        # Reduce the list to its newest elements.
        prev_items = prev_items[-limit:]

        # If the current line is 'Alpha', we don't need to read any more.
        if line == 'Alpha':
           break

# Append prev_items to the results file.
with open('results.txt', 'a') as f:
    f.write('\n'.join(prev_items))

rawDescription: python search a string in a text file and copy a block

description: Python search a string in a text file and copy a block


code:
N = 5
idx = np.arange(N)
idx = idx[1:] - (idx[:, None] >= idx[1:])
idx

rawDescription: python leave-one-out estimation

description: Python leave-one-out estimation


code:
curses.echo()            # Enable echoing of characters

# Get a 15-character string, with the cursor on the top line
s = stdscr.getstr(0,0, 15)

rawDescription: How to input a word in ncurses screen?

description: Input a word in ncurses screen


code: [('viewAllLimiter =', '0')]

rawDescription: Search string with re module in html page


rawDescription: Working of Enumerate in Python

description: Working of Enumerate in Python


code:
def get_initial(self):
    initial = super(MyCreateView, self).get_initial()
    initial['user'] = self.request.user
    return initial

rawDescription: Django: How do I add data to a ModelForm subclass before validation?


code:
from pycorenlp import StanfordCoreNLP
stanford = StanfordCoreNLP('http://localhost:9000')
text = ("Selected variables by univariate/multivariate analysis, constructed logistic regression, calibrated the low defaults portfolio to benchmark ratings, performed back")
output = stanford.annotate(text, properties={'annotators': 'tokenize,ssplit,pos,depparse,parse', 'outputFormat': 'json'})
print(output['sentences'][0]['parse'])

rawDescription: Getting NLTK tree leaf values as a string


rawDescription: How do I define a different logger for an imported module in Python?

description: Define a different logger for an imported module in Python


code:
from collections import defaultdict

result = defaultdict(list)
with open("sentences.txt","r") as filer:
    for line in filer:
        label, sentence = line.strip().split(' ', 1)
        result[label].append(sentence)

rawDescription: How do I group sentences depending on the label?

description: Group sentences depending on the label


code:
import sys
import os
from plotly import session, tools, utils
import uuid
import json

def get_plotlyjs():
    path = os.path.join('offline', 'plotly.min.js')
    plotlyjs = resource_string('plotly', path).decode('utf-8')
    return plotlyjs

def js_convert(figure_or_data,outfilename, show_link=False, link_text='Export to plot.ly',
          validate=True):

    figure = tools.return_figure_from_figure_or_data(figure_or_data, validate)

    width = figure.get('layout', {}).get('width', '100%')
    height = figure.get('layout', {}).get('height', 525)
    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    try:
        float(width)
    except (ValueError, TypeError):
        pass
    else:
        width = str(width) + 'px'

    plotdivid = uuid.uuid4()
    jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder)
    jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder)

    config = {}
    config['showLink'] = show_link
    config['linkText'] = link_text
    config["displaylogo"]=False
    config["modeBarButtonsToRemove"]= ['sendDataToCloud']
    jconfig = json.dumps(config)

    plotly_platform_url = session.get_session_config().get('plotly_domain',
                                                           'https://plot.ly')
    if (plotly_platform_url != 'https://plot.ly' and
            link_text == 'Export to plot.ly'):

        link_domain = plotly_platform_url\
            .replace('https://', '')\
            .replace('http://', '')
        link_text = link_text.replace('plot.ly', link_domain)

    script = '\n'.join([
        'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{',
        '    $(".{id}.loading").remove();',
        '}})'
    ]).format(id=plotdivid,
              data=jdata,
              layout=jlayout,
              config=jconfig)

    html="""

                 Drawing...

                 """.format(id=plotdivid, script=script,
                           height=height, width=width)

    #html =  html.replace('\n', '')
    with open(outfilename, 'wb') as out:
        out.write(r'')
        for line in html.split('\n'):
            out.write(line)

        out.close()
    print ('JS Conversion Complete')

rawDescription: Plot 3D plots using plotly

description: Plot 3D plots using plotly


code:
my_class = MyClass()
scheduler.add_job(my_class.post, 'interval', {'seconds': 3}, kwargs={'first_argument': first_argument})

rawDescription: passing current object to python apscheduler method

description: Passing current object to python apscheduler method


code:
def acorr(x, ax=None):
    if ax is None:
        ax = plt.gca()

    x = x - x.mean()

    autocorr = np.correlate(x, x, mode='full')
    autocorr /= autocorr.max()

    return ax.stem(autocorr)

fig, ax = plt.subplots()
acorr(data)
plt.show()

rawDescription: bug of autocorrelation plot in matplotlib‘s plt.acorr?

description: Bug of autocorrelation plot in matplotlib‘s plt.acorr


code:
literal_eval(r"'Hello World!'")
literal_eval(r"'\'Stack Overflow\''")
literal_eval(r"""'x=\"x=\'Python\n\'\"'""")

rawDescription: Python find python strings in string

description: Python find python strings in string


code:
from collections import defaultdict
import re

def humantime2minutes(s):
    d = {
      'w':      7*24*60,
      'week':   7*24*60,
      'weeks':  7*24*60,
      'd':      24*60,
      'day':    24*60,
      'days':   24*60,
      'h':      60,
      'hr':     60,
      'hour':   60,
      'hours':  60,
    }
    mult_items = defaultdict(lambda: 1).copy()
    mult_items.update(d)

    parts = re.search(r'^(\d+)([^\d]*)', s.lower().replace(' ', ''))
    if parts:
        return int(parts.group(1)) * mult_items[parts.group(2)] + humantime2minutes(re.sub(r'^(\d+)([^\d]*)', '', s.lower()))
    else:
        return 0

print(humantime2minutes('1 week 3 days 1 hour 30 min'))
print(humantime2minutes('2h1m'))

rawDescription: convert "1h30min" string to minutes in python

description: Convert "1h30min" string to minutes in python


code:
import heapq
dic = {}
dic.update({k:d[k] for k in heapq.nlargest(2, d, key=d.get)})
dic

rawDescription: put top 2 biggest keys and values of dictionary in another dictionary

description: Put top 2 biggest keys and values of dictionary in another dictionary


code:
test = foo('matchthis -butnothis -"and not this"')
test("we should matchthis...")
test("some stuff matchthis blah and not this...")

rawDescription: Python advanced string searching with operators and boolean


rawDescription: zip two values from the dictionary in Python

description: Zip two values from the dictionary in Python


rawDescription: defaultdict equivalent for lists

description: Defaultdict equivalent for lists


code:
thing = [[20,0,1],[20,0,2],[20,1,1],[20,0],[30,1,1]]
dico = {}
for x in thing:
    if not tuple(x[:2]) in dico:
        dico[tuple(x[:2])] = x[2:]
        continue
    if tuple(x[:2])[1] < x[1]:
        dico[tuple(x[:2])] = x[2:]

new_thing = []
for i, j in dico.items():
    new_thing.append(list(i) + j)

rawDescription: Unique items in a list with condition

description: Unique items in a list with condition


code: df = pd.read_csv('data', dtype=object, encoding='utf-8').set_index('Contract')

rawDescription: Numbers used as string in Pandas index

description: Numbers used as string in Pandas index


code:
def digit_or_slash(s):
    return all([c.isdigit() or c == '/' for c in s])

digit_or_slash(match)
digit_or_slash(no_match)

rawDescription: How to I check that a string contains only digits and / in python?


rawDescription: grouping pandas dataframe by two columns (or more)?

description: Grouping pandas dataframe by two columns (or more)


rawDescription: How can i access element value in SOAP response with lxml objectify

description: Access element value in SOAP response with lxml objectify


code: self.pegs = self.ax.scatter([0], [0], s=100, facecolor='#dd8800',edgecolor='black', picker=self.pegs_picker)

rawDescription: Matplotlib pick event order for overlapping artists


code:
from flask import Blueprint

class MyBlueprint(Blueprint):

    bp_data = {}

    def set_data(data):
        # here you can make extra task like ensuring if
        # a minum group of value were provided for instance
        bp_data = data

rawDescription: Flask Blueprint Initialization - Initializing some global variables


code:
id=("a","b")
start_L=(1,15)
stop_L=(16,40)

i=0
table=open('largefile.tsv',"r")
out1=(("file%s.txt")%(id[i]))
temp_out=open(out1,"w")

# start iterating through the file
for line in table:
     stop=int(stop_L[i])

     # Split the line into a position piece, and a
     # throw away variable based upon the 1st tab char
     position,the_rest= line.split("\t",1)

     # I'm ignoring start as you mentioned it was sorted in the file
     if int(position) >= stop :
           # Close the current file
           temp_out.close()

           # Increment index so file name is pulled from id properly
           # If the index is past the length of the id list then
           # break otherwise open the new file for writing
           i += 1
           if (i < len(id)):
             out1=(("file%s.txt")%(id[i]))
             temp_out=open(out1,"w")
           else:
             break

     temp_out.write(line)

rawDescription: splitting a large tab delimited file in python

description: Splitting a large tab delimited file in python


code: import seaborn.apionly as sns

rawDescription: Seaborn configuration hides default matplotlib


code: '%-20s %s' % ('## execute', 'Execute an IRC command')

rawDescription: How to Left Justify part of a String in python?

description: Left Justify part of a String in python


rawDescription: getting only integers from a list of tuples python 3

description: Getting only integers from a list of tuples python 3


rawDescription: Python list writing through loop, all previous values being overwritten


code:
from tkinter import *
from tkinter import colorchooser

mGui = Tk()
mGui.geometry("600x300+500+500")
mGui.title("Hexadecimal Color Chooser")

def getColor():
    color_choice = colorchooser.askcolor()[1]  # get the hex code
    color = Label(mGui, bg=color_choice)
    color.pack()
    hexcode = Label(mGui, text="The hexadecimal color code is: "+color_choice)
    hexcode.pack()

button = Button(mGui, text="Choose a color", command=getColor)
button.place(x=0, y=0)

mGui.mainloop()

rawDescription: How to make a label with the background color as a color chosen by the user?

description: Make a label with the background color as a color chosen by the user


code:
import scipy.stats as stats
stats.kstest(np.random.normal(0,1,10000),'norm')

rawDescription: Implementing a Kolmogorov Smirnov test in python scipy


code:
if hours > 12:
    afternoon = True
    hours -= 12
else:
    afternoon = False
    if hours == 0:
        # Special case
        hours = 12

rawDescription: 24-Hour Time Conversion to 12-Hour Clock (ProblemSetQuestion) on Python


code:
sums = []
prev = -1
curr_sum = 0

for element in data:
    if element != prev:
        if prev > 0:
            sums.append(curr_sum)
        curr_sum = 0
        prev = 0
    curr_sum += element

sums.append(curr_sum)

rawDescription: calculate the sum of repeated numbers in a tuple

description: Calculate the sum of repeated numbers in a tuple


code:
from redis import Redis
r = Redis(host="hostname-of-machine-running-redis")
while r.llen('jobs:machine1'):
    job = r.lpop('commands:machine1')
    os.system('sh ' + job + ' &')

rawDescription: Python ( or maybe linux in general) file operation flow control or file lock


code:
print ('Welcome to Hangman! By Aaron Taylor')
print (HANGMANPICS[6])
words = Welcome()
MISSEDLETTERS = ''
CORRECTLETTERS = ''
SECRETWORD = getRandomword(words)

done = False

while True:
    Display(HANGMANPICS,MISSEDLETTERS,CORRECTLETTERS,SECRETWORD)

rawDescription: Hangman program

description: Hangman program


code:
from myapp.models import Mall, Shop, Employee
m = Mall(name="Super Mall")
m.save()
Mall.objects.all()

rawDescription: How do I create this object with the models I have set up?

description: Create this object with the models I have set up


code:
def stepashka_spider(max_pages):
    for page in range(1,max_pages+1):
        url = "http://online.stepashka.com/filmy/page/{}/".format(page)
        source_code = requests.get(url)
        plain_text = source_code.text
        soup = BeautifulSoup(plain_text)
        print("Movies for page {}".format(page))
        for resoult in soup.findAll("div", {"class": "video-title"}):
            a_tag = resoult.a
            print(a_tag["href"])
        print()

rawDescription: Python Web Crawler not printing any result


code:
def allbinarytrees(s):
    if len(s) == 1:
        yield s
    else:
        for i in range(1, len(s), 2):
            for l in allbinarytrees(s[:i]):
                for r in allbinarytrees(s[i+1:]):
                    yield '({}{}{})'.format(l, s[i], r)

rawDescription: What python code generates all possible groupings (trees) for binary operators


code:
my_list = ["This", "is", "an", "example", "list", "hehe", "onemore"]
map(None, *[iter(my_list)] * counter)
from itertools import izip_longest
list(izip_longest(*[iter(my_list)] * counter, fillvalue = ''))

rawDescription: Getting every X word from list

description: Getting every X word from list


code: lambda rec: rec.desired_field

rawDescription: Opening and searching dBase III (DBF) databases in Python


code:
#line = input() # python 3
line = raw_input() # python 2

print("received:", line)

rawDescription: Passing argument from one python script to another


code:
directions = (
    (1, 0, '>'),
    (0, 1, 'v'),
    (-1, 0, '<'),
    (0, -1, '^'),
)

def solve(x, y, mazeList=None):
    if mazeList is None:
        mazeList = loadMaze("sample.maze")

    for dx, dy, char in directions:
        nx, ny = x + dx, y + dy

        if mazeList[ny][nx] == "E":
            return "YOU'VE SOLVED THE MAZE!"

        if mazeList[ny][nx] == " ":
            new_maze = [m[:] for m in mazeList]
            new_maze[ny][nx] = char
            result = solve(nx, ny, new_maze)
            if result is not None:
                return result

rawDescription: Runtime Error in python: "Maximum recursion depth exceeded"


rawDescription: Insert multiple rows into DB with Python list of Tuples


rawDescription: Regex Help, por favor

description: Regex Help, por favor


rawDescription: Doubly Linked list in Python

description: Doubly Linked list in Python


code:
from django.contrib.auth.models import User
from key_auth.models import SecurityKey

class KeyAuthBackend(object):
    def authenticate(self, key=None):
        try:
            return SecurityKey.objects.get(key=key).user
        except SecurityKey.DoesNotExist:
            return None

    def get_user(self, user_id):
        try:
            return User.objects.get(pk=user_id)
        except User.DoesNotExist:
            return None

rawDescription: Security issues with a middleware screener page


code:
pd.read_csv('rawdata.txt', converters={'voltage(V)': binary, 'current(A)': binary},
                 names='time(s) voltage(V) current(A)'.split(), skiprows=1)

rawDescription: I am trying to get binary data from text and converting to numpy arrays


code:
from Tkinter import *

root = Tk()

premadeList = ["foo", "bar", "baz"]

for checkBoxName in premadeList:
    c = Checkbutton(root, text=checkBoxName)
    c.pack()

root.mainloop()

rawDescription: Dynamically add checkboxes with tkinter in python 2.7


code: sum([x._short_opts + x._long_opts for x in parser._get_all_options()],[])

rawDescription: Python : Not able to get the list of the options that have been added via 'add_option'?


code:
parser = argparse.ArgumentParser(description=func.__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter)

rawDescription: Python’s argh library: preserve docstring formatting in help message


code:
text = el.text
text += ''.join(map(lxml.html.tostring, el.iterchildren()))

rawDescription: Python, lxml and removing outer tag from using lxml.html.tostring(el)


code:
import xml.etree.ElementTree as ET
import collections

refdoc = """<Items>
    <Timestamp></Timestamp>
    <Item>
        <ID>1</ID>
        <ID>2</ID>
        <ID>3</ID>
        <ID>4</ID>
    </Item>
    <Item>
        ...
    </Item>
</Items>"""

doc = ET.XML(refdoc)
counts = collections.Counter(elem.tag for elem in doc)
print(counts)
total = sum(count for count in counts.values() if count > 1)
print(total)

rawDescription: How to detect number of xml nodes?

description: Detect number of xml nodes


code:
import pip

_all_ = [
    "SOAPpy>=0.12.22",
    "pycrypto>=2.6.1",
    "suds>=0.4",
    "Python-ldap>=2.4.19",
    "paramiko>=1.15.2",
    "nose>=1.3.4",
    "selenium>=2.44.0",
    "bottle>=0.12.8",
    "CherryPy>=3.6.0",
    "pika>=0.9.14",
]

windows = ["wmi-client-wrapper>=0.0.12",]

linux = ["WMI>=1.4.9",]

darwin = []

def install(packages):
    for package in packages:
        pip.main(['install', package])

if __name__ == '__main__':

    from sys import platform

    install(_all_)
    if platform == 'windows':
        install(windows)
    if platform == 'linux':
        install(linux)
    if platform == 'darwin': # MacOS
        install(darwin)

rawDescription: Is there a way to have a conditional requirements.txt file for my Python application based on platform?


code:
from astropy.coordinates import SkyCoord
import astropy.units as u
import numpy as np
phi = np.linspace(0,2*np.pi,20)
theta = np.linspace(0, np.pi, 20)
radecs = SkyCoord(ra=phi*u.rad, dec=(0.5*np.pi - theta)*u.rad)
radecs

rawDescription: How to sort through a list of observable coordinates?

description: Sort through a list of observable coordinates


rawDescription: How to remove the last element in each tuple in a list

description: Remove the last element in each tuple in a list


code:
number, salary, position, rest = items.split(None, 3)
oname, first = rest.rsplit(None, 1)
data.append((first, oname, number, position, salary))

rawDescription: Tuple rearrangment Python

description: Tuple rearrangment Python


code: k2 = ndb.Key(Revision, '2', parent=ndb.Key('Account', 'Sandy', 'Message', 'greetings'))

rawDescription: GAE Transaction Alternatives to overcome entity group limit of 5


code:
lst = ['abcdef', 'uvwxyz']
[x[::-1] for x in lst]

rawDescription: Reverse the content of each element in a list python


code:
{k: {l.strip(): [n.strip() for n in nums.split(',')]
     for i in v.split(';')
     for l, nums in (i.split(':', 1),)}
 for k, v in tuplist}

rawDescription: How to convert this tuple list to this dict in a Pythonic way?

description: Convert this tuple list to this dict in a Pythonic way


code: menu=QMenu(self)

rawDescription: How to apply CSS Style to QMenu via an entire MainWIndow

description: Apply CSS Style to QMenu via an entire MainWIndow


code: bitvalues[tuple((x & y) != 0 for y in pot)] = chr(x)

rawDescription: Python: What's the best way to send status bits and timestamps with PySerial


code:
def isEven(x):
    return any(v % 2 == 0 for v in x)

rawDescription: Python: Function to find out if a tuple contains even numbers?


code:
# A hack, since I do not know how to deal with iso-8859-8-i
content=content.replace('iso-8859-8-i','iso-8859-8')
doc=ET.fromstring(content)

rawDescription: How can I scrape data from the Israeli Bureau of Statistics web query tool?

description: Scrape data from the Israeli Bureau of Statistics web query tool


code: splitted_line = line.split(',', 4)

rawDescription: How to parse csv file and compute stats based on that data

description: Parse csv file and compute stats based on that data


code: [odd_digits] + [zero_to_nine]*(ndigits-2) + [even_digits]

rawDescription: How many inverse numbers equal only odd numbers under 1 billion


code: myvar = "String",value,"more string"

rawDescription: How to eliminate {} brackets from message box

description: Eliminate {} brackets from message box


rawDescription: Tkinter label overwrite: update or refresh?


rawDescription: Python Pandas qcut behavior with # of observations not divisible by # of bins


rawDescription: Checking a List for a Sequence

description: Checking a List for a Sequence


code:
import time
import asyncio
from concurrent.futures import ProcessPoolExecutor

def blocking_func(x):
   time.sleep(x) # Pretend this is expensive calculations
   return x * 5

@asyncio.coroutine
def main():
    #pool = multiprocessing.Pool()
    #out = pool.apply(blocking_func, args=(10,)) # This blocks the event loop.
    executor = ProcessPoolExecutor()
    out = yield from loop.run_in_executor(executor, blocking_func, 10)  # This does not
    print(out)

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: What kind of problems (if any) would there be combining asyncio with multiprocessing?


code:
main.pro
TEMPLATE = app
TARGET = qdir-traverse
QT = core
SOURCES += main.cpp

rawDescription: os.walk analogue in PyQt

description: Os.walk analogue in PyQt


code:
class MyClass(object):

    def __init__(self, init_dict={}):
        """
        initialize internal data structures with 'init_dict'
        """
        for k, v in itit_dict.items():
            # do something with k & v
            setattr(self, k, v)

    @classmethod
    def from_sequence(cls, init_list):
        """
        initialize internal  data structures with 'init_list'
        """
        result = cls()
        for item in init_list:
            setattr(result, item, None)
        return result

rawDescription: The most pythonic way to implement two constructors


rawDescription: How can I have my program read updates that it has just made to a text file?

description: Have my program read updates that it has just made to a text file


code:
import os
import sys

# create a dog and test its speak action
def test_dog():
    from farm.animals.dog import dog
    d = dog("Allen")
    d.speak()

def test_cat():
    from farm.animals.dog import cat
    c = cat("Micy")
    d.speak()

def test_rabbit():
    from farm.animals.dog import rabbit
    r = rabbit()
    r.speak()

rawDescription: Running python scripts within a subpackage of my package


code: print("You know "+ str(len(words)), "unique word(s)!")

rawDescription: How to not count the duplicates from an user input?

description: Not count the duplicates from an user input


rawDescription: How to create a copy of a python function

description: Create a copy of a python function


code:
somestring = 'abcd'

with open("test.bin", "wb") as file:
    file.write(somestring.encode('ascii'))

rawDescription: Writing an ASCII string as binary in python


rawDescription: ggplot styles in Python

description: Ggplot styles in Python


code:
ts_float = float(ts[0]) + float(ts[1]) / 1000000
dt.fromtimestamp(ts_float)

rawDescription: Time tuple to a datetime

description: Time tuple to a datetime


code:
def calculateProportions(strategies,proportions):
    import itertools
    combinations = []
    columns = list(itertools.product(strategies, repeat=3))
    for i in range(0, len(columns)):
        columns[i] = list(columns[i])
    for n in range(0, len(strategies)):
        combinations.append([item[:] for item in columns])

rawDescription: Cloned list seems to be functioning as an alias, even though explicitly declared as a a clone


code:
with open("test.csv", "r") as inp, open("foo.csv", "w") as out:
    w = csv.writer(out, delimiter=",")
    w.writerows(x for x in csv.reader(inp, delimiter="#"))

rawDescription: Replace column separation of # with comma or tab


rawDescription: How does readline and readlines work in Python


rawDescription: Python - How to transform a list of tuple to a tuple


code:
def union(self,p,q):
        self.pid = self.id[p]
        self.qid = self.id[q]
        for i in range(len(self.id)):
                if(self.id[i]==self.pid):
                        self.id[i]=self.qid

rawDescription: python too many self in class

description: Python too many self in class


code:
try:
  binary = struct.pack('>f', value)
except OverflowError:
  binary = struct.pack('>d', value)

rawDescription: Differentiate between single and double precision


code:
from scipy.spatial import Delaunay
tri = Delaunay(points[:,:2])
len(tri.simplices)
tri.simplices

rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code:
import MySQLdb
import csv
import pprint
import time

MAX_CACHE_AGE = 60*20  # 20 Minutes
CACHE_FILENAME = 'results.cache'

with open(CACHE_FILENAME, 'r') as cache:
    cached = pickle.load(cache)

if(time.time() > cached['timestamp'] + MAX_CACHE_AGE):
    # Cache too old, run query
    db = MySQLdb.connect(host="localhost", # The Host
                     user="username", # username
                     passwd="password", # password
                     db="dbname") # name of the data base

    cursor = db.cursor()
    cursor.execute("SELECT name, id, city, storeid FROM Products;")
    StudentsData = cursor.fetchall()

    # Update cache file
    data = {'results': StudentsData, 'timestamp':time.time()}
    with open(CACHE_FILENAME, 'w') as cache:
        pickle.dump(data, cache)

else:
    # Cached data is fresh enough, use that
    StudentsData = cached['results']

pprint.pprint(StudentsData)

rawDescription: caching mysql query returned by Python script

description: Caching mysql query returned by Python script


rawDescription: How to flash tkinter label limited number of times, and only if conditions are met

description: Flash tkinter label limited number of times, and only if conditions are met


code:
# for large numbers, xrange will throw an error.
# OverflowError: Python int too large to convert to C long
# to get over this:

def mrange(start, stop, step):
    while start < stop:
        yield start
        start += step

# benchmarked on an old single-core system with 2GB RAM.

from math import sqrt

def is_prime(num):
    if num == 2:
        return True
    if (num < 2) or (num % 2 == 0):
        return False
    return all(num % i for i in mrange(3, int(sqrt(num)) + 1, 2))

# benchmark is_prime(100**10-1) using mrange
# 10000 calls, 53191 per second.
# 60006 function calls in 0.190 seconds.

rawDescription: Working with large primes in Python

description: Working with large primes in Python


rawDescription: Typecast "340" to int results in '34' losing the last zero


code: crypto = rsa.encrypt(message, bob_pub)

rawDescription: Decripting RSA in python

description: Decripting RSA in python


code: import ast.literal_eval as eval

rawDescription: raw_input() and math equations

description: Raw_input() and math equations


rawDescription: how to apply ceiling to pandas DateTime

description: Apply ceiling to pandas DateTime


code:
super(B, B).m
super(B, B).m()
super(B, B).m(B())

rawDescription: Usage of Python 3 super()

description: Usage of Python 3 super()


code:
def callback(event):
    current = event.widget.get()
    #compare value here and select nearest
    event.widget.set(newvalue)

rawDescription: tkinter: slider ("scale") with discrete steps?

description: Tkinter: slider ("scale") with discrete steps


code: printer.setPageMargins(12, 16, 12, 20, QPrinter.Millimeter)

rawDescription: How to set QTextDocument margins and other properties (setHTML, print to pdf)?

description: Set QTextDocument margins and other properties (setHTML, print to pdf)


code:
def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))

rawDescription: what's a good way to combinate through a set?

description: What's a good way to combinate through a set


code: for i in range(lst.count(itemToExclude)): lst.remove(itemToExclude)

rawDescription: What is the fastest way to remove all instances of a particular entry from a list in Python?


rawDescription: Python regex substitution using a dictionary


code:
import matplotlib.pyplot as plt
import networkx as nx

G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
G.add_edge(3,5)
G.add_edge(4,6)
G.add_edge(1,6)
G.add_edge(2,6)
G.add_edge(7,8)
G.add_edge(9,8)

tree = nx.bfs_tree(G, 4)
nx.draw(tree)
plt.savefig('/tmp/bfs_image.png')

rawDescription: How can i get directed tree from graph?

description: Get directed tree from graph


code:
#urls.py
urlpatterns = patterns(
    url(r'^setup-form/$', views.SetupView.as_view(), name='setup-form'),
    url(r'^base_collect/$', views.base, name = 'base-form'),
)

rawDescription: Django, redirected url is not proper

description: Django, redirected url is not proper


code: newdict

rawDescription: Modifying a dictionary with datetime as keys


code: [i for i in lst if i == y]

rawDescription: Writing the filter() function using for/while loops


code:
# INSERT TEST DATA
a1 = Asset(
    version=0,
    documents=[
        AssetDocument(version=1),
        AssetDocument(version=2),
    ])
session.add(a1)
session.commit()

# TEST MODIFICATIONS
# remove first one
del a1.documents[0]
# insert a position 0
a1.documents.insert(0, AssetDocument(version=3))
# add at the end
a1.documents.append(AssetDocument(version=4))
session.commit()

# check that the document_idx are properly ordered
q = (session
     .query(AssetAssetDocument.asset_document_id)
     .filter(AssetAssetDocument.asset_id == a1.id)
     .order_by(AssetAssetDocument.documents_idx)
     )
doc_ids = [x.asset_document_id for x in q]
assert doc_ids == [3, 2, 4]

rawDescription: SQLAlchemy Join Table with a field to order the rows


rawDescription: numpy take can't index using slice

description: Numpy take can't index using slice


code:
from urlparse import urlsplit
urlsplit('http://www.sparkbrowser.com/index.php')
_.netloc

rawDescription: Python web scraping - print only part of url


code:
def _today():
    """Todays date formatted as a string"""

    todays_date = datetime.date.today()
    return todays_date.strftime('%d.%m.%Y')

rawDescription: python: datetime within module always provides date of first call

description: Python: datetime within module always provides date of first call


rawDescription: How to get the index range of a list that the values satisfy some criterion in Python?

description: Get the index range of a list that the values satisfy some criterion in Python


code:
import datetime
import collections

Entry = collections.namedtuple('Entry', ['date', 'location'])

entries = []

entries.append(Entry(datetime.datetime.now(), "Siberia"))
entries.append(Entry(datetime.datetime.now(), "Wisconsin"))

rawDescription: Best way to keep the elements of a structure up to date

description: Keep the elements of a structure up to date


code:
import numpy as np
from scipy import interpolate

data = np.genfromtxt('data.txt')

x = data[:,0]  #first column
y = data[:,1]  #second column

f = interpolate.interp1d(x, y)

xnew = np.arange(1, 5.1, 0.1) # this could be over the entire range, depending on what your data is
ynew = f(xnew)   # use interpolation function returned by `interp1d`

fig = plt.figure()
ax1 = fig.add_subplot(111)

ax1.set_title("Plot B vs H")
ax1.set_xlabel('B')
ax1.set_ylabel('H')

ax1.plot(x,y, c='r', label='the data')
ax1.plot(xnew, ynew, 'o', label='the interpolation')

leg = ax1.legend()
plt.show()

rawDescription: how to interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program?

description: Interpolate points in a specific interval on a plot formed by loading a txt file in to scipy program


code:
#!/usr/bin/env python

import os
import subprocess

from setuptools import setup, Extension

def mysql_test_extension():
    process = subprocess.Popen(['which', 'mysql_config'],
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               close_fds=True)

    result, error = process.communicate()
    if process.returncode > 0:
        raise RuntimeError(error)

    config_command = result.strip()

    cflags = subprocess.check_output([config_command, '--cflags'], close_fds=True).strip()

    include_dirs = []
    extra_compile_args = []
    for arg in cflags.split(' '):
        if not arg.strip():
            continue
        elif arg.startswith('-I'):
            include_dirs.append(arg[2:])
        elif arg.startswith('-'):
            extra_compile_args.append(arg)
        else:
            extra_compile_args[-1] = extra_compile_args[-1] + ' ' + arg

    libs = subprocess.check_output([config_command, '--libs'], close_fds=True).strip()

    libraries = []
    linkers = []
    for arg in libs.split(' '):
        if not arg.strip():
            continue
        elif arg.startswith('-L'):
            libraries.append(arg[2:])
        elif arg.startswith('-'):
            linkers.append(arg)
        else:
            linkers[-1] = extra_compile_args[-1] + ' ' + arg

    return Extension('test_mysqlclient', ['test/test_mysqlclient.c'],
                     include_dirs=include_dirs,
                     library_dirs=libraries,
                     extra_link_args=linkers,
                     extra_compile_args=extra_compile_args)

setup(name='python-project',
      version='1.0',
      description='Python Project',
      classifiers=[
          'Development Status :: 5 - Production/Stable',
          'Environment :: Console',
          'Intended Audience :: Developers',
          'License :: OSI Approved :: MIT License',
          'Operating System :: OS Independent',
          'Programming Language :: Python :: 2.7',
          'Natural Language :: English',
      ],
      keywords='mysql python project',
      author='Ozgur Vatansever',
      url='http://github.com/ozgur/python-project/',
      license='MIT',
      packages=['some_project'],
      ext_modules = [mysql_test_extension()]
)

rawDescription: How to handle C extensions for python apps with pip?

description: Handle C extensions for python apps with pip


code:
A = ['a1', 'a2', 'a3', 'a4', 'a5']
y = 'some value'
reduce(lambda x, s: {s: x}, reversed(A), y)

rawDescription: Converting a list to a nested dictionary?


code:
self.enableXThread = Thread(target=self.enableX)
self.enableXThread.daemon = True
self.enableXThread.start()

rawDescription: killing a thread in python before its done

description: Killing a thread in python before its done


rawDescription: Nested ifelse alternative in pandas

description: Nested ifelse alternative in pandas


rawDescription: Finding groups of letters, numbers, or symbols


code: sorted(line, key=lambda l: l.lower().split(', ')[2:0:-1])

rawDescription: Python Line Sorting -

description: Python Line Sorting -


code:
entries = []
for item in selectiondetails:
    entry = Entry(top1)
    entry.insert(0, item)
    entry.pack()
    entries.append(entry)

rawDescription: Loading a list into seperate Entry widgets


code: [{'website': u'http://www.abcl.com', 'phone': u'(123)456-789', 'email': u'abc@gmail.com'}]

rawDescription: How to get span value using python,BeautifulSoup

description: Get span value using python,BeautifulSoup


code: [(h + (None,) * 3)[:3] for h in handlers]

rawDescription: elegant unpacking variable-length tuples

description: Elegant unpacking variable-length tuples


rawDescription: Why does this Python RegEx pipe not pick out both unicode ranges?


code:
bigrams = [('hi', 'ya'), ('see', 'you'), ('my', 'name')]
trigrams = [('it', 'is', 'fine'), ('see', 'you', 'tomorrow'), ('my', 'name', 'is')]
fourgrams = [('it', 'is', 'fine', 'thanks'), ('blah', 'blah', 'blah', 'blah'), ('what', 'sort', 'of', 'question'), ('is', 'this', 'any', 'ways'), ('please', 'read', 'SO', 'FAQ'), ('before', 'posting', 'questions', 'here')]
filtered_trigrams = [i for i in trigrams if i[:-1] not in bigrams]
filtered_trigrams
filtered_fourgrams = [i for i in fourgrams if i[:-1] not in trigrams]
filtered_fourgrams

rawDescription: Python Nltk: ngrams filtration

description: Python Nltk: ngrams filtration


code: ctrl = TestViewController(view)

rawDescription: How to connect a signal from the controller in PyQt4? (iOS like MVC structure in PyQt4)

description: Connect a signal from the controller in PyQt4? (iOS like MVC structure in PyQt4)


code:
data = {}
data["coords"] = [1,2]

rawDescription: How to permanently modify a dictionary in python?

description: Permanently modify a dictionary in python


code:
from app import App
import Tkinter as tk

if __name__ == "__main__":
    root = tk.Tk()
    myapp = App(root)
    myapp.pack()
    root.mainloop()

rawDescription: Python GUI and Class Structure

description: Python GUI and Class Structure


code: print(s)

rawDescription: Python Regex Replace Matching Text

description: Python Regex Replace Matching Text


rawDescription: Pythonic way to convert two adjacent list elements to a tuple and preserve rest of list


code:
"""
Download zip file
""" % movedZip

rawDescription: Variable web link in python

description: Variable web link in python


rawDescription: ManyToMany relation custom serializer

description: ManyToMany relation custom serializer


code:
import itertools

def generate_passwords(wordlist):
    for password_length in range(1, len(wordlist) + 1): # no repeats
        for password in itertools.permutations(wordlist, password_length):
            yield " ".join(password)

rawDescription: Python multiprocessing with subprocess stops working


code: self.a.append(numpy.hstack((numpy.ones((self.z[-1].shape[0], 1)),numpy.tanh(self.z[-1])))) #tanh is a fancy sigmoid

rawDescription: Trying to write my own Neural Network in Python


code:
input_file = open('file', 'r')
float_array = array('d')
float_array.fromstring(input_file.read())

rawDescription: How to output list of floats to a binary file in Python

description: Output list of floats to a binary file in Python


code: listb_dict = {item[0]: item[1:] for item in listb}

rawDescription: Compare list w/ sublist

description: Compare list w/ sublist


code: matching = [system for system in systems if any(re.search('foo', i) for i in system.mgmt_classes)]

rawDescription: Overly complex list comprehension?

description: Overly complex list comprehension


code: np.genfromtxt ('sr00-1min.txt', delimiter=',', converters={0:convert_string_to_bigint}).shape

rawDescription: convert array of tuples to 2 dimensional array

description: Convert array of tuples to 2 dimensional array


code:
import locale
locale.setlocale(locale.LC_ALL, 'de_DE')

mylist = ['2 another test', '4,32', '801', '4apples', 'foo', '4,32 hi', 'apples4', '', '13.300 a test', '2apples', 'doo', '12 today']
flat_lambda1, flat_lambda2 = lambda x: x.split()[0], lambda x: (x == "", x)
WeirdSort(mylist, True, flat_lambda1, flat_lambda2)
print(mylist)
sublst_lambda1, sublist_lambda2 = lambda x: x[0].split()[0], lambda x: (x[0] == "", x[0])
WeirdSort(mylist, False, lambda x: x.split()[0], lambda x: (x == "", x))
print(mylist)

mylist = [['3,25', 1], ['12 text', 2], ["", 5], ['23 text', 3]]
WeirdSort(mylist, True, sublst_lambda1, sublist_lambda2)
print(mylist)
WeirdSort(mylist, False, sublst_lambda1, sublist_lambda2)
print(mylist)

rawDescription: Sort numeric lines with thousand separators


code:
with open('output.csv', 'wb') as f:
    w = csv.writer(f, delimiter='\t')
    for key in keys:
        w.writerow(dct[item].get(key, '') for item in lst)

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code:
string_to_search = "this is the string we will be searching"
letter_to_look_for = "a"

index_of_letter = string_to_search.find(letter_to_look_for)

rawDescription: How to find the position of a letter in a string in python

description: Find the position of a letter in a string in python


rawDescription: Python system resources enumeration

description: Python system resources enumeration


code:
import binascii
binary = '\x5A\x05\x70\x5D\xC2\x5C\xA1\x51\x23\xC8\xE4\x75\x0B\x80\xD0\xA9'
text = '5A05705DC25CA15123C8E4750B80D0A9'
binary == binascii.unhexlify(text)
text == binascii.hexlify(binary).upper()

rawDescription: Converting string to raw bytes

description: Converting string to raw bytes


code: min(points_list, key=distance)

rawDescription: How can I get the element of a list that has a minimum/maximum property in Python?

description: Get the element of a list that has a minimum/maximum property in Python


code:
blacklist = ["olive leaf plucked", "during mating searson"]
blacklist = [tuple(b.split()) for b in blacklist]
blacklist

rawDescription: finder.apply_ngram_filter in nltk.collocations to classify some ngrams

description: Finder.apply_ngram_filter in nltk.collocations to classify some ngrams


code:
import marshal
import pickle
import types

# Receive the marshaled bytecode and the other function things.
marshaled_bytecode, pickled_name, pickled_arguments, pickled_closure = receive_from_a_socket()
your_function = types.FunctionType(marshal.loads(marshaled_bytecode), globals(), pickle.loads(pickled_name), pickle.loads(pickled_arguments), pickle.loads(pickled_closure))

rawDescription: We need to pickle any sort of callable

description: We need to pickle any sort of callable


code:
banana
apple
pear
orange

rawDescription: Why iteration on dict will change keys order in output?


code:
for item in tree.xpath("//description/*|//description/text()"):
    print([item.strip(), 'normal'] if isinstance(item, basestring) else [item.text, 'bold'])

rawDescription: ElementTree text mixed with tags

description: ElementTree text mixed with tags


rawDescription: Return a list of missing values?

description: Return a list of missing values


code:
somelist = ['a', 'b', 'c', 'd']
somedict = dict.fromkeys(somelist, 1)

rawDescription: Python converting a list into a dict with a value of 1 for each key


code:
def call(arg1=None, arg2=None, **kwargs):
    pass

kwargs = {'arg1': 'test', 'arg3': 'whatever'}
call(**kwargs)

rawDescription: Using variables from a returned function as arguments in another function


code:
import pandas as pd
pd.DataFrame(x).groupby(0).sum()

rawDescription: Round labels and sum values in label-value pair 2d-numpy array


code:
import pandas as pd

# create frame with six columns of ints
df = pd.DataFrame({'a':[1,2,3,4,10],
                   'b':[8,5,3,2,11],
                   'c':[3,7,1,8,8],
                   'd':[3,7,1,8,8],
                   'e':[3,1,1,8,8],
                   'f':[7,7,1,8,8]})

# list of ints
base =[1,2,3,4,5,6]

# define function to count membership of list
def base_count(y):
    return sum(True for x in y if x in base)

# apply the function row wise using the axis =1 parameter
df.apply(base_count, axis=1)

rawDescription: Occurence frequency from a list against each row in Pandas dataframe


code:
import json

json_value = json.dumps(python_object)

rawDescription: Convert utf string ftom python to javascript dictionary


code:
import csv
from collections import OrderedDict

with open('b.csv', 'rb') as f:
    r = csv.reader(f)
    dict2 = {row[0]: row[1:] for row in r}

with open('a.csv', 'rb') as f:
    r = csv.reader(f)
    dict1 = OrderedDict((row[0], row[1:]) for row in r)

result = OrderedDict()
for d in (dict1, dict2):
    for key, value in d.iteritems():
        result.setdefault(key, []).extend(value)

with open('ab_combined.csv', 'wb') as f:
    w = csv.writer(f)
    for key, value in result.iteritems():
        w.writerow([key] + value)

rawDescription: Python Joining csv files where key is first column value


code:
def create_perm(lst_str):
    li = list(lst_str.replace('[','').replace(']',''))
    for perm in itertools.permutations(li):
        yield '[{}]'.format(''.join(perm))

rawDescription: Filtering permutations of strings

description: Filtering permutations of strings


code:
def __dir__(self):
    res = dir(type(self)) + list(self.__dict__.keys())
    res.extend(['dynamic1', 'dynamic2'])
    return res

rawDescription: Python dynamic help and autocomplete generation


code:
import inspect
import logging
import linecache

def main():
    something_is_not_right = True
    logging.basicConfig(level=logging.DEBUG,
                        format=('%(filename)s: '
                                '%(levelname)s: '
                                '%(funcName)s(): '
                                '%(lineno)d:\t'
                                '%(message)s')
                        )

    if something_is_not_right:
        logging.debug(linecache.getline(
            __file__,
            inspect.getlineno(inspect.currentframe())-1))

if __name__=='__main__':
    main()

rawDescription: How to print source code lines in python logger

description: Print source code lines in python logger


code:
from django.utils.timezone import now

# first() returns None if the result is empty
next_raid = models.RaidSession.objects \
    .filter(scheduled__gte=now()) \
    .order_by('scheduled') \
    .first()

rawDescription: Next upcoming date model object ignoring past dates


code:
class MyForm(forms.ModelForm):
    model = MyModel

    field = forms.Charfield(required=False)

rawDescription: Model field blank=false doesn't work when field is readonly in admin.py


code: map(list, zip(*a))

rawDescription: Transpose nested list in python

description: Transpose nested list in python


code:
from scipy.interpolate import interp1d
interp = interp1d(x, y, kind='cubic')
from scipy.integrate import quad
quad(interp, 0, 1)

rawDescription: Integral function of a interpolating polynomial in python


code: regex = re.compile('((\d+,)*\d+)')

rawDescription: python - regex search and findall

description: Python - regex search and findall


rawDescription: python/scons help: maintaining lists of source files + object files

description: Python/scons help: maintaining lists of source files + object files


code:
def parse_tree(tree, string, start=0):
    index = start
    while index < len(string):
        current = string[index]
        if current == "(":
            child = tree[-1][1]
            child_parsed = parse_tree(child, string, index+1)
            index += child_parsed + 2 # adds 2 for the parentheses
        elif current == ")":
            break
        else:
            tree.append((current, []))
            index += 1
    return index - start
tree = []
print(parse_tree(tree, 'abc(abc(defg)d)de(f)gh'))

rawDescription: Optimizing string parsing with Python

description: Optimizing string parsing with Python


code:
with open('test.csv') as f:
    line_values = [line.strip().split(',') for line in f.readlines()]
transposed_values = dict([(v.strip(), k) for k, v in line_values])
with open('test2.csv') as fi:
    with open('out.csv', 'w') as fo:
        for line in fi.readlines():
            B = line.strip()
            try:
                print >>fo, '{}, {}'.format(B, transposed_values[B])
            except KeyError:
                print >>fo, '{}, ?'.format(B)

rawDescription: How to make equivalency in Python?

description: Make equivalency in Python


rawDescription: Search specific format in specific order for a text file data


rawDescription: Counting the number of unique words in a list


code:
from nltk.corpus import wordnet as wn
wn.synset('mass.n.03').name().split(".")[0]

rawDescription: Extract word from a list of synsets in NLTK for Python


rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


rawDescription: Grab rows between two Datetime and avoid iterating


code:
import ast
with open("test.txt") as f:
    user_info = ''
    for i,line in enumerate(f):
        user_info += line
        if  i==5:
            break
    registros = [ast.literal_eval(x) for x in f if x.startswith('[')]

rawDescription: How to read just lists in a text file in Python?

description: Read just lists in a text file in Python


code:
zipped = zip(*list2)
result = [min(zipped[i]) for i in range(3)] + [max(zipped[i]) for i in range(3, 6)]

rawDescription: Compare elements of a list of lists and return a list


code:
def sumColumns1(columnfile):
    import csv
    with open(columnfile) as csvfile:
        r = csv.reader(csvfile)
        names = next(r)
        sums = [ 0 for _ in names ]
        for line in r:
            for i in range(len(sums)):
                sums[i] += int(0 if line[i]=='' else line[i])
        return dict(zip(names,sums))

rawDescription: python 3: Adding .csv column sums in to dictionaries with header keys

description: Python 3: Adding .csv column sums in to dictionaries with header keys


code:
import tkinter.messagebox
from tkinter import Tk

root = Tk()
root.withdraw()
answer=tkinter.messagebox.askquestion('Question','what is your name?')
if answer=='yes':
    print('I am King')

rawDescription: tKinter dialog button not responding

description: TKinter dialog button not responding


rawDescription: How to display Image in pygame?

description: Display Image in pygame


code:
import shelve

T='Hiya'
val=[1,2,3]

filename='/tmp/shelve.out'
my_shelf = shelve.open(filename,'n') # 'n' for new

for key in dir():
    try:
        my_shelf[key] = globals()[key]
    except TypeError:
        #
        # __builtins__, my_shelf, and imported modules can not be shelved.
        #
        print('ERROR shelving: {0}'.format(key))
my_shelf.close()

rawDescription: How can I save all the variables in the current python session?

description: Save all the variables in the current python session


code:
import types as _types
import ctypes as _ctypes
from ctypes import wintypes as _wtypes
_mtypes = _types.ModuleType('_mtypes')

_ole32 = _ctypes.WinDLL('ole32')
_shell32 = _ctypes.WinDLL('shell32')
_user32 = _ctypes.WinDLL('user32')

try:
    from win32com.shell import shell as _shell
except ImportError:
    _shell = None

try:
    from win32com.shell import shellcon
except ImportError:
    shellcon = _types.ModuleType('shellcon')
    shellcon.SHGFI_LARGEICON         = 0x00000
    shellcon.SHGFI_SMALLICON         = 0x00001
    shellcon.SHGFI_OPENICON          = 0x00002
    shellcon.SHGFI_SHELLICONSIZE     = 0x00004
    shellcon.SHGFI_PIDL              = 0x00008
    shellcon.SHGFI_USEFILEATTRIBUTES = 0x00010
    shellcon.SHGFI_ICON              = 0x00100
    shellcon.SHGFI_DISPLAYNAME       = 0x00200
    shellcon.SHGFI_TYPENAME          = 0x00400
    shellcon.SHGFI_ATTRIBUTES        = 0x00800
    shellcon.SHGFI_ICONLOCATION      = 0x01000
    shellcon.SHGFI_EXETYPE           = 0x02000
    shellcon.SHGFI_SYSICONINDEX      = 0x04000
    shellcon.SHGFI_LINKOVERLAY       = 0x08000
    shellcon.SHGFI_SELECTED          = 0x10000
    shellcon.SHGFI_ATTR_SPECIFIED    = 0x20000

try:
    import win32con
except ImportError:
    win32con = _types.ModuleType('win32con')
    win32con.MAX_PATH = 260
    win32con.FILE_ATTRIBUTE_READONLY            = 0x00001
    win32con.FILE_ATTRIBUTE_HIDDEN              = 0x00002
    win32con.FILE_ATTRIBUTE_SYSTEM              = 0x00004
    win32con.FILE_ATTRIBUTE_DIRECTORY           = 0x00010
    win32con.FILE_ATTRIBUTE_ARCHIVE             = 0x00020
    win32con.FILE_ATTRIBUTE_DEVICE              = 0x00040
    win32con.FILE_ATTRIBUTE_NORMAL              = 0x00080
    win32con.FILE_ATTRIBUTE_TEMPORARY           = 0x00100
    win32con.FILE_ATTRIBUTE_ATOMIC_WRITE        = 0x00200
    win32con.FILE_ATTRIBUTE_SPARSE_FILE         = 0x00200
    win32con.FILE_ATTRIBUTE_REPARSE_POINT       = 0x00400
    win32con.FILE_ATTRIBUTE_XACTION_WRITE       = 0x00400
    win32con.FILE_ATTRIBUTE_COMPRESSED          = 0x00800
    win32con.FILE_ATTRIBUTE_OFFLINE             = 0x01000
    win32con.FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = 0x02000
    win32con.FILE_ATTRIBUTE_ENCRYPTED           = 0x04000
    win32con.FILE_ATTRIBUTE_VIRTUAL             = 0x10000

_mtypes.CData = _ctypes.Array.__bases__[0]
_mtypes.PPIDLIST_ABSOLUTE = _ctypes.POINTER(_ctypes.c_void_p)
_mtypes.SFGAOF = _wtypes.ULONG
_mtypes.PSFGAOF = _ctypes.POINTER(_mtypes.SFGAOF)

_ole32.CoInitialize.restype = _ctypes.HRESULT # checked
_ole32.CoInitialize.argtypes = (_ctypes.c_void_p,)
_ole32.CoUninitialize.restype = None
_ole32.CoUninitialize.argtypes = ()
_ole32.CoTaskMemFree.restype = None
_ole32.CoTaskMemFree.argtypes = (_ctypes.c_void_p,)
_user32.DestroyIcon.argtypes = (_wtypes.HICON,)

_shell32.SHParseDisplayName.restype = _ctypes.HRESULT # checked
_shell32.SHParseDisplayName.argtypes = (
    _wtypes.LPCWSTR,           # pszName,   _In_
    _ctypes.c_void_p,          # pbc,       _In_opt_
    _mtypes.PPIDLIST_ABSOLUTE, # ppidl,     _Out_
    _mtypes.SFGAOF,            # sfgaoIn,   _In_
    _mtypes.PSFGAOF)           # psfgaoOut, _Out_opt_

class SHFILEINFO(_ctypes.Structure):
   _fields_ = (('hIcon', _wtypes.HICON),
               ('iIcon', _ctypes.c_int),
               ('dwAttributes', _wtypes.DWORD),
               ('szDisplayName', _wtypes.WCHAR * win32con.MAX_PATH),
               ('szTypeName', _wtypes.WCHAR * 80))

_mtypes.SHFILEINFO = SHFILEINFO
_mtypes.PSHFILEINFO = _ctypes.POINTER(SHFILEINFO)

_shell32.SHGetFileInfoW.restype = _ctypes.c_void_p
_shell32.SHGetFileInfoW.argtypes = (
    _wtypes.LPVOID,      # pszPath,          _In_
    _wtypes.DWORD,       # dwFileAttributes,
    _mtypes.PSHFILEINFO, # psfi,             _Inout_
    _wtypes.UINT,        # cbFileInfo,
    _wtypes.UINT)        # uFlags

def SHGetFileInfo(pidl, attributes=0, flags=0):
    if _shell is not None:
        if not isinstance(pidl, (str, bytes, _mtypes.CData)):
            pidl = _shell.PIDLAsString(pidl)
    finfo = SHFILEINFO()
    _ole32.CoInitialize(None)
    try:
        retval = _shell32.SHGetFileInfoW(pidl,
                                         attributes,
                                         _ctypes.byref(finfo),
                                         _ctypes.sizeof(finfo),
                                         flags)
    finally:
        _ole32.CoUninitialize()
    if not retval:
        if flags != shellcon.SHGFI_EXETYPE:
            raise _ctypes.WinError()
    return retval, finfo

rawDescription: How to use SHGetFileInfo with SHGFI_PIDL in python

description: Use SHGetFileInfo with SHGFI_PIDL in python


code:
class Guest(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    guest_id = db.Column(db.String(15))

rawDescription: Generate user ids in a sequence using sqlalchemy in sqllite databse.


code:
a = b'{"username":"test","available":false,"status":"unavailable","failed_reason":null,"callback_url":"http://www.twitter.com/"}'
a = a.decode('utf-8')
import json
a = json.loads(a)
a.get('username')

rawDescription: How to get a value from json dictionary in python?

description: Get a value from json dictionary in python


code:
class VerboseListIterator(object):
    def __init__(self, collection, node):
        self.collection = collection
        self.node = node
        self.idx = 0

    def __iter__(self):
        return self

    def __next__(self):
        print('Printing {}th child of "{}". Stack size: {}'.format(self.idx, self.node, len(stack())))
        if self.idx >= len(self.collection):
            raise StopIteration()

        self.idx += 1
        return self.collection[self.idx - 1]

rawDescription: Chaining of Python generators to traverse a nested data structure; best practices


rawDescription: How can I scale my y axis into y**constant

description: Scale my y axis into y**constant


code:
class NewUserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)

    class Meta:
        model = NewUser
        fields = ('username', 'email', 'first_name', 'last_name', 'newField')       # few example fields and new one: newField

    def clean_password2(self):
        password1 = self.cleaned_data.get("password1")
        password2 = self.cleaned_data.get("password2")
        if password1 and password2 and password1 != password2:
            raise forms.ValidationError("Passwords don't match")
        return password2

    def save(self, commit=True):
        user = super(NewUserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data["password1"])
        if commit:
            user.save()
        return user

class NewUserChangeForm(UserChangeForm):
    class Meta(UserChangeForm.Meta):
        model = NewUser
        fields = ('username', 'email', 'first_name', 'last_name', 'newField', 'last_login', 'is_staff')     # few example fields and new one: newField

rawDescription: New field in django-admin Add User

description: New field in django-admin Add User


code:
import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

dir = find('image.gif', os.path.expanduser("~"))

rawDescription: Python - File Directory Issue

description: Python - File Directory Issue


rawDescription: Most efficient way to split strings in Python


code:
[{'id': 9, 'name': 'one project', 'otherkey': 'othervalue'},
 {'id': 3, 'name': 'project one', 'otherkey': 'othervalue'},
 {'id': 5, 'name': 'project two', 'otherkey': 'othervalue'},
 {'id': 1, 'name': 'project three', 'otherkey': 'othervalue'},
 {'id': 6, 'name': 'abc project', 'otherkey': 'othervalue'}]

rawDescription: Sorting list of dictionaries with primary key from list of keywords and alphabetical order as secondary key


code:
for entry in log_data:
    entry_data = entry.split(',')
    # We are going to have a separate entry for each source ip
    # If we haven't already seen this ip, we need to make an entry for it
    if entry_data[2] not in results:
        results[entry_data[2]] = {'total':0}
    # Now check to see if we've seen the protocol for this ip before
    # If we haven't, add a new entry set to 0
    if entry_data[4] not in results[entry_data[2]]:
         results[entry_data[2]][entry_data[4]] = 0
    # Now we increment the count for this protocol
    results[entry_data[2]][entry_data[4]] += 1
    # And we increment the total count
    results[entry_data[2]]['total'] += 1

rawDescription: Python parsing log file for IP address and Protocol


code:
def build_ranges(steps):
    val = 0
    for step in steps:
        yield val, val + step
        val += step

rawDescription: Building ranges using python set-builder notation


rawDescription: How to append dictionary to a list in loop

description: Append dictionary to a list in loop


code:
from urllib import urlencode

items = [('first_name', '&&'), ('first_name', '&&&&')]
query_string = urlencode(items)

rawDescription: Escaping string in Python

description: Escaping string in Python


code:
import Tkinter as tk
import json, htmllib, formatter, urllib2
from urllib2 import *
from contextlib import closing

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

    def createWidgets(self):
        self.StatusTextVar = tk.StringVar()
        self.EntryText = tk.Entry(self)
        self.GetButton = tk.Button(self, command=self.GetURL)
        self.StatusLabel = tk.Label(self, textvariable=self.StatusTextVar)

        self.EntryText.grid(row=0, column=0)
        self.GetButton.grid(row=0, column=1, sticky=tk.E)
        self.StatusLabel.grid(row=1, column=0, sticky=tk.W)

    def GetURL(self):
         try:
             self.url_target = ("http://www." + self.EntryText.get())
             self.req = urllib2.urlopen(self.url_target)
             self.StatusTextVar.set("Success")

         except:
             self.StatusTextVar.set("Wrong input. Retry")
             pass

root = tk.Tk()
app = Application(master=root)
app.mainloop()

rawDescription: Python 2.7: updating Tkinter Label widget content


code: [(k, v) for (k, v) in distutils.sysconfig.get_config_vars().items() if "/tmp/so" in str(v)]

rawDescription: Get the path of python console commands installed as 'entry_points' with distribute


code:
from sqlalchemy import inspect
i = inspect(Animal)
i.polymorphic_map

rawDescription: List polymorphic inheritance choices and create an instance based on that choice


code:
elem = etree.Element('TreeInventory')
elem.set(location_attribute, 'Trees.xsd')

rawDescription: Python: adding namespaces in lxml

description: Python: adding namespaces in lxml


rawDescription: Merge two equal-length lists into a dictionary, mapping one-to-many


rawDescription: Python adding values in Tuples

description: Python adding values in Tuples


code:
import json, sys

json.dump(obj, sys.stdout, sort_keys=True,
          indent=4, separators=(',', ': '))

rawDescription: How to execute a python module (python -m json.tool) programatically?

description: Execute a python module (python -m json.tool) programatically


rawDescription: Generating permutations

description: Generating permutations


rawDescription: Exporting Python List to CSV in "column" format


code:
merged = zip(user, next_level, comment_values, likes_values, rating_values, date)

# merged is now [(user[0], next_level[0], comment_values[0], ...),
#                (user[1], next_level[1], comment_values[1], ...),
#                ...]

rawDescription: Django turn lists into one list

description: Django turn lists into one list


code:
dicts1 = [
      {'K1': 'kval', 'L1': 'Lval', 'F1': None, 'F2': None, 'F3': 'ERR1'},
      {'K1': 'kval', 'L1': 'Lval', 'F1': None, 'F2': None, 'F3': 'ERR1'},
      {'F1': None, 'F2': None, 'F3': 'ERR2'}]

special_keys = ['F1', 'F2', 'F3']

def concat_dict(dicts1):
    outdict = {}
    for dictionary in dicts1:
        for key, value in dictionary.items():
            #FOr special keys
            if key in special_keys:
                #Check first if key is already inserted in outdict
                if key not in outdict or not outdict[key]:
                    outdict[key] = value
                #Else only if value is not None, do concatenation
                elif value:
                    outdict[key] = '{prepend};{newValue}'.format(prepend=outdict[key], newValue=value)
            else:
                outdict[key] = value

    return outdict

rawDescription: Python - Combine number of dictionaries with conditional concatenation


code: [[0]*2 for i in range(2)]

rawDescription: Deepcopy on nested referenced lists created by list multiplication does not work


code: defaultdict(int, [(i, i*i) for i in range(5)])

rawDescription: Populating a defaultdict at init time

description: Populating a defaultdict at init time


code:
characterObject = {
    "player": player,
    "minion" : minion,
    "monster": monster,
    "arrrow": arrow,
    "encounter": encounter
}

rawDescription: Python - Use object as parameter to function


code:
def split_by_n( seq, n ):
    while seq:
        yield seq[:n]
        seq = seq[n:]

def make_matrix(string):
    col_count = 6
    matrix = list(split_by_n(string,6))
    row_count = len(matrix)

    # the last row has "less_by" fewer elements than the rest of the rows
    less_by = len(matrix[-2]) - len(matrix[-1])
    matrix[-1] += '$' * less_by

    return matrix

def make_transpose(matrix):
    col_count = len(matrix[0])
    transpose = []
    for i in range(col_count):
        transpose.append([row[i] for row in matrix])

    return transpose

string = list("ZPFKYLGJPNSGNMQGFGCITLVRIWMGFBLBFDSIOAJGBGAVFVHBGLFSRPNIOFSYOBTFCGRQLWWZAAJFUPGAFZSNXLTGARUVFKOLGAIWGUUCMVSEKLIAGJGGUZFBAOILVRIZPORNXWVFRGNMEGCEUNUZSPNIUAHFRQLWALHWEQGQKDFDCCKLUZWFSITKWIKLSMUQKNJUWRTKZAHJGABKDEGEMNCVIMBFRNYXSSKYPWLWHUKKISHFAJPOOFGJBJTBXXSGTRYAJGBNRMYHOGXQBLSFEWVUCHRLEJWAQBIWFRLWSSKRKSBFRAKDFJVRGZUOCJUZEKWAPIQSBRYM")
matrix = make_matrix(string)

transpose = make_transpose(matrix)

for e in matrix:
    print(e)

print('\nThe transpose:')
for e in transpose:
    print(e)

rawDescription: Generate a matrix from a given string

description: Generate a matrix from a given string


code:
mismatches = incorrect_terms(polynomial, terms)
first_mismatch = mismatches.next()

rawDescription: Python converting nested loops to simple line


code: c1 = Class_1()

rawDescription: Class management in python

description: Class management in python


code:
a = np.arange(9)
a
a.ndim    # number of dimensions
a.shape
b = np.array([[0,0,0],[1,2,3],[2,2,2],[9,9,9]])
b
b.ndim
b.shape

rawDescription: In Python NumPy what is a dimension and axis?


code:
import numpy as np
import pandas as pd
import itertools as IT

# generate a large-ish example
np.random.seed(2015)
N, M = 200, 200
df1 = pd.DataFrame(list(IT.product(np.arange(N), np.arange(M))),
                   columns=['obs','year'])
df1['val'] = np.random.choice([1,2,np.nan], size=len(df1))

df2 = pd.DataFrame(list(IT.product(np.arange(N), np.arange(M))),
                   columns=['obs','year'])
df2['val'] = np.random.choice([1,2,np.nan], size=len(df1))
df2.index = np.arange(len(df2)) + len(df1)

m1 = using_merge(df1, df2)
m2 = using_update(df1, df2)
m3 = using_set_index(df1, df2)
assert m3.reset_index(drop=True).equals(m1)
assert m1.equals(m2)

rawDescription: pandas DataFrame update/combine when indices don't align

description: Pandas DataFrame update/combine when indices don't align


code: driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', element)

rawDescription: Selenium webdriver: How do I find ALL of an element's attributes?


code:
class SomeForm(Form):
    def __init__(self, bar, *args, **kwargs):
        ch1 = SomeTable.query.filter_by(bar=bar)
        self.choice1.kwargs['choices'] = tuple((e.name, e.name) for e in ch1)
        super(SomeForm, self).__init__(*args, **kwargs)

rawDescription: Flask forms. How to make variable from views visible in forms.py


code:
class MembershipSerializer(serializers.HyperlinkedModelSerializer):

    id = serializers.Field(source='group.id')
    name = serializers.Field(source='group.name')

    class Meta:
        model = Membership

        fields = ('id', 'name', 'join_date', )

rawDescription: Include intermediary (through model) in responses in Django Rest Framework


code:
dictionary = { 'A': 2, 'B': 1, 'C': 2 }
maxValue = max(dictionary.values())
[k for k, v in dictionary.items() if v == maxValue]

rawDescription: Python Dict more than one Max value

description: Python Dict more than one Max value


code: df.apply (lambda row: label_race (row),axis=1)

rawDescription: pandas create new column based on values from other columns

description: Pandas create new column based on values from other columns


code:
c = []

aa, bb = a.pop(0), b.pop(0)
while True:
    if aa < bb:
        c.append(aa)
        try:
            aa = a.pop(0)
        except IndexError:
            c += b
            b = []
    else:
        c.append(bb)
        try:
            bb = b.pop(0)
        except IndexError:
            c += a
            a = []

rawDescription: How do I take 2 sorted lists and add them to another list while removing the elements

description: Take 2 sorted lists and add them to another list while removing the elements


code:
import matplotlib.pyplot as plt
plt.subplot2grid( (4,4), [0,1], 2, 2 )
plt.plot( x1, y1 )
plt.subplot2grid( (4,4), [2,0], 2, 2 )
plt.plot( x2, y2 )
plt.subplot2grid( (4,4), [2,2], 2, 2 )
plt.plot( x2, y2 )

rawDescription: Can I arrange 3 equally sized subplots in a triangular shape?

description: Arrange 3 equally sized subplots in a triangular shape


rawDescription: Is it possible to assign two different returned values from a python function to two separate variables?


code: isinstance(x, int)

rawDescription: Check whether the type of a variable is a specific type in Python


code:
width = 500
height = 500
surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
ctx = cairo.Context(surface)
ctx.set_source_rgb(1,1,1)
rect(ctx, (0,0), (width, height), stroke=False)
ctx.set_source_rgb(0,0,0)
for i in xrange(5):
    for j in xrange(5):
        x = 100 * i + 20
        y = 100 * j + 20
        theta = math.pi*0.25*(5*i+j)
        text(ctx, 'hello world', (x, y), theta, font_size=15)
surface.write_to_png('text-demo.png')

rawDescription: rotate text around its center in pycairo

description: Rotate text around its center in pycairo


code:
import ctypes
from wand.image import Image
from wand.api import library

# Tell python about library method
library.MagickSetImageDispose.argtypes = [ctypes.c_void_p, # Wand
                                          ctypes.c_int]    # DisposeType
# Define enum DisposeType
BackgroundDispose = ctypes.c_int(2)
with Image() as new_gif:
    for img_path in input_images:
        with Image(filename=img_path) as inimg:
            # create temp image with transparent background to composite
            with Image(width=inimg.width, height=inimg.height, background=None) as new_img:
                new_img.composite(inimg, 0, 0)
                library.MagickSetImageDispose(new_img.wand, BackgroundDispose)
                new_gif.sequence.append(new_img)
    # Also rebuild loop and delay as ``new_gif`` never had this defined.
    new_gif.save(filename=output_path)

rawDescription: wand: How to assemble transparent gif / clear background each frame

description: Wand: How to assemble transparent gif / clear background each frame


code:
def get_nums(lst):
    letters = 'abcdefghijklmnopqrstuvwxyz' # also string.ascii_lowercase
    mapping = {lett:idx for idx,lett in enumerate(letters, start=1)}
    return [mapping[lett] for lett in lst]

rawDescription: swapping inside the list in python

description: Swapping inside the list in python


code:
def up(x):
    return (x >= 0).sum()
def down(x):
    return (x < 0).sum()

result = A.loc[:, 'B':'C'].groupby((A['A'] > 2)).agg(
             [up, down, 'mean', 'std'])
print(result)

rawDescription: How to use groupby to apply multiple functions to multiple columns in Pandas?

description: Use groupby to apply multiple functions to multiple columns in Pandas


code: nsmap = root.nsmap

rawDescription: lxml and xml namespaces - Using find and findall to get XML Tag Value

description: Lxml and xml namespaces - Using find and findall to get XML Tag Value


code:
import numpy as np

A = np.array([ 6, 4, 5, 7, 9 ])
ind = np.array([ 0, 0, 2, 1, 2 ])

N=100
M=10
A2 = np.array([np.random.randint(M) for i in range(N)])
ind2 = np.array([np.random.randint(M) for i in range(N)])

def use_extra_axis(A,ind,f):
    B=np.zeros((len(A),max(ind)+1))
    B[zip(*enumerate(ind))]=A
    return f(B)

def use_loop(A,ind,f):
    n=max(ind)+1
    B=np.empty(n)
    for i in range(n):
        B[i]=f(A[ind==i])
    return B

def fmax(arr):
    return np.max(arr,axis=0)

if __name__=='__main__':
    print(use_extra_axis(A,ind,fmax))
    print(use_loop(A,ind,fmax))

rawDescription: Functional assignment in numpy

description: Functional assignment in numpy


code:
for c, r in zip(range(23,42), range(5,24)) :
  stdscr.addstr(c, r, '#')

rawDescription: What's the short way to add same symbol at the specified place in ncurses?


code:
from urlparse import urlparse
import csv
import re

ifile =open(ipath,'r')
ofile = open(opath, 'wb')
writer = csv.writer(ofile, dialect='excel')

url =[urlparse(u).netloc for u in ifile]
sitesource =  set([re.sub("www.", "", e) for e in url])

for u in sitesource:
    print ("Creation de:", u)
    writer.writerow([u])

ofile.close()
ifile.close()

rawDescription: Python .csv writer

description: Python .csv writer


rawDescription: simplest mergesort implementation in Python, having type troubles

description: Simplest mergesort implementation in Python, having type troubles


code:
for idx in list(combinations(range(len(history)), n-1)):
    pass # Do something

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
super(Puppy, dizzy).intro()  # uses Dog.intro()
super(Dog, dizzy).intro()    # uses Animal.intro()

rawDescription: Call a method on the parent class of an initialized object


code:
s = (ctypes.c_wchar * 12)()
v = u'\u0100'.encode('utf-8')
v
s.value = v

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


rawDescription: Most efficient dictionary counter

description: Most efficient dictionary counter


code:
from itertools import groupby

def find_dub_strs(mystring):
    grp = groupby(mystring)
    seq = [(k, len(list(g)) >= 2) for k, g in grp]
    allowed = ('aeioupt')
    return rec_dubz('', seq, allowed=allowed)

def rec_dubz(prev, seq, allowed='aeiou'):
    if not seq:
        return [prev]
    solutions = rec_dubz(prev + seq[0][0], seq[1:], allowed=allowed)
    if seq[0][0] in allowed and seq[0][1]:
        solutions += rec_dubz(prev + seq[0][0] * 2, seq[1:], allowed=allowed)
    return solutions

rawDescription: Remove letter duplicates that are in a row


code:
class Foo(object):
    def __init__(itsa_me_maaaario, name):
        itsa_me_maaario.name = "Mario"

rawDescription: python classes getters and setters static method and class method

description: Python classes getters and setters static method and class method


code:
from itertools import izip
sample = [(1,3), (4,5), (8,2)]
t1, t2 = map(sum, izip(*sample))

rawDescription: Two sums from one list

description: Two sums from one list


code:
def read_lines_with_duplicate_replace_v2(path,replace_char="X"):
    """Generator that read the lines in the file contained in path
       and for each line that start as the previous line replace each
       part that is similar with replace_char. Yield a list with the result """
    #assume that each line has the same number of elements
    num_elem = 0
    previous_line = list()
    with open(path) as file:
        for line in file:
            result = line.split()
            if previous_line:
                for i in range(num_elem):
                    if result[i] == previous_line[i]:
                        result[i] = replace_char
                    else:
                        break
                previous_line[i:] = result[i:]
            else:
                previous_line.extend(result)
                num_elem = len(previous_line)
            yield result

rawDescription: Python-Replacing Duplicatte information in a Text file


code:
class myTestFrame( tk.Frame ):
    tk.Frame.__init__(self, parent, *args, **kwargs)

rawDescription: Python Classes in Tkinter's Grid Manager


code:
def say_something(thing):
    return getattr(a, thing, lambda: 'Not Found')
say_something('duck')()
say_something('person')()
say_something('foo')()

rawDescription: How to iterate over class methods

description: Iterate over class methods


code:
import copy
route = copy.deepcopy(triangle) #This will work

rawDescription: Finding the Maximum Route in a given input


code:
import subprocess
import contextlib
@contextlib.contextmanager
def noop():
    yield None

logging = False
file_path = '/tmp/out'

with open(file_path, 'wb') if logging else noop() as shell_stdout:
    subprocess.call(['ls'], stdout=shell_stdout)

rawDescription: Python context for file or None

description: Python context for file or None


rawDescription: Django MPTT get related objects

description: Django MPTT get related objects


code:
text = '''
Table TRKGRP1: New table control.
      TRKGRP1: 1000 tuples checked. Tuple checking still in progress...
      Completed tuple checking.
      SUMMARY: Tbl TRKGRP1: tuples checked 1297, passed 1297, failed 0.
Table TOLLTRKS: New table control.
      Completed tuple checking.
      SUMMARY: Tbl TOLLTRKS: tuples checked 3, passed 3, failed 1.
Table BRANDOPT: New table control.
      Completed tuple checking.
      SUMMARY: Tbl BRANDOPT: tuples checked 0, passed 0, failed 0.
Table C7UPTMR: New table control.
      Completed tuple checking.
      SUMMARY: Tbl C7UPTMR: tuples checked 4, passed 4, failed 3.
Table TOPSCOIN: New table control.
      Completed tuple checking.
      SUMMARY: Tbl TOPSCOIN: tuples checked 0, passed 0, failed 2.
'''
lines = text.split('\n')

rawDescription: Script/regex for log file editing

description: Script/regex for log file editing


code:
parser.add_argument('filesIn',
                    action="store",
                    type=str,
                    nargs='+',
                    help="input file(s)")

rawDescription: Usage message when using argparse.REMAINDER


code:
mod, error = loadmodule('mystuff.py')

if mod is not None:
    # loading succeeded you can now proceed and do things with it
    pass

rawDescription: Extend the functionality of a compiled Python script


rawDescription: Python - quick interpolate by left value


code:
import pickle
import numpy

rawDescription: Is there an alternative to numpy.save(file, arr) that will work with pypy?


code:
match = re.search(r'"TES\d+":"=TES\d+"', subject)
if match:
    result = match.group()

rawDescription: extracting items using regular expression in python

description: Extracting items using regular expression in python


code:
def collide_widget(self, wid):
    if max(self.x, self.right) < min(wid.x, wid.right):
        return False
    if min(self.x, self.right) > max(wid.x, wid.right):
        return False
    if max(self.top, self.y) < min(wid.y, wid.top):
        return False
    if min(self.top, self.y) > max(wid.y, wid.top):
        return False
    return True

rawDescription: collide_widget with negative size

description: Collide_widget with negative size


code:
a = numpy.array([0,1,3,2], dtype=numpy.int)
a.sort()
a

rawDescription: How to sort an integer array in-place in Python?

description: Sort an integer array in-place in Python


code:
for reg in Region:
   pages = -1

rawDescription: How to Crawl Multiple pages/cities from a website (BeautifulSoup,Requests,Python3)


rawDescription: Python - Remove accents from all files in folder


rawDescription: Matching @user with regex

description: Matching @user with regex


code:
from datetime import datetime, timedelta

seconds, dot, us = "1440498131.372625".partition('.')
d = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=int(seconds))
if dot:
    d = d.replace(microsecond=datetime.strptime(us, '%f').microsecond)

rawDescription: fractions of seconds and pytz: do you have a cleaner solution?

description: Fractions of seconds and pytz: do you have a cleaner solution


code:
lista = [i for i in range(10)]

file=open("file.txt","a")
file.write("\n")
file.write("".join(str(lista)))
file.close()

rawDescription: Python won't write small object to file but will with large object


rawDescription: Pandas time series indexing -- re

description: Pandas time series indexing -- re


code:
fig1 = plt.figure(figsize=(10,8))
ax1 = fig1.add_axes((0.1, 0.1, 0.8, 0.8), # full positional control
    frameon=True,                         # display frame boundary
    aspect='equal',                       # set aspect ratio upon creation
    adjustable='box',                     # what part of the axes can change to meet the aspect ratio requirement?
    xticks=[0.1, 1.2, 10],
    xlabel='voltage (V)',
    xlim=(0.05, 10.05),
    yticks=[0, 10],
    ylabel='current (µA)',
    ylim=(0, 2))

rawDescription: Matplotlib: set x y label in one line

description: Matplotlib: set x y label in one line


code:
import pandas as pd
import seaborn
import matplotlib.pyplot as plt

n = 480
ts = pd.Series(np.random.randn(n), index=pd.date_range(start="2014-02-01", periods=n, freq="H"))

fig, ax = plt.subplots(figsize=(12,5))
seaborn.boxplot(ts, ts.index.dayofyear, ax=ax)

rawDescription: Time-series boxplot in pandas

description: Time-series boxplot in pandas


code: email.utils.getaddresses(re.findall(r'^To:\s+((?:.*(?:\n[ \t]+)?)*)', text, flags=re.M))

rawDescription: Ignore strings which do not completely match regex?


code:
images[some_size] = ['x/a.jpg', 'b/f.jpg', 'n/q.jpg']
images[some_other_size] = ['q/b.jpg']

rawDescription: Is it possible to detect duplicate image files?


rawDescription: Representing version number as regular expression


code:
#!/usr/bin/env python
def job():
    import os
    hostname = "192.168.254.102" #example
    response = os.system("ping -c 1 " + hostname)
    if response == 0:
        print(hostname, 'is up!')
        os.system("sudo python ../aquarium/nightlight_on.py 1")
    else:
        print(hostname, 'is down!')

import schedule
schedule.every(10).seconds.do(job)

rawDescription: Python script to continue running

description: Python script to continue running


code:
#Directory containing ArcGIS Install files
installDir = arcpy.GetInstallInfo("desktop")["InstallDir"]
#Path to XML schema for FGDC
translator = os.path.join(installDir, "Metadata/Translator/ARCGIS2FGDC.xml")
#Export your metadata
arcpy.ExportMetadata_conversion(featureClassPath, translator, tempXmlExportPath)

rawDescription: updating metadata for feature classes programatically using arcpy

description: Updating metadata for feature classes programatically using arcpy


rawDescription: Python issues with return statement

description: Python issues with return statement


code: from numpy.lib.stride_tricks import as_strided

rawDescription: Modifying diagonals in multidimensional numpy arrays


code:
#! /usr/bin/python

import foo

file = open("testfile", "rb")
foo.read_input_from(file)

rawDescription: Pythonic equivalent of ./foo.py < bar.png


code:
import json

class Foo(object):
    def __init__(self, x=1, y='bar'):
        self.x = x
        self.y = y

class CustomEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, Foo):
            return obj.__dict__
        else:
            return json.JSONEncoder.default(self, obj)

filename = '/tmp/test.json'
with open(filename, 'w') as f:
    json.dump(
        [Foo(1, 'manchego'), Foo(2, 'stilton'), [{'brie': Foo(3,'gruyere')}]],
        f, cls=CustomEncoder)

def custom_decoder(dct):
    try:
        return Foo(**dct)
    except TypeError:
        return dct

with open(filename, 'r') as f:
    newfoo = json.load(f, object_hook=custom_decoder)
print(newfoo)
# [{"y": "manchego", "x": 1}, {"y": "stilton", "x": 2}, [{"brie": {"y": "gruyere", "x": 3}}]]

rawDescription: Not about to deserialize json kept as string in Python using json.load


rawDescription: How to test if a dictionary contains certain keys

description: Test if a dictionary contains certain keys


code:
b=np.arange(100).reshape(10,10)
b
i,j=a.shape
a=b[:i,:j]
a

rawDescription: Numpy: How to resize an random array using another array as template


code:
def enumerate(sequence, start=0):
    n = start
    for elem in sequence:
        yield n, elem
        n += 1

rawDescription: Why are some python builtin "functions" actually types?


code:
from __future__ import print_function
import matplotlib
import numpy as np

matplotlib.use("TkAgg")

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation

import Tkinter as tk
import ttk

a = Figure(figsize=(4, 4))
plot_a = a.add_subplot(111)
plot_a.set_xlim([0, 2*np.pi])
plot_a.set_ylim([-1, 1])
lna, = plot_a.plot([], [], color='orange', lw=5)

b = Figure(figsize=(4, 4))
plot_b = b.add_subplot(111)
plot_b.set_xlim([0, 2*np.pi])
plot_b.set_ylim([-1, 1])

lnb, = plot_b.plot([], [], color='olive', lw=5)

x = np.linspace(0, 2*np.pi, 1024)

def updateGraphsA(i):
    lna.set_xdata(x)
    lna.set_ydata(np.sin(x + i * np.pi / 10))
    print('in A')

def updateGraphsB(i):
    lnb.set_xdata(x)
    lnb.set_ydata(np.sin(x - i * np.pi / 10))

    print('in B')

class TransientAnalysis(tk.Tk):

    def __init__(self, *args, **kwargs):
        self._running_anim = None
        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.wm_title(self, "Transient Analysis GUI: v1.0")

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (GraphPageA, GraphPageB):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(GraphPageA)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()
        frame.canvas.draw_idle()

class GraphPageA(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        button1 = ttk.Button(self, text="Show Graph B",
                             command=(
                                 lambda: controller.show_frame(GraphPageB)))
        button1.grid(row=1, column=0, pady=20, padx=10, sticky='w')

        canvasA = FigureCanvasTkAgg(a, self)
        canvasA.show()
        canvasA.get_tk_widget().grid(
            row=1, column=1, pady=20, padx=10, sticky='nsew')
        self.canvas = canvasA

class GraphPageB(tk.Frame):

    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        button1 = ttk.Button(self, text="Show Graph A",
                             command=(
                                 lambda: controller.show_frame(GraphPageA)))

        button1.grid(row=1, column=0, pady=20, padx=10, sticky='w')

        canvasB = FigureCanvasTkAgg(b, self)
        canvasB.show()
        canvasB.get_tk_widget().grid(
            row=1, column=1, pady=20, padx=10, sticky='nsew')
        self.canvas = canvasB

app = TransientAnalysis()
app.geometry("800x600")
aniA = animation.FuncAnimation(a, updateGraphsA, interval=1000, blit=False)
aniB = animation.FuncAnimation(b, updateGraphsB, interval=1000, blit=False)

app.mainloop()

rawDescription: Using FigureCanvasTkAgg in two TKinter "pages" with python


rawDescription: scipy.optimize.curve_fit failing to fit curve

description: Scipy.optimize.curve_fit failing to fit curve


code:
import numpy as np
N = 5
A = np.arange(N)
X = np.arange(N*N).reshape(N,N)

B = np.arange(N)
W = np.arange(N*N).reshape(N,N)

G = np.arange(N)
Zij = np.arange(N)

rawDescription: Compute each element of matrix

description: Compute each element of matrix


code:
from __future__ import print_function

import math
import random

def patched_log(x):
    print('Computing log({:g})'.format(x))
    return math.log(x)

patches = {'math.log': patched_log}
cloned_modules = clone_modules(patches, ['random'])
new_math = cloned_modules['math']
new_random = cloned_modules['random']
print('Original log:         ', math.log(2.0))
print('Patched log:          ', new_math.log(2.0))
print('Original expovariate: ', random.expovariate(2.0))
print('Patched expovariate:  ', new_random.expovariate(2.0))

rawDescription: Making a copy of an entire namespace?

description: Making a copy of an entire namespace


code: data = gevent.with_timeout(5, sock.recv, timeout_value="")

rawDescription: How do I detect a socket disconnection? / How do I call socket.recv with a timeout?

description: Detect a socket disconnection? / How do I call socket.recv with a timeout


code:
from math import *
logsum = 0
n = raw_input('This is a logarithm ratio tester. Which number do you want to test? ')
for x in range(2,n):                            #picks numbers to test
    for divisor in range(2, 1+int(sqrt(x+1))):
        if x%divisor == 0:                      #checks if x is prime
            break
    else:
        logsum += log(x)

rawDescription: Python 2.5.4: how to find sum of logarithm values


code:
gradient = np.empty((8,N-2,N-2),dtype=np.float)
code = np.empty(8,dtype=np.int)
for k in range(8):
    theta = -k*np.pi/4
    code[k] = 2**k
    j, i = np.int(1.5*np.cos(theta)),-np.int(1.5*np.sin(theta))
    d = np.linalg.norm([i,j])
    gradient[k] = (array[1+i: N-1+i,1+j: N-1+j]-array[1: N-1,1: N-1])/d

rawDescription: Applying functions to multidimensional numpy arrays without loops