code:
characters = []
for code in eventData:
    characters.append(chr(code))
myString = ''.join(characters)

rawDescription: python django decode array html codes to readable text

description: Python django decode array html codes to readable text


code:
f = open('file.txt', 'r+')
f.truncate()

rawDescription: how to erase the file contents of text file in Python

description: Erase the file contents of text file in Python


rawDescription: How can I find all substrings that have this pattern: some_word.some_other_word with python?

description: Find all substrings that have this pattern: some_word.some_other_word with python


code:
qs = QuestionAnswer.objects.filter(pk=12345)
qs[0] is qs[0]
bool(qs) # This forces evaluation of the entire queryset
qs[0] is qs[0]
qs[0].graded
qs[0].graded = 1
qs[0].save()
qs = QuestionAnswer.objects.filter(pk=12345)
qs[0].graded

rawDescription: Django objects.filter is not updating field but objects.get is


code:
from subprocess import check_call

check_call(["xcopy","/y",sourceuserdata, destinationuserdata])

rawDescription: python file overwriting with os module

description: Python file overwriting with os module


code:
with open("example.txt") as f:
    for line in f:
        key, value = line.strip().split("=")
        do_something(key,value)

rawDescription: Delineating a Read File

description: Delineating a Read File


code:
from __future__ import division  # For Python 2

def moving_averages(values, size):
    for selection in window(values, size):
        yield sum(selection) / size

rawDescription: How to calculate moving average in Python 3?

description: Calculate moving average in Python 3


rawDescription: UCSC BLAT output python

description: UCSC BLAT output python


code:
def input_thread():
    msvcrt.getch()
    thread.interrupt_main()

rawDescription: Making An "Any Key" Interuptable Python Timer


code:
output = np.array([ 40.3,  57.7,   2. ])

np.sum(output) == 100
True
round(np.sum(p*output),8) >= 24
True
round(np.sum(e*output),8) >= 76
True

rawDescription: Migrating from PuLP to Scipy

description: Migrating from PuLP to Scipy


rawDescription: Is python+pandas able to handle large amounts of data?


code:
def delta(r, dr):
    res = np.zeros_like(r)
    ma = (r >= 0.5*dr) & (r <= 1.5*dr)  # Create first mask
    res[ma] = (5-3*np.abs(r[ma])/dr[ma]-np.sqrt(-3*(1-np.abs(r[ma])/dr[ma])**2+1))/(6*dr[ma])
    ma = (r <= 0.5*dr)    # Create second mask
    res[ma] = (1+np.sqrt(-3*(r[ma]/dr[ma])**2+1))/(3*dr[ma])
    return res

rawDescription: Avoid using for loop in np.array operations. Python


code:
for json_dict in data:
    for key,value in json_dict.iteritems():
        print("key: {0} | value: {1}".format(key, value))

rawDescription: python json dict iterate {key: value} are the same

description: Python json dict iterate {key: value} are the same


code:
call_jill = Telephone.objects.filter(contact=jill) # if you already pulled jill
call_jill = Telephone.objects.filter(contact__nickname='jill')

rawDescription: How does a model relate to another model via Foreignkey?


code: grandparent/g/parent/p/child

rawDescription: Endpoints Proto Datastore - Path {requirement} variable used for keys randomly breaks


code: threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

rawDescription: Overriding __init__ in threading.Thread

description: Overriding __init__ in threading.Thread


code:
def my_import(name):
    components = name.split('.')
    mod = __import__(components[0])
    for comp in components[1:]:
        mod = getattr(mod, comp)
    return mod

rawDescription: How to dynamically load a Python class

description: Dynamically load a Python class


code: return (False, result)

rawDescription: Returning success or failure as well as result from function


code:
b = []
for i in range(a.shape[0]):
    for j in range(a.shape[1]):
        for k in range(a.shape[2]):
            b.append(a[i,j,k])

rawDescription: Python, from matrix to array

description: Python, from matrix to array


code:
M = np.vstack( (np.hstack((a, b)), np.hstack((z, c))) )
M

rawDescription: Combining Numpy Arrays in Blockwise Form


code: '         a         b         c         d         e'

rawDescription: How do i format the ouput of a list of list into a textfile properly?

description: Format the ouput of a list of list into a textfile properly


code:
import pickle

def fruit():
        try:
            with open('fruits.pickle', 'rb') as f:
                items = pickle.load(f)
        except (ValueError,IOError) as e:
            print(e)
            items =  {'Banana': {'mon': [14], 'count': 14}, 'Apple': {'mon': [10], 'count': 10}, 'Orange': {'mon': [23], 'count': 23}, 'Watermelon': {'mon': [54], 'count': 54}}
        fruit_t = input("Please type in the name of the fruit: ")
        fruit_n = int(input("Please type in the amount of the fruit: "))
        if fruit_t in items:
            items[fruit_t]["mon"].append(fruit_n)
            if items[fruit_t]["count"] < fruit_n:
                items[fruit_t]["count"] = fruit_n
        else: # else add new fruit
            items[fruit_t] = {"mon":[fruit_n],"count":fruit_n}
        with open('fruits.pickle', 'wb') as f:
            pickle.dump(items, f)
        print(items)

rawDescription: CSV how to find the value, and edit its value


code:
for row in tree.xpath("//*[@class='asdf']"):
    print("row: ", row.text_content())

rawDescription: proper xpath to roll up text of children

description: Proper xpath to roll up text of children


code:
"in" in ["in", "out"]
"in" in ["indigo", "violet"]

rawDescription: Use and meaning of "in" in an if statement in python


code:
fig, axes = plt.subplots(ncols=2, sharey=True)
plt.setp(axes, title='Test')
fig.suptitle('An overall title', size=20)

fig.tight_layout()
fig.subplots_adjust(top=0.9)

plt.show()

rawDescription: GridSpec with shared axes in Python

description: GridSpec with shared axes in Python


code:
a2 = np.memmap('a.npy', dtype=np.float64, mode='r', shape=(2, 3))
a2

rawDescription: Python memory mapping

description: Python memory mapping


code:
def style_ax(ax):
   ax.legend(loc='best')
   ax.set_yscale('log')
   ax.set_xscale('log')

rawDescription: Matplotlib subplots: legend and axis-scale


code:
vowels = 0
consonants = 0
total = 0

rawDescription: Multiple-Target Assignments

description: Multiple-Target Assignments


code:
from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^register/$', views.Register, name='register'),

    url(r'^login/$', views.Login, name='login'),
    url(r'^logout/$', views.Logout, name='logout'),
]

rawDescription: Django registration form on startpage, without redirect to loginpage


code:
from matplotlib import pyplot as plt
plt.ion()
plt.plot([1,2,3])
h = plt.ylabel('y')
h.set_rotation(0)
plt.draw()

rawDescription: How to print Y axis label horizontally in a matplotlib / pylab chart?

description: Print Y axis label horizontally in a matplotlib / pylab chart


code:
class MyInt(int):
    pass
mi = MyInt(6)
mi.foo = 'bar'

rawDescription: If everything is an object, why can't I add attributes to some?


code:
forms = [f for f in br.forms()]
forms[1].controls[0].name
[c.name for c in forms[3].controls]

rawDescription: How do you select choices in a form using Python?

description: Select choices in a form using Python


code:
original = list(range(10))
modified = list(original)
modified[5] = "a"
modified[6] = "a"

def without_repeated(original, modified):
    seen = set()
    for (o, m) in zip(original, modified):
        if m not in seen:
            seen.add(m)
            yield o, m

original, modified = zip(*without_repeated(original, modified))

print(original)
print(modified)

rawDescription: Deduping a complex list using a simplified copy of itself


code:
class SomeClass(object):

    def __init__(self):
        self.member_var_1 = "some value"
        self.member_var_2 = "some other value"

    def method1(self):
        print("Could use any member variables here:", self.member_var_1)
        self.member_var_1 = "new value"

    def method2(self):
        print("If this method is called after method1, we will get new value:", self.member_var_1)

# create object/instance of SomeClass
obj = SomeClass()

# could also use member variables like below
obj.member_var_1 = "new value modified outside method"

# similar to how we call the method of a class
obj.method2()

rawDescription: Global variables, member variables and instance variables in Python


code:
all( df['vwap_pandas'] == df['vwap_numpy'] )
all( df['vwap_pandas'] == df['vwap_numba'] )

rawDescription: Pandas Efficient VWAP Calculation

description: Pandas Efficient VWAP Calculation


code: [b.taste for b in beers if b.name==name]

rawDescription: How to access an object in a list by property?

description: Access an object in a list by property


code: clusters = dict(zip(lables, model[1]))

rawDescription: Python Relating k-means cluster to instance


code: final = [(tag, word.lower()) for word, tag in a]

rawDescription: Python list comprehension. Alternative/Better way to write this code?


code:
import os
os.utime('file', (mtime, mtime))

rawDescription: Extracting tar file with original time stamp


rawDescription: Multiplication on slice of pandas dataframe


code: x = (lambda result=some_very_complex_computation(y): [(t, result) for t in z])()

rawDescription: Python functional evaluation efficiency

description: Python functional evaluation efficiency


code:
from operator import attrgetter
min_num = min(li,key=attrgetter('number'))

rawDescription: Python min function with a list of objects


code:
import re

# see https://docs.python.org/2/howto/regex.html
year_month_pattern = re.compile(r"""
.*/
(?P<month>.*)
/
(?P<year>\d*)
:.*
""", re.VERBOSE)

def year_month(s):
    res = year_month_pattern.match(s)
    if res is None:
        return None
    try:
        return int(res.group('year')), res.group('month')
    except ValueError:
        pass

rawDescription: Python 2.7 - Find the number of web server hits


code:
# This takes your data and creates a new array that is (T, V-1, 2, 3)
lstLines = np.concatenate((Spar_Res[:, :-1, None, :],
                           Spar_Res[:,  1:, None, :]), axis=2)
# This reshapes the array to be (T * (V - 1), 2, 3)
lstLines = lstLines.reshape(-1, 2, 3)

rawDescription: Line construction with double iteration

description: Line construction with double iteration


code: x = raw_input()

rawDescription: Why isn't my while loop, looping?

description: Why isn't my while loop, looping


code:
a = [None, None, None]
next((item for item in a if item is not None), 'All are Nones')

rawDescription: Getting the first non None value from list


code: ['i386-linux-gnu_xorg_extra_modules', 'nvctrl_include', 'template-dkms-mkdsc', 'run', '1', 'conf.d', 'conf.d']

rawDescription: Different results achieved using Python's os.walk function and ls command


code:
def grade(i):
    if i<40: return "Fail"
    if i>75: return "A++"
    if i>50: return "A"

rawDescription: Convert numbers to grades in python list


code: right = DataFrame(bf.values [1::2], index=bf.index[1::2])

rawDescription: How can I join 2 rows in a dataframe into 1 row in a new one?

description: Join 2 rows in a dataframe into 1 row in a new one


code:
import requests
import json

url = 'https://euw.api.pvp.net/api/lol/euw/v2.5/league/by-summoner/266302,29338851,44112476,24693443,42900539,32556822,25575027,27677126,24648065,19083702/entry?api_key=2c0543ab-aeca-476d-8276-a5c23748898c'
response = requests.get(url)
data = json.loads(response.text)

for ids in data:
    print(data[ids][0]['tier'])

rawDescription: How to parse this please i'm stuck

description: Parse this please i'm stuck


code:
hSizer = wx.BoxSizer(wx.HORIZONTAL)
hSizer.Add(mySizer, 0, wx.CENTER)

rawDescription: Puting a BoxSizer in the middle of its panel


rawDescription: python3, how to repeat a list of character

description: Python3, how to repeat a list of character


