code:
app.on_insert_myendpoint += flat_to_complex
app.on_update_myendpoint += flat_to_complex

rawDescription: How can I insert records which have dicts and lists in Flask Eve?

description: Insert records which have dicts and lists in Flask Eve


code:
self.example = StringVar()
self.example.set("put what you want it to say at the start here")
#note put this before you make your entry
self.example_txt = Entry(self,textvariable = self.example)
self.example_txt.place(row = 1, column = 1)
#note iv purposely missed out class declaration ectra as i am assuming you already have that)

rawDescription: How to make pre initilized text appear in Tkinter Entry widget?/ How to set limit of number of same windows open?

description: Make pre initilized text appear in Tkinter Entry widget?/ How to set limit of number of same windows open


code: from datetime import datetime

rawDescription: Why python's monkeypatch doesn't work when importing a class instead of a module?


rawDescription: How to decode url to path in python, django

description: Decode url to path in python, django


code:
result = db_session.query(Data)
count = result.count()

for row in result.yield_per(10):
    update_progress_bar(progress, count)
    do_something_with_data(row)
    progress += 1

rawDescription: Geting results from database one by one

description: Geting results from database one by one


code:
headers = ["Resident Number", "Rent Date", "Customer number", "Rent ammount", "Ammount paid", "Outstanding Ammount"]

print("    ".join(headers))
for line in open("test.txt", "r"):
    line = line.strip().split(",")
    line.append(str(int(line[3]) - int(line[5])))
    if line[5] == line[3] or line[4] in ("N", "P"):
        continue
    for i, word in enumerate(line):
        if i == 4:
            continue
        print(word.ljust(len(headers[i - (i > 4)])), end="    " * ((i - (i > 4)) != len(headers) - 1))
    print()

rawDescription: Reading from a .txt file and printing in a table form


rawDescription: Add 24 hours to a negative time difference in python


code:
@app.url_value_preprocessor
def _is_valid_token(endpoint, values):
    if 'token' not in values:
        return

    if values['token'] != TOKEN:
        abort(400)

rawDescription: Auto validate a function parameter using a method


code:
@app.route("/<language>/<category>")
def mixin(language, category):
    links = []

    query = models.Post.select().where(
        (models.Post.language ** language) &
        (models.Post.category ** category))
    for contenido in query:
        links.append(contenido.content)

    iframe = random.choice(links)
    return render_template('language.html', iframe=iframe, language=language, category=category)

rawDescription: Routes filtering by Language and/or category


code: filtered_ls[:] = [x for x in ls if okay(x)]

rawDescription: Iterating through a list using for loops in Python3


code: ITEM_PIPELINES = [ 'myproject.pipeline.DropIfEmptyFieldPipeline', ]

rawDescription: remove scraped data with an empty value

description: Remove scraped data with an empty value


code:
months[1]
months[4]

rawDescription: date handling issue in Python

description: Date handling issue in Python


code:
f = Foo ()
b = Bar ()

f_msg = f.protected.get_message () # protected from failure
b_msg = b.protected.get_message () # protected from failure

b_msg = b.get_message ()           # will raise exception

rawDescription: How can I wrap an empty function to be implemented by a child class in a try-except block?

description: Wrap an empty function to be implemented by a child class in a try-except block


code:
col_ranges = df.max() - df.min()
df.loc[:,col_ranges == col_ranges.max()]

rawDescription: Pandas: Find the maximum range in all the columns of dataframe


code:
STATUSMAILER_RECIPIENTS = []
STATUSMAILER_COMPRESSION = 'gzip'
#STATUSMAILER_COMPRESSION = None

MAIL_HOST = 'smtp.gmail.com'
MAIL_PORT = 587
MAIL_USER = ''
MAIL_PASS = ''

rawDescription: Emailing items and logs with Scrapy

description: Emailing items and logs with Scrapy


code:
class SelfAttributesVisitor(ast.NodeVisitor):
    def __init__(self):
        self.attributes = []

    def visit_Attribute(self, node):
        if isinstance(node.value, ast.Name) and node.value.id == 'self':
            self.attributes.append(node.attr)
        else:
            self.visit(node.value)

rawDescription: python print variables of a specific line

description: Python print variables of a specific line


code:
echo.py
test.py
test.sh

rawDescription: How to make a python script "pipeable" in bash?

description: Make a python script "pipeable" in bash


code:
for (i1,int1),(i2,int2) in itertools.product(enumerate(Intervals1),enumerate(Intervals2)):
    if overlap(int1,int2):
        print(i1,i2)

rawDescription: Checking two time intervals are overlapping or not


code: M == N.max()

rawDescription: Python find list of surrounding neighbours of a node in 2D array


code: [list(map(int, x)) for x in values]

rawDescription: Python: One-liner to perform an operation upon elements in a 2d array (list of lists)?


code:
Setup
import pandas as pd
import numpy as np

np.random.seed([3,1415])
df = pd.DataFrame(np.random.rand(20, 2), columns=['A', 'B'])

rawDescription: Pandas' equivalent of resample for integer index


code:
import math
import numpy as np
import time
import sys
import multiprocessing as mp
import scipy.interpolate as interpolate

_tm=0
def stopwatch(msg=''):
    tm = time.time()
    global _tm
    if _tm==0: _tm = tm; return
    print("%s: %.2f seconds" % (msg, tm-_tm))
    _tm = tm

class BigData:
    def __init__(self, n):
        z = np.random.uniform(size=n*n*n).reshape((n,n,n))
        self.ff = []
        for i in range(n):
            f = interpolate.RectBivariateSpline(
                np.arange(n), np.arange(n), z[i], kx=1, ky=1)
            self.ff.append(f)
        self.n = n

    def do_chunk(self, k, xi, yi):
        n = self.n
        s = np.sum(np.exp(self.ff[k].ev(xi, yi)))
        sys.stderr.write(".")
        return s

    def do_chunk_of_chunks(self, k_start, k_end, xi, yi):
        s = sum(np.sum(np.exp(self.ff[k].ev(xi, yi)))
                    for k in range(k_start, k_end))
        sys.stderr.write(".")
        return s

    def do_multi(self, numproc, xi, yi):
        procs = []
        pool = mp.Pool(numproc)
        stopwatch('\nPool setup')
        ks = list(map(int, np.linspace(0, self.n, numproc+1)))
        for i in range(len(ks)-1):
            k_start, k_end = ks[i:i+2]
            p = pool.apply_async(_do_chunk_wrapper, (k_start, k_end, xi, yi))
            procs.append(p)
        stopwatch('Jobs queued (%d processes)' % numproc)
        total = 0.0
        for k, p in enumerate(procs):
            total += np.sum(p.get(timeout=30)) # timeout allows ctrl-C interrupt
            if k == 0: stopwatch("\nFirst get() done")
        print(total)
        stopwatch('Jobs done')
        pool.close()
        pool.join()
        return total

    def do_single(self, xi, yi):
        total = 0.0
        for k in range(self.n):
            total += self.do_chunk(k, xi, yi)
        stopwatch('\nAll in single process')
        return total

def _do_chunk_wrapper(k_start, k_end, xi, yi):
    return bd.do_chunk_of_chunks(k_start, k_end, xi, yi)

if __name__ == "__main__":
    stopwatch()
    n = 50
    bd = BigData(n)
    m = 1000*1000
    xi, yi = np.random.uniform(0, n, size=m*2).reshape((2,m))
    stopwatch('Initialized')
    bd.do_multi(2, xi, yi)
    bd.do_multi(3, xi, yi)
    bd.do_single(xi, yi)

rawDescription: Minimize overhead in Python multiprocessing.Pool with numpy/scipy


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

x = np.linspace(0, 10, 100)
y = np.sin(x)

fig, ax = plt.subplots()
line, = ax.plot(x, y, color='k')

for n in range(len(x)):
    line.set_data(x[:n], y[:n])
    ax.axis([0, 10, 0, 1])
    fig.canvas.draw()
    fig.savefig('Frame%03d.png' %n)

rawDescription: Animating "growing" line plot in Python/Matplotlib


code:
def round(x):
    n, remainder = divmod(x, 10)
    if remainder >= 5:
        n += 1
    return n * 10

rawDescription: Round integer in python without using round()


rawDescription: Create CSR matrix from x_index, y_index, value


code: random.choice([a for a in agents if a.state == 0])

rawDescription: Selecting random elements in a list conditional on attribute


code: [num*2 for num in numbers]

rawDescription: Python: How to combine the results of for loop into one output?


code:
class Counter:
    def __init__(self, n):
        self.n = n
    def __call__(self):
        self.n += 1
        return self.n

rawDescription: lambda in python

description: Lambda in python


code:
if any(c not in message for c in ('CondA', 'CondB', ...)):
    ...

rawDescription: How to simplify multiple conditions in Python

description: Simplify multiple conditions in Python


code:
with open(file, mode) as f:
    do_something_with(f)

rawDescription: Open/write deleting txt file contents?

description: Open/write deleting txt file contents


rawDescription: Flatten a column with value of type list while duplicating the other column's value accordingly in Pandas


code:
def fill_zeros_with_last(arr):
    prev = np.arange(len(arr))
    prev[arr == 0] = 0
    prev = np.maximum.accumulate(prev)
    return arr[prev]

rawDescription: Fill zero values of 1d numpy array with last non-zero values


code:
import pyparsing
from pyparsing import ZeroOrMore, Group

OP_EQ   = pyparsing.Literal('=').suppress()
DQUOTE  = pyparsing.Literal('"').suppress()
ESPACE  = pyparsing.Literal('\\ ').suppress().leaveWhitespace()
BSLASH  = pyparsing.Literal('\\')

S       = pyparsing.Word(" \t\r\n").suppress().leaveWhitespace()

DELIM   = ZeroOrMore(S ^ BSLASH).suppress()

KEY     = pyparsing.Word(pyparsing.alphanums)("KEY")

VALTOK  = pyparsing.Word(pyparsing.printables, excludeChars='="\\')

QVALUE  = ( DQUOTE +
            Group(VALTOK + ZeroOrMore(S + VALTOK)) +
            DQUOTE
            )
NQVALUE = Group(VALTOK + ZeroOrMore(ESPACE + VALTOK))
VALUE   = (NQVALUE ^ QVALUE)("VALUE")

PAIR    = Group(KEY + OP_EQ + VALUE)("PAIR")

PAIRS   = (PAIR + ZeroOrMore(DELIM + PAIR))

with open('input.txt') as f:
    lines = f.read()

res = PAIRS.parseString(lines, parseAll=True)

for (k,v) in res:
    print('{} = "{}"'.format(k, ' '.join(v)))

rawDescription: PyParsing: shell style space escape using backslash


code:
import math
for letter in dic:
    for element in l1:
        if letter in element:
            result.append(dic[letter]**2 * element.count(letter))
return math.sqrt(sum(result))

rawDescription: mapping dictionary items and normalize them

description: Mapping dictionary items and normalize them


code:
import pandas as pd
df = pd.DataFrame([[1,0,0,0], [0,0,1,0]])
df

rawDescription: Delete Column in Pandas based on Condition


rawDescription: generating random values based on condition in structured array python

description: Generating random values based on condition in structured array python


rawDescription: Python - Removing overlapping lists

