code:
temp_dict= {
    "2010": [2, 3, 4, 5, 7, 3, 20, 29, 34, 2, 10, 1],
    "2011": [2, 7, 4, 5, 9, 3, 20, 9, 34, 2, 10, 10]
}

# Find the highest temp of all years
ath = max([ max(v) for v in temp_dict.values()])

for key in temp_dict:
    # Output Year
    print("Year{k}:".format(k=key))
    x=0
    # Find max
    max_value = max(temp_dict[key])
    for temps in temp_dict[key]:
        # Output Month
        x=x+1
        s = "Month {x}:{v:3d}".format(x=str(x), v=temps)
        # Tag the max value
        if max_value == temps:
            s += "(YearHighest)"
        if ath == temps:
            s += "(ATH)"
        print(s)
    print()

rawDescription: Find max values in a dict containing lists


code:
def gen_user():
  return {"name":"foo", "age":22}

userdata = {"data": [gen_user() for i in xrange(0,5)]}

# or fill separated from declaration so you can fill later
userdata ={"data":None} # None: not initialized
userdata["data"]=[gen_user() for i in xrange(0,5)]

rawDescription: Python | How to create dynamic and expandable dictionaries


code:
def getdict(struct):
    result = {}
    for field, _ in struct._fields_:
         value = getattr(struct, field)
         # if the type is not a primitive and it evaluates to False ...
         if (type(value) not in [int, long, float, bool]) and not bool(value):
             # it's a null pointer
             value = None
         elif hasattr(value, "_length_") and hasattr(value, "_type_"):
             # Probably an array
             value = list(value)
         elif hasattr(value, "_fields_"):
             # Probably another struct
             value = getdict(value)
         result[field] = value
    return result

rawDescription: Python: Can we convert a ctypes structure to a dictionary?


code:
def get(self, name=None):
    if name is None:
        """deal with the /rest/users case"""
    else:
        # deal with the /rest/users/(.*) case
        self.response.out.write('Hello '+ name+'!')

rawDescription: Rest Web Service with App Engine and Webapp


code:
copy = list(depth_list)
print(construct(copy))

rawDescription: Mirroring List with Depth Values, to Nested List ~ Python


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import nltk
from nltk.collocations import *
import codecs
line = ""
open_file = codecs.open('s.txt', 'r', encoding='utf-8').read()
for val in open_file:
    line += val.lower()
tokens = line.split()

bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(tokens)
finder.apply_freq_filter(1)
a = finder.ngram_fd.viewitems()
for i, j in a:
  print("{0} {1} {2}".format(i[0], i[1], j))

rawDescription: finding bigrams in unicode text with nltk

description: Finding bigrams in unicode text with nltk


code:
import re
s = "I love #stackoverflow because #people are very #helpful!"
re.findall(r"#(\w+)", s)

rawDescription: Parsing a tweet to extract hashtags into an array in Python


code:
not_found = not (letter.lower() in word)
not_guessed = not (letter.lower() in guessed_letters)
new_letter = not_found or not_guessed
not_space = letter != ' '
result = new_letter and not_space

rawDescription: if statement syntax - different than taught

description: If statement syntax - different than taught


code:
import networkx as nx

S = nx.DiGraph()#S-sample graph
S.add_nodes_from([0, 1, 2])
S.add_edge(0, 2)
S.add_edge(1, 2)

R = nx.DiGraph()#R-reference graph
R.add_nodes_from([0, 1, 2])
R.add_edge(1, 2)

def difference(S, R):
    DIF = nx.create_empty_copy(R)
    DIF.name = "Difference of (%s and %s)" % (S.name, R.name)
    if set(S) != set(R):
        raise nx.NetworkXError("Node sets of graphs is not equal")

    r_edges = set(R.edges_iter())
    s_edges = set(S.edges_iter())

    # I'm not sure what the goal is: the difference, or the edges that are in R but not in S
    # In case it is the difference:
    diff_edges = r_edges.symmetric_difference(s_edges)

    # In case its the edges that are in R but not in S:
    # diff_edges = r_edges - s_edges

    DIF.add_edges_from(diff_edges)

    return DIF

print(difference(S, R).edges())

rawDescription: Computing the Difference between two graphs 'edge wise' in networkx


code:
EPOCH_DATETIME = datetime.datetime(1970,1,1)
SECONDS_PER_DAY = 24*60*60

def utc_to_local_datetime( utc_datetime ):
    delta = utc_datetime - EPOCH_DATETIME
    utc_epoch = SECONDS_PER_DAY * delta.days + delta.seconds
    time_struct = time.localtime( utc_epoch )
    dt_args = time_struct[:6] + (delta.microseconds,)
    return datetime.datetime( *dt_args )

rawDescription: How to convert a python utc datetime to a local datetime using only python standard library?

description: Convert a python utc datetime to a local datetime using only python standard library


code:
import csv

with open('sample.txt','rb') as tsvin, open('new.csv', 'wb') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in xrange(count)])

rawDescription: reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

description: Reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)


code: rList=gList=bList=[]

rawDescription: Why are my lists not being created properly in Python 2.7?


rawDescription: How to make json decimal round to three digits

description: Make json decimal round to three digits


code:
SCREEN_SIZE = SCREEN_WIDTH, SCREEN_HEIGHT = 800, 600
BACKGROUND_COLOR = pygame.Color("white")
SCREEN_COLOR = BACKGROUND_COLOR

rawDescription: why I'm getting a square instead of a circle in pygame?

description: Why I'm getting a square instead of a circle in pygame


code:
import re
re.sub("^or", "*", "organization")

rawDescription: regular expression pattern about word boundary in python

description: Regular expression pattern about word boundary in python


code:
lst = sorted(itertools.chain(list_a,list_b), key=lambda x:x['user__id'])
list_c = []
for k,v in itertools.groupby(lst, key=lambda x:x['user__id']):
    d = {}
    for dct in v:
        d.update(dct)
    list_c.append(d)
    #could also do:
    #list_c.append( dict(itertools.chain.from_iterable(dct.items() for dct in v)) )
    #although that might be a little harder to read.

rawDescription: Merge/join lists of dictionaries based on a common value in Python


rawDescription: rounding-up numbers within a tuple

description: Rounding-up numbers within a tuple


code:
def write_json(entry):
    with open("Dota2data.txt","r") as infile:
        for member in entry.players:
            current_players = current_players.append(member['account_id'])
        data = json.load(infile)
        infile.close
        data['matches'].append({'match':entry.match_id, 'winner':entry.radiant_win, 'players':current_players})
        with open("Dota2data.txt","w") as outfile:
            json.dump(data, outfile)
            outfile.close()

rawDescription: Is there an easy way to edit a json file with python


rawDescription: Cleanest way to return a tuple containing a particular element?


code: zf.write('foo/bar', 'bar') # save foo/bar as bar

rawDescription: How to make SCons not include the base dir in zip files?

description: Make SCons not include the base dir in zip files


code:
zmin = Z1.min()
zmax=Z1.max()
levels=linspace(zmin, zmax, 400)

rawDescription: smoothing outer edges in matplotlib

description: Smoothing outer edges in matplotlib


code: all(not X for X in dict.itervalues())

rawDescription: Quick and easy way to check if all items in a dictionary are empty strings?


code:
a = np.arange(12).reshape(3,4)
b = a.T
b.shape = (12,)

rawDescription: Block mean of numpy 2D array

description: Block mean of numpy 2D array


code:
data = [(datetime.datetime(2013,10,10), datetime.datetime(2013,10,16)),
(datetime.datetime(2013,10,17), datetime.datetime(2013,10,24)),
(datetime.datetime(2013,10,24), datetime.datetime(2013,11,1))
]

rawDescription: How to get gap between dates?

description: Get gap between dates


code:
from django.core.exceptions import ValidationError

def validate_current_century(value):
    if value < 2000 or value > 2100:
        raise ValidationError(u'%s is not a valid year!' % value)

rawDescription: How to restrict user to select date between range of years in django?

description: Restrict user to select date between range of years in django


code:
from matplotlib import pyplot as plt

def ecdf(x):
    vals, counts = np.unique(x, return_counts=True)
    ecdf = np.cumsum(counts).astype(np.float64)
    ecdf /= ecdf[-1]
    return vals, ecdf

x1, y1 = ecdf(img.ravel())
x2, y2 = ecdf(normed.ravel())

fig = plt.figure()
gs = plt.GridSpec(2, 2)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[0, 1], sharex=ax1, sharey=ax1)
ax3 = fig.add_subplot(gs[1, :])
for aa in (ax1, ax2):
    aa.set_axis_off()

ax1.imshow(img, cmap=plt.cm.gray)
ax1.set_title('Original')
ax2.imshow(normed, cmap=plt.cm.gray)
ax2.set_title('Normalised')

ax3.plot(x1, y1 * 100, lw=2, label='Original')
ax3.plot(x2, y2 * 100, lw=2, label='Normalised')
for xx in bin_edges:
    ax3.axvline(xx, ls='--', c='k')
for yy in quantiles:
    ax3.axhline(yy * 100., ls='--', c='k')
ax3.set_xlim(bin_edges[0], bin_edges[-1])
ax3.set_xlabel('Pixel value')
ax3.set_ylabel('Cumulative %')
ax3.legend(loc=2)

rawDescription: How can I transform the histograms of grayscale images to enforce a particular ratio of highlights/midtones/shadows?

description: Transform the histograms of grayscale images to enforce a particular ratio of highlights/midtones/shadows


code:
def get_next_line(file_name):
    with open(file_name) as f:
        for line in f:
            yield line.strip()

rawDescription: Reading from a file: find the new line

description: Reading from a file: find the new line


code:
a, b, c = bytearray('abcd'), bytearray('abcd'), bytearray('abzd')
a_buf, b_buf, c_buf = buffer(a), buffer(b), buffer(c)
d = {b_buf:1, c_buf:2}
b[2] = 'z'
d[a_buf] = 0

rawDescription: Python quickly hash mutable object

description: Python quickly hash mutable object


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, title='wx.Notebook')
        # create a wx.Notebook
        book = wx.Notebook(self)
        # create a new page; wx.Notebook owns the page
        # therefore the notebook must be the parent window
        page = MyPage(parent=book)
        # add the page to the notebook:
        book.AddPage(page, 'Page 1')
        book.AddPage(MyPage(book),'Page 2')
        book.AddPage(MyPage(book),'Page 3')

class MyPage(wx.Panel):
    "a page for wx.Notebook"
    def __init__(self, parent):
        # NOTE: wxPython 2.9.4/winXP may create graphic
        # artifacts when more than one page is added. This can
        # be avoided by creating the page with a size of (0,0).
        # the reason for this is: the page (here a panel) is
        # created with the default size and position (upper
        # left corner). Once the layout is applied, the page
        # is moved to the proper coordinates. However, the
        # wx.Notebook is not redrawn so it will leave a black
        # spot where the page was moved away from. Alternatively,
        # the frame or notebook can be Refresh()ed after the
        # frame is shown.
        wx.Panel.__init__(self, parent, size=(0,0))
        # create sizer to add a border
        pageSizer = wx.BoxSizer(wx.VERTICAL)
        # create a grid sizer for the content
        self.grid = wx.GridSizer(0, 4, 5, 5)
        # add the grid sizer to the page sizer:
        # to allow the grid to fill the entire page,
        # set proportion>0 and add the wx.EXPAND flag.
        # the border of 10 is the spacing between the
        # page and the cells of the grid
        pageSizer.Add(self.grid, 1, wx.EXPAND|wx.ALL, 10)
        # set the main sizer:
        self.SetSizer(pageSizer)
        # add content to the grid
        self.GenerateContent()
        # DEMO: click any white space on the page to
        # generate new content
        self.Bind(wx.EVT_LEFT_DOWN, self.GenerateContent)

    def GenerateContent(self, event=None):
        "dynamically create page content"
        # remove all items from the grid and destroy them
        # NOTE: if you don't actually create new controls here,
        # but use a list of controls created elsewhere (like in
        # in your code), do not delete the items! Use:
        # deleteWindows=False instead.
        self.grid.Clear(deleteWindows=True)
        # generate new grid content
        for i in range(10):
            # the contents are owned by the page,
            # therefore the page must be the parent window:
            # NOTE: size=(0,0) here is not required but
            # eliminates a briefly shown graphic artifact
            cell = wx.Panel(self, size=(0,0))
            cell.SetBackgroundColour(self.NewColor())
            # add the content (cells) to the grid:
            # specify the wx.EXPAND flag to fit the
            # content to the grid cell
            self.grid.Add(cell, flag=wx.EXPAND)
        # DEMO: hint text
        self.grid.Add(wx.StaticText(self, label=
            'Click empty cell to update content ->'),
                      flag=wx.EXPAND)
        # recalculate the layout to move the new contents
        # of the grid sizer into place
        self.Layout()

    col = 0 # DEMO: coloring
    def NewColor(self):
        self.col = (self.col + 3) % 241
        return wx.Colour(0, self.col * 10 % 255, self.col % 255)

