code:
from collections import defaultdict
from string import punctuation
d = defaultdict(list)
for line in lines.splitlines():
    for word in line.split():
        word = word.translate(None,punctuation)
        d[sum(l_n.get(ch,0) for ch in word)].append(word)

rawDescription: How would I convert words to numbers in python 3 (own keys and values)?


code:
def filter_lines(f, stride):
    for i, line in enumerate(f):
        if i%stride and (i-1)%stride:
            yield line

rawDescription: NumPy reading file with filtering lines on the fly


code:
s = set()
s.add(3)
s.add(3)
# s only has one 3 in it

rawDescription: Is there another way to avoid duplication of large hashable objects?


code: total_count = sum(stat.values()) # should be 130

rawDescription: calculate percentage of strings instead of statistics

description: Calculate percentage of strings instead of statistics


rawDescription: boost::python and swig integration

description: Boost::python and swig integration


code: df3 = df3.drop('variable', axis=1)

rawDescription: Iterate through a dataframe to find number of times a str value appears in an array of tuples


code:
from bs4 import BeautifulSoup, Comment

data = """
<!-- Special_ID -->
<p> stuff1 </p>
<p> stuff2 </p>
<!-- /Special_ID -->
"""
soup = BeautifulSoup(data, "html.parser")

# find "Special_ID" comment
special_id = soup.find(text=lambda text: isinstance(text, Comment) and "Special_ID" in text)

# find all sibling "p" elements
for p in special_id.find_next_siblings("p"):
    p.extract()

# create new "p" element
tag = soup.new_tag("p")
tag.string = "test"

# insert the new "p" element after the comment
special_id.insert_after(tag)

print(soup.prettify())

rawDescription: Python script to substitute text in HTML file with user-supplied values


code: from Microsoft.Win32 import OpenFileDialog

rawDescription: Open file dialog and select a file using WPF controls and Ironpython


code:
def good_for_g(g, n):
    # for some container `g` and item value `n`:
    u, v, w = n.value
    return v in g[u] and w in g[v] and u not in g[w]

rawDescription: Efficient list manipulation in python

description: Efficient list manipulation in python


code:
for line in lines:
    if 'w5CT$n<jfW' in line:
        password = line.partition('=')[2].rstrip('\n')

rawDescription: Python variables stored in text files not working, but should be


code:
def listPrinter(lst, cols):
    l = len(lst)
    rs = int(l/cols)
    for i in range(rs):
        for j in range(cols):
            print(lst[i + rs*j] , end='\t')
        print('')

rawDescription: Split long column into several columns and print them side by side


rawDescription: Spark Dataframe distinguish columns with duplicated name


rawDescription: What's the logic behind Python's hash function order?


code:
from itertools import chain

def sublists(lst, *args):
    return [[list(chain.from_iterable(l))[i] for i in args] for l in lst]

rawDescription: How to reorganize sublists and exclude specific indexes in those sublists?

description: Reorganize sublists and exclude specific indexes in those sublists


code:
from datetime import datetime
now = datetime.now()

rawDescription: Python - Start a Function at Given Time

description: Python - Start a Function at Given Time


code: ' ' in 'منهدم کردن'

rawDescription: Tokenizing non English Text in Python

description: Tokenizing non English Text in Python


code:
def get_cell(u, i):
    return str(u[-i]) if len(u) >= i else ''

def print_table(seq, width=3):
    maxlen = max(len(u) for u in seq)
    for i in range(maxlen, 0, -1):
        row = [get_cell(u, i).rjust(width) for u in seq]
        print(''.join(row))

#Test
lista=[[2], [1, 2], [2], [3], [3]]
listb=[[4], [2, 5], [1, 3, 6], [7], [8]]

print(lista)
print_table(lista)
print('-' * 20)

print(listb)
print_table(listb)

rawDescription: Print elements of list horizontally

description: Print elements of list horizontally


code:
import multiprocessing as mp
logger = mp.log_to_stderr(logging.INFO)

rawDescription: Why is a Python multiprocessing daemon process not printing to standard output?


code:
from flask import make_response

outdata = ""

for data in alldata:
    outdata += ",".join(data) + "\n"

response = make_response(outdata)
response.headers["Content-Disposition"] = "attachment; filename=data.csv"

return response

rawDescription: Serve file to browser from python (flask) webservice


code:
def eval(self):
    v = self.value
    if v in self.var_:  # has_key is deprecated Python, use 'in'
        varval = self.var_[v]
        return varval.eval() if hasattr(varval,'eval') else varval
    else:
        return float(v)

rawDescription: Evaluating nested variables with pyparsing for a DSL


code: max(x, key=x.get)

rawDescription: Finding largest value in a dictionary

description: Finding largest value in a dictionary


code: zip(b, a)

rawDescription: Create multidimensional list in python through two other lists


code:
example_post = Post.objects.get(pk=1)
posts_that_quote_my_example_post = example_post.quoted_by.all()

rawDescription: Django: get info from same table based on column vsalue for data record


code:
args = (arg1, arg2, arg3)
func(*args)

rawDescription: How can i have more than 255 arguments in Z3py function?

description: Have more than 255 arguments in Z3py function


code: logging.info('Info message')

rawDescription: Project/Multiple Class Verbose Mode Python


code:
import cv2
import numpy as np

# Colors (B, G, R)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

def create_blank(width, height, color=(0, 0, 0)):
    """Create new image(numpy array) filled with certain color in BGR"""
    image = np.zeros((height, width, 3), np.uint8)
    # Fill image with color
    image[:] = color

    return image

def draw_half_circle_rounded(image):
    height, width = image.shape[0:2]
    # Ellipse parameters
    radius = 100
    center = (width / 2, height - 25)
    axes = (radius, radius)
    angle = 0
    startAngle = 180
    endAngle = 360
    thickness = 10

    # http://docs.opencv.org/modules/core/doc/drawing_functions.html#ellipse
    cv2.ellipse(image, center, axes, angle, startAngle, endAngle, BLACK, thickness)

# Create new blank 300x150 white image
width, height = 300, 150
image = create_blank(width, height, color=WHITE)
draw_half_circle_rounded(image)
cv2.imwrite('half_circle_rounded.jpg', image)

rawDescription: How can I draw half circle in OpenCV?

description: Draw half circle in OpenCV


rawDescription: Pack a list with string and int type use struct.pack python


code:
def get_tuples(length, total):
    if length == 1:
        yield (total,)
        return

    for i in xrange(total + 1):
        for t in get_tuples(length - 1, total - i):
            yield (i,) + t

rawDescription: How to generate a set of all tuples of given length and sum of elements?

description: Generate a set of all tuples of given length and sum of elements


code:
class Foo(object):
    def __init__(self):
        self._vals = {}

    def __setitem__(self, key, val):
        do_side_effect(key, val)
        self._vals[key] = val

rawDescription: Pythonic alternative to dict-style setter?


code: free, total, totalfree = win32file.GetDiskFreeSpaceEx(r'\\server\share')

rawDescription: Available disk space on an SMB share, via Python


code: [obj2, obj1, obj5, obj3, obj4]

rawDescription: Python: sort list based on value present in dictionary


code: relation_dict = {'Charlotte': ['Tim'], 'Sue': ['Chad', 'Brenda', 'Harris'], 'Alice': ['John', 'Dick', 'Harry'], 'Brenda': ['Freddy', 'Alice']}

rawDescription: Looping dictionary values

description: Looping dictionary values


code:
def binary(length=4, ones=2):
    result = []
    for positions in combinations(range(length), ones):
        result.append("".join("1" if _ in positions else "0" for _ in range(length)))
    return result

rawDescription: Find unique permutation of a list binary values without generating all possibilities


code: data = '\x55\xaa\xf0'

rawDescription: python - pack exactly 24 bits into unsigned/signed int

description: Python - pack exactly 24 bits into unsigned/signed int


code:
from collections import defaultdict

dict1 = defaultdict(list)
dict1['x1'] = ['y1','y2']
dict1['x2'] = ['y2','y3','y4']
dict2 = defaultdict(list)
dict2['y1'] = ['x1']
dict2['y2'] = ['x1','x2']
dict2['y3'] = ['x2']

rawDescription: inserting a new entry into adjacency list

description: Inserting a new entry into adjacency list


code:
from sqlalchemy import func, select, distinct

query = select([distinct(func.date_part('YEAR', Topic.date_created))])
for row in session.execute(query):
        print(row[0])

rawDescription: How to retrieve only the year from timestamp column?

description: Retrieve only the year from timestamp column


code:
egg_link = os.path.join(self.buildout['buildout']['eggs-directory'], 'external-package.egg-link')
f = open(egg_link, 'wt')
f.write(self.options['install-directory'] + '\n')
f.close()
self.options.created(egg_link)
return self.options.created()

rawDescription: How to prepend a path to a buildout-generated script

description: Prepend a path to a buildout-generated script


code:
ENABLEPRINTER=y
PRINTERLIST=PRNT3

PRNT1.PORT=8310
PRNT1.BITS=8

rawDescription: Edit configuration file through python

description: Edit configuration file through python


code:
from collections import Counter
lines = Counter([line for line in myfile if match_string in line])

rawDescription: Count lines matching different patterns in one pass


code:
day = int(input("Which numeric day of the month were you born in?\n"))
if(day <= 0) or (day > maxdays):
    print("For your selected month, the value for day must be within the range {0} >= Day > 0. Please enter the value again.".format(maxdays))
    print("\n")
    day = int(input("Which numeric day of the month were you born in?\n"))

rawDescription: Python: getting nested while loops to work with boolean statements(beginner)


code:
@render_to()
def return_qr(request):
    text = request.GET.get('text')
    qr = generate_qr_code(text, 10, 2)
    response = HttpResponse(mimetype="image/png")
    qr.save(response, "PNG")
    return response

rawDescription: How to display a PIL image object in Django view?

description: Display a PIL image object in Django view


rawDescription: How to sort tire sizes in python

description: Sort tire sizes in python


code:
from BeautifulSoup import BeautifulSoup
from pprint import pprint

html = '''

HEADER 1

DATA11

DATA12

DATA12

DATA21

DATA22

DATA23

DATA31

DATA32

DATA33

HEADER 2

DATA11

DATA12

DATA13

DATA21

DATA22

DATA23

DATA31

DATA32

DATA33

'''

soup = BeautifulSoup(html)
rows = soup.findAll('tr')

section = ''
dataset = {}
for row in rows:
    if row.attrs:
        section = row.text
        dataset[section] = {}
    else:
        cells = row.findAll('td')
        for cell in cells:
            if cell['class'] in dataset[section]:
                dataset[section][ cell['class'] ].append( cell.text )
            else:
                dataset[section][ cell['class'] ] = [ cell.text ]

pprint(dataset)

rawDescription: Iterating through a table of rows with beautiful soup in python


code:
comp = esfera.vertex['orid'] == esfera.vertex['orid2']

np.all(comp)
Out[15]: True

rawDescription: How to efficiently compute orientation of 3D normals in large pointclouds

description: Efficiently compute orientation of 3D normals in large pointclouds


code:
try:
    from numpy import ndarray
    np_arrays = True
except ImportError:
    np_arrays = False

rawDescription: Pretty print and substitute numpy arrays


code: acceptable_values = set([10, 20])

rawDescription: How to check whether script input param is among list of acceptable values?

description: Check whether script input param is among list of acceptable values


code:
from operator import add

docs = corpus.flatMap(lambda doc: doc.split(' '))
docs.map(lambda word: (word,1)).reduceByKey(add)

rawDescription: Pyspark, perform word count in an RDD comprised of arrays of strings.


rawDescription: Better way to convert file sizes in Python


code:
import wx #For graphics' interface
import os #For operating system compatibility