description: Python - Removing overlapping lists


code:
tups = [
    ('a1',['b1','b2','b3']),
    ('a2',['b2']),
    ('a3',['b1','b2'])
]

d = collections.defaultdict(list)
for a, bs in tups:
    for b in bs:
        d[b].append(a)

rawDescription: List of tuples from (a, all b) to (b, all a)


rawDescription: Python colorbar ticks are labeled with an offset of +1 and not with specifed values


code:
regex = r'''
(@[a-z][a-z0-9_]*) # function name, captured in group
(                  # open capture group for all parameters
\(                 # opening function parenthesis
  (?!,)            # negative lookahead for unwanted comma
  (?:              # open non-capturing group for all params
  [a-z][a-z0-9_]*  # parameter name
  =                # parameter assignmentoperators
  (?:"[a-z0-9_, ]*"|true|false|(?:\d+l?)) # possible parameter values
  (?!,\))          # negative lookahead for unwanted comma and closing parenthesis
  ,?               # optional comma, separating params
  )*               # close param non-capturing group, make it optional
\)                 # closing function parenthesis
(?!\(\))           # negative lookahead for empty parentheses
|$                 # OR end-of-line (in case there are no params)
)                  # close capture group for all parameters
'''

rawDescription: Python regex for Java annotations

description: Python regex for Java annotations


rawDescription: how do i rewrite this function to implement OrderedDict?

description: Rewrite this function to implement OrderedDict


code:
def parse_bin(s):
    return int(s[1:], 2) / 2.**(len(s) - 1)

rawDescription: How to convert a string representing a binary fraction to a number in Python

description: Convert a string representing a binary fraction to a number in Python


code: question = lst.pop()

rawDescription: Pick a random variable then have it become unavailable to be chosen again in Python?


code:
if __debug__:
    from ipdp import set_trace
else:
    def set_trace(): return

rawDescription: Does importing a module (but not using it) decrease performance in Python?


code:
import collections

Stats = collections.namedtuple("Stats", "speed weight acceleration handling drift offroad turbo")

rawDescription: What is an elegant way to solve this max and min problem in Ruby or Python?


rawDescription: Efficient storage of large string column in pandas dataframe


code:
class old_style:
    def __init__(self):
       pass

class new_style(object):
    def __init__(self):
        pass

old_style_instance1 = old_style()
old_style_instance2 = old_style()
new_style_instance1 = new_style()
new_style_instance2 = new_style()

type(old_style_instance1) == type(old_style_instance2)

rawDescription: Why do I need to pass an object to this class to make it work?


code:
class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    addresses = db.relationship('Address', backref='person',
                                lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    email = db.Column(db.String(50))
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

rawDescription: One to many SQL relationship

description: One to many SQL relationship


code:
frame = driver.find_element_by_id("fm2")
driver.switch_to.frame(frame)

driver.switch_to.frame("contentFrame")

rawDescription: Selenium Webdriver give NoSuchFrameException


code:
class UserEventsFilter(QtCore.QObject):
    """
    Reference: http://stackoverflow.com/a/2017400/1011276
    """
    def __init__(self, parent=None):
        super().__init__(parent)

        self.filterEnabled = False

    @QtCore.Slot()
    def enableFilter(self):
        self.filterEnabled = True

    @QtCore.Slot()
    def disableFilter(self):
        self.filterEnabled = False

    def eventFilter(self, obj, event):
        if self.filterEnabled:
            t = event.type()
            if (t == QtCore.QEvent.KeyPress or
                t == QtCore.QEvent.KeyRelease or
                t == QtCore.QEvent.MouseButtonPress or
                t == QtCore.QEvent.MouseButtonDblClick or
                t == QtCore.QEvent.MouseMove or
                t == QtCore.QEvent.Enter or
                t == QtCore.QEvent.HoverEnter or
                t == QtCore.QEvent.HoverLeave or
                t == QtCore.QEvent.HoverMove or
                t == QtCore.QEvent.DragEnter or
                t == QtCore.QEvent.DragLeave or
                t == QtCore.QEvent.DragMove or
                t == QtCore.QEvent.Drop):
                return True
        return QtCore.QObject.eventFilter(self, obj, event)

rawDescription: QProgressDialog not modal before minimum duration


rawDescription: Change elements in 2d ndarray into arrays


rawDescription: Add an offset to part of a list in Python?


code:
def flattened_list_and_sublists(l):
    # First return value is l, flattened.
    # Second return value is a list of flattened forms of all nested sublists
    # of l.

    flattened = []
    flattened_sublists = []

    for i in l:
        if isinstance(i, list):
            i_flattened, i_flattened_sublists = flattened_list_and_sublists(i)
            flattened += i_flattened
            flattened_sublists.append(i_flattened)
            flattened_sublists += i_flattened_sublists
        else:
            flattened.append(i)
    return flattened, flattened_sublists

rawDescription: Python extract all sublists from a nested list


rawDescription: Copy and Write XML Node in Python

description: Copy and Write XML Node in Python


code:
text = [
    ["Ah!",  "We do have\nsome Camembert", "sir"],
    ["It's a bit", "runny", "sir"],
    ["Well,",  "as a matter\nof fact it's", "very runny,\nsir"],
    ["I think it's\nrunnier",  "than you",  "like it,\nsir"]
]

from itertools import chain, izip_longest

matrix = chain.from_iterable(
    izip_longest(
        *(x.splitlines() for x in y),
        fillvalue='')
    for y in text)

rawDescription: Pretty print 2D Python list

description: Pretty print 2D Python list


code: subprocess.call(['php', '-f', '/path/to/sort.php', result])

rawDescription: python calling command issue

description: Python calling command issue


code:
def getWithoutCommonElements(a, b): # Name subject to change
    a2 = a.copy()
    b2 = b.copy()
    for e in a:
        if e not in b:
            a2.remove(e)
            b2.remove(e)
    return a2, b2

rawDescription: Removing common elements in two lists

description: Removing common elements in two lists


code:
def showClassification(self ):
    self.stackedWidget.setCurrentIndex(3)
    self.classification.chooseWidget.reload()

rawDescription: How to connect to parent SIGNAL in PyQt?

description: Connect to parent SIGNAL in PyQt


code:
import pickle
pickle.dump(operators, open("operators", "wb"))

rawDescription: How to properly pass text file to search the data there?

description: Properly pass text file to search the data there


rawDescription: How to find the list in a list of lists whose sum of elements is the greatest?

description: Find the list in a list of lists whose sum of elements is the greatest


code:
from dateutils import parser
parser.parse('January 12, 2012').strftime('%s')
parser.parse('01/12/2012').strftime('%s')
parser.parse('Sunday, 16/09/2012').strftime('%s')

rawDescription: Temporal Expression recognition in Python


rawDescription: Python: Mean of several dictionaries with the same keys


code:
from heapq import nlargest
top_30 = nlargest(30, my_list, key=lambda x: x['y_time'])

rawDescription: For a list containing dictionary objects, how do I filter the list based on the value of a key?


code: timeit.timeit('permutation(138)[:4]', setup='from numpy.random import permutation', number=1000000)

rawDescription: Time performance of np.random.permutation, np.random.choice


code:
df[df.loc[:, ['Value1', 'Value2', 'Value3']].apply(pd.notnull).all(1)]
df = df[df.loc[:, ['Value1', 'Value2', 'Value3']].apply(pd.notnull).all(1)]

rawDescription: Skipping rows in a csv file using Python Pandas


code:
class TestMyTest(unittest.TestCase):
    def test_example(self):
        a = 'a'
        b = 'b'
        self.assertEqual(a, b, 'a did not equal b')

rawDescription: python unittests assertEqual print too much when it fails

description: Python unittests assertEqual print too much when it fails


code:
y = np.around(x, decimals = 3)
y

rawDescription: Rounding numpy float array read from img with python, values returned not rounded


code: text = re.sub(r'statt \d+,\d+ â‚¬ nur ', '', text)

rawDescription: How to select a string of variable length but with fixed beginning and ending?

description: Select a string of variable length but with fixed beginning and ending


code:
from bisect import bisect_left
def f3(t, x):
    i = bisect_left(t, x)
    if t[i] - x > 0.5:
        i-=1
    return i

rawDescription: Python/Numpy - Quickly Find the Index in an Array Closest to Some Value


rawDescription: How to set up and solve simultaneous equations in python

description: Set up and solve simultaneous equations in python


code:
df[0].fillna(np.Inf, inplace=True)
df2 = pd.concat([df[col] for col in df], axis=0)
df2.dropna(inplace=True)
df2[df2 == np.Inf] = np.NaN

rawDescription: Unrolling / expanding a dictionary of iterables into a dataframe


code:
for tr in subpage.cssselect('tr.nob-border'):
    tr.xpath(""" set:difference(following-sibling::tr[not(contains(@class, "nob-border"))],
                                following-sibling::tr[contains(@class, "nob-border")]
                                                   /following-sibling::tr)""",
             namespaces={"set": "http://exslt.org/sets"})

rawDescription: Selecting siblings from html with Python lxml(html) library


code:
dfs = { i: df.loc[df['title'].str.contains(i, case=False),'id'].tolist() for i in li }

print (dfs['Sensor'])
[3, 4]
print (dfs['0x024'])
[1, 4]

rawDescription: How to find duplicate words in a line using pandas?

description: Find duplicate words in a line using pandas


code: import itertools, operator

rawDescription: How Can I: Generate 40/64 Bit WEP Key In Python?


code:
for hay in haystack:
  if needle in hay:
    return hay

rawDescription: Python finding a value in a list of lists


code:
from datetime import datetime
original = '23/Oct/2014'
datetime.strptime(original, '%d/%b/%Y').strftime('%Y/%m/%d')

rawDescription: Converting 23/Oct/2014 to 2014/10/23 in Python


rawDescription: How to get the index with the key in Python dictionary?

description: Get the index with the key in Python dictionary


code:
from collections import OrderedDict

# replace existing pages dict with a new one maintaining ordering
pages = {page_id: OrderedDict() for page_id in pages}

for supporter in combined_supporters:
    page_id = supporter.pop('page_id')
    pages[page_id][supporter['profile_id']] = supporter

rawDescription: Re-mapping a sorted list into a dictionary


code:
def __init__(self, attr1, attr2):
    Base.__init__(self, attr1)
    self.attr2 = attr2

rawDescription: What is the practical use of the keyword super in Python inheritance?


code:
if data.find("s") is not None:
    gender = data.find("s").text
else:
    gender = "?"

rawDescription: Chatango xml parsing in python

description: Chatango xml parsing in python


code: some_name = BooleanColumn(yesno='1,2')

rawDescription: django-tables2 edit yesno parameter for all BooleanColumn

description: Django-tables2 edit yesno parameter for all BooleanColumn


rawDescription: Odd values_list and filter behavior in Django


code:
def accepts(*types):
    def check_accepts(f):
        assert len(types) == f.func_code.co_argcount
        def new_f(*args, **kwds):
            for (a, t) in zip(args, types):
                assert isinstance(a, t), \
                       "arg %r does not match %s" % (a,t)
            return f(*args, **kwds)
        new_f.func_name = f.func_name
        return new_f
    return check_accepts

rawDescription: How to use Python decorators to check function arguments?

description: Use Python decorators to check function arguments


rawDescription: Merge Dictionaries with different TimeStamp


code: [ p for p in database if (p.x, p.y, p.z) == ( 1, 2, 3 ) ]

rawDescription: Storing information on points in a 3d space


code:
class Sentence(object):
    def __init__(self, the_sentence):
        pass

sentence = Sentence("This is a sentence.")
sentence.the_string = "This is a different sentence."

rawDescription: Storing a string into a property

description: Storing a string into a property


code:
from bs4 import BeautifulSoup
content = "
some text
 \
        Text blah5454"
soup = BeautifulSoup(content)
soup("a", text='Text')
soup("a", text=re.compile(r"\bText\b"))

rawDescription: How to strip characters interfering with Beautiful Soup returning links with specified text?

description: Strip characters interfering with Beautiful Soup returning links with specified text


code:
A = [['Yes', 'No'], ['Yes', 'Idontknow'], ['No', 'Yes'], ['No', 'Idontknow']]
['Yes', 'No'] in A

rawDescription: How to use sets in Python to find list membership?

description: Use sets in Python to find list membership


code:
CITIES = (
    (0, 'London'),
    (1, 'New York'),
    (2, 'Moscow'),
)

class Office(models.Model):
    room = models.CharField(max_length=3)
    phone = models.CharField(max_length=8)
    city = models.CharField(choices=CITIES)

rawDescription: What to do with model general attributes in django models?


code: df[df['some_column'] != "Not found"]

rawDescription: Excluding pandas rows based on a String value


rawDescription: Get values from multiple entries after entry duplication


code:
#!/usr/bin/env python
from collections import Counter
from itertools import izip_longest

strings = ['foo_a', 'foo_b','foo_c','fnord']
assert len(strings) > 1
threshold = len(strings)
prefix = []
prefixes = []
for chars in izip_longest(*strings, fillvalue=''):
    char, count = Counter(chars).most_common(1)[0]
    if count == 1:
        break
    elif count < threshold:
        if prefix:
            prefixes.append((''.join(prefix), threshold))
        threshold = count
    prefix.append(char)
if prefix:
    prefixes.append((''.join(prefix), threshold))
print(prefixes)
# -> [('f', 4), ('foo_', 3)]

rawDescription: Find *most* common prefix of strings - a better way?


code:
# NEVER DO THIS
cur.execute("SELECT * FROM list WHERE InstitutionName='%s'" % (Variable,))

rawDescription: Searching SQLite Database with Python Variables


rawDescription: python pandas converting dataframe(s) to lists

description: Python pandas converting dataframe(s) to lists


rawDescription: Pattern-matching algorithm for lists

description: Pattern-matching algorithm for lists


code:
class Property(models.Model):
  owner = models.ForeignKey(Company)

rawDescription: What is the best solution for multi tenancy in Django?


code: normed_data = (data - data.mean()) / data.std()    # this is NOT okay

rawDescription: Implementing a Kolmogorov Smirnov test in python scipy


code:
def unq_searchsorted(A,B):

    # Get unique elements of A and B and the indices based on the uniqueness
    unqA,idx1 = np.unique(A,return_inverse=True)
    unqB,idx2 = np.unique(B,return_inverse=True)

    # Create mask equivalent to np.in1d(A,B) and np.in1d(B,A) for unique elements
    mask1 = (np.searchsorted(unqB,unqA,'right') - np.searchsorted(unqB,unqA,'left'))==1
    mask2 = (np.searchsorted(unqA,unqB,'right') - np.searchsorted(unqA,unqB,'left'))==1

    # Map back to all non-unique indices to get equivalent of np.in1d(A,B),
    # np.in1d(B,A) results for non-unique elements
    return mask1[idx1],mask2[idx2]

rawDescription: Find indices of common values in two arrays


code:
o4 = O4()
o4.method()
o4.var
o4.__dict__["var"]

rawDescription: Confused with getattribute and setattribute in python


code: clf.predict(['Bruce Campbell', 'Sarah Roemer'])

rawDescription: How to store predicted classes matching the pre-vectorized X in Python Scikit-learn?

description: Store predicted classes matching the pre-vectorized X in Python Scikit-learn


code:
import http.server
import socketserver

PORT = 8000
handler = http.server.SimpleHTTPRequestHandler

httpd = socketserver.TCPServer(("", PORT), handler)

print("serving at port", PORT)
httpd.serve_forever()

rawDescription: Creating a WebSocket Client in Python

description: Creating a WebSocket Client in Python


code:
interp = tkinter.Tcl()
myvar = tkinter.StringVar()

def pydict2tcldict(d):
    return tkinter._stringify(list(d.items()))

d = {'num': 10000, 'time': 10000, 'rate': 10}
myvar.set(pydict2tcldict(d))

interp.eval("""source {myscript.tcl}
               myproc $%s""" % myvar._name)

rawDescription: Pass Python variables to `Tkinter.Tcl().eval()`


code:
a
1 - a

rawDescription: Matlab / Octave bwdist() in Python or C

description: Matlab / Octave bwdist() in Python or C


code:
infile = open("inpu.txt", 'r') # open file for reading
outfile = open("output.txt","a") # open file for appending

line = infile.readline()    # Invokes readline() method on file
while line:
  outfile.write(line.strip("\n")+" 1\n")
  line = infile.readline()

infile.close()
outfile.close()

rawDescription: Writing a value to an existing file repeatedly


code:
class B:

    def __init__(self):
        self.data = []

    def update(self, row):
        for r in row:
            self.data.append(r)

    def finalize(self):
        return np.reshape(self.data, newshape=(len(self.data)/5, 5))

rawDescription: Fastest way to grow a numpy numeric array


rawDescription: How to get a graph axis into standard form

description: Get a graph axis into standard form


code:
@classmethod
def get(cls, uid):
    ldap_data = LdapUtil.get(uid + ',' + self.base_dn)
    return cls._from_ldap(ldap_data)

rawDescription: How do you cast an instance to a derived class?

description: Cast an instance to a derived class


code:
import os
os.system('bash -i -c "alias"')

rawDescription: How to show user aliases in python

description: Show user aliases in python


code:
import pygtk
pygtk.require('2.0')
import gtk

clipboard = gtk.clipboard_get()

clipboard.set_text('Hello, World')
clipboard.store()

rawDescription: Is there a way to directly send a python output to clipboard?


code:
def uniq(base, l):
    # function used to replace all values with the base
    nl = []
    for i in l:
        if type(i) is list:
            nl.append(uniq(base, i)) # recursion for deep lists
        else:
            nl.append(base)
    return nl

rawDescription: More elegant way to initialize list of duplicated items in Python


code:
members = db.Table('members',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
    db.Column('group_id', db.Integer, db.ForeignKey('groups.id'))
)

class Groups(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(1000))
    members = db.relationship('User', secondary=members, backref=db.backref('group', lazy='dynamic'))

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)