app = wx.App(False)
MyFrame().Show()
app.MainLoop()

rawDescription: wxpython Gridsizer not fitting to panel

description: Wxpython Gridsizer not fitting to panel


code: u'R\xfacola'

rawDescription: python :same character, different behavior

description: Python :same character, different behavior


rawDescription: nested classes in Python

description: Nested classes in Python


code:
def func(x,y):
   if y == 0:
       return 0
   else:
       return x + func(x,y-1)

func(3,4)
func(3,0)

rawDescription: Could anyone show me how the recursive part of this function works?


rawDescription: Is there a method that tells my program to quit?


rawDescription: Pandas group by time windows

description: Pandas group by time windows


rawDescription: How to assign scipy.sparse matrix to NumPy array via indexing?

description: Assign scipy.sparse matrix to NumPy array via indexing


code: pd.rolling_mean(df.T, 3).shift(-2).T

rawDescription: Mean in group of columns

description: Mean in group of columns


code: exit

rawDescription: exit from ipython

description: Exit from ipython


code:
odds = set()
for i in B:
    if i in odds:
        odds.remove(i)
    else:
        odds.add(i)

rawDescription: How to check if a sequence could be turned into a palindrome

description: Check if a sequence could be turned into a palindrome


code:
def movie():
    movies_list = [movie.strip() for movie in movies_list]
    movie_explorer()
    return movies_list

def rand(movies_list):
    rand_item = print(random.choice(movies_list))

rawDescription: Using name of strings in different functions


rawDescription: Custom sorting in pandas dataframe

description: Custom sorting in pandas dataframe


code:
def helper(x):
    x = x.reset_index()
    x = x.groupby(x['measurement'].div(3)).mean()
    del x['measurement']
    return x

df.groupby(level=0).apply(helper)

rawDescription: Resample Pandas Dataframe with "bin size"/"frequency"


code: doc.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1))

rawDescription: How to change background of textview in pygobject "gtk3"?

description: Change background of textview in pygobject "gtk3"


code:
import json

with open('output_filename.json', 'w', encoding='utf8') as output:
    json.dump(python_object, output)

rawDescription: How do I make a JSON file out of a list in Python?

description: Make a JSON file out of a list in Python


code:
from test import foo
foo.__globals__

rawDescription: How does from ... import ... statement import global variables


code:
c = 0
emptylist = [""] * len(verbs)

rawDescription: Writing to a specific cell in csv using python


code:
import time
tz = "+10:00"
tz_toconvert = tz[:3] + tz[4:]
tz_struct_time = time.strptime(tz_toconvert, "%z")

rawDescription: Is there a wildcard format directive for strptime?


code:
class Test(objet):

    def __init__(self, x):

        self.x = x

    def show(self):

        print(self.x)

class Foo(object):
     pass

rawDescription: Is there a IPython notebook api?

description: Is there a IPython notebook api


code:
from bs4 import BeautifulSoup
from urllib2 import urlopen

BASE_URL = "http://www.chicagoreader.com"

def get_category_links(section_url):
    # Put the stuff you see when using Inspect Element in a variable called html.
    html = urlopen(section_url).read()
    # Parse the stuff.
    soup = BeautifulSoup(html, "lxml")
    # The next two lines will change depending on what you're looking for. This
    # line is looking for <dl class="boccat">.
    boccat = soup.find("dl", "boccat")
    # This line organizes what is found in the above line into a list of
    # hrefs (i.e. links).
    category_links = [BASE_URL + dd.a["href"] for dd in boccat.findAll("dd")]
    return category_links

rawDescription: Get the code from inspect element using Python


code:
from datetime import datetime
t = Template('It is {{ dt | date:"l" }} today.')
c = Context({'dt': datetime.today()})
t.render(c)

rawDescription: How can I make django output the day of the week? both in views an in templates

description: Make django output the day of the week? both in views an in templates


code: foo(l)

rawDescription: Passing method to a function in Python

description: Passing method to a function in Python


code:
def save(self, **kwargs):
    # Will be done on every save
    kwargs['last_changed'] = timezone.now()
    return super().save(**kwargs)

def create(self, instance, data):
    # Will only be done if a new object is being created
    data['initial_creation'] = timezone.now()
    return super().create(instance, data)

rawDescription: When are create and update called in djangorestframework serializer?


code:
class A(object):pass

class B(A):pass

class C(A): pass

A.__subclasses__()

rawDescription: Calling class method as part of initialization


code:
import requests
from bs4 import BeautifulSoup

url = "https://patentscope.wipo.int/search/en/search.jsf"

data = {"simpleSearchSearchForm": "simpleSearchSearchForm",
        "simpleSearchSearchForm:j_idt341": "EN_ALLTXT",
        "simpleSearchSearchForm:fpSearch": "automata",
        "simpleSearchSearchForm:commandSimpleFPSearch": "Search",
        "simpleSearchSearchForm:j_idt406": "workaround"}
head = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36"}

with requests.Session() as s:
    # Get the cookies and the source to parse the Viewstate token
    init = s.get(url)
    soup = BeautifulSoup(init.text, "lxml")
    val = soup.select_one("#j_id1:javax.faces.ViewState:0")["value"]
    # update post data dict
    data["javax.faces.ViewState"] = val
    r = s.post(url, data=data, headers=head)
    print(r.text)

rawDescription: Python urllib2 or requests post method

description: Python urllib2 or requests post method


code:
def func(kw=None):
    print('kw:', kw)
func(kw=1)
func(1)  # Do not need the name in this case.
def func(*, kwonly=None):
    print('kwonly:', kwonly)
func(kwonly=1)
func(1)  # Always need the name with keyword-only arguments.

rawDescription: Python inspect module: keyword only args


code:
M = sparse.rand(10,10,.1,format='csr')
M
M.data
M.indices
M.indptr

rawDescription: Efficiently select random non-zero column from each row of sparse matrix in scipy


code: from .. import mypackage

rawDescription: Scripts in python package

description: Scripts in python package


code:
from xlutils.filter import process,XLRDReader,XLWTWriter

#
# suggested patch by John Machin
# http://stackoverflow.com/a/5285650/2363712
#
def copy2(wb):
    w = XLWTWriter()
    process(
        XLRDReader(wb,'unknown.xls'),
        w
        )
    return w.output[0][1], w.style_list

rawDescription: Issues in preserving Excel formatting with Python's xlrd and xlutils


code: original_list[0][0][0][1].append(x)  # 2nd of 1st of 1st of 1st.

rawDescription: Inserting list into list containing multiple list


code:
axes([0,0,0.7,0.6]) # add an axes with the position and size specified by
                    # [left, bottom, width, height] in normalized units.

rawDescription: Change resolution of imshow in ipython

description: Change resolution of imshow in ipython


code: li = [line[1:-1].split() for line in file]

rawDescription: parsing a file into a list of lists

description: Parsing a file into a list of lists


code:
subprocess.call(["set", "TEST_VAR=Hello World"], shell=True)
subprocess.call(["set", "TEST_VAR"], shell=True)
subprocess.call(["echo", "%TEST_VAR%"], shell=True)

rawDescription: Running three commands in the same process with Python


rawDescription: Numpy: use dtype from genfromtxt() when exporting with savetxt()


code:
axis=1
m_swapped=m.swapaxes(axis,-1)
print(m_swapped.shape)
# (2, 4, 3)

rawDescription: Iterate across arbitrary dimension in numpy


code:
bool(3), bool(5)
bool(0)

rawDescription: Make a new sublist of preceding characters every time there's a zero in a list, excluding the zero


code:
plt.figure(1)
ax = plt.subplot(111)
#... do your stuff
#need to figure out your image size divided by the number of labels you want
#FOR EXample, if image size was 180, and you wanted every second coordinate labeled:
ax.set_xticks([i for i in range(0,180,2)]) #python3 code to create 90 tick marks
ax.set_xticklabels([-i for i in range(-90,90,2)]) #python3 code to create 90 labels
#DO SAME FOR Y

rawDescription: Change axis range into latitude and longitude using matplotlib in python


code:
users = active_users().filter(lambda user: user.name.startswith('A')) \
                      .order_by(User.name)[:10]

rawDescription: Writing select functions for customized Pony


code:
import os

filename = os.path.abspath(filename)

rawDescription: Getting the current path from where a module is being called


code:
from __future__ import print_function
from struct import pack, unpack

def ulong_to_long_pack(u):
    ''' using pack & unpack '''
    ubytes = pack('L', u)
    return unpack('l', ubytes)[0]

def ulong_to_long_sub(u):
    ''' using subtraction '''
    return u - (1<<32) if u >= (1<<31) else u

def ulong_to_long2_xor(u):
    ''' using exclusive OR '''
    return u ^ ~((1<<32)-1) if u & (1<<31) else u

funcs = (ulong_to_long_pack, ulong_to_long_sub, ulong_to_long2_xor)

# test
for ulong_to_long in funcs:
    print(ulong_to_long.__doc__)

    u = 2600468480
    print(u, ulong_to_long(u))

    big = 1<<31
    for u in range(big - 3, big + 3):
        print(u, ulong_to_long(u))

    print()

rawDescription: Why does bit-wise shift left return different results in Python and Java?


code:
import mpmath
mpmath.mp.dps = 50
nsum(lambda x: exp(-x**2), [-inf, inf])
mpmath.jtheta(3, 0, 1/exp(1))

rawDescription: How to perform infinite sum numerically in python

description: Perform infinite sum numerically in python


code:
i = 0
f = lambda: i

rawDescription: Python: lambda function behavior with and without keyword arguments?


code:
def quantiles_by_row(df):
    """ Reconstruct a DataFrame of expanding quantiles by row """

    # Construct skeleton of DataFrame what we'll fill with quantile values
    quantile_df = pd.DataFrame(np.NaN, index=df.index, columns=df.columns)

    # Pre-allocate numpy array. We only want to keep the non-NaN values from our DataFrame
    num_valid = np.sum(~np.isnan(df.values))
    sorted_array = np.empty(num_valid)

    # We want to maintain that sorted_array[:length] has data and is sorted
    length = 0

    # Iterates over ndarray rows
    for i, row_array in enumerate(df.values):

        # Extract non-NaN numpy array from row
        row_is_nan = np.isnan(row_array)
        add_array = row_array[~row_is_nan]

        # Add new data to our sorted_array and sort.
        new_length = length + len(add_array)
        sorted_array[length:new_length] = add_array
        length = new_length
        sorted_array[:length].sort(kind="mergesort")

        # Query the relative positions, divide by length to get quantiles
        quantile_row = np.searchsorted(sorted_array[:length], add_array, side="left").astype(np.float) / length

        # Insert values into quantile_df
        quantile_df.iloc[i][~row_is_nan] = quantile_row

    return quantile_df

rawDescription: Pandas - expanding inverse quantile function


code:
array1 = ["a", "b", "c", "d"]
array2 = [0, 1, 1, 0]
[array1[index] for index, val in enumerate(array2) if val == 1] # Or if val

rawDescription: python numpy.where function for lists

description: Python numpy.where function for lists


code:
def __key(self):
    return tuple(v for k, v in sorted(self.__dict__.items()))

rawDescription: Automatically making a class hashable

description: Automatically making a class hashable


code:
def xslice(arr, slices):
    return sum((arr[s] if isinstance(s, slice) else [arr[s]] for s in slices), [])
xslice(range(10), s_[0, 3:5, 6::3])
Out[1]: [0, 3, 4, 6, 9]

rawDescription: Python: shorter syntax for slices with gaps?


