code:
sorted_values = sorted(the_values, key=lambda x: x[1])   #sort by second column
formatted_lines = (format_row(row) for row in sorted_values[:10])
for line in formatted_lines:
    writer.writerow(line)

#[-10:] -> take last 10 elements, [::-1] reverse the order
other_lines = (format_row(row) for row in sorted_values[-10:][::-1])
for line in other_lines:
    writer.writerow(line)

rawDescription: Python: Concatenating and formatting strings/floats while writing to a csv


code:
import sys
if sys.version < '3':
    def b(x):
        return x
else:
    import codecs
    def b(x):
        return codecs.latin_1_encode(x)[0]

rawDescription: How to define a binary string in Python in a way that works with both py2 and py3?

description: Define a binary string in Python in a way that works with both py2 and py3


code:
live_games_link = driver.find_element_by_link_text("LIVE Games")
live_games_link.click()

rawDescription: Webscrape Flashscore with Python/Selenium


code:
X
y

rawDescription: Correct and most efficient way to pull data in to a pandas data frame for machine learning


code:
def multiRepeats(chars,n,initial = True):
    strings = []
    if len(chars) == 0 or n == 0: return [""]
    c = chars[0]
    rest = chars[1:]
    base = 1 if initial else 0
    for i in range(base,n+1):
        head = c * i
        strings.extend([head + tail for tail in multiRepeats(rest,n-i,False)])
    return strings

def digitRepeats(digitString,n):
    return sorted([int(s) for s in multiRepeats(digitString,n)])

rawDescription: How to generate numbers based on a pattern in python

description: Generate numbers based on a pattern in python


code:
class Example(QtGui.QMainWindow):
    ...

    def stop(self):
        ...
        test2.active = False

rawDescription: how can i stop module in python?

description: Stop module in python


code: self.test = "foo"

rawDescription: python 3: Class function member to modify a class data member

description: Python 3: Class function member to modify a class data member


code: book_list = [(b, (b in favorite_books)) for b in Book.objects.all()]

rawDescription: Complex django query in a many to many relationship


code:
if have_setuptools:
    extra_arguments = dict(
        zip_safe = False,
        test_suite = 'babel.tests.suite',
        tests_require = ['pytz'],

        entry_points = """
        [console_scripts]
        pybabel = babel.messages.frontend:main

        [distutils.commands]
        compile_catalog = babel.messages.frontend:compile_catalog
        extract_messages = babel.messages.frontend:extract_messages
        init_catalog = babel.messages.frontend:init_catalog
        update_catalog = babel.messages.frontend:update_catalog

        [distutils.setup_keywords]
        message_extractors = babel.messages.frontend:check_message_extractors

        [babel.checkers]
        num_plurals = babel.messages.checkers:num_plurals
        python_format = babel.messages.checkers:python_format

        [babel.extractors]
        ignore = babel.messages.extract:extract_nothing
        python = babel.messages.extract:extract_python
        javascript = babel.messages.extract:extract_javascript
        """,
    )

rawDescription: Examples of entry_point usage

description: Examples of entry_point usage


code:
class MyXRange(object):
    def __init__(self, a1, a2=None, step=1):
        if step == 0:
            raise ValueError("arg 3 must not be 0")
        if a2 is None:
            a1, a2 = 0, a1
        if (a2 - a1) % step != 0:
            a2 += step - (a2 - a1) % step
        if cmp(a1, a2) != cmp(0, step):
            a2 = a1
        self.start, self.stop, self.step = a1, a2, step

    def __iter__(self):
        n = self.start
        while cmp(n, self.stop) == cmp(0, self.step):
            yield n
            n += self.step

    def __repr__(self):
        return "MyXRange(%d,%d,%d)" % (self.start, self.stop, self.step)

    # NB: len(self) will convert this to an int, and may fail
    def __len__(self):
        return (self.stop - self.start)//(self.step)

    def __getitem__(self, key):
        if key < 0:
            key = self.__len__() + key
            if key < 0:
                raise IndexError("list index out of range")
            return self[key]
        n = self.start + self.step*key
        if cmp(n, self.stop) != cmp(0, self.step):
            raise IndexError("list index out of range")
        return n

    def __reversed__(self):
        return MyXRange(self.stop-self.step, self.start-self.step, -self.step)

    def __contains__(self, val):
        if val == self.start: return cmp(0, self.step) == cmp(self.start, self.stop)
        if cmp(self.start, val) != cmp(0, self.step): return False
        if cmp(val, self.stop) != cmp(0, self.step): return False
        return (val - self.start) % self.step == 0

rawDescription: `xrange(2**100)` -> OverflowError: long int too large to convert to int


rawDescription: Python Minidom - how to iterate through attributes, and get their name and value


code:
import numpy as np
import pandas as pd
np.where(pd.isnull(df))
df.iloc[2,7]
[df.iloc[i,j] for i,j in zip(*np.where(pd.isnull(df)))]

rawDescription: Find empty or NaN entry in Pandas Dataframe


rawDescription: Django-Tables column templates with django permissions


rawDescription: Text file number to Python number how?

description: Text file number to Python number how


rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
#!python3

import re
import xml.etree.ElementTree as ET

rex = re.compile(r'''(?P<title>Longitude
                       |Latitude
                       |date&time
                       |gsm\s+cell\s+id
                     )
                     \s*:?\s*
                     (?P<value>.*)
                     ''', re.VERBOSE)

root = ET.Element('root')
root.text = '\n'    # newline before the celldata element

with open('cell.txt') as f:
    celldata = ET.SubElement(root, 'celldata')
    celldata.text = '\n'    # newline before the collected element
    celldata.tail = '\n\n'  # empty line after the celldata element
    for line in f:
        # Empty line starts new celldata element (hack style, uggly)
        if line.isspace():
            celldata = ET.SubElement(root, 'celldata')
            celldata.text = '\n'
            celldata.tail = '\n\n'

        # If the line contains the wanted data, process it.
        m = rex.search(line)
        if m:
            # Fix some problems with the title as it will be used
            # as the tag name.
            title = m.group('title')
            title = title.replace('&', '')
            title = title.replace(' ', '')

            e = ET.SubElement(celldata, title.lower())
            e.text = m.group('value')
            e.tail = '\n'

# Display for debugging
ET.dump(root)

# Include the root element to the tree and write the tree
# to the file.
tree = ET.ElementTree(root)
tree.write('cell.xml', encoding='utf-8', xml_declaration=True)

rawDescription: How to convert .txt file into xml file using python?

description: Convert .txt file into xml file using python


code:
if line.find('Chart1_CategoryGroup1 Label=') != -1:
            vulns[pos] = vulns[pos] + 1

rawDescription: Trying to increment a dictionary value based on a variable key


code:
from json import JSONDecoder

def loads_invalid_obj_list(s):
    decoder = JSONDecoder()
    s_len = len(s)

    objs = []
    end = 0
    while end != s_len:
        obj, end = decoder.raw_decode(s, idx=end)
        objs.append(obj)

    return objs

rawDescription: Retrieving JSON objects from a text file (using Python)


code: new_list = old_list[:]

rawDescription: Sign seperating function overwrites passed in list instead of returning new one


code: #!/usr/bin/env python

rawDescription: Invoke scrapy script from PHP/HTML or webserver


code: df = df.rename(columns={'turk.1': 'other_name'})

rawDescription: How do you import a Qualtrics csv file into a pandas dataframe?

description: Import a Qualtrics csv file into a pandas dataframe


code: set([repr(e) for e in [np.array(range(10)), 22]])

rawDescription: Python: Intersection of two lists of lists


code:
def options_view(request):
    foo = request.context
    return {
        'foo': foo,
    }

rawDescription: Pyramid authorization for stored items

description: Pyramid authorization for stored items


code: r = re.compile(r'#[a-z]+<')

rawDescription: python regular expressions in find and replace

description: Python regular expressions in find and replace


code:
wordset_100 = set(worldlist_100)

for row in data_3k:
    word_matches = wordset_100.intersect(row.phrase.split(" "))
    for match in word_matches:
        # add to accumulator
        # this loop will be run less than len(row.phrase.split(' ')) times
        pass

rawDescription: Searching values in a large matrix

description: Searching values in a large matrix


code: repeat(list(simple_gen()), 2)

rawDescription: Chain repetitions of same generator in python


code:
from functools import partial

class MyModelAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj)
        return super(MyModelAdmin, self).get_form(request, obj, **kwargs)

    def formfield_for_dbfield(self, db_field, **kwargs):
        person = kwargs.pop('obj', None)
        formfield = super(MyModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == "car" and person:
            formfield.queryset = Cars.objects.filter(owner=person)
        return formfield

# or its inline
class MyInlineModelAdmin(admin.StackedInline):
    def get_formset(self, request, obj=None, **kwargs):
        kwargs['formfield_callback'] = partial(self.formfield_for_dbfield, request=request, obj=obj)
        return super(MyInlineModelAdmin, self).get_formset(request, obj, **kwargs)

    def formfield_for_dbfield(self, db_field, **kwargs):
        person = kwargs.pop('obj', None)
        formfield = super(MyInlineModelAdmin, self).formfield_for_dbfield(db_field, **kwargs)
        if db_field.name == "car" and person:
            formfield.queryset = Cars.objects.filter(owner=person)
        return formfield

rawDescription: How to get the current model instance from inlineadmin in Django

description: Get the current model instance from inlineadmin in Django


code: timeit('f(cplxarr.real * factarr, cplxarr.imag)',setup='from __main__ import  factarr,cplxarr; import numpy as np; f=np.vectorize(complex)')

rawDescription: Scale the real part of complex numpy array


rawDescription: Get a list of lists of the sets which intersect each other in python


code: John and Greg, Bob and Tim

rawDescription: Is there a way to pair dictionary items?

description: Is there a way to pair dictionary items


code:
def condfunc(myvar):
    if myvar == "single":
        something = "This"
    else:
        something = "That"
    return something

rawDescription: Passing strings to functions

description: Passing strings to functions


code:
from pyspark.mllib.feature import HashingTF, IDF
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import NaiveBayes

training_raw = sc.parallelize([
    {"text": "foo foo foo bar bar protein", "label": 1.0},
    {"text": "foo bar dna for bar", "label": 0.0},
    {"text": "foo bar foo dna foo", "label": 0.0},
    {"text": "bar foo protein foo ", "label": 1.0}])

# Split data into labels and features, transform
# preservesPartitioning is not really required
# since map without partitioner shouldn't trigger repartitiong
labels = training_raw.map(
    lambda doc: doc["label"],  # Standard Python dict access
    preservesPartitioning=True # This is obsolete.
)

tf = HashingTF(numFeatures=100).transform( ## Use much larger number in practice
    training_raw.map(lambda doc: doc["text"].split(),
    preservesPartitioning=True))

idf = IDF().fit(tf)
tfidf = idf.transform(tf)

# Combine using zip
training = labels.zip(tfidf).map(lambda x: LabeledPoint(x[0], x[1]))

# Train and check
model = NaiveBayes.train(training)
labels_and_preds = labels.zip(model.predict(tfidf)).map(
    lambda x: {"actual": x[0], "predicted": float(x[1])})

rawDescription: How to use spark Naive Bayes classifier for text classification with IDF?

description: Use spark Naive Bayes classifier for text classification with IDF


rawDescription: Why does my negative slicing in Python not work?


code:
import sys
for i in range(sys.maxsize**10):  # you could go even higher if you really want
  if thereIsAReasonToBreak(i):
    break

rawDescription: Looping from 1 to infinity in Python

description: Looping from 1 to infinity in Python


code: return (model-data)

rawDescription: Fitting two non-linear models to data

description: Fitting two non-linear models to data


code:
import dis
dis.dis(compile('x in {1, 2, 3}', '<file>', 'exec'))

rawDescription: Should I use 'in' or 'or' in an if statement in Python 3.x to check a variable against multiple values?


code:
class FilterClass(type):
    @classmethod
    def __prepare__(name, bases, **kwds):
        return collections.OrderedDict()

    def __new__(metacls, name, bases, namespace, **kwds):
        result = type.__new__(metacls, name, bases, dict(namespace))
        result._filters = [
            value for value in namespace.values() if hasattr(value, '_filter')]
        return result

rawDescription: How to apply a metaclass to all my class without hardcoding it in the class declaration

description: Apply a metaclass to all my class without hardcoding it in the class declaration


code:
def bar_view(request, foo_id, order):
    my_bar = Bar.objects.get(foo_id=foo_id, foo_order=order)

rawDescription: Multiple database objects with the same ID using unique_together


rawDescription: Python how to update a dictionary with another dictionary by applying add to existing values


code:
idx = a.reset_index().groupby('A')['index'].max()
idx
a.loc[idx]

rawDescription: How to select group's rows having the greatest index

description: Select group's rows having the greatest index


code:
lines = """assign (resid 3 and name H ) (resid 18 and name H ) 2.5 2.5 2.5 ! note string 1
assign (resid 16 and name H ) (resid 5 and name H ) 2.5 2.5 2.5 ! note string 2
assign (resid 42 and name H ) (resid 55 and name H ) 2.5 2.5 2.5 ! note string 3
assign (resid 44 and name H ) (resid 53 and name H ) 2.5 2.5 2.5 ! note string 4
assign (resid 53 and name H ) (resid 44 and name H ) 2.5 2.5 2.5 ! note string 5
assign (resid 53 and name H ) (resid 44 and name H ) 2.5 2.5 2.5 ! note string 6"""

from collections import defaultdict

d = defaultdict(list)
r1 = re.compile(r"(?<=\))\s")
r2 = re.compile(r"\(.*\)")

for line in lines.splitlines():
    key = tuple(r1.split(r2.findall(line)[0]))
    rev_k = tuple(reversed(key))
    if rev_k in d:
        d[rev_k].append(line + " DUPLICATE " + " ".join(line.rsplit(None,4)[1:]))
    elif key in d:
            d[key] += " DUPLICATE " + " ".join(line.rsplit(None,4)[1:])
    else:
        d[key].append(line)

    pp(list(d.values()))

rawDescription: Python Find Duplicate with Note String Preservation


rawDescription: how to use numpy.vectorize or numpy.frompyfunc

description: Use numpy.vectorize or numpy.frompyfunc


code:
import json
from protorpc import protojson
payload = json.dumps({
    'name': 'Dan',
    'fav_food': 'Mac and Cheese',
    'city': 'San Francisco'
})
message = protojson.decode_message(FoodieResponseMessage, payload)
message

rawDescription: Google cloud endpoint RequestMessage with multiple fields resolution


code:
from itertools import chain
def applyfunc(x):
    ch = chain.from_iterable(y.split(',') for y in x.tolist())
    return ','.join(sorted(set(ch)))

df1_new = df1.groupby('Column1')['Column2'].apply(func1).reset_index()

rawDescription: How to compare column values of pandas groupby object and summarize them in a new column row

description: Compare column values of pandas groupby object and summarize them in a new column row


code: triple1pwm = [int(x*100/255) for x in triple1]

rawDescription: Python: How to convert a rgb or hex value to single color values


code:
for key, item in d.items():
    name = item[item.find("__")+2:item.rfind("__")]
    year = item[item.find("*")+1:item.rfind("*")]
    cat = item[item.rfind("*")+1:]

    fileName = getIncrementedFileName(cat + '_' + year + '.xml')
    os.rename(name, fileName)

rawDescription: Python : Rename files

description: Python : Rename files


code:
import gtk

class PyGtkWidgetDockExample:
    def __init__(self):
        self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        self.window.set_default_size(100, gtk.gdk.screen_height())
        self.window.move(gtk.gdk.screen_width()-100, 0)
        self.window.set_type_hint(gtk.gdk.WINDOW_TYPE_HINT_DOCK)
        self.window.show()
        self.window.window.property_change("_NET_WM_STRUT", "CARDINAL", 32,
            gtk.gdk.PROP_MODE_REPLACE, [0, 100, 0, 0])

app = PyGtkWidgetDockExample()
gtk.main()

rawDescription: Preventing window overlap in GTK

description: Preventing window overlap in GTK


code:
obj = A.__new__(args)
obj.a = "test value"
obj.func1()

rawDescription: Python: best way to test a single method of a class


rawDescription: count elements = "" in tuples inside a list of lists

description: Count elements = "" in tuples inside a list of lists


rawDescription: Python nonogram uniqueness

description: Python nonogram uniqueness


code:
s = aList[0]
if s.endswith('\n'):
    s = s[: -1]
s = aList[1]
if s.endswith('\n'):
    s = s[: -1]
...

rawDescription: Updating list in-place

description: Updating list in-place


code:
def merge(f1,f2,f3):
  with open(f3, "a") as outputFile:

     with open(f1) as usernameFile:
        for line in usernameFile:
           username = line.split(':')[0]
           lastname = line.split(':')[3]
           outputFile.write(username)

        with open(f2) as passwordFile:
           for line in passwordFile:
              lN, password = line.split(':')
              if lN == lastname: outputFile.write(password[1])

merge('file1.txt', 'file2.txt', 'output.txt')

rawDescription: Python - Writing to a new file from another file


code:
def weird_time(current_time,duration):
    start = datetime.strptime(current_time, "%H:%M:%S")
    st_hr, st_min, st_sec = start.hour, start.minute, start.second
    mn, secs = divmod(duration, 60)
    hour, mn = divmod(mn, 60)
    mn, secs = st_min+mn, st_sec+secs
    if secs > 59:
        m, secs = divmod(secs,60)
        mn += m
    if mn > 59:
        h, mn = divmod(mn,60)
        hour += h
    return "{:02}:{:02}:{:02}".format(st_hr+hour, mn, secs)

rawDescription: How to not start the next day with datetime while adding a timedelta?

description: Not start the next day with datetime while adding a timedelta


code:
import re

needles = ['accept','freed','partie','accepta','freeing','party']
haystack = "I am accepting your invitation for the party."

words = re.findall(r'(\w+)', haystack)
results = [(word, key) for key in needles for word in words if key in word]

# Or, the long way

results = []
for key in needles:
    for word in words:
        if key in word:
            results.append((word, key))

for word,key in results:
    print('Found {} {}'.format(word, key))

rawDescription: substring of a string using python?

description: Substring of a string using python


code:
def quantityFunction():
    valid = False
    while not valid:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        for i in quantity:
            try:
                int(i)
                return int(quantity)
            except ValueError:
                print("We didn't recognise that number. Please try again.")
                valid = False
                break

rawDescription: Incorrect Looping and returning of variable


rawDescription: What is the fastest way to do greedy set cover with Pandas?


rawDescription: suppress warnings in rpy2

description: Suppress warnings in rpy2


code:
class MyModel(db.Model):
    my_strings = db.StringListProperty()
    my_ints = db.ListProperty(int)

    def get_data(self):
        return zip(self.my_strings, self.my_ints)

    def set_data(self, data):
        self.my_strings = [element[0] for element in data]
        self.my_ints = [element[1] for element in data]

    data = property(get_data, set_data)

rawDescription: Storing a list of objects in GAE

description: Storing a list of objects in GAE


code:
import xml.etree.ElementTree as ET

source = """replace with the XML in question"""

root = ET.fromstring(source)
keeper_data = ['4294905264']
instances = root.findall('.//DIMENSION/DIMENSION_NODE/DIMENSION_NODE')
removeList = list()
for instance in instances:
    data1 = instance.find('./DVAL/DVAL_ID')
    if data1.attrib.get("ID") not in keeper_data:
        removeList.append(instance)
parent = root.find('.//DIMENSION/DIMENSION_NODE')
for tag in removeList:
    parent.remove(tag)

print(ET.tostring(root))

rawDescription: How do I remove child node from XML in Python?

description: Remove child node from XML in Python


code:
string = 'A','B'
string

rawDescription: Counting occurence within a string Python


code:
def func_you( lambdafunc1, lambdafunc2, lambdafunc3, lambdafunc4):
    return lambda x: lambdafunc1(x) * lambdafunc2(x) * lambdafunc3(x) * lambdafunc4(x)
f = func_you(sum,min,max,sum)
f([1,2])

rawDescription: A function that returns a function (in python)


rawDescription: Python regular expressions not recognizing \number


code:
def get_model(uuid):
    o = MyModel.objects.get(uuid=uuid)
    return xmlrpclib.dumps((o, ), allow_none=True, methodresponse=1)

rawDescription: Output Django Object into XML-RPC response


code: [do_something(item) for item in list if item != 10]

rawDescription: In a for loop, if my iterator satisfies a condition, how can I pass to the next iterator?


code:
process = subprocess.Popen('echo `pwd`', stdout=subprocess.PIPE, shell=True)
out, err = process.communicate()
out

rawDescription: Using back-ticks in Python subprocess

description: Using back-ticks in Python subprocess


rawDescription: How to apply standardization to SVMs in scikit-learn?

description: Apply standardization to SVMs in scikit-learn


code: Z = hierarchy.linkage(ssd.pdist(points), method="average")

rawDescription: Triangle vs. Square distance matrix for Hierarchical Clustering Python?


code: indata = open(from_file).read()

rawDescription: Explicitly closing files in python

description: Explicitly closing files in python


rawDescription: Unique combinations of two lists – comparison at each index position


code:
# Get the name of the parent for the group we want to copy
group_path = fs['/A/B'].parent.name

# Check that this group exists in the destination file; if it doesn't, create it
# This will create the parents too, if they don't exist
group_id = fd.require_group(group_path)

# Copy fs:/A/B/ to fd:/A/G
fs.copy('/A/B', group_id, name="G")

print(fd['/A/G'].keys())
# [u'dataset1', u'dataset2']

rawDescription: How to partially copy using python an Hdf5 file into a new one keeping the same structure?

description: Partially copy using python an Hdf5 file into a new one keeping the same structure


code: df.groupby(df.columns, axis=1).sum()

rawDescription: Merge Columns within a DataFrame that have the Same Name


rawDescription: How to deal with indeterminate form in Python

description: Deal with indeterminate form in Python


code: pp.pprint(r.json()['unis'][0]) # which gave me the first record

rawDescription: Parsing large JSON - Python

description: Parsing large JSON - Python


code:
def OnSelect(self, event, ctrl):
    name, path = selectFile() #gets name and path using FileDialog
    ctrl.SetValue(path)

rawDescription: wxPython - Using filedialog to update a textctrl

description: WxPython - Using filedialog to update a textctrl


code:
import operator
s = sorted(s, key = operator.itemgetter(1, 2))

rawDescription: Sort a list by multiple attributes?

description: Sort a list by multiple attributes


rawDescription: Python numpy array replacing

description: Python numpy array replacing


code:
from pyspark.mllib.linalg import Vectors

tfidf.saveAsTextFile("/tmp/tfidf")
sc.textFile("/tmp/tfidf/").map(Vectors.parse)

rawDescription: Dealing with data inside TFIDF Sparevector or saving it to Dataframe or external file


rawDescription: What's the equivalent of PHP's "$my_array[]" in Python?


code:
pd.Timestamp('now') + np.timedelta64(100, 'ns')
isinstance(_6, datetime.datetime)

rawDescription: Is there a dedicated milli-sec precision timestamp data structure in python pandas?


rawDescription: Sort NumPy float array column by column

description: Sort NumPy float array column by column


code:
#Import Tkinter
from Tkinter import *
#define master
master = Tk()

#Horizontal (x) Scroll bar
xscrollbar = Scrollbar(master, orient=HORIZONTAL)
xscrollbar.pack(side=BOTTOM, fill=X)
#Vertical (y) Scroll Bar
yscrollbar = Scrollbar(master)
yscrollbar.pack(side=RIGHT, fill=Y)

#Text Widget
text = Text(master, wrap=NONE,
            xscrollcommand=xscrollbar.set,
            yscrollcommand=yscrollbar.set)
text.pack()

#Configure the scrollbars
xscrollbar.config(command=text.xview)
yscrollbar.config(command=text.yview)
#Run tkinter main loop
mainloop()

rawDescription: Python scrollbar on text widget

description: Python scrollbar on text widget


rawDescription: Sorting a dictionary in python

description: Sorting a dictionary in python


code:
my_dict = create_dict(b)
my_dict[4]
my_dict[5]
my_dict[1]
my_dict[7]

rawDescription: Having a list of lists - how to get the index of a list containing an item?


code:
xx = ({1,2}, {2,3}, {3,4}, {4,2})
yy = []
for x in xx:
  # Here, x is a reference to one of the existing sets in xx.
  # x.discard modifies x in place and returns None.
  y = x.discard(2)
  # y is None at this point.
  yy.append(y)
yy
xx

rawDescription: List comprehension against tuple of sets


code:
say=lambda x:print(x,end=' ') or print
say('Hello')('World')

rawDescription: Interesting "Hello World" Interview

description: Interesting "Hello World" Interview


rawDescription: In Python ElementTree how can I get list of all ancestors of an element in tree?


code:
def complex_unroll(f, are_complex):

    # This function will have access to are_complex and f through python closure
    # *args give us access to all parameters as a list
    def g(*args, **kwargs):
        # new_args stores new list of parameters, the complex ones
        new_args = []
        # arg_id is iterator used to keep track where are we in the original list
        arg_id = 0
        for is_complex in are_complex:
            if is_complex:
                # if we request complex unroll, we merge two consequtive params
                new_args.append(args[arg_id] + 1J*args[arg_id+1])
                # and move iterator 2 slots
                arg_id += 2
            else:
                # otherwise, just copy the argument
                new_args.append(args[arg_id])
                arg_id += 1
        # finally we return a call to original function f with new args
        return f(*new_args, **kwargs)

    # our unroll function returns a newly designed function g
    return g

rawDescription: Replacing complex-valued arguments of generic function object by two real-valued arguments


code:
df.groupby(df.index).agg(lambda x: list(x)).to_json()
'{"ticket_number":{"person1":[1, 2],"person2":[3]}}'

rawDescription: Grouping values in pandas into on index

description: Grouping values in pandas into on index


code:
for i in range(LIMIT_INDEX):
    if odd_primes[i] is False:
        continue
    odd_primes[2*i**2 + 6*i + 3:LIMIT_INDEX:2*i+3] = False

rawDescription: Optimize Sieve of Eratosthenes Further

description: Optimize Sieve of Eratosthenes Further


code:
from collections import defaultdict
by_status = defaultdict(list)
for report in reports:
    by_status[report].append(report)

rawDescription: Is there a better way to split of objects by one of its attributes?


code:
lower, upper = bounds
upper += 1
my_list[lower:upper] = ['foo'] * (upper - lower)

rawDescription: Python - set list range to a specific value


code:
import lxml.html as LH
doc = LH.fromstring(content)
tds = (td.text_content() for td in doc.xpath('//td'))
for td, val in zip(*[tds]*2):
    if td in ("Working Dir", "Java Data Model"):
        print(td,val)

rawDescription: Simple example regarding how to parse data from html output using lxml


code:
u"..."
#instead of just
"..."

rawDescription: Python - Unicode

description: Python - Unicode


rawDescription: Pandas: add dataframes to dataframe - match on index and column value


code: from models.mymodels import Model1, Model2, Model3

rawDescription: How to structure a python project with three applications that use common module

description: Structure a python project with three applications that use common module


code:
a = np.array([[2], [7], [23]], dtype=np.uint8)
a
b = np.unpackbits(a, axis=1)
b

rawDescription: Built-in function in numpy to interpret an integer to an array of boolean values in a bitwise manner?


rawDescription: eliminate text after certain character in python pipeline- with slice?

description: Eliminate text after certain character in python pipeline- with slice


code: db.uuidtest.insert({'_id': uuid.hex})

rawDescription: Why does PyMongo encode uuid.uuid1() as a BSON::Binary?


code: pylab.text(max_x, max_y, str((max_x, max_y)))

rawDescription: Python find x value to corresponding max y value in plot


code: Line = collections.namedtuple('Line', 'line count path')

rawDescription: How can I write a class that behaves exactly like another dynamically determined class? (Python)

description: Write a class that behaves exactly like another dynamically determined class? (Python)


code:
data['ts_placed'] = [pd.to_datetime(strD) for strD in data.ts_placed]
data.sort('ts_placed')

rawDescription: how to import dates in python

description: Import dates in python


code: from .utils import get_shop_id

rawDescription: Django Global function and variable

description: Django Global function and variable


code:
import wpf

from System.Windows import Window

class AboutWindow(Window):
    def __init__(selfAbout):
        wpf.LoadComponent(selfAbout, 'AboutWindow.xaml')

rawDescription: IronPython WPF Load New Window

description: IronPython WPF Load New Window


code:
from itertools import groupby
from operator import itemgetter
from pprint import pprint

data = [ {
           'Organization' : '123 Solar',
           'Phone' : '444-444-4444',
           'Email' : '',
           'website' : 'www.123solar.com'
         }, {
           'Organization' : '123 Solar',
           'Phone' : '',
           'Email' : 'joey@123solar.com',
           'Website' : 'www.123solar.com'
         },
         {
           'Organization' : '234 test',
           'Phone' : '111',
           'Email' : 'a@123solar.com',
           'Website' : 'b.123solar.com'
         },
         {
           'Organization' : '234 test',
           'Phone' : '222',
           'Email' : 'ac@123solar.com',
           'Website' : 'bd.123solar.com'
         }]

data = sorted(data, key=itemgetter('Organization'))
result = {}
for key, group in groupby(data, key=itemgetter('Organization')):
    result[key] = [item for item in group]

pprint(result)

rawDescription: Sort a list of dictionaries while consolidating duplicates in Python?


code:
import re

p = "Scanning sequence ID\:\s*(?P<label>[A-Z0-9]+\_[A-Z0-9]+).*?(?P<start_value>\d+)"

with open("A.txt", "r") as f:
    s = f.read()

re.findall(p,s, re.DOTALL)

rawDescription: How to extract start and end sites based on capital letter in a sequence?

description: Extract start and end sites based on capital letter in a sequence


rawDescription: Finding row index of max column values in a numpy matrix


code:
x = getattr(t, "attr1")
setattr(t, 'attr1', 21)

rawDescription: How to access object attribute given string corresponding to name of that attribute

description: Access object attribute given string corresponding to name of that attribute


code:
last_lines = df.reset_index().groupby('A').index.last()
df.drop(last_lines)

rawDescription: Splitting Pandas Dataframe with groupby and last


code: from A import*

rawDescription: Running Python Script from another Python Script


rawDescription: Connect to dynamic database parameters sqlalchemy


code: df['id'] = np.arange(len(df))

rawDescription: Is there a better way to index dataframes?


code: d = dict((k,v) for k,v in (i.split(':') for i in a.split("\r\n\t")[2:]))

rawDescription: Python: how to get a number followed by a specific key word from a string


rawDescription: Generating a new order for a list of lists in python


code:
string1
string2
string3
string4
string6
string7
string9

rawDescription: Python: How to skip lines that have extra characters while using Regular Expressions?


code: f = lambda x: 2*x

rawDescription: Assign multiple functions to a single variable?


code:
from lxml import etree as ET

def create_library(lines):
    library = ET.Element('LIBRARY')
    for line in lines:
        split_line = line.split(',')
        library.append(create_book(split_line))
    return library

def create_book(split_line):
    book = ET.Element('BOOK',ID=split_line[0])
    book.append(create_chapter(split_line))
    return book

def create_chapter(split_line):
    chapter = ET.Element('CHAPTER',ID=split_line[1])
    chapter.append(create_sentence(split_line))
    return chapter

def create_sentence(split_line):
    sentence = ET.Element('SENT',ID=split_line[2])
    sentence.append(create_word(split_line))
    return sentence

def create_word(split_line):
    word = ET.Element('WORD',ID=split_line[3])
    word.text = split_line[4]
    return word

rawDescription: creating a xml file with For Loop in python

description: Creating a xml file with For Loop in python


code: num = result[2]

rawDescription: Python: Manipulate an array

description: Python: Manipulate an array


code: [['d', 'disease'], ['bc', 'breast cancer']]

rawDescription: Compare two CSV files and print the rows that are different Python


code:
def import_file(filename):
    with open(filename) as f:
        content = [line.strip() for line in f]
    return content

rawDescription: finding item in text file during 2nd read

description: Finding item in text file during 2nd read


rawDescription: Extract a part of a string in python

description: Extract a part of a string in python


rawDescription: Finding the nearest value and return the index of array in Python


code:
[config]
NumberOfEntries=10

rawDescription: configparser without whitespace surrounding operator

description: Configparser without whitespace surrounding operator


code:
json_string = '{"last_updated": {"$gte": "Thu, 1 Mar 2012 10:00:49 UTC"}}'
dct = json.loads(json_string, object_hook=datetime_parser)
dct

rawDescription: How to convert to a Python datetime object with JSON.loads?

description: Convert to a Python datetime object with JSON.loads


code: table = Table(up=["img1.png","img2.png"], down=..., left=..., right=...)

rawDescription: Copying a list in python

description: Copying a list in python


code:
import datetime
import json
s = " query : {'names' :['abc','xyz'],'location':'India'}"
key, value = s.strip().split(':', 1)
# we can leave out the replacing, single quotes is fine for eval
data = {
    key: eval(value)
}

rawDescription: Converting a MongoDB Query String with Datetime field into Dict in Python


code: sortedlist = sorted(list, key=lambda x: x.rsplit('-', 1)[-1])

rawDescription: Python help sorting after hyphen

description: Python help sorting after hyphen


code: options[num]()

rawDescription: How to use switch in Python?

description: Use switch in Python


code:
def debye_integrand(x,  n):
        return x**n/((np.exp(x) - 1)*(1 - np.exp(-x)))

rawDescription: Fit an integral function with parametric limit to data with Python (Debye Model)


code: object.__dict__["test"] = "test"

rawDescription: Object class override or modify

description: Object class override or modify


code:
import mymodule
mymodule.get_content = mock.Mock(return_value="mocked stuff")

rawDescription: mocking functions using python mock

description: Mocking functions using python mock


code:
def add(a,b):
    print(a+b)
    return a+b
def subtract(a,b):
    print(a-b)
    return a-b
def multiply(a,b):
    print(a*b)
    return a*b
def divide(a,b):
    print(a/b)
    return a/b

rawDescription: How do you print a function's result in python?

description: Print a function's result in python


rawDescription: Sharing data between two lists

description: Sharing data between two lists


code:
def getIP(self, commandline):
    getter_process = subprocess.Popen(commandline, stdout=subprocess.PIPE)
    myip = getter_process.communicate()[0].decode(encoding="ascii", errors="ignore").replace("\n","")
    return myip if isIP(myIP) else None

def askIP(self,ind):
    """
    Start subprocesses asking for external IP in separate threads
    """

    print("askIP start")
    #list of commandlines that are supposed to return IP as a result
    IPgettingMethods = [
        ["dig", "+short", "myip.opendns.com", "@resolver1.opendns.com"],
        ["dig", "+short", "myip.opendns.com", "@resolver1.opendns.com"],
        # and other command line commands I may want in separate threads
    ]

    def get_ip_controller():
        with ThreadPoolExecutor(len(IPgettingMethods)) as executor:
            futures = [executor.submit(self.getIP, i) for i in IPgettingMethods]
            for future in as_completed(futures):
                ip = future.result()
                if ip:
                    GLib.idle_add(self.setIndicatingMenus, ip, self.hIndicator)
                    break

    Thread(target=get_ip_controller).start()

rawDescription: Run a function only by the thread that is the first one to reach it's calling


rawDescription: How to tell if a key has been released in tkinter

description: Tell if a key has been released in tkinter


code: [file for file in os.listdir("directoryone")]

rawDescription: Python - Copying only new files into another directory


rawDescription: Pythonic way to store top 10 results

description: Pythonic way to store top 10 results


code:
{ All1 : [checkbox1A, checkbox1B],
  All2 : [checkbox2A, checkbox2B]}

rawDescription: PyQt - How to connect multiple signals to the same widget


code:
def traverse_preorder(ast):
    yield ast[0]
    for arg in ast[1:]:
        for x in traverse_preorder(arg):
            yield x

rawDescription: Using a grammar parser for Python and constructing files from the tree


code:
import cgi
value, params = cgi.parse_header(header)
value
params

rawDescription: How to get filename from Content-Disposition in headers

description: Get filename from Content-Disposition in headers


code:
s = range(1, 7)
s[4]
neg = -(len(s)-4) # Here you would replace 4 with your index
s[neg]

rawDescription: How do you find the negative index of a position if you know the index?

description: Find the negative index of a position if you know the index


code:
rc = np.vstack([rows,cols]).T.copy()
dt = rc.dtype.descr * 2
i = np.unique(rc.view(dt), return_index=True)[1]

rawDescription: Ignoring duplicate entries in sparse matrix


code:
import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread('image.png',0)
img = cv2.medianBlur(img,7)
ret,th1 = cv2.threshold(img,160,255,cv2.THRESH_BINARY)
th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,31,5)
th3 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,31,5)
titles = ['Original Image', 'Global Thresholding (v = 127)',
'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
for i in xrange(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

rawDescription: Convert different shades of a color in an image to one color


code: my_list + np.sum( harmonic * var1 )

rawDescription: Preventing nested list output from a for-loop / list comprehension when appending new values to an Array


code:
applicant = form.save()
applicant.courses.add(course)

rawDescription: Current field values from session in Django


code: g('plot "' + plot_cmd + datFile + '" using 1:3 with lines, "' + plot_cmd + datFile + '" using 1:5 with lines')

rawDescription: Gnuplot.py plotting multiple lines on the one graph


code: dictAB = {k: [dictA[k], dictB[k]] for k in dictA}

rawDescription: Refactoring with python dictionary comprehension


code:
myfile = fileinput.FileInput("inputRegex.txt", inplace=True)

for line in myfile:
    line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
                  "foundValue",
                  line.rstrip())
    print(line)

rawDescription: Python regex find and replace inplace

description: Python regex find and replace inplace


code:
d = {"foo":"bar", "spam":['green','eggs','and','ham']}
print(d.items())
# [ ("foo", "bar"),
#   ("spam", ["green","eggs","and","ham"])]

rawDescription: Dictionary with lists as values - find longest list


code:
main, new = zip(*[(''.join(parts[::2]), ''.join(parts[1::2])) for parts in [pat.split(m) for m in main]])
main
new

rawDescription: append match to new list and delete match from original list

description: Append match to new list and delete match from original list


rawDescription: parse string into columns python pandas /xa0 in stead of white space

description: Parse string into columns python pandas /xa0 in stead of white space


code:
mylist = list(a.reshape(-1,2)) # list of arrays
mylist.append([]) # make the list irregular
b = np.array(mylist)  # array of objects
b = b[:-1].reshape(2,3)  # cleanup

rawDescription: Convert a numpy array to an array of numpy arrays


code:
{'_id': 122.0, 'impressions_count': 1}
{'_id': 124.0, 'impressions_count': 1}
{'_id': 127.0, 'impressions_count': 1}
{'_id': 123.0, 'impressions_count': 2}

rawDescription: MapReduce in PyMongo

description: MapReduce in PyMongo


code:
def test_if_ascii(text):
    if isinstance(test, unicode):
        raise TypeError('hey man, dont feed me unicode plz')
    return all(32 <= ord(c) <= 126 for c in text)

rawDescription: How to decode() with a subset of 'ascii'?

description: Decode() with a subset of 'ascii'


rawDescription: Django many-to-many return list of releated objects


code:
llong = []
while longmin < longmax:
    longmin+=longstepx
    llong.append(+longmin)

rawDescription: Loop through list and changing indexes

description: Loop through list and changing indexes


rawDescription: From argwhere to where?

description: From argwhere to where


code: from A.B import C1

rawDescription: importing modules with submodules from deep in a library

description: Importing modules with submodules from deep in a library


code: headers = {key for count in counts_to_display.values() for key in count}

rawDescription: How to write defaultdict in more pythonic way?

description: Write defaultdict in more pythonic way


code:
cars.update() #calls the update function on all sprites in group
cars.draw(surface) #draws all sprites in the group

rawDescription: What are PyGame sprites, and what do they do?


code: p_value = value.eval()

rawDescription: How to convert tensorflow variable to a python variable?

description: Convert tensorflow variable to a python variable


code: birth_dates = list(map(date_string, filter(is_over_13, reverse(birthdays))))

rawDescription: Map two functions together in Functional Programming paradigm


code:
import tkinter as tk
import tkinter.ttk as ttk

class TextLineNumbers(tk.Canvas):
    def __init__(self, *args, **kwargs):
        tk.Canvas.__init__(self, *args, **kwargs)
        self.textwidget = None

    def attach(self, text_widget):
        self.textwidget = text_widget

    def redraw(self, *args):
        '''redraw line numbers'''
        self.delete("all")

        i = self.textwidget.index("@0,0")
        while True:
            dline= self.textwidget.dlineinfo(i)
            if dline is None: break
            y = dline[1]
            linenum = str(i).split(".")[0]
            self.create_text(5,y,anchor="nw", text=linenum, font=("Courier", 9))
            i = self.textwidget.index("%s+1line" % i)

class CustomText(tk.Text):
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

        self.tk.eval('''
            proc widget_proxy {widget widget_command args} {

                # call the real tk widget command with the real args
                set result [uplevel [linsert $args 0 $widget_command]]

                # generate the event for certain types of commands
                if {([lindex $args 0] in {insert replace delete}) ||
                    ([lrange $args 0 2] == {mark set insert}) ||
                    ([lrange $args 0 1] == {xview moveto}) ||
                    ([lrange $args 0 1] == {xview scroll}) ||
                    ([lrange $args 0 1] == {yview moveto}) ||
                    ([lrange $args 0 1] == {yview scroll})} {

                    event generate  $widget <<Change>> -when tail
                }

                # return the result from the real widget command
                return $result
            }
            ''')
        self.tk.eval('''
            rename {widget} _{widget}
            interp alias {{}} ::{widget} {{}} widget_proxy {widget} _{widget}
        '''.format(widget=str(self)))

        self.comment = False

class Tab:
    def __init__(self, parent, filename):
        self.parent = parent
        self.filename = filename
        self.tab1 = ttk.Frame(parent)
        self.text = CustomText(self.tab1, bd=0, font=("Courier", 9))

        self.vsb = tk.Scrollbar(self.tab1, orient=tk.VERTICAL)
        self.text.configure(yscrollcommand=self.vsb.set)
        self.vsb.configure(command=self.text.yview)

        self.linenumbers = TextLineNumbers(self.tab1, width=55)
        self.linenumbers.attach(self.text)

        self.vsb.pack(side=tk.RIGHT, fill=tk.Y)
        self.linenumbers.pack(side="left", fill="y")
        self.text.pack(side="right", fill="both", expand=True)

        parent.add(self.tab1, text=filename)

        self.text.bind("<<Change>>", self._on_change)
        self.text.bind("<Configure>", self._on_change)

    def _on_change(self, event):
        self.linenumbers.redraw()

class Window(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.fileName = "Untitled Document"
        self.content = ""
        self.previousContent = ""
        self.language = "Python"
        self.row = "0"
        self.column = "0"
        self.startCol = 0

        self.notebook = ttk.Notebook(self)
        self.tabs = []
        self.menubar()
        self.createtext()

    def createtext(self):
        self.notebook.pack(fill=tk.BOTH, expand=True)
        t = Tab(self.notebook, self.fileName)
        self.tabs.append(t)

    def addtab(self):
        t = Tab(self.notebook, self.fileName)
        self.tabs.append(t)

    def removetab(self):
        numberOfTabs = self.notebook.index("end")

        if numberOfTabs > 1:
            tabIndex = self.notebook.index(self.notebook.select())
            self.notebook.forget(tabIndex)
            del self.tabs[tabIndex]

    def menubar(self):
        self.menu = tk.Menu(self)
        self.master.config(menu=self.menu)

        self.fileMenu = tk.Menu(self.menu, font=("Courier", 9))
        self.fileMenu.add_command(label="New Window", command=self.addtab)
        self.fileMenu.add_command(label="Close Window", command=self.removetab)
        self.menu.add_cascade(label="File", menu=self.fileMenu)

if __name__ == "__main__":
    root = tk.Tk()
    root.title("Window")
    root.geometry("1024x600")
    window = Window(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Line numbers and Syntax Highlighting don't work on different tabs


code:
def name(x):
    return int(x.split()[0])

rawDescription: Using sorted and key parameter on list of strings


code:
log = open('some file.txt', 'a')  # so that data written to it will be appended
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

rawDescription: append subprocess.Popen output to file?

description: Append subprocess.Popen output to file


code:
outlist=[]
for index in  cmdargs:
  outlist.append(row[index])
wtr.writerow(outlist)

rawDescription: Specifying columns though command line to copy columns from csv file in python


code:
class TeamAdmin(admin.ModelAdmin):
    ...
    actions = ['exchange_team']

admin.register(Team, TeamAdmin)

rawDescription: Complex action on Django menu

description: Complex action on Django menu


code:
from collections import defaultdict

newDict = defaultdict(int)
for x, y in M:
    newDict[x] += M[x, y] * v.get(x, 0)

rawDescription: Python: dict multiplication

description: Python: dict multiplication


rawDescription: In Python, how do I remove from a list any element containing certain kinds of characters?


rawDescription: reading flask.session with angularjs

description: Reading flask.session with angularjs


code:
a =[{'id': 1,'desc': 'smth'},{'id': 2,'desc': 'smthelse'},{'id': 1,'desc': 'smthelse2'},{'id': 1,'desc': 'smthelse3'}]

c = {}
for d in a:
    c.setdefault(d['id'], []).append(d['desc'])
b = [{'id': k, 'desc': v} for k,v in c.iteritems()]

rawDescription: python list of dictionaries find duplicates based on value

description: Python list of dictionaries find duplicates based on value


code: results = session.query(User).outerjoin(last_entry, User.email == last_entry.c.email).add_entity(last_entry)

rawDescription: Reference query results with outerjoin in Flask/SQLAlchemy/jinja


code:
import re
s = "name[id]"
re.find(r"\[(.*?)\]", s).group(1) # = 'id'

rawDescription: How to split a string by using [] in Python

description: Split a string by using [] in Python


code:
listA = [1,2,3,2,1]
listB = [1,2,3,4,5,4,3,2,1]

set_A = set(listA)
newlist = list(set(listB) - set_A)[:len(set_A)]

rawDescription: select from list B k distinct elements that are not in list A in python?

description: Select from list B k distinct elements that are not in list A in python


code:
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('https://stackoverflow.com')

driver.current_window_handle

rawDescription: Python Selenium get current window handle


code:
def compose_pair(f1, f2):
    def composition(*args, **kwargs):
        return f1(f2(*args, **kwargs))
    return composition

def compose_iterative(*funcs):
    iterfuncs = iter(funcs)
    comp = next(iterfuncs)
    for f in iterfuncs:
        comp = compose_pair(comp, f)
    return comp

rawDescription: Call several functions and return the collective result


code:
[list(combinations(['a','b','c'],i)) for i in range(1,4)]
l=[list(combinations(['a','b','c'],i)) for i in range(1,4)]
sum(map(len,l))

rawDescription: How to calculate the number of all possible combinations for a range of numbers from 1 to N?

description: Calculate the number of all possible combinations for a range of numbers from 1 to N


code:
result = []
for d in dict1:
    for x in dict1[d]:
        if regex.search(d):
            result.append(x)

rawDescription: how to get dict value by regex in python

description: Get dict value by regex in python


code:
connection = context.idOfZPsycoPGDA()
connection.query('SELECT * FROM your_table')

rawDescription: How to directly query a relational/SQL database from a ZOPE product?

description: Directly query a relational/SQL database from a ZOPE product


code:
from itertools import izip
[list(x) for x in izip(*lis)]

rawDescription: the most pythonic matrix transposition

description: The most pythonic matrix transposition


code:
headers = {'foobar': 'raboof'}
requests.get('http://himom.com', headers=headers)

rawDescription: adding header to python request module

description: Adding header to python request module


code:
example = Example()
example.status = "Happy new year"
example.put()

rawDescription: Add a column to an existing table using GQL?


code:
def funct(arg, do_print=True):
    if do_print:
        print(arg)
    return arg

rawDescription: Functions: return and or print

description: Functions: return and or print


code:
c = Child.objects.get(id=1)
c.family_set.all()  # gives you a list of Families

rawDescription: Reverse lookup on Django m2m field?

description: Reverse lookup on Django m2m field


code:
test0
test1
test2

rawDescription: Python Beautifulsoup Find_all except

description: Python Beautifulsoup Find_all except


code:
record = (5790, 'Vlv-Gate-Assy-Mdl-\xe1M1-2-\xe19/16-10K-BB Credit Memo            ',
          60, True, '40141613')
json.dumps(record, encoding='latin1')

rawDescription: UnicodeDecodeError while using json.dumps()


code:
type(df.A[i])
type(df[(df.index==i)].A)

rawDescription: Updating values in a DataFrame

description: Updating values in a DataFrame


code:
def change_background(self, *args):
        self.canvas.before.clear()#<- clear previous instructions
        with self.canvas.before:
            if self.bg:
                Color(0.2, 0.2, 0.2, mode = 'rgb')
            else:
                Color(0.1, 0.1, 0.1, mode = 'rgb')
            Rectangle(pos = self.pos, size = self.size)

rawDescription: Kivy background in scroll view

description: Kivy background in scroll view


code:
happy_array = np.random.randn(28, 28)
im = plt.imshow(happy_array, cmap='gray', interpolation='none')
cbar = plt.colorbar(im)
plt.show()

rawDescription: Given a 2D numpy array of real numbers, how to generate an image depicting the intensity of each number?


code:
retcode, rusage = resource_call(['spam', 'eggs'])
print('spam used {}s of system time'.format(rusage.ru_stime))

rawDescription: measure elapsed time, amount of memory and cpu used by the extern program

description: Measure elapsed time, amount of memory and cpu used by the extern program


code:
Dict1 = {}
for key, val in zip(Lst1, Lst2):
    Dict1.setdefault(key, []).append(val)

rawDescription: Merge two equal-length lists into a dictionary, mapping one-to-many


rawDescription: Does lexical scope have a dynamic aspect?


code:
B = np.arange(9).reshape(3, 3)
B
np.in1d(B, bads).reshape(3, 3)

rawDescription: Converting Specified Elements of a NumPy Array by a New Value


code:
left
right
left.div(right['Counts'], axis=0)

rawDescription: Normalizing data in data frame with data from different data frame


code:
result_dict = {} # the dict in which you want to get the statistics

# the list of columns can be accessed through df.columns
for column_name in df.columns:
  col = df[column_name] # we get the column
  if column_name in CONT:
    stats = {} # we create a dict to keep the stats for this column
    stats['count'] = col.count()
    stats['mean'] = col.mean()
    stats['min'] = col.min()
    result_dict[column_name] = stats # we add the stats dict to our result_dict

  else:
    stats = {}
    stats['count'] = col.count()
    stats['mode'] = col.mode()
    result_dict[column_name]

rawDescription: Python Dictionary Adding Values

description: Python Dictionary Adding Values


code:
import mock
import unittest
import module_under_test

class TestOriginal(unitest.TestCase):
    @patch('module_under_test.A')
    def test_Original_method(self, mocked_A):
        mocked_A.return_value = 42
        result = module_under_test.B()
        mocked_A.assert_called_with()
        self.assertEqual(result, 420)

rawDescription: Patch a method outside python class

description: Patch a method outside python class


rawDescription: Finding in elements in a tuple and filtering them


code:
def get_next_output_offset_pair(text, offset):
  #A: Adapt first code snippet
  return [next_offset, next_output]

def main():
   text = "\x0A\x0B\x0C\x01"
   offset = 0
   output = ''
   while offset < len(text):
     offset, next_output = get_next_output_offset_pair(text, offset)
     output.append(next_output)

rawDescription: Updating multiple (local) variables by function return value in a loop


code:
A = ['a', 'b', 'c']
B = ['d', 'e', 'f']
set_b = set(B)
res = [i for i in A if i in set_b]

rawDescription: Fastest way of comparing lists of strings


rawDescription: JSON Python Lists

description: JSON Python Lists


rawDescription: python recursive vectorization with timeseries

description: Python recursive vectorization with timeseries


rawDescription: Count occurences of a row with pandas in python


code:
Monday [0]
Tuesday [1]
Friday [4]
Wednesday [2]
Thursday [3]
Sunday [6]
Saturday [5]

rawDescription: Find Out What Days an Event is On With Google Calendar?


rawDescription: How to create dict using csv file with first row as keys

description: Create dict using csv file with first row as keys


code:
records_array = array([1, 2, 3, 1, 1, 3, 4, 3, 2])
vals, inverse, count = unique(records_array, return_inverse=True,
                              return_counts=True)

idx_vals_repeated = where(count > 1)[0]
vals_repeated = vals[idx_vals_repeated]

rows, cols = where(inverse == idx_vals_repeated[:, newaxis])
_, inverse_rows = unique(rows, return_index=True)
res = split(cols, inverse_rows[1:])

rawDescription: Get a list of all indices of repeated elements in a numpy array


code:
command = SCRIPT + " R > " + OUT_FILE + " 2>/dev/null &"
#                                                     ^

rawDescription: stop execution of a bashscript when parent python script is killed

description: Stop execution of a bashscript when parent python script is killed


code:
import csv

with open('input.csv', 'rb') as f_input, open('output.csv', 'wb') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)
    csv_output.writerow(next(csv_input))    # write header

    for cols in csv_input:
        for col in range(1, len(cols)):
            try:
                cols[col] = "{:.1f}".format(float(cols[col]) / 1024.0)
            except ValueError:
                pass
        csv_output.writerow(cols)

rawDescription: Convert numerical data in csv from bytes to kilobytes using Python


code: soup.find('div', attrs={'class':'media item avatar profile'}).a.img['src']

rawDescription: BeautifulSoup: how to select certain tag


code:
myfile = open('xyz.txt', 'w')
myfile.writelines(var1)
myfile.close()

rawDescription: Writing to a file in a for loop

description: Writing to a file in a for loop


code:
from django.db import connection
Lecture.objects.values_list('year','term').distinct()
connection.queries

rawDescription: Get all available combinations of two fields through the Django ORM?


rawDescription: First common element from different lists of numbers


code:
with open('listoffiles.txt') as fp:
    for line in fp:
        filename = line.strip()
        if filename:
            call(filename)

rawDescription: How do I iterate over the lines of a text file?

description: Iterate over the lines of a text file


code:
arr1 = np.subtract(arr.T, means).T
cov = np.dot(arr1, arr1.T)

rawDescription: NumPy vectorised method for computing covariance with population means (for survey data)


rawDescription: Use between_time() on MultiIndex?

description: Use between_time() on MultiIndex


rawDescription: Plot specific rows of a pandas dataframe


code:
'{:<20}'.format('Hello World!') # Add spaces to the right to reach 20 characters
'{:>20}'.format('Hello World!') # Add spaces to the left
'{:20}'.format('Hello World!') # Use default alignment for the type of object

rawDescription: How to make specific parts of a text line indented properly?

description: Make specific parts of a text line indented properly


rawDescription: Parse YAML and assume a certain path is always a string


code:
df = pd.DataFrame([(row['points'], row['freq'], letter)
                   for index, row in df.iterrows()
                   for letter in row[-1]], columns=['points', 'freq', 'letter'])

rawDescription: Pandas: transform a DataFrame by splitting each value into multiple values


code:
from collections import Counter
adjectives = ['awesome', 'amazing', 'awesome']
counts = Counter(adjectives)
counts.items()

rawDescription: Python :getting the count for the adjectives in a string


code:
for new_record in new_records:
    new_node = MyMPTTModel(..., parent=get_parent(new_record))
    new_node.save()

rawDescription: How optimize adding new nodes in `django-mptt`?


code:
for i, url in enumerate(urllist):
    image_request(url, str(i) + ".jpg")

rawDescription: Download and SAVE MANY Images from google Image search to a LOCAL FOLDER (Python)


rawDescription: wxpython cut copy and paste throughout the application

description: Wxpython cut copy and paste throughout the application


code:
lines = file2.readlines()
for line in lines[1:]: # To skip the first empty line in the file
    line = line.split("\t")
    line[2] = str(float(line[2]) * int(serve))
    file3.write("\t".join(line))

rawDescription: python 3 - find and replace all numbers in a text file

description: Python 3 - find and replace all numbers in a text file


code:
__hello()
__init__()
__this_is_a_function()
__this_is_also_a_function__()
__a_URL2_function__()

rawDescription: Regex to match double underscores?

description: Regex to match double underscores


rawDescription: Format number using LaTeX notation in Python


rawDescription: reverse() does not work on a Python literal?

description: Reverse() does not work on a Python literal


code:
Builder.load_string('''
<SweetWidget>:
    BoxLayout:
        canvas:
            Color:
                rgba: 0,0,1,1
            Rectangle:
                size: self.size
                pos: self.pos
        height: 400
        size_hint: 1, None
        pos_hint: {'top': 1}
        orientation: 'vertical'
        Button:
            text: "1"
        Button:
            text: "2"
        Button:
            text: "3"
        Button:
            text: "4"
        Button:
            text: "5"
        Button:
            text: "6"
''')

rawDescription: Why adding height to floatLayout will make it start adding following blocks from the bottom of the screen?


code:
lst = ['aaaa', 'aaata', 'aaatt']
[">{}/n{}".format(x, y) for x,y in enumerate(lst, 1)]

rawDescription: Append/Prepend a different character to each item in a list


rawDescription: Slice by date in pandas without re-indexing


code:
k_space = False #---- Initialize the boolean for the space key here
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True

        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            k_space = True #----- Set it to true here

    if k_space: #---- create a bullet when the k_space variable is set to True
        bullet = Bullet()
        bullet.rect.x = player.rect.x
        bullet.rect.y = player.rect.y
        all_sprites_list.add(bullet)
        bullet_list.add(bullet)

    k_space = False #------ Reset it here

    all_sprites_list.update()

    for bullet in bullet_list:

        block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True)

        for block in block_hit_list:
            explosion.play()
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)
            score += 10

        if bullet.rect.y < -10:
            bullet_list.remove(bullet)
            all_sprites_list.remove(bullet)

    font = pygame.font.Font(None, 36)
    text = font.render("Score: " + str(score), True, WHITE)
    textpos = text.get_rect(centerx=screen.get_width()/12)

    screen.blit(background, (0,0))

    screen.blit(text, textpos)

    all_sprites_list.draw(screen)

    pygame.display.update()

    clock.tick(80)