rawDescription: many to many relationship with three tables (sql-alchemy)

description: Many to many relationship with three tables (sql-alchemy)


code:
"""
zoom : float or sequence, optional
    The zoom factor along the axes. If a float, `zoom` is the same for each
    axis. If a sequence, `zoom` should contain one value for each axis.
"""

rawDescription: Resizing a 3D image (and resampling)

description: Resizing a 3D image (and resampling)


rawDescription: How to refresh the window with Tkinter

description: Refresh the window with Tkinter


code: numpy.all(rolling_window(a, 3) == [8, 4, 0], axis=1)

rawDescription: Python/NumPy first occurrence of subarray


code:
import pandas as pd

df = pd.read_csv('wordlist.csv')
dictionary = {}

for w, s, m, p in zip(df.words, df.meaning):
    dictionary[w] = [m, p]

rawDescription: Creating a dictionary

description: Creating a dictionary


code:
class ball(object):
  def __init__(self, size, color, name):
    self.size = size
    self.color = color
    self.name = name

rawDescription: python getting a specific attribute from a list of objects

description: Python getting a specific attribute from a list of objects


code:
class EggAdmin(admin.ModelAdmin):
    ...
    def queryset(self, request):
        kitchen = request.user.superprofile_set.get().my_kitchen #get related users kitchen
        qs = super(EggAdmin, self).queryset(request) #call original queryset method that you are overriding
        return qs.filter(kitchens=kitchen) #apply your filter

rawDescription: Filter query based on user in Django Admin


code:
names = ["name1", "name2"]
ids = ["id1", "id2"]
dtypes = ["type1", "type2"]

downloadData(names, ids, dtypes)

rawDescription: Run 3 variables at once in a python for loop.


code: custom_action_view = views.MyApiView.as_view({"post": "custom_action"})

rawDescription: Django-rest-framework @detail_route for specific url


code:
#...
f = open("t.txt")
lines = f.readlines()
f.close()

basicfont = pygame.font.SysFont(None, 48)
text = basicfont.render('Hello World!', True, (255, 0, 0), (255, 255, 255))
textrect = text.get_rect()
textrect.centerx = screen.get_rect().centerx
textrect.centery = screen.get_rect().centery

screen.fill((255, 255, 255))
for i in lines:
    # each i has a newline character, so by i[:-1] we will get rid of it
    text = basicfont.render(i[:-1], True, (255, 0, 0), (255, 255, 255))
    # by changing the y coordinate each i from lines will appear just
    # below the previous i
    textrect.centery += 50
    screen.blit(text, textrect)
#...

rawDescription: Pygame: Writing Multiple Lines

description: Pygame: Writing Multiple Lines


code:
from BeautifulSoup import BeautifulSoup
html_decoded_string = BeautifulSoup(html_encoded_string, convertEntities=BeautifulSoup.HTML_ENTITIES)

rawDescription: How can I use Python to replace HTML escape characters?

description: Use Python to replace HTML escape characters


code:
from itertools import product

def count_squares(A):
    width, height = len(A[0]), len(A)
    indices = product(range(width - 1), range(height - 1))
    is_square = lambda x, y: all(A[a][b] == 1 for a, b in product((x, x + 1), (y, y + 1)))
    return sum(1 for x, y in indices if is_square(x, y))

rawDescription: counting 2*2 squares in n*n binary matrix

description: Counting 2*2 squares in n*n binary matrix


code:
def processScores(file, score):
    with open(file, 'r') as f:
        for line in f:
            if line[0] == 'G':
                amount = int(next(f)) # read next line & convert to integer
                score.UpdateOne(amount)

rawDescription: reading a file, taking file line content, then using content as parameters for class method definitions Python

description: Reading a file, taking file line content, then using content as parameters for class method definitions Python


code: comptest('test')

rawDescription: Python - Compress Ascii String

description: Python - Compress Ascii String


rawDescription: Dealing with mis-escaped characters in JSON


rawDescription: wxPython : How do I shrink the size of Button to the width of the label text?

description: WxPython : How do I shrink the size of Button to the width of the label text


code: bb = aa[:,np.arange(N),permutations.T]

rawDescription: Select values from a set of arrays according to an array of permutations


code: array_collect[m] = array_a

rawDescription: how to transfer an numpy array into another array

description: Transfer an numpy array into another array


code:
total = {}
for subject in subjects:
    total[subject] = marks1[subject] + marks2[subject] + marks3[subject] + marks4[subject] + marks5[subject] + marks6[subject] + marks7[subject] + marks8[subject] + marks9[subject] + marks10[subject]