code:
rng = pd.date_range('1/1/2012', periods=10, freq='Min')
df = pd.DataFrame({'Data':np.random.randint(0, 500, len(rng))}, index=rng)
df
df['Data'].resample('5Min')

rawDescription: averaging every five minutes data as one datapoint in pandas dataframe

description: Averaging every five minutes data as one datapoint in pandas dataframe


code:
def interp_1(x, y, z) :
    rows, cols = x.shape
    out = np.empty((rows,) + z.shape, dtype=y.dtype)
    for j in xrange(rows) :
        out[j] =interp1d(x[j], y[j], kind='linear', copy=False)(z)
    return out

def interp_2(x, y, z) :
    rows, cols = x.shape
    row_idx = np.arange(rows).reshape((rows,) + (1,) * z.ndim)
    col_idx = np.argmax(x.reshape(x.shape + (1,) * z.ndim) > z, axis=1) - 1
    ret = y[row_idx, col_idx + 1] - y[row_idx, col_idx]
    ret /= x[row_idx, col_idx + 1] - x[row_idx, col_idx]
    ret *= z - x[row_idx, col_idx]
    ret += y[row_idx, col_idx]
    return ret

rawDescription: Scipy Fast 1-D interpolation without any loop


code: draw_chromosome(x, 120, y, "#1C2F4D")

rawDescription: Why is my line clipping in matplotlib?

description: Why is my line clipping in matplotlib


code:
def get_template_names(self):
    return ["shop/%s/offer_list" % self.shop.get_type()]

rawDescription: django ListView specifying variable available for all methods inside the class

description: Django ListView specifying variable available for all methods inside the class


rawDescription: python password rules validation

description: Python password rules validation


code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class ImageView(QGraphicsView):
  def __init__(self, pixmap=None, parent=None):
    '''
    QGraphicsView shows the image
    '''
    super(ImageView, self).__init__(parent)
    self.pixmap = pixmap

class Widget(QWidget):
  def __init__(self, parent=None):
    super(Widget, self).__init__(parent)
    layout = QVBoxLayout(self)
    pic = QPixmap('/home/-----/Pictures/7 Cat Sins - Wrath.jpg')
    grview = ImageView(pic, self)
    layout.addWidget(grview)
    self.setFixedSize(pic.size())

    scene = QGraphicsScene(self)
    scene.addPixmap(pic)

    grview.setScene(scene)
    self.show()

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

  return sys.exit(app.exec_())

if __name__ == '__main__':
  main()

rawDescription: How do I output a colormap in a scene using pyqt?

description: Output a colormap in a scene using pyqt


rawDescription: Setting the fmt option in numpy.savetxt

description: Setting the fmt option in numpy.savetxt


code:
def tables():
   return dict(tables=db().select(db.mytable.ALL))

rawDescription: How can I put an image from DB table in Web2py?

description: Put an image from DB table in Web2py


code:
import sys

a = ["abcdef", "ghijklmnop"]
sys.getsizeof(a)    # => 44 (size of list a in bytes)

rawDescription: More than 3 mb of data for list of list for 1500 records


code: return dict(zip(columns, transpose))

rawDescription: Change List of Tuples into Dictionary (pythonic way)


code:
equivalent("MNU", "ManUtd")
equivalent("MNU", "Arsenal")
equivalent("MNU", "Not a name")

rawDescription: Finding equality between different strings that should be equal


code:
from itertools import combinations

def isSubsetOrDisjointTo(listA, listB):
    return all(item in listB for item in listA) or all(item not in listB for item in listA)

def func(nodesToJoin):
    #flatten list, extracting duplicates
    allNodes = sorted(set(itertools.chain(*nodesToJoin)))

    result = []

    seen = set()

    for length in xrange(max(map(len, nodesToJoin)), 0, -1):
        #start with longest possible, work to shortest
        for sublist in combinations(allNodes, length):
            if any(item in seen for item in sublist):
                #skip possible sublists with options we've already seen in the result
                continue

            if all(isSubsetOrDisjointTo(sublist, node) for node in nodesToJoin):
                result.append(sublist)
                seen.update(sublist)

    return result

rawDescription: How to breakup a list of list in a given way in Python

description: Breakup a list of list in a given way in Python


code: add_result = (user_input_1 + user_input_2)

rawDescription: Issue with my 'very simple' Python Calculator


code:
carIndex = next((0 for _ in (car for car in
cars if "VW" in car.name or "Poodle" in car.name)),-1)

rawDescription: Python: How to re-use list comprehensions after they are created in an expression


rawDescription: Pandas order datafarme column

description: Pandas order datafarme column


rawDescription: Complex Django query

description: Complex Django query


code:
import codecs

...
with codecs.open(name, encoding=encoding) as file:
    found_words = set(w for line in file for w in findwords(line))

rawDescription: Search for words (exact matches) in multiple texts using Python


code: ' '.join(line.split('/', 3)[-1] for line in source.splitlines())

rawDescription: how to write a regex to parse refs/changes

description: Write a regex to parse refs/changes


rawDescription: get adjacent matrix of point in python

description: Get adjacent matrix of point in python


code:
from operator import add

counts = (a.keys()
    .map(lambda x: (x, 1))
    .reduceByKey(add))

duplicates = (counts
    .filter(lambda x:  x[1] >  1)
    .map(lambda x: (x[0], None)))

a.subtractByKey(duplicates)

rawDescription: Spark RDD remove records with multiple keys


code: 'FUTURE' in 'FOOFUTURE'

rawDescription: For loop python multiple checks

description: For loop python multiple checks


code: L = L and L.string

rawDescription: Is there a `?.` operator in Python?

description: Is there a `?.` operator in Python


code:
while True:
    ...

rawDescription: How to restart a python script after it finishes

description: Restart a python script after it finishes


code:
conn = sqlite3.connect(':memory:')
conn.execute('CREATE TABLE foo (bar, baz)')
conn.execute('INSERT INTO foo VALUES (1, 2)')
cursor = conn.cursor()
cursor.execute('UPDATE foo SET baz=3 WHERE bar=2')
cursor.rowcount
cursor.execute('UPDATE foo SET baz=3 WHERE bar=1')
cursor.rowcount

rawDescription: How to tell whether an update statement is successful in pysqlite 2.6.3

description: Tell whether an update statement is successful in pysqlite 2.6.3


code:
s = "\xff\x03"
a = numpy.frombuffer(s, numpy.uint8)

rawDescription: Converting a hexadecimal character to an int in Python


code:
from collections import defaultdict
Null = None
list1 = [(12, "AB"), (12, "AB"), (12, "CD"), (13, Null), (13, "DE"), (13, "DE")]

keys = []
for k,v in list1:
    if k not in keys:
        keys.append(k)

intermediate = defaultdict(list)
for k, v  in list1:
    if v not in intermediate[k]:
        intermediate[k].append(v)

list2 = []
for k in keys:
    list2.append([k] + intermediate[k])

print(list2)

rawDescription: How to create a new list out of an existing list by removing duplicates and shifting values?

description: Create a new list out of an existing list by removing duplicates and shifting values