code:
d = dict(abspath = os.path.abspath,
         dirname = os.path.dirname)
...
a = d['abspath'](somepath)
d = d['dirname'](somepath)

rawDescription: Can I define a scope anywhere in Python?

description: Define a scope anywhere in Python


code:
class FilterableList(list):
    def __getattr__(self, name):
        # assume non-existing attributes are boolean filters
        return [elem for elem in self if getattr(elem, name)]

rawDescription: Add attribute to class list to return all objects with specific attribute


code:
['literature', 'general education', 'note', ' see approved list']
['social-cultural elective', 'general education', 'note', ' see approved']

rawDescription: Splitting with different delimiters

description: Splitting with different delimiters


code:
def get_stat_feats(data, winSize):
    from scipy.ndimage import generic_filter
    import numpy as np
    mean = lambda x: x.mean()
    std = lambda x: x.std()

    meanData = generic_filter(data, mean, size=winSize)
    stdData = generic_filter(data, std, size=winSize)

    return meanData, stdData

rawDescription: Optimizing windowed feature generation from input image in Python


code:
password = "bar" if authenticate else None
otherarg = "zed" if authenticate else None
connect(username="foo", password=password, otherarg=otherarg)

rawDescription: Pythonic way to pass keyword arguments on conditional


code:
sigma_nums = []
for n in range(1, 23):
    sigma_nums.append(sigma_num(n))
avg_sigma_num = sum(sigma_nums)/len(sigma_nums)

rawDescription: Shortening a Python program

description: Shortening a Python program


code:
from base64 import b64encode, b64decode
from collections import OrderedDict
from datetime import datetime
import uuid
from flask import json
from flask._compat import text_type, iteritems
from flask.debughelpers import UnexpectedUnicodeError
from markupsafe import Markup
from werkzeug.http import http_date, parse_date

class TaggedJSONSerializer(object):
    def dumps(self, value):
        def _tag(value):
            if isinstance(value, tuple):
                return {' t': [_tag(x) for x in value]}
            elif isinstance(value, uuid.UUID):
                return {' u': value.hex}
            elif isinstance(value, bytes):
                return {' b': b64encode(value).decode('ascii')}
            elif callable(getattr(value, '__html__', None)):
                return {' m': text_type(value.__html__())}
            elif isinstance(value, list):
                return [_tag(x) for x in value]
            elif isinstance(value, datetime):
                return {' d': http_date(value)}
            elif isinstance(value, OrderedDict):
                return {'OrderedDict': [[k, _tag(v)] for k, v in iteritems(value)]}
            elif isinstance(value, dict):
                return dict((k, _tag(v)) for k, v in iteritems(value))
            elif isinstance(value, str):
                try:
                    return text_type(value)
                except UnicodeError:
                    raise UnexpectedUnicodeError(u'A byte string with '
                        u'non-ASCII data was passed to the session system '
                        u'which can only store unicode strings.  Consider '
                        u'base64 encoding your string (String was %r)' % value)
            return value
        return json.dumps(_tag(value), separators=(',', ':'))

    def loads(self, value):
        def object_hook(obj):
            if len(obj) != 1:
                return obj
            the_key, the_value = next(iteritems(obj))
            if the_key == ' t':
                return tuple(the_value)
            elif the_key == ' u':
                return uuid.UUID(the_value)
            elif the_key == ' b':
                return b64decode(the_value)
            elif the_key == ' m':
                return Markup(the_value)
            elif the_key == ' d':
                return parse_date(the_value)
            elif the_key == 'OrderedDict':
                return OrderedDict(the_value)
            return obj
        return json.loads(value, object_hook=object_hook)

rawDescription: Flask session attribute loses typing after initial load


code: from functools import reduce

rawDescription: Python: Accessing elements of multi-dimensional list, given a list of indexes


code:
import scipy as sp

#define some dummy p1 and p2
p1 = lambda y: 3*y+2
p2 = lambda y: -4*y-4

#define p_{xi1+xi2}
pplus = lambda x: sp.integrate.quad(lambda u,x=x: p1(u)*p2(x-u),0,x)[0]
#define p_{xi1/xi2}
pdivide = lambda x: sp.integrate.quad(lambda u,x=x: u*p1(u)*p2(u/x),0,sp.minimum(x,1))[0]/x**2

#use it
x = 0.2
outplus = pplus(x)
outdivide = pdivide(x)

rawDescription: How to compute integrals dependent upon two variables with SciPy?

description: Compute integrals dependent upon two variables with SciPy


code:
if word not in (1,2,7,8,9,10):
    print('invalid')

rawDescription: How to format multiple 'or' conditions in an if statement in Python

description: Format multiple 'or' conditions in an if statement in Python


code: bar = [int(i) for i in foo]

rawDescription: Isolating the elements of a row in python


code:
import maya.OpenMayaUI as OpenMayaUI
import maya.OpenMayaRender as OpenMayaRender
import maya.cmds as cmds

def setCamera(*args):
    view = OpenMayaUI.M3dView.active3dView()

    # Get a renderer, then a function table
    glRenderer = OpenMayaRender.MHardwareRenderer.theRenderer()
    glFT = glRenderer.glFunctionTable()

    view.beginGL()

    glFT.glPushAttrib(OpenMayaRender.MGL_LINE_BIT)
    glFT.glLineWidth(5.0)

    glFT.glBegin(OpenMayaRender.MGL_LINES)

    glFT.glColor3f(1.0, 0.0, 0.0)
    glFT.glVertex3f(0.0, 0.0, 0.0)
    glFT.glVertex3f(3.0, 0.0, 0.0)

    glFT.glColor3f(0.0, 1.0, 0.0)
    glFT.glVertex3f(0.0, 0.0, 0.0)
    glFT.glVertex3f(0.0, 3.0, 0.0)

    glFT.glColor3f(0.0, 0.0, 1.0)
    glFT.glVertex3f(0.0, 0.0, 0.0)
    glFT.glVertex3f(0.0, 0.0, 3.0)

    glFT.glEnd()

    glFT.glPopAttrib()

    view.endGL()

if __name__ == '__main__':

    panel = cmds.getPanel(withFocus=True)
    callBack = OpenMayaUI.MUiMessage.add3dViewPostRenderMsgCallback(
        panel, setCamera)

    view = OpenMayaUI.M3dView.active3dView()
    view.refresh(True, True)

rawDescription: OpenGL Python Maya API drawing without MPxLocator plugin


code:
deny = ['login', 'intro', 'candidate', 'referral', 'reminder', 'search']
allow = ['jobs']

rules = (Rule (SgmlLinkExtractor(deny = deny,
                                 allow=allow,
                                 restrict_xpaths=('*')),
                                 callback="parse_items",
                                 follow= True),)

rawDescription: scrapy spider bypass deny my rules

description: Scrapy spider bypass deny my rules


code:
from matplotlib.collections import PatchCollection
from matplotlib.patches import Polygon
import shapely

def plot_polygon_collection(ax, geoms, values=None, colormap='Set1',  facecolor=None, edgecolor=None,
                            alpha=0.5, linewidth=1.0, **kwargs):
    """ Plot a collection of Polygon geometries """
    patches = []

    for poly in geoms:

        a = np.asarray(poly.exterior)
        if poly.has_z:
            poly = shapely.geometry.Polygon(zip(*poly.exterior.xy))

        patches.append(Polygon(a))

    patches = PatchCollection(patches, facecolor=facecolor, linewidth=linewidth, edgecolor=edgecolor, alpha=alpha, **kwargs)

    if values is not None:
        patches.set_array(values)
        patches.set_cmap(colormap)

    ax.add_collection(patches, autolim=True)
    ax.autoscale_view()
    return patches

rawDescription: GeoPandas plotting - any way to speed things up?


code: tup.append(sum(float(x) for x in t[1][1:6:2]))

rawDescription: Sum item inside a tuple

description: Sum item inside a tuple


code:
env = Environment()
SConscript('source/SConscript_obj', variant_dir='object',
           duplicate=0, exports='env')
SConscript('source/SConscript', variant_dir='bin',
           duplicate=0, exports='env')

rawDescription: scons: objects, sources, executables, all in separate directories

description: Scons: objects, sources, executables, all in separate directories


code:
from pyspark.sql.types import *
# all DataFrame rows are StructType
# can create a new StructType with combinations of other types
schema = StructType([
    StructField("column_1", StringType(), True),
    StructField("column_2", IntegerType(), True)
    # etc.
])
df = sqlContext.createDataFrame(rdd, schema=schema)

rawDescription: saving a list of rows to a Hive table in pyspark

description: Saving a list of rows to a Hive table in pyspark


code: subset = table[np.array([i in id_list for i in table.IDs])]

rawDescription: Numpy table - advanced multiple criteria selection


code:
def rebin(a, shape):
    sh = shape[0],a.shape[0]//shape[0],shape[1],a.shape[1]//shape[1]
    return a.reshape(sh).mean(-1).mean(1)

rawDescription: resize with averaging or rebin a numpy 2d array

description: Resize with averaging or rebin a numpy 2d array


code:
l = ['Hi, hello', 'hi mr 12345', 'welcome sir']
d = dict()
for item in l:
    for word in item.split():
            d.setdefault(word, list()).append(item)

rawDescription: Search list: match only exact word/string


code:
def find_overlapping(sequence):
    return re.findall(
    """(?=        # Assert that the following regex could be matched here:
     (            # Start of capturing group number 1.
      AAA         # Match AAA.
      (?:         # Start of non-capturing group, matching...
       [AGCT]{3}  # a DNA triplet
      )*?         # repeated any number of times, as few as possible.
      CCC         # Match CCC.
     )            # End of capturing group number 1.
    )             # End of lookahead assertion.""",
    sequence, re.VERBOSE)

rawDescription: Python Regular Expressions: How to repeat a repeat of a pattern?


code:
try:
    # Python 2.6-2.7
    from HTMLParser import HTMLParser
except ImportError:
    # Python 3
    from html.parser import HTMLParser

h = HTMLParser()
print(h.unescape('£682m'))

rawDescription: Decode HTML entities in Python string?

description: Decode HTML entities in Python string


code:
def last_one(lst):
    lst[1] = 1

df[df.x != df.y].B.apply(last_one)

rawDescription: How do I add conditionally to a selection of cells in a pandas dataframe column when the the column is a series of lists?

description: Add conditionally to a selection of cells in a pandas dataframe column when the the column is a series of lists


code: regex = re.compile(r'\b('+'|'.join(highlight_terms)+r')s?', flags=re.IGNORECASE | re.VERBOSE)  # note the ? instead of {0, 1}. It has the same effect

rawDescription: Finding and substituting a list of words in a file using regex in Python


code:
r = r"((\w+)(\s?))*"
s = "This is a regular sentence."
import re
m = re.match(r, s)
m.group(0)

rawDescription: Confusing Behaviour of regex in Python

description: Confusing Behaviour of regex in Python


code:
def my_dynamic_form(select_field_count=20):
    class F(MyBaseForm):
        pass
    for i in range(select_field_count):
        setattr(F, 'f%d' % i, SelectField('F%d' % i, coerce=int,
                                        validators=[validators.optional()],
                                        choices=[(1, 'A'), (2, 'B'), (3, 'C'),
                                                 (4, 'D'), (5, 'E'), (6, 'FX'),
                                                 (7, 'na')]))
    return F

rawDescription: WTForms , form with more than one SelectField? Does SelectFieldArray exists?


code:
from multiprocessing.dummy import Pool # use threads
from subprocess import call

def run(i):
    with open('log%d.txt' % i, 'wb') as file:
        return call(["cmd", str(i)], stdout=file)

return_codes = Pool(4).map(run, range(10)) # run 10 subprocesses, 4 at a time