rawDescription: How to add more than 2 dictionaries together in python

description: Add more than 2 dictionaries together in python


code:
import datetime
constant_now = datetime.datetime(2009,8,7,6,5,4)
old_datetime_class = datetime.datetime
class new_datetime(datetime.datetime):
    @staticmethod
    def now():
        return constant_now

datetime.datetime = new_datetime

rawDescription: Dictionaries with volatile values in Python unit tests?


code: [[list(x) for x in zip(*sublist)] for sublist in List ]

rawDescription: Python reorder lists inside lists

description: Python reorder lists inside lists


code:
#!/usr/bin/env python3

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtNetwork import *

PORT = 9999
SIZEOF_UINT32 = 4

class ServerDlg(QPushButton):

    def __init__(self, parent=None):
        super(ServerDlg, self).__init__(
                "&Close Server", parent)
        self.setWindowFlags(Qt.WindowStaysOnTopHint)

        self.tcpServer = QTcpServer(self)
        self.tcpServer.listen(QHostAddress("0.0.0.0"), PORT)
        self.connect(self.tcpServer, SIGNAL("newConnection()"),
                    self.addConnection)
        self.connections = []

        self.connect(self, SIGNAL("clicked()"), self.close)
        font = self.font()
        font.setPointSize(24)
        self.setFont(font)
        self.setWindowTitle("Server")

    def addConnection(self):
        clientConnection = self.tcpServer.nextPendingConnection()
        clientConnection.nextBlockSize = 0
        self.connections.append(clientConnection)

        self.connect(clientConnection, SIGNAL("readyRead()"),
                self.receiveMessage)
        self.connect(clientConnection, SIGNAL("disconnected()"),
                self.removeConnection)
        self.connect(clientConnection, SIGNAL("error()"),
                self.socketError)

    def receiveMessage(self):
        for s in self.connections:
            if s.bytesAvailable() > 0:
                stream = QDataStream(s)
                stream.setVersion(QDataStream.Qt_4_2)

                if s.nextBlockSize == 0:
                    if s.bytesAvailable() < SIZEOF_UINT32:
                        return
                    s.nextBlockSize = stream.readUInt32()
                if s.bytesAvailable() < s.nextBlockSize:
                    return

                textFromClient = stream.readQString()
                s.nextBlockSize = 0
                self.sendMessage(textFromClient,
                                 s.socketDescriptor())
                s.nextBlockSize = 0

    def sendMessage(self, text, socketId):
        for s in self.connections:
            if s.socketDescriptor() == socketId:
                message = "You> {}".format(text)
            else:
                message = "{}> {}".format(socketId, text)
            reply = QByteArray()
            stream = QDataStream(reply, QIODevice.WriteOnly)
            stream.setVersion(QDataStream.Qt_4_2)
            stream.writeUInt32(0)
            stream.writeQString(message)
            stream.device().seek(0)
            stream.writeUInt32(reply.size() - SIZEOF_UINT32)
            s.write(reply)

    def removeConnection(self):
        pass

    def socketError(self):
        pass

app = QApplication(sys.argv)
form = ServerDlg()
form.show()
form.move(0, 0)
app.exec_()

rawDescription: PyQt QTcpServer: How to return data to multiple clients?


rawDescription: Parsing JSON string from python to Javascript


code:
theFunction = None
if (isTheWorldRound):
    return Bar
else:
    return [Bar, Foo]

rawDescription: Adding lines to a function

description: Adding lines to a function


code:
from tkinter import *
from time import sleep

root = Tk()
var = StringVar()
var.set('hello')

l = Label(root, textvariable = var)
l.pack()

for i in range(6):
    sleep(1) # Need this to slow the changes down
    var.set('goodbye' if i%2 else 'hello')
    root.update_idletasks()

rawDescription: Update Tkinter Label from variable

description: Update Tkinter Label from variable


code:
alaska
arizona
arkansas
georgia

rawDescription: Sorting out rows in a csv not working as planned


rawDescription: Theano element wise maximum

description: Theano element wise maximum


rawDescription: Add only the first value in my list of arrays


rawDescription: How do I search for multiple identical keys in a dictionary? (Python3)

description: Search for multiple identical keys in a dictionary? (Python3)


code:
df["Order"] = df.groupby("PersonID").cumcount() + 1
df

rawDescription: How can I do a sequential count based on column value and timestamp in pandas?

description: Do a sequential count based on column value and timestamp in pandas


code:
first = list(itertools.takewhile(str.isalpha, l))
second = list(itertools.dropwhile(str.isalpha, l))
first
second

rawDescription: how to split a list in two at the point where predicate is first False

description: Split a list in two at the point where predicate is first False


code:
R = np.random.RandomState(3)
R
R.rand()
R.randint(10**3, 10**4)

rawDescription: How to use random.RandomState

description: Use random.RandomState


code:
Container = namedtuple('Container', ['name', 'date', 'foo', 'bar'])

mycontainer = Container(name, date, foo, bar)

rawDescription: When and why should I use a namedtuple instead of a dictionary?


rawDescription: What's the simplest way to extend a numpy array in 2 dimensions?


rawDescription: Difference between having and not having parenthesis in if statements


rawDescription: Pandas group by time windows

description: Pandas group by time windows


code:
za = re.compile('z\w')
za.sub(lambda m: dict(za='BLU', zo='BLA')[m.group()], 'fa za zo bu')

rawDescription: Can you pass a dictionary when replacing strings in Python?

description: Pass a dictionary when replacing strings in Python


code:
new_x = F * x
position = H * x

rawDescription: kalman 2d filter in python

description: Kalman 2d filter in python


code:
# => cd test-scons
# => ls
#    build/  SConstruct  subdir/
# => scons echo
#    scons: Building targets ...
#    echo HOME/test-scons/build/subdir
#    HOME/test-scons/build/subdir
#    scons: done building targets.

rawDescription: Determining Build Directory from SConscript


code:
def merge_dicts2(list_of_dicts):
    results = {}
    for d in list_of_dicts:
        key = (d['type'], d['obj_id'])
        try:
            results[key][0].append(d['actor'])
        except KeyError:
            results[key] = ([d['actor']], d['extra_fields'])

    return results

rawDescription: Grouping data in a list of of dicts

description: Grouping data in a list of of dicts


code:
def butter_bandpass(lowcut,highcut,fs,order=8):
    nyq = 0.5*fs
    low = lowcut/nyq
    high = highcut/nyq

    b,a = butter(order, [low, high], btype='band')
    return b,a

def butter_bandpass_filter(data, *args, **kwargs):
    b,a = butter_bandpass(*args, **kwargs)
    return lfilter(b,a,data)

rawDescription: Most efficient way to filter a long time series Python


code:
from functools import wraps
from multiprocessing import Process

class TimeoutError(Exception):
    pass

def timeout(seconds=5, error_message="Timeout"):
    def decorator(func):
        def wrapper(*args, **kwargs):
            process = Process(None, func, None, args, kwargs)
            process.start()
            process.join(seconds)
            if process.is_alive():
                process.terminate()
                raise TimeoutError(error_message)

        return wraps(func)(wrapper)
    return decorator

rawDescription: PyUnit - How to unit test a method that runs into an infinite loop for some input?


code: res = 1 - x.astype(bool).astype(int)

rawDescription: Python numpy bool masks for absoluting values


code:
#!/usr/bin/env python
import sys
path = sys.argv[1]
lines = open(path, 'rb').readlines()
if lines and 'import sys' in lines[0]:
    open(path, 'wb').write(''.join(lines[1:-1]) + '\n')

rawDescription: Eggs in path before PYTHONPATH environment variable


rawDescription: Python JSON parse duplicate records

description: Python JSON parse duplicate records


code:
for i, value in enumerate(my_sequence):
    if 3 <= i <= 4:
        old_value = my_sequence[i-2]
        do_something(old_value, value)

rawDescription: How can you manipulate the iterator in a for loop in python?

description: Manipulate the iterator in a for loop in python


rawDescription: Algorithm to find least sum of squares of differences


code:
country_meta = soup.find('meta', attrs={'property': 'og:country-name', 'content': True})
if country_meta:
    country = country_meta['content']

rawDescription: Python beautiful soup issue

description: Python beautiful soup issue


code:
Console.WriteLine("Header is loading")
Console.WriteLine("Variable set by body: %s" %  someVarSetByBody)
Console.WriteLine("Header has loaded")

rawDescription: IronPython 'execfile' Equivalent in C#

description: IronPython 'execfile' Equivalent in C#


rawDescription: Django Templates and variable attributes


code: grouped = df.groupby(['User_ID'], group_keys=False)

rawDescription: pandas - apply time and space functions to groupby

description: Pandas - apply time and space functions to groupby


code:
def sites(x):
    r = []
    modulo = []
    ln = len(x)
    for i,ele in enumerate(x):
        sm = int(float(ele)) + (i + 1)
        r.append(sm)
    for j in range(ln):
        som = r[j] % ln
        modulo.append(som)
    return modulo

rawDescription: how to check if two numbers in a list are the same in Python

description: Check if two numbers in a list are the same in Python


code:
def discard(self, item):
    if item in self.dict:
        index = self.dict[item]
        self.list[index], self.list[-1] = self.list[-1], self.list[index]
        self.dict[self.list[index]] = index
        del self.list[-1]                    # or in one line:
        del self.dict[item]                  # del self.dict[self.list.pop()]

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


code:
import pandas as pd
toss = np.random.randint(0,2,100)

toss = pd.Series(toss)

steps = (toss.cumsum() * toss).diff() # mask out the cumsum where we won [0 1 2 3 0 0 4 5 6 ... ]
edges = steps < 0 # find where the cumsum steps down -> where we won
dsteps = steps[edges].diff() # find the length of each losing streak
dsteps[steps[edges].index[0]] = steps[edges][:1] # fix length of the first run which in now NaN
toss2 = toss.copy() # get a copy of the toss series
toss2[edges] = dsteps # insert the length of the losing streaks into the copy of the toss results
bets = 2 ** (toss2).cumsum() # compute the wagers

res = pd.DataFrame({'toss': toss,
                    'toss2': toss2,
                    'runs': toss2.cumsum(),
                    'next_bet': bets})

rawDescription: Implement a classic martingale using Python and Pandas


code:
filename = input('Please enter a filename: ')
with open(filename) as fh:
    for line in fh:
        if "admin_" in line:
            print(line)

rawDescription: python 3.3 user input

description: Python 3.3 user input


code:
from ast import literal_eval

df['misc'] = [literal_eval(r) for r in df.misc]

rawDescription: remove dictionary from list in pandas colum

description: Remove dictionary from list in pandas colum


code:
{
    "_id" : ObjectId("53465fa60f04c6552ab77475"),
    "_cls" : "User",
    "username" : "boba",
    "email" : "bobsaget@fullhouse.gov",
    "password" : "pbkdf2_sha256$12000$ZYbCHP1K1kDE$Y4LnGTdKhh1irJVktWo1QZX6AlEFn+1daTEvQAMMehA=",
    "is_staff" : false,
    "is_active" : true,
    "is_superuser" : false,
    "last_login" : ISODate("2014-04-10T09:08:54.551Z"),
    "date_joined" : ISODate("2014-04-10T09:08:54.550Z"),
    "user_permissions" : [ ]
}

