code:
from numpy import *
a = (1, 2, 3)
b = arange(27).reshape(3, 3, 3)
s = slice(*a)
b[s]

rawDescription: python: extracting one slice of a multidimensional array given the dimension index

description: Python: extracting one slice of a multidimensional array given the dimension index


code: map(function, enumerate(a))

rawDescription: Can I use index information inside the map function?

description: Use index information inside the map function


code:
class PublicC:
    def __init__(self):
        self._c = C()

    def public(self):
        self._c.public()

rawDescription: How to design a library public api avoiding to expose internals?

description: Design a library public api avoiding to expose internals


code:
base_seq = "atcgtgagt"
codons = [base_seq[i:i + 3] for i in range(0, len(base_seq), 3)]
amino_acid_counts = collections.Counter(aaDict[c] for c in codons)

rawDescription: Python counting all instances of a value which has more than one key


code: week['value'].apply(lambda x: ((x == x.min()).astype(int).groupby(x.index.dayofweek)).sum()).unstack(1)

rawDescription: Daily frequency count with pandas

description: Daily frequency count with pandas


code:
adjecency_list = {'A': {'B','C'}, 'C':{'D'}, 'B': {'E'}}
def level_dict(adj_list,curr_elems,order=0):
    if not curr_elems:
            return {}
    d = {}
    new_elems = []
    for elem in curr_elems:
            d.setdefault(order,[]).append(elem)
            new_elems.extend(adj_list.get(elem,[]))
    d.update(level_dict(adj_list,new_elems,order+1))
    return d
level_dict(adjecency_list,['A'])

rawDescription: How to convert a binary tree in to a dictionary of levels

description: Convert a binary tree in to a dictionary of levels


code:
import itertools

# here is where you might insert the class code from above

def namekey(room):
    return room.name
def pricekey(room):
    return room.price
[min(group, key=pricekey) for name, group \
      in itertools.groupby(sorted(rooms, namekey), namekey)]

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


rawDescription: How to find a missing number from a list

description: Find a missing number from a list


code:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Generate Data.
nobs, nvars = 100, 5
data = np.random.random((nobs, nvars))
columns = ['Variable {}'.format(i) for i in range(1, nvars + 1)]
df = pd.DataFrame(data, columns=columns)

# Make a pairplot using Seaborn
sns.pairplot(df)
plt.show()

rawDescription: Python: Grid of 2D scatter plots (seaborn.PairGrid)


code:
output = ET.tostring(products, "utf-8")
f = open("xml", 'w')
f.write(output)
f.close()

rawDescription: Write values of Python dictionary back to file


code:
import os
full_filename = "/path/to/file.txt"
fname = os.path.basename(full_filename)
onedir = os.path.join(os.path.basename(os.path.dirname(full_filename)), os.path.basename(full_filename))

rawDescription: Pythonic way to extract the file name and its parent directory from the full file path?


code:
class SubjectProbeResults(models.Model):
    subject = models.ForeignKey(Subject, related_name='probe_results')
    probe_group = models.ForeignKey(ProbeGroup, related_name='probe_results')
    genotypes = models.TextField()

rawDescription: Using Django with MySQL for storing and looking up Large DNA Microarray Results


rawDescription: Adding numpy arrays

description: Adding numpy arrays


code:
import string
whitespace_except_space = string.whitespace.replace(" ", "")
my_string.strip(whitespace_except_space)

rawDescription: strip whitespace except spaces

description: Strip whitespace except spaces


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        toolbar = self.addToolBar('Toolbar')
        toolbar.addAction('Action')
        widget = QtGui.QWidget(self)
        layout = QtGui.QVBoxLayout(widget)
        self.canvas = Canvas(widget)
        layout.addWidget(self.canvas)
        self.setCentralWidget(widget)

class Canvas(QtGui.QGraphicsView):
    def __init__(self, parent):
        super(Canvas, self).__init__(parent)
        self.widget = QtGui.QComboBox(self)

    def resizeEvent(self, event):
        self.widget.move(self.width() - self.widget.width() - 2, 2)
        super(Canvas, self).resizeEvent(event)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    window.setGeometry(500, 300, 200, 200)
    sys.exit(app.exec_())

rawDescription: Relative QWidget position in parent - incorrect Y


code:
import pandas as pd
# max no. of rows to display
pd.options.display.max_rows = 30
# max no. of columns to display
pd.options.display.max_columns = 6

# this limit the column width
pd.options.display.max_colwidth = 10
# this controls the floating rounding (precision, keep 4 decimals after .)
pd.options.display.precision = 5

rawDescription: Changing a table's look in Pandas

description: Changing a table's look in Pandas


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

class PiecewiseNorm(Normalize):
    def __init__(self, levels, clip=False):
        # input levels
        self._levels = np.sort(levels)
        # corresponding normalized values between 0 and 1
        self._normed = np.linspace(0, 1, len(levels))
        Normalize.__init__(self, None, None, clip)

    def __call__(self, value, clip=None):
        # linearly interpolate to get the normalized value
        return np.ma.masked_array(np.interp(value, self._levels, self._normed))

    def inverse(self, value):
        return 1.0 - self.__call__(value)

rawDescription: define custom Normalisation function in matplotlib when using plt.colorbar()

description: Define custom Normalisation function in matplotlib when using plt.colorbar()


code: gw_func_dict = {chr(2**i): func for i, func in enumerate(gwfuncs[:8])}

rawDescription: pass dict by reference to bit encoded list of functions

description: Pass dict by reference to bit encoded list of functions


code:
html = render_to_string('main/child_comment.html',
                                 {'comment': [new_comment],
                                  'user': request.user,
                                  'comment_form':comment_form
                        })
response_data = {
                    "status":200, "message":"comment_stored",
                    "comment":html,
                    "parent": True, "parent_id": parent_comment.id,
                    "comment_count": parent_comment.comment_count()
                }
return JsonResponse(response_data)

rawDescription: how to use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this?

description: Use ajax function to send form without page getting refreshed, what am I missing?Do I have to use rest-framework for this


code:
import binascii
filename = 'test.dat'
with open(filename, 'rb') as f:
    content = f.read()
print(binascii.hexlify(content))

rawDescription: How to parse .bin into list?

description: Parse .bin into list


code:
nList = []
for element in nList:
    if option == 0:
        if element > 5:
            nList.append(element)
return nList

rawDescription: Trying to return numbers in a list

description: Trying to return numbers in a list


rawDescription: Extract list from given list and given indices


code:
balance = int(input("Enter initial balance: $ "))
count = 1
total =0
while count <= 11:
    n = int(input("Enter deposit %s #: " %(count)))
    count += 1
    total += n #keep on adding deposit amounts.

print("Original price: $ %d" %balance)
print("Final Amount: $ %d" %(total + balance) )

rawDescription: writing (for and while) loop program in python?

description: Writing (for and while) loop program in python


rawDescription: Downloading files using Python

description: Downloading files using Python


code:
_,_,Third,_,Fifth=[c for c in 'abcde']
Third, Fifth

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


code:
def repeat_bubble_until_finished(expr):
    """ Repeat recursive_bubble_ands_up until there's no change
    (i.e. until all possible bubbling has been done).
    """
    while True:
        old_expr = expr
        expr = recursive_bubble_ands_up(old_expr)
        if expr == old_expr:
            break
    return expr

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

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


code:
class C(object):
    pass

class_c = C

# they are the same
assert class_c is C

# they are both instance of C
instance1 = class_c()
instance2 = C()

def f():
    pass

function_f = f

# again, they are the same
assert function_f is function

# both results are results from function f
result1 = f()
result2 = function_f()

rawDescription: Syntax for a dictionary of functions?

description: Syntax for a dictionary of functions


code: map(int, str(a).split('.'))

rawDescription: How do you index a float value in Python?

description: Index a float value in Python


code:
a = [{'a': 3, 'b': 4}, {'a': 10, 'b': 4}, {'a': 5, 'b': 5}]
seen = set()
[entry for entry in a if not (entry['b'] in seen or seen.add(entry['b']))]

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

description: Use a sentinel list in a comprehension


code:
import copy
lst2=copy.deepcopy(lst1)

rawDescription: What is the best way to copy a list?

description: What is the best way to copy a list


code:
import random

def noncontiguoussample(n,k):
    numbers = set(range(1,n+1))
    samples = []
    for _ in range(k):
        v = random.choice(list(numbers))
        samples.append(v)
        numbers -= set([v-1, v, v+1])
    return samples

rawDescription: Finding k non contiguous random numbers with uniform probability in the range 1..n


code: file_stats_user[user] = []

rawDescription: Python Multiprocessing DictProxy append to dict of list not working


rawDescription: Convert list or numpy array of single element to float in python


rawDescription: Using lambda expression to filter a string


code:
a = "abc" # python caches abc
b = "abc" # it reuses the object when assigning to b
id(a)
id(b)
a = 'abc abc'   # not cached
id(a)
b = 'abc abc'
id(b)         # different id's different objects

rawDescription: Why does a space effect the identity comparison of equal strings?


code:
html = '''
t
    '''
soup = BeautifulSoup(html)
a_tag = soup.find('a')
a_tag.find_parents(attrs={'class':'nv-talk'})

rawDescription: Webcrawler - Check if <a> tag with href is within an li tag using Beautiful soup?


code:
py -2.7 # Runs Python 2.7
py -3.3 # Runs Python 3.3
py -2 # Runs the latest version of Python 2.x (so if you have 2.6 and 2.7 it will run 2.7)

rawDescription: How can I make the "python" command in terminal, run python3 instead of python2?

description: Make the "python" command in terminal, run python3 instead of python2


code:
def my_function(data):
    ...

rawDescription: How can I pass a .txt file as a function parameter

description: Pass a .txt file as a function parameter


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


code: rq.countrychoice[-1] + "/" + rq.citychoice[-1]

rawDescription: How do I get input out of a class and into the main script

description: Get input out of a class and into the main script


code:
lens = [len(item) for item in data]
R = np.repeat(np.arange(len(lens)),lens)
C = np.searchsorted(column_data,np.concatenate(data))

out = np.zeros((len(data), len(column_data)))
out[R,C] = 1

rawDescription: Efficiently filling NumPy array using lists of indices


code:
L = ['foo', 'biology', 'sequence']
[shuffle_word(word) for word in L]

rawDescription: Are there any way to scramble strings in python?


code: dec2bin(double('foo'), 8)

rawDescription: Converting to binary in MATLAB and Python


code:
class boundedlist(list):
    def __getitem__(self,indices):
        try:
            l=list(self)
            for i in indices : l=l[i]
            return l
        except IndexError:
            return 0

rawDescription: Handling out of range list index in Python 2.7


code:
a = range(30)
for i in a[-2:]:
  print(i)

s = slice(-2, None, None)
for ix in range(*s.indices(len(a))):
  print(a[ix])

rawDescription: How do I access the elements of a slice object in python

description: Access the elements of a slice object in python


code: merge_df = pd.merge(holding_df, invest_df, on=['key', 'dept_name', 'res_name', 'year'], how='left').fillna(0)

rawDescription: Merging two pandas dataframes results in "duplicate" columns


code:
import base64

with open('frameBorder.gif', 'rb') as f:
    encoded = base64.encodestring(f.read())
    print(encoded.decode('latin1'))

rawDescription: Tkinter image as frame style