class MainWindow(wx.Frame):
    def __init__(self, parent, id, title):

        #SETUP
        wx.Frame.__init__(self, parent, wx.ID_ANY, title = "MyTitle", size = (550,300))
        self.dirname=''

        #CREATE
        self.create_status_bar()
        self.create_menu_bar()
        self.create_text_panel()
        self.create_graphics_panel()

        self.SetAutoLayout(True)

        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, 5)
        lc.left.SameAs(self, wx.Left, 5)
        lc.bottom.SameAs(self, wx.Bottom, 5)
        lc.right.PercentOf(self, wx.Right, 40)
        self.panelA.SetConstraints(lc)

        lc = wx.LayoutConstraints()
        lc.top.SameAs(self, wx.Top, 5)
        lc.left.RightOf(self.panelA, 5)
        lc.bottom.SameAs(self, wx.Bottom, 5)
        lc.right.SameAs(self, wx.Right, 5)
        self.panelB.SetConstraints(lc)

# FUNCTIONS
# ------------------------------------------------------------------------------
    def create_status_bar(self):
        self.CreateStatusBar() #A Statusbar at the bottom of the window

    def create_menu_bar(self):

    # File Menu
        filemenu= wx.Menu()

        menuOpen = filemenu.Append(wx.ID_OPEN, "&Open", "Open file to edit")
        filemenu.AppendSeparator()
        menuSave = filemenu.Append(wx.ID_SAVE, "&Save", "Save the file")
        menuSaveAs = filemenu.Append(wx.ID_SAVEAS, "Save &As", "Save the file with a new name")
        filemenu.AppendSeparator()
        menuExit = filemenu.Append(wx.ID_EXIT, "E&xit", "Terminate communication and close window")

    #The Menu Bar
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&File") #Adding the "File" menu to the 'menuBar'
        self.SetMenuBar(menuBar)  #Adding the 'menuBar' to the Frame content

    #Event binding
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        self.Bind(wx.EVT_MENU, self.OnExit, menuExit)
        self.Bind(wx.EVT_MENU, self.OnSave, menuSave)
        self.Bind(wx.EVT_MENU, self.OnSaveAs, menuSaveAs)

    def create_text_panel(self):
        self.panelA = wx.Panel(self)
        self.panelA.control = wx.TextCtrl(self.panelA, wx.ID_ANY, style = wx.TE_MULTILINE) #Text area with multiline
        self.panelA.SetBackgroundColour(wx.WHITE)

        panelA_sizer = wx.BoxSizer(wx.VERTICAL)
        panelA_sizer.Add(self.panelA.control, 1, wx.EXPAND)
        self.panelA.SetSizer(panelA_sizer)

    def create_graphics_panel(self):
        self.panelB = wx.Panel(self)
        self.panelB.SetBackgroundColour(wx.BLACK)

# EVENTS
# ------------------------------------------------------------------------------
    def OnExit(self, event):
        self.Close(True) #Close the frame

    def OnOpen(self, event):
        dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.*", wx.OPEN)

        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname, self.filename), 'r')
            self.panelA.control.SetValue(f.read())
            f.close()
        dlg.Destroy()

    def OnSave(self, event):
        f = open(os.path.join(self.dirname, self.filename), 'w')
        f.write(self.panelA.control.GetValue())
        f.close()

    def OnSaveAs(self, event):
        file_choices = "TXT (*.txt)|*.txt"
        dlg = wx.FileDialog(self, message = "Save file as...", defaultDir = os.getcwd(), defaultFile = self.filename, wildcard = file_choices, style = wx.SAVE)

        if dlg.ShowModal() == wx.ID_OK:
            f = open(os.path.join(dlg.GetDirectory(), dlg.GetFilename()), 'w')
            f.write(self.panelA.control.GetValue())
            f.close()

# RUN!
# ------------------------------------------------------------------------------
if __name__ == '__main__':
    app = wx.PySimpleApp(False)
    app.frame = MainWindow(None, wx.ID_ANY, "tSock - Adaptation Technologies")
    app.frame.Show()
    app.MainLoop()

rawDescription: Two panels side by side (one with TextCtrl) - wxPython


code: difference=a-b

rawDescription: What is the easiest way to detect a cross-over in values of 1d list?


rawDescription: Mock: Tracking all Calls. Shell vs. program inconsistency


code:
In [11]: None == None
Out[11]: True

In [12]: np.nan == np.nan
Out[12]: False

rawDescription: How to filter by NaN in string column in pandas?

description: Filter by NaN in string column in pandas


code:
def add_to_tuple(prev,new):
    return prev+(new,) #prev is a tuple, add in the new element to the tuple

for path,value in traverse(doc,(),add_to_tuple): #prev_path is initially an empty tuple
    print("{} = {}".format(path,value))

rawDescription: Python: Loop through all nested key-value pairs created by xmltodict


rawDescription: max row sequence from sorted list for each index

description: Max row sequence from sorted list for each index


code:
import re
re.sub(r'[ \n]', '_', 'a b c\n')

rawDescription: Remove space and newlines in pandas columns using idiomatic Python?


rawDescription: Different databases with the same models on Django


code:
from operator import itemgetter
dictA = {'qty':1000, 'color':'red'}
dictB = {'qty':3000, 'color':'red'}
dictC = {'qty':5000, 'color':'red'}
def minQty(*args):
    return min(args, key=itemgetter('qty'))

minQty(dictA, dictB, dictC)

rawDescription: Comparing value of same key between multiple dictionaries


code:
with open(fname) as f:
    content = f.readlines()

rawDescription: Removing text from field in Mongodb with Python


code: soup.select('tr td.table')

rawDescription: BeautifulSoup4: Find elements with children tags


rawDescription: Python regex and using s/ in pattern

description: Python regex and using s/ in pattern


code: totals['quantity'] = sum([e.quantity for e in entries if EntryMatches(e)])

rawDescription: Iterating through large lists with potential conditions in Python


code: xl, yl = plt.xlim(), plt.ylim()

rawDescription: matplotlib's scatter plot changes the axis of another plot

description: Matplotlib's scatter plot changes the axis of another plot


code:
new_y = np.zeros((a.shape[0], a.max()+1))
new_y[np.indices(a.ravel().shape)[0], a.ravel()] = 1.

rawDescription: Vectorize this function in Numpy Python

description: Vectorize this function in Numpy Python


code: [[int(n) for n in elem.split()] for elem in originallist]

description: List of strings in ints ['123 121','42 23','23 23']


code:
import lxml.etree as ET
tree = ET.parse('data')
root = tree.getroot()
newroot = ET.Element("root")
newroot.insert(0, root)
print(ET.tostring(newroot, pretty_print=True))

rawDescription: PYTHON : How to add root node to an XML

description: PYTHON : How to add root node to an XML


code: g.apply(lambda x: pd.Series(np.average(x[["var1", "var2"]], weights=x["weights"], axis=0), ["var1", "var2"]))

rawDescription: Pandas Group Weighted Average of Multiple Columns


code:
import uuid
uuid.uuid4().int

rawDescription: Is there already package in python which generate strong random sequence which uses only digits?


rawDescription: All possible pairs of factors

description: All possible pairs of factors


code:
coords=zip(X, Y)
from scipy import spatial
dists

rawDescription: Calculate Euclidian Distance in two numpy arrays


code:
x = None
def test(self):
    self.MyTextCtrl.Bind(wx.EVT_TEXT, self.something)

def something(self, event):
    global x
    x = ... # alter variable on event

rawDescription: How can I give variables to the event handler?

description: Give variables to the event handler


code: PyIUnknown = CoCreateInstance(clsid, unkOuter , context , iid )

rawDescription: How to control windows master audio in python script

description: Control windows master audio in python script


code:
import shelve

COLUMNS = ('FirstName', 'LastName', 'Age', 'Sex')

the_db = shelve.open('test.db', writeback=True)
for col_name in COLUMNS:
    if col_name not in the_db:
        the_db[col_name] = []

records = [
    ('John', 'Deer', 20, 'M'),
    ('Ada', 'Lovelace', 23, 'F'),
]

for record in records:
    for col_name, value in zip(COLUMNS, record):
        the_db[col_name].append(value)

the_db.close()

the_db = shelve.open('test.db')

for record in zip(*(the_db[col_name] for col_name in COLUMNS)):
    print(record)

the_db.close()

rawDescription: How to give multiple values to a single key using a dictionary?

description: Give multiple values to a single key using a dictionary


code: ( dct(X, axis=2) == np.array(map(dct, X)) ).all()

rawDescription: Iterating over 2d arrays contained in 3d array in Python


code:
['First', 'Second', 'Third', 'Fourth']
['First', 'Second', 'Third', 'Fourth']
['First', 'Third', 'Second', 'Fourth']
['First', 'Second', 'Third', 'Fourth']
['First', 'Second', 'Third', 'Fourth']
['First', 'Second', 'Third', 'Fourth']

rawDescription: Combine two lists of strings

description: Combine two lists of strings


code:
#!python2
#!python3
#!python3.2
#!python3.2-32

rawDescription: Do I have to uninstall old python versions to update to a new one in Windows?


code:
from sympy import *
N = 10
x = range(N)
mu = Symbol('mu')
s = sum([(xi-mu)**2 for xi in x])
print(s)
print(s.diff(mu))     # to show this is a symbolic expression

rawDescription: How do I use a python array in a symbolic expression?

description: Use a python array in a symbolic expression


code:
pk = (  ignition_data
                  .objects
                  .filter(vehicle=veh_obj,updated_time_lt=new_time)
                  .order_by('updated_time')
                  .values_list('id', flat=True)
                  .first()
      )
ignition_data.objects.filter(pk=pk).update( updated_time =new_time )

rawDescription: update a specific field in a filter queryset django without creating an instance

description: Update a specific field in a filter queryset django without creating an instance


code:
for root, dirs, files in os.walk("/your/path/to/logs"):
    for file in files:
        filepath = os.path.join(root, file)
        with open(filepath, 'r') as content_file:
            file_contents = content_file.read()
            writer.add_document(title=file, content=the_contents, path=filepath)

rawDescription: Whoosh Functionality

description: Whoosh Functionality


code:
# x and y are values in the foo namespace, available as member attributes
# of the foo module object when foo is imported elsewhere
x = 'x'
y = 'y'

rawDescription: Importing "sub" modules to be own "sub" modules


code: mystring = "iBeacon major:{} minor:{}".format(majorVersion, minorVersion)

rawDescription: Python is there an equivalent of stringWithFormat: from Objective-C?


code:
@cache_page(None)  # won't expire, ever
def dyn_css(request):
    (css_theme, created) = CSS_Theme.objects.get_or_create(pk=1)
    return render_to_response('dynamic.css', {'theme': css_theme},
                              content_type="text/css")

rawDescription: Customize CSS from Code (Django)

description: Customize CSS from Code (Django)


code:
fmin(func, 0.3, xtol=1e-8)
np.arcsin(0.5)

rawDescription: python curve_fit doesn't work with stiff model

description: Python curve_fit doesn't work with stiff model


code: gen_list = [mapping[i] for i in org_list]

rawDescription: Python program that generate a list from a given list according to a mapping


code:
with open('binary.txt',"rb",buffering=-1) as f:
    for line in f:
        for c in [b for b in line if b in range(663,765)]: #in a certain range
            print(c)
        for c in [b for b in line if b == 5]: #is a certain number
            print(c)

rawDescription: Python: Read binary file into buffer as integer then Slice


code:
s3 = "a==b"  # I guess you wouldn't want to split that
r.split(s3)
r = re.compile(r"(?<![!=])=(?!=)")
r.split(s3)

rawDescription: Regex: How to split by "=" and not by "!="


code:
rows
cols
am[rows, cols]