rawDescription: Keyboard Event - Pygame

description: Keyboard Event - Pygame


code:
AGE = raw_input("Enter your age: ")

vdf = vertica.select_dataframe("""
    Select
        col1,
        col2,
        coln
    FROM
        TableX
    WHERE
        col2 IN (21, 22, %s)
    Group BY 1
""" % AGE)

rawDescription: Python arguments inside triple quotes

description: Python arguments inside triple quotes


code:
open = f.Open.resample('W-MON', how='last')
close = f.Close.resample('W-FRI', how='last').resample('W-MON', how='last')
high = f.High.resample('W-MON', how='max')
low = f.Low.resample('W-MON', how='min')
vol = f.Volume.resample('W-MON', how='sum')
weekly_data = pd.concat([open, close, high, low, vol], axis=1)

rawDescription: converting daily stock data to weekly-based via pandas in Python

description: Converting daily stock data to weekly-based via pandas in Python


rawDescription: Spark dataframe transform multiple rows to column


code:
for char in packet:
    print("%5d %2s %2r" % (ord(char), char, char))

rawDescription: How to capture all characters in binary string without python interpreting it

description: Capture all characters in binary string without python interpreting it


code:
def strToInt(s, acc):
    if not s:
        return acc
    return strToInt(s[1:], 10 * acc + ord(s[0]) - 48)