description: Tkinter image as frame style


code:
m = {}
i = 0
d_keys = d.keys()
max_value = 0
while i < len(d):
    d_i = d[d_keys[i]]
    j = 0
    while j < len(d_i):
        d_i_j = d_i[j]
        if max_value < d_i_j:
            max_value = d_i_j
        m[d_i_j] = d_keys[i]
        j += 1
    i += 1

l = []
i = 1
while i <= max_value:
    l.append(m.get(i))
    i += 1

rawDescription: How to convert dictionary of indices to list of keys?

description: Convert dictionary of indices to list of keys


rawDescription: numpy get all combinations of rows and column indices 2D array

description: Numpy get all combinations of rows and column indices 2D array


code:
import pandas as pd
import numpy as np
from pandas import melt

df = pd.DataFrame(np.random.randint(10, 1000, size=(2,12)), index=['PrinterBlue', 'PrinterBetter'], columns=pd.date_range('1-1', periods=12, freq='M'))

dft = df.T
dft["date"] = dft.index
result = melt(dft, id_vars=["date"])
result.columns = ["date", "brand", "sales"]
print (result)

rawDescription: Pandas dataframe : Multiple Time/Date columns to single Date index


code:
def remove_letters(str1, str2):
    res = ""
    s = set(str1)
    for char in str2:
        if char not in s:
            res += char
    return res

rawDescription: Removing letters from a string that occur in the previous string


code:
args = list(args)
args.pop(0)
recursiveCall( *tuple(args) )

rawDescription: Variable number of arguments and recursion in Python


code:
from datetime import timedelta
from urllib2 import urlopen
from xml.dom.minidom import parseString
for vid in ('wJ4hPaNyHnY', 'dJ38nHlVE78', 'huXaL8qj2Vs'):
    url = 'https://gdata.youtube.com/feeds/api/videos/{0}?v=2'.format(vid)
    s = urlopen(url).read()
    d = parseString(s)
    e = d.getElementsByTagName('yt:duration')[0]
    a = e.attributes['seconds']
    v = int(a.value)
    t = timedelta(seconds=v)
    print(t)

rawDescription: Getting length of YouTube video (without downloading the video itself)


rawDescription: CSV data to Nested Dictionaries

description: CSV data to Nested Dictionaries


code:
new_email_index = get_email_index(new_emails_list[0])
old_email_index = get_email_index(old_emails_list[0])
s_new_emails = set([row[new_email_index] for row in new_emails_list[1:]])
s_old_emails = set([row[old_email_index] for row in old_emails_list[1:]])

rawDescription: Improving python performance in comparing two lists


code:
import sys

fieldstruct = struct.Struct(fmtstring)
if sys.version_info[0] < 3:
    parse = fieldstruct.unpack_from
else:
    # converts unicode input to byte string and results back to unicode string
    unpack = fieldstruct.unpack_from
    parse = lambda line: tuple(s.decode() for s in unpack(line.encode()))

rawDescription: Efficient way of parsing fixed width files in Python


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

rawDescription: Comparing three numbers?

description: Comparing three numbers


code:
try:
    cmp
except NameError:
    def cmp(x, y):
        if x < y:
            return -1
        elif x > y:
           return 1
        else:
            return 0

rawDescription: How to convert sort using cmp from python 2 to python 3?

description: Convert sort using cmp from python 2 to python 3


code: c = [a + [i] for i in b]

rawDescription: Iteratively add elements to a list

description: Iteratively add elements to a list


code:
def amdfilter(input):
    doc = xee.fromstring(input)

    for node in doc.findall('Component'):
        if 'timeStamp' in node.attrib:
            del node.attrib['timeStamp']

    return xee.tostring(doc)

rawDescription: Filtering XML in Python

description: Filtering XML in Python


code:
def func(x):             # defines the function name and input parameter
    res=0                # created a variable that is right now set to 0
    for i in range(x):   # this has two parts, for-loop, and a range function both explained below
        res += i         # this adds 1 to the variable 'res' each time the for-loop loops
    return res           # end of the function, passes the variables value back to the caller

print(func(5))           # call the function while passing 5 as an argument

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


code:
lst = [tuple(i) for i in ls]
collections.Counter(lst)

rawDescription: Groupby in a list for python

description: Groupby in a list for python


code: revbinnedstars = np.sum(stars * grid, axis=1) / np.sum(grid, axis=1)

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


code:
print(df.dtypes)
# ID               int64
# ORIG             int64
# TIME    datetime64[ns]
# TEXT            object
# dtype: object

rawDescription: Import data into DataFrame with additional commas


code:
class BunchOfStuff(object):
    def __init__(self):
        self.variable1 = 5
        self.variable2 = 10
        self.variable3 = 15
        self.refresh()
    def refresh():
        self.variable4 = self.variable1 + self.variable2 + self.variable3
        self.variable5 = self.variable3 - self.variable2 / self.variable1

stuff = BunchOfStuff()
print(stuff.variable4) # prints 30
stuff.variable1 = 10
print(stuff.variable4) # still prints 30
stuff.refresh()
print(stuff.variable4) # now prints 35

rawDescription: Refreshing a list of variables with one command


rawDescription: Iterating over a Nested List and Changing Values


code:
import pygraphviz as pgv
A=pgv.AGraph()
A.node_attr.update(color="red", style="filled")
A.edge_attr.update(color="blue", len="10.0", width="2.0")
class Watcher(type):
    def __init__(cls, name, bases, clsdict):
        print(bases,"was subclassed by " + name)
        print("Class", cls)
        print("CLS DICT", clsdict)
        print("\n\n"*3)
        A.add_edge(bases, name)
        super(Watcher, cls).__init__(name, bases, clsdict)
        A.write('resources_graph.dot')
        B=pgv.AGraph('resources_graph.dot')
        B.layout()
        B.draw('resources_graph.png')
class Resource:
    __metaclass__ = Watcher

rawDescription: How to plot tree of resources in twisted.web python

description: Plot tree of resources in twisted.web python


code:
1
FredFredFredFred
2
FredFredFred
3
FredFred
4
Fred

rawDescription: Produce the following output (for and while loops) in python?


code:
with open(filename) as f:
    mx = [[int(x) for x in line.split(',')] for line in f]

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

description: How should you read a 2D integer array


code: key, value = list(d.items())[0]

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


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: lst = filter(lambda x: sum(x) in spectrum, lst)

rawDescription: How to filter a list of sublists

description: Filter a list of sublists


rawDescription: Create GCE instance using Python API

description: Create GCE instance using Python API


code:
with open('/Users/kyle/Documents/english words.txt') as word_file:
    english_words = set(word.strip().lower() for word in word_file if len(word.strip()) == 4)

rawDescription: python program very slow

description: Python program very slow


rawDescription: Where does Python retrieve the <filename> traceback entry field from


code: u[row_col_index[0], row_col_index[1]] = u_pres

rawDescription: vectorized assignment statement for selected elements of 2d array in numpy

description: Vectorized assignment statement for selected elements of 2d array in numpy


code:
M.data
M.indices
M.indptr

rawDescription: pointers in sparse matrix in python scipy

description: Pointers in sparse matrix in python scipy


code:
feature = cartopy.feature.NaturalEarthFeature('physical', 'coastline', '110m')
geoms = feature.geometries()

rawDescription: 3D CartoPy similar to Matplotlib-Basemap


code:
if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time

rawDescription: accurately measure time python function takes

description: Accurately measure time python function takes


code:
using_mask      : 0.85
using_apply_alt : 2.04
using_apply     : 3.70

rawDescription: Python: Pandas - Delete the first row by group


code:
def parse(self, response):
    if 'logout' in response.url:
        return

    # extract items

rawDescription: scrapy avoid crawler logging out

description: Scrapy avoid crawler logging out


code:
result=[]
with open(csvfile,'r') as f:
    for line in f:
        row=[]
        for text in line.split('\t'):
            match=re.search('([0-9]/[0-9])',text)
            if match:
                row.append(match.group(1))
            else:
                row.append("NA")
        result.append(row)
print(result)

rawDescription: Slice specific characters in CSV using python


code: func<Ctrl+i>(1, "a")

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

description: Produce a numpy-like documentation


code:
class Bar(object):
    def __init__(self, foo):
        self.myvar = foo.myvar

rawDescription: How do I import a variable from another class?

description: Import a variable from another class


code:
class_num = input('Which class (1, 2, or 3)? ')
score_sort = input('Sort by name or score? ').lower().startswith('s')

with open("Class " + class_num + ".txt", "r") as f:
    scores = {name.strip():float(score) for
              name,score in (line.strip().split(':') for line in f)}
    if score_sort:
        for name in sorted(scores, key=scores.get, reverse=True):
            print(scores.get(name), ':', name)
    else:
        for name in sorted(scores):
            print(name, ':', scores.get(name))

rawDescription: python split and reverse text file

description: Python split and reverse text file


code:
from xml.etree import ElementTree

tree = ElementTree.parse('products.xml')
root = tree.getroot()
product_elements = root.findall('product')

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

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


code: del foo.fields[index]

rawDescription: How can I remove an item from a repeated protobuf field in python?

description: Remove an item from a repeated protobuf field in python


code: json_data = {"name": "f", "args": ["hello world"]}

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


code:
cons = []
for d in [0.1, 0.2, 0.3]:
    cons += {'type': 'ineq', 'fun': lambda x, d=d: -1*bounds(x) + d}

rawDescription: Dynamic dictionary including keywords/ lambda function


code:
df.columns.names = ['asset', 'chart']
df.index.names = ['date']  # well, not in this toy example
df

rawDescription: Commodity Futures Hierarchical Data Structure


rawDescription: Is it possible to fetch the first few, say 1K, of a webpage using python?


code:
try:
   from cStringIO import StringIO
except ImportError:   #python 3
   from io import StringIO

def myfunc(x):
    try:
       x.seek(0)
    except AttributeError: #likely a string
       x = StringIO(x)

    for line in x:
       doSomething(line)

rawDescription: writing Python function to iterate over lines -- accepting either string or file-like object

description: Writing Python function to iterate over lines -- accepting either string or file-like object


code:
from rpy2.robjects import Formula
from rpy2.robjects.lib.ggplot2 import ggplot, geom_bar, aes_string, theme_bw, facet_grid

## oddity with names in the examples, that can either be corrected in the Python-pandas
## structure or with an explicit conversion into an R object and renaming there
drr = rpy2.robjects.pandas2ri.pandas2ri(dr)
drr.names[2] = 'n'
drr.names[3] = 'value'

p = ggplot(drr) + \
    geom_bar(aes_string(x="letters", y="value", fill="bool"),
             stat="identity", position="stack") + \
    theme_bw() + \
    facet_grid(Formula('~ n'))

p.plot()

rawDescription: Pandas stacked multilevel index plot

description: Pandas stacked multilevel index plot


rawDescription: Python Tkinter read only text field

description: Python Tkinter read only text field


rawDescription: Use Column and Row Multi-Index values in Pandas Groupby without unstacking


code:
a=sys.argv[1]
_,a=sys.argv

rawDescription: What is the shortest way to get argument passed into program?


code:
nfl = soup.findAll('li', "player")
lines = ("{}. {}\n".format(ind,span.get_text(strip=True).rstrip("+"))
         for ind, span in enumerate(nfl,1))
print("".join(lines))