rawDescription: Django - Auth with mongoengine DB

description: Django - Auth with mongoengine DB


code:
cols = df.columns
bt = df.apply(lambda x: x > 0)
bt.apply(lambda x: list(cols[x.values]), axis=1)

rawDescription: find the set of column indices for non-zero values in each row in pandas' data frame

description: Find the set of column indices for non-zero values in each row in pandas' data frame


rawDescription: How to plot a very simple bar chart (Python, Matplotlib) using input *.txt file?

description: Plot a very simple bar chart (Python, Matplotlib) using input *.txt file


code:
import gzip
gz = gzip.open(filename + '.gz', 'rb')
obj = pickle.loads(gz.read())
gz.close()

rawDescription: Why does saving/loading data in python take a lot more space/time than matlab?


code:
from flask import Flask, Response
import time

app = Flask(__name__)

@app.route('/')
def index():
    def generate():
        yield 'waiting 5 seconds\n'

        for i in range(1, 101):
            time.sleep(0.05)

            if i % 10 == 0:
                yield '{}%\n'.format(i)

        yield 'done\n'

    return Response(generate(), mimetype='text/plain')

app.run()

rawDescription: Flask Static Progress Screen

description: Flask Static Progress Screen


code:
import readline
readline.parse_and_bind('"\\C-w": backward-kill-word')

rawDescription: CPython interactive readline — better backwards deletion of words


code:
mask0 = 0x07
mask1 = 0x40
mask2 = 0x80

rawDescription: Bit masking in Python

description: Bit masking in Python


code:
from bs4 import BeautifulSoup
from lxml.html import fromstring

data = """
<title>The Dormouse's story</title>

The Dormouse's story

Once upon a time there were three little sisters; and their names were
Elsie,
Lacie and
Tillie;
and they lived at the bottom of a well.

...

"""

def count_bs():
    return sum(len(ele.attrs) + 1 for ele in BeautifulSoup(data).find_all())

def count_lxml_html():
    root = fromstring(data)
    return int(root.xpath("count(//*)")) + int(root.xpath("count(//@*)"))

rawDescription: Finding all tags and attributes in a HTML


rawDescription: Check string by user-given regex

description: Check string by user-given regex


code:
df.val.iloc[1] = 20
df

rawDescription: Assign values to the groups of a groupby in pandas


code:
def make_triangle(size, siblings, step):
    return [['*' * (i-(step*sib)) + ' ' * ((size-(step*sib)) - ((i-(step*sib)) if (i-(step*sib) > 0) else 0)) for sib in xrange(siblings)] for i in xrange(1, size+1)]

rawDescription: Triangle Siblings in python

description: Triangle Siblings in python


code: df.resample('BQS', how='sum')['Open'] - df.resample('BQS', how='sum').shift()['Close']

rawDescription: Getting end of period change with different index


code:
cam = Camera(0)
cam1 = Camera(1)
js = JPegStreamer()
js1 = JPegStreamer(8081)

while True:
    js.save(cam.getImage())
    js1.save(cam1.getImage())

rawDescription: Use simplecv to display videos in multiple windows


code:
['firstname', 'bob', 'lastname', 'stewart', 'dob', '2010-0206',
 'hobbies', 'reading, singing', 'drawing', 'is_minor', 'True']

rawDescription: PyParsing a string representing a function


code:
from pprint import pprint
pprint(word)

rawDescription: printing double quotes around a variable

description: Printing double quotes around a variable


code:
sep = " "
d = {}
with open("file2.txt", "r") as fd:
    for line in fd:
        # strip() to get rid of unnecesary spaces/endline/etc
        key, val = line.strip().split(sep)
        d[key] = val

rawDescription: compare diferent files and get things in common

description: Compare diferent files and get things in common


code:
import itertools
import string
letters = itertools.cycle(string.lowercase)

rawDescription: How to create a letter progression for a variable in a loop in Python?

description: Create a letter progression for a variable in a loop in Python


code:
class Foo(object):
    @classmethod
    def bar(cls):
        pass
    def baz(self):
        pass

Foo.baz
Foo.baz.__self__
Foo.baz.__self__ is None
Foo.bar.__self__
Foo.bar.__self__ is Foo

rawDescription: Check if a function uses @classmethod

description: Check if a function uses @classmethod


code:
self.button=QtGui.QPushButton("my button")
self.button.clicked.connect(self.on_click)
self.button.clicked.connect(self.on_click)
def on_click(self):
    print("1")

rawDescription: One button click fires signal multiple times instead of once


code:
step = 5
split_data = [data[i:i+step] for i in range(0,len(data),step)]

rawDescription: Python csv group rows by n row numbers

description: Python csv group rows by n row numbers


rawDescription: Copying file without previous meta data

description: Copying file without previous meta data


code:
class RideSerializer(serializers.ModelSerializer):
    class Meta:
        model = Ride
        read_only_fields = ('driver', 'passengers')

#inside your RideViewSet
def perform_create(self, serializer):
     serializer.save(driver=self.request.user.userprofile)

rawDescription: django - Many To Many relationship issue

description: Django - Many To Many relationship issue


code: x, y = y, x + y

rawDescription: Why does this code only work when i use 'x,y = y,x + y format instead of 'x = y; y = x + y'?


rawDescription: converting epoch time with milliseconds to datetime

description: Converting epoch time with milliseconds to datetime


code:
import os
os.popen("maf2hal inputfile outputfile")

rawDescription: What is the statement to use for executing a command allied with a different software in python?


code:
# common.py
class A: whatever
class B: whatever

# a.py
from common import A

# b.py
from common import B

rawDescription: Avoiding circular (cyclic) imports in Python?


code:
def __getattribute__(self, name):
    result = super(A, self).__getattribute__(name)
    if name in ('test',):
        return decorate(result)
    return result

rawDescription: Python __getattribute__ and wrapper of method


rawDescription: Python & Pandas: series to timedelta

description: Python & Pandas: series to timedelta


code: agent = driver.execute_script("return navigator.userAgent")

rawDescription: Change user agent for selenium driver

description: Change user agent for selenium driver


rawDescription: Python: how do I dynamically print a table of strings in the terminal?


code:
import re
s = re.match(r'^.*?\.zip', s).group(0)

rawDescription: How to delete everything after a certain character in a string?

description: Delete everything after a certain character in a string


code:
import easygui
#Childs Litercay Game
#Charlotte Lowe 03/09/2015

#Declare Constants and Variables
Score = 0
PlayerAnswer = 0
playOn = 0
while playOn != "Yes":
    playOn = easygui.buttonbox ("Hey there, are you ready to test your spelling?", choices = ["Yes"])
if "Yes":
    PlayerName = easygui.enterbox ("Before we begin, what's your name?")

easygui.msgbox ("Hi " + PlayerName +"! Here are the rules of the game.")
easygui.msgbox ("There will be 3 words you can choose from, 2 will be incorrect and 1 will be right.")
easygui.msgbox ("All you have to do is select the correctly spelt word.")
easygui.msgbox ("For every right word you pick you will earn a point! There are 10 questions in this quiz")
easygui.msgbox ("Let's begin!")

while True:
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices = ["Awesome","Awsome","Awesom"])
    if PlayerAnswer == "Awesome":
        Score += 1
        easygui.msgbox ("You're right! Your score is " + str(Score))
    elif PlayerAnswer == "Awsome":
            Score += 0
            easygui.msgbox ("Sorry Incorrect! Your score is " + str(Score))
    elif PlayerAnswer == "Awesom":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Becuse","Becus","Because"])
    if PlayerAnswer == "Becuse":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "Becus":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "Because":
        Score += 1
        easygui.msgbox ("Correct! Your score is now " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Morning","Moring","Morening"])
    if PlayerAnswer == "Morning":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "Moring":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "Morening":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Beleave","Believe","Belive"])
    if PlayerAnswer == "Believe":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "Beleave":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "Belive":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Jewelry","Jewlery","Jewley"])
    if PlayerAnswer == "Jewelry":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "Jewlery":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "Jewley":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["Mispelled","Misspelled","Misspeled",])
    if PlayerAnswer == "Misspelled":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "Mispelled":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "Misspeled":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly____
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["acceptable","aceptable","acceptble",])
    if PlayerAnswer == "acceptable":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "aceptable":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "acceptble":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["calendar","calender","callendar",])
    if PlayerAnswer == "calendar":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "calender":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "callendar":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["equepment","equiptment","equipment",])
    if PlayerAnswer == "equipment":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "equiptment":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "equipment":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    PlayerAnswer = easygui.buttonbox ("Which word is spelt correctly?", choices =["library","liebary","libary",])
    if PlayerAnswer == "library":
        Score += 1
        easygui.msgbox ("Well done! Your score is now " + str(Score))
    elif PlayerAnswer == "liebary":
         Score += 0
         easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    elif PlayerAnswer == "lieberry":
        Score += 0
        easygui.msgbox ("Sorry Incorrect! Your score is still " + str(Score))
    print(Score) #To check if programme is calculating score properly
    if Score == 10:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, you got them all right " + PlayerName+ "!")
    elif Score == 9:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, one away " + PlayerName+ "!")
    elif Score == 8:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, so close "+ PlayerName+"!")
    elif Score == 7:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, nearly there " + PlayerName+"!")
    elif Score == 6:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, amlost made it " + PlayerName+ "!")
    elif Score == 5:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, half way there " + PlayerName+ "!")
    elif Score == 4:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, a little more pratice " + PlayerName+ "!")
    elif Score == 3:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, pratice makes perfect "+ PlayerName+"!")
    elif Score == 2:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, try again " + PlayerName+"!")
    elif Score == 1:
        easygui.msgbox ("You got a score of " + str(Score) + " out of 10, better luck next time " + PlayerName+ "!")
    elif Score == 0:
        easygui.msgbox ("You got a score of " + str(Score) + "out of 10, better luck next time " + PlayerName+ "!")

    playOn = easygui.buttonbox ("Do you want to play again?", choices = ["Yes", "No"])
    if playOn == "Yes":
       Score = 0 #resets score count, if player wants to play again
    elif playOn == "No":
      easygui.msgbox ("Bye for now. Hope you'll play the game again soon!")
      break

rawDescription: Python program not looping/restarting

description: Python program not looping/restarting


code:
class Foo(object):
    def __init__(self, value):
        self._spam = value
    @property
    def spam(self):
        return self._spam

f = Foo('eggs')
f.spam
f.spam = 'ham'

rawDescription: Python class which instances' atributes can't be edited


code:
theader=['tuple col 1', 'col 2', 'the third' ]
[[theader[i] for i, t in enumerate(zip(*pair)) if t[0]!=t[1]] for pair
      in pairs(LoT)]

rawDescription: Element by element comparison in tuple to return set of sets - python


code:
import math
#import numpy as np
from pylab import plot, show
def model(Dt=1, time_step = 50, w1 = 1, steepness_SS_a=1,
          speed_SS_a=1, threshold_SS_a=1, WS_a=1, SS_a=0,
          t=0, t_final=30):
    result = [SS_a]
    timesteps =[]
    for ti in range(t,t_final+1,Dt):
        result.append( ... ) #<- put here your complicate formula
        timesteps.append(ti)
    print( timesteps )
    plot(result)
    show()
    #return result