rawDescription: Python - String of Digits to Integer using Recursion?


code:
data = (['possible-duplicate', '12345'],
        ['not-a-duplicate', '54321'],
        ['possible-duplicate', '51423'])
data_unique = dict(data)

rawDescription: Uniquifying a list of lists in python

description: Uniquifying a list of lists in python


code: print(b'\33]0;title you want\a', end='')

rawDescription: Set GNOME terminal window title in Python?


code:
list1 = [0.43, -1.2, 50, -60.5, 50]
list2 = ['tree', 'cat', 'cat', 'tree', 'hat']
d = {}
for k, v in zip(list2, list1):
    d.setdefault(k, []).append(v)

rawDescription: Python: zip 2 lists into a dictonary, del the duplicated keys but keep the values


code:
import numpy as np
from sklearn.decomposition import PCA

pca = PCA(n_components=3)
pca.fit(data)

data_reduced = np.dot(data, pca.components_.T) # transform
data_original = np.dot(data_reduced, pca.components_) # inverse_transform

rawDescription: PCA inverse transform manually

description: PCA inverse transform manually


rawDescription: wxPython widgets are one on top of the other

description: WxPython widgets are one on top of the other


code:
whitespace = ' \t\r\n'
operators = '~!%^&*()-+=[]{};:\'"/?.,<>\\|'