rawDescription: How to efficiently select a submatrix with Python?

description: Efficiently select a submatrix with Python


code:
# In your case
import itertools
lst = [0, 1, 3, a, b, c]
output = list(itertools.product(lst, repeat=20))

rawDescription: Create a list with all possible permutations from a know list of objects, but make the final list x in size


code:
d = {}
tuples = [('Jem', 10), ('Sam', 10), ('Sam', 2), ('Jem', 9), ('Jem', 10)]
for tuple in tuples:
    key,val = tuple
    d.setdefault(key, []).append(val)

rawDescription: How can I find the average of each similar entry in a list of tuples?

description: Find the average of each similar entry in a list of tuples


code: df['Score'].apply(lambda score: lookup['Grade'][(lookup['Lower_Boundary'] <= score) & (lookup['Upper_Boundary'] > score)].values[0])

rawDescription: Pandas table lookup

description: Pandas table lookup


code:
# -*- coding: utf-8 -*-
from multiprocessing import Pool
import os

users = {
    'a': '1',
    'b': '2',
    'c': '3'
}

def launcher(args):
    os.system("python implementation.py %s %s" % (args[0], args[1]))

if __name__ == '__main__':
    with Pool(3) as p:
        p.map(launcher, users.items())

rawDescription: Python Multiprocessing function

description: Python Multiprocessing function


code: post_dict = request.POST.copy()

rawDescription: how to create POST data in django python

description: Create POST data in django python


rawDescription: Rearranging Matrix Elements with Numpy

description: Rearranging Matrix Elements with Numpy


code:
mit_courses = set(Course.query.join(
University).filter(University.name == 'MIT'))
[p.name for p in Professor.query if set(
p.courses_assisted).intersection(mit_courses)]

rawDescription: SQLAlchemy/Elixir - querying to check entity's membership in a many-to-many relationship list


code:
# Produces ["/bin/sh", "-c", "ls -al"]
subprocess.call("ls -al", shell=True)

rawDescription: subprocess.call() arguments ignored when using shell=True w/ list

description: Subprocess.call() arguments ignored when using shell=True w/ list


code: b = word in (w for i, w in enumerate(wordList) if i != 1)

rawDescription: python check if word is in certain elements of a list

description: Python check if word is in certain elements of a list


code: my_date.strftime('%A, %d %B')

rawDescription: Format date like: Monday, 1st March

description: Format date like: Monday, 1st March


code:
with open('scores.txt', 'w') as outfile:
    for name, score in scores:
        outfile.write('%s %s\n' % (name, score))

rawDescription: How to create a dictionary based on a text file?

description: Create a dictionary based on a text file


rawDescription: Bokeh package in Python: How to use rgb to color option


code:
def func(data, a, b):
    return data[:,0]*data[:,1]*a + b

rawDescription: Fitting 3D points python

description: Fitting 3D points python


code:
import thread

command = None
command_lock = thread.allocate_lock()

def main():
    thread.start_new_thread(motor_thread)

    global command
    while True:
        data = read_sensors()
        with command_lock:
            command = process(data)

def motor_thread():
    while True:
        while not command: # just to be sure
            time.sleep(0.01)
            # small delay here (for instance, the time consumed by read_sensors + process)
        with command_lock:
            motor_do(command)
            command = None
        time.sleep(delay)

rawDescription: How to multithread/multiprocess just one instance of a particular function in Python?

description: Multithread/multiprocess just one instance of a particular function in Python


code:
for row in rows:
    result.setdefault(row['Type'], {}).setdefault(row['Application'], []).append(row['Name'])

rawDescription: How to convert CSV to a more structured dictionary in python?

description: Convert CSV to a more structured dictionary in python


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code: sort_logic = case(value=Task.priority, whens=whens).label("priority")

rawDescription: Specify the sort-order for an Enum field type


code:
import ast
import datetime

def parse_datetime_dict(astr,debug=False):
    try: tree=ast.parse(astr)
    except SyntaxError: raise ValueError(astr)
    for node in ast.walk(tree):
        if isinstance(node,(ast.Module,ast.Expr,ast.Dict,ast.Str,
                            ast.Attribute,ast.Num,ast.Name,ast.Load, ast.Tuple)): continue
        if (isinstance(node,ast.Call)
                and isinstance(node.func, ast.Attribute)
                and node.func.attr == 'datetime'): continue
        if debug:
            attrs=[attr for attr in dir(node) if not attr.startswith('__')]
            print(node)
            for attrname in attrs:
                print('    {k} ==> {v}'.format(k=attrname,v=getattr(node,attrname)))
        raise ValueError(astr)
    return eval(astr)

good_strings=["{'the_datetime': datetime.datetime(2010, 11, 21, 0, 56, 58)}"]
bad_strings=["__import__('os'); os.unlink",
             "import os; os.unlink",
             "import(os)", # SyntaxError
             ]

for astr in good_strings:
    result=parse_datetime_dict(astr)
    print('{s} ... [PASSED]'.format(s=astr))

for astr in bad_strings:
    try:
        result=parse_datetime_dict(astr)
    except ValueError:
        print('{s} ... [REJECTED]'.format(s=astr))
    else:
        sys.exit('ERROR: failed to catch {s!r}'.format(s=astr))

rawDescription: python ast.literal_eval and datetime

description: Python ast.literal_eval and datetime


rawDescription: Remove occluded scatter plot points

description: Remove occluded scatter plot points


code:
class CurrentUserView(APIView):
    def get(self, request):
        serializer = UserSerializer(request.user)
        return Response(serializer.data)

rawDescription: Return the current user with Django Rest Framework


code:
f = Foo()
q = MockQuery()
assert f.method_one(q) == [1,2]

rawDescription: Mocks or Stubs?

description: Mocks or Stubs


rawDescription: Summing a tuple in a list, in python

description: Summing a tuple in a list, in python


code: print(x, end=" ")  # Appends a space instead of a newline

rawDescription: Print a row of numbers and then have it make a new line and continue counting


code:
import re
import requests
import bs4

page = requests.get("https://au.finance.yahoo.com/q/is?s=AAPL")
soup = bs4.BeautifulSoup(page.content)

table = soup.find("table", class_="yfnc_tabledata1")
total_revenue_label = table.find(text=re.compile(r'Total Revenue'))
total_revenue_label.parent.parent.next_sibling.get_text(strip=True)

rawDescription: Why is this tag empty when parsed with beautiful soup?


code:
fnn = buildNetwork( trndata.indim, 5, trndata.outdim, outclass=SoftmaxLayer )

trainer = BackpropTrainer( fnn, dataset=trndata, momentum=0.1, verbose=True,             weightdecay=0.01)

ticks = arange(-3.,6.,0.2)
X, Y = meshgrid(ticks, ticks)
# need column vectors in dataset, not arrays
griddata = ClassificationDataSet(2,1, nb_classes=n_klass)
for i in xrange(X.size):
    griddata.addSample([X.ravel()[i],Y.ravel()[i]], [0])
griddata._convertToOneOfMany()  # this is still needed to make the fnn feel comfy

rawDescription: Library in python for neural networks to plot ROC, AUC, DET


code:
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

rawDescription: Python equivalent of Ruby's each_slice(count)


rawDescription: Transform numpy ndarray from a column list to row list


rawDescription: Pythonic way to break out of iteration over tuples when one value changes


code:
end = itemgetter(-1)
end([1, 2, 3])

rawDescription: Difficulty Sorting Tuples with itemgetter


code: B.configure(command = mainprgX)

rawDescription: Display a series of interfaces with one click of Run button


code:
def trimmed_std(data, low, high):
    tmp = np.asarray(data)
    return tmp[(low <= tmp) & (tmp < high)].std()

rawDescription: trimmed/winsorized standard deviation

description: Trimmed/winsorized standard deviation


code:
for row in self.SELECT_USERS_ACCOUNTS():
    item = QStandardItem(str(row[1]))
    # add userData to item
    item.setData(row[0],256)
    # item.setData(row[2], 257) and so on if there are further columns in row
    model.appendRow(item)

self.listUser.setModel(model)
self.listUser.clicked.connect(self.getUserData)

def getUserData(self,index):
    item = self.model().item(index.row(),index.column())
    iId = item.data(256)
    # xyz = item.data(257) for further columns
    print(iId) # or do anything else

rawDescription: How to populate a QListView with value and display data?

description: Populate a QListView with value and display data


code:
import re

pattern = re.compile(r"lease ([0-9.]+) {.*?hardware ethernet ([:a-f0-9]+);.*?}", re.MULTILINE | re.DOTALL)

with open("/Users/smitty/Dropbox/Company/Network/DHCP-Info/dhcpd.leases") as f:
    for match in pattern.finditer(f.read()):
        print(match.group(1), match.group(2))

rawDescription: Parsing dhcpd.leases with Python and Regex


code:
one[0]
one[2]

rawDescription: How do I take an integer from a list intending to use it?

description: Take an integer from a list intending to use it


code:
for n in xrange(len(path)):
    ...

rawDescription: Dealing with Nested Loops in Python - Options?


code: df.index = pd.DatetimeIndex(df.index)

rawDescription: Pandas select the year end quarters in a DF


code: data = np.array([mpimg.imread(name) for name in os.listdir('images/sample_images/')], dtype=np.float64)

rawDescription: Python - read images into image matrix

description: Python - read images into image matrix


rawDescription: Non greedy parsing with pyparsing

description: Non greedy parsing with pyparsing


code:
['andy', 'bob', 'marc']
['nick', 'paul', 'zac']

rawDescription: Why is the second list in this code printing three times?


code:
from collections import Counter
def get_siblings(l):
    c = Counter([x.getparent() for x in l])
    return [x for x in l if c[x.getparent()] > 1]

rawDescription: Determine if two html elements are siblings


code:
class Individualistic(object_or_whatever_bases):
  def __init__(self, whatever_args):
    self.__class__ = type('GottaBeMe', (self.__class__, object), {})
    # keep rocking...!-)

rawDescription: Using properties defined at a per-instance level not per-class


code:
e, v = eig(x)
p = np.argsort(np.abs(e))[::-1]  # descending order
v = v[:, p]

rawDescription: Sorting a NumPy array and permuting another one along with it


code:
from scipy.interpolate import RectSphereBivariateSpline

# a 2D array of intensity values
d = np.outer(np.sin(2 * theta), np.cos(2 * phi))

# instantiate the interpolator with the original angles and intensity values.
spl = RectSphereBivariateSpline(theta, phi, d)

# evaluate spline fit on a denser 50 x 50 grid of thetas and phis
theta_itp = np.linspace(0, np.pi, 50)
phi_itp = np.linspace(0, 2 * np.pi, 50)
d_itp = spl(theta_itp, phi_itp)

# in order to plot the result we need to convert from spherical to Cartesian
# coordinates. we can avoid those nasty `for` loops using broadcasting:
x_itp = r * np.outer(np.sin(theta_itp), np.cos(phi_itp))
y_itp = r * np.outer(np.sin(theta_itp), np.sin(phi_itp))
z_itp = r * np.outer(np.cos(theta_itp), np.ones_like(phi_itp))

# currently the only way to achieve a 'heatmap' effect is to set the colors
# of each grid square separately. to do this, we normalize the `d_itp` values
# between 0 and 1 and pass them to one of the colormap functions:
norm = plt.Normalize(d_itp.min(), d_itp.max())
facecolors = plt.cm.coolwarm(norm(d_itp))

# surface plot
fig, ax = plt.subplots(1, 1, subplot_kw={'projection':'3d', 'aspect':'equal'})
ax.hold(True)
ax.plot_surface(x_itp, y_itp, z_itp, rstride=1, cstride=1, facecolors=facecolors)

rawDescription: Attaching intensity to 3D plot