model()

rawDescription: Accessing a value from an np.array from a while loop


code:
input = np.array([True, True, True, True, False, False, False, True, True,
     False, False, False, True, True, True, True, False, True])

rawDescription: Filling next N rows in pandas with False when True found


code: [x for x in old_list if x[-1].isdigit()]

rawDescription: Match a term ending with digit

description: Match a term ending with digit


code:
#
# This file contains the Python code from Program 16.16 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng.  All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm16_16.txt
#
class Algorithms(object):

    def DijkstrasAlgorithm(g, s):
        n = g.numberOfVertices
        table = Array(n)
        for v in xrange(n):
            table[v] = Algorithms.Entry()
        table[s].distance = 0
        queue = BinaryHeap(g.numberOfEdges)
        queue.enqueue(Association(0, g[s]))
        while not queue.isEmpty:
            assoc = queue.dequeueMin()
            v0 = assoc.value
            if not table[v0.number].known:
                table[v0.number].known = True
                for e in v0.emanatingEdges:
                    v1 = e.mateOf(v0)
                    d = table[v0.number].distance + e.weight
                    if table[v1.number].distance > d:

                        table[v1.number].distance = d
                        table[v1.number].predecessor = v0.number
                        queue.enqueue(Association(d, v1))
        result = DigraphAsLists(n)
        for v in xrange(n):
            result.addVertex(v, table[v].distance)
        for v in xrange(n):
            if v != s:
                result.addEdge(v, table[v].predecessor)
        return result
    DijkstrasAlgorithm = staticmethod(DijkstrasAlgorithm)

rawDescription: Python - Dijkstra's Algorithm

description: Python - Dijkstra's Algorithm


code:
def delete_if_not(predicate_key, some_dict):
    for key, subdict in some_dict.items():
        if not subdict.get(predicate_key, True):
            del some_dict[key]

rawDescription: How to delete entries in a dictionary with a given flag in python?

description: Delete entries in a dictionary with a given flag in python


code: import MyModule

rawDescription: Python - Changing global variable in a function


code:
app = Flask(__name__)
@app.route('/')
def index():
    return redirect(url_for('static', filename='index.html'))

if __name__ == "__main__":
    root = resource.Resource()
    root.putChild('', wsgi.WSGIResource(reactor, reactor.getThreadPool(), app))
    root.putChild('static', static.File("./static"))
    root.putChild('my_event_source', SSEResource())

    reactor.listenTCP(8001, server.Site(root))
    reactor.run()

rawDescription: Server-sent events with Python,Twisted and Flask: is this a correct approach for sleeping?


code:
input_dict_1 = {"data": [
    {"gender": "male",
     "data": [
         {"age": "adult",
          "data": {"average_height": 62, "average_weight": 200}},
         {"age": "youth",
          "data": {"average_height": 50, "average_weight": 120}}]},
    {"gender": "female",
     "data": [
         {"age": "adult",
          "data": {"average_height": 55, "average_weight": 130}},
         {"age": "youth",
          "data": {"average_height": 45, "average_weight": 80}},
         {"age": "infant",
          "data": {"average_height": 15, "average_weight": 35}}]}]}

def get_col_names( d, l=None ):
    if l==None: l=[]
    if isinstance(d['data'], list):
        l.extend( k for k in d['data'][0].keys() if k != 'data' )
        get_col_names( d['data'][0], l )
    else:
        l.extend( d['data'].keys() )
    return l

rawDescription: Converting Arbitrarily Nested Dict to List of Lists


code:
import numpy as np
import pandas as pd
from pandas import DataFrame
df = DataFrame(1.,index=list('abcdefghij'),columns=[0,1,2])
df
df2 = DataFrame(0,index=list('afg'),columns=[1,2])
df2
df.loc[df2.index,df2.columns] = df2
df

rawDescription: Fastest way to copy columns from one DataFrame to another using pandas?


rawDescription: python writerow([variable]) instead of actual row

description: Python writerow([variable]) instead of actual row


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

# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    )

STATIC_URL = '/static/'

MEDIA_URL = 'media/'

STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'django.contrib.staticfiles.finders.FileSystemFinder',
)

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
'django.core.context_processors.request',
)

rawDescription: Bootstrap template with Django

description: Bootstrap template with Django


code:
data = ast.literal_eval(data)
data = data[1:-1].replace("''", "'")
obj = ast.literal_eval(data)

rawDescription: Python Json Parse

description: Python Json Parse


code:
import os.path
df["root"].apply(lambda x: os.path.splitext(os.path.basename(x))[0])

rawDescription: How to extract substring with base part of path string

description: Extract substring with base part of path string


code:
Registered()
Registered()
Registered()
Registered._all

rawDescription: How to obtain all instances of a class within the current module

description: Obtain all instances of a class within the current module


code:
def my_function():
    for name in my_list:
        name_list = []
        name_list.append(list1)
        name_list.append(list2)
        name_list.append(list3)
    return name_list

rawDescription: Introducing new variables using a given string


rawDescription: how to format date in ISO using python?

description: Format date in ISO using python


rawDescription: Extract data / parse from HTML in PHP / Python


rawDescription: Iterator that excludes the last element

description: Iterator that excludes the last element


rawDescription: Python look for a format that match specific format


rawDescription: How do I get the modified date/time of a file in Python?

description: Get the modified date/time of a file in Python


code:
NoneCheck([Inventory(0), Inventory(0)], 'book')
NoneCheck([Inventory(0), Inventory(4)], 'book')
NoneCheck([Inventory(0), Inventory(4)], 'undefined')

rawDescription: Passing Attributes as Arguments

description: Passing Attributes as Arguments


code:
res = []
for word in words:
    for letter in word:
        if letter not in res:
            res.append(letter)

rawDescription: Return only single occurrences of a string


code:
from collections import namedtuple
hero = namedtuple('hero', ['name', 'classes', 'level'])
mainList = [
    hero(name='SirGoose', classes='Fighter', level=150 ),
    hero(name='Conan', classes='Barbarian', level=160 ),
    hero( name='KingArthur', classes='Knight', level=170 )
]
sorted(mainList, key=lambda h: (h.name, h.level))

rawDescription: Python: Sort a list of objects based on their attributes


code:
#!/usr/bin/env python3
import errno
import os
import pty
import sys
from select import select
from subprocess import Popen

masters, slaves = zip(pty.openpty(), pty.openpty())
with Popen([sys.executable, '-c', r'''import sys, time
print('stdout', 1) # no explicit flush
time.sleep(.5)
print('stderr', 2, file=sys.stderr)
time.sleep(.5)
print('stdout', 3)
time.sleep(.5)
print('stderr', 4, file=sys.stderr)
'''],
           stdin=slaves[0], stdout=slaves[0], stderr=slaves[1]):
    for fd in slaves:
        os.close(fd) # no input
    readable = {
        masters[0]: sys.stdout.buffer, # log separately
        masters[1]: sys.stderr.buffer,
    }
    while readable:
        for fd in select(readable, [], [])[0]:
            try:
                data = os.read(fd, 1024) # read available
            except OSError as e:
                if e.errno != errno.EIO:
                    raise #XXX cleanup
                del readable[fd] # EIO means EOF on some systems
            else:
                if not data: # EOF
                    del readable[fd]
                else:
                    readable[fd].write(data)
                    readable[fd].flush()
for fd in masters:
    os.close(fd)

rawDescription: Run command and get its stdout, stderr separately in near real time like in a terminal


rawDescription: Python - Removing an element in list

description: Python - Removing an element in list


code:
sel = selenium.selenium("localhost", 4444, "*firefox", "http://www.ncbi.nlm.nih.gov/")
sel.start()
sel.open('/pubmed')
sel.type("search_term", "20032207[uid]")
sel.click("search")
sel.wait_for_page_to_load(30000)
sel.click("//*[contains(@id,'linkout')]")

rawDescription: Clicking links by regexp in python selenium


code:
def get_divisors(r: int) -> list:
    return [i if r % i == 0 else 0 for i in range(1, r+1)]

def sum_div(x, y):
    for k in range(x,y+1):
        sum_of_x_divisors = sum(get_divisors(k))  # Note this is moved here to avoid repeating work.
        for z in range(x,y+1):
            sum_of_y_divisors = sum(get_divisors(z))
            if sum_of_x_divisors == sum_of_y_divisors and k!= z:
                print("({},{})".format(k, z))

rawDescription: How to stop a loop?

description: Stop a loop


code:
class A(object):
    B = 2

rawDescription: Scope of classes inside of functions and classes inside of a class in python


rawDescription: Extract a column from a list of rows with Python


code:
class Struct:
    def __init__(self, **entries):
        self.__dict__.update(entries)

rawDescription: YAML parsing and Python?

description: YAML parsing and Python


code:
xs = arange(1000)
sp.optimize.fsolve(g,zeros_like(xs), xs)

rawDescription: Finding the root of a multivariate function at different variable values with Python


code: s = strings(iter(list_of_values))

rawDescription: Any way to bypass namedtuple 255 arguments limitation?


rawDescription: Pandas to_csv call is prepending a comma


code:
with open(filename + ".jpeg", 'wb') as f:
    f.write(requests.get(image).content)

rawDescription: following webscraping in python tutorial they use urllib im using requests help translating instructions

description: Following webscraping in python tutorial they use urllib im using requests help translating instructions


code:
def getSrc():
    if getSrc.has_been_called is False:
        getSrc.source = askdirectory()
        getSrc.has_been_called = True
        return getSrc.source
    else:
        return getSrc.source

rawDescription: Python Reuse a Variable in the Else Block of an If-Else Statement


code:
from tkinter import *
import re

# Here, we are creating our class, Window, and inheriting from the Frame
# class. Frame is a class from the tkinter module. (see Lib/tkinter/__init__)
class Window(Frame):

    # Define settings upon initialization. Here you can specify
    def __init__(self, master=None):

        # parameters that you want to send through the Frame class.
        Frame.__init__(self, master)

        #reference to the master widget, which is the tk window
        self.master = master

        #with that, we want to then run init_window, which doesn't yet exist
        self.init_window()

    #Creation of init_window
    def init_window(self):

        # changing the title of our master widget
        self.master.title("Used Filament Data")

        # allowing the widget to take the full space of the root window
        self.pack(fill=BOTH, expand=1)

        # creating a menu instance
        menu = Menu(self.master)
        self.master.config(menu=menu)

        # create the file object)
        file = Menu(menu)

        # adds a command to the menu option, calling it exit, and the
        # command it runs on event is client_exit
        file.add_command(label="Exit", command=self.client_exit)

        #added "file" to our menu
        menu.add_cascade(label="File", menu=file)

        #Creating the button
        quitButton = Button(self, text="Load GCODE",command=self.read_gcode)
        quitButton.place(x=0, y=0)

    # Load the gcode file in and extract the filament value
    def get_filament_value(self, fileName):
        with open(fileName, 'r') as f_gcode:
            data = f_gcode.read()
            re_value = re.search('filament used = .*? \(([0-9.]+)', data)

            if re_value:
                value = float(re_value.group(1))
                print('filament value is {}'.format(value))
            else:
                value = 0.0
                print('filament not found in {}'.format(fileName))
        return value

    def read_gcode(self):
        root.fileName = filedialog.askopenfilename(filetypes = (("GCODE files", "*.gcode"), ("All files", "*.*")))
        self.value = self.get_filament_value(root.fileName)

    def client_exit(self):
        exit()