def scan(s):
    "returns a token and a state/token id"
    words = {0:'', 1:'', 2:''} # normal, operator, whitespace
    state = 2 # I pick ws as first state
    for c in s:
        if c in operators:
            if state != 1:
                yield (words[state], state)
                words[state] = ''
            state = 1
            words[state] += c
        elif c in whitespace:
            if state != 2:
                yield (words[state], state)
                words[state] = ''
            state = 2
            words[state] += c
        else:
            if state != 0:
                yield (words[state], state)
                words[state] = ''
            state = 0
            words[state] += c
    yield (words[state], state)

rawDescription: Where do you use generators feature in your python code?


code: filter(lambda path: filterex(path, 'txt'), files)

rawDescription: Python: Passing functions with arguments to a built-in function?


code: [i for e in bad for i in my_list if e in i]

rawDescription: Check if list item contains items from another list


rawDescription: Append a 1d array to a 2d array in Numpy Python


code:
class Terminator(BoxLayout):
    def DelButton(self):
        for child in [child for child in self.children]:
            self.remove_widget(child) # this will delete all children

rawDescription: kivy access child id

description: Kivy access child id


code:
from django.template.loader import render_to_string

def getClasses(request):
   User = request.user
   aircomcode = request.POST.get('aircompany_choice', False)

   working_row = Pr_Aircompany.objects.get(user=User, aircomcode=aircomcode)
   economy_classes = working_row.economy_class
   business_classes = working_row.business_class

   economy = render_to_string('dbmanager/classes.html', {"classes": economy_classes})
   business = render_to_string('dbmanager/classes.html', {"classes": business_classes})

   return JsonResponse({"economy": economy,
                    "business": business})

