code:
if slotNumber == 1:
    Popen("TASKKILL /F /PID {pid} /T".format(pid=self.process1.pid), startupinfo=startupinfo)
elif slotNumber == 2:
    Popen("TASKKILL /F /PID {pid} /T".format(pid=self.process2.pid), startupinfo=startupinfo)
elif slotNumber == 3:
    Popen("TASKKILL /F /PID {pid} /T".format(pid=self.process3.pid), startupinfo=startupinfo)
elif slotNumber == 4:
    Popen("TASKKILL /F /PID {pid} /T".format(pid=self.process4.pid), startupinfo=startupinfo)

rawDescription: Popen process not quitting / releasing when finished in Python


code:
canvas.delete('current&&token') #logical operator in tag search expression

# && = AND, || = OR, ! = NOT

rawDescription: Capability to delete all items with certain object tag tkinter


code:
xx = []
for x in l:
  a, b = x[0], x[1]
  xx += range(a, b+1)

xx
sorted(xx)

rawDescription: Python expand integers inside a list and sort them


code:
import subprocess
proc = subprocess.Popen(['foo', 'bar', 'bar'], stdout=subprocess.PIPE, shell=True)

rawDescription: Stop a command line command in script

description: Stop a command line command in script


code:
df['DATA']
df['DATA'].str.rjust(6,'0')

rawDescription: Add 0 to number with 5 characters (pandas)


rawDescription: Grouping 0s and 1s in python

description: Grouping 0s and 1s in python


code:
class myIterator:
    def __init__(self, n):
        self.last = n

    def __iter__(self):
        prev = 0
        fib = 1
        while fib < self.last:
            res = fib
            yield res
            fib += prev
            prev = res

rawDescription: What is the best way to write a python iterator based on a generator


rawDescription: max row sequence from sorted list for each index

description: Max row sequence from sorted list for each index


code: df.a/df.b.replace({ 0 : np.nan })

rawDescription: handling zeros in pandas DataFrames column divisions in Python

description: Handling zeros in pandas DataFrames column divisions in Python


code:
df.to_hdf('/tmp/out.h5', 'results_table', mode='w', data_columns=True,
          format='table')

rawDescription: read HDF5 file to pandas DataFrame with conditions

description: Read HDF5 file to pandas DataFrame with conditions


code:
for code, (name, num) in dict3.items():
    print(code, name, num)

rawDescription: How to mixing two dictionaries in Python?

description: Mixing two dictionaries in Python


code:
sorter = numpy.lexsort(A[::-1])
sorted_copy = A.T[sorter].T

sorter[list(search2D(sorted_copy, B))]
#>>> array([ 3,  6, 14])

rawDescription: Numpy find indices of matching columns

description: Numpy find indices of matching columns


code:
print('Hello world!')
print('What is your name?')
myName = input()

while True:
    print('It is nice to meet you, ' + myName)

rawDescription: How do I use "while" in this situation

description: Use "while" in this situation


code:
with open('myfile.bin', 'rb') as f:
    with mmap.mmap(f, 0, access=mmap.ACCESS_READ) as m:
        for offset in range(0, m.size(), record.size):
            yield record.unpack_from(m, offset)

rawDescription: Can someone explain Python struct unpacking?


code:
...
data = data.flatten()
...

rawDescription: Python lmfit: Fitting a 2D Model

description: Python lmfit: Fitting a 2D Model


code: np.ndarray.sum(self, axis, dtype, out, keepdims=True)._collapse(axis)

rawDescription: Python/numpy issue with array/vector with empty second dimension


code:
import seaborn as sns

sns.barplot(x='Name', y='var', hue='hour', data=df, saturation=0.8)

rawDescription: Pandas plot on 3 variables

description: Pandas plot on 3 variables


code:
def findRuns(L):
    answer = []
    start = 0
    n = L[start]
    for i,num in enumerate(L[1:],1):
        if num <= n:
            n = num
        else:
            answer.append(L[start:i])
            start = i
            n = L[start]
    answer.append(L[start:])
    return answer

rawDescription: largest array, sorted in reverse order from the given array

description: Largest array, sorted in reverse order from the given array


code:
unique_together = (('nodeIndex', 'refdate', 'nodeType'), )
ordering = ['nodeIndex', 'refdate', 'nodeType']

rawDescription: Django Models - SELECT DISTINCT(foo) FROM table is too slow


code:
class ProductForm(ModelForm):
    long_desc = forms.CharField(widget=forms.Textarea)
    short_desc = forms.CharField(widget=forms.Textarea)
    class Meta:
        model = Product

    # Edit by bryan
    def __init__(self, *args, **kwargs):
        super(ProductForm, self).__init__(*args, **kwargs) # Call to ModelForm constructor
        self.fields['long_desc'].widget.attrs['cols'] = 10
        self.fields['long_desc'].widget.attrs['rows'] = 20

rawDescription: Change the width of form elements created with ModelForm in Django


code:
import argparse

parser1 = argparse.ArgumentParser(add_help=False)
parser1.add_argument("first")

parser2 = argparse.ArgumentParser(parents=[parser1])
parser2.add_argument("second")
args2 = parser2.parse_args(["arg1","arg2"])
assert args2.first == "arg1" and args2.second == "arg2"

rawDescription: How ca I get Python ArgParse to stop overwritting positional arguments in child parser


code:
def class_decorator(cls):
    # modify cls
    return cls

rawDescription: decorate specific methods of a class

description: Decorate specific methods of a class


code:
class reg(object):
 def __init__(self, cursor, row):
    for (attr, val) in zip((d[0] for d in cursor.description), row) :
        setattr(self, attr, val)

rawDescription: presto fetch data

description: Presto fetch data


code: os.path.join(ls, 'foo.txt')    # throws an AttributeError.

rawDescription: call function through variable or without parentheses in python

description: Call function through variable or without parentheses in python


code: results = [q for q in product(range(0, d+1), repeat=len(p)) if dot(p, q, d) == d]

rawDescription: solve particular symbolic equation in python

description: Solve particular symbolic equation in python


code:
import pandas

df = pandas.concat([pak2_df.set_index('time'), pcAbl_df.set_index('time')], axis=1).reset_index()
print(df)

rawDescription: Concatenate pandas dataframes via a column and filling in blanks with 'NaN'


code:
m = sparse.rand(100, 100, density=0.1, format='csr')
print((orig_efreqs(m.copy()) != fast_efreqs(m)).nnz == 0)
# True

rawDescription: Faster way to build a matrix of expected frequencies from a sparse matrix of counts


rawDescription: Finding ElasticSearch records matching empty and null values


code:
import sys, select, tty, termios
class NonBlockingConsole(object):
    def __enter__(self):
        self.old_settings = termios.tcgetattr(sys.stdin)
        tty.setcbreak(sys.stdin.fileno())
        return self

    def __exit__(self, type, value, traceback):
        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)

    def get_data(self):
        try:
            if select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], []):
                return sys.stdin.read(1)
        except:
            return '[CTRL-C]'
        return False

data = ''
printed = ''
last = ''
with NonBlockingConsole() as nbc:
    while 1:
        c = nbc.get_data()
        if c:
            if c == '\x1b': # x1b is ESC
                break
            elif c == '\x7f': # backspace
                data = data[:-1]
                printed = data[:-1]
                last = ''
                sys.stdout.write('\b')
            elif c == '[CTRL-C]':
                data = ''
                last = ''
                sys.stdout.write('\n')
            elif c == '\n': # it's RETURN
                sys.stdout.write('\n')
                # parse data here
                data = ''
            else:
                data += (c)
                last = c
                sys.stdout.write(c)

rawDescription: read raw input from keyboard in python

description: Read raw input from keyboard in python


code:
FILTMAP = {'>=': '$gte', '<=': '$lte', '>': '$gt', '<': '$lt', "!=":"$ne"}
CONJUNCTION_MAP = {"AND":"$and", "OR":"$or"}

def convert_column(dic):
    if not dic['operator'] in FILTMAP:
        return {dic['column']: dic['value']}
    else:
        value = float(dic['value']) if dic['operator'] == "!=" else dic['value']
        return {dic['column']: {FILTMAP[dic['operator']]: value}}

def convert(dic):
    for k,v in dic.items():
        if isinstance(v, list):
            if k in CONJUNCTION_MAP:
                k = CONJUNCTION_MAP[k]
            return {k: [convert(i) for i in v]}
        else:
            return convert_column(dic)

rawDescription: Python dictionary to equivalent pymongo statement


code:
import json
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
for line in inp:
    if not line.strip():
        out.write(line)
        continue
    in_as_obj = json.loads(line)
    json.dump(in_as_obj, out, ensure_ascii=False)
    out.write('\n')

rawDescription: How can I replace Unicode characters with Turkish characters in a text file with Python

description: Replace Unicode characters with Turkish characters in a text file with Python


code: mylist.sort(key=lambda d: (d['weight'], d['factor']))

rawDescription: Ordering a list of dictionaries in python


code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.dates import DateFormatter
from matplotlib.dates import HourLocator

small_dataset = pd.read_csv('SURVEY_RESULTS_WEEK1.csv', header=0,index_col=0, parse_dates=0)
big_dataset = pd.read_csv('PIRDATA_RAW_CONVERTED_DATETIME.csv', header=0,index_col=0, parse_dates=0)

small_dataset.rename(columns={'Occupancy': 'Survey'}, inplace=True)
big_dataset.rename(columns={'Occupancy': 'PIR'}, inplace=True)

big = big_dataset.plot()
big.xaxis.set_major_formatter(DateFormatter('%y-%m-%d H: %H'))
big.xaxis.set_major_locator(HourLocator(np.arange(0, 25, 6)))
big.set_ylabel('Occupancy')

small_dataset.plot(ax=big, drawstyle='steps')

fig = plt.gcf()
fig.suptitle('PIR and Survey Occupancy Comparsion')

plt.show()

rawDescription: How do create a step chart in Pandas with time series data from two seperate data sources


code:
t = raw_input("Enter list items: ")
l = [int(x) if x.isdigit() else x for x in t.split()]
l

rawDescription: How to create a list with strings and integers as its elements?

description: Create a list with strings and integers as its elements


code: roll_gap = esm.loc[roll_date, 'Settle'] - esh.loc[roll_date, 'Settle']

rawDescription: Build Back Adjusted Continous Futures contract from Historical Data


code:
#data_str is an RGB image with dims sx and sy
format_str = str(sx*sy*3).strip() + 'B'
im_data = struct.unpack(format_str, data_str) #conversion to tuple

rawDescription: passing Array[Byte] from ironpython to python using pickle

description: Passing Array[Byte] from ironpython to python using pickle


code:
from operator import itemgetter
tuple(set(map(lambda x:itemgetter(1)(x),mytuple)))

rawDescription: Dropping values from a list of tuples

description: Dropping values from a list of tuples


code:
string_version = ''.join(map(chr, S))
list_version = list(map(ord, string_version))

rawDescription: Clean conversion from int list to character and then back to int list, in Python


rawDescription: Randomly replace 2 values in python dictionary


code:
neigh_sum = np.zeros_like(lattice)
#-- neighbors at (i-1, j+1)
neigh_sum += np.pad(lattice, ((1,0),(1,0)), 'constant')[:-1,:-1]
#-- neighbors at (i+1, j+1)
neigh_sum += np.pad(lattice, ((1,0),(0,1)), 'constant')[:-1,1:]
#-- neighbors at (i+1, j-1)
neigh_sum += np.pad(lattice, ((0,1),(0,1)), 'constant')[1:,1:]
#-- neighbors at (i-1,j-1)
neigh_sum += np.pad(lattice, ((0,1),(1,0)), 'constant')[1:,:-1]