description: Attaching intensity to 3D plot


code:
with open('index.html', 'w'):
    pass

rawDescription: Create an empty HTML file using Python?

description: Create an empty HTML file using Python


code: '{0:.{1}%}'.format(value, digits)

rawDescription: variable number of digit in format string

description: Variable number of digit in format string


code:
def handleButtonClicked(self):
    button = QtGui.qApp.focusWidget()
    # or button = self.sender()
    index = self.table.indexAt(button.pos())
    if index.isValid():
        print(index.row(), index.column())

rawDescription: How to add multiple QPushButtons to a QTableView?

description: Add multiple QPushButtons to a QTableView


code: Bar.write(b, 'Hello, World!')  #should be equivalent to b.write('Hello, World!')

rawDescription: Controlling child class method from parent class


code:
tx = pd.DataFrame(index=df.transmitted)
rx = pd.DataFrame(index=df.received)
tx['p'] = 1   #adding a packet
rx['p'] = -1  #receiving a packet

#create the time series here
t = pd.concat([tx, rx])
t.sort().cumsum()

rawDescription: Python (Pandas): count of records between values at a given time (Packets in Flight)


code:
s='{name} has a {animal} that is %(animal_age)s years old'
dic = {'animal': 'bird', 'animal_age': 10, 'name': 'Dolly'}
s.format(**dic)

rawDescription: Python String Substitute Dict: Skip Key and Leave Formatter


code: axes.set_xticks(ticks, minor=False)

rawDescription: Equivalent function for xticks for an AxesSubplot object


code:
from collections import defaultdict

myDefaultDict = defaultdict(list, {'ab': [1,2,3], 'c': [4], 'def': [5,6]})  # original
reduced_d = defaultdict(list, {k: v for k, v in myDefaultDict.items() if len(v) > 1})

rawDescription: Python filter defaultdict

description: Python filter defaultdict


rawDescription: Star operator (*) applied to lists and integers


rawDescription: Efficient feature reduction in a pandas data frame


rawDescription: can a python decorator make a function able to operate on single objects and collection objects intelligently?

description: Can a python decorator make a function able to operate on single objects and collection objects intelligently


code:
x[x == 0] = limit
x

rawDescription: Reset cumsum if over limit (python)

description: Reset cumsum if over limit (python)


code:
def test():
    button_map_set(x, y)

Button(..., command=test)

rawDescription: Button parameter “command” executes when declared, but not when pressed


code:
def __init__(self, master):
    self.pass1 = tk.Entry(master,show="*")
    self.pass1.bind('<Key>', self.callback1)
    self.pass1.bind('<Return>', self.callback2) # callback2 bound to Enter / Return key
    self.pass1.pack()

rawDescription: Binding multiple events on Tkinter Entry?


rawDescription: What's best way to roundtrip an epoch timestamp?


code:
import os
import re
def locate(pattern = r'\d+[_]', root=os.curdir):
    for path, dirs, files in os.walk(os.path.abspath(root)):
        for filename in re.findall(pattern, ' '.join(files)):
            yield os.path.join(path, filename)

rawDescription: Python - Loop through list within regex

description: Python - Loop through list within regex


code:
import sys
sys.stdout.isatty()

rawDescription: How to check if I'm running in a shell (have a terminal) in Python?

description: Check if I'm running in a shell (have a terminal) in Python


rawDescription: Many2one field with our own function in openerp


code:
for k in range(0, 10):
    dist = math.sqrt((x - data.X[k])**2 + (y - data.Y[k])**2)
    try:
        if dist<min:
            min=dist
    except NameError:
        min=dist

rawDescription: Minimum distance using for loop

description: Minimum distance using for loop


code:
pattern = re.compile(r"""\D(?P<digits>\d+)(?P<field>[eb]par)[^=]+=\D+(?P<number>\d+\.\d+E[+-]\d+)""")

default = lambda : dict((('epar',[]), ('bpar',[])))
datastruct = defaultdict( default)

for line in raw.splitlines():
    result = pattern.search(line)
    parts = result.groupdict()
    datastruct[parts['digits']][parts['field']].append(parts['number'])

pprint.pprint(datastruct.items())

rawDescription: Creating a complex data structure by parsing an output file


code:
from tensorflow.python.ops import control_flow_ops as cfo

i = tf.constant(0)
condition = lambda i: tf.less(i, tf.rank(myTensor))
body = lambda x: ...
inital_accumulator = ...  # will be bound to `x` in first iteration of `body`.

# `result` will contain the value returned from the final iteration of `body`.
result = cfo.While(condition, body, [initial_accumulator])

rawDescription: Using Tensors in control flow and conditional statements


code:
class slot(DryDescriptor):
    def annotate(self, attr, attrs):
        del attrs[attr]
        self.attr = attr
        slots = attrs.setdefault('__slots__', []).append(attr)

    def annotate_class(self, cls):
        if self.alias is not None:
            setattr(cls, self.alias, getattr(self.attr))

rawDescription: OO design: an object that can be exported to a "row", while accessing header names, without repeating myself


code:
import urllib2
response = urllib2.urlopen('http://example.com/')
html = response.read()

rawDescription: How to simulate command prompt in Perl and Python

description: Simulate command prompt in Perl and Python


code:
rules = [
    Rule(SgmlLinkExtractor(restrict_xpaths='//div[@id="pagination"]',
                           canonicalize=False),
         callback='parser', follow=True),
]

rawDescription: Why is my Scrapy scraper only returning the second page of results?


rawDescription: Decimal precision in Python Scipy lfilter?


rawDescription: How can i get the time interval in python

description: Get the time interval in python


code:
from itertools import chain

def foo():
    yield from chain.from_iterable(zip(range(10), range(10, 20)))

rawDescription: Is there a way in python to change the order in which yield from get's processed?


code: writer.add_document(title=u"First document", path=u"/a", content=u"This is the first document we've added!")

rawDescription: Whoosh Functionality

description: Whoosh Functionality


code:
"""
List the partition templates available for the first disk.
The partition templates available will depend on the OS selected and the disk type assigned.

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Hardware_Component_Partition_OperatingSystem/getByDescription
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware_Component_Partition_OperatingSystem/

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""

import SoftLayer
import json

USERNAME = 'set me'
API_KEY = 'set me'

# To get the valid list of description values use SoftLayer_Hardware_Component_Partition_OperatingSystem::getAllObjects method.
description = "linux"

client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
packageService = client['SoftLayer_Hardware_Component_Partition_OperatingSystem']

objectMask = "mask[partitionTemplates[data]]"

try:
    templates = packageService.getByDescription(description, mask=objectMask)
    print(json.dumps(templates, sort_keys=True, indent=2, separators=(',', ': ')))
except SoftLayer.SoftLayerAPIError as e:
    print("Unable to list the partition templates. faultCode=%s, faultString=%s" % (e.faultCode, e.faultString))

rawDescription: Configuring Softlayer Disk Partitions at Order Time


rawDescription: Python - How do I write a more efficient, Pythonic reduce?


code:
def insert(list1, var, i):
    for idx in range(len(list1)-1, i, -1):
        list1[idx] = list1[idx-1]
    list1[i] = var

rawDescription: insert element into list, move pre-existing elements

description: Insert element into list, move pre-existing elements


code:
db = create_engine('mysql://localhost/test', strategy='threadlocal')
db.execute('SELECT * FROM some_table')

rawDescription: Pattern for a Flask App using (only) SQLAlchemy Core


rawDescription: Python extract text data in dynamic text format


code: bigger_array[2:4, 2:4] = masked_smaller_array[~masked_smaller_array.mask]

rawDescription: How to replace only part of a numpy array's values with those of another array?

description: Replace only part of a numpy array's values with those of another array


code:
def create_empty_universum(cols, rows, cell=0):
    return [[cell] * cols] * rows

rawDescription: creating a function that makes a new universum with all elements [0] PYTHON

description: Creating a function that makes a new universum with all elements [0] PYTHON


code:
from itertools import product
from operator import methodcaller

for i, j in product(range(1, 4), range(2, 6)):
  setattr(Tests, "test_%r_%r" % (i, j),
          lambda self, i=i, j=j: self.check(i, j))

rawDescription: What does the lambda self: do

description: What does the lambda self: do


code:
import csv
def read_csv(file_name):
    array_2D = []
    with open(file_name, 'rb') as csvfile:
        read = csv.reader(csvfile, delimiter=';') #Assuming your csv file has been set up with the ';' delimiter - there are other options, for which you should see the first link.
        for row in read:
            array_2D.append(row)
    return array_2D

rawDescription: Building on "How to read and write a table / matrix to file with python?"


code:
#!/usr/bin/env python
import os
import posixpath
import sys
from contextlib import closing

from paramiko import SSHConfig, SSHClient

hostname, out_path, in_string = sys.argv[1:] # get from command-line

# load parameters to setup ssh connection
config = SSHConfig()
with open(os.path.expanduser('~/.ssh/config')) as config_file:
    config.parse(config_file)
d = config.lookup(hostname)

# connect
with closing(SSHClient()) as ssh:
    ssh.load_system_host_keys()
    ssh.connect(d['hostname'], username=d.get('user'))
    with closing(ssh.open_sftp()) as sftp:
        makedirs_exists_ok(sftp, posixpath.dirname(out_path))
        with sftp.open(out_path, 'wb') as remote_file:
            remote_file.write(in_string)

rawDescription: python subprocess communicate freezes

description: Python subprocess communicate freezes


description: Python extract text data in dynamic text format


code:
from flask.json import JSONEncoder

class MyJSONEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, EqltByGene):
            return {
                'gene_id': obj.gene_id,
                'gene_symbol': obj.gene_symbol,
                'p_value': obj.p_value,
            }
        return super(MyJSONEncoder, self).default(obj)

rawDescription: Flask jsonify a list of objects

description: Flask jsonify a list of objects


code:
import ast
t = (u"[('x-xss-protection', '1; mode=block'), ('x-powered-by', 'PHP/5.4.21 ZendServer/6.2.0'), ('transfer-encoding', 'chunked'), ('expi res', '0'), ('vary', 'Accept-Encoding'), ('server', 'nginx'), ('last-modified', 'Thu, 03 Dec 2015 10:20:02 GMT'), ('connection', 'keep-alive '), ('pragma', 'no-cache'), ('cache-control', 'must-revalidate, post-check=0, pre-check=0, public'), ('date', 'Thu, 03 Dec 2015 10:20:02 GMT '), ('x-cached', 'EXPIRED'), ('content-type', 'text/html')]",)
dict(ast.literal_eval(t[0]))['content-type']

rawDescription: Search in list of tuples

description: Search in list of tuples


code:
Builder.load_string("""
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import ListAdapter kivy.adapters.listadapter.ListAdapter

<ListViewModal>:
    ListView:
        size_hint: .8, .8
        adapter:
            ListAdapter(data=["Item #{0}".format(i) for i in range(100)], cls = ListItemButton)