rawDescription: How to send two variables with html as a JSON in Django?

description: Send two variables with html as a JSON in Django


rawDescription: pandas - apply replace function with condition row-wise

description: Pandas - apply replace function with condition row-wise


code:
re.split('(=?" ?)', twikiattribs)
re.split('=?" ?', twikiattribs)

rawDescription: turn key="value" string into a dict

description: Turn key="value" string into a dict


code:
import csv

cr = csv.reader(open('/path/to/your/file.csv'))
cr_head = cr.next()    # throw away the first row

for row in cr:
    update_ops(ops, row)

# Now write a new csv file – csv.writer is your friend :)
with open('new_operation_times.csv', 'w') as newcsv:
    cw = csv.writer(newcsv)

    # first write your header. csv.writer accepts lists for each row.
    header = 'start_time,end_time,operation'.split(',')
    cw.writerow(header)

    # now write out your dict values. You may want them sorted,
    # but how to do that has been answered elsewhere on SE.
    for opname, timesdict in ops.items():
        row = [ opname, timesdict['start_time'], timesdict['end_time'] ]
        cw.writerow(row)

rawDescription: Parse CSV file and modify columns

description: Parse CSV file and modify columns


code:
import itertools
import collections

def borda(ballot):
    n = len([c for c in ballot if c.isalpha()]) - 1
    score = itertools.count(n, step = -1)
    result = {}
    for group in [item.split('=') for item in ballot.split('>')]:
        s = sum(next(score) for item in group)/float(len(group))
        for pref in group:
            result[pref] = s
    return result

def tally(ballots):
    result = collections.defaultdict(int)
    for ballot in ballots:
        for pref,score in borda(ballot).iteritems():
            result[pref]+=score
    result = dict(result)
    return result

ballots = ['A>B>C>D>E',
           'A>B>C=D=E',
           'A>B=C>D>E',
           ]

print(tally(ballots))

rawDescription: Borda Count using python?

description: Borda Count using python


code:
import collections
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)

compare([1,2,3], [1,2,3,3])
compare([1,2,3], [1,2,3])
compare([1,2,3,3], [1,2,2,3])

rawDescription: Check if two unordered lists are equal

description: Check if two unordered lists are equal


rawDescription: Sort Versions in Python

description: Sort Versions in Python


code:
native = ctypes.cdll.LoadLibrary('native.so')
native.add_event_listener.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]

def focused(nodeAddr): focusChanged(cToPython(nodeAddr), True)
def blurred(nodeAddr): focusChanged(cToPython(nodeAddr), False)

CALLBACK = ctypes.CFUNCTYPE(None, ctypes.c_void_p)
focused = CALLBACK(focused)
blurred = CALLBACK(blurred)

rawDescription: Can't find DOMEventTarget.add_event_listener in Python


rawDescription: Python: Split NumPy array based on values in the array


rawDescription: Python regexp to match numbers with spaces


code:
def make_sort_key(word):
    indices = {}
    for i, c in enumerate(word):
        indices.setdefault(c, []).append(i)
    def key(c):
        return indices[c].pop()
    return key

sorted(scrambled, key=make_sort_key(word))

rawDescription: Sorting string into identical words

description: Sorting string into identical words


code: add_matrices(c, d)

rawDescription: Add two matrices in python

description: Add two matrices in python


rawDescription: Getting the first three bytes of an IP address


rawDescription: Fastest Way to Round to the Nearest 5/100ths


code:
for root, dirnames, filenames in os.walk('./'):
    if not fnmatch.fnmatch(root, './*/www/[pP]3*'):
        continue
    for filename in fnmatch.filter(filenames, '*.php'):
            matches.append(os.path.join(root, filename))

rawDescription: Crawling Unix for All .php Files in Specific Subdirectories


code:
def send_names(*args):
    print('sometext, {0}'.format(', '.join(args)))

send_names('message1', 'message2', 'message3')

rawDescription: variadic / arbitrary number of *args or ** kwargs in str.format() in Python

description: Variadic / arbitrary number of *args or ** kwargs in str.format() in Python


code:
members = UserHyperlinkedRelatedField(
    queryset=User.objects.all(),
    view_name='user-detail',
    lookup_field='pk',
    many=True,
)

rawDescription: How do I customize the text of the select options in the api browser?

description: Customize the text of the select options in the api browser


code:
grades = {}
while True:
    k = raw_input('Please enter the module ID: ')
    val = raw_input('Please enter the grade for the module: ')
    grades[k] = val

grades

rawDescription: Iterating on a dictionary, adding keys and values


rawDescription: Find element with function find in lxml

description: Find element with function find in lxml


code:
with open("vals.txt") as f:
    hexVals = f.read()

with open("out.txt", "w") as g:
    for val in hexVals.split():
        g.write('0x' + val[:2] + " ")
        if(len(val) > 2):
            g.write('0x' + val[2:]  + " ")

rawDescription: Add leading zero to hex values in python


rawDescription: Bin size in Matplotlib (Histogram)

description: Bin size in Matplotlib (Histogram)


rawDescription: how to calculate the norm of a vector in a large mxnx3 array?

description: Calculate the norm of a vector in a large mxnx3 array


code:
values = np.fromfile("filepath", dtype=int8)
real = np.bitwise_and(values, 0x0f)
imag = np.bitwise_and(values >> 4, 0x0f)

rawDescription: how to load 4-bit data into numpy array

description: Load 4-bit data into numpy array


code:
class Page(Base):
    slug = sa.Column(sa.String, primary_key=True)
    title = sa.Column(sa.String)
    body = sa.Column(sa.String)
    historical_node_id = sa.Column(sa.Integer, index=True, unique=True)

rawDescription: How to mimic the url aliasing functionality of mod_rewrite with Pyramid (Python Framework)?

description: Mimic the url aliasing functionality of mod_rewrite with Pyramid (Python Framework)