rawDescription: Numpy vectorization for nearest neighbor calculation in semi-sparse arrays


code:
{'geometry': {'coordinates': '[[0,1],[2,3],[4,5]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}
{'geometry': {'coordinates': '[[6,7],[8,9]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}
{'geometry': {'coordinates': '[[10,11],[12,13],[14,15],[16,17],[18,19]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}
{'geometry': {'coordinates': '[[20,21],[22,23]]',
              'type': 'Linestring'},
 'properties': {'prop0': 'red',
                'prop1': 'dashed'},
 'type': 'Feature'}

rawDescription: How to write a Python loop to convert a large amount of coordinates into the GeoJSON LineString format?

description: Write a Python loop to convert a large amount of coordinates into the GeoJSON LineString format


code:
for name, values in d.items():
    print("{name} {avg}".format(name=name, avg=sum(values)/len(values)))

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

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


rawDescription: Coordinates of boxes in Seaborn boxplot

description: Coordinates of boxes in Seaborn boxplot


code:
lst_data = ["SDE_AGS_ADM.PLUVIOMETRIE \ SDE_AGS_ADM.Pluviometres_DAVAR",
            "SDE_AGS_ADM.AIRE_PROTEGE_GOUV \ SDE_AGS_ADM.reserves_integrales_R",
            "SDE_AGS_ADM.DGRSC_Lignes_feu"]
new = [item.split('.')[-1] for item in lst_data]

rawDescription: Search strings behind an index

description: Search strings behind an index


rawDescription: How can I obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy?

description: Obtain the same 'special' solutions to underdetermined linear systems that Matlab's `A \ b` (mldivide) operator returns using numpy/scipy


code: Mail(subject='Goodbye', body='This is not a test\nNo one cares\nFoo bar foo bar foo bar\nRegards\n')

rawDescription: Python: Email content configuration file


code: [{'location':l, 'name':n, 'value':v} for (n, l, v) in all_values]

rawDescription: Creating an iterable of dictionaries from an iterable of tuples


code:
for i in range(len(n)):
   item = n[i]
   item *= 2

rawDescription: What's the difference?< for item in list> and <for i in range(len(list))>


code:
class SearchView(View):
    model = MyModel
    template_name = 'template.html'

    def get(self, request, *args, **kwargs):
        a = request.GET['a']
        b = request.GET['b']
        obj = self.model.get(field1=a, field2=b)
        return render(request, self.template_name, {'obj': obj})

rawDescription: Django template/form for user input

description: Django template/form for user input


code: [t for testrec in testrecord for t in restrec['testdata'] if t.get('color') == 'green']

rawDescription: Nested list of dicts comprehension syntax


code:
resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

rawDescription: Extract single value from JSON response Python


rawDescription: Why java String.length gives different result than python len() for the same string


rawDescription: array construction in python

description: Array construction in python


code: sql, values = theobj.updater()

rawDescription: Efficient way to build a MySQL update query in Python


code:
deviation = grouped.transform(lambda x: x - x.mean())
deviation.cumsum()

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


rawDescription: Python defaultdict get original dictionary


code: title = data.xpath("//*[re:match(@id, '[0-9]+')]/span/text()").extract()

rawDescription: Can we add regular expression in scrapy .xpath()


code:
def insert(list1, var, i):
    # Uglier without unpacking generalizations
    list1[i], list1[i+1:] = var, list1[i:-1]

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

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


code: fields = [ f.name for f in Part._meta.fields if f.name != 'id' ]

rawDescription: writing test for importing contents of text file into database using python and django

description: Writing test for importing contents of text file into database using python and django


code: myfilter = kwargs.pop('myfilter')

rawDescription: Django: ModelMultipleChoiceField doesn't select initial choices


code: ['Blue,sky,ethernet cable', 'Green', 'Blue,sky,ethernet cable', 'Blue,sea']

rawDescription: Exclude repeated values from a dictionary and increment the 'qty' field accordingly


code:
from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

def does_segment_exist(iterable, sublist):
    return tuple(sublist) in window(iterable, len(sublist))

print(does_segment_exist([1,3,4,5,2], [3,4,5]))

rawDescription: Finding consecutive values within a list


rawDescription: Explanation of program's behavior (Python)


code:
from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))

rawDescription: How to query as GROUP BY in django?

description: Query as GROUP BY in django


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def main():
    x, y, z = generate_data()
    plot(x, y, z)
    plt.show()

def generate_data():
    lat, lon = np.radians(np.mgrid[-90:90:20j, 0:180:20j])
    lon -= np.radians(40)
    z = np.cos(lat) * np.cos(lon)
    x = np.cos(lat) * np.sin(lon)
    y = np.sin(lat)
    return x, y, z

def plot(x, y, z):
    fig, ax = plt.subplots(subplot_kw=dict(projection='3d'), facecolor='w')
    artist = ax.scatter(x, y, z, marker='o', color='y')
    ax.set(xlim=[-1.1, 1.1], ylim=[-1.1, 1.1], zlim=[-1.1, 1.1], aspect=1)
    ax.set(xlabel='X', ylabel='Y', zlabel='Z')
    return artist

main()

rawDescription: Finding the opening of a 3D surface

description: Finding the opening of a 3D surface


code:
def yield_and_flatten(nested):
    """Yield sublists and flatten, recursively

    Produces a boolean and list on each yield; the boolean
    flags a merge; sublists are merged just once then
    passed down the recursion tree.

    """
    if not isinstance(nested, list):
        yield True, nested
        return
    res = []
    for elem in nested:
        for extend, sub in yield_and_flatten(elem):
            if isinstance(sub, list):
                if extend:
                    res.extend(sub)
                yield False, sub
            else:
                res.append(sub)
    yield True, res

rawDescription: Python: how to generate a list of "flattened" lists out of a big nested list


code:
datafile = open(b'C:\Users\j\Desktop\helloworld.csv', 'r')
data = []
for row in datafile:
   data.extend(item.strip() for item in row.split())
print(data)

rawDescription: Create a column from a CSV list in Python 3


code:
from functools import partial

[(partial(f, month), partial(g, month)) for month in months]

rawDescription: Python: How to pass functions to another function as arguments?


rawDescription: stretch, scale, or double up an array with numpy?

description: Stretch, scale, or double up an array with numpy


code:
s = 'length 95 width 332 length 1253 length 345 width 22'
import re
re.findall(r'length (\w+)', s)

rawDescription: Find associated value to a keyword in file with python


code:
class TreeExpander:
   def __init__(self, node_tree, matching_items):
       self.node_tree = node_tree
       self.matching_items = matching_items
   def double_click(self, item_name):
      print("double_click ({0})".format(item_name))
      if (item_name in self.matching_items):
         reach(self.node_tree, self.matching_items[item_name])

rawDescription: Python Tkinter: Tree selection

description: Python Tkinter: Tree selection


code:
for i in range(1, 32):
  if i%column != 0:
    print(str(i).rjust(3)),
  else:
    print(str(i).rjust(3))

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


code:
import json
json.loads(str)

rawDescription: Django recive array ajax problem

description: Django recive array ajax problem


rawDescription: numpy - issue with creating a 2D matrix

description: Numpy - issue with creating a 2D matrix


code:
arr=np.ones((10,))
for i in range(2,arr.shape[0]):
     arr[i]=arr[i-1]+arr[i-2]

rawDescription: How to iterate an array in Python pointer-likely and efficiently?

description: Iterate an array in Python pointer-likely and efficiently


code:
# handles edge cases correctly on MY computer
# not extensively QA'd...
import math
# 'double' means IEEE 754 double precision -- c 'double'
epsilon  = math.ldexp(1.0, -53) # smallest double that 0.5+epsilon != 0.5
maxDouble = float(2**1024 - 2**971)  # From the IEEE 754 standard
minDouble  = math.ldexp(1.0, -1022) # min positive normalized double
smallEpsilon  = math.ldexp(1.0, -1074) # smallest increment for doubles < minFloat
infinity = math.ldexp(1.0, 1023) * 2

def nextafter(x,y):
    """returns the next IEEE double after x in the direction of y if possible"""
    if y==x:
       return y         #if x==y, no increment

    # handle NaN
    if x!=x or y!=y:
        return x + y

    if x >= infinity:
        return infinity

    if x <= -infinity:
        return -infinity

    if -minDouble < x < minDouble:
        if y > x:
            return x + smallEpsilon
        else:
            return x - smallEpsilon

    m, e = math.frexp(x)
    if y > x:
        m += epsilon
    else:
        m -= epsilon

    return math.ldexp(m,e)

rawDescription: Increment a python floating point value by the smallest possible amount


code:
import timeit
timeit.timeit('nums[0];nums[1];nums[2]', setup='nums = [1,2,3]')
timeit.timeit('for i in nums:pass', setup='nums = [1,2,3]')
timeit.timeit('for i in range(len(nums)):pass', setup='nums = [1,2,3]')

rawDescription: Why is direct indexing of an array significantly faster than iteration?


rawDescription: How to initialize NumPy structured array with different default value for each column?

description: Initialize NumPy structured array with different default value for each column


code:
def compare(file1, file2):
    # This file SHOULD be one line. But just in case, do a loop anyways.
    homer = ''
    with open(file2, 'r') as f:
        for line in f:
            homer += line

    with open(file1, 'r') as f:
        for line in f:
            data = line.split()

            # -1 and 3 are indices where the Motif Num and TF are
            # located in the list.
            homer = homer.replace('homer{}'.format(data[-1]), data[3])

rawDescription: Iterating through file and retaining data in list - Python


code:
def calculator(user_input):
    global ans
    if any(c not in "0123456789-+/*ansqrt() \n" for c in user_input):
        print("- Invalid Equation | Bad characters")
        return
    time.sleep(0.1)
    print (" | 100%")
    try:
        ans = eval(user_input, {'ans':ans,'sqrt':sqrt},{})
    except (SyntaxError, ZeroDivisionError, NameError, TypeError, ValueError):
        print ("- Invalid Equation | Error")
        return
    print (ans)
calculator('1+2')
calculator('ans')
from math import sqrt
calculator('sqrt(ans)')

rawDescription: Using user defined variables/functions in eval [Python 3.4.2]?


rawDescription: Faster way to compare thousands of values


code:
def on_button_pressed(Panel,event):

    RightPanel().SetBackgroundColour("light blue")

rawDescription: wx.Python: Passing control between multiple panels

description: Wx.Python: Passing control between multiple panels


code:
from nltk.corpus import wordnet
wordnet.synsets('donation')
wordnet.synsets('donations')

rawDescription: using python nltk to find similarity between two web pages?

description: Using python nltk to find similarity between two web pages


code:
fig = gcf()
fig.canvas.manager.window.raise_()

rawDescription: make matplotlib plotting window pop up as the active one

description: Make matplotlib plotting window pop up as the active one


code: {name_: Counter(map(str, data)) for name_, data in zip(name, n1)}

rawDescription: Make dictionary from two lists using Counter object


code: do = deco(do)

rawDescription: How to apply a python decorator to a function?

description: Apply a python decorator to a function


code:
p = np.argsort(A)

B[:, p][p, :]  # rearrange rows and column of B
B.transpose(p)  # rearrange dimensions of B

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


code:
import traceh
traceh.install()

raise NameError
print(5)
print(6)

rawDescription: Python: resuming program at line number in the context before an exception using a custom sys.excepthook


code:
from __future__ import division
3/2
10/9
1/3
7/8
7/9

rawDescription: Python - How to return a double with eval()


rawDescription: Python regular expressions (extracting monetary value from a string)


code: my_url = reverse('ACB', args=(slug,))

rawDescription: Get urls in views.py - python django

description: Get urls in views.py - python django


code:
def solve(arr):
    index = 0
    total = 0
    end = len(arr)
    flag = False
    while index < len(arr) and not flag:
        total += arr[index]
        index += 1
        if total > 100:
            end = index
            flag = True
    print(*arr[0:end], sep = ' ')

solve([100, -3, 4, 7])
solve([1, 2, 3])
solve([101, -3, 4, 7])

rawDescription: Printing out all the numbers in a list if the sum of those numbers exceed 100.


rawDescription: Pygame not displaying text

description: Pygame not displaying text


code: homeless_mask = (df['ChangeEvent']=='Homeless') & (df['first']==1)

rawDescription: add columns where condition is met, but preserve previous value in pandas python

description: Add columns where condition is met, but preserve previous value in pandas python


code:
import mystuff

mystuff.apple()

rawDescription: Python module object without a file

description: Python module object without a file


code: np.sum(n * np.diff(bins))

rawDescription: plotting histograms whose bar heights sum to 1 in matplotlib

description: Plotting histograms whose bar heights sum to 1 in matplotlib


code:
import collections

def map_nested_dicts_modify(ob, func):
    for k, v in ob.iteritems():
        if isinstance(v, collections.Mapping):
            map_nested_dicts_modify(v, func)
        else:
            ob[k] = func(v)

map_nested_dicts_modify(x, lambda v: v + 7)
# x is now
#    {'a': 8, 'b': {'c': 13, 'g': {'h': 10, 'i': 16}, 'd': 14}, 'e': {'f': 10}}

rawDescription: Python: Apply function to values in nested dictionary


rawDescription: Bitwise & outputting numbers other than 1 and 0


code:
a[indices] #returns all elements where the l_dist returns smaller than 2
a[~indices] #returns everything >= 2

rawDescription: Efficient way to sort an array with a condition


code:
# spawnProcess requires you to implement a ProcessProtocol
class TwitterProcess(protocol.ProcessProtocol):
    def outReceived(self, data):
        print("TWITTER: ", data)

    def errReceived(self, data):
        print("TWITTER ERR: ", data)

    def processEnded(self, reason):
        print("twitter process ended.")

# later on...

args = ["python", "twitter_stream.py"] # add other args here if necessary
pp = TwitterProcess()
feedProcess = reactor.spawnProcess(pp, "python", args)

rawDescription: Close Twitty Twister Stream

description: Close Twitty Twister Stream


code:
PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher',
)

rawDescription: How to use Bcrypt to encrypt passwords in Django

description: Use Bcrypt to encrypt passwords in Django


code:
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        uic.loadUi('window.ui', self)

main_window = MainWindow()

rawDescription: PyQt change element in .ui file

description: PyQt change element in .ui file


code:
import matplotlib.pyplot as plt
f1 = plt.figure()
f2 = plt.figure()
ax1 = f1.add_subplot(111)
ax1.plot(range(0,10))
ax2 = f2.add_subplot(111)
ax2.plot(range(10,20))
plt.show()

rawDescription: How can I show figures separately in matplotlib?

description: Show figures separately in matplotlib


code:
class MyHandler(WebSocketHandler):
    connections = {}

    def __init__(self, *args, **kwargs):
        self.key = str(self)
        self.connections[self.key] = self

rawDescription: Non-Blocking WebSocketHandler while receiving jobs from a queue


code:
class MyModelStackedInline(generic.GenericStackedInline):
    model = MyModel
    formset = MyInlineFormset
    extra = 0

rawDescription: Django: disallow can_delete on GenericStackedInline


code:
[['prova.py'], ['GCI', ''], ['GCI', 'prova2.py'],
 ['GCI', 'PyFiles', ''], ['GCI', 'PyFiles', 'prova3.py'],
 ['GCI', 'Screenshots', '']]

rawDescription: Directory tree in a QTreeWidget

description: Directory tree in a QTreeWidget


code:
import re
from textwrap import dedent
try:
    from textwrap import indent
except ImportError:
    def indent(s, prefix):
        return prefix + prefix.join(s.splitlines(True))

class Indentable(str):
    indent_format_spec = re.compile(r'''i([0-9]+)''')

    def __format__(self, format_spec):
        matches = self.indent_format_spec.search(format_spec)
        if matches:
            level = int(matches.group(1))
            first, sep, text = dedent(self).strip().partition('\n')
            return first + sep + indent(text, ' ' * level)

        return super(Indentable, self).__format__(format_spec)

sample_format_string = '''\
  {doc:i2}
  {static}auto {fun}({formals}){const}
    -> {result};
'''

specs = {
    'doc': Indentable('''
        // Convert a string to a float.
        // Quite obsolete.
        // Use something better instead.
    '''),
    'static': '',
    'fun': 'atof',
    'formals': 'const char*',
    'const': '',
    'result': 'float',
}

print(sample_format_string.format(**specs))

rawDescription: Indentation preserving formatting of multiline strings


code: form = MyModelFormWithFileField(request.POST, None)

rawDescription: Is there any way django does not save the file uploaded with form


rawDescription: how to ADD a one list to another in python?

description: ADD a one list to another in python


code:
S_recalculated = 1. / np.sqrt((pca.components_ ** 2).sum(axis=1) / n_samples_train)
assert_array_almost_equal(S, S_recalculated)

rawDescription: Inversing PCA transform with sklearn (with whiten=True)


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

list(foo())

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


rawDescription: Python regex get address without zip code


code:
entry1.VoucherType = 'GV'
entry1.VoucherReq.append([12,34,56])
entry1
entry1.VoucherReq.append(23)
entry1
it.VoucherReqDtls.append(entry1)
it

rawDescription: SUDS: Pass Array Parameter in Client.service Method : GAE Python


code: [sorted(c) for e in dict_list for c in zip(*e.values())]

rawDescription: List of Dictionaries which contain lists


code:
from django.core.mail import get_connection, EmailMessage
from django.core.mail.backends.smtp import EmailBackend

config = Configuration.objects.get(**lookup_kwargs)

backend = EmailBackend(host=config.host, port=congig.port, username=config.username,
                       password=config.password, use_tls=config.use_tls, fail_silently=config.fail_silently)

rawDescription: Dynamic Django Mail Configuration

description: Dynamic Django Mail Configuration


code:
import sys

def main():
    log1 = sys.argv[1]
    log2 = sys.argv[2]

    with open(log1, 'r') as f:
        # print that first line only
        print (f.readline().strip('\n'))

        # print the other lines
        for l in f:
            print(l.strip('\n'))

if __name__ == "__main__":
    main()

rawDescription: How to print single lines from file

description: Print single lines from file


code:
def get_data(request, xml_data):
    data = parse_xml_data(xml_data)
    return_data = create_xml_blob(data)
    return HttpResponse(return_data, mimetype='application/xml')

rawDescription: Simple XML over http web service

description: Simple XML over http web service


rawDescription: Substituting the User model in django with more than one user auth model


rawDescription: 3 Dimensional Data in Python

description: 3 Dimensional Data in Python


rawDescription: Python: split bytes with a hexadecimal delimiter


code:
class MyList(list):
  def append(self, x):
    super(MyList, self).append(x)
    return self
  def extend(self, lst):
    super(MyList, self).extend(lst)
    return self

l = MyList([1, 2, 3])
l.append(4)
l.extend([5, 6, 7])
l

rawDescription: Functional append/extend

description: Functional append/extend


code: df['c'] = (df.groupby('group_id').cumcount() == 0).astype(int)

rawDescription: Python - Pandas: select first observation per group


rawDescription: Multiple parameters in Django URLconf

description: Multiple parameters in Django URLconf


rawDescription: Split list into dictionary

description: Split list into dictionary


code:
import re

_range = re.compile(rb'(.)-(.)')
def _range_expand(match):
    start, stop = match.group(1)[0], match.group(2)[0] + 1
    if start < stop:
        return bytes(range(start, stop))
    return match.group(0)

def expand(s1):
    return _range.sub(_range_expand, s1)

rawDescription: converting a C function into Python3 form?

description: Converting a C function into Python3 form


rawDescription: Twython: Filtering more than one track.

description: Twython: Filtering more than one track.


code:
timezone_countries = {}
for country, timezones in country_timezones.items():
    for timezone in timezones:
        timezone_countries.setdefault(timezone, set()).add(country)

rawDescription: How to convert timezone to country code in Python?

description: Convert timezone to country code in Python


code:
import string
#ABC -> 012 map
abc = {i:j for j,i in enumerate(string.uppercase)}
#012 -> ABC map
abcinv = string.uppercase
#input
x = 'ADEC'
xm = abc[max(list(x), key=ord)] + 1
# data matrix
data = np.zeros((xm, xm))
# we need the permutations of the indexes
xv = [abc[i] for i in x]
for i,j in itertools.permutations(xv,2):
    data[i][j] += 1

#ensure diagonal is empty
np.fill_diagonal(data, 0)
plt.imshow(data, interpolation='none', cmap='Greys');
plt.axis('off');

rawDescription: python iterate over list elements for all combinations and perfom some action

description: Python iterate over list elements for all combinations and perfom some action


code:
a = numpy.array(zip(x, y, ov, aa))
a[a == 1]

rawDescription: combining numpy arrays and masking

description: Combining numpy arrays and masking


code:
def precalc1(jmat):
  # calc all the 'outer' sums/diffs, and zero the k=i,j terms
  ii = np.arange(jmat.shape[0])
  JM1 = jmat[:,:,None] + jmat[:,None,:]
  JM2 = jmat[:,:,None] - jmat[:,None,:]
  JM1[ii,ii,:] = 0
  JM2[ii,ii,:] = 0
  JM1[ii,:,ii] = 0
  JM2[ii,:,ii] = 0
  JM1 = JM1.transpose([1,2,0])
  JM2 = JM2.transpose([1,2,0])
  return JM1, JM2

rawDescription: Implementing intereaved products and sums in Python without loop overhead


code:
import requests

s = requests.Session()

s.get('http://localhost/getEmployees/1')                    # Get first 50
s.get('http://localhost/getEmployees/1')                    # Get next 50

params = {'offset': 0};
s.get('http://localhost/getEmployees/1', params=params)     # Get First 50

rawDescription: flask , breaking query?

description: Flask , breaking query


code:
import sys
int_list = [int(x) for x in sys.argv[1:]]

rawDescription: Input n elements seperated by space in python


code:
class Room(object):
    def __init__(self, name, availability, description, price):
        self.name = name
        self.availability = availability
        self.description = description
        self.price = price

rooms = [Room('BlueRoom', 5, 'Blue', 120), ...]

rawDescription: remove all values from multiple lists at same index position with some logic

description: Remove all values from multiple lists at same index position with some logic


code:
df1 = df.groupby('id').agg(lambda x: x.tolist())
type(df1)

rawDescription: Concatenate rows of pandas DataFrame with same id


code:
from elementtree import ElementTree as ETree
ET = ETree
ET.xml_declaration = "true"
products = ET.Element("products")
properties = ET.Element("properties")
products.append(properties)
products.attrib["xmlns"] = "http://schema.example.com/product_data_1.0"
update = ET.Element("update")
delete = ET.Element("delete")
products.append(delete)
products.append(update)

rawDescription: Write values of Python dictionary back to file


code:
def mutable_repeat(container):
    while True:
        for item in container.copy():
            yield item

rawDescription: Round robin on iterable

description: Round robin on iterable


rawDescription: -> in python function definition

description: -> in python function definition


code:
class Foo(models.Model):
    action_type = models.CharField(max_length=50)

rawDescription: What is an efficient way to get a count of objects grouped by a field in Django?


code:
import StringIO
import numpy as np

def PrintResToFile(filename,result):
  def StripMX(x):
    return str(x).replace('MX(','').replace(')','')

  varstr = '#Variable Name={name: <10}, Unit={unit: <7}, Val={val: <10}, Col={col:< 5}, Comment="{comment}"\n'

  with open(filename,'w') as fout:
    #Print all variables at the top of the file, along with relevant information
    #about them.
    for var in result.model.getAllVariables():
      if not result.is_variable(var.getName()):
        val = result.initial(var.getName())
        col = -1
      else:
        val = "Varies"
        col = result.get_column(var.getName())

      unit = StripMX(var.getUnit())
      if not unit:
        unit = "X"

      fout.write(varstr.format(
        name    = var.getName(),
        unit    = unit,
        val     = val,
        col     = col,
        comment = StripMX(var.getAttribute('comment'))
      ))

    #Ensure that time variable is printed
    fout.write(varstr.format(
      name    = 'time',
      unit    = 's',
      val     = 'Varies',
      col     = 0,
      comment = 'None'
    ))

    #The data matrix contains only time-varying variables. So fetch all of
    #these, couple them in tuples with their column number, sort by column
    #number, and then extract the name of the variable again. This results in a
    #list of variable names which are guaranteed to be in the same order as the
    #data matrix.
    vkeys_in_order = map(lambda x: x[1], sorted([(result.get_column(x),x) for x in result.keys() if result.is_variable(x)]))

    for vk in vkeys_in_order:
      fout.write("{0:>13},".format(vk))
    fout.write("\n")

    sio = StringIO.StringIO()
    np.savetxt(sio, result.data_matrix, delimiter=',', fmt='%13.5f')
    fout.write(sio.getvalue())

rawDescription: Can JModelica print results directly to file?


code:
s="""[1:368:6] ICMP PING BSDtype [**]
[1:368:6] ICMP PING BSDtype [**]
[1:368:6] ICMP PING BSDtype [**]
[1:368:6] ICMP PING BSDtype [**]
[1:563:2] ICMP PING BSDtype [**]"""
set(s.split('\n'))

rawDescription: Use regular expression to delete duplicate strings with python


code: mylist = [s.rstrip('-') for s in mylist]

rawDescription: remove a character from all strings in a list

description: Remove a character from all strings in a list


code:
mydictionary = {"OuterKey1": {"InnerKey1": "Value1", "InnerKey2": "Value2"}, "OuterKey2": {"InnerKey1": "Value3", "InnerKey2": "Value4"}}
d = {}
for k, v in mydictionary.items():
    for ik, iv in v.items():
            d.setdefault(ik, {})[k] = iv

# result:
# d == {'InnerKey2': {'OuterKey2': 'Value4', 'OuterKey1': 'Value2'}, 'InnerKey1': {'OuterKey2': 'Value3', 'OuterKey1': 'Value1'}}

rawDescription: What is an efficient way to exchange the order of keys in nested dictionaries in Python?


code: py-use-current-dir-when-execute-p

rawDescription: How to set the directory of IPython shell in Emacs the same as the python file?

description: Set the directory of IPython shell in Emacs the same as the python file


rawDescription: document with maximum appearance in a collection mongodb

description: Document with maximum appearance in a collection mongodb


code:
class JobList(VirtualList):
  def __init__(self, parent, colref = 'job_columns'):
    VirtualList.__init__(self, parent, colref)

  def _bind(self):
    VirtualList._bind(self)
    self.Bind(wx.EVT_LIST_BEGIN_DRAG, self._startDrag)

  def _startDrag(self, evt):
    # Create a data object to pass around.
    data = wx.CustomDataObject('JobIdList')
    data.SetData(str([self.data[idx]['Id'] for idx in self.selected]))

    # Create the dropSource and begin the drag-and-drop.
    dropSource = wx.DropSource(self)
    dropSource.SetData(data)
    dropSource.DoDragDrop(flags = wx.Drag_DefaultMove)

rawDescription: Python Simple GUI Windows Drag&Drop

description: Python Simple GUI Windows Drag&Drop


code: raw_input('Press enter to continue: ')

rawDescription: How to wait for ENTER key press in Python (2.7 + )?

description: Wait for ENTER key press in Python (2.7 + )


code:
dict_st={}
for line in f:
    for item in line.split():
        k, v = map(int, item.split('-'))
        dict_st.setdefault(k, []).append(v)

rawDescription: Creating dictionaries in a faster way - Python


code:
from random import sample

... # Initialize graph

# Get 2 random edges
random_edges = sample(g.edges(), 2)

rawDescription: Getting the nodes at the end of an edge g.edge_iter


code:
A = np.ones((2,2))
B = 2*A
C = np.kron(np.eye(4), A)
C += np.kron(np.eye(4, k=1), B)
C += np.kron(np.eye(4, k=-1), B)

rawDescription: Matrix with identical diagonals

description: Matrix with identical diagonals


code:
adict = {1: {'process':False, 'length':10}, 2: {'process':True, 'length':34}, 3:{'process': False, 'length': -3}}

def somefiltering(filterDict, *criteria):
    return [key for key in filterDict if all(criterion(filterDict[key]) for criterion in criteria)]

rawDescription: Filter items in a dict of dict

description: Filter items in a dict of dict


rawDescription: Save tuple of numpy arrays to disk?

description: Save tuple of numpy arrays to disk


code: pd.DataFrame({'Keys': MyDict.keys(), 'Values': MyDict.values()})

rawDescription: Python Dictionary to Pandas Dataframe

description: Python Dictionary to Pandas Dataframe


code:
import datetime

delta_h = datetime.timedelta(hours=1)
start = datetime.datetime(2001, 1, 1)
x1 = [start + x * delta_h for x in range(129392)]
x2 = [start + x * delta_h for x in range(0, 129392, 24)]

rawDescription: Add years to x-axis in Matplotlib

description: Add years to x-axis in Matplotlib


code:
import numpy as np

def get_contour_verts(cn):
    contours = []
    # for each contour line
    for cc in cn.collections:
        paths = []
        # for each separate section of the contour line
        for pp in cc.get_paths():
            xy = []
            # for each segment of that section
            for vv in pp.iter_segments():
                xy.append(vv[0])
            paths.append(np.vstack(xy))
        contours.append(paths)

    return contours

rawDescription: Python: find contour lines from matplotlib.pyplot.contour()


rawDescription: Different return when using base64.encodestring with database and session variable


code:
revenue[prices] = ''
revenue

rawDescription: KeyError when assigning values

description: KeyError when assigning values


code:
import fractions
safe_callables = {'Fraction': fractions.Fraction}
literal_eval_with_callables('Fraction(1, denominator=2)', safe_callables)

rawDescription: Is my eval implementation completely safe?


code:
def find(lst, a, b):
    result = []
    for i, x in enumerate(lst):
        if x<a or x>b:
            result.append(i)
    return result

rawDescription: Finding the indices of matching elements in list in Python


code:
import django
from django.template import Template, Context
t = Template("{% if x and x.strip %}OK{% else %}Empty{% endif %}")
t.render(Context({"x": "ola"}))
t.render(Context({"x": "   "}))
t.render(Context({"x": ""}))
t.render(Context({"x": None}))

rawDescription: Python Django Templates and testing if a variable is null or empty string


code: import artman_pkg

rawDescription: How do unit tests import the modules they test?


rawDescription: Is there a Python equivalent to Erlang's pattern matching?


code:
tmp.recursive_bubble_ands_up(('pred', ('and', 'a', 'b'), 'x'))
tmp.recursive_bubble_ands_up(( ('and', 'a', 'b'), 'x'))
tmp.recursive_bubble_ands_up(('not', ('p', ('and', 'a', 'b'), 'x') ))

rawDescription: replacing values in a nested tuple with the whole tuple

description: Replacing values in a nested tuple with the whole tuple


code:
function = fundict['hello']
function()

# or less readable:
fundict['hello']()

rawDescription: Syntax for a dictionary of functions?

description: Syntax for a dictionary of functions


rawDescription: Python: Bivariate Spline not on grid data


code:
def tee(iterable, n=2):
    it = iter(iterable)
    deques = [collections.deque() for i in range(n)]
    def gen(mydeque):
        while True:
            if not mydeque:             # when the local deque is empty
                newval = next(it)       # fetch a new value and
                for d in deques:        # load it to all the deques
                    d.append(newval)
            yield mydeque.popleft()
    return tuple(gen(d) for d in deques)

rawDescription: Python itertools tee, clones and caching


code:
seen = set()
[x for x in a if not (x in seen or seen.add(x))]

rawDescription: how to use a sentinel list in a comprehension?

description: Use a sentinel list in a comprehension


rawDescription: How should I organize my code if I want to define a class which consists of instances of another class?


code: imsave("a.tif", a.astype(np.uint8))  # Convert to 8 bit before saving

rawDescription: Why do values in my 3D numpy array change when I write it to file?


code:
osCommandString = "notepad.exe file.txt"
os.system(osCommandString)

rawDescription: Open a text file using notepad as a help file in python?


code:
subprocess.call(['/etc/openvpn/easy-rsa/build-key', '-batch'], env={
    'SSL_countryName': 'foo',
    'SSL_stateOrProvinenceName': 'bar',
    # ...and so forth for any other $ENV::* setting you want to override
}, stdin=open('/dev/null', 'r'))

rawDescription: Simulate pressing "yes" after few "Enter" within bash command


code:
hashtag_re = re.compile(r"""
       \#                # a hashmark
       [^\s]*            # not whitespace repeated""", re.VERBOSE)

rawDescription: Making links clickable in retrieved tweets


rawDescription: retrieving columns based on condition in data frame

description: Retrieving columns based on condition in data frame


code:
a
b

rawDescription: Is there a python method to set the specified elements to be some value in a list?


rawDescription: .matplotlibrc and default options

description: .matplotlibrc and default options


rawDescription: Rolling standard deviation using parts of data in dataframe with Pandas


code:
for word in string.split(' '):
    # your existing code
    print(word, end=' ')

rawDescription: How do I make part of a string lowercase in python?

description: Make part of a string lowercase in python


code:
from api.apps import gender_detector
gender_detector.get_gender('John')

rawDescription: Django application having in memory a big Panda object shared accros all requests?


rawDescription: How to use Beautiful4 to filter multi class

description: Use Beautiful4 to filter multi class


code:
recently_watched_generator = gen_random_vid(vids)
next(recently_watched_generator)
next(recently_watched_generator)
for _ in range(10):
    print(next(recently_watched_generator))

rawDescription: How to choose a random but non-recent asset from a list?

description: Choose a random but non-recent asset from a list


code:
class Tag(models.Model):
    tag = models.CharField(max_length=70, unique=True)
    class Meta:
        verbose_name = "Tag"
        verbose_name_plural = "Tags"
    def __unicode__(self):
        return self.tag

class Test(models.Model):
    testname = models.CharField(max_length=240)
    tags = models.ManyToManyField(Tag, through='TagOrder')
    category = models.ForeignKey(Category, null=True, blank=True)
    class Meta:
        verbose_name="Test"
        verbose_name_plural="Tests"

class TagOrder(models.Model): #added extra model for adding an additional field 'added'
    test = models.ForeignKey(Test)
    tag = models.ForeignKey(Tag)
    added = models.DateTimeField()

rawDescription: Django show the tags in the order in which they are added to particular test


code:
list1=['xyz','xyz2','other_randoms']
list2=['xyz']

print(set(list2).intersection(list1))
set(['xyz'])

rawDescription: Regular expressions matching words which contain the pattern but also the pattern plus something else


code:
import subprocess
import shlex

cmd="test.py 'some string' 'some string2' '' "
proc=subprocess.Popen(shlex.split(cmd))

rawDescription: How to pass empty argument to Popen (with shell=False)?

description: Pass empty argument to Popen (with shell=False)


rawDescription: Declaring an empty list

description: Declaring an empty list


code: zip(*data)

rawDescription: Restructure / rearange list

description: Restructure / rearange list


code:
import requests.api

def my_get(url, **kwargs):
    print('Hello World!')
    kwargs.setdefault('allow_redirects', True)
    return requests.api.request('get', url, **kwargs)

requests.api.get = my_get

rawDescription: How to override the .get() method in requests?

description: Override the .get() method in requests


code:
for service, data in df.groupby('SERVICENAME'):
    service_result = pd.concat([data.groupby(pd.TimeGrouper('Min')).size(), data.groupby(pd.TimeGrouper('Min'))['REQTDURATION', 'RESPTDURATION', 'HOSTDURATION'].mean()], axis=1)
    service_result.columns = ['ERRORCOUNT', 'AVGREQTURATION', 'AVGRESPTDURATION', 'AVGHOSTDURATION']
    service_result.index = service_result.index.time

rawDescription: Generating regular time series from irregular time series in pandas


code: map(str, range(number + 1))

rawDescription: Generate string of numbers python

description: Generate string of numbers python


code:
if (a < read < b) or (b < read < a):
    print("Yes")
else:
    print("No")

rawDescription: Comparing three numbers?

description: Comparing three numbers


code:
def decode(cypher, msg):
    length = len(msg)
    decoded = ""
    key_index = 0 ## starting position of a key in message
    while key_index < length:
        key = msg[key_index:key_index + 4]
        decoded += str(cypher[key])
        key_index += 4

        # Pass every non digit after
        while key_index < length and not msg[key_index].isdigit():
             decoded += msg[key_index]
             key_index += 1

    return decoded

rawDescription: How to temporarily ignore punctuation? python

description: Temporarily ignore punctuation? python


code:
# Get Cursor
@contextmanager
def get_cursor():
    con = db.getconn()
    try:
        yield con
    finally:
        db.putconn(con)

with get_cursor() as cursor:
    con.cursor.execute("INSERT INTO table (fields) VALUES (values) RETURNING id")
    con.commit()
    id = cursor.fetchone()

rawDescription: How to use "INSERT" in psycopg2 connection pooling?

description: Use "INSERT" in psycopg2 connection pooling


code:
if first.lower() <= second.lower() <= third.lower():
    print(True)

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


code:
dog
cat
rabbit

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


rawDescription: Django using list of primary keys to fetch records


rawDescription: How to do bit manipulation of 64 bit data and output to a C function in a dll

description: Do bit manipulation of 64 bit data and output to a C function in a dll


code:
import imp
imp.find_module('sqlalchemy')
imp.find_module('pip')
imp.find_module('threading')

rawDescription: Find path of module without importing in Python


code: max(mydict, key=lambda k: mydict[k].get('c', float('-inf')))

rawDescription: Grabbing key of dictionary in dictionary with highest value


code:
def glhelperUnbindTexture(target, name):
    max_units = max(glGetInteger(GL_MAX_TEXTURE_UNITS),
                    glGetInteger(GL_MAX_TEXTURE_IMAGE_UNITS),
                    glGetInteger(GL_MAX_TEXTURE_COORDS))
    current_unit = glGetInteger(GL_ACTIVE_TEXTURE)

    for i in range(max_units):
        glActiveTexture(GL_TEXTURE0 + i)
        binding = glGetInteger( {GL_TEXTURE_1D: GL_TEXTURE_BINDING_1D,
                                 GL_TEXTURE_2D: GL_TEXTURE_BINDING_2D,
                                 GL_TEXTURE_3D: GL_TEXTURE_BINDING_3D,
                                 GL_TEXTURE_CUBE_MAP: GL_TEXTURE_BINDING_CUBE_MAP}[target])
        if binding == name:
             glBindTexture(target, 0) # this unbinds the texture from the texturing unit

    glActiveTexture(current_unit)

rawDescription: OpenGL Framebuffer with more than one texture


code:
import numpy as np
import pandas as pd

with open('data', 'r') as f:
    header = [item.strip() for item in next(f).split(',')]
    lines = (line.split(',', 3) for line in f)
    df = pd.DataFrame(lines, columns=header)
    df = df.convert_objects(convert_numeric=True)
    df['TIME'] = pd.to_datetime(df['TIME'])

print(df)

rawDescription: Import data into DataFrame with additional commas


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

description: Get datetime from date object python


code:
def refresh(variable1, variable2, variable3):
    variable4 = variable1 + variable2 + variable3
    variable5 = variable3 - variable2 / variable1
    return variable4, variable5

rawDescription: Refreshing a list of variables with one command


code:
class uf_node:
    def __init__(self, Vertex):
        self.vertex = Vertex
        self.rep = Vertex

    def set_rep(self, Rep):
        self.rep = Rep

    def __str__(self):
        return "Rep: {}, Vertex: {}".format(self.rep, self.vertex)

    def __repr__(self):
        return "Rep: {}, Vertex: {}".format(self.rep, self.vertex)

rawDescription: python class output at the interpreter

description: Python class output at the interpreter


code:
if form.validate_on_submit():
    meal = form.meal.data
    tip_calculator(meal)

rawDescription: How do I make this function redirect to a given html page?

description: Make this function redirect to a given html page


code:
def addOne(x):
    return x+1

def useFunction(addOne, x):
    return addOne(x)**2

rawDescription: how can i call function inside another function.?

description: Call function inside another function.


code:
import numpy as np
mx = np.loadtxt(filename, delimiter=',', dtype=int).tolist()

rawDescription: How should you read a 2D integer array?

description: How should you read a 2D integer array


code: (key, value), = d.items()

rawDescription: How to fetch the key/value pair of a dictionary only containing one item?

description: Fetch the key/value pair of a dictionary only containing one item


code:
data1 = open("a.txt", 'r').readline().strip().split(',')
data2 = open("b.txt", 'r').readline().strip().split(',')
res = list((set(data1) - set(data2)).union(set(data2) - set(data1)))

rawDescription: how can we compare two lists which are in two different files?

description: How can we compare two lists which are in two different files


code:
for i, j, k in zip(list1, list2, [-1] + list2):
    if i > k:
        print(i, j)

rawDescription: Iterate over two lists while i-1 condition is met in python


rawDescription: How to build a dictionary from a list mapping

description: Build a dictionary from a list mapping


code: fig, ax = plt.subplots()

rawDescription: Creating two completely independent plots in matplotlib and going back and forth between them


rawDescription: convert nan value to zero

description: Convert nan value to zero


rawDescription: python conversion int into arbitrary number of bytes

description: Python conversion int into arbitrary number of bytes


code:
[
[['2007-12-18'], ['AAAA'], ['abc', 'def', 'ghi', 'jkl'],
['Objetos de Aprendizagem', 'Personaliza\\xe7\\xe3o', 'Perfil do Usu\\xe1rio',
'Padr\\xf5es de Metadados', 'Vers\\xf5es de Objetos de Aprendizagem',
'Agrupamento de Objetos Similares']],
[['2007-12-18'], ['LOCPN: CADEIA DE PRODU\\xc7\\xc3O'], ['Maria de F\\xe1tima',
'ZZZ','Albert Einstein', 'James Clerk Maxwell', 'Jos\\xe9 da Silva', 'DDD',
'R M. C. A'],
['Objetos de Aprendizagem', 'Modelo de Processo', 'Redes de Petri Colorida',
'Especifica\\xe7\\xe3o formal']],
[['2007-12-18'], ['COMPUTA\\xc7\\xc3O M\\xd3VEL E UB\\xcdQUA  GRADUA\\xc7\\xc3O DE REFER\\xcaNCIA'],
['JB Cardoso', 'Franz Ferdinand', 'Nick Nolte', 'S\\xe9rgio Madruga',
'D\\xe9bora JKLJ'],
['Computa\\xe7\\xe3o M\\xf3vel e Ub\\xedqua',
'Gradua\\xe7\\xe3o de Refer\\xeancia', ' Educa\\xe7\\xe3o Ub\\xedqua']]
]

rawDescription: How to split a list with only one item which is a complex string?

description: Split a list with only one item which is a complex string


code:
re.sub(pat, repl, 'foo\x20\x20\x08bar')
re.sub(pat, repl, 'foo\x20\x20\x08\x08bar')
re.sub(pat, repl, 'foo\x20\x20\x08\x08\x08bar')

rawDescription: How to 'evaluate' backspaces in python?

description: 'evaluate' backspaces in python


code:
import re

text = 'gfgfdAAA1234ZZZuijjk'

m = re.search('AAA(.+?)ZZZ', text)
if m:
    found = m.group(1)

# found: 1234

rawDescription: how to extract a substring from inside a string in Python?

description: Extract a substring from inside a string in Python


code:
def enableFloatField(float_field, *args):
    #enable the float field
    cmds.floatField(float_field, edit=True, enable=True)

def disableFloatField(float_field, *args):
    #disable the float field
    cmds.floatField(float_field, edit=True, enable=False)

rawDescription: enable or disable a field in maya ui with python

description: Enable or disable a field in maya ui with python


code:
import urlparse

qs = urlparse.urlsplit(inputurl).query
url = urlparse.parse_qs(qs).get('url', [None])[0]

rawDescription: Python Regular Expression to Remove Unwanted Parts of URL


rawDescription: Formulating an efficient DB query with highly challenging requirements (Django app)


code:
from flask import Flask, render_template
from flask.ext.socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

@socketio.on('my event', namespace='/test')
def test_message(message):
    emit('my response', {'data': message['data']})

@socketio.on('my broadcast event', namespace='/test')
def test_message(message):
    emit('my response', {'data': message['data']}, broadcast=True)

@socketio.on('connect', namespace='/test')
def test_connect():
    emit('my response', {'data': 'Connected'})

@socketio.on('disconnect', namespace='/test')
def test_disconnect():
    print('Client disconnected')

if __name__ == '__main__':
    socketio.run(app)

rawDescription: Query SQL data in Flask to use for charting without using the app.route decorator


code:
def func(arg1, arg2):
    return True

rawDescription: How can I produce a numpy-like documentation?

description: Produce a numpy-like documentation


rawDescription: Class and Array Problems

description: Class and Array Problems


code:
exec(compile("def f(a):\n  print(a)", "exec", "exec"))
f(2)

rawDescription: Can JSON for Python Encode/decode functions from text files?


code:
def constraint_maker(delta):
    def _(x):
        return -1*bounds(x) + delta
    return _

cons = ({'type' : 'ineq', 'fun': constraint_maker(0.1)},
        {'type' : 'ineq', 'fun': constraint_maker(0.2)},
        {'type' : 'ineq', 'fun': constraint_maker(0.3)})

rawDescription: Dynamic dictionary including keywords/ lambda function


rawDescription: Commodity Futures Hierarchical Data Structure


code:
d['baz'] = 'store me'
args.baz

rawDescription: what is the right way to treat Python argparse.Namespace() as a dictionary?

description: What is the right way to treat Python argparse.Namespace() as a dictionary


rawDescription: How can a Python list be sliced such that a column is moved to being a separate element column?


rawDescription: Abbreviating IPv6 addresses

description: Abbreviating IPv6 addresses


code:
from operater import itemgetter
from itertools import tee, izip

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

def neighbouring_minimum(iterable):
    paired = pairwise(iterable)

    # find minimum pair by second elements summed
    minpair = min(paired, key=lambda pair: pair[0][1] + pair[1][1])
    return min(minpair, key=itemgetter(1))

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code: new_data = numpy.array([0,0], dtype=stereo_data)

rawDescription: constructing a wav file and writing it to disk using scipy

description: Constructing a wav file and writing it to disk using scipy


rawDescription: Pandas Rolling_std with Window using all previous row counts


code:
set2 = set(Arr2)
[item for item in Arr1 if item not in set2]

rawDescription: Pythonic way to write for x in Y and not in Z


code: Tristan and Isolde

rawDescription: navigating text file searches in python

description: Navigating text file searches in python


code: '-'.join('The   Quick  \nBrown\t Fox'.split())

rawDescription: Inserting another character in place of spaces in Python


code:
def process_dict(d):
   for k, v in d.items():
       getattr(MyFuncs, k, lambda *x: None)(*v)

rawDescription: Can one define functions like in JavaScript?


code: sections = re.findall(r'{.*?}', testString)

rawDescription: Python regular expression to print out sections of a string


code:
c = Counter(x)
c

rawDescription: Ordering a nested dictionary by the frequency of the nested value


rawDescription: Compress a very large number (in Python)


code: 'The Matrix is not in the movie archives. Try another?'

rawDescription: Python List in List ("Stuck")

description: Python List in List ("Stuck")


code:
MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    # ... your existing middlewares ...

    # your custom middleware here
    'test_project.middlewares.StatsMiddleware',
)

rawDescription: Django: display time it took to load a page on every page


rawDescription: Plotting pandas groupby

description: Plotting pandas groupby


code:
import gitter  # file containing our clone function
import mock
import unittest

class test_gitter(unittest.TestCase):

    @mock.patch('gitter.Repo')
    @mock.patch('gitter.Git')
    def runTest(self, mock_git, mock_repo):

        # Set the "bare" attribute of the Repo instance to be False
        p = mock.PropertyMock(return_value=False)
        type(mock_repo.clone_from.return_value).bare = p

        gitter.clone_and_checkout(
            '/tmp/docker',
            'git@github.com:docker/docker.git',
            'master'
        )
        mock_git.checkout.called_once_with('master')

rawDescription: How to write unit tests for GitPython clone/pull functions?

description: Write unit tests for GitPython clone/pull functions


code:
import numpy as np

arr = np.arange(2*3*4).reshape(2,3,4).astype(float)
mask = arr % 5 == 0

marr = np.ma.array(arr, mask=mask)
print(np.ma.filled(marr, np.nan))

rawDescription: Save.npy masked array to a .npy array with NaNs where mask == True


rawDescription: Python GPIO wait for either of two buttons to be pressed


rawDescription: Why does pandas series.map method work for column concatenation?


code:
SHARD = os.environ["SHARD"]

# Apps common to all shards go here.
LOCAL_APPS = [
    commonApp,
]

# Add apps specific to each shard.
if SHARD == "Ebony":
    LOCAL_APPS += [
        Ebony,
    ]
elif SHARD == "Ivory":
    LOCAL_APPS += [
        Ivory,
    ]

# Add them to the apps that aren't mine.
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.admin',
    # ... omitted for brevity ...
    'django_extensions',
    'south',
    'debug_toolbar',
) + LOCAL_APPS

rawDescription: Django serving each app separately in each its port


code:
def DisplayIt(request):
    somestring = ""
    for a in A.objects.filter(b__name__isnull=False):
        somestring += a.b.name
    for a in A.objects.filter(b__name__isnull=True):
        somestring += "dummy value for missing b.name"

rawDescription: Django 1.4: Get a field in a foreign key object (null=True), get None or field value


code:
previous = 0
for number in range(10):
    temp = previous + number
    previous = temp

rawDescription: How to store last value of iteration?

description: Store last value of iteration


code:
pattern = re.compile("[^\xFF]\xFF*$")
offset = pattern.search(data, endpos=offset).start() + 1

rawDescription: Find previous byte that isn't equal to unwanted byte in Python


code:
import os
import shutil
import tempfile
from contextlib import contextmanager

@contextmanager
def named_pipes(n=1):
    dirname = tempfile.mkdtemp()
    try:
        paths = [os.path.join(dirname, 'named_pipe' + str(i)) for i in range(n)]
        for path in paths:
            os.mkfifo(path)
        yield paths
    finally:
        shutil.rmtree(dirname)

rawDescription: Multiple pipes in subprocess

description: Multiple pipes in subprocess


code:
# let scipy do its magic (k==3 groups)
res, idx = kmeans2(numpy.array(zip(xy[:,0],xy[:,1],z)),3)

rawDescription: Using scipy's kmeans2 function in python


code: tuple([0 for j in range(n)])

rawDescription: How to create a tuple of tuples and pass it to the superclass's constructor

description: Create a tuple of tuples and pass it to the superclass's constructor


code:
# Air (time, latitude, longitude)
airSubset = f.variables['air'][ : , latli:latui , lonli:lonui ]

rawDescription: netcdf4 extract for subset of lat lon

description: Netcdf4 extract for subset of lat lon


rawDescription: How to read in a file with a mixture of different delimiters using Python csv module?

description: Read in a file with a mixture of different delimiters using Python csv module


code:
def sorted_group_by_start(inputlist, n):
    key = itemgetter(slice(n))
    return [res[0] if len(res) == 1 else res for k, g in groupby(sorted(inputlist, key=key), key=key) for res in (list(g),)]

rawDescription: Python. How to make list from another list by mark?


code:
def funct():
    "This function is self-documenting"
    pass

rawDescription: How do I show my argspec/docstring in bpython?

description: Show my argspec/docstring in bpython


code: import html.parser

rawDescription: HTML parser in Python

description: HTML parser in Python


code:
def sections(sequence, key):
    it = iter(sequence)
    a = placeholder = object()
    group = []
    while True:
        try:
            a, last = next(it), a
        except StopIteration:
            if group:
                yield group
            return
        if last is not placeholder and key(a, last):
            if group:
                yield group
            group = [a]
        else:
            group.append(a)

rawDescription: How to organize data that alternates between negative and positive values in Python

description: Organize data that alternates between negative and positive values in Python


code:
stream_index = []
for sample_num in range(lcm):
    stream_index += [i for i, ch in enumerate(all_channels)
                     if ch.samples_for(sample_num)]
repeat_count = [b[i] for i in stream_index]
stream_index = numpy.array(stream_index).repeat(repeat_count)

rawDescription: Fast way to read interleaved data?

description: Fast way to read interleaved data


code: pool.apply(select, info)

rawDescription: Python, how to implement parallel process


code:
answer = ('Ten for that? You must be mad!' if does_not_haggle(brian)
          else "It's worth ten if it's worth a shekel.")

rawDescription: How to make a line break on the Python ternary operator?

description: Make a line break on the Python ternary operator


code:
def move_valid(position, last_position):
    if last_position is None:
        return True
    return (
        abs(position[0] - last_position[0]) <= 1 and
        abs(position[1] - last_position[1]) <= 1
    )

def find_word(word, used=None):
    if word == "":
        return []
    if used is None:
        used = []
    letter, rest = word[:1], word[1:]
    for position in letter_positions.get(letter) or []:
        if position in used:
            continue
        if not move_valid(position, used and used[-1]):
            continue
        path = find_word(rest, used + [position])
        if path is not None:
            return [position] + path
    return None

rawDescription: Python: Find a word in a matrix of characters


code: input(print("Would you like to find the factorial of another non-negative integer? Y/N: "))

rawDescription: Recursive Function inside While loop (Python)


code:
underscores = ('_', '__')
if myString.endswith(underscores): pass

rawDescription: Python: How to check characters occurrence in string in one line


code:
table = soup.find(class_='apple-font', id=True).find_parent('table')
groups = {}
group = None
for tr in table.find_all('tr'):
    id_span = tr.find(class_='apple-font', id=True)
    if id_span is not None:
        # new group
        group = []
        groups[id_span['id']] = group
    else:
        vid_link = tr.find('a', vid=True)
        if vid_link is not None:
            group.append(vid_link['vid'])

rawDescription: Using BeautifulSoup with Python to parse page for attribute values


code: occurrence_map[(x,y)] = ...

rawDescription: Python Co-occurrence matrix of words and phrases


code:
table = soup.find(text="[Dgr Rgn] Station").find_parent("table")
for row in table.find_all("tr")[1:]:
    cells = row.find_all("td")
    print(cells[0].get_text(), cells[1].get_text())

rawDescription: Python web scrape failing

description: Python web scrape failing


rawDescription: PyQt4 Gui that prints loop

description: PyQt4 Gui that prints loop


code:
order_type = 'a'
class Population (object):
    def __init__(self,a):
        self.a = a

    def method1 (self):
        self.a = self.a*2
        return self

    def method2 (self):
        self.a += 2
        return self

    def method3 (self):
        self.a = 0
        return self

if order_type=='a':
    order = [Population.method1, Population.method2, Population.method3]
elif order_type=='b':
    order = [Population.method2, Population.method1, Population.method3]
else :
    order = [Population.method3, Population.method2, Population.method1]

my_pop = Population(3)

while iteration < 100:
    iteration +=1
    for method_to_use in order:
        method_to_use(my_pop)

rawDescription: Using a dictionary to control the flow of methods


rawDescription: KeyError with integer tuples as keys

description: KeyError with integer tuples as keys


code:
from requests.compat import chardet

r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
peek = r.iter_content(256).next()
mime = magic.from_buffer(peek, mime=True)

if mime == "text/html":
    contents = peek + b''.join(r.iter_content(10 * 1024))
    encoding = r.encoding
    if encoding is None:
        # detect encoding
        encoding = chardet.detect(contents)['encoding']
    try:
        textcontent = str(contents, encoding, errors='replace')
    except (LookupError, TypeError):
        textcontent = str(contents, errors='replace')
    print(textcontent)

rawDescription: python-requests: fetching the head of the response content without consuming it all

description: Python-requests: fetching the head of the response content without consuming it all


code:
df['inc_index'] = df.mn_earn_wne_p6.apply(
    lambda v: 1 if v < 20000 else 2 if v < 30000 else 3 if v < 40000 else 4)

rawDescription: Python/Pandas - Best way to group by criteria?


code: etree.SubElement(item, 'Date').text = '2014-01-01'

rawDescription: Insert xml node in specific location

description: Insert xml node in specific location


code:
points_zipped = zip(*points)
xvals = points_zipped[0]
yvals = points_zipped[1]

rawDescription: Using Python with a set of not regular point X,Y,Z in order to create a regular grid where each pixel is the minimum value of the point


code:
def main():
    # When you assign variables here, make sure you are putting the int outside
    # You also don't need to reference the variable twice
    a = int(input("enter a number: "))
    b = int(input("enter a number: "))

    # Here is where your call goes (try to avoid using variable names that
    # are the same as Python keywords, such as sum)
    s = my_sum(a, b)

    print(" result: ", s)

rawDescription: Keep getting syntax error. What do I need to do?


code:
d = {k: [] for k in l}
d = {k: 1 for k in l}

rawDescription: How to make a dictionary from list

description: Make a dictionary from list


code: soup.select("a[id^=link]")  # id starts with 'link'

rawDescription: Using BeautifulSoup to parse by id

description: Using BeautifulSoup to parse by id


rawDescription: Why doesn't python overwite non-zero arrays?


code:
{
    u'1x1': {'Central Spectrum': 10, 'Full Frame': 9},
    u'4x4': {'Central Spectrum': 10, 'Full Frame': 10},
    u'4x2': {'Central Spectrum': 10, 'Full Frame': 10}
}

rawDescription: summing nested dictionary entries

description: Summing nested dictionary entries


rawDescription: Calculating the distance and print it out


code: Foo.objects.extra(select={ 'd_field' : 'cast(the_column AS UNSIGNED)' }).extra(order_by=['d_field'])

rawDescription: Fetch data order by whole numbers instead of order by each digit of a number


code: slist = [st for row in s for st in row]

rawDescription: Pandas Series of lists to one series

description: Pandas Series of lists to one series


code: [y.strip() for y in x.xpath('//i[.="blabla"]/..//text()') if y.strip()]

rawDescription: How to prevent infinite looping in Python while parsing with lxml?

description: Prevent infinite looping in Python while parsing with lxml


rawDescription: Handle Multiple Checkboxes with a Single Serverside Variable


rawDescription: python - search for a string and return the whole string which has the matched string or required data

description: Python - search for a string and return the whole string which has the matched string or required data


code:
import itertools
for x,y in itertools.product(a,b):
    print(x + " " + y)

rawDescription: is there a way to get the index for multiple lists python?

description: Is there a way to get the index for multiple lists python


code:
from bs4 import BeautifulSoup
import requests

r = requests.get("http://www.transfermarkt.co.uk/championship/marktwerte/wettbewerb/GB2", headers={
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36"
})
soup = BeautifulSoup(r.content,"html.parser")
print(soup.title.get_text())

rawDescription: Python requests not responding

description: Python requests not responding


code:
df = read_csv(StringIO(data),sep='\s+',skiprows=1,parse_dates=[[3,4],[5,6]],header=None)
df.columns = ['created','closed','idx','num','typ']
df
df.dtypes

rawDescription: pandas DataFrame - Getting hours in a Duration

description: Pandas DataFrame - Getting hours in a Duration


code:
def step(state):
    return ''.join(['MNNN' if s == 'M' else 'M' for s in state])

rawDescription: Simulating Fibonacci's Rabbits with multiple offsprings using python


code:
with faker(os.getenv, dict(HOME='here').__getitem__):
   ...

rawDescription: Pythonic way to intercept calls to a function?


code:
import numpy as np
import pandas as pd
np.random.seed(2015)
df = pd.DataFrame(np.random.randint(10, size=(10, 2)),
                  columns=['account', 'salary'])
df['percent salary'] = df.groupby(['account'])['salary'].transform(lambda x: x/x.sum())

print(df)

rawDescription: apply sum calculated using pandas group by to all elements of group

description: Apply sum calculated using pandas group by to all elements of group


rawDescription: python how to pad numpy array with zeros

description: Python how to pad numpy array with zeros


code:
import logging
from controllers import server
from config import config
import webapp2

app = webapp2.WSGIApplication([
        # Essential handlers
        ('/', server.RootPage),
        ('/vote/', server.VoteHandler)
    ],debug=True, config=config.config)

# Extra Hanlder like 404 500 etc
def handle_404(request, response, exception):
    logging.exception(exception)
    response.write('Oops! Naughty Mr. Jiggles (This is a 404)')
    response.set_status(404)

app.error_handlers[404] = handle_404

rawDescription: How to use AJAX with Google App Engine (Python)

description: Use AJAX with Google App Engine (Python)


code:
arr._mmap
type(arr._mmap)

rawDescription: Correct way to do operations on Memmapped arrays


code:
# project/celery_app.py
from __future__ import absolute_import

import os

from celery import Celery

from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('project_name')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
# YOUR APPLICATION MUST BE LISTED IN settings.INSTALLED_APPS for this to work
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

rawDescription: Received unregistered task of type xx. The message has been ignored and discarded


code:
import socket
#import arcpy

def actual_work():
    #val = arcpy.GetCellValue_management("D:\dem-merged\lidar_wsg84", "-95.090174910630012 29.973962146120652", "")
    #return str(val)
    return 'dummy_reply'

def main():
    sock = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
    try:
        sock.bind( ('127.0.0.1', 6666) )

        while True:
            data, addr = sock.recvfrom( 4096 )
            reply = actual_work()
            sock.sendto(reply, addr)
    except KeyboardInterrupt:
        pass
    finally:
        sock.close()

if __name__ == '__main__':
    main()

rawDescription: Run python script without importing class everytime


code:
def f(counter):
  counter.day_count(a, b)
  # ...
  counter.year_fraction(x, y)

rawDescription: Static method-only class and subclasses in Python - is there a better design pattern?


code:
from django import template

register = template.Library()

@register.filter
def print_file_content(f):
    try:
        return f.read()
    except IOError:
        return ''

rawDescription: How to insert the content of text file in django template?

description: Insert the content of text file in django template


rawDescription: Cantor ternary set in Python or C

description: Cantor ternary set in Python or C


code:
import csv
import itertools as IT

filenames = ['1.csv', '2.csv']
handles = [open(filename, 'rb') for filename in filenames]
readers = [csv.reader(f, delimiter=',') for f in handles]

with  open('combined.csv', 'wb') as h:
    writer = csv.writer(h, delimiter=',', lineterminator='\n', )
    for rows in IT.izip_longest(*readers, fillvalue=['']*2):
        combined_row = []
        for row in rows:
            row = row[:2] # select the columns you want
            if len(row) == 2:
                combined_row.extend(row)
            else:
                combined.extend(['']*2)
        writer.writerow(combined_row)

for f in handles:
    f.close()

rawDescription: Combine columns from several CSV files into a single file


code:
df2 = df.iloc[1:] + df.iloc[0]
df.prod()
df2/df.prod()

rawDescription: How do I add one row of a PANDAS dataframe to the rest of the rows?

description: Add one row of a PANDAS dataframe to the rest of the rows


rawDescription: Python json parser allow duplicate keys

description: Python json parser allow duplicate keys


code:
import netCDF4

dset = netCDF4.Dataset('test.nc')

dset['var'][:][dset['var'][:] < 0] = -1

dset.close() # if you want to write the variable back to disk

rawDescription: Python : Replacing Values in netcdf file using netCDF4


code:
previous = abcstring[0]

for c in abcstring[1:]:
    if values(c) < values(previous):
        do_something()
    previous = c

rawDescription: How does one talk about comparing positions of characters in a string?

description: Talk about comparing positions of characters in a string


rawDescription: Python http.client json request and response. How?


code:
import re
from suds.plugin import DocumentPlugin

class FixUrls(DocumentPlugin):
    def loaded(self, context):
        context.document = re.sub(r'badhost\d', 'goodhost', context.document)

rawDescription: Is it possible to replace schema locations in Suds/python?


rawDescription: Efficiency of Python "in" keyword for sorted list


code:
def removeTuplesWithOne(lst):
    return [x for x in lst if x[0] != 1]

a = removeTuplesWithOne([(1,2),(1,4),(2,6),(1,8),(3,6),(1,10),(1,6)])

rawDescription: Removing specific tuples from List

description: Removing specific tuples from List


code:
len_short = min([len(x) for x in names])
len_long = max([len(x) for x in names])

rawDescription: Create new lists of the shortest and longest words in an existing list - Python


code:
from kivy.uix.carousel import Carousel
from kivy.uix.boxlayout import BoxLayout
from kivy.app import App
from kivy.lang import Builder

Builder.load_string('''
<Page>:
    label_id: label_id
    Label:
        id: label_id
        text: str(id(root))

<Carousel>
    on_current_slide: print(args[1].label_id.text)
''')

class Page(BoxLayout):
    pass

class TestApp(App):
    def build(self):
        root = Carousel()
        for x in range(10):
            root.add_widget(Page())
        return root

if __name__ == '__main__':
    TestApp().run()

rawDescription: Kivy Event on carousel when slide change


code:
re.sub("'", "\\'","Newton's method")
re.sub("'", r"\'","Newton's method")

rawDescription: Replace single quote with backslash single quote in python


code: Example.objects.extra(select={'value': 'column1 + column2 + column3'})

rawDescription: Django annotation based on multiple columns


code:
import imp

global_var = 7
y = imp.load_source('y', 'y.py') # <---
global_var = y.global_var        # <---
print(global_var)

rawDescription: Allow a module loaded with imp to access local variables in python


code: x = t.treepositions("leaves").index( np.treeposition()+np.leaf_treeposition(0) )

rawDescription: How many leaves are there before a subtree?


code: a

rawDescription: Numpy: Why doesn't 'a += a.T' work?

description: Numpy: Why doesn't 'a += a.T' work


code:
if Product.objects.all().count() == Product.objects.filter(price=price).count():
    pass

rawDescription: how to check whether all the values of a database field are same using django queries

description: Check whether all the values of a database field are same using django queries


code:
import urllib.parse
s = 'http://domain.com/xxxxx/xxxxxxxx?tags=%7C105651%7C102496&Asidebar=1&dnr=y'
urllib.parse.parse_qs(urllib.parse.urlparse(s).query)['tags'][0]

rawDescription: get substring from the main string Python

description: Get substring from the main string Python


code: mydict = {'var%i' %idx : item for idx, item in enumerate(reader)}

rawDescription: Python csvreader separate lines

description: Python csvreader separate lines


code: t

rawDescription: How to add dictionaries to tuple

description: Add dictionaries to tuple


code:
import win32com.client
autoit = win32com.client.Dispatch("AutoItX3.Control")

#Run(program, workingdir, show_flag)
autoit.Run("notepad.exe",'',5)

rawDescription: Not able to open notepad using autoit with python


code:
for p in Post.objects.all():
    Vote.objects.get_or_create(post_id=p.id, value=0)

rawDescription: Order by dig-like rating in django

description: Order by dig-like rating in django


rawDescription: Immutable dictionary in Python 3: how to make keys(), items(), and values() dictionary views immutable


rawDescription: Create new numpy array-scalar of flexible dtype


rawDescription: How to animate scale and rotate in pygame using rotozoom

description: Animate scale and rotate in pygame using rotozoom


code:
result = df2.stack()
result
result.index.names = ['POI_id', 'matched_POI_ids']
result[result].reset_index()

rawDescription: Geo Pandas Data Frame / Matrix - filter/drop NaN / False values


code:
test_f()
test_f.count
test_f()
test_f.count

rawDescription: Change an attribute of a function inside its own body?


code:
with open('data{}.txt'.format(self.timestamp), 'a') as f:
    f.write(data + '\n')

rawDescription: Python: Dump to Json adds additional double quotes and escaping of quotes


rawDescription: python - Overhead on looping over an iterable class

description: Python - Overhead on looping over an iterable class


code:
with open('/tmp/f1.txt','r') as f1, open('/tmp/f2.txt','r') as f2:
    diff = difflib.ndiff(f1.readlines(),f2.readlines())
    for i,line in enumerate(diff):
        if line.startswith(' '):
            continue
        sys.stdout.write('My count: {}, text: {}'.format(i,line))

rawDescription: Returning lines that differ between two files (Python)


type: date

type: number

type: string

role: style

v: color: green

rawDescription: How to use Custom Properties with Python Google Charts aviz_api.py

description: Use Custom Properties with Python Google Charts aviz_api.py


rawDescription: Python - Parse a String into Float Array?


code:
with open("oldfile", "rb") as old, open("newfile", "wb") as new:
    new.write(string)
    new.write(old.read())

rawDescription: How to prepend data to the binary file?

description: Prepend data to the binary file


code:
it = itertools.count(1)
next(it)
next(it)
next(it)

rawDescription: regex sub with pattern reference

description: Regex sub with pattern reference


street: Wall Street

city: New York

type: home

rawDescription: Json organization

description: Json organization


code:
for i in range(len(content2)):
    if not content2[i]:
        content2[i] = None

rawDescription: python changing integers/ floats to None in list

description: Python changing integers/ floats to None in list


code:
from matplotlib import pyplot as plt
plt.hist(A, bins=nbins, weights=B);

rawDescription: Which elements of list go into which histogram bins?


rawDescription: Testing all Letters?

description: Testing all Letters


rawDescription: Parsing message parameters received by a GSM modem in python


code:
class SnapShotAnimation(ArtistAnimation):
    def __init__(self, fig, artists, snapshot_delay, *args, **kwargs):
        self._snapshot_delay = snapshot_delay
        self._time_to_snapshot = snapshot_delay
        ArtistAnimation.__init__(self, fig, artists, *args, **kwargs)

    def _step(self, *args):
        if self._time_to_snapshot <= 0:
            do_snapshot()
            self._time_to_snapshot = self._snap_shot_delay #reset timer
        else:
            self._time_to_snapshot -= self._interval
        ArtistAnimation._step(*args) #ancestor method maybe better at start

    def do_snapshot(self):
        """Your actual snapshot code comes here - basically saving to a output"""
        fname = 'snapshot.png'
        self._fig.savefig(fname)

rawDescription: take snapshots every second using artist animation

description: Take snapshots every second using artist animation


code:
import collections

def remove_common(x,y):
    count = lambda x: collections.Counter(c for c in x.lower() if c.isalpha())
    cx, cy = count(x), count(y)
    diff  = cx - cy
    rev_diff = cy - cx
    assert len(rev_diff) == 0, "%s in y and not x" % "".join(rev_diff.elements())

    return "".join(sorted(diff.elements()))

rawDescription: Remove common letters in strings

description: Remove common letters in strings


code:
client = app.test_client()
def check(url):
    r = client.get(url)
    return r.status, r.headers.get('location')

check('/user/123')
check('/user/123/')
check('/user/123/foo')
check('/user/123/johndoe')
check('/user/123/johndoe/')
check('/user/125698')

rawDescription: Flask redirecting multiple routes

description: Flask redirecting multiple routes


code:
d = {"chuck" : 1 , "annie" : 42, "jan" : 100};
s = '\n'.join(['%s %s' % (key, value) for (key, value) in sorted(d.items(), key=lambda x: x[0])])
print(s) # 'annie 42\nchuck 1\njan 100'

rawDescription: Generating string from a dictionary

description: Generating string from a dictionary


code:
for element in inputList:
    elem_wt = atomic_wt[element]

rawDescription: Having user input variables to be used in a later equation


code: ','.join(str(instance.public_dns_name) for instance in instances)

rawDescription: Joining a list of object values into a string using list comprehensions in python 2.7


rawDescription: How to quickly find first multiple of 2 of list element in list of large integers?

description: Quickly find first multiple of 2 of list element in list of large integers


code:
vec = TfidfVectorizer(input='filename')
my_document_features = vec.fit_transform(my_text_files)

rawDescription: scikit-learn how to know documents in the cluster?

description: Scikit-learn how to know documents in the cluster


rawDescription: Order list of Json object by value using python


code:
from string import punctuation
' '.join(y for y in (x.strip(punctuation) for x in s.split()) if y in word)

rawDescription: Text clean up in Python

description: Text clean up in Python


code:
class AnimalFactory(type):

    animal_classes = {}

    def __new__(cls, name, bases, attrs):

        new_class = super(AnimalFactory, cls).__new__(cls, name, bases, attrs)
        AnimalFactory.animal_classes[name] = new_class
        return new_class

    @classmethod
    def build(cls, name, *args, **kwargs):

        try:
            klass = cls.animal_classes[name]
        except KeyError:
            raise ValueError('No known animal %s' % name)
        return klass(*args, **kwargs)

class Animal(object):

    __metaclass__ = AnimalFactory

    def __init__(self, age):

        self.age = age

    def speak(self):

        raise NotImplementedError()

# As long as the file it is implemented in is imported at some point,
# the following can be anywhere

class Dog(Animal):

    def speak(self):

        return 'woof'

# And then to use, again, anywhere

new_animal = AnimalFactory.build('Dog', 5)

rawDescription: Dynamically load module with Inheritance


code:
import decimal
decimal.getcontext().prec = 3
[(x, decimal.Decimal(y) / 7) for x, y in a]

rawDescription: Python - 'tuple' object does not support item assignment


code:
entropy = np.array(entropy)
entropy = savitzky_golay(entropy, 51, 3) # window size 51, polynomial order 3

rawDescription: how to smooth a curve in python

description: Smooth a curve in python


code:
with open("output.csv", "wb") as f:
    writer = csv.writer(f,delimiter=',')
    for i,j in my_dict.iteritems():
        writer.writerow([i]+j)

rawDescription: How to combine multiple lines in CSV into one line

description: Combine multiple lines in CSV into one line


code:
class Skill(models.Model):
    player = ForeignKey('Player')
    match = ForeignKey('match.Match')

class Player(models.Model):
    #yadda yadda

    def get_skill():
       skill = Skill.object.filter()

rawDescription: Model Definitions: Ordering Importo Avoid ImportError


code:
tmp = set()  # create a set of already added elements
[x for x in lst1 if x not in tmp and not tmp.add(x)]

rawDescription: Accessing the List Being Generated by List Comprehension


code:
daily = ts.groupby(lambda x: x.isocalendar()[1:]).agg(lambda s: s[-1])
daily

rawDescription: Pandas: how to plot yearly data on top of each other


code:
class CriticalResource:
    def __init__(self, resource):
        self.r = resource

    def __del__(self):
        self.r.close_nicely()  # whatever

class FancyObject:
    def __init__(self):
        # ...
        self.r = CriticalResource(get_some_resource())
        # ...

rawDescription: How many times can `__del__` be called per object in Python?


code:
def my_triu_indices(n, k=0):
    rows, cols = np.triu_indices(n, k)
    rows = cols - rows - k
    return rows, cols

rawDescription: Wrapping/unwrapping a vector along array diagonals


code:
def foo():
    pass

instance.foo = foo

rawDescription: Adding a method to a class within a class


code:
#!/usr/bin/env python
"""Square Wave approximation by Fourier Series."""
import math
from multiprocessing.dummy import Pool # use threads
from timeit import default_timer as timer

import matplotlib.pyplot as plt
import numpy as np

n = 100000 # compute first n terms in the series

# generate x's to calculate the points.
x = np.arange(0, 360, .1)

# generate odd numbers to add the sines terms
impar = np.c_[1:n+2:2]
no = 4 / math.pi # just for normalize the sequence to converge to 1 (not pi/4)

# calculate the points
start = timer()
# y = 4/pi*(sin(x) + sin(3x)/3 + sin(5x)/5 + ... n) terms
y = np.empty_like(x)

def compute_y(i):
    t = impar * x[i]
    np.radians(t, out=t)
    np.sin(t, out=t)
    t *= no
    t /= impar
    np.add.reduce(t, out=y[i])

step = 10**8 // n
Pool().map(compute_y, (slice(j, j + step) for j in range(0, len(x), step)))
print("y calc. takes us %.2f seconds" % (timer() - start,))

# plot
plt.plot(x, y, "-")
plt.title("%d terms" % n)
plt.grid()
# save a image(just in case)
plt.savefig("%dsqwv.png" % n)
# show the graph
plt.show()

rawDescription: Python multiprocessing pylab Fourier

description: Python multiprocessing pylab Fourier


code:
def is_visible(self):
    now = datetime.now()

    if self.is_visible:
        # is_visible field is checked.
        return True

    #elif self.visible_start < now and self.visible_stop == Null:
    #    return True

    elif self.visible_start < now and self.visible_stop > now:
        # Start is before now and stop is after now.
        return True

    else:
        # All other options
        return False

rawDescription: Determine if entry is visible by startdate and enddate


code:
def person(request, id):
    person = Person.objects.get(pk=id)
    return render(request, 'person/index.html', {'person': person, })

rawDescription: Displaying one Django database object on a page at a time


code:
def find_max(L):
    length = len(L)
    mid_index = length/2
    if length == 0:
        return 0
    elif length == 1:
        return max(L[0], 0)

    left = find_max(L[:mid_index])
    right = find_max(L[mid_index:])

    left_half = right_half = 0
    # to the left
    accum = 0
    for x in L[mid_index-1::-1]:
        accum += x
        left_half = max(left_half, accum)

    # to the right
    accum = 0
    for x in L[mid_index:]:
        accum += x
        right_half = max(right_half, accum)

    return max(left, right, left_half + right_half)

assert find_max([]) == 0
assert find_max([-1]) == 0
assert find_max([1, 2, 3]) == 6
assert find_max([2, -5, 3]) == 3
assert find_max([-5, 1, 4, -2, 2, -1, 2, -3, 1, -3, 4]) == 6

rawDescription: Generative recursion to find the sublist with the maximum sum


rawDescription: Bar heights and widths in histogram plot of several data


code:
def traverse_tree(t):
    yield t.label, t.val
    for child in t.children:
        yield from traverse_tree(child)

rawDescription: Python generator with recursive call

description: Python generator with recursive call


code:
import copy
x = copy.copy(y)

rawDescription: How can I make x=y in terms of value and not memory?

description: Make x=y in terms of value and not memory


code:
def _spawn_background_interpreter(*args,**kwargs):
    from multiprocessing import Process
    import sys, os
    def _open_interp(locs,stdin):
        import code
        sys.stdin = os.fdopen(stdin)
        code.interact(local=locs)
    locs = args[0] if args else None
    fileno = sys.stdin.fileno()
    p = Process(target=_open_interp, args=(locs,fileno))
    p.daemon = True
    p.start()

rawDescription: Python live coding/debugging

description: Python live coding/debugging


code:
from myapp.serializers import UserSerializer

def getNameandDept(request, salary):
    users = User.objects.filter(salary__gt=salary)
    serializer = UserSerializer()
    return HttpResponse(serializer.serialize(users), mimetype='application/json')

rawDescription: using Django Rest framework to serialize custom data types and return response

description: Using Django Rest framework to serialize custom data types and return response


code:
e = t.xpath('//text')[0]
(e.text + ''.join(map(etree.tostring, e))).strip()

rawDescription: How do I get the whole content between two xml tags in Python?

description: Get the whole content between two xml tags in Python


code:
template = {
    'key_1' : '%(key_1)s',
    'key_2' : '%(key_2)s',
}

values_dict = {'key_1': 'something', 'key_2': 'anything'}

rawDescription: Python dictonary with string placeholders and defaults


item: one two three

item: four five six

rawDescription: Creating a json output out of one item and a second as a dictionary


code:
for header in h3s.select("h3"):
    print("Feature title: ", header.text)
    ul = header.find_next_sibling("ul")
    print(ul.get_text(' ', strip=True))

rawDescription: Unable to scrape the text from a certain LI element