rawDescription: Print multithread subprocess

description: Print multithread subprocess


code:
import pydoc
def wrappedHelpText (wrappedFunc):
    def decorator (f):
         f.__doc__ = 'This method wraps the following method:\n\n' + pydoc.text.document(wrappedFunc)
         return f
    return decorator

@wrappedHelpText(worker_function)
def wrapper_function(**args):
    worker_function(**args)

rawDescription: How to override default help message on python function

description: Override default help message on python function


code:
from mechanize import Browser

br = Browser()
r = br.open('http://bac.menara.ma/ministere')
br.select_form(nr=0)
# print br.form    # displays form fields and target URL
br.form['txt1'] = '12345678'
r = br.submit()
html = r.read()
assert 'Nom ; ELOUARDI ASSIA' in html

rawDescription: Sending Post method manually using Python


code:
# unroll the kernel (again, can be done directly when generating `ker`)
ker = np.roll(ker, 50, 0)
ker = np.roll(ker, 50, 1)

from scipy.signal import fftconvolve
dd = fftconvolve(og, ker, mode='same')

rawDescription: Python 2D convolution without forcing periodic boundaries


code:
next(i for i,x in enumerate(a) if x > 1.1)
next(i for i,x in enumerate(a) if x > 1.3)

rawDescription: Getting the index of a list for the first value that satisfies a criterion


rawDescription: How to programatically get the SDK version in Google Appengine (Python)?

description: Programatically get the SDK version in Google Appengine (Python)


code:
import dis
dis.dis(foo)

rawDescription: Does Python import statement also import dependencies automatically?


code: os.path.join(os.getcwd(), filename)

rawDescription: Why does os.path.join throw away arguments?


code: df = pd.read_csv('foo.csv', header=[0, 1, 2], index_col=[0, 1], tupleize_cols=False, sep='\s*,\s+')

rawDescription: Read csv file with many named column labels with pandas


code:
first_row = df.index.get_loc(first[0])
last_row = df.index.get_loc(last[0])
if first_row == last_row:
    result = df.loc[first[0], first[1]: last[1]].min()
elif first_row < last_row:
    first_row_min = df.loc[first[0], first[1]:].min()
    last_row_min = df.loc[last[0], :last[1]].min()
    middle_min = df.iloc[first_row + 1:last_row].min().min()
    result = min(first_row_min, last_row_min, middle_min)
else:
    raise ValueError('first row must be <= last row')

rawDescription: Pandas DataFrame: How to natively get minimum across range of rows and columns


code: "a^Mb"

rawDescription: Mulitple Lines in a single Excel cell

description: Mulitple Lines in a single Excel cell


code:
class ProjectComment(RewardBase):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name="projects")

class User (AbstractBaseUser):
    email = models.EmailField()

class Profile(models.Model):
    bio = models.CharField(max_length=80)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, unique=True, related_name="profile")

rawDescription: Using Django ORM to get a related model in a method


code:
import types

class B(object):
    def __init__(self):
        print("base")

class C(B):
    def dummy(self): __class__

def __init__(self):
    print('calling __init__')
    super().__init__()

def MakeCodeObjectWithClass(c):
    """
    Return a copy of the code object c, with __class__ added to the end
    of co_freevars.
    """
    return types.CodeType(c.co_argcount, c.co_kwonlyargcount, c.co_nlocals,
            c.co_stacksize, c.co_flags, c.co_code, c.co_consts, c.co_names,
            c.co_varnames, c.co_filename, c.co_name, c.co_firstlineno,
            c.co_lnotab, c.co_freevars + ('__class__',), c.co_cellvars)

new_code = MakeCodeObjectWithClass(__init__.__code__)
old_closure = __init__.__closure__ or ()
C.__init__ = types.FunctionType(new_code, globals(), __init__.__name__,
    __init__.__defaults__, old_closure + (C.dummy.__closure__[0],))

if __name__ == '__main__':
    c = C()

rawDescription: How to make super() work by manually filling the __class__ cell?

description: Make super() work by manually filling the __class__ cell


rawDescription: Zero padding between values in Python

description: Zero padding between values in Python


code:
import getCamera

getCamera.main(arg1, arg2)

rawDescription: how to execute a python script file with an argument from inside another python script file

description: Execute a python script file with an argument from inside another python script file


code: list_of_people = [p for i, p in enumerate(list_of_people) if (i + 1) % steps]

rawDescription: Controlling the flow of for loop in python


rawDescription: Python Function to return a list of common letters in first and last names


code:
from tkinter import *

class AT_content_calculator:

    def dna_sequence(self):
        self.dna_sequence = ()

    def __init__(self, master):
        frame_1 = Frame(master, width=700, height=700)
        frame_1.pack()
        frame_1.pack_propagate()
        self.entry_1 = Entry(frame_1)
        self.entry_1.pack()
        self.varoutput_1 = StringVar()
        self.output_1 = Label(frame_1, textvariable=self.varoutput_1)
        self.output_1.pack()
        self.button_1 = Button(frame_1, text="Calculate", command=self.at_calculate)
        self.button_1.pack()
        self.button_2 = Button(frame_1, text="Quit", command=frame_1.quit)
        self.button_2.pack()

    def at_calculate(self):
        self.dna_sequence = self.entry_1.get()
        self.total_bases = len(self.dna_sequence)
        self.a_bases = self.dna_sequence.count("A")
        self.b_bases = self.dna_sequence.count("T")
        self.at_content = (self.a_bases + self.b_bases) / self.total_bases
        print(self.at_content)
        self.varoutput_1.set(self.at_content)

root = Tk()
b = AT_content_calculator(root)
root.mainloop()

rawDescription: Can't find the AT content in percentage (tkinter, classes)


rawDescription: How does sympy calculate pi?

description: How does sympy calculate pi


rawDescription: Scripting Python for Linux commands

description: Scripting Python for Linux commands


code:
[
    {
        'comment': '/**\n* @param string username   required \n* @param string password   required\n* @param string first_name required\n* @param string last_name  required\n* @param string email      required\n*/\n',
        'path': '/register',
        'handler': 'UserController@Register',
        'method': 'POST'
    },
    {
        'comment': '/**\n* @param string username   required \n* @param string password   required\n* @param string first_name required\n* @param string last_name  required\n* @param string email      required\n*/\n',
        'path': '/login',
        'handler': 'UserController@login',
        'method': 'POST'
    }
]

rawDescription: Python 3 read file by part

description: Python 3 read file by part


code:
# res = requests.post.....
data = res.json()  # get response as parsed json (will return a dict)
auth_token = data.get('access token')

rawDescription: Using Python to test HTTP APIs

description: Using Python to test HTTP APIs


code:
import os
os.path.join()

rawDescription: Read files based on dates in their names in Python


code: zip(*B)

rawDescription: Count the occurence of specific number from column // convert column data to list


rawDescription: Pandas days between in a single column

description: Pandas days between in a single column


code:
import re
match = re.match( '(disc|dis|se|oti)(\\d+)\\s', line)

rawDescription: How can I check for specific strings in python?

description: Check for specific strings in python


code:
from Crypto.Cipher import AES
import base64

MASTER_KEY="Some-long-base-key-to-use-as-encyrption-key"

def encrypt_val(clear_text):
    enc_secret = AES.new(MASTER_KEY[:32])
    tag_string = (str(clear_text) +
                  (AES.block_size -
                   len(str(clear_text)) % AES.block_size) * "\0")
    cipher_text = base64.b64encode(enc_secret.encrypt(tag_string))

    return cipher_text

rawDescription: Basic encrypt() and decrypt() function

description: Basic encrypt() and decrypt() function


code:
sentence = 'The cat sat on the mat.'
c = 0
for letter in sentence:
    if letter == 'a':
        c += 1
print(c)

rawDescription: How can i change a string that counts how many letters in a sentence into counting the occurence of one letter?

description: Change a string that counts how many letters in a sentence into counting the occurence of one letter


code:
Entry.objects.filter((Q(start__gte=appointment.start) & Q(start__lt=appointment.end)) |
   (Q(end__gt=appointment.start) & Q(end__lte=appointment.end)))

rawDescription: Django complex queries

description: Django complex queries


code:
#!/bin/env python

col = 2

values = []
with open('csv.csv', 'r') as csv:
    for line in csv.readlines():
        elements = line.strip().split(',')
        values.append(int(elements[col]))

csum = sum(values)
cavg = sum(values)/len(values)
print("Sum of column %d: %f" % (col, csum))
print("Avg of column %d: %f" % (col, cavg))

rawDescription: Adding up values in a specific column in a CSV file (in Sage Notebook)


code:
class A(object):

    a1 = ProtectedAttribute('__a1')

    def __init__(self, **kwargs):
        self.a1 = kwargs.get("some_value", -1)

rawDescription: Writing a function to define class properties


code:
def foo(cls):
    pass
foo = synchronized(lock)(foo)
foo = classmethod(foo)

rawDescription: Decorate a function after it is defined?

description: Decorate a function after it is defined


code:
# Take a sum of logarithms of rates over the window
log_sum = sum(log(col("rate") + 1)).over(wr)

# Take sum of logs and exponentiate to go back to original space
cumulative_rate = exp(log_sum).alias("cumulative_rate")

# Find base population for each group
base_population = first("population").over(w).alias("base_population")

# Prepare final column (base population * cumulative product of rates)
current_population = coalesce(
     # This is null for the first observation in a group
     cumulative_rate * base_population,
     # so we provide population as an alternative
     col("population")
).alias("current_population")

rawDescription: How to calculate a column in a Row using two columns of the previous Row in Spark Data Frame?

description: Calculate a column in a Row using two columns of the previous Row in Spark Data Frame


code:
import numpy as np
from scipy.integrate import odeint
from matplotlib import pyplot as plt
T = np.arange(1000)
xarr = odeint(lambda t, x: x / (x**2 + t**2)**1.5, 1, T)
plt.plot(T, xarr)
plt.show()

rawDescription: Speed issues, python not responding: Solving ODEs


code:
def DELETEMIN( A ):
        if A.leftchild is None:
                return A.element, A.rightchild
        else:
                return DELETEMIN( A.leftchild )

rawDescription: Python classes -- mutability

description: Python classes -- mutability


code:
from itertools import product

# pair info for each image with info of every image from another dictionary
for (fn1,lst1), (fn2,lst2) in product(dict1.iteritems(), dict2.iteritems()):
    # assume all lists has the same order of elements
    for string_value1, string_value2 in zip(lst1, lst2):
        compute(string_value1, string_value2)

rawDescription: Python: Iterate over two dictionaries that has lists as its values


code:
new = pd.DataFrame(
    {'a' : [   (df.loc[Ind[0], 'x1'], df.loc[Ind[0], 'x2'], df.loc[Ind[0], 'x3'], df.loc[Ind[0], 'x4'], df.loc[Ind[0], 'x5'])
                for Ind in idx
            ],
     'b' : [   (df.loc[Ind[1], 'x1'], df.loc[Ind[1], 'x2'], df.loc[Ind[1], 'x3'], df.loc[Ind[1], 'x4'], df.loc[Ind[1], 'x5'])
                for Ind in idx
            ]
    },
    index = idx
)

rawDescription: Looping to calculate False Acceptance Rate (FAR) in python


code: set(['test','sentence'])&set(['this is my sentence'])

rawDescription: Fastest way to check does string contain any word from list


code:
class partialAP(abc.abstractproperty):
    def getter(self, func):
        if getattr(func, '__isabstractmethod__', False) or getattr(self.fset, '__isabstractmethod__', False):
            p = partialAP(func, self.fset)
        else:
            p = property(func, self.fset)
        return p

    def setter(self, func):
        if getattr(self.fget, '__isabstractmethod__', False) or getattr(func, '__isabstractmethod__', False):
            p = partialAP(self.fget, func)
        else:
            p = property(self.fset, func)
        return p