code: niu = value

rawDescription: How to create an incremental field (sequence) that is validated with a method (def)

description: Create an incremental field (sequence) that is validated with a method (def)


code:
class Meta(type):
    def __repr__(cls):
        if hasattr(cls, '_class_repr'):
            return getattr(cls, '_class_repr')()
        else:
            return super(Meta, cls).__repr__()

class A(object):
    __metaclass__ = Meta

    @classmethod
    def _class_repr(cls):
        return 'My class %s' % cls.__name__

class B(object):
    __metaclass__ = Meta

rawDescription: Can I define a __repr__ for a class rather than an instance?

description: Define a __repr__ for a class rather than an instance


code:
try:
    o = open(x, "r")
    p = o.read()
    y = tuple(j.split() for j in p.splitlines())
    #m = " ".join(map(str, y))
    for v1,v2,v3,fname,*rest_of_name in y:
        #print(v1,v2,v3,fname,*rest_of_name)

        if int(v1) != some_year:
            continue;

        print("{:<30} {:<10} {:<5} {:<5}".format(fname + ', ' +  ' '.join(rest_of_name), v1,v3, v2))
    o.close()
except IOError as e :
    print("File Does Not Exist")

rawDescription: Converting a string into a table format with columns


code:
id(regfield)
id(registers[0]['fields'])

rawDescription: Placing a numpy record array inside another record array python


code:
sets={frozenset(e) for e in fruits}
us=set()
while sets:
    e=sets.pop()
    if any(e.issubset(s) for s in sets) or any(e.issubset(s) for s in us):
        continue
    else:
        us.add(e)

rawDescription: Fastest way to remove subsets of lists from a list in Python


code:
from django.db.models import Q
Room.objects.filter( Q(surface_area__lte=40) | Q(surface_area__isnull=True) )

rawDescription: How can I include null values in arithmetic query in django

description: Include null values in arithmetic query in django


rawDescription: wxPython .SetFocus() on ID

description: WxPython .SetFocus() on ID


code:
def combine(template, options):
    template = template.replace('?', '{}')
    for opts in itertools.product(*options):
        yield template.format(*opts)

rawDescription: Generate combinations from an input in python


rawDescription: Breaking down instances of classes into lists, or: a better way to sum class variables?


code:
num = ['{}{}'.format(h, b + 1)
       for h in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for b in range(int(size))]

rawDescription: Bombs Away Battleships

description: Bombs Away Battleships


rawDescription: python code to get the files outside the current working directory

description: Python code to get the files outside the current working directory


rawDescription: How to remove all \n's and make it as csv file of 5 columns?

description: Remove all \n's and make it as csv file of 5 columns


code:
def sieve_using_set_and_ranges(b):
    seq_primes=list(range(2, b + 1))
    sieve_set=set(range(2, b + 1))
    for c in range(0, math.floor(math.sqrt(b)) + 1):
        for k in range(c, math.floor(b / seq_primes[c]) + 1):
            sieve_set.discard(seq_primes[k] * seq_primes[c])
    return list(sorted(sieve_set))

rawDescription: Sieve of eratosthenes using dictionaries in python


rawDescription: Custom Icon in gtk toggle_action

description: Custom Icon in gtk toggle_action


code:
import os

open('file1', 'wc')

# switch to userid 501
os.seteuid(501)
open('file2', 'wc')

# switch back to root
os.seteuid(0)
open('file3', 'wc')

rawDescription: Python: drop root privileges for certain operations


code:
class StaffInLineFormSet(forms.models.BaseInlineFormSet):
    def clean(self):
        count = 0
        for form in self.forms:
            try:
                if form.cleaned_data.get('is_team_coord') is True:
                    count += 1
            except AttributeError:
                pass
        if count == 0:
            raise forms.ValidationError('You must choose at least one Team Coordinator')

rawDescription: Django-admin validation on Foreign object


code:
def func(var1=False, var2=False, var3=False, var4=False, var5=False):
    pass

rawDescription: Initialize all variables to a common value except one TBD variable


code:
lo = heappop(tree)
hi = heappop(tree)

rawDescription: Huffman encoding issue

description: Huffman encoding issue


code:
import sys
import inspect
import os

class PluginBase(object): pass

def search(base):
    for root, dirs, files in os.walk('.'):
        candidates = [fname for fname in files if fname.endswith('.py')
                      and not fname.startswith('__')]
        classList=[]
        if candidates:
            for c in candidates:
                modname = os.path.splitext(c)[0]
                try:
                    module=__import__(modname)
                except (ImportError,NotImplementedError):
                    continue
                for cls in dir(module):
                    cls=getattr(module,cls)
                    if (inspect.isclass(cls)
                        and inspect.getmodule(cls)==module
                        and issubclass(cls,base)):
                        # print('found in {f}: {c}'.format(f=module.__name__,c=cls))
                        classList.append(cls)
        print(classList)

search(PluginBase)

rawDescription: Dynamic importing of modules followed by instantiation of objects with a certain baseclass from said modules


code: UsefulClass()

rawDescription: Only creating object through factory class in Python - factory class related


code:
from django.conf.urls import patterns, url

urlpatterns = patterns('',
    url(r'^(?P<name>\w+)/$', 'my_view'),)

rawDescription: Capturing objects in Django Url

description: Capturing objects in Django Url


code:
import numpy
from scipy.spatial.distance import pdist
D=2
N=3000
p=numpy.random.uniform(size=(N,D))
dist=pdist(p, 'euclidean')

rawDescription: Java vs. Python specific code-fragment performance improvement


code:
f = open('myfile','w')
f.write('hi there\n') # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call it

rawDescription: Correct way to write line to file in Python


code:
table = {i: chr(i) for i in xrange(i)}
table

rawDescription: Python (numpy) sort character order?

description: Python (numpy) sort character order


code:
set(['apple', '16', 'gb', '6', 'silver', 'iphone'])
set(['apple', '16', 'mobile', 'phone', 'gb', '6', 'gsm', 'silver', 'iphone'])
True

rawDescription: How to perform pattern matching between two strings?

description: Perform pattern matching between two strings


code:
colored_result = HTML.TableCell(new, bgcolor=color)
colored_result2 = HTML.TableCell(new, bgcolor='white')
t.rows.append([colored_result, colored_result2])

rawDescription: Trouble making a table with HTML.py in python


code:
from contextlib import contextmanager

@contextmanager
def foo(arg):
    print("entered foo({!r})".format(arg))
    yield
    print("exited foo({!r})".format(arg))

foo_deco_factory = Decontext(foo)

@foo_deco_factory("bar")
def baz(arg):
    print("called baz({!r})".format(arg))

baz("quux")

rawDescription: Passing arguments to decontext decorator


code:
item = [ structtype() for i in range(10)]
item[9].a = numpy.array([1,2,3])
item[9].a[1]

rawDescription: Complex matlab-like data structure in python (numpy/scipy)


code: print(" ".join(item))

rawDescription: How to make unique combinations of the following list of tuples

description: Make unique combinations of the following list of tuples


code:
my_functions = [A, B, C, D]

for function in my_functions:
    while flag == 0:
        function()

rawDescription: continued condition checking on a loop of functions

description: Continued condition checking on a loop of functions


code:
def sum_digits(number):
    reminder = 0
    while number:
        reminder += number%10
        number = number/10
    return reminder

num = __import__('math').factorial(10)
print(sum_digits(num))
27

rawDescription: usage of str() to convert number in int() in Python

description: Usage of str() to convert number in int() in Python


rawDescription: Writing 8 bit values to a binary file in python v3.3


code: out_text = out_bytes.decode('utf-8')

rawDescription: Redirect screen output to text file

description: Redirect screen output to text file


code:
import itertools

def combos(*seqs):
    counts = map(len, seqs)
    base = []
    for ii, count in enumerate(counts):
        base.extend([ii]*count)
    for take in set(itertools.permutations(base)):
        result = []
        where = [0] * len(seqs)
        for elem in take:
            result.append(seqs[elem][where[elem]])
            where[elem] += 1
        yield result

rawDescription: Merging 2 Lists In Multiple Ways - Python


code:
stu = []
inp = input('Students: ')
inp
type(inp)

rawDescription: Printing on new line - python

description: Printing on new line - python


code:
line1
line2
line3

rawDescription: Reading a specific line in a file

description: Reading a specific line in a file


code:
class myApp(object):
    @do_profile(DO_PROFILE)
    def foo_method(self, arg1):
        pass

    @do_profile(DO_PROFILE)
    def bar_method(self, arg2):
        pass

rawDescription: how can I profile class methods of my python app?

description: Profile class methods of my python app


code: connSqlServer = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=192.106.0.102\instance1;DATABASE=master;UID=sql2008;PWD=password123')

rawDescription: python pyodbc : how to connect to a specific instance

description: Python pyodbc : how to connect to a specific instance


code:
ciphertext = b'ciphertext'

blocks = [ciphertext[i:i+keylength] for i in range(0, len(ciphertext), keylength)]
# [b'cip', b'her', b'tex', b't']

transposed = [bytes(t) for t in zip_longest(*blocks, fillvalue=0)]
# [b'chtt', b'iee\x00', b'prx\x00']

rawDescription: Break bytes object into n equally sized blocks based on index


code:
from itertools import count
def postponed_sieveR(level=0,PData={}):
    '''recursive form of postponed_sieve
    modified from
    http://stackoverflow.com/a/10733621
    http://stackoverflow.com/a/19391111
    '''
    dat=PData.get(level,[0,0,0])#load any previous data
    #inital data is stored as [0, current_prime, starting_index]

    if not dat[0]:# handling the inital primes
        init=[2, 3, 5, 7]
        p,srt=dat[1:]
        i=srt

        if p<=7:
            for i,p in enumerate(init[srt:]):#start
                i+=srt#correct the index
                if STOP:
                    break
                yield p

                #to prevent getting caught constantly returning 7 after reloads
                if p==init[-1]:p+=2

        if STOP:# store the data
            Internals[level]=[0,p,i]
            return# no lower levels, so return

        D,C={},9
        ps=postponed_sieveR(level+1,PData)
        next(ps)
        p=next(ps)
        psq=p*p

    else:#past the inital primes, load from previous run
        D,C,psq,p=PData[level]
        ps=postponed_sieveR(level+1,PData)

    for i in count(C,2):

        if STOP:#set this outside of the generator

            #dict, current index (count value), squared prime and prime
            Internals[level]=[D,i,psq,p]
            w=next(ps)#call the next level down
            #(it will hit this if statement and stop before changing its data)
            break

        if i in D:
            step=D.pop(i)
        elif i<psq:
            yield i
            continue
        else:
            step=2*p
            p=next(ps)
            psq=p*p

        i+=step
        while i in D:
            i+=step
        D[i]=step

rawDescription: Pausable prime generator

description: Pausable prime generator


code: apply(map, [None] + result)

rawDescription: How do I convert apply(map, args) to map(function, iterable) in this case?

description: Convert apply(map, args) to map(function, iterable) in this case


code:
h1 = Heater()
h1.startlog(5)
h1.do_other_stuff()

rawDescription: Elegant way to add functionallity to previously defined functions


code: cursor.execute("SELECT foo FROM bar WHERE baz = '30%%' and id = %s", [self.id])

rawDescription: Calling DATE_FORMAT() in MySQL from Django fails


code: [seq[i:i+division+overlap] for i in range(0,n*division,division)]

rawDescription: Print out a large list from file into multiple sublists with overlapping sequences in python


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)

plt.show()

rawDescription: How to display only a left and bottom box border in matplotlib?