code:
delta = b - a
print(delta.total_seconds() // 60)

rawDescription: Calculating the time difference between two datetime values in Python


rawDescription: convert data table format in python

description: Convert data table format in python


code:
def rolling_max_dd(x, window_size, min_periods=1):
    """Compute the rolling maximum drawdown of `x`.

    `x` must be a 1d numpy array.
    `min_periods` should satisfy `1 <= min_periods <= window_size`.

    Returns an 1d array with length `len(x) - min_periods + 1`.
    """
    if min_periods < window_size:
        pad = np.empty(window_size - min_periods)
        pad.fill(x[0])
        x = np.concatenate((pad, x))
    y = windowed_view(x, window_size)
    running_max_y = np.maximum.accumulate(y, axis=1)
    dd = y - running_max_y
    return dd.min(axis=1)

rawDescription: Compute *rolling* maximum drawdown of pandas Series


code:
from statistics import mean, stdev
from math import sqrt

# test conditions
c0 = [2, 4, 7, 3, 7, 35, 8, 9]
c1 = [i * 2 for i in c0]

cohens_d = (mean(c0) - mean(c1)) / (sqrt((stdev(c0) ** 2 + stdev(c1) ** 2) / 2))

print(cohens_d)

rawDescription: How to calculate cohen's d in Python?

description: Calculate cohen's d in Python


code: self.fields[group_and_properties.name] = CharField(label = group_and_properties, widget = HTMLWidget())

rawDescription: Dynamic Django form not only with inputs


code:
gaugeWidth = (1/5.0)*self.configSet["width"]
gaugeHeight = (1/10.0)*self.configSet["height"]

rawDescription: wxPython -- BoxSizers not placing things correctly

description: WxPython -- BoxSizers not placing things correctly


code:
AUTH_LDAP_PROFILE_ATTR_MAP = {
    "uid": "uid",
    "cn": "cn",
    "sn": "sn",
    "givenName": "givenName",
    "userPassword": "userPassword",
    "shadowLastChange": "shadowLastChange",
    "shadowMax": "shadowMax",
    "shadowWarning": "shadowWarning",
    "loginShell": "loginShell",
    "uidNumber": "uidNumber",
    "gidNumber": "gidNumber",
    "homeDirectory": "homeDirectory",
    "gecos": "gecos",
    "mail": "mail",
    "l": "l",
    "telephoneNumber": "telephoneNumber",
}
AUTH_PROFILE_MODULE = 'myapp.UserProfile'

rawDescription: django-auth-ldap - Display user information from LDAP in custom view

description: Django-auth-ldap - Display user information from LDAP in custom view


code:
s = set(list_2)
[f for f in list_1 if not f in s]

rawDescription: What is a more efficient way in Python to return list elements which are not in a second list?


rawDescription: Between double curly braces: replace particular text


code:
from fabric.api import (cd, env)
from fabric.operations import get

env.host_string = "127.0.0.1:2222"
env.user = "jfroco"
env.password = "********"

remote_path = "/home/jfroco/development/fabric1"
remote_file = "test.txt"
local_file = "local.txt"

lf = open(local_file, "a")

with cd(remote_path):
    get(remote_file, lf)

lf.close()

rawDescription: Python appending file remotely

description: Python appending file remotely


code:
def run(first, second):
    return [a + b for a, b in zip(first, second)]

rawDescription: Turning this simple block to idiomatic Python code


code:
heap = []            # creates an empty heap
heappush(heap, item) # pushes a new item on the heap
item = heappop(heap) # pops the smallest item from the heap
item = heap[0]       # smallest item on the heap without popping it
heapify(x)           # transforms list into a heap, in-place, in linear time

rawDescription: PriorityQueue is very slow

description: PriorityQueue is very slow


code:
NUM_SAMPLES = 100000
SKEW_PARAMS = [-3, 0]

def skew_norm_pdf(x,e=0,w=1,a=0):
    # adapated from:
    # http://stackoverflow.com/questions/5884768/skew-normal-distribution-in-scipy
    t = (x-e) / w
    return 2.0 * w * stats.norm.pdf(t) * stats.norm.cdf(a*t)

# generate the skew normal PDF for reference:
location = 0.0
scale = 1.0
x = np.linspace(-5,5,100)

plt.subplots(figsize=(12,4))
for alpha_skew in SKEW_PARAMS:
    p = skew_norm_pdf(x,location,scale,alpha_skew)
    # n.b. note that alpha is a parameter that controls skew, but the 'skewness'
    # as measured will be different. see the wikipedia page:
    # https://en.wikipedia.org/wiki/Skew_normal_distribution
    plt.plot(x,p)

rawDescription: generate N random numbers from a skew normal distribution using numpy

description: Generate N random numbers from a skew normal distribution using numpy


rawDescription: How do I lock window resizing in a Python matplotlib window?

description: Lock window resizing in a Python matplotlib window


code:
foo=Foo()
foo.__dict__['a']=a

rawDescription: Automatically setting class member variables in Python


rawDescription: Indexing an array using mac address

description: Indexing an array using mac address


code:
from ctypes import cdll

lib = cdll.LoadLibrary('./libsvmlight_classify.so')
lib.classify()

rawDescription: calling function from linux executable file

description: Calling function from linux executable file


code:
import sys
sys.stdout.encoding

rawDescription: python: unicode in Windows terminal, encoding used?

description: Python: unicode in Windows terminal, encoding used


code:
driver.find_element_by_xpath("//span[contains(text(), 'Select Operator')]").click()
driver.find_element_by_xpath("//span[contains(text(), 'Idea')]/..").click()

rawDescription: Python selenium select option from angular js drop down


code:
#!/usr/bin/env python3

def copyimmut(fromdict, todict):
    for key in fromdict:
        if type(fromdict[key]) is dict and key in todict:
            copyimmut(fromdict[key], todict[key])
        else:
            todict[key] = fromdict[key]

main_dict = {
    'a': {'a1': 1, 'a2': 2},
    'b': {'bb': {'bb1' : 1,'bb2' : 2, }}}

my_b = main_dict['b']
assert(my_b is main_dict['b'])
print(my_b)

new_dict = {
    'a': {'a1': 11, 'a2': 22},
    'b': {'bb': {'bb1' : 11, 'bb2' : 22, }},
    'c': {'cc': {'cc1' : 11, 'cc2' : 22, }}}

copyimmut(new_dict, main_dict)
assert(my_b is main_dict['b'])
print(my_b)
print(main_dict['c'])

rawDescription: Is there a way to update a dictionary without changing any contained mutable types?


rawDescription: Re-order a numpy array python

description: Re-order a numpy array python


code:
x = MyClassFactory.Build("Hello")
MyClassFactory.Counter
MyClassFactory.LastValue
y = MyClassFactory.Build("Goodbye")
MyClassFactory.Counter
MyClassFactory.LastValue
x.Name
y.Name

rawDescription: (Usage of Class Variables) Pythonic - or nasty habit learnt from java?


code: var = '{0} {0} {0}'.format('look_at_meeee')

rawDescription: Output formatting in Python: replacing several %s with the same variable


rawDescription: How to extract a common name from multipal filenames and delete something I don't want

description: Extract a common name from multipal filenames and delete something I don't want


code:
"_".join(re.findall('[A-Z][^A-Z]*', s))
# Some_String_Like_This

rawDescription: python: SomeStingLikeThis to some_string_like_this

description: Python: SomeStingLikeThis to some_string_like_this


code: session['somekey'] = 'foo'

rawDescription: How to use beaker with GAE

description: Use beaker with GAE


code:
# As a method of a Path object
def expanduser(self):
    """ Return a new path with expanded ~ and ~user constructs
    (as returned by os.path.expanduser)
    """
    return self.__class__(os.path.expanduser(str(self)))

rawDescription: Getting Home Directory with pathlib

description: Getting Home Directory with pathlib


code:
if username not in usernames:
    usernames.append(username)
elif username in usernames:
    usernames.append(username_w_surname)

rawDescription: Creating Username from Text File Python

description: Creating Username from Text File Python


code: strptime(s, "%Y-%I-%d %H:%M:%S%z")

rawDescription: Format a timestring in python

description: Format a timestring in python


code:
pts = np.array(pts)  #Skip if pts is a numpy array already
lp = len(pts)
arr = np.zeros((lp,lp,lp,3))
arr[:,:,:,0] = pts[:,None,None]  #None is the same as np.newaxis
arr[:,:,:,1] = pts[None,:,None]
arr[:,:,:,2] = pts[None,None,:]

rawDescription: Constructing a 3D cube of points from a list


rawDescription: Combining generators

description: Combining generators


code:
data = sorted(yourdict.items(),
              key=lambda i: datetime.datetime.strptime(i[0], '%d.%m.%Y'))

rawDescription: Python3: Date strings to chronological order


code: [word for word in [first + second for second in alphabet for first in alphabet] if word in your_dictionary]

rawDescription: How to generate 2 letter words using a function in python?

description: Generate 2 letter words using a function in python


code:
for row in reader:
    match = city_re.search(row[0])
    if match:
        writer.writerow(row)

rawDescription: Faster Approach of Double for loop when iterating large list (18,895 elements)


code:
from gevent import monkey; monkey.patch_all()
import grequests

req = grequests.get('http://localhost:1234')
resp = grequests.map([req])[0]

rawDescription: What could I grep for in strace output from a gevent app to test whether it's using blocking network IO?


code:
def first_true1(a):
    """ return a dict of row: index with value in row > 0 """
    di={}
    for i in range(len(a)):
        idx=np.where(a[i]>0)
        try:
            di[i]=idx[0][0]
        except IndexError:
            di[i]=None

    return di

rawDescription: Finding first non-zero value along axis of a sorted two dimensional numpy array


code:
import easywebdav
pem_path = os.path.expanduser('~/.pki/CA/cacert.pem')
webdav = easywebdav.connect('example.com', username='user', password='pass',
                            protocol='https', port=443,
                            verify_ssl=pem_path)
...

rawDescription: How can I verify my selfsigned certificate when using easywebdav?

description: Verify my selfsigned certificate when using easywebdav


code:
def slice_consc(df,n):

    Acol = np.array(df['A'])
    Acol_ext = np.concatenate(([0],(Acol==0)+0,[0]))

    starts = np.where(np.diff(Acol_ext)==1)[0]
    stops = np.where(np.diff(Acol_ext)==-1)[0]

    id = np.zeros(Acol.size+2,dtype=int)

    valid_mask = stops - starts >= n
    id[stops[valid_mask]] = -1
    id[starts[valid_mask]+2] = 1

    return df[(id.cumsum()==1)[:-2]]

rawDescription: slice pandas df based on n consecutive instances of element

description: Slice pandas df based on n consecutive instances of element


code:
nodeName = "E1_40873886"
nodeName.split("_")[-1].translate(None,ascii_uppercase+"-")
nodeName = "40873886-B"
nodeName.split("_")[-1].translate(None,ascii_uppercase+"-")
nodeName = "40873886"
nodeName.split("_")[-1].translate(None,ascii_uppercase+"-")

rawDescription: Ignore all characters and just read numbers portion from the string


code: spamwriter = csv.writer(csvfile,  delimiter=';',quotechar='|', quoting=csv.QUOTE_MINIMAL)

rawDescription: Python csv writer writing all contents to one cell


code: [[(i, k) for k in re.findall('\((.+?)\)', j)] for i, j in l]

rawDescription: how to make regex go line by line to match two strings at the same time?

description: Make regex go line by line to match two strings at the same time


code: nonzero_values = data[data!=0]

rawDescription: Obtain a subset of 2-D indices using numpy


rawDescription: How to reorder indexed rows based on a list in Pandas data frame

description: Reorder indexed rows based on a list in Pandas data frame


code:
def paintGL(self):
    if not self.isValid():
        return

rawDescription: PyQT5 OpenGL 4.1 Core profile - invalid frame buffer operation - Mac OS


code:
def hash(string):
    x = string[0] << 7
    for chr in string[1:]:
        x = ((1000003 * x) ^ chr) & (1<<32)
    return x

rawDescription: What hash algorithm does Python's dictionary mapping use?


rawDescription: Python Postgres return result when it is none


rawDescription: Python: count the matrix values according to the threshold


rawDescription: Python Reshape 3d array into 2d

description: Python Reshape 3d array into 2d


rawDescription: How can i find next highest value in django query

description: Find next highest value in django query


rawDescription: Python - zip only lists that contain data


code: [[number+1 for number in group] for group in x]

rawDescription: Python: List comprehension list of lists


code: item["email"] = set(re.findall(r'[\w.-]+@(?![\w.-]*\.(?:png|jpe?g|gif)\b)[\w.-]+\b', response.body))

rawDescription: Erase duplicate emails

description: Erase duplicate emails


code:
lambda x: x*x
(lambda x: x*x)
x = 10
(lambda x: x*x)(x)

rawDescription: Why do parentheses appear to cause evaluation in Python?


code:
d = defaultdict(list)
for k,v in x:
  d[v].append(k)

y = [(max(k),v) for v,k in d.items()]
y

rawDescription: Python: conditionally delete elements from list


code:
block.update()
block.draw()

rawDescription: How do you make an image move through the screen and then make it disappear in python?

description: Make an image move through the screen and then make it disappear in python


code:
import Image

imgsize = (250, 250) #The size of the image

image = Image.new('RGB', imgsize) #Create the image

innerColor = [80, 80, 255] #Color at the center
outerColor = [0, 0, 80] #Color at the edge

for y in range(imgsize[1]):
    for x in range(imgsize[0]):

        #Find the distance to the closest edge
        distanceToEdge = min(abs(x - imgsize[0]), x, abs(y - imgsize[1]), y)

        #Make it on a scale from 0 to 1
        distanceToEdge = float(distanceToEdge) / (imgsize[0]/2)

        #Calculate r, g, and b values
        r = innerColor[0] * distanceToEdge + outerColor[0] * (1 - distanceToEdge)
        g = innerColor[1] * distanceToEdge + outerColor[1] * (1 - distanceToEdge)
        b = innerColor[2] * distanceToEdge + outerColor[2] * (1 - distanceToEdge)

        #Place the pixel
        image.putpixel((x, y), (int(r), int(g), int(b)))

image.save('rectgradient.jpg')

rawDescription: Plot gradients using PIL in Python

description: Plot gradients using PIL in Python


rawDescription: How to slice and extend a 2D numpy array?

description: Slice and extend a 2D numpy array


rawDescription: Hiding console window of Python GUI app with py2exe


code:
class RealDevice():
    def start(self):
        self.device.do_start()
    def stop(self):
        self.device.do_stop()
    def pause(self):
        self.device.do_pause()
    def resume(self):
        self.device.do_resume()

class SimuDevice():
    def start(self):
        self._state = "running"
        print("started")
    def stop(self):
        self._state = "stopped"
        print("stopped")
    def pause(self):
        self._state = "paused"
        print("paused")
    def resume(self):
        self._state = "running"
        print("resumed")

rawDescription: simulation/operation mode in class

description: Simulation/operation mode in class


code: from . import module_name

rawDescription: Python package import own files, without knowing the package name at compile time


code:
from django.conf import settings
def my_site_url(request):
    return {
        'SITE_URL': Site.objects.get_current().domain,
    }

rawDescription: a way to have django SITEURL constant in settings.py

description: A way to have django SITEURL constant in settings.py


code:
def popRandom(self):
    item = self.getRandom()
    self.discard(item)
    return item

rawDescription: Python set with the ability to pop a random element


code:
A = np.dstack(list_of_arrays)  # Combine the 2D arrays along a new 3rd dimension
A.mean(axis=2)                 # Calculate the means along that new dimension

rawDescription: Computing average across a list of MxN arrays


rawDescription: How to iterate a 3D numpy array

description: Iterate a 3D numpy array


code: vbox.Add(topLabel, 1, wx.EXPAND)

rawDescription: wxPython control spacing

description: WxPython control spacing


code:
a = np.random.rand(10, 10, 20)
b = np.random.randint(20, size=(10,10))  # random integers in range 0..19

rawDescription: Index numpy nd array along last dimension


rawDescription: Scapy set class attribute question

description: Scapy set class attribute question


code:
d = PyQt4.QtCore.QDateTime(2014, 2, 20, 17, 10, 30)
d.toTime_t()

rawDescription: Convert QDate to seconds

description: Convert QDate to seconds


code: [BaseSurf.set_palette_at(swapidx, newRGBA) for swapidx, newRGBA in zip(tuple(n for n, RGBA in enumerate(BaseSurf.get_palette()) if RGBA == blankRGBA), tuple(RGBA for RGBA in NewSurf.get_palette() if RGBA != blankRGBA))]  # PLEASE GOD NO.

rawDescription: Is there a way to merge palettes for indexed pygame.Surfaces?


code:
time2D,length2D = np.meshgrid(time,length)
ordinate_vectorized = np.row_stack((length2D.ravel(),time2D.ravel()))

description: Numpy-native "nested-for-like" structrue


code: [it for it in item_list if date_from_db > it.date]

rawDescription: Search a list of objects in Python

description: Search a list of objects in Python


code:
import numpy as np
a = np.ma.masked_equal([2, 0, 1, 1, 3, 0, 0, 2, 0], 0)
rep = np.random.geometric(1. / a)
rep[a.mask] = 0

rawDescription: Python: Generating from geometric distribution


rawDescription: How to get a list of datatypes on Django model?

description: Get a list of datatypes on Django model


code:
from subprocess import Popen, PIPE
process = subprocess.Popen(['ls'], stdout = PIPE, stderr = PIPE, shell = True )
process.communicate()

rawDescription: how do i test subprocess's stdout, stderr in python on windows

description: Test subprocess's stdout, stderr in python on windows


code:
from sqlalchemy.sql.postgresql import JSONB, TEXT
from sqlalchemy.sql import cast

id_order = { str(v): k for k, v in enumerate(user_ids) }
users = User.query.filter(User.id.in_(user_ids)).\
    order_by(cast(id_order, JSONB)[cast(User.id, TEXT)])

rawDescription: Sqlalchemy get results in the same order


code:
pointArray = (1, 2, 3)
output = ["XYZ"] + pointArray
output = ["XYZ"] + list(pointArray)
output

rawDescription: How to transform a list to a sequence of its comma-separated elements?

description: Transform a list to a sequence of its comma-separated elements


code:
from bs4 import BeautifulSoup
import requests

url = "http://sunsettheatre.com/"
response = requests.get(url)
soup = BeautifulSoup(response.content, "html5lib")

font = soup.find("b", text="Past Movies:").find_next_sibling("font")
for event in font.find_all("b", recursive=False):
   event_date = event.previous_sibling.strip()
   event_text = event.get_text(strip=True)
   print(event_date, event_text)

rawDescription: Using BeautifulSoup to find specific text on a webpage


code:
a = input("value one:  ")
b = input("value two:  ")
os.execlp('python', 'python', 'product.py', a, b)

rawDescription: os.exec. passing arguments to new file function

description: Os.exec. passing arguments to new file function


code:
items = ['matt', 'zen', 'a', 'b', 'c', 'cat', 'dog']
{'a', 'b', 'c'}.issubset(items)

rawDescription: Searching through mutliple values in a list in python


code:
df["new_column"][is_null] = df["return_column"][is_null] # method 1
df["new_column"].loc[is_null] = df.loc["return_column"].loc[is_null] # method 2
df.loc[is_null, "new_column"] = df.loc[is_null, "return_column"] # method 3, thanks @joris

rawDescription: Using np.where, or another broadcasting technique in pandas dataframe


code:
s = """name is concat of first_name, last_name
price is sum of product, taxes, shipping"""

out = []

for line in s.splitlines():
    new_field,func,fields = re.match(r'(\w+) is (\w+) of (.*)',line).groups()
    out.append({'new_field':new_field,
                'func':func,
                'fields':fields.split(',')})

rawDescription: Match multiple lines on a pattern and return placeholders


code: row = Base(r[0], *map(int, r[1:]))

rawDescription: Converting values of named tuples from strings to integers


code:
# multiplication between 1s and 0s acts like logical AND
mask = (y_interp >= lower_bound) * (y_interp <= upper_bound)
accepted_parameters = x_interp[mask]

rawDescription: Locating region between a confidence interval in data using Python


code:
word = 'g4m3\n'
md5.new(word).hexdigest()
word = word.strip()
md5.new(word).hexdigest()

rawDescription: MD5 Encrypting Woes

description: MD5 Encrypting Woes


code: ax.xaxis.LABELPAD = 8  # default is 5

rawDescription: Python subplots leaving space for common axis labels


code:
import re
i = re.search('\d', s).start()
s = s[:i] + '-' + s[i:]

rawDescription: How to search & replace in Python?

description: Search & replace in Python


code: next(itertools.dropwhile(lambda t: not 100 < t[1] < 150, zip(xvalues, yvalues)))

rawDescription: Python 2.7 plotting query

description: Python 2.7 plotting query


code:
import pandas as pd
from numpy.random import rand
vars = ("fld1", "fld2", "fld3")
n = len(vars)
df = pd.DataFrame(rand(n, n), index=vars, columns=vars)
dfprobs = df/df.sum(axis=0)  # divide by sum of rows, or axis=1 to divide by sum of columns

rawDescription: While Loop and Pandas Iterrows

description: While Loop and Pandas Iterrows


rawDescription: Xpath normalize-space

description: Xpath normalize-space


code:
from itertools import repeat, chain

m = list(chain.from_iterable(zip(m, repeat(99))))[:-1]

rawDescription: Python for loop doesn't execute last iteration


code:
from rpy2.robjects import r
from rpy2.robjects.numpy2ri import numpy2ri
a = np.array([[i*2147483647**2 for i in range(5)], range(5)], dtype="uint64")
a = np.array(a, dtype="float64") # <- convert to double precision numeric since R doesn't have unsigned ints
ro = numpy2ri(a)
r.assign("bar", ro)
r("save(bar, file='another.gzip', compress=TRUE)")

rawDescription: Save 2d numpy array to R file format using rpy2


code: abc_grade = determine_score(avg)

rawDescription: Test Average and Grade - Python

description: Test Average and Grade - Python


code:
def activity(t):
       return  len(filter(lambda x:x[0]<t<x[0]+x[1],tickets))

rawDescription: Numpy : find number of active tickets at time t given a list of start and duration


code:
import json
json.loads(s)

rawDescription: Convert string to list in python

description: Convert string to list in python


code:
from collections import OrderedDict
counter = (Counter(dict(foo)) + Counter(dict(bar)))
order = OrderedDict(foo + bar).keys()
[[k, counter[k]] for k in order]

rawDescription: python: fast and easy way to compare these lists?

description: Python: fast and easy way to compare these lists


code:
import glob, shutil
for f in glob.glob('c:/files/*.bin'):
    shutil.move(f, 'c:/tmp/')

rawDescription: Why does the code : os.popen('move *.bin tmp) only move one file?


code: print(list(indexN))

rawDescription: How to make filter regex not ignore minus sign in a line of text?

description: Make filter regex not ignore minus sign in a line of text


code: [list(g) for k, g in groupby('2456890048', key=lambda x:int(x)%2) if not k]

rawDescription: Best way of getting the longest sequence of even digits in an integer


code: {'q': 'variable'}

rawDescription: What is the meaning of 'q' in request.GET var?


code:
import json
output = json.loads(sample)

rawDescription: Python string to list conversion

description: Python string to list conversion


rawDescription: How do I create bidimensional table from list?

description: Create bidimensional table from list


code:
class Thing( models.Model ):
    name = models.CharField(max_length=140)
    discarded = models.BooleanField( default=False )
    belongs_to = models.ForeignKey( Person, blank=True, null=True, related_name="things" )

    objects = ThingManager()

rawDescription: Django: Using a deleted/discarded field en lieu of deleting a database row - What to do with related models?


code: kernel_manager = KernelManager(kernel_name='python', client_class='__main__.TestClient')

rawDescription: How can I add a callback to a ThreadedKernelClient in IPython?

description: Add a callback to a ThreadedKernelClient in IPython


code:
import collections
class Foo(object):
    def __init__(self):
        self.CompleteAnalysis=collections.defaultdict(
            lambda: collections.defaultdict(list))

    def getFilledFields(self,sentence):
        field, field_value, field_date = sentence.split('|')
        field_value = field_value.strip('\n')
        field_date = field_date.strip('\n')
        self.CompleteAnalysis[field]['date'].append(field_date)
        self.CompleteAnalysis[field]['value'].append(field_value)

foo=Foo()
foo.getFilledFields('A|1|2000-1-1')
foo.getFilledFields('A|2|2000-1-2')
print(foo.CompleteAnalysis['A']['date'])
# ['2000-1-1', '2000-1-2']

print(foo.CompleteAnalysis['A']['value'])
# ['1', '2']

rawDescription: setDefault for Nested dictionary in python

description: SetDefault for Nested dictionary in python


code:
import matplotlib.pyplot as plt

x = [1, 2, 3]
y =[1, 2, 3]

fig, ax = plt.subplots()
ax.plot(x, y, linewidth=10, color='yellow')
ax.text(2, 2, 'label', ha='center', size=72)

# For the moment, hide everything else...
ax.axis('off')
fig.tight_layout()

plt.show()

rawDescription: Remove matplotlib text plot border

description: Remove matplotlib text plot border


code:
# __init__.py
__all__ = ["fun1", "fun2"]
# doing import * will load those 2

rawDescription: How to import from another folder (python)

description: Import from another folder (python)


code:
cursor = conn.cursor()
cursor.executemany('INSERT INTO sometable (id, name, time) VALUES (%(Registration ID)s, %(Name)s, %(registration time)s)',
    records)
conn.commit()

rawDescription: How to put info of a text file in a tuple to be convertible to SQL table?

description: Put info of a text file in a tuple to be convertible to SQL table


code: graph.cypher.execute("CREATE (n:Test {name: {name})", parameters={"name": "Bob"})

rawDescription: Multiple variables in cypher query (name, label) - py2neo


rawDescription: Python regex and find multiple times

description: Python regex and find multiple times


code: assert a.shape[1] % 3 == 0

rawDescription: Create view to recarray subclass

description: Create view to recarray subclass


code:
import numpy as np

[(name, int(perc) if perc else np.nan)
 for name, perc in re.findall(r'(\b[\w -]+\b)(?:\s+\((\d+)%\))?', inputtext)]

rawDescription: One Way to Grab both text and percentages regex python


code: count = len(re.findall(r'(?<!\S)'+ word + r'(?!\S)', line, re.IGNORECASE))

rawDescription: Count the occurrence of a word in a txt file in python


code:
N4
AP15

rawDescription: python for getting big number string form a column

description: Python for getting big number string form a column


code:
def mem_fib(n, _cache={}):
    '''efficiently memoized recursive function, returns a Fibonacci number'''
    if n in _cache:
        return _cache[n]
    elif n > 1:
        return _cache.setdefault(n, mem_fib(n-1) + mem_fib(n-2))
    return n

rawDescription: bottom up fibonacci in python using O(1) space

description: Bottom up fibonacci in python using O(1) space


code:
engine = sqlalchemy.create_engine("mysqldb://user:password@host/db")
res = engine.execute("DESCRIBE table_name;")
columns = [row["Field"] for row in res]

res = engine.execute("{}".format(query_for_foreign_keys))
foreign_keys = [row["COLUMN_NAME"] for row in res]
referenced_column_names = [row["REFERENCED_COLUMN_NAME"] for row in res]
referenced_table_names = [row["REFERENCED_TABLE_NAME"] for row in res]

rawDescription: How to do a SELECT * following all foreign keys

description: Do a SELECT * following all foreign keys


code: df.to_sql(con=con, name='table_name_for_df', if_exists='replace', flavor='mysql')

rawDescription: How to insert pandas dataframe via mysqldb into database?

description: Insert pandas dataframe via mysqldb into database


code:
while True:
    pygame.display.flip()
    screen.blit(text, textRect)

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

rawDescription: Python/Pygame: Placing text in a specific location


code:
glued = pd.concat([x, y], axis=1, keys=['x', 'y'])
glued
glued.swaplevel(0, 1, axis=1).sortlevel(axis=1)
glued = glued.swaplevel(0, 1, axis=1).sortlevel(axis=1)
glued

rawDescription: Averaging data from multiple data files in Python with pandas


code:
def calculateGPA(gradeDict):
    return sum(gradeDict.values())/len(gradeDict)

students = {}
# We can set the keys to variables so we might minimize typos
name, age, gender, level, grades = "name", "age", "gender", "level", "grades"
john, jane = "john", "jane"
math = "math"
students[john] = {}
students[john][age] = 12
students[john][gender] = "male"
students[john][level] = 6
students[john][grades] = {math:3.3}

students[jane] = {}
students[jane][age] = 12
students[jane][gender] = "female"
students[jane][level] = 6
students[jane][grades] = {math:3.5}

# At this point, we need to remember who the students are and where the grades are stored. Not a huge deal, but avoided by OOP.
print(calculateGPA(students[john][grades]))
print(calculateGPA(students[jane][grades]))

rawDescription: When should I be using classes in Python?


rawDescription: Python Pipe Character for calling functions


code:
for col in data:
    coord1 = mapping[col[0]]
    coord2 = mapping[col[1]]
    heatmap[[coord1, coord2], [coord2, coord1]] += col[2]

rawDescription: Heat Map Python

description: Heat Map Python


rawDescription: Splitting information in a specific column python?


code: sum(map(lambda x:x*x,l))

rawDescription: sum of squares in a list in one line?

description: Sum of squares in a list in one line


rawDescription: Extract the minimum of a list of arrays, plot lines along with their intersections in Python


code:
from datetime import datetime, timedelta
from pytz import timezone

AmericaNewYorkTz = timezone('America/New_York')

def _to_datetime(air_date, air_time):
    schedule_time = '{}:{}'.format(air_date, air_time)
    naiveDateTime = datetime.strptime(schedule_time,'%m/%d/%Y:%I:%M %p')
    localizedDateTime = AmericaNewYorkTz.localize(naiveDateTime, is_dst=None)
    return localizedDateTime

dt = _to_datetime('05/27/2015', '06:00 AM')
print('DateTime:', dt)

rawDescription: How to convert datetime string without timezone to another datetime with timezone in python?

description: Convert datetime string without timezone to another datetime with timezone in python


rawDescription: How to change the location of the pointer in python?

description: Change the location of the pointer in python


code:
step = 256 / 30.0
value = int(frame * step)
rgb = (value, value, value)

rawDescription: How to add each element of a tuple or list by a fixed value?

description: Add each element of a tuple or list by a fixed value


code:
import os, shutil

def cp_parents(target_dir, files):
    dirs = []
    for file in files:
        dirs.append(os.path.dirname(file))
    dirs.sort(reverse=True)
    for i in range(len(dirs)):
        if not dirs[i] in dirs[i-1]:
            need_dir = os.path.normpath(target_dir + dirs[i])
            print("Creating", need_dir )
            os.makedirs(need_dir)
    for file in files:
        dest = os.path.normpath(target_dir + file)
        print("Copying %s to %s" % (file, dest))
        shutil.copy(file, dest)

rawDescription: Copy a file into a directory with its original leading directories appended


rawDescription: assigning range values to a data table

description: Assigning range values to a data table


code:
timeit('filter(None, str_list)', 'str_list=["a"]*1000', number=100000)
timeit('filter(bool, str_list)', 'str_list=["a"]*1000', number=100000)
timeit('filter(len, str_list)', 'str_list=["a"]*1000', number=100000)
timeit('[x for x in str_list if x]', 'str_list=["a"]*1000', number=100000)
timeit('filter(lambda item: item, str_list)', 'str_list=["a"]*1000', number=100000)

rawDescription: Remove empty strings from a list of strings


rawDescription: Python: Why can't I unpack a tuple into a dictionary?


rawDescription: What area deals with the extraction of words with similar characteristics?


code: age + height - weight * iq / 2

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


rawDescription: Challenge: Creating a list of tuples of different combinations with different value 'options' in each location of the tuple.


code:
import locale

def read_float_with_comma(num):
    return locale.atof(num)

rawDescription: Convert Python strings into floats explicitly using the comma or the point as separators


rawDescription: How to do many-to-many Django query to find book with 2 given authors?

description: Do many-to-many Django query to find book with 2 given authors


rawDescription: regex - how to recognise a pattern until a second one is found

description: Regex - how to recognise a pattern until a second one is found


code:
import httplib
from cStringIO import StringIO
from urllib3.response import HTTPResponse

http = 'HTTP/1.1 200 OK\r\nServer: nginx\r\nDate: Tue, 09 Feb 2016 12:02:25 GMT\r\nContent-Type: application/json\r\nContent-Length: 115\r\nConnection: close\r\nContent-Encoding: gzip\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Credentials: true\r\n\r\n\x1f\x8b\x08\x00\xa0\xda\xb9V\x02\xff\xab\xe6RPPJ\xaf\xca,(HMQ\xb2R()*M\xd5Q\x00\x89e\xa4&\xa6\xa4\x16\x15\x03\xc5\xaa\x81\\\xa0\x80G~q\t\x90\xa7\x94QRR\x90\x94\x99\xa7\x97_\x94\xae\x04\x94\xa9\x85(\xcfM-\xc9\xc8\x07\x99\xa0\xe4\xee\x1a\xa2\x04\x11\xcb/\xcaL\xcf\xcc\x03\x89\x19Z\x1a\xe9\x19\x9aY\xe8\x19\xea\x19*q\xd5r\x01\x00\r(\xafRu\x00\x00\x00'

class DummySocket(object):
    def __init__(self, data):
        self._data = StringIO(data)
    def makefile(self, *args, **kwargs):
        return self._data

response = httplib.HTTPResponse(DummySocket(http))
response.begin()
response = HTTPResponse.from_httplib(response)
print(response.data)

rawDescription: How to decode a source code which is compressed with gzip in python

description: Decode a source code which is compressed with gzip in python


code: (expand-file-name (buffer-file-name))

rawDescription: Emacs: check if filepath contains directory name


code:
import random
from operator import mul

class Node:
    __slots__ = ['w', 'v', 'tw']
    def __init__(self, w, v, tw):
        self.w, self.v, self.tw = w, v, tw

def rws_heap(items):
    h = [None]
    for w, v in items:
        h.append(Node(w, v, w))
    for i in range(len(h) - 1, 1, -1):
        h[i>>1].tw += h[i].tw
    return h

def rws_heap_pop(h):
    gas, i = h[1].tw * random.random(), 1
    while gas > h[i].w:
        gas -= h[i].w
        i <<= 1
        if gas > h[i].tw:
            gas -= h[i].tw
            i += 1
    w, v = h[i].w, h[i].v
    h[i].w = 0
    while i:
        h[i].tw -= w
        i >>= 1
    return v

def random_weighted_sample_no_replacement(items, n):
    heap = rws_heap(items)
    for i in range(n):
        yield rws_heap_pop(heap)

def random_weighted_sample_no_replacements_inverse_weights(mapping, n):
    keys, values = zip(*mapping.items())
    total = reduce(mul, (v + 1 for v in values))
    weights = (total / (v + 1) for v in values)
    heap = rws_heap(zip(weights, keys))
    for i in xrange(n):
        yield rws_heap_pop(heap)

rawDescription: Random from Python Dict with lowest values as priority


code:
{'baz': ['apple', 'orange', 'pear', 'guava', 'banana'],
 'foo': 'bar',
 'hello': 'world'}

rawDescription: Suppress unicode prefix on strings when using pprint


code:
import subprocess

result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test("a", "b")'])
print(result)

result = subprocess.check_output(['lua', '-l', 'demo', '-e', 'test2("a")'])
print(result)

rawDescription: Run Lua script from Python

description: Run Lua script from Python


code:
common_flags = wx.SizerFlags().Expand().Border(wx.ALL, 1)  # creates the object
bar_flags = common_flags.Proportion(0)  # bar_flags points to the common_flags object

# Referencing common_flags with Proportion set to 0
main_box.Add(toolbar1, bar_flags)

# Changes the value of common_flags.
main_box.Add(wrap_panels_box, common_flags.Proportion(1))

# Since bar_flags points to common_flags, it also has Proportion set to 1
main_box.Add(toolbar2, bar_flags)
main_box.Add(statusbar, bar_flags)

rawDescription: How to layout wxPython panels that expand both directions

description: Layout wxPython panels that expand both directions


code:
g = sns.FacetGrid(data=df, col='group')
g.map(plt.hist, 'val', color='black', lw=0)
g.set_titles('{col_value}')

rawDescription: Customizing annotation with Seaborn's FacetGrid


code:
a='very'
print("I a {name} find {site} {a} {a} {a} {a} useful".format(name=name, site=site, a=a))

rawDescription: Use same variable multiple times in print


code:
def serve(prob, player):
    if random.random() < prob:
        return player
    else:
        return other[player]

rawDescription: Table tennis simulator

description: Table tennis simulator


code:
def mixed_order( a ):
    return ( a.attribute1, -a.attribute2 )

someList.sort( key=mixed_order )

rawDescription: Python: List Sorting with Multiple Attributes and Mixed Order


rawDescription: Keep dataframe columns depending on row value


rawDescription: fastest way to find the magnitude (length) squared of a vector field

description: Fastest way to find the magnitude (length) squared of a vector field


code:
l3 = []
for i in l1:
    temp = 0
    for j in l2:
        temp += i*j
    l3.append([temp])

rawDescription: Iterating over two lists and resulting in a third one


rawDescription: All possible matrices (list of list) containing only elements from raw list elements python


code:
app = webapp2.WSGIApplication([('/', MainPage),
                               ('/foo', FooHandler),
                               ('/bar', BarHandler),
                               ('/.*', CatchEverythingElseHandler)], debug=True)

rawDescription: google app engine (python27) fetch request url

description: Google app engine (python27) fetch request url


code:
import random

SUITS = ("D", "H", "C", "S")
suit = random.choice(SUITS)

number = random.randint( 1,13)

card_names = {'ace': 1, 'jack': 11, 'queen': 12, 'king': 13}
for i in range(2, 11):
    card_names[str(i)] = i
guessCount = 0

Guess_Suit = input("Start by guessing the Suit: ")

guessCount = guessCount + 1
while guessCount < 9:
    Guess_Suit = Guess_Suit.upper()
    guessCount = guessCount + 1
    if Guess_Suit == suit:
        print("Correct!")
        break
    elif Guess_Suit != suit:
        print('Wrong')
        Guess_Suit = input("Guess the Suit again: ")

Guess_number = input("Now Guess the card number or name of the face card:")
Guess_number = card_names.get(Guess_number.lower().strip())
guessCount = guessCount + 1
while guessCount < 9:
    if Guess_number is None:
        print("The card you picked is invalid")
        Guess_number = input("Pick another one: ")
        Guess_number = card_names.get(Guess_number.lower().strip())
        guessCount = guessCount + 1
    elif Guess_number == number:
        print("THATS IT YOU WON")
        break
    else:
        print('Wrong')
        Guess_number = input("Pick another one: ")
        Guess_number = card_names.get(Guess_number.lower().strip())
        guessCount = guessCount + 1

rawDescription: Python card guessing game

description: Python card guessing game


code:
with open(path_to_recipe) as infile:
    ingredients = []
    while True:
        try:
            sentinel = next(infile) # skip a line
            if sentinel.startswith("Step"):
                # we're past the ingredients, so
                break
            name = next(infile)
            amount = next(infile)
            metric = next(infile)
        except StopIteration:
            # you've reached the end of the file
            break
        ingredients.append({'name':name, 'amount':float(amount), 'metric':metric})
        # use a dictionary for easier access

rawDescription: (Python) How can I let a user open a text file and then change an integer / number


code:
A = np.random.random((3,3))
B = np.random.random((3,3))+1
C = np.random.random((3,3))+2
D = np.random.random((3,3))+3

lbls = ['la', 'le', 'li']

fig, axar = plt.subplots(2,2)
fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])