rawDescription: Inheriting setter, overwriting getter in python abstract class


code:
points = np.array([[1,2,3],[4,5,6]])
info = np.array([1, 2])
output = np.hstack([points, info.reshape(2,1)])

rawDescription: Numpy built in elementwise append

description: Numpy built in elementwise append


code:
def clean(text):
    result=""
    last=""
    for c in text:
        if c!=last:
            last = c
            result += c
    return result

rawDescription: Contradictory outputs in simple recursive function


code:
def redirect_dest(fallback):
    dest = request.args.get('dest')
    try:
        dest_url = url_for(dest)
    except:
        return redirect(fallback)
    return redirect(dest_url)

@app.route("/login", methods=["GET", "POST"])
def login():
    ...
    if user_is_logged_in:
        flash("Logged in!")
        return redirect_dest(fallback=url_for('general.index'))
    else:
        flash("Sorry, but you could not log in.")
        return render_template("login.html")

rawDescription: How do I pass through the "next" URL with Flask and Flask-login?

description: Pass through the "next" URL with Flask and Flask-login


code:
def show_lists(request):

    username = request.user.username
    lists_under_control = [la.mailingList for la in
                           ListAdministrator.objects.filter(username=username)]

    mailing_lists = list(MailingList.objects.all())
    for mailing_list in mailing_lists:
        mailing_list.user_may_delete = (mailing_list in lists_under_control)

    return render(request, 'app/mailing_lists.html',
                           {'mailing_lists': mailing_lists})

rawDescription: Django permission check in template based on current user


code:
for animal in zoo.getAnimals():
    add(animal)

rawDescription: Create set of Python functions

description: Create set of Python functions


code: longest = max((L for L in lol if any(lt==w.lower() for w in L)), key=len)

rawDescription: Project Gutenberg Python problem?

description: Project Gutenberg Python problem


code:
#Now make a pie chart
df.country.value_counts().plot(kind='pie')
plt.axis('equal')
plt.title('Number of appearances in dataset')

rawDescription: Unable to pie-plot my data in pandas python


code: a, b, mean = np.linalg.lstsq(A, X)[0]

rawDescription: Loops to minimize function of arrays in python


code:
import re
with open(filename, 'r') as f:
    inBetween = re.search(r"Marker 2(.*)Marker 3", f.read(), re.S | re.I).group()

rawDescription: How do I grab text from a text file within a boundary of line numbers pythonically?

description: Grab text from a text file within a boundary of line numbers pythonically


code:
from functools import partial
from multiprocessing import Pool

def dist_mp(centroid, target):
    return target, edit_distance(centroid, target)

def main():
    # ...
    pool = Pool() # use all CPUs
    for target, d in pool.imap_unordered(partial(dist_mp, centroid),
                                         sequence_list[1:]):
        results_dict[centroid][target] = d
    pool.close()
    pool.join()

if __name__ == "__main__":
    main()

rawDescription: Python multiprocessing edit-distance calculation


code:
result = Element(element, None)
self.tail.next = result
self.tail = result

rawDescription: Issue with Python implementation of assignment chaining


code:
class myclass():
    a = 1
    def __init__(self):
        self.b = 2
x = myclass()
y = myclass()
x.a
myclass.a = 2   # modify the class variable
x.a
y.a
x.b = 3         # modify the instance variable
x.b
y.b
x.a = 4         # create new local instance variable a
x.a
y.a

rawDescription: How to change all objects of a class at once?

description: Change all objects of a class at once


rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
class JSON_Namespace(object):
    def __init__(self, data_dict):
        self.__dict__.update(data_dict)
    @classmethod
    def load_from_json(cls, json_string):
        return json.loads(json_string, object_hook=cls)

rawDescription: Parameterizing Python's json.loads() object_hook to a Factory Method


code:
class myobj(object):
    def __init__(self):
        self.count = 0
    @staticmethod
    def addOne(n):
        return n + 1
    def addOneTimesTwo(self, n):
        return self.addOne(n) * 2
    def __getitem__(self, attrname):
        "Allows attributes to accessed as if they were key/value pairs in a map."
        return getattr(self, attrname)

myObj = myobj()
assert myObj["addOneTimesTwo"](1) == 4

rawDescription: Effective closures in python

description: Effective closures in python


code:
df = DataFrame(np.random.randn(5,3),columns=list('ABC'))
df

rawDescription: change Pandas dataframe column order in place

description: Change Pandas dataframe column order in place


code: a, b, c = func_1(a, b, c)

rawDescription: Python: variables not cumulative passing through functions


code:
b = np.array([0,0,1])
dt = np.dtype((np.void, arr.dtype.itemsize * arr.shape[1]))
(arr.view(dt) == b.view(dt)).reshape(-1)

rawDescription: Get only those elements of array that match all elements of test array?


rawDescription: How to melt/stack a 2-factorial multivariate DataFrame from wide to long format?

description: Melt/stack a 2-factorial multivariate DataFrame from wide to long format


code:
_period_context_fmt = r"""
    \S*                          # some word material
    %(SentEndChars)s             # a potential sentence ending
    (?=(?P<after_tok>
        %(NonWord)s              # either other punctuation
        |
        \s+(?P<next_tok>\S+)     # or whitespace and some other token
    ))"""

rawDescription: Preserve empty lines with NLTK's Punkt Tokenizer


code:
def is_prime_mers(step, result = None, modulo = None):
    result = 4 if result is None else result
    modulo = cunt_mersenne(step) if modulo is None else modulo

rawDescription: Initialize parameter in recursive function in Python


code:
ax = s.hist()  # s is an instance of Series
fig = ax.get_figure()
fig.savefig('/path/to/figure.pdf')

rawDescription: save a pandas.Series histogram plot to file

description: Save a pandas.Series histogram plot to file


code:
cross_val_score(LinearRegression(), X, y, cv=threefold)
gs = GridSearchCV(LinearRegression(), {}, cv=threefold, verbose=3).fit(X, y)

rawDescription: How is scikit-learn GridSearchCV best_score_ calculated?


rawDescription: Scrapy parse javascript

description: Scrapy parse javascript


code:
for l in list1:
   for i in l:
    total=total+card_value.get(i,0)
    if i[0] == 'H':   # first character of card string is a H- so it's a heart
      heart_counter = heart_counter + 1
if heart_counter == len(list1):
   total = total - 26

rawDescription: How to make a function that calculate elements in list?

description: Make a function that calculate elements in list


rawDescription: numpy merge upper and lower triangular

description: Numpy merge upper and lower triangular


code: np.apply_along_axis(lambda x: f(*x), 2, arr)

rawDescription: Reducing an axis with numpy

description: Reducing an axis with numpy


rawDescription: How to extract the related fields for base, version and others from this url?

description: Extract the related fields for base, version and others from this url


code:
class MyCheckButton(CheckButton):
    def __init__(self,*args,**kwargs):
        self.var=kwargs.get('variable',IntVar())
        kwargs['variable']=self.var
        Checkbutton.__init__(self,*args,**kwargs)

    def is_checked(self):
        return self.var.get()

rawDescription: Python, Tkinter, Checkbutton: Is there a way to check on/off value


code: veggies = x['Non-Meats']['Vegetable']

rawDescription: Loop through 3 levels of lists

description: Loop through 3 levels of lists


code:
file_name = werkzeug.security.safe_join("/path/to/savedimages", picture)
return send_file(file_name)

rawDescription: chmod a folder on heroku app

description: Chmod a folder on heroku app


code: pd.pivot_table(df, values = 'Value', index=['Country','Year'], columns = 'Indicator').reset_index()

rawDescription: How to pivot a dataframe in Pandas?

description: Pivot a dataframe in Pandas


rawDescription: Python method accessor creates new objects on each access?


rawDescription: Accessing columns after applying the stack function on a pandas dataframe


code:
for label in ax.get_xticklabels():
    pass
label.set_visible(False)

rawDescription: How to make the last mark invisible in a matplotlib axes subplot?

description: Make the last mark invisible in a matplotlib axes subplot


code: call('echo hello', shell=True, stdout=dn, stderr=dn)

rawDescription: Supressing output with os.system()

description: Supressing output with os.system()


code:
from operator import itemgetter

for resolution, banners in tvdb_api_result.items():
    bannerpath = max(banners.values(), key=itemgetter('rating'))['_bannerpath']
    print("%s %s" % (resolution, bannerpath))

rawDescription: Python: comparing nested values - neater method


code:
text = 'منهدم کردن : 1 خراب کردن، ویران کردن، تخریب کردن 2 نابود کردن، از بین بردن'
want = ['منهدم کردن','خراب کردن', 'ویران کردن', 'تخریب کردن','نابود کردن', 'از بین بردن']
[x for x  in map(str.strip, regex.findall(r'[\p{Cf}\p{L}\s]+', text)) if x] == want

rawDescription: Tokenizing non English Text in Python

description: Tokenizing non English Text in Python


code:
with open("myFile.txt") as f:
    array = []
    for line in f:
        if line.startswith('start flag'):
            # beginning of section use first lin
            for line in f:
                # check for end of section breaking if we find the stop lone
                if line.startswith("stop flag"):
                    break
                 # else process lines from section

rawDescription: Read multiple block of file between start and stop flags


rawDescription: Applying a function by bins on a vector in Numpy


code:
tor.connect()
tor.new_identity()

t = threading.Timer(10.0, tor.new_identity())
t.start()

total = 0
thread_limit = 200
while True:
    if threading.activeCount() < thread_limit:
        stress_test(host_ip, host_port).start()

rawDescription: Python running two threads simultaneously


code:
def shortest_word_in_longest_line(filename):
    with open(filename) as file:
        longest_line = max(file, key=len)  # file is an iterator over lines
    return min(longest_line.split(), key=len)  # whitespace-separated words

rawDescription: How can I return the shortest word within the longest line?

description: Return the shortest word within the longest line


code:
Manager.DefaultDomainName

# also referenced by
self.__class__.DefaultDomainName

rawDescription: How do python classes work?

description: How do python classes work


code:
config = Configuration(braintree.Environment.Sandbox, "your_merchant_id", "your_public_key", "your_private_key")
braintree_gateway = BraintreeGateway(config)
testing_gateway = TestingGateway(braintree_gateway)

testing_gateway.settle_transaction("transaction_id")

rawDescription: importing TestHelper from braintree

description: Importing TestHelper from braintree


code:
import numpy as np
a = np.random.random_integers(0,9, (2,2))
b = np.random.random_integers(0,9, (3,3))
c = np.einsum('ij,kl-> ijkl', a, b)
a
b
c

rawDescription: Matrix direct product retaining indices in python


rawDescription: function that given a list returns a list of list decreasing

description: Function that given a list returns a list of list decreasing


code:
st2 = set(set2)

inter = st2.intersection(set1)

diff = st2.difference(set1)

rawDescription: Comparing each element between 2 sets?

description: Comparing each element between 2 sets


code: df.loc[df[col].value_counts()[df[col]].values < 10, col] = "RARE_VALUE"

rawDescription: Replace rarely occurring values in a pandas dataframe


code:
d = collections.defaultdict(list)
for i in f.split(','):
    k, v = i.split('=')
    d[k].append(v)

rawDescription: Is there a Python standard library class like collections.Counter() but with with lists as values?


rawDescription: python : reading a datetime from a log file using regex

description: Python : reading a datetime from a log file using regex


code: l_sorted = sorted(l, key=itemgetter(0))

rawDescription: How to add items in a list of tuples if the item is the same