rawDescription: Beautiful Soup - how to clean extracting data?


code:
def remove_tags_if_orphan(tags_pk_set):
    """Removes tags in tags_pk_set if they're associated with only 1 File."""

    annotated_tags = Tags.objects.annotate(n_files=Count('files'))
    unreferenced = annotated_tags.filter(pk__in=tags_pk_set).filter(n_files=1)
    unreferenced.delete()

# This will clean unassociated Tags when clearing or removing Tags from a File
@receiver(m2m_changed, sender=Files.tags.through)
def handle_tags(sender, **kwargs):
    action = kwargs['action']
    if action == "pre_clear":
        tags_pk_set = kwargs['instance'].tags.values_list('pk')
    elif action == "pre_remove":
        tags_pk_set = kwargs.get('pk_set')
    else:
        return
    remove_tags_if_orphan(tags_pk_set)

# This will clean unassociated Tags when deleting/bulk-deleting File objects
@receiver(pre_delete, sender=Files)
def handle_file_deletion(sender, **kwargs):
    associated_tags = kwargs['instance'].tags.values_list('pk')
    remove_tags_if_orphan(associated_tags)

rawDescription: How to delete many to many when unassociated in Django?

description: Delete many to many when unassociated in Django


code:
lst = ['url1', 'value1', 'url2', 'value2']
i = iter(lst)
zip(i,i)

rawDescription: Retrieve a 2 items from a list at a time in loop?


code:
from PIL import Image
from numpy import*

temp=asarray(Image.open('test.jpg'))
for j in temp:
    new_temp = asarray([[i[0],i[1]] for i in j]) # new_temp gets the two first pixel values

rawDescription: import image to python as 2D array

description: Import image to python as 2D array


code:
foo = 12345
[int(digit) for digit in str(foo)]

rawDescription: How to convert a number into a linked list of its digits in python

description: Convert a number into a linked list of its digits in python


code:
sys.path.insert(0, os.path.abspath('../../')) #documentation is detected
sys.path.insert(0, os.path.abspath('../../package')) #documentation isn't detected

rawDescription: Sphinx doesn't process python classes

description: Sphinx doesn't process python classes


code:
import socket, struct

def main(host):
    # Connect to server and get image size.
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client.connect((host, 65000))
    packed = recvall(client, struct.calcsize('!I'))
    # Decode the size and get the image data.
    size = struct.unpack('!I', packed)[0]
    print('Receiving data from:', host)
    data = recvall(client, size)
    # Shutdown the socket and create the image file.
    client.shutdown(socket.SHUT_RDWR)
    client.close()
    with open('image.bmp', 'wb') as file:
        file.write(data)

def recvall(sock, size):
    message = bytearray()
    # Loop until all expected data is received.
    while len(message) < size:
        buffer = sock.recv(size - len(message))
        if not buffer:
            # End of stream was found when unexpected.
            raise EOFError('Could not receive all expected data!')
        message.extend(buffer)
    return bytes(message)

if __name__ == '__main__':
    main('localhost')

rawDescription: Data lost on receiver side in python socket programming


code:
import socket,struct
packed_value = struct.pack('!I', 167772160)
addr = socket.inet_ntoa(packed_value)
assert addr == '10.0.0.0'

rawDescription: using inet_ntoa function in Python

description: Using inet_ntoa function in Python


code:
def form(request):
    #This is using regular Django forms
    #print request.POST
    #form = EmailForm(request.POST or None)

    #This is using model forms
    number = request.POST.get('telephone')
    number_occurrences = User.objects.filter(number=user_number).count()
    if  number_occurrences > 0:
        context = {'error':'Number already exist'}
        return render(request,template,context)

    form = UserForm(request.POST or None)
    if form.is_valid():
        new_instance = form.save(commit=True)

        new_instance.save()
        context = {"form": form }
        template = "form.html"
        return render(request,template,context)

rawDescription: Django Integrity Error Handling

description: Django Integrity Error Handling


code:
class CellClass:
  def __init__(self, value):
    self.value = value
  def __repr__(self):
    return 'Cell value: %s' % (self.value)
c = CellClass('cell text')

rawDescription: how to get the value stored in the hex file location in python?

description: Get the value stored in the hex file location in python


code:
try:
    from io import BytesIO
except ImportError: # Python < 2.6
    from StringIO import StringIO as BytesIO
import csv
with open('utf16.csv', 'rb') as binf:
    c = binf.read().decode('utf-16').encode('utf-8')
for line in csv.reader(BytesIO(c)):
    print(line) # do something with the line

rawDescription: Python UTF-16 CSV reader

description: Python UTF-16 CSV reader


code: SObj1.X = 10

rawDescription: ndarray that updates its data on demand

description: Ndarray that updates its data on demand


code:
vowels = {'a', 'u', 'U', 'o', 'e', 'i', 'A', 'I', 'E', 'O'}

def get(x, step):
    yield from (x[i:i+step] for i in range(len(x[:-1])))

print([x for x in s.split() if any(vowels.issuperset(pr) for pr in get(x, 2))])

rawDescription: Delete words which have 2 consecutive vowels in it


code:
def DisplayIt(request):
    stringparts = []
    for a in A.objects.filter(b__name__isnull=False).select_related():
        stringparts.append(a.b.name)
    for a in A.objects.filter(b__name__isnull=True).select_related():
        stringparts.append("dummy value for missing b.name")
    ''.join(stringparts)

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


code:
from mpmath import mp

# set precision
mp.dps = 20

for x in range(21):
    print(x, mp.besselj(0, x), mp.besselj(1, x), mp.besselj(2, x))

rawDescription: Python numerical integration with Simson's rule


code: headers = {'Accept': 'application/json; charset=UTF-8'}

rawDescription: Unable to make post request using request library python


code:
for line in txt:
    is_number = phonenumbers.parse(line,"GB")
    if phonenumbers.is_valid_number(is_number):
        if line.startswith(area_codes):
            print(line, next(filter(line.startswith, area_codes)))

rawDescription: In Python,if startswith values in tuple, I also need to return which value


code:
df['OEDatum'] = df[['OEDatum','OEUhrzeit']].apply(lambda x: dt.datetime.combine(x['OEDatum'].date(),x['OEUhrzeit']), axis=1)
df['ODatum'] = df[['ODatum','OUhrzeit']].apply(lambda x: dt.datetime.combine(x['ODatum'].date(),x['OUhrzeit']), axis=1)

rawDescription: Pulling date and time from Excel to Pandas and combining it to a timestamp


code:
foo.__code__.co_lnotab
bar.__code__.co_lnotab
foo.__code__.co_code == bar.__code__.co_code

rawDescription: Is the resulting bytecode generated in Python deterministic?


code: data = InputFile.read()

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


code: data = np.column_stack([xy, z])

rawDescription: Using scipy's kmeans2 function in python


code:
1
a
2
b
3
c

rawDescription: Loop print of 2 columns in to 1

description: Loop print of 2 columns in to 1


code:
l = [0]
t = (l,)
t[0] is l #both t[0] and l point to the same object [0]
l[0] += 1 # modify [0] in-place
t
l
x = y =[]    # x, y point to the same object
x.append(1)  # list.append modifies the list in-place
x, y
x = x + [2]  # only changes x, x now points to a new object
x, y

rawDescription: Assignment rules

description: Assignment rules


code:
board = empty_board(4)
board[5][2] = 1

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


rawDescription: Remove duplicate values from entire dataframe


code:
T = 1  # eval('T') will be 1
F = 0  # eval('F') will be 0

rawDescription: asked to calculate the logical matrix P=mn

description: Asked to calculate the logical matrix P=mn


code:
#test script
import foo
import foo2
foo2.foo.parse() #i want this to print 'foo2'
foo2.foo.Parser()
foo.parse() #i want this to print 'foo'
foo.Parser()

rawDescription: Alter module variables in one module while it doesn't change in the original


rawDescription: Extract row with maximum value in a group pandas dataframe


code: [line.split() for line in csv.splitlines()]

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: help(funct)

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

description: Show my argspec/docstring in bpython


code:
df['date'] = df.index.date
df['year'] = df.index.year
df['month'] = df.index.month

rawDescription: Modify Pandas dataframe to list year month and date


code:
df["Website"].str
df["Website"].str.lower()
df["Website"].str.lower().str.contains("see over")

rawDescription: Conditional Cell Substitution in Pandas, Python 2.7


code:
import inspect

class renameable(object):
  def rename_me(self, new_name):
    for stack_frame in inspect.stack()[1:]:
      frame_object = stack_frame[0] # frame is the first object in the tuple
      for (name, value) in frame_object.f_locals.iteritems():
        if value is self:
          old_name = name
          matched_frame = frame_object
          break
      if matched_frame:
        break
    if matched_frame:
      matched_frame.f_locals[new_name] = matched_frame.f_locals[old_name]
      del matched_frame.f_locals[old_name]

rawDescription: distinct classes using `with` in Python

description: Distinct classes using `with` in Python


code:
with open("class.txt", "rt") as f:
    classes = [int(line) for line in f.readlines()]

rawDescription: Python: How to extract data in text file based on class information from another text file?


code:
cc1 = configContainer()
cc2 = configContainer()
cc1.instances["line10"] = "foo"
configContainer.instances
cc2.instances["line10"] = "bar"
configContainer.instances
cc1.instances

rawDescription: Python nested objects unable to retrieve value in function


code:
import struct
x = [10, -41, -119, 65]
struct.unpack('<f', struct.pack('4b', *x))[0]

rawDescription: Converting a float in chars to float (PYTHON)


code:
import os
MYDIR = os.path.dirname(__file__)
with open(os.path.join(MYDIR, 'test.txt')) as f:
    pass
    # and so on

rawDescription: Python - IOError: [Errno 2] No such file or directory: u'lastid.py' for file in same directory. Works locally, doesn't on Heroku


code:
import csv
from collections import OrderedDict as od

data = od() # ordered dict object remembers the order in the csv file

with open(path,'rb') as csvFile:
    reader = csv.reader(csvFile, delimiter = ' ')
    for row in reader:
        data[row[0]] = row[1:] # Slice the row up into 0 (first item) and 1: (remaining)

rawDescription: Extracting variable names and data from csv file using Python


code:
import numpy as np
x = 1000
lowDimRepresentation = np.random.random((x, 100))
principalComponents = np.random.random((100, 784))
sameDimRepresentation = (lowDimRepresentation[:, np.newaxis] * principalComponents.T).sum(axis=2)
esum_same = np.einsum('ij,jl->il', lowDimRepresentation, principalComponents)
np.allclose(sameDimRepresentation, esum_same)

rawDescription: Numpy rewriting operation using einsum

description: Numpy rewriting operation using einsum


code:
from sympy import *
x, y, z = symbols('x y z')
f = symbols('f', cls=Function)

rawDescription: Simplify removes relational term in Sympy?


rawDescription: Python: Scrape Data from Web after Inputing Info


code:
import lxml.etree as etree
xml_node = etree.Element("node")
item = etree.SubElement(xml_node, 'Item')
etree.SubElement(item, 'Name').text = 'Hello'
etree.SubElement(item, 'Hero').text = '1'
etree.SubElement(item, 'Date').text = '2014-01-01'
item.insert(1, item[-1])
print(etree.tostring(xml_node, pretty_print=True))

rawDescription: Insert xml node in specific location

description: Insert xml node in specific location