ar_plts = [A, B, C, D]

for i,ax in enumerate(axar.flat):
    im = ax.imshow(ar_plts[i]
                    , interpolation='nearest'
                    , origin='lower')
    ax.grid(False)
    ax.set_yticks([0,1,2])
    ax.set_xticks([0,1,2])

    ax.set_xticklabels(lbls)
    ax.set_yticklabels(lbls)

fig.colorbar(im, cax=cbar_ax)

fig_path = r"blah/blub"
fig_name = "matrices.png"
fig_fobj = os.path.join(fig_path, fig_name)
fig.savefig(fig_fobj)

rawDescription: label matplotlib imshow axes with strings

description: Label matplotlib imshow axes with strings


code: fields = fields.reset_index(drop=True)

rawDescription: Pandas series removing duplicates issue

description: Pandas series removing duplicates issue


code: tfidf = TfidfVectorizer(tokenizer=None)

rawDescription: TFIDF with previously preprocessed data

description: TFIDF with previously preprocessed data


code:
def Bolzano(fonction, a, b, tol=0.000001):
   while abs(b-a)>tol:
       m=(a+b)/2
       if cmp(fonction(m), fonction(a)) == 0:
           a=m
       else:
           b=m
   return a, b

rawDescription: Any way to extract the sign of a number in Python?