description: Add items in a list of tuples if the item is the same


rawDescription: How to create a keyframe with Python API for 3D Studio Max

description: Create a keyframe with Python API for 3D Studio Max


code:
class LinkedList(object):

    class Node(object):
        __slots__ = ('prev', 'next', 'value')

        def __init__(self, prev=None, next=None, value=None):
            self.prev = prev
            self.next = next
            self.value = value

    def __init__(self, iterable=[]):
        self.head = LinkedList.Node() # dummy node
        self.tail = self.head
        self.size = 0
        for item in iterable:
            self.append(item)

    def __iter__(self):
        current = self.head
        while True:
            if current.next is not None:
                current = current.next
                yield current.value
            else:
                raise StopIteration

    def append(self, value):
        self.tail.next = LinkedList.Node(prev=self.tail, value=value)
        self.tail = self.tail.next
        self.size += 1

    def pop(self):
        if self.size > 0:
            value = self.tail.value
            self.tail = self.tail.prev
            self.tail.next = None
            self.size -= 1
            return value
        else:
            raise IndexError('pop from empty list')

    def count(self, value):
        cumsum = 0
        for item in self:
            if item == value:
                cumsum += 1
        return cumsum

rawDescription: Single Linked List search in Python

description: Single Linked List search in Python


code:
d = defaultdict(lambda: [])
for school in a, b, c:
    for g in school['grades']:
        d[g].append(school)

rawDescription: Functional Python - Multiple Dictionaries to One Dictionary


code:
h, w = 20, 10
A = np.arange(h*w).reshape(h, w)
del_ind = np.random.randint(0, w, size=h)
mask = np.ones((h,w), dtype=bool)
mask[range(h), del_ind] = False
A_ = A[mask].reshape(h, w-1)

rawDescription: Python with numpy: How to delete an element from each row of a 2-D array according to a specific index


code:
import pandas as pd
import sklearn.feature_extraction as FE

data = pd.DataFrame({
    'foo': ['hi', 'no', 'please', 'no', 'yea', 'hi'],
    'bar': [1, 5, 7, 2, 4, 5],
    'zoo': ['car', 'bike', 'car', 'bus', 'bus', 'car']})

X_dicts = data.to_dict('records')
vec = FE.DictVectorizer(sparse=False)
X_vec = vec.fit_transform(X_dicts)

def inverse_transform(vec, X_vec):
    feature_map = vec.inverse_transform(X_vec)
    result = list()
    for dct in feature_map:
        newdct = dict()
        for k, v in dct.items():
            if '=' in k:
                k, v = k.split('=', 1)
            newdct[k] = v
        result.append(newdct)
    return result

data2 = pd.DataFrame(inverse_transform(vec, X_vec))
print(data2)

rawDescription: How to get categorical data back after transformations?

description: Get categorical data back after transformations


code:
import pandas as pd
df = pd.DataFrame(a, columns=['value', 'city'])

rawDescription: How to replace specific entries of a Numpy array based on its content

description: Replace specific entries of a Numpy array based on its content


code:
site_load_process = multiprocessing.Process(target=load_dat_site,
                                            args=(d,)) # the comma is essential!

rawDescription: Using manager to modify variables between multiprocess processes


code:
import re
p = re.compile('^(?=[^a-z]*([a-z]))(?=[^A-Z]*([A-Z]))(?=[^0-9]*([0-9]))', re.MULTILINE)
test_str = "adkkeEdkj$4\n4jdkg5UU"
print(re.findall(p, test_str))

rawDescription: How to take out symbols from string with regex

description: Take out symbols from string with regex


code:
import pandas as pd
import numpy as np
import matplotlib.pylab as plt

d = {'City': ['London', 'New York', 'New York', 'London', 'Paris',
                        'Paris', 'New York', 'New York', 'London', 'Paris'],
     'Age': [36., 42., 6., 66., 38., 18., 22., 43., 34., 54],
     'Weight': [225, 454, 345, 355, 234, 198, 400, 256, 323, 310]}

df = pd.DataFrame(d)
fig, ax = plt.subplots(figsize=(5, 4))    # 1
df.groupby(['City']).plot(kind='scatter', x='Age', y='Weight',
                          ax=ax,          # 2
                          color=['red', 'blue', 'green'])

plt.show()

rawDescription: Pandas for loop on a group by

description: Pandas for loop on a group by


rawDescription: How to chosse AWS profile using Boto3 to connect to CloudFront

description: Chosse AWS profile using Boto3 to connect to CloudFront


code: [function(element) for element in list]

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


rawDescription: IPython: Alias which uses a magic function itself


code: len(set(e['type'] for e in L)) == 1

rawDescription: Pythonic way of comparing multiple elements in a list of dictionaries


code:
#!/usr/bin/python
import numpy as np

# let us generate fake test data
x = np.arange(10)
y1 = np.random.rand(10) * 20
y2 = np.random.rand(10) * 20

rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code:
from __future__ import print_function
import pandas as pd

df1 = pd.read_csv('a1.txt', names=['read_name','meth_state','position'], usecols=['position', 'meth_state'], delimiter=r'\s+')
df1 = df1[(df1.meth_state == '+')]
print('DF1 %s' % ('-' * 50))
print(df1)

df2 = pd.read_csv('a2.txt', names=['read_name','meth_state','position'], usecols=['position', 'meth_state'], delimiter=r'\s+')
df2 = df2[(df2.meth_state == '+')]
print('DF2 %s' % ('-' * 50))
print(df2)

m1 = pd.merge(df2, df1, how='left', on='position')
print('DF2 - DF1 %s' % ('-' * 50))
print(df2[m1['meth_state_y'].isnull()])

m2 = pd.merge(df1, df2, how='left', on='position')
print('DF1 - DF2 %s' % ('-' * 50))
print(df1[m2['meth_state_y'].isnull()])

rawDescription: Building a dictionary out of components in a file


code:
from testconfig import config

def test_url_is_dev():
    assert 'dev' in config['url']

rawDescription: passing a URL to test against with nose testconfig

description: Passing a URL to test against with nose testconfig


code:
from django.http import HttpResponse
from xml.dom.minidom import parseString
import xml
import urllib

def index(request, number):
    data = open('myfile.xml', 'r').read()
    dom = parseString(data)
    rows = (dom.getElementsByTagName("card")[0]
               .getElementsByTagName("markers")[0]
               .getElementsByTagName("marker"))

    for row in rows:
        if row.getAttribute("number") == str(number):
             return HttpResponse(str(xml.dumps({'long': row.getAttribute("lng"),
                    'lat': row.getAttribute("lat")}, sort_keys=True, indent=4)))
    return HttpResponse("Not Found")

rawDescription: Django - consume XML - RESTful

description: Django - consume XML - RESTful


code: copied_list = original_list[:]

rawDescription: How to create copies of a python object that are not linked to original object?

description: Create copies of a python object that are not linked to original object


code:
res[pd.isnull(res) | (res < 0)] = 0
res

rawDescription: pandas groupby on a values based on n-1 index record

description: Pandas groupby on a values based on n-1 index record


code:
class X(object):
    items  = []

class Y(object):
    items  = []

class Z(object):
    items  = []

rawDescription: How to use a decorator to modify mutable class variables?

description: Use a decorator to modify mutable class variables


code: c = np.sum(np.sum(a*b,axis=2),axis=2)

rawDescription: Numpy product or tensor product question


rawDescription: How to show and hide QtGui.QGridLayout in PySide

description: Show and hide QtGui.QGridLayout in PySide


code:
def get_changelist(self, request, **kwargs):
    """
    Returns the ChangeList class for use on the changelist page.
    """
    return MyChangeList  # PUT YOU OWERRIDEN CHANGE LIST HERE

rawDescription: How to get filtered queryset in django admin?

description: Get filtered queryset in django admin


code:
import re
papa = 'papa is a good man'
app = 'app is important'
papa3 = 'papa is a papa, and papa'
patt = re.compile('(\s*)papa(\s*)')
patt.sub('\\1mama\\2', papa)
patt.sub('\\1mama\\2', papa3)
patt.sub('', papa3)

rawDescription: How to strip a specific word from a string?

description: Strip a specific word from a string


code: print([i for i in x if re.search('[\x05-\x40]',i)])

rawDescription: Python split list of strings into two containing hex strings and regular


code: [x_o_r(zip(list(a), list(b))) for a in x for b in x]

rawDescription: Python - Result returns generator instead of list (comprehension)


code:
nested_items = (repeat(item,2) if item==3 or item==7 else [item] for item in abc)
result = [item for nested_item in nested_items for item in nested_item]

rawDescription: python: repeating elements in a list based a predicateHow

description: Python: repeating elements in a list based a predicateHow


code:
from PIL import Image
im = Image.open('image.png')
im = im.convert('L')
im.save('image_grey.png')

rawDescription: Black and white colorbar

description: Black and white colorbar


code:
c = C()
a = c.a

rawDescription: Django get base model from parent model

description: Django get base model from parent model


code:
import os
user_name = os.getenv("USERNAME")

rawDescription: How do you find the root directory so that a path works across multiple computers?

description: Find the root directory so that a path works across multiple computers


code:
import numpy as np
import pandas as pd
auto_data = pd.DataFrame({
    'HORSEPOWER':[1, np.nan, 2],
    'DISPLACEMENT': [3, 4, 5]})
slope, intercept = 2, 0.5
y = (slope * auto_data['DISPLACEMENT'] + intercept).round()
auto_data['HORSEPOWER'].update(y)
print(auto_data)

rawDescription: Correct Syntax for clearing SettingWithCopyWarning in Pandas


rawDescription: Index multiple, non-adjacent ranges in numpy


rawDescription: xor matrix multiplication for AES mix column stage

description: Xor matrix multiplication for AES mix column stage


code:
k = []
v = []
with open("1.txt", "r") as crs:
    for line in crs:
        x = line.split()
        k.append(x[0]) # use float(x[0]) if you want numbers rather than strings
        v.append(x[1])

rawDescription: reading a datafile to array/list

description: Reading a datafile to array/list


code: soup.find('table', cellpaddin="4", cellspacing="0") # Notice how the integers are now strings, like in the HTML.

rawDescription: Parse table with BeautifulSoup Python

description: Parse table with BeautifulSoup Python


rawDescription: Design ideas for a webapp in Django

description: Design ideas for a webapp in Django


code:
a[a < thr] = 0
ndimage.measurements.center_of_mass(a)

rawDescription: In Python: the center of mass of specific regions of values in a 2D numpy array


rawDescription: Reading all lines in a file with list comprehension


rawDescription: Numpy array filled with random numbers so that you only change the value by one along the x/y axis


code:
res = pd.concat([df0, df1], axis=1)
res

rawDescription: Merge multiple dataframes with non-unique indices


code:
a
['/home/lesmana/tmp/a.py', '-m', 'b']

rawDescription: Multiple -m command line arguments (Python)


code:
c
d
c+d

rawDescription: Python 3: faster int?

description: Python 3: faster int


code:
# define xpath generation JS in python
xpathJS = "function getPathTo(element){ if(element....."

# add new function to the page
execute_script(xpathJS)

# select an element with SE
element1 = driver.find_element_by_id('id_of_element')

# get the xpath of the element
xpath1 = execute_script("return getPathTo(arguments[0])", element1)

rawDescription: get javascript selector of WebElement

description: Get javascript selector of WebElement


code: ['November 5 - December 10', 'September 23 - December 16']

rawDescription: regex to find a specific pattern in python

description: Regex to find a specific pattern in python


rawDescription: Python Pandas: Groupby date, and accessing each group by timestamp


code:
df.set_index(['x','b']).to_panel()
p1 = df.set_index(['x','b']).to_panel()