# root window created. Here, that would be the only window, but
# you can later have windows within windows.
root = Tk()

root.geometry("400x300")

#creation of an instance
app = Window(root)

#mainloop
root.mainloop()

rawDescription: Simple python program to read . gcode file


rawDescription: Url pattern matching is confusing in django


code:
sql = "SELECT y, w, d FROM t"
df = pd.read_sql(sql, engine)

date = (df['y'].astype('<i8')-1970).view('<M8[Y]')
delta = (df['w'].astype('<i8')*7).view('<m8[D]')
df['date'] = date+delta
df = df[['date', 'd']]
print(df)

rawDescription: pandas.read_sql and interpreting dates specified as weeks

description: Pandas.read_sql and interpreting dates specified as weeks


code:
# ... 8< - -
h_slice = slice(max(0, x - sight), min(x + sight + 1, width))
v_slice = slice(max(0, y - sight), min(y + sight + 1, height))

known_section = known_environment[h_slice, v_slice]
actual_section = actual_environment[h_slice, v_slice]
if not np.array_equal(known_section, actual_section):
    known_environment[h_slice, v_slice] = actual_section
# - - >8 ...

rawDescription: Fastest method for comparing ranges of multidimensional lists


code: np.einsum('nr,mr,lr->nml', A, B, C)

rawDescription: Matrix triple product with theano

description: Matrix triple product with theano


code:
import re

# Read in your ugly text file.
tweet_string = open('nameoffile.txt', 'rU')
tweet_string = tweet_string.read()

# Find all the id numbers with a regex.
id_finder = re.compile('[0-9]{18,18}')

# Go through the twee_string object and find all
# the IDs that meet the regex criteria.
idList = re.findall(id_finder, tweet_string)

rawDescription: Downloading Full JSON data from Tweets Using Rest API and Tweepy, Querying by Tweet ID


code:
def print_names(*names):
    for name in names:
        print(name)

print_names('Bob', 'James', 'Harry')

rawDescription: Tkinter option menu

description: Tkinter option menu


rawDescription: Setting stacksize in a python script

description: Setting stacksize in a python script


rawDescription: Storing large amount of boolean data in python


rawDescription: Understanding builtin next() function

description: Understanding builtin next() function


code:
now = datetime.utcnow()
later = now + timedelta(weeks=78, minutes=85, seconds=128)
diff = later - now

rawDescription: Convert epoch/unix time into readable format


code: M1, M2 = (list(i) for i in zip(*M))

rawDescription: Separate lists of format M=[(a,x), (b,y)] into M1=[a,b] and M2=[x,y]


rawDescription: numpy/scipy build adjacency matrix from weighted edgelist

description: Numpy/scipy build adjacency matrix from weighted edgelist


code:
headerrow = ['SeqName']
for i in range(1,6):
  headerrow.append('M%d' % i)
  headerrow.append('Hits')
headerrow

rawDescription: Automatically writing headers using csv python


code: dftest.apply(lambda x: x['string'][:x['position']], axis=1)

rawDescription: Python: In a dataframe, create a new column with a string sliced from a column with the value of another column


code: nc.call("some_service_function", {foo: "some", bar: "thing"})

rawDescription: Passing in **kwargs from Flex over PyAMF


code:
z = (tuple([[dct, operator.setitem(dct, 'picked', vval)][0] \
      for dct,vval in zip(map(dict,dcts), val)]) for val in y)

rawDescription: all possible combinations of dicts based on values inside dicts

description: All possible combinations of dicts based on values inside dicts


code: print('My name is ', name, '.', sep="")

rawDescription: options when formatting strings

description: Options when formatting strings


code:
from nltk.corpus import wordnet as wn
wn.synsets('dog')
dog = wn.synsets('dog')[0]
dog.definition()
dog.lemma_names()
dog.pos()
dog.offset()
dog.name()

rawDescription: While working on nltk, how to manipulate the nltk.corpus.reader.wordnet.Synset?


code: data = sys.stdin.readlines()

rawDescription: Preparing Python program to be run in UNIX enviroment


code:
['',
 '/usr/local/bin',
 '/home/keith/src/pytabix',
 '/home/keith/devel/onpythonpath',
 '/usr/lib/python2.7',
 '/usr/lib/python2.7/plat-x86_64-linux-gnu',
 '/usr/lib/python2.7/lib-tk',
 '/usr/lib/python2.7/lib-old',
 '/usr/lib/python2.7/lib-dynload',
 '/usr/local/lib/python2.7/dist-packages']

rawDescription: How can I keep python from loading the 'wrong' package?

description: Keep python from loading the 'wrong' package


code:
df2 = df.groupby(['stock','same1','same2'])[['positions']].sum()
df2

rawDescription: Summing across rows of Pandas Dataframe

description: Summing across rows of Pandas Dataframe


code:
from monitor import monitor
monitor.write("Foo")

rawDescription: classmethod for Tkinter-Monitor-Window

description: Classmethod for Tkinter-Monitor-Window


rawDescription: Intersect dictionaries with keys averaged


code: A = la.inv(points.T*np.diag(u)*points - c.T*c)/d

rawDescription: Port MATLAB bounding ellipsoid code to Python


code:
pairs = [(totalq, 'quarters'),
         (totald, 'dimes'),
         (totaln, 'nickels'),
         (totalp, 'pennies')]
total = ' '.join(str(value) + ' ' + name
                 for value, name in pairs
                 if value)
print(total)

rawDescription: Printing specific parts of a function for Python


code:
with open(infilepath) as infile:
  answer = {}
  name = None
  for line in infile:
    line = line.strip()
    if line.startswith("NGC"):
      name = line
      answer[name] = {}
    else:
      var, val = line.split(':', 1)
      answer[name][var.strip()] = val.strip()

rawDescription: Opening a text file and then storing the contents into a nested dictionary in python 2.7


code: df_later = df.iloc[idx:]

rawDescription: possible speed up of pandas apply

description: Possible speed up of pandas apply


code:
dt = parser.parse('2014/08/19 03:38:46 GMT-4')
dt.replace(tzinfo=pytz.utc) + dt.tzinfo._offset

rawDescription: Convert GMT based time to UTC python

description: Convert GMT based time to UTC python


code:
def pick_Q(N, M, Q):
    """
    Given a deck of N cards, where M are marked,
    and Q cards are taken randomly without replacement,
    return the probability that at least one marked card is taken.
    """
    return scipy.stats.hypergeom.sf(0, N, M, Q)

rawDescription: Drawing cards from a deck in SciPy with scipy.stats.hypergeom


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

rawDescription: Python split string in moving window

description: Python split string in moving window


code:
rsync_args = shlex.split(rsync_options)
rsync_args.extend(['/tmp/1', '/tmp/2'])
rsync_args.insert(0, 'rsync')
rsync_args

rawDescription: Python: split and format space separated values in a string to use in subprocess.check_call


code: pairs = objects.map(lambda obj: (obj.name, obj))

rawDescription: How to return a dictionary in parallel processing in spark?

description: Return a dictionary in parallel processing in spark


code:
kp = orb.detect(img,None)
kp, des = orb.compute(img, kp)

rawDescription: OpenCV - After feature points detection, how can I get the x,y-coordinates of the feature points


code:
def show_table(table):
    string = ''
    for line in table:
        for item in line:
            string += '| {} '.format(item)
        string += '|\n'

    return string

rawDescription: function def show_table create a and return a formatted string representing the 2D table

description: Function def show_table create a and return a formatted string representing the 2D table


code:
indices = mask.nonzero()
T.set_subtensor(A[indices], T.exp(A[indices]))

rawDescription: Theano: Operate on nonzero elements of sparse matrix


code:
if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser()
    # ... Add args
    ns = parser.parse_args()

rawDescription: Is there a way I can use mock() (or similar) to mock the date & time for a script I *invoke* from a unit test?


code:
period = 'DAY'
bq.Query(test1, period = period).sample()

rawDescription: Passing parameters for TABLE_QUERY in Google Cloud Datalab iPython notebook


code:
import string
string.lowercase

rawDescription: Returning the value of an index in a python list based on other values


code:
def foo(c):
    c.ID += 1
    return c

rawDescription: How to assign value inside list comprehension

description: Assign value inside list comprehension


code:
np.arange(N * K).reshape((N, K))
Series(randn(N), index=index)

rawDescription: What does the .N mean in this block of Python code?


code:
from collections import OrderedDict

def find_closest(distances):
    closest = OrderedDict()
    for distance in distances:
        origin = distance['origin_addresses'][0]
        destination = distance['destination_addresses'][0]
        value = distance['rows'][0]['elements'][0]['distance']['value']

        if origin not in closest or value < closest[origin][1]:
            closest[origin] = (destination, value)

    return closest

def format_closest(closest):
    for origin, (destination, value) in closest.items():
        yield "%s: the closest destination is %s (%d m)" % (origin, destination, value)

for line in format_closest(find_closest(response)):
    print(line)

rawDescription: Manipulating data from a list of dictionaries (Google API Distance Matrix)


code: return my_list == range(my_list[0],my_list[-1]+1)

rawDescription: Python: find out whether a list of integers is coherent


rawDescription: Add front slash to python regex

description: Add front slash to python regex


code: [[int(element[1])] for element in arrResult]

rawDescription: Python sqlite => reportlab data what is difference between [1,2,3] and [[1],[2],[3]]


rawDescription: Unifying OAuth handling between gdata and newer Google APIs


code:
class C:
    @staticmethod
    def default_concrete_strategy():
        print("default")

    @staticmethod
    def other_concrete_strategy():
        print("other")

    def __init__(self, strategy=default_concrete_strategy.__func__):
        self.strategy = strategy

rawDescription: In Python, how can I use a static method as a default parameter for the strategy design pattern?


code:
from openpyxl import Workbook

workbook = Workbook()
worksheet = workbook.worksheets[0]
worksheet.title = "Sheet1"

worksheet.cell('A1').style.alignment.wrap_text = True
worksheet.cell('A1').value = "Line 1\nLine 2\nLine 3"

workbook.save('wrap_text1.xlsx')

rawDescription: Writing multi-line strings into cells using openpyxl


code:
import zipfile
z = zipfile.ZipFile(some_source)
entry_info = z.getinfo(entry_name)
i = z.open(entry_name)
o = open(target_name, 'w')
offset = 0
while True:
    b = i.read(block_size)
    offset += len(b)
    set_percentage(float(offset)/float(entry_info.file_size) * 100.)
    if b == '':
        break
    o.write(b)
i.close()
o.close()
set_attributes_from(entry_info)

rawDescription: Extract ZipFile using Python, display Progress Percentage?


code:
import numpy as np
from scipy.stats import mstats
import matplotlib.pyplot as plt