code: lines = [locale.atof(line.strip()) for line in open(filename)]

rawDescription: what is a quick way to import a text file in python?

description: What is a quick way to import a text file in python


rawDescription: "Matching"/relations data across databases in Django


code:
import glob
import pandas as pd

fmask = 'MonthlyDataSplit/Day/Day*.csv'
df = pd.concat((pd.read_csv(f, sep=',', usecols=['Month','Day','AirTemperature']) for f in glob.glob(fmask)))
df.groupby(['Month','Day']).mean().to_csv('my_csv.csv')

rawDescription: Create empty csv file with pandas

description: Create empty csv file with pandas


code:
# Don't do this!
end_message._font = pygame.font.Font('/path/to/my/font/file', size)

rawDescription: Changing font in a livewires message

description: Changing font in a livewires message


code:
import pprint

def no_unicode(object, context, maxlevels, level):
    """ change unicode u'foo' to string 'foo' when pretty printing"""
    if pprint._type(object) is unicode:
        object = str(object)
    return pprint._safe_repr(object, context, maxlevels, level)

mypprint = pprint.PrettyPrinter()
mypprint.format = no_unicode

rawDescription: Python: Force pprint to display unicode strings as strings?


code: df['xy'] = df.apply(lambda x: [x['x'], x['y']], axis=1)