rawDescription: Pandas data types change when iterating over the major axis


code:
from bs4 import BeautifulSoup
import requests

page1 = requests.get("http://www.century21.com/search.c21?lid=COHADA&t=0&s=0&subView=searchView.AllSubView")
c1 = page1.json()["list"]
soup1 = BeautifulSoup(c1, "html.parser").find_all("div", {"class": "propertyRow"})[0].find_all("span", {
    "class": "propAddressCollapse"})[0].text

page2 = requests.get("http://www.century21.com/search.c21?lid=COHADA&t=0&s=10&subView=searchView.AllSubView")
c2 = page2.json()["list"]
soup2 = BeautifulSoup(c2, "html.parser").find_all("div", {"class": "propertyRow"})[0].find_all("span", {
    "class": "propAddressCollapse"})[0].text

print(soup1)
print(soup2)

rawDescription: Request the second load of the page with Python


code:
for key in dic:
    do_some_stuff()
    break

rawDescription: python loop to run only once for temporary testing

description: Python loop to run only once for temporary testing


rawDescription: Python Regular Expression Match All 5 Digit Numbers but None Larger


code: numPossibilities = sum([L - bisect.bisect_right(numset2,n1) for n1 in numset1])

rawDescription: Improve performance on Python nested for loop


code:
index_mapper.on_trait_change(self.on_mapper_updated, "updated")

def on_mapper_updated(self, mapper, name, value):
    if not self.rangeselect.selection:
        self.rangeXMin = mapper.range.low
        self.rangeXMax = mapper.range.high

rawDescription: Chaco: Get Index and Value out of a chaco plot


code: y = ["%02d" % v for v in x]

rawDescription: Python - list transformation

description: Python - list transformation


code: schema2 = schema1[:]

rawDescription: Python Changes Both Variables When Set Equal?


code:
x = np.random.randint(0,9,(4,5,3,3,2,4))
m = x.argmax(axis=-1)
shp = x.shape[:-1]
np.allclose(x.max(-1),y_out)

rawDescription: indexing in numpy (related to max/argmax)

description: Indexing in numpy (related to max/argmax)


code:
if __name__ == '__main__':
    if options.list:
        list_my_repos()

rawDescription: python - beginner - integrating optparse in a program

description: Python - beginner - integrating optparse in a program


code:
from itertools import islice

with open('input') as fin, open('output', 'w') as fout:
    fout.writelines(islice(fin, None, None, 2))

rawDescription: Read every second line and print to new file


code: reduce(lambda y, _: f(y), xrange(nIterations), initValue)

rawDescription: Iteration in a single line

description: Iteration in a single line


code:
import datetime
import re
from collections import defaultdict
months = defaultdict(int)
# months = {}  # for Python 2.4
with open("test.txt") as timestamps:
    for line in timestamps:
        month = line[:7]
        time = re.search(r"(\d+):(\d+):(\d+)", line)
        if time:
             seconds = int(time.group(1))*3600 + \
                       int(time.group(2))*60 +   \
                       int(time.group(3))
             months[month] += seconds
             # if month in months:          # Python 2.4
             #     months[month] += seconds
             # else:
             #     months[month] = seconds
for month in sorted(months.keys()):
    print("Times for {}: {}".format(month,
                                    datetime.timedelta(seconds=months[month])))

rawDescription: Add timestamps in python

description: Add timestamps in python


code:
class ModuleModel(db.Model):
  @classmethod
  def kind(cls):
    return '%s_%s' % (cls.__module__, super(ModuleModel, cls).kind())

rawDescription: Set a kind name independently of the model name (App Engine datastore)


code:
from itertools import imap
print(sum(sum(imap(int,r.findall(line))) for line in data))

rawDescription: Find all occurrences of integer within text in Python


rawDescription: pandas series cumulative argmax

description: Pandas series cumulative argmax


rawDescription: Delete elements at different indices in a text file


code:
from collections import defaultdict
counter = defaultdict(int)
for c in "<text xx will xx be xx pasted xx here>":
    counter[c]+=1

"".join(k for k,v in counter.items() if v<8)

rawDescription: what is a way to match any char that appears less than a given number of times with regex python?

description: What is a way to match any char that appears less than a given number of times with regex python


code:
st=  input("Enter string:").split(',')
st[1]

rawDescription: string slicing python in lists

description: String slicing python in lists


code: ret_list = [e[0] if len(e) == 1 else e for e in ret_dict.itervalues()]

rawDescription: Python - Convert JSON object data into a List


code:
newargs = (b, c)
myfunc2(a, *newargs)

rawDescription: Passing n arguments to a function in Python


code:
lines = []  # container for a list of lines
for x in xrange(10):  # assume 10 cycles
    line = []
    # ... (here is your code, appending data to line) ...
    lines.append('%r\n' % line)  # here you add line to the list of lines
# here "lines" is your list of cycle results
with open('some_file.dat', 'w') as f:
    f.writelines(lines)

rawDescription: How can I append to the new line of a file while using write()?

description: Append to the new line of a file while using write()


code:
def is_list(value):
    return isinstance(value, list)

rawDescription: Testing for a List in Jinja2

description: Testing for a List in Jinja2


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def post(self):
        data = tornado.escape.json_decode(self.request.body)
        key = data.get('key', None)

        # result = fetch_data_for(key)
        result = "ok\n"

        self.add_header('validation', 'value')
        self.write(result)

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: How to change tornado post header and add into header new data?

description: Change tornado post header and add into header new data


code:
[tuple(group)[-1][0] for key, group in
        groupby(enumerate(myList), key=itemgetter(1))][:-1]

rawDescription: Get index from a list where the key changes, groupby


code: x = ''.join(stringExample)

rawDescription: How can i make sure \n does not register? when it is in a string

description: Make sure \n does not register? when it is in a string


code:
file_date_tuple_list = [(x,os.path.getmtime(x)) for x in files]
file_date_tuple_list.sort(key=lambda x: x[1])

rawDescription: How to make a chronological list of files, with the file modification date

description: Make a chronological list of files, with the file modification date


code: a=array.array('i',(0 for i in range(0,10)))

rawDescription: How to create an integer array in Python?

description: Create an integer array in Python


rawDescription: Is there a way to use bincount with a clause in python?


code:
import lxml.html

root = lxml.html.fromstring(document_string)
for elem in root.cssselect('elem.class'):
    print(elem.tag)
    print(elem.get('src'))

rawDescription: How to getElementsByClassName by using python xml.dom.minidom?

description: GetElementsByClassName by using python xml.dom.minidom


code:
time_pattern = re.compile(r'(\d+)hr\s*(\d+)min')
hours, minutes = time_pattern.search(soup.span.get_text()).groups()
hours
minutes

rawDescription: Regular expression for data scraping?

description: Regular expression for data scraping


code:
# first pass to count
with open(file_name) as fid:
    n_lines = sum(1 for line in fid)

# second pass to actually do something
with open(file_name) as fid:
    for i_line in xrange(n_lines - n_skip):  # does nothing if n_lines <= n_skip
        line = fid.readline()
        do_something_with(line)

rawDescription: Simple Way of NOT reading last N lines of a file in Python


code:
promotion = [[""], ["promotion applied"],[""]]
[x[0] for x in promotion]

rawDescription: how do i get rid of extra array in python?

description: Get rid of extra array in python


code:
import requests
url = "http://localhost:8000/list/"
response = requests.post(url,files={'docfile': open('test.txt','rb')})

rawDescription: Uploading files from a Python client to a Django Server


code:
import numpy as np
X = np.random.rand(10, 2)

rawDescription: specifying missing values to pdist in scipy

description: Specifying missing values to pdist in scipy


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

def main():
    data = [np.random.random((2, 3)) for _ in range(5)]
    fig, ax = plt.subplots()
    polygons = plot_polygons(data, alpha=0.5, ax=ax, color='gray')
    verts = plot_verts(data, marker='s', color='red', ax=ax, s=200)

    def on_click(event):
        visible = polygons[0][0].get_visible()
        plt.setp(polygons, visible=not visible)
        plt.setp(verts, color=np.random.random(3))
        plt.draw()
    fig.canvas.mpl_connect('button_press_event', on_click)

    ax.set(title='Click on plot to change')
    plt.show()

def plot_polygons(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.fill(x, y, **kwargs) for x, y in data]
    return artists

def plot_verts(data, ax=None, **kwargs):
    if ax is None:
        ax = plt.gca()

    artists = [ax.scatter(x, y, **kwargs) for x, y in data]
    return artists

main()

rawDescription: What is the best way of combining two independent plots with matplotlib?


code: {'name': 'peter', 'identity': '1'}

rawDescription: create a new dict based on old dict

description: Create a new dict based on old dict


code: gravitation(oval1, oval2)

rawDescription: Update Tkinter Label

description: Update Tkinter Label


code:
#!/usr/bin/env python
from datetime import date, timedelta

today = date.today()
yesterday = today - timedelta(1)
print(yesterday.timetuple())
# -> time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=112, tm_isdst=-1)

rawDescription: Time - get yesterdays date

description: Time - get yesterdays date


code:
class Thing(db.Model):
  ...

class User(db.Model):
  things = db.ListProperty(db.Key)
  ...

rawDescription: Minimize subqueries with IN queries on AppEngine (python)


code:
def countSpaces(s):
    answer = []
    start = None
    maxCount = 0
    for i,char in enumerate(s):
        if char == ' ':
            if start is None:
                start = i
                answer.append(char)
        else:
            if start is not None:
                maxCount = max(i-start-1, maxCount)
                start = None
            answer.append(char)
    print("The whitespace normalized string is", ''.join(answer))
    print("The maximum length of consecutive whitespace is", maxCount)

rawDescription: removing excess spaces from a string (and counting them)

description: Removing excess spaces from a string (and counting them)


code:
import re
trailing0 = re.compile(r"""(\.       # decimal point
                            \d*?)    # and as few digits as possible
                           0+$       # before at least 1 trailing 0
                        """, re.VERBOSE)
def replacer(m):
    g = m.group(1)
    if len(g) == 1:
        assert g == "."
        return ""
    else:
        return g

def normalize(x):
    return trailing0.sub(replacer, str(x))

rawDescription: How can I "trim" significant figures of a Decimal in Python to only those that are non-zero?


rawDescription: Dictionary value sorting

description: Dictionary value sorting


code: df.values == rowmax[:,None]

rawDescription: Find all indices of maximum in Pandas DataFrame


code:
c = np.array([1,2,3])
c2 = np.power(c, 2)
# returns "array([1, 4, 9], dtype=int32)"

rawDescription: take different powers of a vector and save in txtfile

description: Take different powers of a vector and save in txtfile


code:
def unwrap_data(filename, wrap_len=101, map_func=None):
    """
    Generator which reads a file and returns a list of float,
    one for each data row.

    Rows in the file are assumed to be wrapped after every
    wrap_len columns, so we unwrap it before returning each
    data row.

    wrap_len defaults to 101 (1 time column + 100 cell values).

    Caveat: If a timing data has exactly 100 cell values (101
    columns), the output of this function will be wrong unless
    an additional newline exists before the next timing row, e.g.

         time1      cell1_1    cell1_2  ... cell1_100
         cell1_101  cell1_102  ...
         time2      cell2_1    cell2_2  ... cell2_100

         time3      cell3_1    cell3_2  ...
    """
    next_data = []
    for line in open(filename, 'r'):  # for each line in file
        L = line.strip().split()
        if map_func:
            L = map(map_func, L)  # run map_func() on each list element
        next_data.extend(L)  # add to prev row
        if len(L) != wrap_len and next_data:
            # the line was not wrapped, assume new timing data
            # "and next_data" will avoid returning empty lists for blank lines
            yield next_data
            next_data = []