code:
from collections import defaultdict
minpoints = defaultdict(lambda: defaultdict(lambda : 0.))  # 0. or another suitable min value
for p in points:
    minpoints[p[0]][p[1]] = min(p[2], minpoints[p[0]][p[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 transposeDict(listOfDicts):
    """Turn a list of dicts into a dict of lists.  Assumes all dicts in the list have the exact same keys."""

    keys = listOfDicts[0].iterkeys()
    return {key: [d[key] for d in listOfDicts] for key in keys}

rawDescription: Python: DictReader returning a list of dictionaries?


code:
import json
myfile = open("myfile.txt")
myVars = json.load(myfile)
myfile.close()
myVars['a']

rawDescription: Read .arrays txt files with python?

description: Read .arrays txt files with python


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

rawDescription: How to make a dictionary from list

description: Make a dictionary from list


code:
ii = np.argsort(a)[-3:] # positions
vals = a[ii]            # values

rawDescription: How to select not only the maximum of a `numpy.ndarray` but the top 3 maximal values in python?

description: Select not only the maximum of a `numpy.ndarray` but the top 3 maximal values in python


code:
a = []
d = {}
d['a'] = a
a.append(1)
a
d['a']    # modified because d is actually storing a reference to that list.
a = []    # now a is a completely different object
a
d['a']   # old reference keep original a value alive.

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


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

description: Prevent infinite looping in Python while parsing with lxml


code: cmap, norm = mcolors.from_levels_and_colors(levels, colors)

rawDescription: Join two colormaps in imshow

description: Join two colormaps in imshow


code: "".join([chr((ord(i)+ord(j))%26+97) for i,j in zip(uinput,uinput2)])

rawDescription: Adding list/string ord() values in Python


code:
mapping = {item.id: item for item in collection}
item = mapping.get(1)

rawDescription: Select an element that satisfies a condition


code: print([link.get_attribute("href") for link in links])

rawDescription: Selenium pull HREF out of TD in table

description: Selenium pull HREF out of TD in table


code:
import itertools
for x,y in itertools.izip(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


rawDescription: Catch multiple string occurrences in multiline text


code: browse(cr ,uid, select, context=None, list_process=None, fields_process=None)

rawDescription: How can I loop and access values of fields in OpenERP?

description: Loop and access values of fields in OpenERP


code:
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
)

rawDescription: Template directory logic in Django

description: Template directory logic in Django


rawDescription: Python - How to find datetime overlapping?


code:
import nfqueue
from dpkt import ip

q = None

def cb(dummy, payload):
    # make decision about if the packet should be allowed. in this case, drop everything:
    payload.set_verdict(nfqueue.NF_DROP)

q = nfqueue.queue()
q.open()
q.bind()
q.set_callback(cb)
q.create_queue(1)

q.try_run()

rawDescription: Is it possible to write a firewall in python?


code:
from base64 import b64encode

@app.route('/event/<int:id>/logo')
def event_logo(id):
    event = Event.query.get_or_404(id)
    image = b64encode(event.logo)
    return render_template('event.html', event=event, logo=image)

rawDescription: Serve image stored in SQLAlchemy LargeBinary column


code:
class A:
  def some_func():
    pass

  def __init__(self):
    self.init = 1

    self.some_func() # just call member function

rawDescription: Class defintion and methods

description: Class defintion and methods


code:
dct = {'light': ['on', 'off'], 'lock': ['lock', 'unlock']}
dct

rawDescription: PHP like array handling in Python: Indexing multidimensional array


code:
import re

# I assume you have a list of all possible sections
sections = [
    'CLINICAL HISTORY',
    'MEDICATIONS',
    'INTRODUCTION',
    'DESCRIPTION OF THE RECORD',
    'IMPRESSION',
    'CLINICAL CORRELATION'
]

# Build a regexp that will match any of the section names
exp = '|'.join(sections)

with open(some_file, 'r') as r:
    contents_of_file = r.read()
    infos = list(re.split(exp, contents_of_file)) # infos is a list of what's between the section names
    infos = [info.strip('\n :') for info in infos] # let's get rid of colons and whitespace in our infos
    print(infos) # you don't have to print it :)

rawDescription: Storing multiple lines from a file to a variable using a delimiter


code: getattr(module, name)

rawDescription: Dynamically return a class implementation in Python


code:
x = ('var1=abc\n', 'var2=xyz\n', 'var3=10')
{elem.split('=', 1)[0]: elem.split('=', 1)[1].strip() for elem in x}

rawDescription: How to parse a tuple of "x=y" strings into a dictionary in python?

description: Parse a tuple of "x=y" strings into a dictionary in python


code:
result = np.zeros(b.shape)
# actually you can also use result = np.zeros_like(b)
# but that also copies the dtype not only the shape

rawDescription: python how to pad numpy array with zeros

description: Python how to pad numpy array with zeros


code:
l=7
x=6
set(itertools.permutations([1]*x + [0]*(l-x)))

rawDescription: find binary permutations in python

description: Find binary permutations in python


code: keys = [k for k in x if k[0] == 1]

rawDescription: Python key exists: Key is a tuple of integer and string


rawDescription: Correct way to do operations on Memmapped arrays


code:
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.set_xlabel('Z')
ax.set_ylabel('X')
ax.set_zlabel('Y')

for i in range(0,X.shape[0]):
    # Only do the scatter inside the loop
    ax.scatter(X[i,:], Y[i,:], Z[i,:], c='r', marker='o')

plt.show()

rawDescription: Matplotlib - Plot 3D with for loop

description: Matplotlib - Plot 3D with for loop


code:
[{'name': name,
  'iq': iq,
  'distance': iq<=95 and "low" or iq<=100 and "mid" or "high"}
 for name,iq in intelligence.items()]

rawDescription: Doing mapping from range of numbers to words


code: owner = models.ForeignKey(User, related_name="owners_friend")

rawDescription: Django models, how to set object owner while saving


rawDescription: Multiple request filtr from url Djjango

description: Multiple request filtr from url Djjango


code: [queue.write(queue.new_message(i)) for i in dataone]

rawDescription: Unable to upload a json file in same syntex to amazon SQS using Python BOTO


code: list(IT.izip_longest(readers[0], readers[1], readers[2], ...))

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


code: df['connection'] = df.apply(lambda row: check(row['fld1'], row['fld2'],cnxn), axis=1)

rawDescription: Conditionally and interatively calculate column based on value of three columns


code:
from tkinter import *

root = Tk()
entry = Entry(root)
entry.config(state='disabled') # OR entry['state'] = 'disabled'
entry.pack()
root.mainloop()

rawDescription: In Tkinter, How I disable Entry?

description: In Tkinter, How I disable Entry


rawDescription: How do I change my float into a two decimal number with a comma as a decimal point separator in python?

description: Change my float into a two decimal number with a comma as a decimal point separator in python


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


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata

# with this way you can load your csv-file really easy -- maybe you should change
# the last 'dtype' to 'int', because you said you have int for the last column
data = np.genfromtxt('output.csv', dtype=[('x',float),('y',float),('z',float)],
                     comments='"', delimiter='|')

# just an assigning for better look in the plot routines
x = data['x']
y = data['y']
z = data['z']

# just an arbitrary number for grid point
ngrid = 500

# create an array with same difference between the entries
# you could use x.min()/x.max() for creating xi and y.min()/y.max() for yi
xi = np.linspace(-1,1,ngrid)
yi = np.linspace(-1,1,ngrid)

# create the grid data for the contour plot
zi = griddata(x,y,z,xi,yi)

# plot the contour and a scatter plot for checking if everything went right
plt.contour(xi,yi,zi,20,linewidths=1)
plt.scatter(x,y,c=z,s=20)
plt.xlim(-1,1)
plt.ylim(-1,1)
plt.show()

rawDescription: Matplotlib contour plot with intersecting contour lines


code:
myUser = User()
myUser.function()

rawDescription: Use a variable in a function

description: Use a variable in a function


code:
def __init__(self, items=()):
    ''' Accepts any iterable
    The appropriate TypeError will be raised if items is not iterable '''
    self.l = list(items)

rawDescription: How to allow __init__ to allow 1 or no parameters in python

description: Allow __init__ to allow 1 or no parameters in python


code:
d1 = {'a': 1, 'b':2}
d2 = {'a':2, 'b': 2, 'c':3}
diff = set(d1.items()).symmetric_difference(d2.items())
diff

rawDescription: script to find the difference between two dictionaries in python

description: Script to find the difference between two dictionaries in python


code:
def sql_decorator(table_name):
    def the_actual_decorator(func):
        def decorated(user, limit):
            ... # do stuff with table_name
            return func(user, limit)
        return decorated
    return the_actual_decorator

@sql_decorator('some_table_name')
def user_records(user, limit):
    ...

rawDescription: Python Decorator with extraneous arguments


rawDescription: How to get time from this xml tag?

description: Get time from this xml tag


rawDescription: Stripping an dynamic url content

description: Stripping an dynamic url content


code:
"Newton\\'s method"
print("Newton\\'s method")

rawDescription: Replace single quote with backslash single quote in python


code:
a0b0c
a1b0c
a0b1c
a1b1c

rawDescription: Getting info out of each loop for use in the next without terminating the loop (Python)


code: a

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

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


code: con.execute("SELECT STR_TO_DATE(date_recieved, '%m/%d/%Y') from raw_table")

rawDescription: Escaping % in MySQLdb

description: Escaping % in MySQLdb


code:
if Product.objects.all().values('price').annotate(Count('price')).count() == 1:
    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: mylist[0] # instead of 'var0'

rawDescription: Python csvreader separate lines

description: Python csvreader separate lines


rawDescription: How to add dictionaries to tuple

description: Add dictionaries to tuple


code: np.exp(np.outer(x, y))

rawDescription: product of arrays of different sizes in numpy

description: Product of arrays of different sizes in numpy


code:
td = server_dt - local_dt
minutes, seconds = divmod(td.total_seconds(), 60)
hours, minutes = divmod(minutes, 60)
print("%02d:%02d:%02d" % (hours, minutes, seconds))
#-> 03:00:00

rawDescription: Python - how do calculate the time difference between local and server


rawDescription: Create new numpy array-scalar of flexible dtype


rawDescription: Determine if given class attribute is a property or not, Python object


code: np.where(np.diff(x) > .5)[0]

rawDescription: Splitting lists by short numbers

description: Splitting lists by short numbers


code:
import csv
import os.path

# You already have a list of absolute paths
files = ["/tmp/999/123.tif"]

# csv writer
with open('/tmp/out.csv', 'wb') as out_file:
    csv_writer = csv.writer(out_file, delimiter=',')
    csv_writer.writerow(('DirName','Filename'))
    for f in files:
        csv_writer.writerow((os.path.basename(os.path.dirname(f)),
                             os.path.basename(f)))

rawDescription: Directory Name + File Name to Text File

description: Directory Name + File Name to Text File


code:
Tests
string_lists = [["test11", "test12", "test13"],
                ["test-a", "test-b", "test-c"],
                ["test1", "test1a", "test12"],
                ["testa-1", "testb-1", "testc-1"]]

for string_list in string_lists:
    print(string_list)
    print(find_prefix(string_list))

rawDescription: Find common sub string from the list of strings


code:
def opt_must_contain(info, request):
    opt = info['match'].get('opt')
    return opt in ('opt_a', 'opt_b', 'opt_c')

config.add_route('my_route', '/view_1/{opt}', custom_predicates=[opt_must_contain])

rawDescription: Pyramid: Routing schemas and restraints

description: Pyramid: Routing schemas and restraints


code:
import random

name = ['Hans', 'Peter', 'Eliza']
print('Your name is ' + random.choice(name) + '!')

rawDescription: How to save a random string from a list of strings?

description: Save a random string from a list of strings


code:
class YourModelResource(ModelResource):
    class Meta:
        queryset = YourModel.objects.all()
        resource_name = 'your_model'

    def prepend_urls(self):
        return [
            url(r"^(?P<resource_name>%s)/do_some_work%s$" % (self._meta.resource_name, trailing_slash()), self.wrap_view('do_some_work'), name="api_do_some_work"),
        ]

    def do_some_work(self, request, **kwargs):
        self.method_check(request, allowed=['post'])
        self.is_authenticated(request)

        #Call the script and get the results
        results = []

        result_list = {
            'results': results,
        }

        return self.create_response(request, result_list)

rawDescription: django-tastypie usage without model

description: Django-tastypie usage without model


code: ('http://somlink.com/section/name-here', 'http://www.somlink.com/thumb/imgsection/thumbnail.jpg', u'name here', u'99:99')

rawDescription: xbmc/kodi python scrap data using BeautifulSoup

description: Xbmc/kodi python scrap data using BeautifulSoup


code:
{'category': u'Just for fun',
 'description': "Graffiti lets you draw on your friends' profiles.",
 'id': '2439131959',
 'name': 'Graffiti'}

rawDescription: Facebook Graph API and Django

description: Facebook Graph API and Django


code:
from time import time

start = time()

# code to be timed

finish = time()
print(finish - start)

rawDescription: Python loop speed sources

description: Python loop speed sources


code:
gb = df.groupby('Key')
df['C1+C2'] = gb['C1'].transform(np.sum) + gb['C2'].transform(np.sum)

rawDescription: Pandas: conditional group-specific computations


code:
import email.mime, email.mime.nonmultipart, email.charset
m=email.mime.nonmultipart.MIMENonMultipart('text', 'plain', charset='utf-8')

#Construct a new charset which uses Quoted Printables (base64 is default)
cs=email.charset.Charset('utf-8')
cs.body_encoding = email.charset.QP

#Now set the content using the new charset
m.set_payload(u'This is the text containing ünicöde', charset=cs)

rawDescription: Encode MIMEText as quoted printables

description: Encode MIMEText as quoted printables


code: [name[:-4] if name.endswith('_new') else name for name in list_of_names]

rawDescription: removing a pattern from a list items in python

description: Removing a pattern from a list items in python


code:
class AutoServer(Server):
    def __init__(self):
        Server.__init__(self)
        self.start_listening()

rawDescription: Call method just after object creation

description: Call method just after object creation


code:
from collections import Counter

advk = Counter(['a','a','r','d','v','a','r','k'])

with open('input.txt', 'rU') as file:
    for i, line in enumerate(file.readlines()):
        if not advk - Counter(line.lower()):
            print ("Aardvark on line " + str(i+1))

rawDescription: Testing all Letters?

description: Testing all Letters


code: struct.pack("Bbh", 0, 1, 7)

rawDescription: How to send packets in a Minecraft Classic server written in Python

description: Send packets in a Minecraft Classic server written in Python


code:
import matplotlib.pyplot as plt

def formatter(x, y):
    return '{:0.0f} rainbows, {:0.0f} unicorns'.format(10*x, 10*y)

fig, ax = plt.subplots()
ax.format_coord = formatter
plt.show()

rawDescription: Matplotlib : Default Resolution of Plot Mouse-over Values


code:
input_to_chars = {
    'lowercase': lowercase,
    'uppercase': uppercase,
    'digits': digits,
    'punctuation': punctuation
}

rawDescription: Getting function as string then run it

description: Getting function as string then run it


rawDescription: Computing total_seconds in Python for datetime module with true division enabled


rawDescription: Getting chrome performance and tracing logs


rawDescription: Strip special characters and punctuation from a unicode string


rawDescription: python matplotlib save plot

description: Python matplotlib save plot


code:
import pandas as pd
names = '''\
John Snow
Black, Jack
Jim Bean/
Draper, Don
'''
df = pd.DataFrame({'Name': names.splitlines()})
#           Name
# 0    John Snow
# 1  Black, Jack
# 2    Jim Bean/
# 3  Draper, Don

df['Name'] = df['Name'].str.replace(r'(.+),\s+(.+)', r'\2 \1')

rawDescription: Reversing names in pandas

description: Reversing names in pandas


code: os.system("python {0} {1} {2}".format(code, input_file, output_file)) # Python 2.x

rawDescription: passing variable defined as files to os.system()

description: Passing variable defined as files to os.system()


code:
env.command_prefixes=["export myvar='Hello world'",]
def echo_env():
    run(r"echo $myvar")

rawDescription: Fabric set environment variable globally


code:
im1 = im.astype('u2')
im2 = im.astype('u2')
tmp = im1 + im2
result = tmp.clip(0,255).astype('u1')

rawDescription: Difference in adding two images in numpy and opencv


code:
try:
    productToUpdate = session.query(Product).filter(Product.name == "my-tshirt", Product.quantity > 0).with_for_update().one() #assume Product.name is unique and name exists
except sqlalchemy.orm.exc.NoResultFound as e:
    return "No reservations available" #Handle no reservation case here
productToUpdate.quantity -= 1
newReservation = Reservation()
newReservation.product = productToUpdate #assume relationship setup
newReservation.user = userForReservation #assume relationship setup
session.commit()

rawDescription: How can I limit rows and prevent race conditions for a reservation system

description: Limit rows and prevent race conditions for a reservation system


rawDescription: Matplotlib matshow with many string labels


code:
import requests
import BeautifulSoup

r = requests.get('http://example.com')
html = r.content
soup = BeautifulSoup(html)
table = soup.find("table", {"id": "targettable"})

rawDescription: urllib keeps freezing while trying to pull HTML data from a website - is my code correct?

description: Urllib keeps freezing while trying to pull HTML data from a website - is my code correct


rawDescription: Using Xpath in Scrapy to select any text below paragraph


rawDescription: Python dict as local, not reference

description: Python dict as local, not reference


code:
from io import StringIO
from unittest.mock import patch
import unittest, importlib, sys, os
from time import sleep

# setup the environment
backup = sys.stderr

class TestTypingExercise(unittest.TestCase):
    def __init__(self, test_name, filename, inputs):
        super(TestTypingExercise, self).__init__(test_name)
        self.library = filename.split('.')[0]
        self.inputs = inputs

    def setUp(self):
        sys.stdin = StringIO(self.inputs[0])
        try:
            ## Stores output from print() in fakeOutput
            with patch('sys.stdout', new=StringIO()) as self.fakeOutput:
                ## Loads submission on first test, reloads on subsequent tests
                if self.library in sys.modules:
                    importlib.reload(sys.modules[ self.library ] )
                else:
                    importlib.import_module( self.library )
        except Exception as e:
            self.fail("Failed to Load - {0}".format(str(e)))

    ## Test Cases
    def test_code_runs(self):
        test_case = "Checking to See if code can run"
        self.assertTrue(True, msg=test_case)

    def test_says_hello(self):
        test_case = "Checking to See if code said 'Hi Adam'"
        # Regex might be cleaner, but this typically solves most cases
        self.output = self.fakeOutput.getvalue().strip().lower()
        self.assertTrue('hi adam' in self.output, msg=test_case)

if __name__ == '__main__':
    ignore_list = ["grader.py"]

    # Run Through Each Submitted File
    directory = os.listdir('.')
    for filename in sorted(directory):
        if (filename.split('.')[-1] != 'py') or (filename in ignore_list):
            continue
        #print("*"*15, filename, "*"*15)

        # 'Disables' stderr, so I don't have to see all their errors
        sys.stderr = StringIO()     # capture output

        # Run Tests Across Student's Submission
        suite = unittest.TestSuite()
        suite.addTest(TestTypingExercise('test_code_runs', filename, 'Adam'))
        suite.addTest(TestTypingExercise('test_says_hello', filename, 'Adam'))
        results = unittest.TextTestRunner().run(suite)

        # Reset stderr
        out = sys.stderr.getvalue() # release output
        sys.stderr.close()  # close the stream
        sys.stderr = backup # restore original stderr

        # Display Test Results
        print(filename,"Test Results - ", end='')
        if not results.wasSuccessful():
            print("Failed (test cases that failed):")
            for error in results.failures:
                print('\t',error[1].split('\n')[-2])
        else:
            print("Pass!")
        sleep(0.05)

rawDescription: Is this a proper way to test stdout with Python 3 unittest?


rawDescription: Replace a pattern in CSV file Python

description: Replace a pattern in CSV file Python


code:
class FTPConnector:
    def __init__(self, params):
        self.params = params
    def __enter__(self):
        for user, passw, host in params:
            try:
                # import pdb;pdb.set_trace()  # not sure what you want to do with that...
                self.h_context = FTPHost(host, user, passw)
                return self.h_context.__enter__()
            except FTPError as e:
                logger.debug("Can't connect to ftp error is {}".format(e))
        else:
            raise Exception(
                "Can't connect to ftp server with none of the {}".format(params)
            )
    def __exit__(self, exc_type, exc_value, traceback):
        return self.h_context.__exit(exc_type, exc_value, traceback)

rawDescription: How to return from with statement?

description: Return from with statement


rawDescription: List a specific position in each list within a list (python)


code:
def only_even_elements(l):
    """ (list of int) -> bool

    Return a whether a list contains only even integers.

    >>> only_even_elements([1, 2, 4])  # 1 is not even
    False
    """
    for e in l:
        if e % 2 == 1:
            return False
    return True

def get_even_lists(lst):
    """ (list of list of int) -> list of list of int

    Return a list of the lists in lst that contain only even integers.

    >>> only_evens([[1, 2, 4], [4, 0, 6], [22, 4, 3], [2]])
    [[4, 0, 6], [2]]
    """
    # return [l for l in lst if only_even_elements(l)]
    even_lists = []
    for sublist in lst:
        if only_even_elements(sublist):
            even_lists.append(sublist)
    return even_lists

rawDescription: How to get only even numbers from list

description: Get only even numbers from list


code: cur.execute('SELECT Savings, Chequing FROM Accounts WHERE Number == (?)', [number])

rawDescription: Calling to a database in Python

description: Calling to a database in Python


code:
from lxml import etree
t = etree.XML(
"""<?xml version="1.0" encoding="UTF-8"?>
<review>
  <title>Some testing stuff</title>
  <text>Some text with <extradata>data</extradata> in it.</text>
</review>"""
)
(t.text + ''.join(map(etree.tostring, t))).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:
import math
def make_cylinder_volume_func(r):
    def volume(h):
        return math.pi * r * r * h
    return volume

rawDescription: How do I write a function that returns another function?

description: Write a function that returns another function


code:
def analyse_sentence():
   sentence = input("Please enter your sentence")
   unique_words =  list(set(sentence.lower().split(' ')))
   print('sentence : %s' % sentence)
   print('unique words : %s' % ','.join(unique_words))
   return unique_words

rawDescription: How to strip capital letters and then put them back in again in the same place?

description: Strip capital letters and then put them back in again in the same place


code:
for index, test in enumerate(h3s.select("h3")):
    print("Feature title: ", test.text)
    ul = h3s.select("ul")[index]
    print(ul.get_text(' ', strip=True))

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


code:
class UnicodeRedis(redis.Redis):

    def __init__(self, *args, **kwargs):
        if "encoding" in kwargs:
            self.encoding = kwargs["encoding"]
        else:
            self.encoding = "utf-8"
        super(UnicodeRedis, self).__init__(*args, **kwargs)

    def get(self, *args, **kwargs):
        result = super(UnicodeRedis, self).get(*args, **kwargs)
        if isinstance(result, str):
            return result.decode(encoding)
        else:
            return result

rawDescription: Distinction between str and unicode: why Redis returns binary data when passed unicode?


code:
result = defaultdict(float)
with open('filename') as f:

   def lineValue(line):
     parts = line.split('\t')
     return float(parts[5]) * float(parts[6])

   def lineKey(line):
     parts = line.split('\t')
     return parts[0]

   for line in f:
     if "Fam" in line and "TK" in line:
       result[lineKey(line)] += lineValue(line)

rawDescription: Using temp memory for smart calculating

description: Using temp memory for smart calculating


code:
def paths(d, path=(), res=None):
    if res is None:
        res = []
    for key, value in d.iteritems():
        if not value:
            # end of the line, produce path
            res.append(','.join(path + (key,)))
        else:
            # recurse down to find the end of this path
            paths(value, path + (key,), res)
    return res

rawDescription: Recurse through dictionary of dictionaries, always starting from the top


code: print(new)

rawDescription: Python to combine lines in a txt file

description: Python to combine lines in a txt file


code:
nums = [int(input("Enter Numbers ")) for _ in range(6)]
print([x for x in nums if x > mean(nums)])

rawDescription: How to display numbers greater than the mean in a list?

description: Display numbers greater than the mean in a list


code:
diffs.mean() # this is in nanoseconds
diffs.std()

rawDescription: Calcuate Duration and Average of CSV file data using python


code:
start_list = [5, 3, 1, 2, 4]
b = [x**2 for x in start_list]

rawDescription: Square a list (or array?) of numbers in Python


code:
list_of_dataframes[0].to_csv(...)  # write first, using headers..  assumes list isn't empty!
for df in list_of_dataframes[1:]:
    df.to_csv(..., header=False, mode='a')

rawDescription: Python: Export a matrix in csv

description: Python: Export a matrix in csv


code:
def decode(text, shift):
    d = {}
    for i in range(26):
        d[chr(i+97)] = chr((i+shift) % 26 + 97)
    return "".join([d.get(c, c) for c in text])

rawDescription: Efficient Translation Function without using maketrans()


code: df['LastDayWeek'] = pd.to_datetime((df['Week']-1).astype(str) + "6", format="%Y%U%w")

rawDescription: python dataframe convert week number to month

description: Python dataframe convert week number to month


code:
from dateutil import parser
date = 'Wed Jun  4 19:01:58 CDT 2014'
parser.parse(date)

rawDescription: How to ssh with paramiko when prompted for password?

description: Ssh with paramiko when prompted for password


rawDescription: Python script freezes for no apparent reason (afaik)


code: result = A*b[:, np.newaxis]

rawDescription: np.tile to repeat an 1D array

description: Np.tile to repeat an 1D array


rawDescription: How to print a MySQLdb unicode result in human readable way

description: Print a MySQLdb unicode result in human readable way


code:
n = Decimal('0.1239')
plus(n)

rawDescription: How to plus one at the tail to a float number in Python?

description: Plus one at the tail to a float number in Python


code: ['asda', 'asda1', 'test', 'ada', 'test1', 'yuil', 'test2']

rawDescription: vectorizing a for loop in python

description: Vectorizing a for loop in python


code: newline = " ".join(spl)

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


code:
# parameters
start_id = session.query(Room).filter(Room.name == 'A').first().id
max_level = 2

# CTE definition
starting_exits = (session.query(Exit, literal(0).label("level"))
    .filter(Exit.src == start_id)
    .cte(name="starting_exits", recursive=True)
)
start = aliased(starting_exits, name="st")

exit = aliased(Exit, name="e")
joined = (session.query(exit, (start.c.level + 1).label("level"))
    .filter(exit.src == start.c.dst)
    # @note: below line will avoid simple cycles of 2, which does not always help, but should reduce the result-set significantly already
    .filter(exit.dst != start.c.src)
    .filter(start.c.level < max_level)
)

cte = start.union_all(joined)
for x in session.query(cte).order_by(cte.c.src, cte.c.dst, cte.c.level):
    print(x)

rawDescription: Recursively select (with limited depth) relationships in SQLAlchemy using ORM, declarative style, and Association objects


code:
f = urllib.urlopen("http://SOMEWHERE")
soup = BeautifulSoup(f)

rawDescription: Using urllib and BeautifulSoup to retrieve info from web with Python


code:
from scipy.interpolate import interp2d
from numpy.random import rand

b = BlochDensity()
b.sphere_alpha=0.5

thetas, phis = linspace(-pi,pi,10), linspace(0,pi,10)
density = rand(len(thetas), len(phis))

#scale density to a maximum of 1
density /= density.max()

interpolated_density = interp2d(thetas, phis, density)

def f(theta, phi):
  return hsv_to_rgb(interpolated_density(theta,phi), 1, 1)

b.density = f

b.show()

b.density = f

b.show()

rawDescription: density plot on a sphere Python

description: Density plot on a sphere Python


code:
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import itertools as IT

def points_on_sphere(dim, N, norm=np.random.normal):
    """
    http://en.wikipedia.org/wiki/N-sphere#Generating_random_points
    """
    normal_deviates = norm(size=(N, dim))
    radius = np.sqrt((normal_deviates ** 2).sum(axis=0))
    points = normal_deviates / radius
    return points

# Number of hyperplanes
n = 10
# Dimension of space
d = 3

fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
points = points_on_sphere(n, d).T
uu, vv = np.meshgrid([-5, 5], [-5, 5], sparse=True)
colors = np.linspace(0, 1, len(points))
cmap = plt.get_cmap('jet')
for nhat, c in IT.izip(points, colors):
    u = (0, 1, 0) if np.allclose(nhat, (1, 0, 0)) else np.cross(nhat, (1, 0, 0))
    u /= math.sqrt((u ** 2).sum())
    v = np.cross(nhat, u)
    u = u[:, np.newaxis, np.newaxis]
    v = v[:, np.newaxis, np.newaxis]
    xx, yy, zz = u * uu + v * vv
    ax.plot_surface(xx, yy, zz, alpha=0.5, color=cmap(c))
ax.set_xlim3d([-5,5])
ax.set_ylim3d([-5,5])
ax.set_zlim3d([-5,5])
plt.show()

rawDescription: How to draw random planes

description: Draw random planes


code:
global_board = createBoard(3,3,4)
print(global_board)

rawDescription: list assignment index out of range (creating a minesweeper board)

description: List assignment index out of range (creating a minesweeper board)


code:
@app.route("/user", methods=("POST",))
def save_user():
    data = request.get_json()
    # ... etc. ...

rawDescription: Getting Form data with Flask

description: Getting Form data with Flask


code:
if request.method == 'POST':
    sign_up = up_form(request.POST)
    if sign_up.is_valid():
        sign_up = sign_up.save(commit = False)
        sign_up.password = make_password(sign_up.cleaned_data['password'])

rawDescription: Saving Hashed Version of User Password in Django Form Not Working


code:
class MyThing():
  def __init__(self, ode, y0):
    self.ode = integrate.ode(ode)  # define the ODE
    self.ode.set_integrator("dopri5")  # choose an integrator
    self.ode.set_initial_value(y0)

  def update(self, u, t_step):
    """Update the ODE step-wise."""

    self.ode.set_f_params(u)  # need to pass extra parameters with this method
    self.ode.integrate(self.ode.t + t_step)  # step-wise update
    return self.ode.successful()

  def get_output(self):
    """Get output from ODE function."""

    return self.ode.y

rawDescription: Passing parameterized function handle in Python


code:
# Argument for default thread pool executor creation.
_MAX_WORKERS = 5

rawDescription: Why is the asyncio library slower than threads for this I/O-bound operation?


code:
def sct(from_date=None):
    if from_date is None:
        from_date = datetime.datetime.now().date()
    value = getValueByDate(from_date)

rawDescription: datetime.datetime.now() returns old value

description: Datetime.datetime.now() returns old value


code: (first_byte, second_byte, the_short) = unpack("cc!h", data)

rawDescription: python proper way to decode raw udp packet

description: Python proper way to decode raw udp packet


code:
class MyJSONDecoder(json.JSONDecoder):
    def __init__(self, encoding=None, object_hook=None, parse_float=None,
            parse_int=None, parse_constant=None, strict=True,
            object_pairs_hook=None):

        json.JSONDecoder.__init__(self, encoding, object_hook, parse_float, parse_int, parse_constant, strict, object_pairs_hook)

        # override scanner
        self.scan_once = make_my_scanner(self)

rawDescription: Python JSONDecoder custom translation of null type


code:
subseq
max(subseq, key=len)

rawDescription: How to find longest consistent increment in a python list?

description: Find longest consistent increment in a python list


code:
resultA = unwrap(method_A())
resultB = unwrap(method_B())

rawDescription: How to remove extra list from the result in python

description: Remove extra list from the result in python


code:
import pandas as pd

# get your data into pandas
data = '''
item_list     group_list
A             1
B             1
C             2
D             1
E             2
F             1
G             2
H             2
I             1
J             2'''
from StringIO import StringIO # import from io for python 3
df = pd.read_csv(StringIO(data), sep=r'\s+', index_col=None, header=0)

# use a dictionary comprehension to compile the collection of lists
lists = {x: df[df['group_list'] == x].item_list.tolist()
    for x in df['group_list'].unique()}

rawDescription: Dynamically creating lists in Python

description: Dynamically creating lists in Python


code: pd.pivot_table(df, index='location', columns='year', values='cost', fill_value=0)

rawDescription: Rearranging Data in Python/Pandas: Turn specific column vlaues into headers


rawDescription: How to set lower triangular matrix of 0-1?

description: Set lower triangular matrix of 0-1


code:
timeit('list(f(mylist))', 'from __main__ import set_test as f, mylist', number=10)
timeit('list(f(mylist))', 'from __main__ import create_combos as f, mylist', number=10)

rawDescription: How do I find out if a combination of numbers are in another combination of numbers?

description: Find out if a combination of numbers are in another combination of numbers


code:
result = min((min((v, c) for c, v in enumerate(row)), r) for r, row in enumerate(e))
return result[1], result[0][1]

rawDescription: Find the row and column with the min value in python?


rawDescription: Sort paragraphs in a text file alphabetically using Python


code: out = [sum(i) for i in zip(*lst)]

rawDescription: Reduce list based on index

description: Reduce list based on index


code:
from itertools import product

for combo in product(*map(set, zip(good, bad))):
    print(combo)

rawDescription: all combinations of differences of two lists

description: All combinations of differences of two lists


code: contains(s, sub)

rawDescription: Error: name 's' is not defined

description: Error: name 's' is not defined


code:
from Tkinter import Label, Tk
root = Tk()
prompt = 'hello'
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def close_after_2s():
    root.destroy()

root.after(2000, close_after_2s)
root.mainloop()

rawDescription: How to launch a Python/Tkinter dialog box that self-destructs?

description: Launch a Python/Tkinter dialog box that self-destructs


code:
values = [1, 2, 3, 4]
for leaf, value in zip(leaves(g), values):
    leaf.value = value

rawDescription: Mapping a list of inputs to the lowest level of nested lists


code: list(chain.from_iterable(repeat(Counter(x).most_common(1)[0][0],5) for x in grouper(s,5)))

rawDescription: What filter do I need? Want to keep high frequency values only


code: population = range(10)

rawDescription: randomly choose from list using random.randint in python

description: Randomly choose from list using random.randint in python


code:
curX = self.canvas.canvasx(event.x)
curY = self.canvas.canvasy(event.y)

rawDescription: Tkinter: Draw rectangle using a mouse

description: Tkinter: Draw rectangle using a mouse


rawDescription: Regex scientific notation

description: Regex scientific notation


code:
for index, (first, second) in enumerate(zip(list1, list2)):
    if first != second:
        print(index, second)

rawDescription: comparing two lists and finding indices of changes

description: Comparing two lists and finding indices of changes


rawDescription: add only specific colums in array - python

description: Add only specific colums in array - python


code:
myform.fields['status'].widget.attrs['readonly'] = True # text input
myform.fields['status'].widget.attrs['disabled'] = True # radio / checkbox

rawDescription: How can I disable a model field in a django form

description: Disable a model field in a django form


code: Tk.attributes("-fullscreen", True)

rawDescription: Python full-screen graphics

description: Python full-screen graphics


code:
from django import template
from cms.models.pagemodel import Page

register = template.Library()

def cms_navigation():
    cms_pages = Page.objects.filter(in_navigation=True, published=True)
    return {'cms_pages': cms_pages}

register.inclusion_tag('main-navigation.html')(cms_navigation)

rawDescription: How do I access all page objects in django-cms from every page?

description: Access all page objects in django-cms from every page


code:
import requests
from concurrent.futures import ThreadPoolExecutor

NUM_OF_WORKERS=32

def check(username):
    try:
        req = requests.get("http://kik.me/"+username, allow_redirects=False).status_code

        if req == 302:
            print(username, " does not exist.")
        if req == 200:
            print(username, "exists.")
    except Exception as error:
        print(error)

usernames = _loadList(filename)

with ThreadPoolExecutor(max_workers=NUM_OF_WORKERS) as pool:
    pool.map(check, usernames)

rawDescription: Any possible way to speed up the processing of this?


rawDescription: A pythonic way to remove all instances of an element without generating a new list


code:
from pprint import pprint
from urllib2 import urlopen

from bs4 import BeautifulSoup

html = urlopen("http://www.gbgb.org.uk/resultsMeeting.aspx?id=135754")
soup = BeautifulSoup(html, 'lxml')

rows = []
for header in soup.find_all("div", class_="resultsBlockHeader"):
    track = header.find("div", class_="track").get_text(strip=True)

    results = header.find_next_sibling("div", class_="resultsBlock").find_all("ul", class_="line1")
    for result in results:
        greyhound = result.find("li", class_="greyhound").get_text(strip=True)

        rows.append({
            "track": track,
            "greyhound": greyhound
        })

pprint(rows)

rawDescription: Displaying contents of web scrape

description: Displaying contents of web scrape


code:
class FooView(BrowserPage):
    index = ViewPageTemplateFile('foo.pt')
    def __call__(self):
        self.update()
        return self.index()

    def update(self):
        self.portal_catalog = ...  # initialize code

rawDescription: What is the difference between template in ZCML and ViewPageTemplateFile


code: encrypt = 'd' if raw_input("Encrypt or decrypt a file (E/d):").lower() == 'd' else 'e'

rawDescription: Python Input validation

description: Python Input validation


code:
return {
        'type': 'ir.actions.report.xml',
        'report_name': 'my_report',
        'datas': datas,
        'nodestroy': True
    }

rawDescription: Print two report in Odoo8

description: Print two report in Odoo8


code:
def instance_dict(typ, **kwargs):
    for k, v in kwargs.iteritems():
        kwargs[k] = typ(*v)
    return kwargs

# later...
self.bot = servo.Robot(
               instance_dict(servo.Servo,
                   waist = (3, 90, .02, 0),
                   shoulder = (4, 130, .03, 15),
                   elbow = (5, 110, .02, 19),
                   wrist = (6, 20, .01, 9),
                   claw = (7, 40, .01, 0) ),
               [5, 15, 25])

rawDescription: Preferred way to format a dictionary being passed to a function?


code:
keylambda = lambda s: str.lower(s[2])
sortedList = sorted(strLst, key=keylambda)

rawDescription: How to alphabetize a column?

description: Alphabetize a column


code: binned_statistic_dd([np.ones(10), np.ones(10)], None, 'count', bins=3, range=[[2,3],[0,0.5]])

description: Output in scipy.stats.binned_statistic_dd()


code:
import numpy as np

def rolling_window(a, window):
    # http://www.mail-archive.com/numpy-discussion@scipy.org/msg29450.html
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

def circular_rolling_window(a, window):
    pseudocircular = np.pad(a, pad_width=(0, windowsize-1), mode='wrap')
    return rolling_window(pseudocircular, windowsize)

a = np.arange(5)
windowsize = 3
print(circular_rolling_window(a, windowsize))

rawDescription: Rolling window on a circular array

description: Rolling window on a circular array


code:
from matplotlib import path
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
p.contains_points([(.5, .5)])

rawDescription: inpolygon for Python - Examples of matplotlib.path.Path contains_points() method?

description: Inpolygon for Python - Examples of matplotlib.path.Path contains_points() method


code: _conv_table = [_bin(x,8) for x in range(256)]

rawDescription: Base-2 (Binary) Representation Using Python


code:
def grouper(line):
    return line.startswith('>') and line[1:]

def itersplit(it, pred):
    groups = (list(group) for key, group in itertools.groupby(it, pred))
    yield from zip(groups, groups)

def parse(file):
    for key, group in itersplit(file, grouper):
        yield key[0], ''.join(group)

rawDescription: Rewind File Pointer to Previous Line Python File IO


code:
import decimal

def drem(x, y):
    xd = decimal.Decimal(x)
    yd = decimal.Decimal(y)

    return float(xd.remainder_near(yd))

rawDescription: How can I simulate GNU C Library drem / remainder function in Google App Engine Python 2.7 runtime?

description: Simulate GNU C Library drem / remainder function in Google App Engine Python 2.7 runtime


code:
def main():
    sound = get_sound()
    key = find_key()
    make_video(*sound, key)

rawDescription: How to assign values returned from a function to another function

description: Assign values returned from a function to another function


code:
"""
Hello
.
1-methyl-4-phenylpyridinium
is
ultra-bad
.
However
,
1-methyl-4-phenyl-1,2,3,6-tetrahydropyridine
is
worse
.
"""

rawDescription: Python: question about parsing human-readable text


code:
def joke1():
    #Execute joke 1
    pass

def joke2():
    #Execute joke 1
    pass

joke_list = [joke1, joke2] #list of functions
import random
joke = random.choice(joke_list)
joke() #execute the selected joke, which is a function

rawDescription: How to choose a random interaction with user input in Python?

description: Choose a random interaction with user input in Python


code:
@delegate
def intfactory(num):
    return int(num)

rawDescription: What's the preferred way to implement a hook or callback in Python?


code:
def x():
   def y():
      pass

x
x.y

rawDescription: How to autodoc a function inside a method in Sphinx

description: Autodoc a function inside a method in Sphinx


code: overall_cost = tf.mul(cost, x_weights) / batch_size

rawDescription: How to use event-by-event weights in Tensorflow?

description: Use event-by-event weights in Tensorflow


code:
X1=np.zeros(1,dtype=type2)
X2=np.zeros(1,dtype=desired_type)
X1.itemsize
X2.itemsize

rawDescription: Best Way to Resize Numpy Dtype for Structured data


code:
'
One 2- to 3-pound farm-raised chicken
\n'
'
Kosher salt and freshly ground black pepper
\n'
'
2 teaspoons minced thyme (optional)
\n'
'
Unsalted butter
\n'
'
Dijon mustard
\n'

'
Kosher salt and freshly ground black pepper
\n'
'
2 teaspoons minced thyme (optional)
\n'
'
Unsalted butter
\n'
'
Dijon mustard
\n'

"
One 2- to 3-pound farm-raised \nchicken
\n"
'
Kosher salt and freshly ground black pepper
\n'
'
2 teaspoons minced thyme (optional)
\n'
'
Unsalted butter
\n'
'
Dijon mustard
\n'

rawDescription: Python HTML parsing specific information within tags


code:
#Load and initialize Modules here
import pygame
pygame.init()

#Window Information
displayw = 800
displayh = 600
window = pygame.display.set_mode((displayw,displayh))

#Clock
windowclock = pygame.time.Clock()

#Load other things such as images and sound files here
image = pygame.image.load("foo.png").convert #Use conver_alpha() for images with transparency

#Main Class
class MainRun(object):
    def __init__(self,displayw,displayh):
        self.dw = displayw
        self.dh = displayh
        self.Main()

    def Main(self):
        #Put all variables up here
        stopped = False

        while stopped == False:
            window.fill((255,255,255)) #Tuple for filling display... Current is white

            #Event Tasking
            #Add all your event tasking things here
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()
                elif event.type == pygame.KEYDOWN:
                    stopped = True

            #Add things like player updates here
            #Also things like score updates or drawing additional items
            #Remember things on top get done first so they will update in the order yours is set at

            #Remember to update your clock and display at the end
            pygame.display.update()
            windowclock.tick(60)

        #If you need to reset variables here
        #This includes things like score resets

    #After your main loop throw in extra things such as a main menu or a pause menu
    #Make sure you throw them in your main loop somewhere where they can be activated by the user

#All player classes and object classes should be made outside of the main class and called inside the class
#The end of your code should look something like this
if __name__ == __main__:
    MainRun()

rawDescription: Using classes in Pygame

description: Using classes in Pygame


code:
from django.utils.decorators import method_decorator
from contextlib import contextmanager

def ExtendedTestCase(TestCase):

    @method_decorator(context_manager)
    def assertDifference(self, func, diff, message=None):
        " A Context Manager that performs an assert. "
        old_value = func()
        yield # `with` statement runs here. Roughly equivalent to ruby's blocks
        new_value = func()
        self.assertEqual(new_value-old_value, diff, message)

def ArticleTestCase(ExtendedTestCase):

    def test_article_creation(self):
        " Test that new articles can be created "
        with self.assertDifference(Article.count, 1):
             self.client.post("/article/new/", {
                 "title": "My First Django Article",
                 "content": "Boring Technical Content",
             })

rawDescription: Python / Django - is there an assertion similar to Rails' assert_difference?


rawDescription: convert a list to matrix in python

description: Convert a list to matrix in python


code:
from lxml import etree
data = """

Title One

40.531.3

Title Two

12.182.0

"""
d = etree.HTML(data)
d.xpath('//h1/following-sibling::p[1]/a/text()')

rawDescription: Regex matching items following a header in HTML


code:
def computeMatXGradient(img):
    rows, cols = img.shape
    out = np.zeros((rows,cols))
    for y in range(rows):
        Mr = img[y]
        Or = out[y]
        Or[0] = float(Mr[1]) - float(Mr[0])
        for x in xrange(1, cols - 1):
            Or[x] = (float(Mr[x+1]) - float(Mr[x-1]))/2.0
        Or[cols-1] = float(Mr[cols-1]) - float(Mr[cols-2])
    return out

rawDescription: Implementing gradient operator in Python


code:
list(zip(*I))
[arr[j] for j in zip(*I)]

rawDescription: Python 2D NumPy array comprehension

description: Python 2D NumPy array comprehension


code:
import ast

data="""\
{
    "translate_tabs_to_spaces": True,
    "word_wrap": "true",
    "font_face": "Monaco",
    "font_size": 14.0,
    "highlight_line": True,
    "ignored_packages":
    [
        ""
    ],
    "what": '''
            This is python file, not json
            '''
}\
"""

print(ast.literal_eval(data))

rawDescription: Loading settings.py config file into a dict


code:
if re.search(r'^\.|\.$', domain) or re.search(r'\.\.', domain):
    return False
elif re.search(r'\.', domain):
    return True
else:
    return False

rawDescription: Python regex for finding dots in email address


code:
class YourCreateView(CreateView):
    form_class  = YourModelForm

rawDescription: django how to insert a textbox input to sqlite database?

description: Django how to insert a textbox input to sqlite database


code:
return_list = []
for i in bot_list:
    if i in r["bot"]:
        return_list.append(i)
return len(return_list)

rawDescription: python - parse a bot true a list of bots ( bot_list )

description: Python - parse a bot true a list of bots ( bot_list )


code:
#!/usr/bin/env python

import collections

a = collections.OrderedDict([(u'p', [u"""
    "The Exam Room" is a new series in
    which everyday medical questions are answered by physicians and
    professors from the Yale School of Medicine.""",
    u"""In our second episode: Dr. Stephen Strittmatter,
    Vincent Coates Professor of Neurology and director of
    the Adler Memory Clinic in Neurology, explains when
    memory loss can become a problem and what you can do to
    boost your brain power.""",
    collections.OrderedDict([(u'em',
        u'Produced & Hosted by Noah Golden')])])])

rawDescription: Separate text from nested OrderedDict in Python


code:
from collections import defaultdict

collision_list = defaultdict(list)

# ....

# No `if numbers[tiles[int(tile)]] not in collision_list` needed
collision_list[numbers[tiles[int(tile)]]].append(tiles[int(tile)].rect)

rawDescription: Add object to existing value in dictionary


code: rm -rf /path/to/your/folder

rawDescription: Create a batch file which remove folder in my Desktop - mac


code:
def addEmptyColumns(df, colNames):
    exprs = df.columns + ["null as " + colName for colName in colNames]
    return df.selectExpr(*exprs)

def concatTwoDfs(left, right):
    # append columns from right df to left df
    missingColumnsLeft = set(right.columns) - set(left.columns)
    left = addEmptyColumns(left, missingColumnsLeft)

    # append columns from left df to right df
    missingColumnsRight = set(left.columns) - set(right.columns)
    right = addEmptyColumns(right, missingColumnsRight)

    # let's set the same order of columns
    right = right[left.columns]

     # finally, union them
    return left.unionAll(right)

def concat(dfs):
    return reduce(concatTwoDfs, dfs)

rawDescription: Efficiently inferring dataframe schema based on key in pyspark


code:
list_2 = list(list_1) # copy
list_2.reverse()
list_2

rawDescription: Invert position of sublists

description: Invert position of sublists


rawDescription: Python - Pandas - How to mark elements in 1 dataframe with elements from a second dataframe?


code:
from urlparse import urljoin

base_url = response.url
data = [urljoin(base_url, link)
        for link in response.xpath('//*[@id="mw-content-text"]/ul[9]/li/a/@href').extract()]

rawDescription: Get links form wikipedia

description: Get links form wikipedia


code: obj = obj = MyModel.objects.filter(my_integer=77).order_by('-created_ts').first()

rawDescription: How to get the Django model with maximum field value?

description: Get the Django model with maximum field value


code:
try:
    os.remove(filename)
except OSError:
    pass

rawDescription: Most pythonic way to delete a file which may not exist


code:
import collections
import re
output_dicts = collections.defaultdict(dict)

for k, v in mydict.iteritems():
    for pattern, suffix in OutputNameDict.iteritems():
        if re.match(pattern,k):
            output_dicts['mydict' + str(suffix)][k] = v
            break
    else:
        output_dicts['not matched'][k] = v

rawDescription: how to group new dictionaries by using common strings from my dictionary

description: Group new dictionaries by using common strings from my dictionary


code:
QtCore.QObject.connect(self.treeView1 , QtCore.SIGNAL("clicked (const QModelIndex&)") , self.clickedTree1)
QtCore.QObject.connect(self.treeView2 , QtCore.SIGNAL("clicked (const QModelIndex&)") , self.clickedTree2)

rawDescription: PyQt 2 trees and button

description: PyQt 2 trees and button


rawDescription: Adding elements in arrays that fall within a criteria in Python


code:
import numpy as np
arr = np.array([1,2,3,4,5], dtype='float32')
arr**-3 == 1/arr**3

rawDescription: Negative exponent with NumPy array operand


code: np.repeat(yp, np.diff(x))

rawDescription: Python - quick interpolate by left value


code:
for i in range(0,10,2):
  print(i)

rawDescription: How do I loop through a Python list by twos?

description: Loop through a Python list by twos


rawDescription: Most Pythonic Way to Split an Array by Repeating Elements


code: {'section': {'red': '3three'}, 'section2': {'blue': '4four', 'green': '5five'}}

rawDescription: Coding a parser in Python

description: Coding a parser in Python


code:
from __future__ import print_function
import collections
g = (print(x) for x in 'potato')
_ = collections.deque(g, maxlen=0)

rawDescription: To execute a generator

description: To execute a generator


code:
def map_date_to_position(dt, YD):
    """
    Maps the datetime value to a position in the occupancy array
    """
    # the start position is the offset to day 1 in the dt1,year,
    # plus the day of year - 1 for dt1 (day of year is 1-based indexed)
    yr = dt.year
    assert yr in YD[:, 0]  # guard...YD should include all years for this person's dates
    position = YD[YD[:, 0] < yr, 1].sum()  # the sum of the days in year before this year
    position += dt.timetuple().tm_yday - 1
    return position

def map_position_to_date(pos, YD):
    """
    Inverse of map_date_to_position, this maps a position in the
    occupancy array back to a datetime value
    """
    yr_offsets = np.cumsum(YD[:, 1])
    day_offsets = yr_offsets - pos
    idx = np.flatnonzero(day_offsets > 0)[0]
    year = YD[idx, 0]
    day_of_year = pos if idx == 0 else pos - yr_offsets[idx-1]
    # construct datetime as first of year plus day offset in year
    dt = datetime.strptime(str(year), "%Y")
    dt += timedelta(days=int(day_of_year)+1)
    return dt

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


code:
responses_dict = {}
user_input = raw_input(requests_dict['location2'])
responses_dict[user_input] = 'You are in %s' % user_input

rawDescription: Python: How to store a REQUEST for input in a variable?


code:
credentials = [
    ('login1', 'password1'),
    ('login2', 'password2'),
    ('login3', 'password3'),
]

for login, password in credentials:
    the_task.delay(login, password)

rawDescription: Property tied to a task instance in celery


code: df.merge(unique_ids[['id', 'geometry']], how='left', on='id')

rawDescription: Pandas and GeoPandas indexing and slicing


code:
Location,MovieDate,Formatted_Address,Lat,Lng
"Edgebrook Park, Chicago ","Jun-7 A League of Their Own Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA","Jun-9 It's a Mad, Mad, Mad, Mad World Edgebrook Park, 6525 North Hiawatha Avenue, Chicago, IL 60646, USA",41.9998876,-87.7627672

rawDescription: python ordered dict issue

description: Python ordered dict issue


code:
import inspect

def whoami():
    frame = inspect.currentframe()
    return inspect.getframeinfo(frame).function

def foo():
    print(whoami())

foo()

rawDescription: How can get current function name inside that function in python


code: filter(lambda x: x.get('infos', {}).get('spam') == 'eggs', my_json)

rawDescription: Filtering json response with python list comprehension


code:
def parse(self, response):
    sel = scrapy.Selector(response)
    requests = sel.xpath('//div@class="container"]')
    itemlist = []
    for r in requests:
        item = projectItem()
        item['product'] = r.xpath('normalize-space(.//*[@class="productname"])').extract()
        item['price'] = r.xpath('normalize-space(.//*[@class="price"]/text()[1])').extract()
        itemlist.append(item)
    return itemlist

rawDescription: Selecting the text contents in a particular <div> that has another <div> within it using Scrapy and Xpath


code:
DFList = []
for group in df.groupby(df.index.day):
    DFList.append(group[1])

rawDescription: How to split a pandas dataframe or series by day (possibly using an iterator)

description: Split a pandas dataframe or series by day (possibly using an iterator)


code:
iface = 'wlan0'
mac_addr = open('/sys/class/net/%s/address' % iface).read().rstrip()

rawDescription: Python string extraction from Subprocess


code: erlangDict = Suppress('[') + delimitedList( erlangTaggedTuple ) + Suppress(']')

rawDescription: pyparsing: grammar for list of Dictionaries (erlang)

description: Pyparsing: grammar for list of Dictionaries (erlang)


rawDescription: ElementTree findall 'or' operator

description: ElementTree findall 'or' operator


code:
import datetime as DT
import numpy as np
import pandas as pd
np.random.seed(2016)

date_times = pd.date_range(DT.datetime(2012, 4, 5, 8, 0),
                           DT.datetime(2012, 4, 5, 12, 0),
                           freq='1min')
tamb = np.random.sample(date_times.size) * 10.0
radiation = np.random.sample(date_times.size) * 10.0
df = pd.DataFrame(data={'tamb': tamb, 'radiation': radiation},
                  index=date_times)

resampled = df.resample('1H', how={'radiation': np.sum, 'tamb': np.mean})
print(resampled[['radiation', 'tamb']])
#                       radiation      tamb
# 2012-04-05 08:00:00  279.432788  4.549235
# 2012-04-05 09:00:00  310.032188  4.414302
# 2012-04-05 10:00:00  257.504226  5.056613
# 2012-04-05 11:00:00  299.594032  4.652067
# 2012-04-05 12:00:00    8.109946  7.795668

def using_agg(df):
    grouped = df.groupby(pd.TimeGrouper('1H'))
    return pd.DataFrame(
        {'radiation': grouped['radiation'].agg('sum'),
         'tamb': grouped['tamb'].agg('mean'),
         'new_column': grouped['tamb'].agg('count')})

print(using_agg(df))

rawDescription: insert new non-existing column in how= of resample

description: Insert new non-existing column in how= of resample


code:
df['total_fwd_bytes'] = df['m_srcaddr'].apply(lambda x: lookup.ix[x, 'm_fwd_bytes'])
df['total_rev_bytes'] = df['m_srcaddr'].apply(lambda x: lookup.ix[x, 'm_rev_bytes'])

rawDescription: Create New Columns in dataFrame using existing columns in Panda