rawDescription: Pandas - convert columns to grouped array coordinates


code:
index = pd.DatetimeIndex(start=date(2015,1,1), freq='W', periods = 100)
df1 = pd.DataFrame(np.random.random((100,3)), index=index)
df2 = pd.DataFrame(np.random.random((100,1)), index=index)
print(pd.rolling_corr(df1, df2.squeeze(), window=20).tail())

rawDescription: Pandas Data Frame correlation with Series


code: [v if i not in idx else 0 for i, v in enumerate(l)]

rawDescription: Best way to replace values in a list based on many indexes

description: Replace values in a list based on many indexes


rawDescription: Python sports XML parsing

description: Python sports XML parsing


code:
urlFile = "path/to/file"
urls = open(urlFile).readLines()

for url in urls:
  doAction(url)

rawDescription: Python 3 - Reading line by line from a textfile and doing action for each line


code:
[a,b,c] = [1,2,3]
Arg = numpy.array([[0.12],[0.9],[0],[0],[0.2]])
Solution = Arg
Solution[Solution ==0] = 1
Solution = Solution * a * b * c
print(Solution)

rawDescription: Array indexing by array-value and array-value dependant operation


code:
match = re.search(r'\ba\b', text)
start, end = match.start(), match.end()

rawDescription: Python BeautifulSoup - Add Tags around found keyword


code:
SOURCE_IP = "fe80000000000000020086fffe0580da"
DEST_IP = "fe80000000000000026097fffe0769ea"
pseudo_header = build_pseudo_header(SOURCE_IP, DEST_IP, 32)

rawDescription: Computing 16-bit checksum of ICMPv6 header


code:
extent=[xslice.start, xslice.stop+1, yslice.start, yslice.stop+1]
plt.contour(mask[xslice, yslice], extent=extent)

rawDescription: Setting position of contour sub-plot in Matplotlib


rawDescription: Put zeros in front of a number to make it 4 digits


code:
def recurse(min1, min2, list):
    if len(list)==0:
        return min2
    first, rest = list[0], list[1:]
    if first < min1:
        return recurse(first, min1, rest)
    if first < min2:
        return recurse(min1, first, rest)
    return recurse(min1, min2, rest)

def second_smallest(list):
    if len(list) < 2:
        raise ValueError("too few elements to find second_smallest")
    a, b, rest = list[0], list[1], list[2:]
    if b < a:
        return recurse(b, a, rest)
    else:
        return recurse(a, b, rest)

rawDescription: Find the second smallest number in a list using recursion


code:
import tempfile

with tempfile.TemporaryFile() as tf:
    tf.write(bytes(my_str_input + "\n", "ascii"))
    tf.flush()
    tf.seek(0)  # Might not be needed
    proc = subprocess.Popen(["MyCommandHere"], stdin=tf)

rawDescription: Use subprocess.communicate() to pipe stdin without waiting for process


rawDescription: Trying to put matrices into a set using python, but it still allows duplicates


code:
# assuming you have a list of thread objects somewhere
threads = [MyThread(), ...]
for thread in threads:
    thread.start()
for thread in threads:
    thread.join()

rawDescription: wait till other python script ends

description: Wait till other python script ends


rawDescription: Grabbing values from within a list of string arrays?


code: t0 -= t0 % (30*60) # round down to previous half-hour

rawDescription: Add one hour forward to current time in Python


code:
import struct
day = 1; month = 2; year = 2003
hour = 4; minute = 5
date = day + month * 32 + (year - 2000) * 512
time = 100 * hour + minute
data = struct.pack(b'HH', date, time)
data
data.encode("hex")

rawDescription: integer to byte without using struct in python

description: Integer to byte without using struct in python


code:
def foo1(L):
    param_of_foo1 = L[0]  # other entries will be ignored

rawDescription: Calling random functions from a list when functions have different number of parameters


code:
m = re.match(r'[%s]+' % ch_, str_)
return m.end() if m else 0

rawDescription: Number of the same characters in a row - python


code:
import random
List1 = ['AAAA','BBBBB','CCCCC','DDDD','EEEE']

base_name = "Group"
my_dic = dict()
for x in range(len(List1)):
    my_dic[base_name + str(x +1)] = []

for x in range (len(List1)):
    losowanie1 = random.sample(List1,1)
    my_dic[base_name + str(x +1)].append(losowanie1[0])
    List1.remove(losowanie1[0])
print(my_dic)

rawDescription: Append to arrays in loop

description: Append to arrays in loop


code:
echo_stdout = os.popen('echo foo', 'r')
echo_stdout.read()

rawDescription: Translating code using subprocess in Python 2.7 to Python 2.3


code: {s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}

rawDescription: How can I convert python class with slots to dictionary?

description: Convert python class with slots to dictionary


code:
class User(Base):
    ...

    @classmethod
    def by_id(cls, id):
        return session.query(cls).get(id)

rawDescription: Application Layout with Groups of single items in Python


code:
mylist = [1,2,3]
for idx, item in enumerate(mylist):
    mylist[idx] = myfunc(item)

rawDescription: How to replace an object in python

description: Replace an object in python


code:
serializer.object.status = "I"
serializer.object.journal = id

rawDescription: Django REST Framework Specify Some Fields Before calling serializer.isValid()


code:
def align_xaxis(ax2, ax1, x1, x2):
    "maps xlim of ax2 to x1 and x2 in ax1"
    (x1, _), (x2, _) = ax2.transData.inverted().transform(ax1.transData.transform([[x1, 0], [x2, 0]]))
    xs, xe = ax2.get_xlim()
    k, b = np.polyfit([x1, x2], [xs, xe], 1)
    ax2.set_xlim(xs*k+b, xe*k+b)

rawDescription: Multiple plots on same figure with DataFrame.Plot


rawDescription: Creating resources combination

description: Creating resources combination


code:
def matches_pattern(s, patterns):
    return any(p.match(s) for p in patterns)

rawDescription: Python, fastest way to iterate over regular expressions but stop on first match


code:
def read_4th(fn):
    return pd.read_csv(fn, delim_whitespace=1, usecols=[3])

files = ['./1.csv', './2.csv', './3.csv']

big_df = pd.concat([read_4th(fn) for fn in files], axis=1)

big_df.to_excel('./mybigdf.xlsx')

rawDescription: Grab one specific column from multiple csv files and merge into one


code:
strs = 'test'
int(strs,36)

rawDescription: Convert string to decimal (base 10) in python


code:
received = dict.fromkeys(SERVICES , {'MS1':[]})
received.values()
[id(v) for v in received.values()]

rawDescription: dict.fromkeys method in Python 3.2

description: Dict.fromkeys method in Python 3.2


code: Result['ratio']= fuzz.ratio(Result['Account Name_x'],Result['Account Name_y'] )

rawDescription: fuzzywuzzy ratio of 2 columns if one column satisfies 100 percent match the best one

description: Fuzzywuzzy ratio of 2 columns if one column satisfies 100 percent match the best one


code: mydatetime = datetime.datetime(d.year, d.month, d.day)

rawDescription: How do I get datetime from date object python?

description: Get datetime from date object python


code:
for product_element in product_elements:
    print(ElementTree.tostring(product_element))

rawDescription: Python : How to pass XML element as an argument


code: models.Issue.objects.extra(select={'year': "EXTRACT(year FROM pub_date)", 'month': "EXTRACT(month from pub_date)"}).values('year', 'month').annotate(Count('title'))

rawDescription: How to do this GROUP BY query in Django's ORM with annotate and aggregate

description: Do this GROUP BY query in Django's ORM with annotate and aggregate


rawDescription: Is there a way to NOT an arbitrary M x N matrix using numpy broadcasting?


code:
def func(x):
    return int(x[-1])
max(the_list, key=func)
#['b', 'c', 'e', '4']

rawDescription: Output element with the greatest value in certain position. Python


code:
users['user1']['age'] = 21
users['user2'] = {'name': 'John Doe', 'age': 30, 'password': 'qwerty'}

rawDescription: Python extend matrix

description: Python extend matrix


code:
to_shift_over = df.Website.str.lower().str.contains("see over")
df.loc[to_shift_over, "Website"] = df["Notes"]
df.loc[to_shift_over, "Notes"] = ""

rawDescription: Conditional Cell Substitution in Pandas, Python 2.7


code:
from itertools import product
for a, b in product([False, True], repeat=2):
    print('{a!r:5} and {b!r:5}: {o1!r:5}    {a!r:5} & {b!r:5}: {o2!r:5}'.format(a=a, b=b, o1=a and b, o2=a & b))

rawDescription: Explicitly evaluate both conditions when using boolean and


code:
with open('file01.txt') as fobj1, open('file02.txt') as fobj2:
    data1 = fobj1.readlines()
    data2 = fobj2.readline()

rawDescription: Replacing data to different file

description: Replacing data to different file


code:
@name.expression
def name (cls):
    f = cls.first_name
    m = cls.middle_name
    l = cls.last_name
    return f+' '+m+' '+l

rawDescription: How to create a class attribute and class property within Elixir/SqlAlchemy

description: Create a class attribute and class property within Elixir/SqlAlchemy


code:
import pandas as pd
df = pd.DataFrame({'year':['2012', '2012'], 'month':['01', '02']})
df
df['concatenated'] = df['year'] + df['month']
df

rawDescription: Concatenate Columns as Index in Pandas

description: Concatenate Columns as Index in Pandas


rawDescription: Conjoin function made in functional style


code: data = zip(projects.values(), employees_on_projects, tasks_in_projects)

rawDescription: Selecting all columns from related model with django queryset


code:
with open("file.txt") as f:
    lines = list(f)
# do something with lines

rawDescription: Reading text from a text file in python

description: Reading text from a text file in python


code:
'hello'
'\x1b[41mRED'

rawDescription: Prevent terminal character set switch on data printing


code:
print('Eight-Character Key: ',end='')
for i in range(0,8):
            key = random.randint(33,126)
            key = chr(key)
            print(key,end='')

rawDescription: How to display a string of integers and letters from a for loop

description: Display a string of integers and letters from a for loop


code:
import numpy as np
from scipy import optimize
np.set_printoptions(precision=4)

def gaussian(p, x, y):
    height, center_x, center_y, width_x, width_y = p
    return height*np.exp(-(((center_x-x)/width_x)**2+((center_y-y)/width_y)**2)/2)

def moments(data):
    total = np.nansum(data)
    X, Y = np.indices(data.shape)
    center_x = np.nansum(X*data)/total
    center_y = np.nansum(Y*data)/total
    row = data[int(center_x), :]
    col = data[:, int(center_y)]
    width_x = np.nansum(np.sqrt(abs((np.arange(col.size)-center_y)**2*col))
                        /np.nansum(col))
    width_y = np.nansum(np.sqrt(abs((np.arange(row.size)-center_x)**2*row))
                        /np.nansum(row))
    height = np.nanmax(data)
    return height, center_x, center_y, width_x, width_y

def errorfunction(p, x, y, data):
    return gaussian(p, x, y) - data

def fitgaussian(data):
    params = moments(data)
    X, Y = np.indices(data.shape)
    mask = ~np.isnan(data)
    x = X[mask]
    y = Y[mask]
    data = data[mask]
    p, success = optimize.leastsq(errorfunction, params, args=(x, y, data))
    return p

def make_data(shape):
    h, w = shape
    p = 50, h/2.0, w/2.0, h/3.0, w/5.0
    print('Actual parameters: {}'.format(np.array(p)))
    X, Y = np.indices(shape)
    data = gaussian(p, X, Y) + np.random.random(shape)
    mask = np.random.random(shape) < 0.3
    data[mask] = np.nan
    return data