rawDescription: Python-Cannot convert string to float...manipulating a text file


code:
from collections import namedtuple as nifty_thing
Data = nifty_thing("Data", ["foo", "bar", "baz"])
data = Data(foo=1, bar=2, baz=3)
data.foo
data.bar
data.baz

rawDescription: Is there a Python 'shortcut' to define a class variable equal to a string version of its own name?


code:
import os

src = '/Users/storm/server/svr_user'
dst = '/svr_user2'

a = '/Users/storm/server/svr_user/x/y/z'
os.path.join(dst, os.path.relpath(a, src))

rawDescription: Python: How to remove string from string


code:
import h5py
import numpy as np
f = h5py.File('File Location')
matlab_arr=f['array name']
matlab_arr=np.array(matlab_arr,dtype='f8')

rawDescription: Import Matlab Workspace variables into Spyder (Python)


code:
def get_resource_path(rel_path):
    dir_of_py_file = os.path.dirname(__file__)
    rel_path_to_resource = os.path.join(dir_of_py_file, rel_path)
    abs_path_to_resource = os.path.abspath(rel_path_to_resource)
    return abs_path_to_resource

rawDescription: Adding a program icon in Python GTK

description: Adding a program icon in Python GTK


code:
a = int(input("Enter a number: "))
more = input("Please enter Y or N if you want to add more numbers: ")
summ=a          #intialize sum to a
count=1         # no. of integers entered, to calculate mean
while more.lower()=="y":
    b = int(input("Enter another number: "))
    count+=1          #increase count by 1
    summ+= b          #add b to sum
    abMean = summ/float(count)         #used float(count) to get actual value

    print("sum=",summ)
    print("mean=",abMean)
    more = input("Please enter Y or N if you want to add more numbers: ") #ask for user input
print("sum=",summ)
print("mean=",abMean)

rawDescription: Noob Python While Loop

description: Noob Python While Loop


code:
win_size=5
win_step=2
coef_ls=[]
for i in range(0,len(dfd)-win_size,2):
    coef_ls.append(smf.ols('A ~ B', data=dfd.ix[i:i+win_size]).fit().params)
pd.concat(coef_ls, axis=1).T # The resulting DataFrame of coefficients.

rawDescription: Regression of a timeseries delta in pandas


rawDescription: How to reformat a string in python?

description: Reformat a string in python


code:
tupList = [(2,16), (4, 42), (3, 23)]
tupList = sorted(tupList, key = lambda tup: tup[1])
print(tupList)

rawDescription: Sorting tuples by element value in Python


code: print(any(len(str(i))==3 for i in numbers_list))

rawDescription: Struggling with 'for' statement in Python


code:
import os, os.path
import logging.handlers
import pickle

class BufferingSocketHandler(logging.handlers.SocketHandler):
    def __init__(self, host, port, buffer_file):
        super().__init__(host, port)
        self._buffer = FileBuffer(buffer_file)

    @property  # getter only
    def buffer(self):
        return self._buffer

    def _emit(self, record):
        try:
            s = self.makePickle(record)
            self.send(s)
            return (self.sock is not None)
        except Exception:
            self.handleError(record)
            return False

    def emit(self, record):
        self.send_buffer()
        success = self._emit(record)
        if not success:
            self.buffer.append(record)

    def send_buffer(self):
        try:
            self.acquire()
            success = True
            for item in self.buffer:
                success &= self._emit(item)
            if success:
                self.buffer.flush()
        finally:
            self.release()

class FileBuffer:
    def __init__(self, fname):
        self.fname = fname

    @property
    def size(self):
        return int(os.path.isfile(self.fname) \
                and os.path.getsize(self.fname))

    def append(self, data):
        with open(self.fname, 'ba') as f:
            pickle.dump(data, f)

    def __iter__(self):
        if self.size > 0:
            try:
                with open(self.fname, 'br') as f:
                    while True:
                        yield pickle.load(f)
            except EOFError:
                return

    def flush(self):
        if self.size > 0:
            os.remove(self.fname)

rawDescription: How to send unsent logs to python logging server when it comes back online?

description: Send unsent logs to python logging server when it comes back online


code: calendar.monthrange(year, month)[1]

rawDescription: Get Last Day of the Month in Python

description: Get Last Day of the Month in Python


rawDescription: Interpolating values by group in a dataframe - Python


code: [list(t) for t in zip(*4*[iter(x)])]

rawDescription: Getting two-tuples out of a list

description: Getting two-tuples out of a list


code:
def __iter__(self):
    return iter(self._iterable)

rawDescription: python make class iterable by returning embedded iterable

description: Python make class iterable by returning embedded iterable


code:
if not line.startswith('Xac:'):
    return None

rawDescription: Delete unusable characters or data in archive with python


code:
@staticmethod
def eliminar_nota(ID = None):
    ID = str(ID) or input('ID?: ')
    linea = 1
    try:
        with open('temp.txt', 'x+') as archivo_temporal:
            with open("notas.txt", "r") as archivo_notas:
                for line in archivo_notas:
                    linea += 1
                    archivo_temporal.write(line)
                    if ID in line:
                        linea_buscada = linea
                        print(linea_buscada)
            print('Si no veo nada antes aqui, hay problemas ;)')
            os.remove("notas.txt")
            archivo_temporal.seek(0,0)
            with open("notas.txt", "w") as archivo_notas:
                linea = 1
                counting = False
                for line in archivo_temporal:
                    linea += 1
                    if linea == linea_buscada - 1:
                        counting = 5
                    if not counting:
                        archivo_notas.write(line)
                    else:
                        counting -= 1
                        continue
    finally:
        os.remove('temp.txt')

rawDescription: Error on variable after assignment?

description: Error on variable after assignment


code:
from itertools import tee

def sliding_range(file, size):
    fin1, fin2 = tee(int(ln.strip()) for ln in open(file) if ln.strip())
    n = 1
    next(fin2)
    val2 = next(fin2)
    for val1 in fin1:
        while val2 is not None and val2 <= val1 + size:
            n += 1
            try:
                val2 = next(fin2)
            except StopIteration:
                val2 = None
                break
        yield n
        n -= 1

rawDescription: Counting the number of points in a sliding range


rawDescription: Pandas Series with column names for each value above a minimum


code: def typecheck(obj): return not isinstance(obj, str) and isinstance(obj, Iterable)

rawDescription: Type checking: an iterable type that is not a string


code:
def is_happy(items):
   return all(item.state in ['happy', 'cheerful'] and is_happy(item.childs) for item in items)

rawDescription: Is it possible to nest the all function?

description: Is it possible to nest the all function


code:
def testing(a,b):
    result = []
    for count in range(a,b):
        result.append(0)
    return result

rawDescription: How to import a module of functions and pass variables between modules

description: Import a module of functions and pass variables between modules


code: (x == thing).any()

rawDescription: How does __contains__ work for ndarrays?

description: How does __contains__ work for ndarrays


rawDescription: How to display the result with temple jinjia2 or others?

description: Display the result with temple jinjia2 or others


code: new = ''.join(c if 32 <= ord(c) < 128 else '\\u{:04x}'.format(ord(c)) for c in u)

rawDescription: Python: Replace character by its Unicode-representation


rawDescription: Example scrapy feed_export to FTP site needed


code:
import datetime, logging

logfile = 'logfile.log'

logging.basicConfig(filename=logfile,
                    level=logging.INFO,
                    format='%(asctime)s.%(msecs)03d %(levelname)s %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S')

x = (10,11,12)
y = str("case when id =1 then gr8 else ok end")
z = datetime.datetime.today().strftime('%Y-%m-%d')

logging.info(x)
logging.info(y)
logging.info(z)

rawDescription: redirecting python output to a log file

description: Redirecting python output to a log file


code:
for r in results:
  for field in ['Phone','Email']:
    if r[field]:
      processed[r['ID']][field.lower()].add(r[field])
      processed[r['ID']]['type'].add(field.lower())

rawDescription: Consolidating row data from DB into a list of dicts


code: return format(int(number), '-2d')

rawDescription: And and Or confusion

description: And and Or confusion


code:
(u'PsiNapse', u'San Mateo, CA')
(u'Videology', u'Baltimore, MD')
(u'Charles Schwab', u'Lone Tree, CO')
(u'Cognizant', u'Dover, NH')
...
(u'Concur', u'Bellevue, WA')

rawDescription: python BeautifulSoup soup.findAll(), how to make search result match

description: Python BeautifulSoup soup.findAll(), how to make search result match


rawDescription: Find repeated pattern in text with "Re" Python


code:
s = 'something{now I am wrapped {I should not cause splitting} I am still wrapped}something else'
f(s,'{','}')

rawDescription: regex split on wrapping patterns

description: Regex split on wrapping patterns


code:
fig = my_plot(...)
fig.savefig("somefile.png")

rawDescription: save a plot resulting from a function matplotlib python

description: Save a plot resulting from a function matplotlib python


rawDescription: Python: delete the words between two delimeters


rawDescription: Algorithm to sort object by attribute value without allowing gaps or duplicates


code:
xml = '''<data>
  <item>
      <title>contains KEYWORD of interest </title>
      <description> description text of interest "1"</description>
  </item>
  <item>
      <title>title text </title>
      <description> description text not of interest</description>
  </item>
  .
  .
  .
  <item>
      <title>also contains KEYWORD of interest </title>
      <description> description text of interest "k" </description>
  </item>
</data>
'''

import lxml.etree
root = lxml.etree.fromstring(xml)
root.xpath('.//title[contains(text(), "KEYWORD")]/'
           'following-sibling::description/text()')
# => [' description text of interest "1"', ' description text of interest "k" ']

rawDescription: parsing xml with python, selecting a tag using a sibling tag as selector

description: Parsing xml with python, selecting a tag using a sibling tag as selector


code:
import io
import pandas as pd

text = '''\
1 2 3
4 5 6
'''

print(pd.read_csv(io.BytesIO(text), sep=' '))

rawDescription: Python Pandas does not read the first row of csv file


code: result=input.split(" ")

rawDescription: Converting a string to array of words - Python


code:
from nltk import pos_tag
sent1 = 'get me now'.split()
sent2 = 'run fast'.split()
def imperative_pos_tag(sent):
    return [(word, tag[:2]) if tag.startswith('VB') else (word,tag) for word, tag in pos_tag(['He']+sent)[1:]]

imperative_pos_tag(sent1)
imperative_pos_tag(sent2)

rawDescription: NLTK identifies verb as Noun in Imperatives


code:
def nest(rows):
    root = {}
    for row in rows:
        d = root
        for item in row[:-2]:
            d = d.setdefault(item, {})
        d[row[-2]] = row[-1]
    return root

rawDescription: Populating nested dictionary from database query


code: grouped = monthly_rainfall.groupby(lambda x: x.month)

rawDescription: Calculating a cumulative deviation from mean monthly value in pandas series


code:
import pandas as pd
import numpy as np
df1 = pd.DataFrame(np.random.rand(4,4),columns=['a','b','c','d'])
df2 = pd.DataFrame(np.random.rand(4,4),columns=['a','b','c','d'])
df3 = pd.concat([df1,df2],axis=1,keys=['Credit1','Credit2'])

rawDescription: How to merge panda dataframe based on column?

description: Merge panda dataframe based on column


code:
output = "selected tupple is " + str(selected_tupple) + "\n"
output += final_seq + "\n"
output += "The longest orf length is " + str(max_val) + "\n"
return output

rawDescription: How to find a open reading frame in Python

description: Find a open reading frame in Python