description: Display only a left and bottom box border in matplotlib


code:
for row_num in range(4):
    formula = '=IF(E{}>0,(G{}+H{})/E{},0)'.format(*([row_num + 1] * 4))

rawDescription: Python xlsxwriter: Adjust excel reference cells in loop when creating formula


code:
s = df.stack()
s
s[s >= 6]
s[s >= 6].index
s[s >= 6].index.tolist()

rawDescription: Extract indexes from Pandas DataFrame

description: Extract indexes from Pandas DataFrame


rawDescription: Mapping a table with a compound primary key to a python dictionary


code:
ls = ['one.two.three.four', 'one.six.seven.eight', 'five.nine.ten', 'twelve.zero']
tree = {}

for item in ls:
    t = tree
    for part in item.split('.'):
        t = t.setdefault(part, {})

rawDescription: convert a list of delimited strings to a tree/nested dict, using python

description: Convert a list of delimited strings to a tree/nested dict, using python


code:
freq = pd.crosstab(game_table['game_x'], game_table['game_y'])
# game_y  gameA  gameB  gameC  gameD
# game_x
# gameA       2      2      0      0
# gameB       2      2      0      0
# gameC       0      0      2      1
# gameD       0      0      1      1

rawDescription: Pandas: calculate overlapping with pivot_table or crosstab


code:
from django.core.files.images import ImageFile
img_file = open('path/to/file.jpg', 'rb')  # 'rb' --> read as bytes since image
django_wrapped_img = ImageFile(img_file)
User.objects.create(name='Nick Brady', headshot=django_wrapped_img)

rawDescription: Using django ImageField with Tastypie

description: Using django ImageField with Tastypie


code:
class Messages(db.Model):
    MessageId = db.Column(db.INTEGER, primary_key=True, autoincrement=True)
    SenderId = db.Column(db.INTEGER, db.ForeignKey('users.UserId'), nullable=False)
    ReceiverId = db.Column(db.INTEGER, db.ForeignKey('users.UserId'), nullable=False)
    Message = db.Column(db.String, nullable=False)

    # define relationships
    sender = db.relationship(Users, foreign_keys=[SenderId], backref='sent')
    receiver = db.relationship(Users, foreign_keys=[ReceiverId], backref='received')

rawDescription: Relationship between two tables one with 2 foreign keys in flask-sqlalchemy


code:
with open("save_file.txt") as f:
    for each_line in f:
        s = {}
        (s['name'], s['race'], s['class'], s['FOR'], s['INT'], s['DES']) = each_line.split(";")
        print(s['name'])
        print(s['race'])
        print(s['class'])
        print(s['FOR'])
        print(s['INT'])
        print(s['DES'])
        break  #<---

rawDescription: How to stop print lines?

description: Stop print lines


rawDescription: Filter with an else clause (numpy.where)


code: word = line.split()

rawDescription: python condition in function without_E not doing what is suppose to

description: Python condition in function without_E not doing what is suppose to


code:
my_tuple = (10, 20, 30)
my_shuffled_tuple = tuple(my_tuple[i] for i in new_positions)
my_shuffled_tuple

rawDescription: Permute a tuple by a list of indices

description: Permute a tuple by a list of indices


code:
M = g.reshape(g.shape+(1,)) - a.T.reshape((1,a.shape[1],a.shape[0]))
np.any(np.any(M == 0, axis=0), axis=1)
# returns:
# array([ True, False,  True,  True, False], dtype=bool)

rawDescription: Map numpy's `in1d` over 2D array

description: Map numpy's `in1d` over 2D array


code:
a = np.fromfile("qaz.mda", dtype=dt)
a

rawDescription: improve speed when reading a binary file

description: Improve speed when reading a binary file


code: SomeModel.objects.extra(select={'total_price': 'base_price + commission'})

rawDescription: How to calculate the total of two fields for each item in the queryset

description: Calculate the total of two fields for each item in the queryset


code:
with  open("clues.txt", 'r') as f, open("words.txt", 'r') as f2:
    clues = [list(line.rstrip()) for line in f]
    for line in f2:
        for rep, orig in clues:
            line = line.replace(orig, rep)
        print(line.rstrip())

rawDescription: Replace character(s) in list a with character from list b


code:
def countLetters(search_in, search_for):
    return sum(1 for s in search_in if s==search_for)

rawDescription: Exercise 7.9 in "How to Think Like a Computer Scientist (python)" measuring occurrences of a character in a string


code:
class Event:
  # stuff here

  @property
  def status(self):
     # do the same thing here as in your status function
     return status

rawDescription: Extra data about objects in django templates


code:
import json

articleContent = ClientCookie.urlopen(url)
data = json.load(articleContent)

rawDescription: Python - sending unicode characters (prefixed with \u) in an HTTP POST request


code:
namedict = dict(names)
genderdict = dict(genders)
[(namedict[id], genderdict[id]) for id in set(namedict) & set(genderdict)]

rawDescription: In python how can I match two lists of tuples by a tuple element?


code:
def slice_per(source, step):
    return [source[i::step] for i in range(step)]

rawDescription: How to Split Python list every Nth element

description: Split Python list every Nth element


code:
from pprint import pprint
A, B, C = 'ABC'
inputlist = [(A, 1, None),
 (B, 1, None),
 (C, 1, None),
 (A, 2, 1.1),
 (B, 2, 5.0),
 (C, 2, 5.0),
 (C, 3, 40),
 (B, 3, 55)]
values = {}
minlevel, maxlevel = float('inf'), float('-inf')
for id_, level, value in inputlist:
    values[id_, level] = value
    if level < minlevel:
        minlevel = level
    if level > maxlevel:
        maxlevel = level

def level_sort(tup):
    id_, level, value = tup
    sortkey = [level]
    for l in range(minlevel, maxlevel + 1):
        sortkey.append(values.get((id_, l)) if l >= level else None)
    return sortkey

pprint(sorted(inputlist, key=level_sort))

rawDescription: Python advanced list ordering

description: Python advanced list ordering


code:
def coroutine(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        runner = None
        future = TracebackFuture()

        if 'callback' in kwargs:
            callback = kwargs.pop('callback')
            IOLoop.current().add_future(
                future, lambda future: callback(future.result()))

        def handle_exception(typ, value, tb):
            try:
                if runner is not None and runner.handle_exception(typ, value, tb):
                    return True
            except Exception:
                typ, value, tb = sys.exc_info()
            future.set_exc_info((typ, value, tb))
            return True
        with ExceptionStackContext(handle_exception) as deactivate:
            try:
                result = func(*args, **kwargs)
            except (Return, StopIteration) as e:
                result = getattr(e, 'value', None)
            except Exception:
                deactivate()
                future.set_exc_info(sys.exc_info())
                return future
            else:
                if isinstance(result, types.GeneratorType):
                    def final_callback(value):
                        deactivate()
                        future.set_result(value)
                    runner = Runner(result, final_callback)
                    runner.run()
                    return future
            deactivate()
            future.set_result(result)
        return future
    return wrapper

rawDescription: Difference in tornado.gen.engine v/s tornado.gen.coroutine


code:
import re
import sys

def parse_doc_string(istr):
    pattern = re.compile(r'@(\w+)\s+(.*)')
    docstring = list()
    for line in map(lambda s : s.strip(), istr):
        if line == '/**':
            continue
        if line == '*/':
            return docstring
        line = line.lstrip('* ')
        match = pattern.match(line)
        if match:
            docstring.append((match.group(1), match.group(2)))

def extract(istr, docstrings):
    pattern = re.compile(r'^//\s*DocString:\s*(\w+)$')
    for line in map(lambda s : s.strip(), istr):
        match = pattern.match(line)
        if match:
            token = match.group(1)
            docstrings[token] = parse_doc_string(istr)

def format_doc_string(docstring):
    return '\n'.join('{}: {}'.format(k, v) for (k, v) in docstring)

def escape(string):
    return string.replace('\n', r'\n')

def substitute(istr, ostr, docstrings):
    pattern = re.compile(r'@DocString\((\w+)\)')
    for line in map(lambda s : s.rstrip(), istr):
        for match in pattern.finditer(line):
            token = match.group(1)
            docstring = format_doc_string(docstrings[token])
            line = line.replace(match.group(0), escape(docstring))
        print(line, file=ostr)

if __name__ == '__main__':
    sourcefile = sys.argv[1]
    docstrings = dict()
    with open(sourcefile) as istr:
        extract(istr, docstrings)
    with open(sourcefile) as istr:
        with sys.stdout as ostr:
            substitute(istr, ostr, docstrings)

rawDescription: How to avoid redundancy between c++ and boost::python docs?

description: Avoid redundancy between c++ and boost::python docs


code:
class SimpleRegionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Region
        fields = ('id', 'name')

rawDescription: Handling different levels of nesting in Django REST Framework


code:
import nltk

groucho_grammar = nltk.CFG.fromstring("""
S -> NP VP
PP -> P NP
NP -> Det N | Det N PP | 'I' | NUM N
VP -> V NP | VP PP
Det -> 'an' | 'my'
N -> 'elephant' | 'pajamas' | 'elephants'
V -> 'shot'
P -> 'in'
NUM -> '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9' | '10'
""")

sent = 'I shot 3 elephants'.split()
parser = nltk.ChartParser(groucho_grammar)
for tree in parser.parse(sent):
    print(tree)

rawDescription: How to match integers in NLTK CFG?

description: Match integers in NLTK CFG


code: wins = sorted(map(len, filter(None, seq.split("0"))))

rawDescription: Python longest/average 'losing' run in a sequence of binary digits in a string


code:
timeit(lambda: truncate(StringIO('abc' * 1000)))
timeit(lambda: new(StringIO('abc' * 1000)))

rawDescription: how do I clear a stringio object?

description: Clear a stringio object


code:
0
['foo\n', 'bar\n', 'baz']
True

rawDescription: creating stream to iterate over from string in Python

description: Creating stream to iterate over from string in Python


code: [x.span() for x in re.finditer('foo', 'foo foo foo foo')]

rawDescription: How to find all occurrences of a pattern and their indices in Python

description: Find all occurrences of a pattern and their indices in Python


code: arr = np.asarray(arr).ravel()

rawDescription: Python Passing List or Numpy Array

description: Python Passing List or Numpy Array


rawDescription: Sending javascript form data in python (post request)?


code:
def paths(tree, cur=()):
    if not tree:
        yield cur
    else:
        for n, s in tree.items():
            for path in paths(s, cur+(n,)):
                yield path

rawDescription: Generate all leaf-to-root paths in a dictionary tree in Python


code:
class Scm1:
    def __init__(self):
        self.keys = {'b':0, 'i':0, 's':0}

rawDescription: Python pickle load doesn't work when program is run again


code:
import csv, pprint

with open("file_1.csv") as fh:
    csv_reader = csv.reader ( fh )
    file_1_tuples = { tuple(row) for row in csv_reader }

with open("file_2.csv") as fh:
    csv_reader = csv.reader ( fh )
    matched_rows = [ row for row in csv_reader if (tuple(row[:3]) in file_1_tuples)]

pprint.pprint (matched_rows)

rawDescription: Compare entries in columns from CSV files and extract matched - python


code:
d = {}
with open(sys.argv[1]) as f:
    for line in f:
        if line[0].isalpha(): # is first character in the line a letter?
            curr = d.setdefault(line.strip(), [])
        elif filter(str.isdigit, line): # is there any digit in the line?
            curr.append(line.strip())

rawDescription: How to extract particular set of value from a file in Python?

description: Extract particular set of value from a file in Python