# Create 10 columns with 100 rows of random data
rd = np.random.randn(100, 10)
# Calculate the quantiles column wise
quantiles = mstats.mquantiles(rd, axis=0)
# Plot it
labels = ['25%', '50%', '75%']
for i, q in enumerate(quantiles):
    plt.plot(q, label=labels[i])
plt.legend()

rawDescription: Plotting quantiles, median and spread using scipy and matplotlib


code:
# Concatenates a and b with ' - ' or Coalesces them if one is None
'-'.join([x for x in (a,b) if x])

rawDescription: What better way to concatenate string in python?


code:
c = Context({
   'foo': 'bar',
   'url': 'http://127.0.0.1/test?a=1&b=2',
}, autoescape=False)

rawDescription: How to disable HTML encoding when using Context in django

description: Disable HTML encoding when using Context in django


rawDescription: Check if user collected any points from my quiz


rawDescription: Python for loop overwriting

description: Python for loop overwriting


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

#-- Generate some data...
x, y = np.mgrid[-5:5:0.1, -5:5:0.1]
z = np.sqrt(x**2 + y**2) + np.sin(x**2 + y**2)

#-- Extract the line...
# Make a line with "num" points...
x0, y0 = 5, 4.5 # These are in _pixel_ coordinates!!
x1, y1 = 60, 75
num = 1000
x, y = np.linspace(x0, x1, num), np.linspace(y0, y1, num)

# Extract the values along the line
zi = z[x.astype(np.int), y.astype(np.int)]

#-- Plot...
fig, axes = plt.subplots(nrows=2)
axes[0].imshow(z)
axes[0].plot([x0, x1], [y0, y1], 'ro-')
axes[0].axis('image')

axes[1].plot(zi)

plt.show()

rawDescription: How to extract an arbitrary line of values from a numpy array?

description: Extract an arbitrary line of values from a numpy array


code:
class DirContents(generics.GenericAPIView):
    def get(self, request, *args, **kwargs):
        files = FileObj.objects.filter(parent=kwargs.get('dir_id'))
        dirs = DirObj.objects.filter(parent=kwargs.get('dir_id'))

        context = {
            "request": request,
        }

        files_serializer = FileObjSerializer(files, many=True, context=context)
        dirs_serializer = DirObjSerializer(dirs, many=True, context=context)

        response = files_serializer.data + dirs_serializer.data

        return Response(response)

rawDescription: Serialize multiple models in a single view


code:
i = 34
i.to_bytes(length=2, byteorder='big')

rawDescription: Add part of an integer to bytearray

description: Add part of an integer to bytearray


rawDescription: Elegant Python function to convert CamelCase to snake_case?


code: xc.add('apples', 4)

rawDescription: Ideal data structure with fast lookup, fast update and easy comparison/sorting


code:
from __future__ import print_function
import click

@click.command()
@click.option('--output', 'data')
def generate_data(data):
    print(data)

if __name__ == '__main__':
    generate_data()

rawDescription: Select destination variable for click parser


rawDescription: Regular expression to find any number in a string


code:
from itertools import product
for base, new in product([base_list_meat, base_list_fruit], [list_fresh, list_old]):
    food_processor(base, new)

rawDescription: python multiple list, AND func, then create new list

description: Python multiple list, AND func, then create new list


code:
def main():
    app = QtGui.QApplication(sys.argv)
    main = Main()
    main.show()

    input_timer = QTimer(self)
    input_timer.timeout.connect(lambda : main.text.setReadOnly(True))
    input_timer.setSingleShot(True)
    input_timer.start(2000)

    sys.exit(app.exec_())

rawDescription: Background Timer in PyQt Python Applicatiion


code:
def slicing(input_date):
    try:
        year = int(input_date[:4])
        month = int(input_date[5:7])
        day = int(input_date[8:])
        my_date = date(year, month, day)
    except ValueError:
        my_date = None

timeit.timeit('f("2014-07-08")', 'from __main__ import slicing as f')

rawDescription: Speeding up datetime.strptime

description: Speeding up datetime.strptime


code:
@patch('__builtin__.open', spec=open)
def test_interface_mapping(self, mock_open):
    handle1 = MagicMock()
    handle1.__enter__.return_value.__iter__.return_value = ('aa', 'bb')
    handle1.__exit__.return_value=False
    handle2 = MagicMock()
    handle2.__enter__.return_value.__iter__.return_value = ('AA', 'BB')
    handle2.__exit__.return_value=False
    mock_open.side_effect = (handle1, handle2)
    with open("ppp") as f:
        self.assertListEqual(["aa","bb"],[x for x in f])
    with open("ppp") as f:
        self.assertListEqual(["AA","BB"],[x for x in f])

rawDescription: Python mock builtin 'open' in a class using two different files


rawDescription: Shallow copy: why is list changing but not a string?


code: from driver import window

rawDescription: Namespaces and Accessing Tkinter

description: Namespaces and Accessing Tkinter


code:
n = []
for i in k:
    n.append(some_value)

rawDescription: Declaring variable name with string and number?


code:
(1, u'channel-1', True)
(2, u'channel-2', False)
(3, u'channel-3', True)
(4, u'channel-4', False)
(1, u'channel-1', False)
(2, u'channel-2', True)
(3, u'channel-3', False)
(4, u'channel-4', False)

rawDescription: How do I join three tables with SQLalchemy and keeping all of the columns in one of the tables?

description: Join three tables with SQLalchemy and keeping all of the columns in one of the tables


code:
np.in1d(a, b)
Out[156]: array([False, False,  True,  True, False,  True], dtype=bool)

rawDescription: check membership of a set in python

description: Check membership of a set in python


code: self.skills = filter(lambda skill: skill.id != skill_to_remove.id, self.skills)

rawDescription: Python. How to efficiently remove custom object from array


rawDescription: Python string,re.match,loop

description: Python string,re.match,loop


code:
from __future__ import print_function
import re
#NDoc = raw_input("Enter name of to-be-made document")
#log = open("C:\Users\XYZ\Desktop\Python\NDoc.txt", "w")
#Need help with this^ How do I make new file instead of opening a file?

#nl = list()
#file = raw_input("Enter a file to be sorted")
xfile = open("file2")

for line in xfile:
    l=line.strip()
    n=re.sub("(\B)(?=((MTH|SCN|ENG|HST)[|]))","\n\n",line)
                       #Edited out some x's here that I left in, sorry
    if len(n) > 0:
      nl=n.split("\n")
      for item in nl:
         print(item)

rawDescription: RegEx Python Find and Print to a new document


code: self.currentDistance = self.tempTime * self.speed

rawDescription: Calculate a distance in for racing game in python


code: my_tuple = 1, 2, 3

rawDescription: Python string formatting

description: Python string formatting


rawDescription: Iterating through multiple values in a dictionary?


code: reverse(line(49, "of beer on the wall"))

rawDescription: How to reverse an int in python?

description: Reverse an int in python


code:
some_list = []

def foo(bar):
    some_list.append(bar)

foo('baz')

rawDescription: What are non-pure functions in python?

description: What are non-pure functions in python


code:
def __eval(self, expr, eval_globals=None, eval_locals=None):
    call_frame = sys._getframe(1)
    eval_globals, eval_locals = call_frame.f_globals, call_frame.f_locals

rawDescription: Is it possible to get locals() and globals() from an upper stack frame?


rawDescription: Calculating e (base of the natural log) to high precision in Python?


code:
from IPython.display import display

def show_more(df, lines):
    foo = 1
    display(df)
    foo = 2

rawDescription: Is there a concise way to show all rows in pandas for just the current command?


code:
myKeys = ("Last name", "First name")
myValues = ("Miller", "Joe")
print(dict(zip(myKeys, myValues)))

rawDescription: Adding tuple to as keys dictionary

description: Adding tuple to as keys dictionary


code:
class PatchedQDate (QtCore.QDate):
    @classmethod
    def currentDate (cls):
        return QtCore.QDate (2012, 1, 1)

QtCore.QDate = PatchedQDate

rawDescription: Change local date in PyQt application

description: Change local date in PyQt application


code:
result = s.decode('unicode-escape').encode('latin1').decode('utf8')
print(result)

rawDescription: python 3, unicode conversion, two \u0000 as one character

description: Python 3, unicode conversion, two \u0000 as one character


code:
class Xyzzy(object):

    def __init__(self, which_factory):
        print('calling Xyzzy.__init__')
        self.which_factory = which_factory

    @classmethod
    def factory_foo(cls):
        print('calling factory_foo with', cls)
        return cls('factory_foo')

    @classmethod
    def factory_bar(cls):
        print('calling factory_bar with', cls)
        return cls('factory_bar')

class Yappy(Xyzzy):

    def __init__(self, which_factory):
        print('calling Yappy.__init__')
        super(Yappy, self).__init__(which_factory)
        print(which_factory)

rawDescription: Python derived class intricacies

description: Python derived class intricacies


rawDescription: How can I sort a 2D list?

description: Sort a 2D list


code:
from string import digits
[i.translate(None,digits) for i in contents]

rawDescription: how to identify that anystring of list contains digits or not in python

description: Identify that anystring of list contains digits or not in python


code:
class MetadataSerialier(pagination.BasePaginationSerializer):
    count = serializers.Field(source='paginator.count')
    next = NextPageField(source='*')
    previous = PreviousPageField(source='*')

class CustomPaginationSerializer(pagination.BasePaginationSerializer):
    metadata = MetadataSerializer(source='*')

rawDescription: Where to change the form of json response in django rest framework?


code: testvar = 1 if x == 'dog' else 2 if x == 'cat' else 0 if x.isspace() else None

rawDescription: possible to set variable with multiple if statments?

description: Possible to set variable with multiple if statments


code:
def defaultArgs(default_kw):
    "decorator to assign default kwargs"
    def wrap(f):
        def wrapped_f(**kwargs):
            kw = {}
            kw.update(default_kw)  # apply defaults
            kw.update(kwargs)  # apply from input args
            f(**kw)  # run actual function with updated kwargs
        return wrapped_f
    return wrap

rawDescription: Dynamically define functions with varying signature


code:
scipy.sparse.vstack((a,m))
#<6x3 sparse matrix of type '<type 'numpy.float64'>'
#        with 12 stored elements in COOrdinate format>

rawDescription: stacking sparse and dense matrices

description: Stacking sparse and dense matrices


rawDescription: What is the best way to split a line of numbers separated by a marker and spaces and store it into a tuple?


code:
anagram_dict = {} # You could also use defaultdict(list) here
for w in words:
    key = "".join(sorted(w))
    if key in anagram_dict:
        anagram_dict[key].append(w)
    else:
        anagram_dict[key] = [w]

rawDescription: Large anagram search not reading to end of set Python


code:
def lambdas_equivalencies(restfreq):
    restfreq_hz = restfreq.to(u.Hz, equivalencies=u.spectral())
    ...

rawDescription: Astropy Units equivalencies - interferometry baselines


code:
with open('points.csv', 'a') as csvfile:
     ...

rawDescription: python write to a csv file

description: Python write to a csv file


code:
import __builtin__
def isinstance(a, b):
    class tmp(type(a)):
         pass
    return __builtin__.isinstance(tmp(), b)

__builtin__.isinstance(a, A)
isinstance(a, A)

rawDescription: Why __instancecheck__ is not always called depending on argument?


rawDescription: Python: Finding symmetries in list of lists