shape = 100, 200
data = make_data(shape)
X, Y = np.indices(shape)
parameters = fitgaussian(data)
print('Fitted parameters: {}'.format(parameters))
fit = gaussian(parameters, X, Y)

rawDescription: Python 2D Gaussian Fit with NaN Values in Data


code:
for i in range(xbox, xbox+3):
    for j in range(ybox, ybox+3):
        if val == sud[j][i]:                    ### check box for val
            return 1

rawDescription: Passing matrix in recursive sudoku solver


code: sum(a * b + 1 for a, b in zip(l1, l2))

rawDescription: Doing calculation in Tuples on List Comprehension


code:
claw = map(lambda x: 'Fizzbuzz' if x % 15 == 0 else (lambda x: 'Fizz' if x % 3 == 0 else (lambda x: 'Buzz' if x % 5 == 0 else x)(x))(x), alist)
claw

rawDescription: Nested if-else lambdas in python returning function object rather than value (passing variable through?)


code:
In : [(from_node, to_node) for from_node, to_node, key in g.edges(keys=True) if key=="1/2/12"]
Out: [('Bob', 'Pencil'), ('Alice', 'Pencil')]

rawDescription: What is the correct graph data structure to differentiate between nodes with the same name?


code:
def application(environ, start_response):
    start_response('200 OK', [('Content-type', 'text/plain')])
    return ['Hello World!']

rawDescription: How to hide "cgi-bin", ".py", etc from my URLs?

description: Hide "cgi-bin", ".py", etc from my URLs


code:
import itertools

with open('test.txt','r') as infile, open('shuffles.txt','w') as outfile:
    words = infile.read().strip().split('\n')
    shuffles = itertools.permutations(words)
    output = '\n'.join(' '.join(shuffle) for shuffle in shuffles)
    outfile.write(output)

rawDescription: How can I read a file, put contents in an array, shuffle the array, and then write the shuffled array to the file in python 2.7

description: Read a file, put contents in an array, shuffle the array, and then write the shuffled array to the file in python 2.7


rawDescription: Randomize a generator

description: Randomize a generator


code:
import json
json.loads(dates.iloc[0])
type(json.loads(dates.iloc[0]))

rawDescription: Python pandas.read_csv split column into multiple new columns using comma to separate


code:
import time

videoid = requests.get("http://www.youtube-mp3.org/a/pushItem/",
                 params={
                      "item": "your youtube video url",
                      "el": "na",
                      "bf": "false",
                      "r": int(time.time() * 1000000)   # JS timestamps are in microseconds
                 }).text

info = requests.get("http://www.youtube-mp3.org/a/itemInfo/",
                   params={
                       "video_id": videoid,
                       "ac": "www",
                       "t": "grp",
                       "r": int(time.time() * 1000000)
                   }).text

rawDescription: How to enter a parameter for a HTTP GET request that doesn't have a name?

description: Enter a parameter for a HTTP GET request that doesn't have a name


code:
myMailInstance.start()

logging.debug('This message should be printed before the mail thread ends')

myMailInstance.join()

if myMailInstance.get_result() == 0:
    logging.debug('Success')
elif myMailInstance.get_result() == 1:
    logging.debug('Failed')

rawDescription: How to properly execute a non-blocking task with threads in Python

description: Properly execute a non-blocking task with threads in Python


code:
import functools
import scipy.integrate as si
import scipy.optimize as so

def test_fn(x, c):
    return c / x

def integrate_fn(ul, fn, ll, args, target):
    return si.quad(fn, ll, ul, args=args) - target

def main():
    lower_limit =  8.0
    target_area =  2.5
    c_val       = 42.0
    sol = so.brentq(
        integrate_fn, lower_limit, 20.0, args=(
            test_fn, lower_limit, (c_val,), target_area
        )
    )
    print(sol)

if __name__=="__main__":
    main()

rawDescription: Integrate in a if statement? (python)

description: Integrate in a if statement? (python)


code:
Import(names=[alias(name='foo', asname=None)])
ImportFrom(module='bar', names=[alias(name='*', asname=None)], level=0)

rawDescription: How to tell which modules have been imported in some source code?

description: Tell which modules have been imported in some source code


code:
f = h5py.File(sys.argv[1], 'r')
A = np.empty(f['A'].shape, f['A'].dtype)
T = np.empty(f['T'].shape, f['T'].dtype)
f['A'].read_direct(A)
f['T'].read_direct(T)

rawDescription: Efficiently create 2d histograms from large datasets


code: arg_dict = lambda l: dict(zip(l.split(', '), eval(l)))

rawDescription: Passing keyword arguments to a function when local variable names are same as function parameter names


code: spl = line.split()

rawDescription: Replacing strings in specific positions into a text and then rewriting all the text


code:
for sourceIP, otherHeader in testDictionary.items():
    if otherHeader[0] != destinationIP:
        testDictionary[sourceIP].append(["10.10.10.2", 22, 8080, 1])
    else:
        testDictionary[sourceIP][-1] += 1

rawDescription: Store and lookup IP Packet header fields in Python


rawDescription: How to center align text produced by numpy.savetxt?

description: Center align text produced by numpy.savetxt


code:
import urlparse
import cherrypy

class HelloWorld:

  @cherrypy.expose
  def index(self, name):
    postParams = cherrypy.request.body.params
    getParams  = urlparse.parse_qs(cherrypy.request.query_string)
    print(postParams, getParams)
    # ({u'name': u'bar'}, {'name': ['foo']})

rawDescription: CherryPy combining querystring value with form value in POST body


code:
def by_veg_sum(record):
    return sum(record[entry] for entry in ['Cucumber','Carrot','Runner Bean'])

rawDescription: Ordered dictionary Sum and Top 3 of the Ordered dictionary sum


code:
import theano
import os
os.environ["THEANO_FLAGS"] = "mode=FAST_RUN,device=gpu,floatX=float32"

rawDescription: Theano config directly in script

description: Theano config directly in script


code:
Oct-1
Dec-2
Mar-6
Jan-4
Feb-3
Sep-1
Nov-7

rawDescription: Count of days of each month from a list of dates python


code:
if "HOW ARE YOU" in talk.upper():
    perform_action()

rawDescription: How would I save time with or statements in Python?


rawDescription: validating IP address - python

description: Validating IP address - python


rawDescription: Python cgi and stdin

description: Python cgi and stdin


rawDescription: Manipulating dictionary data structures

description: Manipulating dictionary data structures


rawDescription: Flatten doubly nested lists

description: Flatten doubly nested lists


rawDescription: creating cumulative percentage from a dictionary of data

description: Creating cumulative percentage from a dictionary of data


code:
import gc
f = a.f
len(gc.get_referrers(a.g)),len(gc.get_referrers(f))
sys.getrefcount(a.g),sys.getrefcount(f)

rawDescription: Why do different methods of same object have the same `id`?


code:
my_list = ListWrapper('abc')
my_list

rawDescription: __getattr__ throwing maximum recursion error when __setattr__ implemented


code:
class SCT_LEX_ERLANG_IDNOISE(BaseLexer):
    STC_ERLANG_IDNOISE_DEFAULT = 1
    STC_ERLANG_IDNOISE_VARIABLE = 2
    STC_ERLANG_IDNOISE_ATOM = 3
    STC_ERLANG_IDNOISE_MODULE = 4
    STC_ERLANG_IDNOISE_KEYWORD = 5
    STC_ERLANG_IDNOISE_COMMENT = 6
    STC_ERLANG_IDNOISE_MACROS = 7
    STC_ERLANG_IDNOISE_NUMBER = 8

    def __init__(self, control):
        super(SCT_LEX_ERLANG_IDNOISE, self).__init__(control)
        self.typeFormatDict = {}
        self.typeFormatDict["other"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_DEFAULT
        self.typeFormatDict["variable"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_VARIABLE
        self.typeFormatDict["atom"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_ATOM
        self.typeFormatDict["module"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MODULE
        self.typeFormatDict["keyword"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_KEYWORD
        self.typeFormatDict["comment"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_COMMENT
        self.typeFormatDict["macros"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MACROS
        self.typeFormatDict["number"] = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_NUMBER

    def StyleText(self, event):
        start = self.control.GetEndStyled()
        end = event.GetPosition()
        line = self.control.LineFromPosition(start)
        start = self.control.PositionFromLine(line)
        text = self.control.GetTextRange(start, end)

        self.control.StartStyling(start, 0x1f)
        lastEnd = 0
        for type, start, end, value in getHighlightRules(text):
            style = SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_DEFAULT
            if start > lastEnd:
                self.control.SetStyling(start - lastEnd, style)
            if type in self.typeFormatDict:
                style = self.typeFormatDict[type]
            self.control.SetStyling(len(value), style)
            lastEnd = end

class CustomSTC(stc.StyledTextCtrl):
    def __init__(self, parent):
        super(CustomSTC, self).__init__(parent)
        self.custlex = SCT_LEX_ERLANG_IDNOISE(self)

        #self.SetKeyWords(0, kwlist)

        self.SetLexer(stc.STC_LEX_CONTAINER)
        self.EnableLineNumbers()

        self.StyleSetSpec(stc.STC_STYLE_DEFAULT, ColorSchema.formats["other"])
        self.StyleClearAll()
        self.StyleSetSpec(stc.STC_STYLE_LINENUMBER, ColorSchema.lineFont)
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_DEFAULT, ColorSchema.formats["other"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_VARIABLE, ColorSchema.formats["variable"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_ATOM, ColorSchema.formats["atom"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MODULE, ColorSchema.formats["module"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_KEYWORD, ColorSchema.formats["keyword"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_COMMENT, ColorSchema.formats["comment"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_MACROS, ColorSchema.formats["macros"])
        self.StyleSetSpec(SCT_LEX_ERLANG_IDNOISE.STC_ERLANG_IDNOISE_NUMBER, ColorSchema.formats["number"])

        # Event Handlers
        self.Bind(stc.EVT_STC_STYLENEEDED, self.OnStyle)

    def EnableLineNumbers(self, enable=True):
        """Enable/Disable line number margin"""
        if enable:
            self.SetMarginType(1, stc.STC_MARGIN_NUMBER)
            self.SetMarginMask(1, 0)
            self.SetMarginWidth(1, 35)
        else:
            self.SetMarginWidth(1, 0)

    def OnStyle(self, event):
        if self.custlex:
            self.custlex.StyleText(event)
        else:
            event.Skip()

rawDescription: wxPython StyleSetSpec and SetLexer not working?

description: WxPython StyleSetSpec and SetLexer not working


code: [''.join(map(str,tup)) for tup in product(range(3),repeat=4)]

rawDescription: How to list X numbers in base of Y?

description: List X numbers in base of Y


rawDescription: dictionary in python problem

description: Dictionary in python problem


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

data = np.random.random((5, 5))

fig = plt.figure()
ax = fig.add_axes([0, 0, 1, 1])
cnt = ax.contour(data)
ax.clabel(cnt)
ax.axis('off')

fig.savefig('test.png')

rawDescription: Completely removing axes from contour plot


code:
data = {'uid': ['restest'], 'mail': [''], 'givenName': ['Research'], 'cn': ['Research Test Account'], 'sn': ['Account']}
data
data = {k:v[0] for (k,v) in data.items()}
data

rawDescription: LDAP Python query and converting the appropriate dictionary


code:
n=2
r'(?=({}))'.format(r's\+'.join(r'\w+' for i in range(n)))

rawDescription: Check if string contains a certain amount of words of another string


code:
mylist = [['ANTT'],['XSOB']]
[list(l[0]) for l in mylist]

rawDescription: Split words in a nested list into letters


code:
from collections import defaultdict
dict3 = defaultdict(list)

for key in set().union(dict1, dict2):
  for dic in [dict1, dict2]:
    if key in dic:
      dict3[key] += dic[key]

rawDescription: Combining 2 dictionaries with common key


rawDescription: Matplotlib: How to make a contour plot?

description: Matplotlib: How to make a contour plot


rawDescription: Writing and reading complex numbers using numpy.savetxt and numpy.loadtxt


code:
def mp_handler():
    subdata = zip(data[0::2], data[1::2])
    for task1, task2 in subdata:
        p = multiprocessing.Pool(2)
        p.map(mp_worker, (task1, task2))

rawDescription: Dead simple example of using Multiprocessing Queue, Pool and Locking