code:
def log_with_func(funcentry='Running {}',funcexit='Returning {}',setConfig=None):
    ENTRY_MESSAGE = funcentry
    EXIT_MESSAGE  = funcexit
    def func(f):
        @functools.wraps(f)
        def wrapper(*args, **kwds):
            for handler in logging.root.handlers[:]:
                logging.root.removeHandler(handler)
            logger = logging.getLogger(__name__)
            if setConfig:
                logging.basicConfig(**setConfig)
            else:
                logging.basicConfig(level=logging.INFO)
            logger.info(ENTRY_MESSAGE.format(f.__name__)+'\n\n')
            logger.debug("The following arguments have been received:\n{}\n\nThe following keyword arguments have been received:\n{}\n\n".format(args,kwds))
            try:
                f_result = f(*args, **kwds)
                logger.info(EXIT_MESSAGE.format(f.__name__))
                return f_result
            except Exception:
                logger.exception("An exception was raised:\n\n")
        return wrapper
    return func

rawDescription: Logging decorator with basicConfig settings as arguments


rawDescription: Most pythonic means to find out if an element from one list is not a member of another list


code:
def month_in(year, months, field='date'):
    q = Q(**{field + '__year': year})
    for m in months:
       q |= Q(**{field + '__month': m})
    return q

Sample.objects.filter(month_in(2013, [2, 7, 9, 12]))

rawDescription: Get records for multiple months in django query


code:
s = "-local locally local test local."
variable = 'local'
re.sub(r'(^|\s)%s($|\s)' % re.escape(variable), r'\1we\2', s)
variable = '-local'
re.sub(r'(^|\s)%s($|\s)' % re.escape(variable), r'\1we\2', s)

rawDescription: python: replacing exact with minus sign

description: Python: replacing exact with minus sign


code:
p = pexpect.spawn(cmd,args,timeout=None)
line = p.readline()
while line:
    sys.stdout.write(line)
    sys.stdout.flush()
    # DO OTHER STUFF
    line = p.readline()

rawDescription: Printing output in realtime from subprocess


code:
def lstIndex(lst, item):
    if len(lst) == 0:
        return -1
    elif lst[-1] == item:
        return len(lst) - 1
    else:
        return lstIndex(lst[0:-1], item)

rawDescription: How to return that last index of a list Python

description: Return that last index of a list Python


code: utc.tzinfo == pytz.utc # returns True if utc in UTC

rawDescription: Checking if date is in UTC format

description: Checking if date is in UTC format


code:
tuple_ = (a,b,c)
"\n".join( foo(i) for i in tuple_ )

rawDescription: Tuple to string with a function to each element


code: v = [interp(x, y, i) for i in u]

rawDescription: Interploating list using python

description: Interploating list using python


code: żaglówka

rawDescription: pyodbc + MS Access(*.mdb) + UnicodeDecodeError

description: Pyodbc + MS Access(*.mdb) + UnicodeDecodeError


code:
class ExcludedDateForm(ModelForm):
    class Meta:
        model = models.ExcludedDate
        exclude = ('user', 'recurring',)
    def __init__(self, user=None, **kwargs):
        super(ExcludedDateForm, self).__init__(**kwargs)
        if user:
            self.fields['category'].queryset = models.Category.objects.filter(user=user)

rawDescription: How do I filter values in a Django form using ModelForm?

description: Filter values in a Django form using ModelForm


code: ABC = map(list, map(chain.from_iterable, product(*SETS)))

rawDescription: Python: Concatenate list of lists in the algebraic way


code:
for pos, item in enumerate(values):
    try:
        diffs.append(values[pos+1] - item)
    except IndexError:
        pass

rawDescription: Read other items in a python list while iterating through it


code:
new=[l[i:i+8] for i in range(0,len(l),8)]
[all(i==1 for i in sub) for sub in new]
new.append([1,1,1,1,1,1,1])
[all(i==1 for i in sub) for sub in new]

rawDescription: How do i make a list a list of list?

description: Make a list a list of list


code:
score = bonus = 0
score+=5
bonus = score/5
bonus
score+=5
score+=5
score+=5
score+=5
score
bonus = score/5
bonus

rawDescription: Increment a variable based on another variable


code:
x = 1
for i in range(2, 11):
    if i != 3:    # I add a condition to skip 3
        x *= i
        print(x)

rawDescription: Repeat an action a specified amount of times


rawDescription: Pythonic way to insert every 2 elements in a string


code:
from itertools import product
[sum(t*k for t,k in zip(i,j)) for i,j in product(m1,m2)]

rawDescription: Python: How do I multiply and sum elements across two lists (without using a library)?


rawDescription: How to select particular element in Selenium with IE Webdriver

description: Select particular element in Selenium with IE Webdriver


code:
import random
from functools import wraps

def method(func):
    key = '_memoize_%s' % func.__name__
    @wraps(func)
    def wrapper(self):
        if not hasattr(self, key):
            setattr(self, key, func(self))
        return getattr(self, key)

    return wrapper

class Test(object):
    @method
    def cached(self):
        return random.random()

    def uncached(self):
        return random.random()

t = Test()
for x in range(3):
    print('cached: %s' % t.cached())
    print('uncached: %s' % t.uncached())
print(t.__dict__)

rawDescription: Understanding this memoize decorator

description: Understanding this memoize decorator


code:
df['time_diff'] = df.creationdate.diff()
df.time_diff

rawDescription: Loop through rows in pandas dataframe

description: Loop through rows in pandas dataframe


code: rcParams['toolbar'] = 'None'

rawDescription: Remove Matplotlib Toolbar from the Graph


code:
equation = re.sub(r"([)xyzuvet]|pi|exp|frexp)([xyzuvet]|pi|exp|frexp)\b",r"\1*\2", equation)
equation = re.sub(r"([)xyzuvet]|pi|exp|frexp)([xyzuvet]|pi|exp|frexp)\b",r"\1*\2", equation)

rawDescription: Using Python's Regular Expression to Insert Symbol Between Certain Characters


code:
def function_that_depends_on_python_specific_state(self, *args):
   if not hasatttr( self, 'python_data'):
        self.python_data = self.make_python_data() # construct the relevant data
   pass # do work that involves the python specific data

rawDescription: Swig and Python - different object instantation


rawDescription: How does a Python custom comparator work?


code:
items = set(items)
fruits = set(foods_dict['fruit']) & items
veggies = set(foods_dict['veg']) & items
others = items - fruits - veggies

rawDescription: Python - categorizing items in a list based on occurrence in a dictionary of lists


code: f.write ("P1 skill is {0}".format( PlayerOneSkill + P1SkillMod))

rawDescription: '0' characters appering within string values when writing to a text file


code:
''.join(['a', 'b', 'b'])
[random.choice('abcde') for _ in range(3)]
''.join(random.choice('abcde') for _ in range(3))

rawDescription: Random string generation with upper case letters and digits in Python


code:
def alt_cpu_usage_str(cpu_percentage):
    return 'CPU:[%s]' % ('#' * int(round(cpu_percentage / 10.0)))

rawDescription: Python: Add character to string an amount of times depending on an int


rawDescription: How to split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary?

description: Split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary


code:
...
textOne = Entry(self, width=2)
textOne.x = 0

def increment_textOne():
    textOne.x += 1

    # register "increment_textOne" to be called every 1 sec
    self.after(1000, increment_textOne)

rawDescription: Run an infinite loop in the backgroung in Tkinter


rawDescription: Python - Sorting List of Ints User Input


code:
import sys
from lxml import etree

invalid_xml = """
<field name="id">abcdef</field>
<field name="intro" > pqrst</field>
<field name="desc"> this is a test file. We will show 5>2 and 3<5 and
try to remove non xml compatible characters.</field>
"""
root = etree.fromstring("<root>%s</root>" % invalid_xml,
                        parser=etree.XMLParser(recover=True))
root.getroottree().write(sys.stdout)

rawDescription: Matching patterns in Python

description: Matching patterns in Python


code: return  pair[not pair.index(core)]

rawDescription: pythonic solution for finding the other element in a list of length two

description: Pythonic solution for finding the other element in a list of length two


code:
class Foo(models.Model):
    pass

class Bar(models.Model):
    foo = models.ForeignKey(Foo)

rawDescription: Django : Foreign key set not found after saving object


code:
for key, value in theDict.items():
    if not len(value) > 0:
        del theDict[key]

rawDescription: How to avoid using tuples and what will this look like without list comprehension

description: Avoid using tuples and what will this look like without list comprehension


code:
class Category(models.Model):
    catID = models.CharField(max_length=20, primary_key=True)
    title = models.CharField(max_length=200)
    description = models.CharField(max_length=200)

    def latest_post(self):
        post = self.post_set.order_by('-pub_date')
        if post:
            return post[0]
        return None

rawDescription: Get latest post for category

description: Get latest post for category


code:
subprocess.call("if [ ! -d '{output}' ]; then mkdir -p {output}; fi",
                shell=True,
                executable="/bin/bash")

rawDescription: Does the `shell` in `shell=True` in subprocess means `bash`?


code: num_threads = threading.activeCount()

rawDescription: Watch number of Threads in Python

description: Watch number of Threads in Python


rawDescription: Python Environment variable within environment variable


code: newlist

rawDescription: Transform a list of dicts to a new list of dicts with a different format


code:
import types
types.ModuleType('name')

rawDescription: Python importlib's analogue for imp.new_module()


code: all(key in dict_obj for key in properties_to_check_for)

rawDescription: Check to see if a collection of properties exist inside a dict object in Python


code:
for link in soup.select('a[href*=players]'):
    print(link["href"])

rawDescription: Using `find_all()` to get all tags of a subset of that same tag


rawDescription: python numpy array of arbitrary length strings

description: Python numpy array of arbitrary length strings


code:
# The Class has to inherit QtCore.Object

class ConsoleProcessRunner(QtCore.QObject):
    # The Signals that allow the callback are declared

    cout = QtCore.Signal(str)
    quit = QtCore.Signal(int)

    # Constructor
    def __init__(self, parent = None):
        super(ConsoleProcessRunner, self).__init__(parent)

    def your_function_here():
        # now you can use our previously defined signals to do the callback
        # your code goes here
        self.cout.emit(stdoutdata)
        self.quit.emit(ret)

rawDescription: How to call a function in pyside MainWindow from another python script

description: Call a function in pyside MainWindow from another python script


code:
def main():
    #do stuff
    f()
    g()
    ...

rawDescription: Best way to put functions python

description: Put functions python


code:
class NoneFound:
  @classmethod
  def split(self, _):
    return None

rawDescription: In Python, what is a minimal way of assigning a value to a variable depending on whether a dictionary contains a key?


rawDescription: Fixing values in columns of a csv file with python


rawDescription: how to specify version of python to run a script?

description: Specify version of python to run a script


code:
imgobj = Image.open('x.png')
pixels = imgobj.convert('RGBA')
data = imgobj.getdata()
lofpixels = []
for pixel in data:
    lofpixels.extend(pixel)

rawDescription: List all RGBA values of an image with PIL


code:
def compareFiles():
    if rsef == rssf:
        print("Congratulations! Puzzle Solved!")
    else:
        print("Sorry! Try Again!")
        secMenu()

rawDescription: Python Basics - Comparing 2 Arrays

description: Python Basics - Comparing 2 Arrays


rawDescription: How to treat a returned/stored string like a raw string in Python?

description: Treat a returned/stored string like a raw string in Python


code:
q = self.request.get('q')
if q is '':
  custQuery = db.Query(Customer)
elif q is None:
  q = '' #Force it! (Previously: q is '' - and it works.)
  custQuery = db.Query(Customer)
elif q!=None:
  custQuery = db.Query(Customer)
  custQuery.filter('license = ',q)

rawDescription: Receiving the requests and using If else statements on Queries with None in Python GAE