""")

rawDescription: Kivy: Why does ListView declare differently in .kv file?


rawDescription: minimum of list of lists

description: Minimum of list of lists


code:
def bar(a, b, c, d):
    d, c, b, a = a, b, c, d

dis.dis(bar)

rawDescription: How does swapping of members in the python tuples (a,b)=(b,a) work internally?


code:
from pyquery import PyQuery
from collections import defaultdict

doc = PyQuery(html)
values = defaultdict(dict)
for tr in doc('tr').items():
    if tr('th.title'):
        title = tr('th.title').text()
    else:
        items = zip(tr('.properties_label').items(),
                    tr('.properties_value').items())
        values[title].update(dict([(k.text(), v.text()) for k, v in items]))

rawDescription: How to parse HTML table using pyquery?

description: Parse HTML table using pyquery


code: set(codes)

rawDescription: I've been using dictionary keys as membership markers. Is this a good idea?


code:
def on_call(self, callback):
    callback()

rawDescription: Python multi-threaded unittesting

description: Python multi-threaded unittesting


code: indices = [i for i, w in enumerate(words) if w=='not']

rawDescription: Python: finding the two words following a key word


code:
l = [['One', 'Two', 'Three', 'Four'], ['Five', 'Six', 'Seven']]
[', '.join(x) for x in l]

rawDescription: Getting each word from long list in python


code:
def decorator(old):
    def new(*args, **kwargs):
        # ...
        return old(*args, **kwargs)
    return new

rawDescription: Why use **kwargs in python? What are some real world advantages over using named arguments?


code: list(modseq(10, 13))

rawDescription: Time based rotation

description: Time based rotation


code:
ln.remove()  # remove the artist
plt.draw()   # force a re-rendering of the canvas (figure) to reflect removal

rawDescription: How to remove the previous drawing in matplotlib, Python?

description: Remove the previous drawing in matplotlib, Python


code:
with open(file_name, 'w') as f:
    for line in iter(raw_input, ""):
        f.write(line+"\n")

rawDescription: How to make this code simply which uses argv, raw_input(), f.write() in Python

description: Make this code simply which uses argv, raw_input(), f.write() in Python


code:
set([np.nan, np.nan])
set([float('nan'), float('nan')])
set([np.float64('nan'), np.float64('nan')])

rawDescription: Reducing pandas series with multiple nan values to a set gives multiple nan values


code:
var1,var2,*extras=[' the ', ' the ','foo','bar']
var1
var2
extras             #rest of the elements are stored in extras

rawDescription: How can i grab the matched regex pattern in python

description: Grab the matched regex pattern in python


code:
line = [['CC', 'DC', 'EC', 'FC', 'GC', 'HC', 'XX'], ['value1']]
line[0].append(line.pop()[0])
line

rawDescription: Changing the value of an item in a list in a Python for loop


code:
import Tkinter as tk

master = tk.Tk()

frame = tk.Frame(master, width=40, height=40) #their units in pixels
button1 = tk.Button(frame, text="btn")

frame.grid_propagate(False) #disables resizing of frame
frame.columnconfigure(0, weight=1) #enables button to fill frame
frame.rowconfigure(0,weight=1) #any positive number would do the trick

frame.grid(row=0, column=1) #put frame where the button should be
button1.grid(sticky="wens") #makes the button expand

tk.mainloop()

rawDescription: Displaying square Tkinter.Button's?

description: Displaying square Tkinter.Button's


code:
from functools import reduce

sum_with_inplace_semantics = reduce(Foo.__iadd__, a, Foo())

rawDescription: Why doesn't python take advantage of __iadd__ for sum and chained operators?


code:
for row in c:
    print(foo(row))

rawDescription: In python's sqlite3 module, will using cursor.fetchone() as the condition for a while loop fetch a row?


rawDescription: How to force sympy to extract specific subexpressions?

description: Force sympy to extract specific subexpressions


code: df[g.cumcount() == n - 1]

rawDescription: pandas dataframe groupby and get nth row

description: Pandas dataframe groupby and get nth row


code:
from collections import defaultdict
looknext = defaultdict(list)
s="attempt"
for index, char in enumerate(s[:-1]):
    looknext[char].append(s[index+1])
looknext  # looks like: defaultdict(<type 'list'>, {'a': ['t'], 'm': ['p'], 'e': ['m'], 't': ['t', 'e'], 'p': ['t']})

rawDescription: Python: Get the following letters in a string and use as key value in dictionary


code:
kwargs = {'first_name': 'Bobby', 'last_name': 'Smith'}
print_keyword_args(**kwargs)

rawDescription: Understanding kwargs in Python

description: Understanding kwargs in Python


code:
def get_section_text(text):
    section = soup.find(text=text)
    if not section:
        raise ValueError("Section not found")

    texts = []
    for item in section.parent.find_next_siblings():
        if item.name == 'strong':
            break
        text_before = item.previous_sibling
        if isinstance(text_before, NavigableString):
            texts.append(text_before)

    return ' '.join(texts)

rawDescription: Get text separated by tags / BS4

description: Get text separated by tags / BS4


code:
class ReplViewAndExecute(sublime_plugin.TextCommand):
    def run(self, edit):
        v = self.view
        ex_id = v.scope_name(0).split(" ")[0].split(".", 1)[1]
        lines = v.lines(self.view.sel()[0]) # get the region, ordered
        last_point = v.line(self.view.sel()[0]).b # get last point (must use v.line)
        last_line = v.line(last_point) # get region of last line

        for line in lines:
            self.view.sel().clear() # clear selection
            self.view.sel().add(line) # add the first region/line
            text = v.substr(line)
            print('%s' % text) # prints in console (ctrl+`)

            if not line.empty() and text[0] != '#': # ignore empty lines or comments
                v.window().run_command('focus_group', {"group": 1}) # focus REPL
                v.window().active_view().run_command("insert",
                    {"characters": text})
                v.window().run_command('repl_enter')

        # if the last line was empty, hit return
        # else, move the cursor down. check if empty, hit return once more
        if last_line.empty():
            self.view.sel().clear()
            self.view.sel().add(last_line)
            v.window().run_command('focus_group', {"group": 1}) # focus REPL
            v.window().run_command('repl_enter')
            v.window().run_command('focus_group', {"group": 0})
            v.window().run_command('move', {
                "by": "lines",
                "forward": True,
                "extend": False
            })
        else:
            v.window().run_command('focus_group', {"group": 0})
            v.window().run_command('move', {
                "by": "lines",
                "forward": True,
                "extend": False
            })
            if self.empty_space():
                v.window().run_command('focus_group', {"group": 1}) # focus REPL
                v.window().run_command('repl_enter')

        # move through empty space
        while self.empty_space() and self.eof():
            v.window().run_command('focus_group', {"group": 0})
            v.window().run_command('move', {
                "by": "lines",
                "forward": True,
                "extend": False
            })
    def eof(self):
        v = self.view
        s = v.sel()
        return True if v.line(s[0]).b < v.size() else False

    def empty_space(self):
        v = self.view
        s = v.sel()
        return True if v.line(s[0]).empty() else False

rawDescription: Display output from evaluating selection - Sublime Text Python REPL


code: reduce(lambda a,e: a and e > 5, my_list, True)

rawDescription: python reduce accum as an argument

description: Python reduce accum as an argument


code:
from scrapy.loader.processors import Join

loader = MyItemLoader(response=response)
loader.add_xpath("genre", '//a[@class="genre"]/text()', Join(", "))

yield loader.load_item()

rawDescription: Python Scrapy, parsing multiple child objects into the same item?


code:
#!/usr/bin/env python3
import os
import pty

output = []
def read(fd):
    data = os.read(fd, 1024)
    output.append(data)
    return data
status = pty.spawn(['apt-get', 'download', 'firefox'], read)

rawDescription: Last unbuffered line can't be read

description: Last unbuffered line can't be read


code:
class Foo(object):
    def __init__(self, a = 'init'):
        self.a = a
        self.spam = 2

rawDescription: which to use: class variables versus classmethod?

description: Which to use: class variables versus classmethod


code:
with open(r'D:\python\input.txt') as data:
    symbols = []
    for line in data:
        symbols.extend(line.split())
    for prod in product(symbols, repeat=n):
        print("".join(prod))

rawDescription: enumeration in python for the combinations

description: Enumeration in python for the combinations


code: df.set_index('Timestamp', inplace=True)

rawDescription: create timestemps for given data

description: Create timestemps for given data


code:
import re
re.sub(r'[^A-Za-z]', '', s)

rawDescription: Is there a way to remove all characters except letters in a string in Python?


code:
for word in t.with_prefix(string): # I assume with_prefix() returns a list of words
    if len(word) == len(string):
       words.append(word)

rawDescription: blo python tree

description: Blo python tree


code:
class A(object):

    def __init__(self, first, second):
        self._first = first
        self._second = second

    @property
    def first(self):
        return self._first

    @property
    def second(self):
        return self._second

rawDescription: How to make class immutable in python?

description: Make class immutable in python


code:
x = 2
x

rawDescription: If Elif statements in python

description: If Elif statements in python


rawDescription: How to create a numeric triangle with user input in python?

description: Create a numeric triangle with user input in python


code:
stuff = ['a','b','c','d']
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)])

rawDescription: How to create a sequential combined list in python?

description: Create a sequential combined list in python


rawDescription: Unpickle a data structure Vs. build by calling readlines()


rawDescription: Getting limited information from JSON with Python


code:
def grouper(n, iterable):
    it = iter(iterable)
    while True:
       chunk = tuple(itertools.islice(it, n))
       if not chunk:
           return
       yield chunk

rawDescription: Iterate an iterator by chunks (of n) in Python?


code:
from splinter.browser import Browser
browser = Browser()
browser.visit('http://google.com')

rawDescription: What's the easiest way to download the source of a webpage in python? (After javascript has been applied)


code: older_groups = Group.objects.filter(grouptraffic__time_of_visit < one_hour_ago).extra(select={'visits':0})

rawDescription: How to sort a Django queryset by a conditional aggregation of related items?

description: Sort a Django queryset by a conditional aggregation of related items


code:
import itertools
import string

letter = string.lowercase
vowel  = "aeiouy"

def all_words(*args):
    return (''.join(letters) for letters in itertools.product(*args))

wordlist = list(all_words(vowel, letter, letter, "n", "o"))

rawDescription: Python script to generate words

description: Python script to generate words


rawDescription: Find C Keywords inside a String with Python and Regex


rawDescription: How to simplify this mass of similar ifs

description: Simplify this mass of similar ifs


code:
url ="https://news.google.co.uk"

import requests
import re
from bs4 import BeautifulSoup

def get_links(start):
    cont = requests.get(start).content
    soup = BeautifulSoup(cont, "lxml")
    keys = ['news','article','business', 'world']
    # links are all in the  a tag inside the esc-layout-table table
    # where the a tag class is article
    return [a["url"] for a in soup.select(".esc-layout-table a.article") if any(k in a["url"] for k in keys)]

def parse_links_text(links, css_d):
    # use regex to extract find out what page the link points to
    # so we can pull the appropriate selector from the dict
    r = re.compile("telegraph\.|bbc\.|dailymail\.|independent\.")
    for link in links:
        print(link)
        cont = requests.get(link).content
        soup = BeautifulSoup(cont)
        css = r.search(link).group()
        p = [p.text for p in soup.select(css_d[css])]
        yield p

# map each page to its correct css selector to pull the main text
d = {"dailymail.": "p.mol-para-with-font","telegraph.":"#mainBodyArea",
     "bbc.": "div.story-body p","independent.":"div.text-wrapper p"}

for text in (parse_links_text(get_links(url), d)):
    print(text)

rawDescription: Why does my webcrawler not follow into the next link containing keywords


code:
with open("file") as f:
    for i in f:
       with open("output") as f2:
           f2.write(re.sub(r'<tag>1(\d+)</tag>','<tag>YYYYY</tag>',i))

rawDescription: Replace string between tags if string begins with "1"


code:
def get_train_data(training_file):
    with open(training_file, "rt") as f:
        next(f)  # throw away "headers" in first line
        for line in f:
            lst = line.rstrip('\n').split(',')
            # lst contains: id,title,body,category_labels
            yield (lst[1],lst[2])

train_dict = dict(get_train_data("data.csv"))

rawDescription: Looking for a quick way to speed up my code


code:
from decimal import Decimal
pi = Decimal(3)
a=2
b=a * (a+1) * (a+2)
c=4/b
type(c)
pi = pi + c

rawDescription: Why has my program "stopped" working?

description: Why has my program "stopped" working


code:
bench(listcomp)
bench(concurrent)

rawDescription: Python and performance of list comprehensions


code:
from bs4 import BeautifulSoup
html = """

            User write:
               I DO NOT WANT THIS

    THIS IS THE COMMENT THAT I NEED!

"""
soup = BeautifulSoup(html, 'html.parser')
soup.find('blockquote').decompose()
soup.find("div", {"class" : "content"}).text.strip()

rawDescription: Extract content with BeautifulSoup and Python


code:
import operator

def prod(lst):
    return reduce(operator.mul, lst, 1)

f = open("filename", "r")

buff = ""
array = []
for line in f:
    buff += line
    if "}" in line:
        start = buff.index("{")
        end = buff.index("}")
        array.append([prod(float(factor.strip()) for factor in val.split("*")) for val in buff[start+1:end].split(",")])
        buff = buff[end+1:]

f.close()

print(array)

rawDescription: Matrix converting to a list in python

description: Matrix converting to a list in python


code:
def make_replacer(s):
    mods = [mod.split(', ') for mod in s.split(' / ')]
    def replacer(v):
        v = str(v)
        for mod in mods:
            v = v.replace(mod[0], mod[1])
        return v
    return replacer

rawDescription: Pythonically creating a string-modifying lambda function dynamically based off of input recieved


code: f_set = inlineformset_factory(ModelB, ModelA, extra=1)

rawDescription: How to have a ModelForm with a dynamic amount of related objects?

description: Have a ModelForm with a dynamic amount of related objects


code:
imported_lines = []
comment_start = '--comment--'
file_list = ['path/to/file1','path/to/file2','path/to/fileN']
for file_path in file_list:
    data_file = open(file_path,'r')
    for line in data_file.readlines():
        if line[:len(comment_start)]==comment_start:
            continue
        imported_lines.append(line)
    data_file.close()

rawDescription: How to import uncommented text from a file in Python?

description: Import uncommented text from a file in Python


code: auxdict = dict((d['name'], d['val']) for d in listA)

rawDescription: List of Dicts comparision to match between lists and detect value changes in Python


code:
def drawCard():
    drawnCard = random.choice(cardDeck)
    adPos = cardDeck.index(drawnCard)
    drawnCardValue = cardValues[adPos]
    return drawnCard, drawnCardValue

drawnCard, drawnCardValue = drawnCard()

rawDescription: Using local variables outside their functions


code:
N = 20

def worker(outq):
    from random import randrange
    from time import sleep
    while True:
        i = randrange(N)
        outq.put(i)
        sleep(0.1)

def uniqueifier(inq, outq):
    seen = set()
    while True:
        i = inq.get()
        if i not in seen:
            seen.add(i)
            outq.put(i)

def consumer(inq):
    n = 0
    for _ in range(N):
        i = inq.get()
        print(i)

if __name__ == "__main__":
    import multiprocessing as mp
    q1 = mp.Queue()
    q2 = mp.Queue()
    consume = mp.Process(target=consumer, args=(q2,))
    consume.start()
    procs = [mp.Process(target=uniqueifier, args=(q1, q2))]
    for _ in range(4):
        procs.append(mp.Process(target=worker, args=(q1,)))
    for p in procs:
        p.start()
    consume.join()
    for p in procs:
        p.terminate()

rawDescription: Can a set() be shared between Python processes?


rawDescription: Finding which rows have all elements as zeros in a matrix with numpy


code: final = [x.split(':') for x in ':'.join(l).split(':,:')]

rawDescription: splitting comma separated list

description: Splitting comma separated list


rawDescription: Extracting 2nd element from multiple sub-lists with stepping


code:
first = (input('Enter first word: '))
second = (input('Enter second word: '))
third = (input('Enter third word: '))
if first <= second <= third:
    print(True)

rawDescription: Creating a program that prints true if three words are entered in dictionary order


code:
payload = {
  'length'     :'length',      #Length
  'netcharge'  :'netcharge',   #Net Charge
  'amino'      :'amino',       #Amino acid composition
  'aliphatic'  :'aliphatic',   #Aliphatic Index
  'instability':'instability', #Instability Index
  'gravy'      :'gravy',       #Hydrophobicity
  'sec'        :'sec'          #Secondary Structure Propensity
  }

rawDescription: Using request.post to post multipart form data via python not working


code:
Veg(name, color)
vegList.append(Veg)

rawDescription: Instantiating Python objects, and using lists


rawDescription: Learning python... stumped. Where is the loop in this function?


code:
def playerVsAiGame (sticksOnBoard):
    # main game loop
    while True:
        sticks = sticksOnBoard
        isPlayerMove = True

        # only ask when there are more than 3 left; otherwise the current
        # player can just choose the remaining number and win
        while sticks > 3:
            print('There are {} sticks on the board.'.format(sticks))
            if isPlayerMove:
                move = int(input('How many sticks would you like to take? (1-3) '))
            else:
                # the computer just chooses randomly between 1, 2, and 3 sticks
                # this is where you could add additional game logic to make the AI
                # smarter
                move = random.choice((1, 2, 3))
                print('The computer takes {} sticks.'.format(move))

            sticks -= move
            isPlayerMove = not isPlayerMove

        # the current player wins
        print('There are {} sticks on the board.'.format(sticks))
        if isPlayerMove:
            print('You win!')
        else:
            print('The computer wins!')

        # break the main loop unless the player wants to play again
        if input('Play again? Yes (1) / No (0) ').lower() not in ('1', 'yes', 'y'):
            break

rawDescription: Stuck in infinite loop, cant figure out why - python


code:
bins = 10
binwidth = numpy.max(rev_count)//bins
revbin = np.arange(0, np.max(rev_count)+binwidth+1, binwidth)

rawDescription: Python: Binning one coordinate and averaging another based on these bins


code:
for i in range(len(letters)):
    s = list(letters)
    s[i] = '1'
    print(''.join(s))

rawDescription: Change one character at a time in a string, don't change the string?


code:
# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

rawDescription: How to Customize the time format for Python logging?


code:
class Child(Parent):
    @classmethod
    def from_parent(cls, parent):
        return cls(parent.a, parent.b)

    def __init__(self, a, b):
        super(Child, self).__init__(a, b)
        # Note: the fact that yo have to do this,
        # or not call the parent's __init__ in the first
        # place, makes me question whether inheritance
        # is the right tool here.
        self.a = revert_change(self.a)
        self.b = revert_change(self.b)

p = Parent(3, 5)
c1 = Child.from_parent(p)
c2 = Child(6, 6)

rawDescription: initialize child class with parent

description: Initialize child class with parent


code:
import sys
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebPage

# Set vars here for convenience
username = "myUsername"
password = "myPassword"

class HeadlessBrowser(QWebPage):
    def __init__(self, url):
        self.app = QApplication(sys.argv)
        super(HeadlessBrowser, self).__init__()
        self.loadFinished.connect(self.login)
        self.mainFrame().load(QUrl(url))
        self.app.exec_();

    def login(self):
        doc = self.mainFrame().documentElement()
        user = doc.findFirst("input[name=login]")
        pwd = doc.findFirst("input[name=password]")
        button = doc.findFirst("button[id=logonForm_connect_button]")

        user.setAttribute("value", username)
        pwd.setAttribute("value", password)
        button.evaluateJavaScript("this.click()")
        # Uncomment if the button click above is not enough
        #form = doc.findFirst("form[name=logonForm]")
        #form.evaluateJavaScript("this.submit()")
        self.app.quit()

page = HeadlessBrowser("http://localhost/~iskren/headlesstest.html")
html = page.mainFrame().toHtml()

rawDescription: How can I log into a simple web access login using Python?

description: Log into a simple web access login using Python


code:
mGui.overrideredirect(1) # Remove shadow & drag bar. Note: Must be used before wm calls otherwise these will be removed.
mGui.call("wm", "attributes", ".", "-topmost", "true") # Always keep window on top of others
mGui.geometry("100x100+500+500") # Set offset from top-left corner of screen as well as size
mGui.call("wm", "attributes", ".", "-transparent", "true") # Remove shadow from window
mGui.call("wm", "attributes", ".", "-fullscreen", "true") # Fullscreen mode
mGui.call("wm", "attributes", ".", "-alpha", "0.9") # Window Opacity 0.0-1.0

rawDescription: tkinter with mac osx

description: Tkinter with mac osx


code:
def increment_item(item = 'A'):
    '''
    Given a character sequence item, produces the next item in the character sequence set

    :type item: str
    :param item: The character sequence item to increment
    :rtype: str
    :return: The next element in the sequence. EX: item='A', return ='B'. item='Z', return ='AA'

    '''
    next_char = [ord(char) for char in item]
    next_char[-1] += 1
    for index in xrange(len(next_char)-1, -1, -1):
            if next_char[index] > ord('Z'):
                    next_char[index] = ord('A')
                    if index > 0:
                            next_char[index-1] += 1
                    else:
                            next_char.append(ord('A'))
    return ''.join((chr(char) for char in next_char))

def char_generator(start = 'A'):
    '''
    A generator which yields the next item in the character sequence every time next() is called

    :type start: str
    :param start: The starting item for the generator sequence

    '''
    current = start
    yield start
    while True:
        current = increment_item(current)
        yield current

def build_unique_sequence(sequence):
    '''
    Given an input sequence, returns the same sequence with characters
    appended such that every element in the returned sequence is unique

    :type sequence: list
    :param sequence: The sequence to make unique
    :rtype: list
    :return: The resultant unique sequence. EX: sequence = [0, 1, 2, 3, 1, 4, 2, 1], return = ['0A', '1A', '2A', '3A', '1B', '4A', '2B', '1C']

    '''
    key_set = dict([item, char_generator()] for item in set(sequence))
    return map(lambda item:'{}{}'.format(item, key_set[item].next()), sequence)

rawDescription: iterating over list and concatenating alphabetical sequence in Python

description: Iterating over list and concatenating alphabetical sequence in Python


code:
dictionary = {}
for i in dict:
    for j in dict:
        c = set(dict[i]).intersection(set(dict[j]))
        if len(c) == 1:
            # ok, so now we know, that exactly one tuple exists in both
            # sets at the same time, but this one will be the key to new dictionary
            # we need the second tuple from the set to become value for this new key
            # so we can subtract the key-tuple from set to get the other tuple
            d = set(dict[i]).difference(c)
            # Now we need to get tuple back from the set
            # by doing list(c) we get list
            # and our tuple is the first element in the list, thus list(c)[0]
            c = list(c)[0]
            dictionary[c] = list(d)[0]
        else: pass

rawDescription: How do I extract part of a tuple that's duplicate as key to a dictionary, and have the second part of the tuple as value?

description: Extract part of a tuple that's duplicate as key to a dictionary, and have the second part of the tuple as value


code: excluded_ids = [user.id for user in MarkedUserIds.objects.filter(marked_user_id = {specific_one_user_id})]

rawDescription: How to select users which is not paired with a custom user through many-to-one?

description: Select users which is not paired with a custom user through many-to-one


code:
class A:
  def __call__(self): pass

rawDescription: How to distinguish bound method or a function from a class?

description: Distinguish bound method or a function from a class


code:
import random as rn

x = range(3)*2 #generate a list where each number appears twice

rn.shuffle(x) #shuffle it
x.pop()       #remove one number

rawDescription: how to generate random num with conditions

description: Generate random num with conditions


code:
from Tkinter import *
from ttk import *

class Controller(Frame):

    def __init__(self,parent):
        Frame.__init__(self, parent)

        buttons = Frame(parent)
        buttons.pack(side=TOP)
        for letter in 'ABCDEF':
            Button(buttons, text=letter).pack(side=LEFT)

        Entry(parent, width=50).pack(side=LEFT)
        Button(parent, text='OK').pack(side=RIGHT)

root = Tk()
app = Controller(root)
root.mainloop()

rawDescription: Python create Buttons and Entry widget

description: Python create Buttons and Entry widget


code:
def filter_(x, y):
    count = 0
    for num in y:
            if num in x:
                    count += 1
    return count

filter_(a, b)

rawDescription: Count duplicates between 2 lists

description: Count duplicates between 2 lists


code: from .base import *

rawDescription: How to settings.py for different environments (dev, production, etc.)

description: Settings.py for different environments (dev, production, etc.)


rawDescription: Convert Time Column to UTC Time, no date


code:
mask = ((lower_x_limit < array[0]) & (array[0] < upper_x_limit) &
        (lower_y_limit < array[1]) & (array[1] < upper_y_limit))
count = sum(mask)

rawDescription: Numpy: Comparison within Multidimensional array values


code:
from collections import defaultdict
d = defaultdict(list)
d['blue'].append(3)
d['blue'].append(4)
d

rawDescription: using nested loops in order to group data in a csv

description: Using nested loops in order to group data in a csv


code: locations = [moment[5] for moment in results['moments']]

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

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


code: move_from, move_to = prev_item['path'], item['path']

rawDescription: Double assignment in python

description: Double assignment in python


code: dct = next((x for x in example_list if x['id'] == 3), None)

rawDescription: Determine if nested object is in list

description: Determine if nested object is in list


code:
b = 'bar'
b is a  #False -- they're not longer the same object because you assigned a new object to b

rawDescription: Python: copy of a variable

description: Python: copy of a variable


rawDescription: Python 2: Why is floor division operator faster than normal division operator?


code:
from scrapy.contrib.downloadermiddleware.retry import RetryMiddleware
from scrapy import log

class CustomRetryMiddleware(RetryMiddleware):

    def _retry(self, request, reason, spider):
        retries = request.meta.get('retry_times', 0) + 1

        if retries <= self.max_retry_times:
            log.msg(format="Retrying %(request)s (failed %(retries)d times): %(reason)s",
                    level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)
            retryreq = request.copy()
            retryreq.meta['retry_times'] = retries
            retryreq.dont_filter = True
            retryreq.priority = request.priority + self.priority_adjust
            return retryreq
        else:
            # do something with the request: inspect request.meta, look at request.url...
            log.msg(format="Gave up retrying %(request)s (failed %(retries)d times): %(reason)s",
                    level=log.DEBUG, spider=spider, request=request, retries=retries, reason=reason)

rawDescription: Scrapy: collect retry messages

description: Scrapy: collect retry messages


code:
import collections

class AppendDict(collections.MutableMapping):
    def __init__(self, container=list, append=None, pairs=()):
        self.container = collections.defaultdict(container)
        self.append = append or list.append
        for key, value in pairs:
            self[key] = value

    def __setitem__(self, key, value):
        self.append(self.container[key], value)

    def __getitem__(self, key): return self.container[key]
    def __delitem__(self, key): del self.container[key]
    def __iter__(self): return iter(self.container)
    def __len__(self): return len(self.container)

rawDescription: defaultdict one-step initialization

description: Defaultdict one-step initialization


rawDescription: Reinitializing numbers in file (with differing amounts of columns?)


code: result = random_operator(number1, number2)

rawDescription: Implement a random math operation (+, -, or *)


rawDescription: Converting dataframe to numpy array causes all numbers to be printed in scientific notation


code:
with open("newfile.txt", "r") as f:
    sorted_data = sorted(f.readlines(), key=lambda item: int(item.strip().split("\t")[-1]))
    sort = [" ".join(line.strip().split("\t")) for line in sorted_data]
    print(sorted)

rawDescription: How to sort contents of a file.txt in python numerically

description: Sort contents of a file.txt in python numerically


rawDescription: Cleanest way to obtain a list of the numeric values in a string


code: [z for z in ([x for x in line] for line in a.split('\n')) if z]

rawDescription: How can I transform a string into a matrix

description: Transform a string into a matrix


code:
data = np.load('/path/to/data.npz', 'r')
a = data['a']
b = data['b']
# etc

rawDescription: How to load a npz file in a non-lazy way?

description: Load a npz file in a non-lazy way


code:
from pylab import *
from random import random
r = range(10)
x = [3 + i + random() for i in r]
y = [50*i + random() for i in r]
x2 = [5 + i + random() for i in r]
y2 = [5*i + random() for i in r]
z2 = [i + random() for i in r]
scatter(x,y,   c="0.1", marker = 'o', hold = True, label = 'collected underwear')
scatter(x2,y2, c=z2,marker = 's',  hold = True, label = 'Profit!',cmap=cm.Greys)
legend(loc='upper left')
show()

rawDescription: Python: matplotlib - Black and White Scatter


code:
def locatexml(pattern,exfiles=None):
    exfiles = set(exfiles)
    for path, dirs, files in os.walk(settings.MEDIA_ROOT):
        for filename in fnmatch.filter(files, pattern):
            if filename not in exfiles:
                yield os.path.join(path, filename)

rawDescription: Exclude python list containing filenames in os.walk


code:
col1 = data[:,0]
col2 = data[:,1]

subsets = {}
for val1, val2 in itertools.product(np.unique(col1), np.unique(col2)):
    subset = data[(col1 == val1) & (col2 == val2)]
    if np.any(subset):
        subsets[(val1, val2)] = subset

rawDescription: Subsetting data in python

description: Subsetting data in python


rawDescription: Numpy.cumsum in reverse

description: Numpy.cumsum in reverse


code: return re.match('^[a-zA-Z]{2}$', s) is not None

rawDescription: Validate a two characters code using python


code:
def to_string(value):
    return str(value)

def stringify(func):
    @wraps(func)
    def wrapper(*args):
        return to_string(func(*args))

    return wrapper

rawDescription: How to unit-test decorated functions?

description: Unit-test decorated functions


code:
from itertools import product
[x+y for x,y in product('12345','ab')]

rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.db import models

class MyUserManager(BaseUserManager):
    def create_user(self, username, password, email, created_at):
        """
        Creates and saves a User with the given username, password, email, created_a
        birth and password.
        """
        if not username:
            raise ValueError('Users must have a username')
        if not email:
            raise ValueError('Users must have an email address')

        user = self.model(
            username=username,
            email=self.normalize_email(email),
            created_at=created_at,
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, email, created_at):
        user = self.create_user(username, password, email, created_at)
        user.is_admin = True
        user.save(using=self._db)
        return user

class MyUser(AbstractBaseUser):
    email = models.EmailField(
        verbose_name = 'email address',
        max_length = 255,
        unique = True,
        )

    username = models.CharField(
        max_length = 100,
        unique = True,
        db_index = True,
        )

    created_at = models.DateField()

    is_active = models.BooleanField(default = True)
    is_admin = models.BooleanField(default = False)

    objects = MyUserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email', 'created_at']

    def get_full_name(self):
        return self.email

    def get_short_name(self):
        return self.username

    def __unicode__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    @property
    def is_staff(self):
        return self.is_admin

rawDescription: django can't create superuser

description: Django can't create superuser


code:
with open("input.txt") as inf:
    try:
        while True:
            latin = inf.next().strip()
            gloss = inf.next().strip()
            trans = inf.next().strip()
            process(latin, gloss, trans)
            inf.next()    # skip blank line
    except StopIteration:
        # reached end of file
        pass

rawDescription: Using Python to count morphemes in a file & list them in columns


code: cv_arr = cv.fromarray(mask)

rawDescription: How to create Mask matrix variable for OpenCV minMaxLoc function in Python?

description: Create Mask matrix variable for OpenCV minMaxLoc function in Python


code: pd.pivot_table(df, index=['Col X'], columns=['Col Y'], aggfunc=len, fill_value=0)

rawDescription: Pivot Tables or Group By for Pandas?

description: Pivot Tables or Group By for Pandas


rawDescription: How to test each specific digit or character

description: Test each specific digit or character


rawDescription: Finding minimum values in a list of dicts


code:
from functools import reduce
class Foo(object):
    def __add__(self, other):
        global add_calls
        add_calls += 1
        return Foo()
    def __iadd__(self, other):
        global iadd_calls
        iadd_calls += 1
        return self

a = [Foo() for _ in range(6)]
result = Foo()
add_calls = iadd_calls = 0
reduce(Foo.__iadd__, a, result) is result
add_calls, iadd_calls

rawDescription: Why doesn't python take advantage of __iadd__ for sum and chained operators?


code:
import math
def angle_wrt_x(A,B):
    """Return the angle between B-A and the positive x-axis.
    Values go from 0 to pi in the upper half-plane, and from
    0 to -pi in the lower half-plane.
    """
    ax, ay = A
    bx, by = B
    return math.atan2(by-ay, bx-ax)

def dist(A,B):
    ax, ay = A
    bx, by = B
    return math.hypot(bx-ax, by-ay)

A = (560023.44957588764, 6362057.3904932579)
B = (560036.44957588764, 6362071.8904932579)
theta = angle_wrt_x(A, B)
d = dist(A, B)
print(theta)
print(d)

rawDescription: Python: Does a module exist which already find an angle and the distance between two points?


code: tmp = df.apply(lambda x: pd.DataFrame({'value': x[x > 0]}).reset_index().iloc[0] if not x[x > 0].empty else (x.index[-1], np.nan), axis=1)

rawDescription: Running through appended data frame to locate where the first positive number is in python


code:
def __init__(self, parent=None):
    QWidget.__init__(self, parent)

    edit = QLineEdit("Select & Focus", self)
    edit.selectAll()
    edit.setFocus()             # works now

    vbox = QVBoxLayout()
    vbox.addWidget(edit)
    self.setLayout(vbox)

rawDescription: PyQt4 Give Focus to Widget as it is called by the MainWindow and set as CentralWidget?


code:
match = re.search(r'On +([A-Z]+[a-z]{2}), +([A-Z]+[a-z]{2}) +([1-31]).*?\n', text)
text[match.end():] # Don't forget to check if match is None

rawDescription: Given a list of strings, how to locate position of first string matching substring using RegEx?


code: credentials[username] == password

rawDescription: Python Login Script; Usernames and Passwords in a separate file


code:
def move(var):
    mGridv = var.getM()
    iGridv = var.getI()
    ...

rawDescription: How to get the variable name of a button I have just clicked, tkinter

description: Get the variable name of a button I have just clicked, tkinter


code: axis = PlotAxis(tick_generator = tick_gen)

rawDescription: python chaco axis labels time formatting

description: Python chaco axis labels time formatting


code:
import sys
setattr(sys.modules[__name__], "var_name", value)

rawDescription: What is the pythonic way to setattr() for a module?


code:
V_Ci, tau, V_Cf = symbols('V_Ci, tau, V_Cf')

target = V_Ci*exp(-t/tau) + Heaviside(t)*V_Cf*(1 - exp(-t/tau))

solve([(eqVc.rhs - target).subs(t, ti) for ti in [0, 1, 2]],
      [V_Ci, tau, V_Cf], dict=True)

rawDescription: How to force sympy to extract specific subexpressions?

description: Force sympy to extract specific subexpressions


code: [b for _,b in sorted(zip(L2, L1), reverse=True)][:3]

rawDescription: Python Converting a sorted dictionary to list?


code:
def list(self, request, *args, **kwargs):
    instance = self.filter_queryset(self.get_queryset())
    page = self.paginate_queryset(instance)
    if page is not None:
        serializer = self.get_pagination_serializer(page)
    else:
        serializer = self.get_serializer(instance, many=True)
    return Response(serializer.data)

rawDescription: "get_paginated_response" in django-rest-framework 3.0


code:
if ENVIRONMENT == 'production':
  from production_config import ACCESS_TOKEN
else:
  from development_config import ACCESS_TOKEN

rawDescription: How do I use an access token in modules?

description: Use an access token in modules


code:
dic = {i[0]:i[1] for i in scrabbleScores}
dic["c"]

rawDescription: Letter scores in python

description: Letter scores in python


code:
import stat
print("last accessed => {}".format(time.ctime(st[stat.ST_ATIME])))
# last accessed => Wed Jan  4 14:09:55 2012
print("last modified => {}".format(time.ctime(st[stat.ST_MTIME])))
# last modified => Wed Jan  4 14:19:06 2012
print("last changed => {}".format(time.ctime(st[stat.ST_CTIME])))
# last changed => Wed Jan  4 14:19:06 2012

rawDescription: Print file age in seconds using Python

description: Print file age in seconds using Python


code:
def __new__(self, x, y, gridsize=100):
    return super(Point, self).__new__(self, (x % gridsize, y % gridsize))

rawDescription: python: representing square grid that wraps on itself (cylinder)

description: Python: representing square grid that wraps on itself (cylinder)


code:
bins = np.linspace(0, 10, 25, endpoint=False)
g1 = dfml.groupby([dfml.LEAGUE, dfml.MATCH_DATE.dt.month,
                   pd.cut(dfml.MATCH_HOME, bins)]).agg({'MATCH_HOME' : 'min',
                                                        'PROFIT': sum,
                                                        'PROFIT_2': sum,
                                                        'TOTAL': sum
                                                       })
g1[g1['TOTAL'] > 0]

rawDescription: GroupBy in pandas divided by date range

description: GroupBy in pandas divided by date range


rawDescription: Suggestions for parsing these data and rounding numbers


rawDescription: Newbie Q about Scrapy pipeline.py

description: Newbie Q about Scrapy pipeline.py


code:
def replace_runs_of_whitespace_with_hyphen(word):
    return '-'.join(word.split())

hyphrases = [replace_runs_of_whitespace_with_hyphen(w) for w in phrases]

rawDescription: Inserting hyphens in python strings

description: Inserting hyphens in python strings


code:
#!/usr/bin/env python3.2

# BEGIN DEBUG
def _strip_debug():
    """
    Generates an optimized version of its own code stripping off all debugging
    code.

    """
    import os
    import re
    import shutil
    import sys
    import tempfile
    begin_debug = re.compile("^\s*#+\s*BEGIN\s+DEBUG\s*$")
    end_debug = re.compile("^\s*#+\s*END\s+DEBUG\s*$")
    tmp = None
    debug = False
    try:
        tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False)
        with open(sys.argv[0]) as my_code:
            for line in my_code:
                if begin_debug.match(line):
                    debug = True
                    continue
                elif end_debug.match(line):
                    debug = False
                    continue
                else:
                    if not debug:
                        tmp.write(line)
        tmp.close()
        shutil.copy(tmp.name, sys.argv[0])
    finally:
        os.unlink(tmp.name)
# END DEBUG

def foo(bar, baz):
    """
    Do something weired with bar and baz.

    """
    # BEGIN DEBUG
    if DEBUG:
        print("bar = {}".format(bar))
        print("baz = {}".format(baz))
    # END DEBUG
    return bar + baz

# BEGIN DEBUG
if __name__ == "__main__":
    _strip_debug()
# END DEBUG

rawDescription: How to prevent a part of arbitrary code to be compiled in Python?

description: Prevent a part of arbitrary code to be compiled in Python


code:
from nltk import word_tokenize, pos_tag, RegexpParser
text = "This has allowed the device to start, and I then see glitches which is not nice."
tagged_text = pos_tag(word_tokenize(text))
g = r"""
VP: {<VB.*><DT><NN.*>}
"""
p = RegexpParser(g); p.parse(tagged_text)

rawDescription: NLTK RegEx Chunker not capturing defined grammar patterns with wildcards


code:
list(root)
root[1]

rawDescription: Creating XML-child's from a list

description: Creating XML-child's from a list


code: H[0][1]  # 0 - "a" array; 1 - row with index 1 in "a"

rawDescription: Accessing rows of an array, inside an array of arrays?


code:
import urllib2
import json
from pprint import pprint
response = urllib2.urlopen('http://census.soe.com/get/ps2:v2/weapon_datasheet?c:start=0&c:limit=1&c:show=capacity,clip_size,damage,fire_rate_ms,item_id,reload_ms')
response1 = urllib2.urlopen('http://census.soe.com/get/ps2:v2/item?c:start=0&c:limit=1&c:show=name.en,description.en,item_id')
data = json.load(response)
data1 = json.load(response1)
class Weapon(object):
    """Creates a PlanetSide2 Weapon"""
    def __init__(self, capacity, clip_size, damage, fire_rate_ms, item_id,
                 reload_ms, description, name):
        self.capacity = capacity
        self.clip_size = clip_size
        self.damage = damage
        self.fire_rate_ms = fire_rate_ms
        self.item_id = item_id
        self.reload_ms = reload_ms
        self.description = description
        self.name = name

name = data1['item_list'][0]['name']['en']
description = data1['item_list'][0]['description']['en']
mag_cutter = Weapon(name=name, description=description,
                    **data['weapon_datasheet_list'][0])
pprint(vars(mag_cutter))

rawDescription: Use Json data to initialize an object in python?


code:
class DecorMethod(object):
    def __init__(self, decor, instance):
        self.decor = decor
        self.instance = instance

    def __call__(self, *args, **kw):
        return self.decor(instance, *args, **kw)

    def __getattr__(self, name):
        return getattr(self.decor, name)

    def __repr__(self):
        return '<bound method {} of {}>'.format(self.decor, type(self))

rawDescription: Callable object decorator applied to method doesn't get self argument on input


rawDescription: When does a passed class instance require an import in python


code:
#!/usr/bin/env python

from socket import socket, AF_UNIX, SOCK_STREAM, SOL_SOCKET

SO_PASSCRED = 16 # Pulled from /usr/include/asm-generic/socket.h

s = socket(AF_UNIX, SOCK_STREAM)

s.setsockopt(SOL_SOCKET, SO_PASSCRED, 1)

s.connect('/tmp/pass_cred')

s.close()

rawDescription: Unix socket credential passing in Python


code:
class People:
    pass

type(People)

isinstance(People, object)

rawDescription: Are class names objects in python?

description: Are class names objects in python


code:
name = 'Mark Smith'
age = 25
gender = 'Male'
contacts[name] = [age, gender]
contacts

rawDescription: Defining a variable with pre-entered information


code:
for root, dirs, files in os.walk(top_level_folder):
    if root.lower().endswith("inbox") or root.lower().endswith("sent"):
        for fn in files:
            with open(os.path.join(root, fn), 'r') as f:
                pass  # do something

rawDescription: Only enumerate files in folders with specific names


code:
def instanceVariables(func):
    def returnFunc(*args, **kwargs):
        selfVar = args[0]

        argSpec = inspect.getargspec(func)
        argumentNames = argSpec[0][1:]
        defaults = argSpec[3]
        if defaults is not None:
            defaultArgDict = dict(zip(reversed(argumentNames), reversed(defaults)))
            selfVar.__dict__.update(defaultArgDict)

        argDict = dict(zip(argumentNames, args[1:]))
        selfVar.__dict__.update(argDict)

        validKeywords = set(kwargs) & set(argumentNames)
        kwargDict = {k: kwargs[k] for k in validKeywords}
        selfVar.__dict__.update(kwargDict)

        func(*args, **kwargs)

    return returnFunc

rawDescription: Python decorator to automatically define __init__ variables


code:
if form.is_valid():
    project = form.save()
    next = 'project_new_step2'
    if project.requires_swedish_setup():
        next = 'project_new_se'
    next_url = reverse(next, kwargs={'project_id': project.id})
    return HttpResponseRedirect(next_url)

rawDescription: Django: How do I access post data and match with a criteria


code:
#! /usr/bin/env python3.5
# defineterm.py

import requests
from bs4 import BeautifulSoup
import sys
import html
import codecs

searchterm = ' '.join(sys.argv[1:])

url = 'https://www.google.com/search?q=define+' + searchterm
res = requests.get(url)
try:
    res.raise_for_status()
except Exception as exc:
    print('error while loading page occured: ' + str(exc))

text = html.unescape(res.text)
soup = BeautifulSoup(text, 'lxml')
prettytext = soup.prettify()

#next lines are for analysis (saving raw page), you can comment them
frawpage = codecs.open('rawpage.txt', 'w', 'utf-8')
frawpage.write(prettytext)
frawpage.close()

firsttag = soup.find('h3', class_="r")
if firsttag != None:
    print(firsttag.getText())
    print()

#second tag may be changed, so check it if not returns correct result. That might be situation for all searched tags.
secondtag = soup.find('div', {'style': 'color:#666;padding:5px 0'})
if secondtag != None:
    print(secondtag.getText())
    print()

termtags = soup.findAll("li", {"style" : "list-style-type:decimal"})

count = 0
for tag in termtags:
    count += 1
    print( str(count)+'. ' + tag.getText())
    print()

rawDescription: How can I get the contents of the "feedback" box from Google searches?

description: Get the contents of the "feedback" box from Google searches


rawDescription: Blurring images containing text using Python Imaging Library


code: [('station1_140208.txt', 'Saturday, February 08, 2014'), ('station1_1402010.txt', 'Saturday, February 10, 2014'), ('station1_1402012.txt', 'Saturday, February 12, 2014')]

rawDescription: Python Regex to extract relative href links


code: [PyQt5.QtCore.QByteArray(b'bmp'), PyQt5.QtCore.QByteArray(b'ico'), PyQt5.QtCore.QByteArray(b'jpeg'), PyQt5.QtCore.QByteArray(b'jpg'), PyQt5.QtCore.QByteArray(b'pbm'), PyQt5.QtCore.QByteArray(b'pgm'), PyQt5.QtCore.QByteArray(b'png'), PyQt5.QtCore.QByteArray(b'ppm'), PyQt5.QtCore.QByteArray(b'tif'), PyQt5.QtCore.QByteArray(b'tiff'), PyQt5.QtCore.QByteArray(b'wbmp'), PyQt5.QtCore.QByteArray(b'xbm'), PyQt5.QtCore.QByteArray(b'xpm')]

rawDescription: How to save Qimage with 'jpeg' format in PyQt?

description: Save Qimage with 'jpeg' format in PyQt


code:
import random
random.shuffle(listOfItems)
for singleSelectedItem in listOfItems:
    blahblah

rawDescription: Python - run through a loop in non linear fashion


code:
slist =[]
for x in series:
    slist.extend(x)

rawDescription: Pandas Series of lists to one series

description: Pandas Series of lists to one series


code:
import urllib2

req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()

rawDescription: Python equivalent of Curl HTTP post

description: Python equivalent of Curl HTTP post


code:
y_min, y_max = ax.get_ylim()
ticks = [(tick - y_min)/(y_max - y_min) for tick in ax.get_yticks()]

rawDescription: matplotlib get axis-relative tick positions

description: Matplotlib get axis-relative tick positions


code: query = "update myTable set %(column)s = %%s where ID = %%s" % dict(column = column)

rawDescription: What is the best escape character strategy for Python/MySQL combo?


code:
index_map = {}
for index, value in enumerate(list_1):
    index_map.setdefault(value, []).append(index+1)

rawDescription: make new python lists with indexes from items in a single list

description: Make new python lists with indexes from items in a single list


rawDescription: get absolute path from one absolute and one relative

description: Get absolute path from one absolute and one relative


rawDescription: Namedtuple in Numpy

description: Namedtuple in Numpy