code:
df['data']['pf'] = df['data']['pf'] * df['pchg']
df['data']['bm'] = df['data']['bm'] * df['pchg']

rawDescription: Pandas multiply several multi-index columns in a dataframe by another column


rawDescription: Python. user input(1) string to list. User input (2) finds if there is the word in the first user input


code:
import datetime

def parsedelta(hhmmss):
    h, m, s = hhmmss.split(':')
    return datetime.timedelta(hours=int(h), minutes=int(m), seconds=int(s))

rawDescription: Compare if datetime.timedelta is between two values


code:
L.sort()
L

rawDescription: python, 2 operations: find closest value above and below a specified value in array, find associated values in another array

description: Python, 2 operations: find closest value above and below a specified value in array, find associated values in another array


code:
s = 'Q\xcb\x80\x80\x00\x00\x01\x9bQ\xcc\xd2\x00\x00\x00\x01\x9b'
len(s)
import struct
struct.unpack('>QQ',s) # big-endian
struct.unpack('<QQ',s) # little-endian

rawDescription: Binary Data in Python

description: Binary Data in Python


code:
import builtins
builtins.open

rawDescription: Is it possible to access original function which has been overwritten in python


rawDescription: Set a variable to a random element from an array and not the elements value. ---python---


code: import spam

rawDescription: How do I cause or create an invalid memory reference in Python on purpose?

description: Cause or create an invalid memory reference in Python on purpose


code:
def removeDups(duptest, iterable):
  res = []
  for e in iterable:
    if not any(duptest(e, r) for r in res):
       res.append(e)
  return res

rawDescription: Remove duplicates with a different equality test in Python


code:
for linebreak, li in reversed(list(zip(ul.contents, items))):
    linebreak.insert_after(li)

rawDescription: How do I sort an unordered list using BeautifulSoup 4 by a child element

description: Sort an unordered list using BeautifulSoup 4 by a child element


code:
palette = palettes["red-yellow-green"]
colors = [round(x) for x in rescale(g.degree(), out_range=(0, len(palette)-1))]
plot(g, vertex_color=colors, palette=palette)

rawDescription: How to use igraph python's metamagic class?

description: Use igraph python's metamagic class


code:
import csv

infilename = r'c:\Python27\scripts\colnewfile.csv'
outfilename = r'c:\Python27\scripts\final.csv'

with open(infilename, 'rb') as fp_in, open(outfilename, 'wb') as fp_out:
    reader = csv.reader(fp_in, delimiter=",")
    headers = next(reader)  # read first row

    writer = csv.writer(fp_out, delimiter=",")
    writer.writerow(headers + ['email2'])

    for row in reader:
        if len(row) > 3:
            # make sure there are at least 4 columns
            email = row[3].split('@', 1)[0] + '@hotmail.com'
        writer.writerow(row + [email])

rawDescription: python csv copy column

description: Python csv copy column


code:
class ItemWarehouse(Base):
    # version-1:
    __tablename__ = 'item_warehouse'
    __table_args__ = (PrimaryKeyConstraint('item_id', 'warehouse_id', name='ItemWarehouse_PK'),)
    # version-2:
    #__table_args__ = (UniqueConstraint('item_id', 'warehouse_id', name='ItemWarehouse_PK'),)
    #id = Column(Integer, primary_key=True, autoincrement=True)

    # other columns
    item_id = Column(Integer, ForeignKey('items.id'), nullable=False)
    warehouse_id = Column(Integer, ForeignKey('warehouses.id'), nullable=False)
    quantity = Column(Integer, default=0)

rawDescription: sqlalchemy / table setup

description: Sqlalchemy / table setup


code:
a = ModelFormA()
b = ModelFormB()
c = ModelFormC()

c = {'a':a,'b':b,'c':c}
return rendertoresponse('template.html',c)

rawDescription: Django model forms - multiple models

description: Django model forms - multiple models


code:
d = defaultdict(list)
import csv
with open("in.txt") as f:
    next(f)
    for line in f:
        _id, lt_lon = line.split(",", 1)
        d[_id].append(lt_lon.rstrip())
print(d)

rawDescription: Python: reorganize data and add it to dictionary


code: newlist = rs1 + rs2

rawDescription: BeautifulSoup4 - python: how to merge two bs4.element.ResultSet and get one single list?


code:
def gen_triplet_list_from_sextuplets(st):
    triplets = [combinations(s, 3) for s in st]
    return list(t for trip in triplets for t in trip)

tlist = gen_triplet_list_from_sextuplets(sextuplets(range(10)))
len(tlist)
len(set(tlist))
tlist = gen_triplet_list_from_sextuplets(sextuplets(range(80)))
len(tlist)
len(set(tlist))

rawDescription: All triplet combinations, 6 values at a time


rawDescription: Where is the correct place to enable CORS?


code:
dates = ['08/08/2014', '09-13-2014', '10.10.1997', '9_29_09']
separators = list()
new_sep = "/"
match_pat = re.compile(r'''
    \d{1,2}              # two digits
    (.)                  # followed by a separator (capture)
    \d{1,2}              # two more digits
    \1                   # a backreference to that separator
    \d{2}(?:\d{2})?      # two digits and optionally four digits''', re.X)
for idx,date in enumerate(dates):
    match = match_pat.match(date)
    if match:
        sep = match.group(1) # the separator
        separators.append(sep)
    else:
        dates.pop(idx) # this isn't really a date, is it?
repl_pat = '|'.join(map(re.escape, separators))
final_dates = re.sub(repl_pat, new_sep, '\n'.join(dates))
print(final_dates)
# 08/08/2014
# 09/13/2014
# 10/10/1997
# 9/29/09

rawDescription: What Regex to use in this example

description: What Regex to use in this example


rawDescription: Python - How to identify un-commented if statements lines in cpp file


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


code:
import email.generator
import io
import shutil

def _encode_multipart_formdata(self, fields, files):
    boundary = email.generator._make_boundary()
    buf = io.BytesIO()
    textwriter = io.TextIOWrapper(
        buf, 'utf8', newline='', write_through=True)

    for (key, value) in fields.items():
        textwriter.write(
            '--{boundary}\r\n'
            'Content-Disposition: form-data; name="{key}"\r\n\r\n'
            '{value}\r\n'.format(
                boundary=boundary, key=key, value=value))

    for (key, filepath, filename) in files:
        if os.path.isfile(filepath):
            textwriter.write(
                '--{boundary}\r\n'
                'Content-Disposition: form-data; name="{key}"; '
                'filename="{filename}"\r\n'
                'Content-Type: {content_type}\r\n\r\n'.format(
                    boundary=boundary, key=key, filename=filename,
                    content_type=self._get_content_type3(filename)))
            with open(filepath, "rb") as f:
                shutil.copyfileobj(f, buf)
            textwriter.write('\r\n')

    textwriter.write('--{}--\r\n\r\n'.format(boundary))
    content_type = 'multipart/form-data; boundary={}'.format(boundary)
    return content_type, buf.getvalue()

rawDescription: Python 3.4 - Multipart Post Using Standard Library


code: my_list.extend( itertools.islice( reversed(color), 0, bits))

rawDescription: What is the most pythonic way to extend a list with the reversal of another?


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

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

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


code: {'rope': 1, 'gold coin': 45, 'dagger': 1, 'ruby': 1}

rawDescription: Is there a reasonable way to add to dictionary values without importing libraries?


code:
df = pd.DataFrame({"beta": beta, "cluster": item_clusters})
df.head()
df["beta"] = df["beta"].replace(0, np.nan)
df["beta"] = df["beta"].fillna(df["beta"].groupby(df["cluster"]).transform("mean"))
df.head()

rawDescription: Missing value imputation in Python

description: Missing value imputation in Python


code:
from collections import deque
from itertools import islice

def fixtures(teams):
    if len(teams) % 2:
        teams.append("Bye")

    ln = len(teams) // 2
    dq1, dq2 = deque(islice(teams, None, ln)), deque(islice(teams, ln, None))
    for _ in range(len(teams)-1):
        yield zip(dq1, dq2) # list(zip.. python3
        #  pop off first deque's left element to
        # "fix one of the competitors in the first column"
        start = dq1.popleft()
        # rotate the others clockwise one position
        # by swapping elements
        dq1.appendleft(dq2.popleft())
        dq2.append(dq1.pop())
        # reattach first competitor
        dq1.appendleft(start)

rawDescription: Grouping list combinations for round-robin tournament


code: df['letter'] =df.apply(f,axis=1)

rawDescription: Python pandas: accumulate data frame rows by condition


code:
class List(list):
    def push(self, x):
        self.append(x)

rawDescription: Can I add an operation to a list in Python?

description: Add an operation to a list in Python


code: from itertools import imap

rawDescription: Python one-liner that answers: Do any of these inputs return True for this function?


code: lst = ['Daniel', '2', 'daniel@outlook.com', 'Jay', '1212', 'jay@siber.com']

rawDescription: How do I print the following objects of a list

description: Print the following objects of a list


code: zip(*np.where(np.char.find(x, '.') > -1))

rawDescription: finding element of numpy array that satisfies condition

description: Finding element of numpy array that satisfies condition


rawDescription: How to dynamically load a Python class

description: Dynamically load a Python class


rawDescription: autodoc a class that extends a mocked class

description: Autodoc a class that extends a mocked class


code:
idx = 0
while idx < len(glist):
    if glist[idx] in glist[0:idx]:
        del glist[idx]
    else:
        idx += 1

rawDescription: Removing duplicates within list without creating a new list while preserving order


code:
import numpy as np
z = np.zeros( (3, 2) )

rawDescription: Combining Numpy Arrays in Blockwise Form


code: 'this is a verylong string toofor sure ...'

rawDescription: Pythonic way to create a long multi-line string


rawDescription: Python - Extract and reformat field names from rows of data


rawDescription: How to split the return of socket,gethostbyaddr and write to file?

description: Split the return of socket,gethostbyaddr and write to file


code:
subprocess.call([vlc_path, video_path, '--play-and-exit',
    '--fullscreen', '--stop-time','3600'], shell=False)

rawDescription: Python - quit vlc before completing video file


rawDescription: Stacked Histogram not working in Pandas

description: Stacked Histogram not working in Pandas


code:
a2 = np.ones_like(a1)
a2[::3] = 0
a1[a2.astype(bool)]

rawDescription: How to "extract" certain values out of an array?


code:
def my_function(**kwargs):
    try:
        a_value = kwargs.pop('a')
    except KeyError:
        raise TypeError("Missing required keyword argument 'a'")

    b_value = kwargs.pop(b, False)
    if b_value is True:
        try:
            c_value = int(kwargs.pop('c'))
            if not (1 <= c_value <= 10):
                raise ValueError
        except KeyError:
            raise TypeError("Must use keyword argument 'c' if 'b' is True")
        except ValueError:
            raise ValueError("'c' must be an integer between 1 and 10!")

    try:
        # Are there anymore keyword arguments? We don't care which one we get
        x = next(iter(kwargs))
    except StopIteration:
        # Good, nothing besides a, b, or c
        pass
    else:
        raise TypeError("Unrecognized keyword argument '{0}'".format(x))

    # Now do what my_function is supposed to with a_value, b_value, c_value

rawDescription: How do we define optional keywords for a function?


code:
class JobdtlSerializer(serializers.ModelSerializer):

    class Meta:
        model = Jobdtl

class JobmstSerializer(serializers.ModelSerializer):
    jobdtl_id = JobdtlSerializer()

    class Meta:
        model = Jobmst

rawDescription: django rest framework nested relationships

description: Django rest framework nested relationships


code: checkbox = QtGui.QCheckBox('Title', groupbox)

rawDescription: How to search for a specific kind of qt gui control

description: Search for a specific kind of qt gui control


code:
import re

def pcre_escape_repl(match):
    char = match.group(0)
    if ord(char) in range(32, 127):
        # if this is a printable ascii character, use re.escape instead of a \x escape
        return re.escape(char)
    # replace non-ascii (or non-printable) characters with a \x escape
    return r'\x{' + hex(ord(char))[2:] + '}'

def pcre_escape(s):
    regex = re.compile('.', re.DOTALL)
    return regex.sub(pcre_escape_repl, s)

rawDescription: unicode string to PCRE regular expression in python

description: Unicode string to PCRE regular expression in python


code:
from sklearn.feature_extraction.text import TfidfVectorizer

documents = [open(f) for f in text_files]
tfidf = TfidfVectorizer().fit_transform(documents)
# no need to normalize, since Vectorizer will return normalized tf-idf
pairwise_similarity = tfidf * tfidf.T

rawDescription: How can I detect that these two URLs drive to the same site?

description: Detect that these two URLs drive to the same site


code:
import ctypes
from random import randint

class STRUCT_2(ctypes.Structure):
    #_pack_=2
    _fields_ = [('field_1', ctypes.c_short),
                ('field_2', ctypes.c_short),
                ('field_3', ctypes.c_short),
                ('field_4', ctypes.c_short),
                ('field_5', ctypes.c_short),
                ('field_6', ctypes.c_short),
                ('field_7', ctypes.c_short),
                ('field_8', ctypes.c_short)]

class STRUCT_1(ctypes.Structure):
    #_pack_=2
    _fields_ = [('elements', ctypes.c_short),
                #an array of pointers
                ('STRUCT_ARRAY', ctypes.POINTER(ctypes.POINTER(STRUCT_2)))]

    def __init__(self,num_of_structs):
        elems = (ctypes.POINTER(STRUCT_2) * num_of_structs)()
        self.STRUCT_ARRAY = ctypes.cast(elems,ctypes.POINTER(ctypes.POINTER(STRUCT_2)))
        self.elements = num_of_structs

        for num in range(0,num_of_structs):
            self.STRUCT_ARRAY[num].field_1 = 1
            self.STRUCT_ARRAY[num].field_2 = 2
            self.STRUCT_ARRAY[num].field_3 = 3

for num in range(0,100):
    test = STRUCT_1(num)
    print("%i done" % num)

rawDescription: python ctypes array of structs

description: Python ctypes array of structs


code:
import shlex
argv = shlex.split("TRAPTOOL -a STRING \"ABC\" -o STRING 'XYZ'")
myProcess = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)
(stdOut, stdErr) = myProcess.communicate()

rawDescription: python subprocess sends backslash before a quote

description: Python subprocess sends backslash before a quote


rawDescription: how to search through a mongodb collection for dictionary keys nested in array

description: Search through a mongodb collection for dictionary keys nested in array


code:
class Test(Base):
    __tablename__ = 'test'
    created_at = Column(TZDateTime)

rawDescription: How do I handle "out of range" warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy

description: Handle "out of range" warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy


code: d = d.pivot_table(index=['Team','Date'], columns=['Metric', 'Unit']).reset_index()

rawDescription: Pandas DataFrame efficient moving of data


code:
def speed_inverse(score, attacks_per_second):
    """
    as above, but higher scores are better
    """
    return attacks_per_second * (score / 100)

rawDescription: trying to figure out a weird math formula

description: Trying to figure out a weird math formula


code:
if all is not None:
     # only document that which the programmer exported in __all__
     return name in all

rawDescription: Using pydoc on modules with imported functions


code:
# do some stuff to extract the parameters
# do something with the parameters
# return the response.

rawDescription: Can't figure out how to invoke cProfile inside of a program


rawDescription: Accessing the column of the matrix

description: Accessing the column of the matrix


code:
for line in f_in.readlines():
    actual_line = line.rstrip('\n')

rawDescription: Python readlines() and append data to each line output to one line


code:
for idx, (bl, dl) in enumerate(zip(buttonlist, daylist)):
    TKinter.Button(text=dl, command=lambda: button_pressed(bl))

rawDescription: Python: Assign commnds to buttons using a for loop when using Tkinter


code:
class Curried(object):
    def __init__(self, func, args=None, kwargs=None):
        self._func = func
        self._args = () if args is None else args[:]
        self._kwargs = {} if kwargs is None else dict(kwargs)
        self._name = None

    def __call__(self, *args, **kwargs):
        if args or kwargs:
            return Curried(self._func,
                           self._args + args,
                           dict(self._kwargs.items() + kwargs.items()))
        else:
            return self._func(*self._args, **self._kwargs)

    def __str__(self):
        if self._name is None:
            self._name = self._get_curried_name()
        return self._name

    def _get_curried_name(self):
        _args = ([str(a) for a in self._args] +
                 ['{}={}'.format(k, v) for k, v in self._kwargs.iteritems()])
        all_args = ", ".join(_args)
        return '<curried {}({}) at 0x{:x}>'.format(
            self._func.func_name, all_args, id(self))

    def curry(func):
        _curried = Curried(func)
        return _curried

rawDescription: Is there any way to lazy evaluate function.func_name?


code:
def year_month(s):
     try:
         discard, month, rest = s.split('/', 2)  # split twice on '/'
     except ValueError:
         return None  # for last line without /
     year = rest.split(':', 1)[0]
     year = int(year)  # optional
     return year, month

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


code:
class A(object):
    def fun(self):
        print ("hello world")

ins_a = A.fun
ins_b = A().fun

rawDescription: What is difference between A.fun and A().fun?


code:
if x in list1:
    n=list1.index(x)
    n2=n-n1
    y=list1[n2]
    print(y)
else:
    print(x)

rawDescription: How can i get python to check if every term of a input is in list1, and if not print the term as is?

description: Get python to check if every term of a input is in list1, and if not print the term as is


rawDescription: Group computation between rows on condition


code:
class Foobar(object):
    def __init__(self, init_dict):
        self.__dict__.update(init_dict)

rawDescription: Should I extract values from Python dictionaries into object attributes?


code:
def my_input(*args):   # input() takes either no args or one non-keyword arg
    try:
        return input(*args)
    except KeyboardInterrupt:
        print('^C')   # on my system, input() doesn't show the ^C
        return '\n'

rawDescription: Handle CTRL-C in Python cmd module

description: Handle CTRL-C in Python cmd module


code:
pd.merge(left=df, left_index=True,
         right=df2, right_index=True)

rawDescription: Python Pandas - Reformat Datetime Index

description: Python Pandas - Reformat Datetime Index


rawDescription: Flask session attribute loses typing after initial load


code: im = Image.frombuffer('RGB', (img.width, img.height), buff)

rawDescription: Pixel manipulation with PIL.Image and ctypes


code:
cam.stopPreview()
cam.release()

rawDescription: Accessing android flashlight(camera LED flash) with kivy/python


rawDescription: Most Efficient Method of Searching Neighbour Data for Nth Neighbour


code: contains_Hamburg = any('Hamburg' == c for c, s in cities)

rawDescription: Use in, on a list to check one item in tuple


code:
import argparse
parser = argparse.ArgumentParser(description='Some Description')
parser.add_argument('command', help='Either stop or start', choices=['start', 'stop'])

args = parser.parse_args()
print(args.command)

rawDescription: Python3 daemon library

description: Python3 daemon library


code:
py-django
py25-django
py26-django

rawDescription: Django Python Macports

description: Django Python Macports


code:
def FindOccurences(data, condition, left, right):
    func = eval( u"lambda data, i : " + condition)
    return [i for i in range(left, right) if func(data, i)]

rawDescription: Get fast functor from text of expression in Python (faster than eval)


code:
"""
Setup for Ghostscript 9.07:

Download it from http://www.ghostscript.com/GPL_Ghostscript_9.07.html
and add `/path/to/gs9.07/bin/` and `/path/to/gs9.07/lib/` to your path.
"""

import Tkinter as tk
import subprocess
import os

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Canvas2PDF")
        self.line_start = None
        self.canvas = tk.Canvas(self, width=300, height=300, bg="white")
        self.canvas.bind("<Button-1>", lambda e: self.draw(e.x, e.y))
        self.button = tk.Button(self, text="Generate PDF",
                                command=self.generate_pdf)
        self.canvas.pack()
        self.button.pack(pady=10)

    def draw(self, x, y):
        if self.line_start:
            x_origin, y_origin = self.line_start
            self.canvas.create_line(x_origin, y_origin, x, y)
            self.line_start = None
        else:
            self.line_start = (x, y)

    def generate_pdf(self):
        self.canvas.postscript(file="tmp.ps", colormode='color')
        process = subprocess.Popen(["ps2pdf", "tmp.ps", "result.pdf"], shell=True)
        process.wait()
        os.remove("tmp.ps")
        self.destroy()

app = App()
app.mainloop()

rawDescription: Python tkinter save canvas as postscript and add to pdf


code:
def test():
    print("I'm called only once")
    return False

def foo(b=5 if test() else 10):
    print(b)

foo()
foo()

rawDescription: Python function optional arguments - possible to add as condition?


rawDescription: Python: extract Cyrillic string from EXIF


code:
from distutils.core import setup
from distutils.dist import Distribution

# Get our own instance of Distribution
dist = Distribution()
dist.parse_config_files()
dist.parse_command_line()

# Get prefix from either config file or command line
prefix = dist.get_option_dict('install')['prefix'][1]
print("Prefix is: " + prefix)

# Use the prefix to decide on the data path for data.txt
setup(data_files=[('/first/path/to/data' if prefix == '/some/prefix'
                                         else '/second/path/to/data',
                   ['data.txt'])])

rawDescription: Referring to existing distutils options inside setup.cfg and setup.py


code:
d = {'bar': 456}
for key,value in d.items():
    setattr(c,key,value)

rawDescription: Python update object from dictionary

description: Python update object from dictionary


code:
#!/usr/bin/env python
import cgi; cgi.test()

rawDescription: How to run python script on my server?

description: Run python script on my server


code:
end_location = [1, 0, 3, 5, 7, 0, 0, 3]
for v in reversed(range(1, max(end_location)+1)):
    print(''.join('0' if x >= v else ' ' for x in end_location))

rawDescription: The Bean Machine Function - Python

description: The Bean Machine Function - Python


code: new_list = [x * y * z for x, y, z in zip(a, b, c)]

rawDescription: How to multiple each object of several lists in Python

description: Multiple each object of several lists in Python


code: from module import Class

rawDescription: Is it costly in Python to put classes in different files?


rawDescription: get some substring from readline() in python with regular expression

description: Get some substring from readline() in python with regular expression


code:
#!/usr/bin/env python

import glob
import os

map(os.unlink, glob.glob(u'*.txt'))

rawDescription: os.unlink multiple file in python

description: Os.unlink multiple file in python


code: df

rawDescription: python collecting data from dataframe at specific row location

description: Python collecting data from dataframe at specific row location


code:
s="This is a regular sentence."
import re
re.findall(r'\w+\s?', s)

rawDescription: Confusing Behaviour of regex in Python

description: Confusing Behaviour of regex in Python


code:
sub1_x = nx.iloc[subject1_index]
sub1_y = ny.iloc[subject1_index]
for i in subject1_index:
    plt.plot(nx.iloc[i], ny.iloc[i], 'r', alpha=.3)
plt.plot(sub1_x.mean(), sub1_y.mean(), 'r', linewidth=2)

rawDescription: Coding variables with Pandas TimeSeries

description: Coding variables with Pandas TimeSeries


code:
f = input("Please enter a number: ")
try:
    f=int(f)
    print("That's good")
except ValueError:
    print("That isn't a number.")

rawDescription: How to print something on the basis of data (input) type?

description: Print something on the basis of data (input) type


code: orig

rawDescription: Interpolation when no datarow exists

description: Interpolation when no datarow exists


rawDescription: Regex to insert a character at the beginning of each word


code:
def filename_with_no_extension(filepath):
    from os.path import splitext, basename
    return splitext(basename(filepath))

rawDescription: PyCharm file path separator

description: PyCharm file path separator


code:
from gevent import monkey
monkey.patch_all(thread=False)

rawDescription: Gevent,http/cgi non blocking server

description: Gevent,http/cgi non blocking server


code: (x == xmax).sum(axis=0)

rawDescription: numpy count elements across axis 0 matching values from another array

description: Numpy count elements across axis 0 matching values from another array


code:
import mmap

with open("crap.txt", "r+b") as f:
    # Create the mapper
    mapper = mmap.mmap(f.fileno(), 0)
    # Initialize your output variables
    latitudes = []
    blocks = []
    # Find the beginning of the first block
    position = mapper.find("latitude")
    # `position` will be -1 if we can't find it
    while (position >= 0):
        # Move to the beginning of the block
        mapper.seek(position)
        # Read the first line
        lat_line = mapper.readline().strip()
        latitudes.append(lat_line.split()[-1])
        # Read the second one
        zap = mapper.readline()
        # Where are we ?
        start = mapper.tell()
        # Where's the next block ?
        position = mapper.find("latitude")
        # Read the lines and combine them into a large string
        current_block = mapper.read(position-start).replace("\n", " ")
        # Transform the string into a list of floats and update the block
        blocks.append(list(float(i) for i in current_block.split() if i))

rawDescription: How to parse block data from a text file into an 2D array in Python?

description: Parse block data from a text file into an 2D array in Python


code:
from bs4 import BeautifulSoup

content = '''
<root>

        12
        F5684
        20182
        VELOCITY SOLUTIONS INC.
        EQPRAN77717
        RANPAK FILLPAK TT 2
        W/UNIVERSAL STAND S/N 51345563
        1
        51345563

        Grand Total

</root>'''

soup = BeautifulSoup(content, 'html')

answer = []
rows = soup.find_all('tr')

for row in rows:
    if not row.text.strip():
        continue

    row_text = []
    for cell in row.find_all('td'):
        if cell.text.strip():
            row_text.append(cell.text)

    answer.append(row_text)

print(answer)

rawDescription: Python & BS4: Exclude blank and Grand Total Row


rawDescription: Parse FB Graph API date string into python datetime


rawDescription: Mask numpy array using intervals

description: Mask numpy array using intervals


code:
myfunc = f()
# ('a',)
print(myfunc.__code__.co_freevars)
# (<cell at 0xb7abce84: int object at 0x82b1de0>,)
print(myfunc.__closure__)

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

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


code:
import numpy as np

def foo(x):
    """Return 2D square array of zeros."""
    return np.zeros((x, x))

del np

rawDescription: Delete modules to clean namespace?

description: Delete modules to clean namespace


code:
job = group(ping.s(ip) for ip in ipToPing)
result = job.apply_async()
while not result.ready():
    time.sleep(0.1)
result.save()
return result.id

rawDescription: Celery - One task calls a smaller task n times with different parameters


code: "902".isdigit() and "2".isdigit()

rawDescription: Why does this Python boolean comparison return a triple?


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

def f(x, r):
    """Discrete logistic equation with parameter r"""
    return r*x*(1-x)

if __name__ == '__main__':
    # initial condition for x
    ys = []
    rs = numpy.linspace(0, 4, 400)

    # Loop through `rs`. `r` is assigned the values in `rs` one at a time.
    for r in rs:
        x = 0.1
        # Repeat this loop 500 times.
        # i is just a dummy variable since it is not used inside the for-loop.
        for i in range(500):
            # Evaluate f at (x, r). The return value is assigned to x.
            # x is then fed back into f(x, r).
            # This makes x jump around 500 times according to the logistic equation.
            # r remains fixed.
            x = f(x, r)

        # Do this 50 times
        for i in range(50):
            # Again make the x jump around according to the logistic equation
            x = f(x, r)
            # Save the point (r, x) in the list ys
            ys.append([r, x])

    # ys is a list of lists.
    # You can also think of ys as a list of [r, x] point.
    # This converts the list of lists into a 2D numpy array.
    ys = numpy.array(ys)

    # ys[:,0] is a 1D array of r values
    # ys[:, 1] is a 1D array of x values
    # This draws a scatter plot of (r, x) points.
    pylab.plot(ys[:,0], ys[:,1], '.')
    pylab.show()

rawDescription: Code for logistic equation

description: Code for logistic equation


code:
output = BottomPipeResult.scrapeResult(myLinkResult)
f.write('\n'.join(['<p>' + x + '</p>' for x in output.split('\n')]))

rawDescription: Python: How to keep breaks reading from a txt file when printing to html


code:
import re
from pprint import pprint

with open('Packages') as fp:
    data = fp.read()

data = re.findall(
    r'''
    (?smx)                  # Dot matches all, Multiline, Verbose
    ^Package:\s*(.*?)$      # The package line
    .*?                 #     Arbitrary lines
    (?:
        ^Provides:\s*(.*?$) # The provides line
        |                   # OR
        ^$                  #  an empty line
    )
    ''',
    data)

data = {k:v.split(',') if v else [] for k,v in data}

pprint(data)

rawDescription: Extracting what each package provides from a text file using regex in python


code:
random.shuffle(Questions)   # This shuffles `Questions` in-place

print(Questions[0])
...

rawDescription: Python - Lists checking if something has been randomised already


code:
s = "Group <stuffhere> User <IwantThis> IP <notimportant> Address <IalsoWantThis> assigned"
ans = re.findall(r'<(.+?)>', s)

rawDescription: Regex expression in Python to match text after words and between angle brackets


code:
broadsword = Item.objects.get(name='Broadsword')
player1.set_item(broadsword, at_slot='main_hand')
player1.items.all()

rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


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

"""
This is the base py file for the GUI

Todo list
-----------------
- Pop up menu for adding new Nodes
- node connectivity
- create data structure for storing

"""

import sys
from PyQt4 import QtGui, QtCore
from array import *

"""
Base class for a node. Contains all the inilization, drawing, and containing inputs and outputs
"""
class node(QtGui.QGraphicsRectItem):

    width = 100
    height = 100
    color = 1
    x = 90
    y = 60
    inputs=[]
    outputs=[]
    viewObj = None

    def __init__(self, n_x, n_y, n_width,n_height):
        QtGui.QGraphicsRectItem.__init__(self, n_x, n_y, n_width, n_height)
        self.width = n_width
        self.height = n_height
        self.x = n_x
        self.y = n_y
        self.setFlag(QtGui.QGraphicsItem.ItemIsMovable, True)
        self.setFlag(QtGui.QGraphicsItem.ItemIsSelectable, True)
        self.iniNodeData()

    def mousePressEvent(self, e):
        print("Square got mouse press event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsRectItem.mousePressEvent(self, e)

    def mouseReleaseEvent(self, e):
        print("Square got mouse release event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsRectItem.mouseReleaseEvent(self, e)

    """
    This is where inputs and outputs will be created based on node type
    """
    def iniNodeData(self):
        print('making node data')
        for j in range(5):
            this = self
            x = input(this,0, 0+(j*10))
            self.inputs.append(x)

        for k in range(5):
            this = self
            x = output(this,self.x+self.width, self.y+(k*10))
            self.outputs.append(x)

    def mouseMoveEvent(self, event):
        print('Dragging@')
        QtGui.QGraphicsRectItem.mouseMoveEvent(self, event)

    def mousePressEvent(self, event):

        print('moving!')

"""
Nodes will evaluate from the last node to the first node, therefore inputs are evaluted
"""
class input(QtGui.QGraphicsRectItem):
    currentConnectedNode = None
    currentConnectedOutput = None
    parentNode = None
    width = 10
    height = 10
    x = 1
    y = 1
    color = 1
    drawItem = None

    def __init__(self, pnode, posX, posY):
        self.parentNode = pnode
        self.x = posX
        self.y = posY
        self.color = 1
        QtGui.QGraphicsRectItem.__init__(self, self.x+self.parentNode.x, self.y+self.parentNode.y, self.width, self.height, self.parentNode)

'''
Output value from a node
'''
class output(node):
    parentNode = None
    width = 10
    height = 10
    x = 1
    y = 1

    def __init__(self, pnode, posX, posY):
        self.parentNode = pnode
        self.x = posX
        self.y = posY
        self.color = 1
        QtGui.QGraphicsRectItem.__init__(self, self.x-self.width, self.y, self.width, self.height, self.parentNode)

'''
Check Click events on the scene Object
'''
class Scene(QtGui.QGraphicsScene):

    nodes = []

    def mousePressEvent(self, e):
        print("Scene got mouse press event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsScene.mousePressEvent(self, e)

    def mouseReleaseEvent(self, e):
        print("Scene got mouse release event")
        print("Event came to us accepted: %s"%(e.isAccepted(),))
        QtGui.QGraphicsScene.mouseReleaseEvent(self, e)

    def dragMoveEvent(self, e):
        print('Scene got drag move event')

    def addNode(self):
        newNode = self.addItem(node(250,250,100,150))
        self.nodes.append(newNode)

'''
Main Window Object
'''

class MainWindowUi(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setWindowTitle('RIS RIB Generator')
        self.scene = Scene(0, 0, 800, 850, self)
        self.view = QtGui.QGraphicsView()
        self.setCentralWidget(self.view)
        self.view.setScene(self.scene)

        exitAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)

        newNodeAction = QtGui.QAction(QtGui.QIcon('exit24.png'), 'New Node', self)
        newNodeAction.setStatusTip('Add a blank node')
        newNodeAction.triggered.connect(self.scene.addNode)

        self.statusBar()
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(newNodeAction)
        fileMenu.addAction(exitAction)

'''
Start Point
'''

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = MainWindowUi()
    win.show()
    sys.exit(app.exec_())

rawDescription: PyQt Node interface - Parrent to ItemIsMovable object


code:
disk_exists("/dev/bsd0")
True
disk_exists("/dev/bsd2")
False

rawDescription: Python: Check if a /dev/disk device exists


code:
def visualizeSignals(self, imin, imax):

    times = self.time[imin:imax]
    nrows = (int)((times[(len(times)-1)] - times[0])/self.mod) + 1

    fig = plt.figure('2d profiles')
    ax = fig.gca(projection='3d')
    for i in range(nrows-1):
        x = self.mat1[i][0] + self.mod * i
        y = np.array(self.mat1T[i])
        z = np.array(self.mat2[i])
        ax.plot(y, z, zs = x, zdir='z')

    plt.show()

rawDescription: matplotlib wireframe plot / 3d plot howTo

description: Matplotlib wireframe plot / 3d plot howTo


code:
def foo(*bars):
    for bar in bars:
        print(bar)

list_of_things = ['one', 'two', 'three']

foo(*list_of_things)

rawDescription: Python - list of dicts into function that only accepts *dicts


rawDescription: Python: use regular expression to remove the white space from all lines


code:
dict((k, v if isinstance(v, (unicode, int, long)) else unicode(v))
     for k,v in dct.iteritems())

rawDescription: In Python, loop through a dict and set all values of list or dict to string


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


code:
prev_dates = included.date.shift().fillna(pd.datetime(2012,1,2))
prev_dates

rawDescription: Pandas days between in a single column

description: Pandas days between in a single column


code:
import sys
print(sys.version)

rawDescription: how to check which compiler was used to build Python

description: Check which compiler was used to build Python


code: dbh = pyodbc.connect(db_credentials)

rawDescription: Mocking pyodbc module calls for django unit tests


code: ref + ',' + alt

rawDescription: How to merge cells in python3

description: Merge cells in python3


code: re.match(r'^\S+\s+\b%s\b' % CartID, line)

rawDescription: Python re.search exact match on variable


rawDescription: Remove return key (\n) from read file

description: Remove return key (\n) from read file


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

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


code:
{('someFileName.jpg', 'forecolor'): [2,3,5,5,6],
 ('someFileName.jpg', 'edge'): [2,4,5],
 ('someFileName.jpg', 'texture'):[5,4,3]}

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


code:
from __future__ import print_function

from itertools import permutations
import pandas as pd

df = pd.read_csv('data.csv', sep='\s+', index_col=['Person'])
print(df)

idx = list(permutations(df.index, 2))

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

print(new)

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


code: A.ravel()[np.in1d(A,B)] = 0

rawDescription: Intersection of 2d and 1d Numpy array

description: Intersection of 2d and 1d Numpy array


code:
xys_bot = []
xys_top = []

rawDescription: Draw a line correlating zones between multiple subplots in matplotlib


code:
mydict ={'Plekhg2': {'Bcells': '233.55', 'DendriticCells': '190.12'},
  'Barxxxx': {'Bcells': '132.11', 'DendriticCells': '92.01'}, }
{k: sum(float(f) for f in v.itervalues()) for k, v in mydict.iteritems()}

rawDescription: Sum up values from a dictionary (the Python way)


code: sales[index] = float(input("Sales for day #{}: ".format(index+1)))

rawDescription: Creating a list of integers, adding the list and displaying the sum


code:
import csv
import io  # requires Python 2.6+

filename = 'many_values_per_line.txt'

with io.open(filename, 'r', newline='') as f_input:
    csv_input = csv.reader(f_input, delimiter=' ', skipinitialspace=True)
    header = next(csv_input)
    blocks = []
    block = []
    for row in csv_input:
        if row:
            block.append(row)
        elif block:
            blocks.append(zip(*block))
            block = []
    if block:  # final block
        blocks.append(zip(*block))
    columns = [list(i) for i in zip(*blocks)]

for i, column in enumerate(columns):
    print('column {}: {}'.format(i, column))
print('')
print('columns[1][0]: {}'.format(columns[1][0]))

rawDescription: How to read many values separated by newlines

description: Read many values separated by newlines


code:
def get_libc_name():
    if sys.platform == 'win32':
        # Parses sys.version and deduces the version of the compiler
        import distutils.msvccompiler
        version = distutils.msvccompiler.get_build_version()
        if version is None:
            # This logic works with official builds of Python.
            if sys.version_info < (2, 4):
                clibname = 'msvcrt'
            else:
                clibname = 'msvcr71'
        else:
            if version <= 6:
                clibname = 'msvcrt'
            else:
                clibname = 'msvcr%d' % (version * 10)

        # If python was built with in debug mode
        import imp
        if imp.get_suffixes()[0][0] == '_d.pyd':
            clibname += 'd'

        return clibname+'.dll'
    else:
        return ctypes.util.find_library('c')

# Make sure the name is determined during import, not at runtime
libc_name = get_libc_name()
standard_c_lib = ctypes.cdll.LoadLibrary(get_libc_name())

rawDescription: Access to errno from Python?

description: Access to errno from Python


code:
import my_socket_module as socket_imported

socket_imported = imp.load_module('my_socket_module',
    *imp.find_module('my_socket_module')
)

rawDescription: How to make a copy of a python module in runtime?

description: Make a copy of a python module in runtime


rawDescription: Python weekday() for getting Sunday as 1 & Saturday as 7


rawDescription: Adding index level to a dataframe

description: Adding index level to a dataframe


code:
changed = '1010101'
changed = ''.join(newstate[c] for c in changed)
changed

rawDescription: How to implement the concept of cellular automata in python

description: Implement the concept of cellular automata in python


rawDescription: Difference in text file saved manually and with Python codecs : Lemur Malformed document


code:
def factorial(n):
    r = 1
    i = 2
    while i <= n:
        # Use shorter version
        r *= i
        i += 1
    return r

rawDescription: Custom non-recursive factorial function refuses further input after execution


code:
L = len(X)
K = np.identity(L) - np.ones((L, L)) / L

rawDescription: Loops to minimize function of arrays in python


code:
pagination +='
%(current)s
' % \
                     {'current_link': current_link, 'current': current_link}

rawDescription: String formatting in python isn't working as expected


code:
def create_random_chromosomes(genes):
    chromosomes = set()
    randomgenes = genes[:]
    for i in range(2000):
        random.shuffle(randomgenes)
        chromosomes.add(tuple(randomgenes))
    return list(chromosomes)

rawDescription: python random.shuffle() in a while loop

description: Python random.shuffle() in a while loop


rawDescription: NLTK - Counting Frequency of Bigram

description: NLTK - Counting Frequency of Bigram


code:
import clr
import System
typelib = clr.LoadTypeLibrary(System.Guid("00020905-0000-0000-C000-000000000046"))
word = typelib.Word.Application()

rawDescription: How to import COM into Ironpython?

description: Import COM into Ironpython


rawDescription: Append to a dict of lists with a dict comprehension


code: data[param_tag_pos + 1: model_tag_pos]

rawDescription: Split list based on first character - Python


code:
def sequences(mapping, lst):
    result = None
    for elem in lst:
        if elem == 'AUG' and result is None:
            # start a new list
            result = []
        if result is None:
            # not currently creating an input sequence, ignore this element
            continue
        value = mapping.get(elem)
        if value is None or value == '*':
            # sequence end
            yield result
            result = None
            continue
        result.append(value)

rawDescription: Python list slicing sequence genetic code


rawDescription: change Pandas dataframe column order in place

description: Change Pandas dataframe column order in place


code:
result = Counter()
for c in counters:
    result |= c

rawDescription: Union of many Counters

description: Union of many Counters


code: df.loc[mask,1] = 'lincRNA'

rawDescription: How can I replace a column given a specific condition in python?

description: Replace a column given a specific condition in python


code:
import csv
from collections import OrderedDict
from itertools import groupby
from operator import itemgetter

with open('in.csv') as f:
    r = csv.reader(f)
    od = OrderedDict()
    for k, v in groupby(r, key=itemgetter(0)):
        od[k] = [sub[1:] for sub in v]

rawDescription: Converting CSV data to list in dictionary


code: "%0.2f" % yournumber

rawDescription: defining precision in python(2.6) division

description: Defining precision in python(2.6) division


code:
# assumes Python 2.7

from Bio import SeqIO
from collections import Counter
from itertools import izip, product, tee

def get_aligned_quads(seq, length=4):
    args = [iter(seq)] * length
    return (''.join(letters) for letters in izip(*args))

def get_unaligned_quads(seq, length=4):
    args = tee(iter(seq), length)
    for steps,arg in enumerate(args):
        for step in range(steps):
            next(arg, None)
    return (''.join(letters) for letters in izip(*args))

all_quads = [''.join(seq) for seq in product("ACGT", repeat=4)]

def quad_freq(sequence, aligned=True):
    get_quads = get_aligned_quads if aligned else get_unaligned_quads
    counts    = {quad:[] for quad in all_quads}

    for i,record in enumerate(SeqIO.parse(sequence, 'fasta')):
        for quad in all_quads:
            counts[quad].append(0)
        for quad in get_quads(record.seq):
            counts[quad][i] += 1
    return counts

print(quad_freq("$foo"))

rawDescription: iterate through existing keys and update dictionary python

description: Iterate through existing keys and update dictionary python


code:
A = [[1,'a'],[1,'b'],[2,'c'],[2,'d'],[1,'e'],[2,'f']]
stack = [ [] ]
for level, item in A:
    while len(stack) > level:
        stack.pop()
    while len(stack) <= level:
        node = (item, [])
        stack[-1].append(node)
        stack.append(node[1])

result = stack[0]

rawDescription: Python: Read a list with tree depth level and output a tree like nested list


code: re.compile(r"RESPONSE from[^:]+:\s*TSB\d Duration:\s*(\d+) seconds.*?RESPONSE from[^:]+:\s*TSB\d Bit Rate:\s*(\d+) kbps", re.DOTALL)

rawDescription: multiline regex pattern match

description: Multiline regex pattern match


code:
#!/usr/bin/python3

#Python DBUS Test Server
#runs until the Quit() method is called via DBUS

from gi.repository import Gtk
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

class MyDBUSService(dbus.service.Object):
    def __init__(self):
        bus_name = dbus.service.BusName('org.my.test', bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, '/org/my/test')

    @dbus.service.method('org.my.test')
    def hello(self):
        """returns the string 'Hello, World!'"""
        return "Hello, World!"

    @dbus.service.method('org.my.test')
    def string_echo(self, s):
        """returns whatever is passed to it"""
        return s

    @dbus.service.method('org.my.test')
    def Quit(self):
        """removes this object from the DBUS connection and exits"""
        self.remove_from_connection()
        Gtk.main_quit()
        return

DBusGMainLoop(set_as_default=True)
myservice = MyDBUSService()
Gtk.main()

rawDescription: Use dbus to just send a message in Python


rawDescription: How would I convert words to numbers in python 3 (own keys and values)?


code:
left = [pd.DataFrame({'Column_A' : [1],
                      'Column_B' : [2]},
                     index = ["row1"]),
        pd.DataFrame({'Column_A' : [3],
                      'Column_B' : [4]},
                     index = ["row2"])]

right = [pd.DataFrame({'Column_C' : [5],
                       'Column_D' : [6]},
                      index = ["row1"]),
         pd.DataFrame({'Column_C' : [7],
                       'Column_D' : [8]},
                      index = ["row2"])]

df = pd.concat(left).merge(pd.concat(right), left_index=True, right_index=True)

rawDescription: Merge many sub-dataframes in a big dataframe in a loop in python pandas


code:
now = datetime.now()
now_plus_thirtydays = now + timedelta(days=30)
def get_calendar_events(pageToken=None):
    events = gc_source.service.events().list(
        calendarId=cal_id[cal_count],
        singleEvents=True,
        orderBy='startTime',
        timeMin=now.strftime('%Y-%m-%dT%H:%M:%S-00:00'),
        timeMax=now_plus_thirtydays.strftime('%Y-%m-%dT%H:%M:%S-00:00'),
        pageToken=pageToken,
        ).execute()
    return events

rawDescription: How to return ALL events in a Google Calendar without knowing whether it is a timed or all day event

description: Return ALL events in a Google Calendar without knowing whether it is a timed or all day event


rawDescription: Reducing an axis with numpy

description: Reducing an axis with numpy


code:
X = {
    "Meats": {
        "Pig": [
            ["Bacon"], ["Ham"]
        ],

        "Cow": [
            ["Ribs"], ["Steak"]
        ]
     },

     "Non-Meats": {
         "Fruit": [
            ["Apple"],  ["Oranges"]
        ],

        "Vegetable": [
            ["Broccoli"], ["Carrots"]
        ]
    }
}

rawDescription: Loop through 3 levels of lists

description: Loop through 3 levels of lists


code: from user_directory.models import Contact

rawDescription: Python mock patch not reseting the return value


code:
import re

xml = "your XML String"
pattern = re.compile('app name="test"')
replaced = pattern.sub('app name="delete me"', xml)

rawDescription: How to to search a key in an xml and replace it's value with Python?

description: To search a key in an xml and replace it's value with Python


code:
df = pd.merge(df1, df2, how='outer')
df

rawDescription: Adding/inserting values in pandas dataframe based on 1 or more columns


code: stack = [[node, True]]

rawDescription: Stack based modified preorder tree traversal


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


code:
import matplotlib.pyplot as plt
plt.hist([1, 2, 1], bins=[0, 1, 2, 3])
plt.show()

rawDescription: How does numpy.histogram() work?

description: How does numpy.histogram() work


code:
m = MyItem()
m.foo = 42       # works
m.bar = "hello"  # works
m.test = 12      # raises AttributeError

rawDescription: Ruby like DSL in Python

description: Ruby like DSL in Python


code:
import io
with io.open(filename,'r',encoding='utf8') as f:
    text = f.read()
# process Unicode text
with io.open(filename,'w',encoding='utf8') as f:
    f.write(text)

rawDescription: Python reading from a file and saving to utf-8


code:
from fractions import Fraction
Fraction(98, 42)

rawDescription: Does Python have a function to reduce fractions?


code:
class justAClass(object):
    def do_something(self, pause):
        while True:
            time.sleep(pause)
            print("Thread2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

rawDescription: Python running two threads simultaneously


rawDescription: python regex comma separated group

description: Python regex comma separated group


code: # encoding: utf-8

rawDescription: UTF in Python Regex

description: UTF in Python Regex


code:
set1 = ["a","b","c","d","e","f"]
set2 = ["a","c","e"]

inter = set(set2).intersection(set1)

vals = {k:k in inter for k in set1}

print(vals)
{'a': True, 'c': True, 'b': False, 'e': True, 'd': False, 'f': False}

rawDescription: Comparing each element between 2 sets?

description: Comparing each element between 2 sets


code: HERE

rawDescription: numpy python class calling wrong __setitem__

description: Numpy python class calling wrong __setitem__


rawDescription: Efficient 1D array comparison, scaling and summation


code:
def assign_var(tokens):
    if tokens.assign_op == '*=':
        # store expression to be eval'ed later
        EvalConstant.var_[tokens.varname] = tokens.varvalue
    else:
        # eval now and save result
        EvalConstant.var_[tokens.varname] = tokens.varvalue.eval()

rawDescription: Evaluating nested variables with pyparsing for a DSL


code:
from dateutil.parser import parse
parse('8th April')

rawDescription: Date conversion with strptime()

description: Date conversion with strptime()


code:
s = "this is  a\nsentence"
re.split(r'(\W+)', s) # Notice parentheses and a plus sign.

rawDescription: Partitioning a string in Python by a regular expression


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

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


code:
df = pd.DataFrame({'data':[24,26,27,28,26]})
df['result'] = df['data'].diff().fillna(0)
df

rawDescription: create a column in a pandas dataframe which calculates the difference between two rows

description: Create a column in a pandas dataframe which calculates the difference between two rows


code: re.compile('See full summary', re.DOTALL | re.IGNORECASE)

rawDescription: Match href value with a regular expression


rawDescription: How can i have more than 255 arguments in Z3py function?

description: Have more than 255 arguments in Z3py function


code:
text = "hello, this is some text to break up, with some reeeeeeeeeaaaaaaally long words."
n = 16

words = iter(text.split())
lines, current = [], next(words)
for word in words:
    if len(current) + 1 + len(word) > n:
        lines.append(current)
        current = word
    else:
        current += " " + word
lines.append(current)

rawDescription: Split a string into pieces of max length X - split only at spaces


code:
def my_open(filename, *args):
    logger.debug('Opening %s' % filename)
    return open(filename, *args)

def my_close(file_obj):
    logger.debug('Closing %s' % file_obj.name)
    return file_obj.close()

rawDescription: How can I find out which line of code is leaving a file open?

description: Find out which line of code is leaving a file open


rawDescription: Parsing graph data file with Python

description: Parsing graph data file with Python


code:
unqA, idx=np.unique(x['recod'], return_inverse=True)
cnt = np.bincount(idx, x['count'])

rawDescription: Merging records in a Numpy structured array


code:
def get_transfers(self):
    return Transfers.objects.filter(person=self)

rawDescription: Get self instance from within model in Django


code:
d = {'(': 'a'}
"".join(d.get(x,x) for x in 'text with m(ny letters')

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
from django.db import models
from django.core.exceptions import ValidationError

class Status(models.Model):
    name = models.CharField(max_length=30)

class Person(models.Model):
    name = models.CharField(max_length=30)
    status = models.ManyToManyField(Status)

    def clean(self):
        # check person status count
        if self.status.all().count() > 3:
            raise ValidationError("Person can not have more than 3 statuses")

rawDescription: Need help on Django Modelling

description: Need help on Django Modelling


code:
# For autoreloading of modules (%autoreload, %aimport)
import ipy_autoreload

rawDescription: revert/undo/redo/refresh, an `import` in interactive python session

description: Revert/undo/redo/refresh, an `import` in interactive python session


code:
import exp_protocols

switch_blocks = [
    [Relay('1-A'), Relay('1-B'), Gauge('1-1')],
    [Relay('2-A'), Relay('2-B'), Gauge('2-1')],
]

for switch1, switch2, gauge in switch_blocks:
    exp_protocols.my_protocol(switch1, switch2, gauge)

rawDescription: Accessing global variables from inside a module


code: date.strftime("%m %d, %Y %H:%M:%S")

rawDescription: Convert LinkedIn APIs time to a standard date in Python


code:
np.matrix(B).shape     # one row
np.matrix(B).T.shape   # one column

rawDescription: Is it possible to use einsum to transpose everything?


rawDescription: Numpy append ones to matrix

description: Numpy append ones to matrix


code:
s = "abcdefgh"
[s[i:i+4] for i in xrange(len(s)-3)]

rawDescription: Most efficient way to take sequential substrings python


code:
import re
pat = re.compile('ENABLEPRINTER|PRINTERLIST|PRNT1.PORT')

def jojo(mat,dic = {'ENABLEPRINTER':'y',
                    'PRINTERLIST':'PRNT3',
                    'PRNT1.PORT':'734'} ):
    return dic[mat.group()]

with open('configfile','rb+') as f:
    content = f.read()
    f.seek(0,0)
    f.write(pat.sub(jojo,content))
    f.truncate()

rawDescription: Edit configuration file through python

description: Edit configuration file through python


code:
import sys, time
from PyQt4 import QtGui, QtCore

class TimeSlider (QtGui.QVBoxLayout):
    def __init__ (self):
        QtGui.QVBoxLayout.__init__ (self)
        # Put everything in a grid
        _manLayout = QtGui.QVBoxLayout ()
        self._frame = QtGui.QFrame();
        _manLayout.addWidget(self._frame)
        _grid = QtGui.QGridLayout (self._frame)

        # Slider limit labels

        _grid.addWidget (QtGui.QLabel (''), 0, 0)
        _labelLayout = QtGui.QHBoxLayout ()
        _grid.addLayout (_labelLayout, 0, 1)
        self.lower = QtGui.QLabel ('LOW')

        _labelLayout.addWidget (self.lower)
        self.higher = QtGui.QLabel ('HIGH')
        self.higher.setAlignment (QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)

        _labelLayout.addWidget (self.higher)

        # Slider

        _grid.addWidget (QtGui.QLabel (''), 1, 0)
        self.sliderBarLayout = QtGui.QHBoxLayout ()
        self.sliderBarLayout.setSpacing (0)
        _grid.addLayout (self.sliderBarLayout, 1, 1)

        # self.sliderBarLayout.addWidget (self.leftEndstop)

        self.slider = QtGui.QSlider (QtCore.Qt.Horizontal)
        self.slider.setTickPosition (QtGui.QSlider.TicksBelow)
        self.slider.setTracking (True)
        self.slider.setMinimumWidth (40)
        self.slider.setPageStep (1)

        self.sliderBarLayout.addWidget (self.slider)
        self._frame.setLayout(_grid)
        self.addLayout (_manLayout)

        #self.rightEndstop = RightEndstop (self, self.root)

        # self.sliderBarLayout.addWidget (self.rightEndstop)
    def show(self):
        self._frame.show()
    def hide(self):
        self._frame.hide()
    def isHidden(self):
        return self._frame.isHidden()

class NewTimeSliderTest(QtGui.QWidget):
    def __init__(self, parent=None, total=20):
        super(NewTimeSliderTest, self).__init__(parent)
        self.newTimeSlider = TimeSlider()
        self.resize(841, 474)
        self.newTimeSlider.hide()
        self.button = QtGui.QPushButton('Show/Hide')
        self.button.clicked.connect(self.handleButton)
        main_layout = QtGui.QGridLayout()
        main_layout.addWidget(self.button, 0, 0)
        main_layout.addLayout(self.newTimeSlider, 0, 1)
        self.setLayout(main_layout)
        self.setWindowTitle('Test')
        self._active = False

    def handleButton(self):
        #self.newTimeSlider.show()
        isHidden = self.newTimeSlider.isHidden()
        if isHidden:
            self.newTimeSlider.show()
        else:
            self.newTimeSlider.hide()

app = QtGui.QApplication(sys.argv)
bar = NewTimeSliderTest(total=101)
bar.show()
sys.exit(app.exec_())

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

description: Show and hide QtGui.QGridLayout in PySide


code: plt.xticks(locs + bar_width/2, label, rotation=-90)

rawDescription: How to draw bar in python

description: Draw bar in python


code:
import pandas as pd
from StringIO import StringIO

s1="""
domain               ttl           nameserver               file_date
fakedomain.com       86400         ns1.fakedomain.com       8/8/2008
fakedomainz.com      86400         ns1.fakedomainz.com      8/8/2008
"""

s2="""
domain               ttl           nameserver               file_date
fakedomain.com       86400         ns1.fakedomain.com       9/8/2008
fakedomainz.com      86400         ns1.fakedomainz.com      9/8/2008
"""

rawDescription: python merge panda dataframes keep dates

description: Python merge panda dataframes keep dates


code:
codes_i_want = [301,some_code,some_other_code]
result = [h for h in r.history if h.status_code in codes_i_want]

if(result):
    print(result[0])

rawDescription: Python: Find First Redirect of URL

description: Python: Find First Redirect of URL


code:
import copy
import lxml.etree

def pprint(e): print(lxml.etree.tostring(e, pretty_print=True))

xml = '''

        ...

...

'''

root_element = lxml.etree.fromstring(xml)
div_parents = root_element.xpath('//div[div]')

for outer_div in div_parents:
    if len(outer_div.getchildren()) == 1:
        inner_div = outer_div[0]
        # Copy the children of innder_div to outer_div
        for e in inner_div: outer_div.append( copy.deepcopy(e) )
        # Remove inner_div from outer_div
        outer_div.remove(inner_div)

pprint(root_element)

rawDescription: lxml - how to remove element but not it's content?

description: Lxml - how to remove element but not it's content


code:
def find_even_count():
    count = 0
    x = raw_input("Enter a value, or q to quit: ")
    while (x != "q") and (x > 0):
        if (int(x) % 2 == 0):
            count += 1
        x = raw_input("Enter a value, or q to quit: ")
    return count

rawDescription: Find the Number of even intergers in a sequence


rawDescription: averaging elements in a matrix with the corresponding elements in another matrix (in python)

description: Averaging elements in a matrix with the corresponding elements in another matrix (in python)


code:
data = []
for x, y in zip(arrayForInitialSpots, arrayForChosenSpots):
    data.extend(x + y)
with open('data.csv','a') as out:
     csv.writer(out).writerow(data)

rawDescription: Python and CSV: Output everything to one line


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

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


code:
class Attribs(Base):
    listing_id = Column(Integer,ForeignKey("Listing"))
    name = Column(String)
    val = Column(String)

class Listing(Base):
    id = Column(Integer,primary_key = True)
    attributes = relationship("Attribs",backref="listing")
    def __init__(self,**kwargs):
        for k,v in kwargs.items():
            Attribs(listing_id=self.id,name=k,value=v)
    def __str__(self):
        return "\n".join(["A LISTING",] + ["%s:%s"%(a.name,a.val) for a in self.attribs])

rawDescription: Dynamic Datasets and SQLAlchemy

description: Dynamic Datasets and SQLAlchemy


rawDescription: Regex for finding variable references in a C file using Python


code:
from hurry.filesize import size
size(11000)
size(198283722)

rawDescription: Better way to convert file sizes in Python


rawDescription: Create alias of part of a list in python


code:
f.write(struct.pack('B' * len(bytes), *bytes))
# the < is redundant; there is NO ENDIANNESS ISSUE

rawDescription: Python method for storing list of bytes in network (big-endian) byte order to file (little-endian)


code:
import re
str ="""
Tim is so stupid.
stupid Tim!
Tim foobar barfoo.
Where is Tim?"""
m = re.findall(r'^(?=.*Tim)(?=.*stupid).+$', str, re.MULTILINE)
m
m = re.findall(r'^(?=.*Tim).*stupid', str, re.MULTILINE)
m

rawDescription: Regex for existence of some words whose order doesn't matter


rawDescription: xor matrix multiplication for AES mix column stage

description: Xor matrix multiplication for AES mix column stage


code: result = (user_id << 32) + timestamp

rawDescription: How do you "concatenate" two 32 bits int to get a 64 bits long in Python?


code:
store_success_ids =  [ k[0] for k in l_succ if k in l_last ]
#store_success_ids = [1, 5, ... ]          <-store_success_ids result
#Cast l_last to dictionary to do lookups if you have a lot of stores.

result = Store.objects.filter( pk__in = store_success_ids)

rawDescription: Filtering a model in Django based on a condition upon the latest child record


rawDescription: Python table titles into dictionary

description: Python table titles into dictionary


code:
s0.index = s0.index + (s0.groupby(level=0)._cumcount_array() / 1000.)
s1.index = s1.index + (s1.groupby(level=0)._cumcount_array() / 1000.)
res = pd.concat([s0, s1], axis=1)
res.index = res.index.values.astype('int64')

rawDescription: Merge multiple dataframes with non-unique indices


code:
x_indices = [0, 5, 10, 25, 50]
max_size = max(x_indices)
x_percents = [ n/max_size * 100 for n in x_indices]

rawDescription: Adding secondary X-axis with user-defined list of coordinates


code: set(tuple(sorted(r.iteritems())) for r in result)

rawDescription: Count the duplicates in list of dict in django python


code:
country = [u'USA']
country[0] = str(country[0])
country

rawDescription: Python turn list values into String

description: Python turn list values into String


rawDescription: print out binary representation of c type in python

description: Print out binary representation of c type in python


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


code:
input1="""Davide
...:Michele
...:Giorgio
...:Paolo"""

rawDescription: Python - Converting long list of addresses into list of strings and intersection of lists


code:
from django.core import serializers
from django.http import HttpResponse, HttpResponseBadRequest

def ajax_get_languages_for_category(request):
    cat_id = request.GET.get('cat_id')
    if cat_id is not None:
        category = get_object_or_404(ProgrammingCategory, id=cat_id)
        data = serializers.serialize('json', category.languages.all())
        return HttpResponse(data, mimetype='application/json')
    else:
        return HttpResponseBadRequest()

rawDescription: Django options field with categories

description: Django options field with categories


code:
n_array = np.arange(0,c-1)
temp_vec= C[c-n_array] * A[n_array]
A[c] += temp_vec.sum(axis=0)

rawDescription: numpy array multiplication slower than for loop with vector multiplication?

description: Numpy array multiplication slower than for loop with vector multiplication


code:
class MyModel(QtSql.QSqlRelationalTableModel):
    def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
        if orientation == QtCore.Qt.Vertical:
            index = self.index(section, 0) # assuming ID is the first column
            return self.data(index, role)
        else:
            # return original headers for horizontal orientation
            return super(MyModel, self).headerData(section, orientation, role)

rawDescription: Data in the qtableview's vertical header?


code:
def next_quarter_hour(self):
    dt = datetime.datetime.now()
    nsecs = dt.minute*60+dt.second+dt.microsecond*1e-6
    delta = (nsecs//900)*900+900-nsecs
    return delta * 1000.0

rawDescription: Update QWidget every minutes

description: Update QWidget every minutes


code:
ser2.median()
ser2.mean()

rawDescription: Using grouby for counting

description: Using grouby for counting


code:
for i in range(1, 31):
    if i == 6:
        continue

    ...

rawDescription: How can I combine range() functions

description: Combine range() functions


code:
player.name = getName()

while not player.dead:
    input = raw_input(">> ").split()
    input.append("EOI")

    if isValidCMD(input[0]):
        runCMD(input[0], input[1], player)

rawDescription: Python skipping a step

description: Python skipping a step


code:
import numpy as np
x = np.zeros(1, dtype=np.dtype([('field', '<f8', (1, 2))]))
y = x[0]['field'].copy()
y[0] = 3
y[1] = 4
y[0][1] = 4
x
y
x[0]['field'] = y
x

rawDescription: Assigning values to a NumPy array

description: Assigning values to a NumPy array


code:
(u'John', u'Deer', 20, u'M')
(u'Ada', u'Lovelace', 23, u'F')

rawDescription: How to give multiple values to a single key using a dictionary?

description: Give multiple values to a single key using a dictionary


code: for i in range(nIterations): y = f(y)

rawDescription: Iteration in a single line

description: Iteration in a single line


rawDescription: write csv row (from within for loop) out to csv file without using python csv module

description: Write csv row (from within for loop) out to csv file without using python csv module


code:
vbox = QtGui.QVBoxLayout()
overviewBox = QtGui.QGroupBox('Overview')

# Main window
part_num_layout = QtGui.QHBoxLayout()
part_num_layout.addWidget(QtGui.QLabel('Part Number'))
part_num_layout.addWidget(QtGui.QLineEdit(), stretch=1)
vbox.addLayout(part_num_layout)
vbox.addWidget(overviewBox)
...
self.setLayout(vbox)

rawDescription: How can I right-align the second column in a QFormLayout?

description: Right-align the second column in a QFormLayout


rawDescription: how to magnify a peak in matplotlib?

description: Magnify a peak in matplotlib


rawDescription: Retrieving each element of multiple arrays in python


code:
# -*- coding: utf-8 -*-
"""
This file contains custom definition of Django Model Fields
"""

from django.core.exceptions import ValidationError
from django.db.models import PositiveSmallIntegerField

_ = lambda x: x

class RangeValidator(object):
    """
    Validates whether proper value belongs to specified range
    """
    def __init__(self, bottom_limit, top_limit, message, code):
        self.bottom_limit = bottom_limit
        self.top_limit = top_limit
        self.message = message
        self.code = code

    def __call__(self, value):
        if not self.bottom_limit <= value <= self.top_limit:
            raise ValidationError(self.message, code=self.code)

class WeekdayField(PositiveSmallIntegerField):
    """
    Weekday field - simple Integer based field, to store number of the week.
    First day of the week is Monday, which is represented by number 1.
    """

    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5
    SATURDAY = 6
    SUNDAY = 7

    DAY_OF_THE_WEEK = (
        (MONDAY, _('Monday')),
        (TUESDAY, _('Tuesday')),
        (WEDNESDAY, _('Wednesday')),
        (THURSDAY, _('Thursday')),
        (FRIDAY, _('Friday')),
        (SATURDAY, _('Saturday')),
        (SUNDAY, _('Sunday')),
    )

    default_validators = [
        RangeValidator(
            bottom_limit=MONDAY,
            top_limit=SUNDAY,
            message=_(
                'Day number should be between {} and {}'.format(MONDAY, SUNDAY)
            ),
            code=_('wrong day number')
        )
    ]

rawDescription: How write unittests to Django CustomField with restricted range?


code:
import numpy as np
rate = 0.2
f = lambda x: np.random.choice((True, x),1,p=[rate,1-rate])[0]

a = np.array([0,0,1,0,1], dtype='bool')
map(f, a)
# This will output array a with on average 20% of the elements changed to "1"
# it can be slightly more or less than 20%, by chance.

rawDescription: Randomize part of an array

description: Randomize part of an array


rawDescription: How do I stop Django "python manage.py syndb" from adding tables to multiple DB's in Settings?

description: Stop Django "python manage.py syndb" from adding tables to multiple DB's in Settings


code: int('FFABCD', 16)

rawDescription: Treat String as Hex Python

description: Treat String as Hex Python


rawDescription: How to create variables inside a for loop to assign dataframes?

description: Create variables inside a for loop to assign dataframes


rawDescription: Collecting like term of an expression in Sympy


code:
def is_transparent(colour):
    red, green, blue, alpha = colour
    if alpha == 0:
        return True
    return False

rawDescription: Pygame cross platform color inconsistency


code: team_combos(0, 0, 0, 0, 16)   # start with 16 four-person teams

rawDescription: How to find the following desired probability using computational method (e.g. using Python)?

description: Find the following desired probability using computational method (e.g. using Python)


code:
nm.loc['a',sngl.columns] = sngl.loc['a'].values
nm
nm.reset_index().set_index(['level_0','level_1','level_2'])

rawDescription: copying a single-index DataFrame into a MultiIndex DataFrame

description: Copying a single-index DataFrame into a MultiIndex DataFrame


code:
pairs = {}
for first in range(1,7):
    for second in range(1,7):
        total = first + second
        if total in pairs:
            # If sum exists, add this tuple to the list for this key.
            pairs[total] += [(first,second)]
        else:
            # If sum doesn't exist, start a new list for this key
            pairs[total] = [(first,second)]

rawDescription: A Confusing task

description: A Confusing task


code:
soup = BeautifulSoup('''<span class=info>2hr 3min - Rated PG-13&#8''')
soup.span.get_text()

rawDescription: Regular expression for data scraping?

description: Regular expression for data scraping


code:
if "b" in array:
    del array[array.index("b"):]

rawDescription: Delete array values in python

description: Delete array values in python


code:
def func2():
    list1=[]
    list2=[]
    value=10
    if somePredicate():
        (list3,list4)=func3(value)
        return list1, list2, list3, list4
    else:
        return list1, list2

rawDescription: Returning function values based on argument?


rawDescription: Map each element in a Series to a Series and combine the result into a DataFrame


code:
TEMPLATE_CONTEXT_PROCESSORS = (
    ...,
    'django.core.context_processors.request',

)

rawDescription: Django display in html from views.py

description: Django display in html from views.py


rawDescription: Rearranging Matrix Elements with Numpy

description: Rearranging Matrix Elements with Numpy


code:
rel = Course._descriptor.find_relationship('assistants')
assert rel
table = rel.table

rawDescription: SQLAlchemy/Elixir - querying to check entity's membership in a many-to-many relationship list


code:
def main():
    data = [np.random.random((2, 3)) for _ in range(5)]
    plot_polygons(data, alpha=0.5)
    plot_verts(data, marker='^', color='black')
    plt.show()

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


code:
list(normalize_number('222 2 333 3333'))
list(normalize_number('222 2333 3333'))
list(normalize_number('222 2 333 53333'))

rawDescription: Writing with numbers

description: Writing with numbers


code:
for img in to_delete:
    if img['id'] not in in_use:
        gc.images.delete(img['id'])

rawDescription: Openstack - Selectively deleting images based on some criteria?


code:
from tkinter import *
import math

x, y = 135, 135

def gravitation (obj1,obj2):
    a, b, c, d = can.coords (obj1)
    e, f, g, h = can.coords (obj2)
    dist = math.sqrt ((((a+c)/2)-((e+g)/2))**2+(((b+d)/2)-((f+h)/2))**2)
    grav = 6.67384/dist
    ##################
    lbl["text"] = grav
    ##################

def move (ov, lr, tb):
    coo = can.coords(ov)
    coo[0] = coo[0] + lr
    coo[1] = coo[1] + tb
    coo[2] = coo[0]+30
    coo[3] = coo[1]+30
    can.coords(ov, *coo)
    ########################
    gravitation(oval1, oval2)
    ########################

def moveLeft ():
    move(oval1, -10, 0)

def moveRight ():
    move(oval1, 10, 0)

def moveTop ():
    move(oval1, 0, -10)

def moveBottom ():
    move(oval1, 0, 10)

def moveLeft2 ():
    move(oval2, -10, 0)

def moveRight2 ():
    move(oval2, 10, 0)

def moveTop2 ():
    move(oval2, 0, -10)

def moveBottom2 ():
    move(oval2, 0, 10)

wind = Tk()
wind.title ("Move Da Ball")
can = Canvas (wind, width = 300, height = 300, bg = "light blue")
can.pack (side = LEFT,padx = 5, pady = 5)
Button(wind, text = 'Quit', command=wind.destroy).pack(padx = 5, pady = 5)

oval1 = can.create_oval(x,y,x+30,y+30,width=2,fill='orange') #Planet 1 moving etc
Button(wind, text = 'Left', command=moveLeft).pack(padx = 5, pady = 5)
Button(wind, text = 'Right', command=moveRight).pack(padx = 5, pady = 5)
Button(wind, text = 'Top', command=moveTop).pack(padx = 5, pady = 5)
Button(wind, text = 'Bottom', command=moveBottom).pack(padx = 5, pady = 5)

oval2 = can.create_oval(x+50,y+50,x+80,y+80,width=2,fill='orange') #Planet 2 moving etc
Button(wind, text = 'Left', command=moveLeft2).pack(padx = 5, pady = 5)
Button(wind, text = 'Right', command=moveRight2).pack(padx = 5, pady = 5)
Button(wind, text = 'Top', command=moveTop2).pack(padx = 5, pady = 5)
Button(wind, text = 'Bottom', command=moveBottom2).pack(padx = 5, pady = 5)

###############################
lbl = Label(wind, bg = 'white')
lbl.pack(padx=5, pady=5)
gravitation(oval1, oval2)
##############################

wind.mainloop()

rawDescription: Update Tkinter Label

description: Update Tkinter Label


code:
class Zombie:
    def __init__(self):
            self.defense = 10
            self.hp = 100
    def hit(self, hp):
            self.hp-=hp
    def upgrade(self, level):
            self.defense+=level

rawDescription: Passing on the parameters of a function into another one?


code:
friends = User.get_by_key_name(friend_ids)
thing_keys = []

for friend in friends:
  thing_keys.extend(friend.things)

things = db.get(thing_keys)

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


rawDescription: How can I get pivot_table to apply a function over combinations of values?

description: Get pivot_table to apply a function over combinations of values


code:
import itertools as IT
import operator
idx = np.where(df.values == rowmax[:,None])
groups = IT.groupby(zip(*idx), key=operator.itemgetter(0))
[[df.columns[j] for i, j in grp] for k, grp in groups]

rawDescription: Find all indices of maximum in Pandas DataFrame


code:
import sys
getattr(sys.stdout, 'buffer', sys.stdout)

rawDescription: Writing bytes to standard output in a way compatible with both, python2 and python3


code:
from itertools import combinations

#this is the list of digits to consider
my_numbers = range(1,10)

def make_groups(n):
    #initialize a couple lists for groups that we want, my_groups,
    # and a list to keep track of pairs that we've already included
    my_groups = []
    pairs_seen = []
    #get all combinations of size n of our digits
    size_n_combins = combinations(my_numbers,n)
    #for each combination to see if it meets our condition that each pair contained
    # should not be in any of our other groups, if it does keep track of the pairs it
    # contains and keep track of the combination by adding it to my_groups
    for combin in size_n_combins:
        if all([pair not in pairs_seen for pair in combinations(combin,2)]):
            pairs_seen += [pair for pair in combinations(combin,2)]
            my_groups.append(combin)
        else:
            continue
    #finally return the groups we wanted
    return my_groups

rawDescription: Python partitions excluding numbers already been together


code:
from refunc import *

pattern = Compile(
    'a',
    Capture(
        Choices('b', 'c'),
        N_of( 'd', 1, Infin() ),
        N_of( 'e', 0, Infin() ),
    ),
    Look_ahead('foo'),
)

rawDescription: is there need for a more declarative way of expressing regular expressions ? :)

description: Is there need for a more declarative way of expressing regular expressions ? :)


code:
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.base import runTouchApp

Builder.load_string('''
<SpinnerOption>:
    size_hint: None, None
    size: 20, 20

<MyWidget>:
    Spinner:
        id:some_id
        text:"some text"
        values:("1","2","3")
        size_hint:(None,None)
        size: root.width/4,root.height/12
''')

class MyWidget(BoxLayout):pass

runTouchApp(MyWidget())

rawDescription: how to set the buttons size inside a spinner in kivy?

description: Set the buttons size inside a spinner in kivy


code:
class Person(db.Model):
  __tablename__ = 'people'
  id       = db.Column(db.Integer, primary_key = True)
  forename = db.Column(db.String(64))
  surname  = db.Column(db.String(64))

  memberships = db.relationship('Membership', backref='person')

  @property
  def name(self):
    return self.forename + ' ' + self.surname

  def __repr__(self):
    return '<Person %r %r>' % (self.forename, self.surname)

class User(db.Model):
  __tablename__ = 'users'
  id       = db.Column(db.Integer, db.ForeignKey('people.id'), primary_key = True)
  email    = db.Column(db.String(120), index = True, unique = True)
  role     = db.Column(db.SmallInteger, default = ROLE_USER)

  salt     = db.Column(db.BINARY(8))
  password = db.Column(db.BINARY(20))

  person   = db.relationship('Person')

rawDescription: How do I create a child class from a parent class in SQLAlchemy's Joined Table Inheritance?

description: Create a child class from a parent class in SQLAlchemy's Joined Table Inheritance


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code:
context['js_paths'] = webapp.settings.template['js_paths']
context['js_paths'].append( '/static/path/to/js/file.js' )

rawDescription: Python list append adding element twice

description: Python list append adding element twice


code:
with file_or_stdout(file_name) as wfile:
    do_stuff_writing_to(wfile)

rawDescription: Fallback to stdout if no file name provided


code:
import wave
import audioop

with wave.open('intput.wav') as fd:
    params = fd.getparams()
    frames = fd.readframes(1000000) # 1 million frames max

print(params)

frames = audioop.reverse(frames, params.sampwidth)

with wave.open('output.wav', 'wb') as fd:
    fd.setparams(params)
    fd.writeframes(frames)

rawDescription: How to convert a wav file -> bytes-like object?

description: Convert a wav file -> bytes-like object


code:
F = treecomp(T, L)
F(x0, x1, x2, x3, x4, x5)

rawDescription: Composition of a hierarchy of functions

description: Composition of a hierarchy of functions


code:
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import Paragraph

class MultiFontParagraph(Paragraph):
    # Created by B8Vrede for http://stackoverflow.com/questions/35172207/
    def __init__(self, text, style, fonts_locations):

        font_list = []
        for font_name, font_location in fonts_locations:
            # Load the font
            font = TTFont(font_name, font_location)

            # Get the char width of all known symbols
            font_widths = font.face.charWidths

            # Register the font to able it use
            pdfmetrics.registerFont(font)

            # Store the font and info in a list for lookup
            font_list.append((font_name, font_widths))

        # Set up the string to hold the new text
        new_text = u''

        # Loop through the string
        for char in text:

            # Loop through the fonts
            for font_name, font_widths in font_list:

                # Check whether this font know the width of the character
                # If so it has a Glyph for it so use it
                if ord(char) in font_widths:

                    # Set the working font for the current character
                    new_text += u'{}'.format(font_name, char)
                    break

        Paragraph.__init__(self, new_text, style)

rawDescription: ReportLab: working with Chinese/Unicode characters


code:
import operator

params = [("a1", "b1"), ("a2", "b2"), (...), ("an", "bn")]
q = [Q(param1=a, param2=b) for a, b in params]
q = reduce(operator.or_, q)
result = MyModel.objects(q)

rawDescription: Django filter where multiple params match one of multiple sets


code: [[i,j] for i,j in zip(*2*[iter(x)])]

rawDescription: Getting two-tuples out of a list

description: Getting two-tuples out of a list


rawDescription: Summing values in nested list when item changes


code: parts = filter(lambda x: bool(x), parts)

rawDescription: Delete unusable characters or data in archive with python


code:
if index == len(l) or l[index] != e:
    return -1
return index

rawDescription: Python bisect: pass value instead of returning insertion index


code:
df
pprint.pprint(recur_dictify(df))

rawDescription: Convert pandas DataFrame to a nested dict


code:
stock = [("fileName1","url1"), ("fileName2","url2")]
stock_dict = dict(stock)
dirs = ["fileName1", "fileName2", "fileName3"]
urls = [stock_dict.get(file, "Not found") for file in dirs]
urls

rawDescription: Iterate two lists in python

description: Iterate two lists in python


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


code:
myfile.seek(0)
for entry in mylist:
    myfile.write(entry)
myfile.truncate()
myfile.close()

rawDescription: reading a file that follows pattern into array

description: Reading a file that follows pattern into array


code:
from bs4 import BeautifulSoup

data = """

 content1

 content2

 content3

     link1
     link2
     link3

"""

soup = BeautifulSoup(data)
soup.find_all(class_=["div1", "a1"])
soup.find_all(["a", "div"], class_=["div1", "a1"])

rawDescription: I want to search div and <a> with specified class using beautifulsoup


code:
exclude = set(b)  # O(m)

new_list = [x for x in a if x not in exclude]  # O(n)

rawDescription: Finding difference between two very large lists


code:
from datetime import datetime, timedelta
import leapseconds
Tgps = 1092121243.0
gps_time = datetime(1980, 1, 6) + timedelta(seconds=Tgps)
leapseconds.dTAI_UTC_from_tai(leapseconds.gps_to_tai(gps_time))

rawDescription: How to get leap seconds from gps epoch for current date in python

description: Get leap seconds from gps epoch for current date in python


code:
def function(x, y):
     pass # ...
r.sub(functools.partial(function, y=arg),string)

rawDescription: Python lambda with regex

description: Python lambda with regex


code: u = s.decode('utf-8')

rawDescription: Python: Replace character by its Unicode-representation


code:
from decimal import *
getcontext().prec = 150
Decimal("10.25")**100

rawDescription: Handling very large numbers

description: Handling very large numbers


code:
class Session(db.Model):
    token = Column('token') # auto generated thingy
    # foreign key to user for example
    # expiration time/date

rawDescription: Flask: How to store credentials in session and retrieve them?


code:
import sys
import os
import dev_appserver
sys.path[1:1] = dev_appserver._DEVAPPSERVER2_PATHS

from google.appengine.tools.devappserver2 import devappserver2
from google.appengine.tools.devappserver2 import python_runtime
# ...
def setUp(self):
    APP_CONFIGS = ['/path/to/app.yaml']
    python_runtime._RUNTIME_ARGS = [
        sys.executable,
        os.path.join(os.path.dirname(dev_appserver.__file__),
                     '_python_runtime.py')
    ]
    options = devappserver2.PARSER.parse_args([
        '--admin_port', '0',
        '--port', '8123',
        '--datastore_path', ':memory:',
        '--logs_path', ':memory:',
        '--skip_sdk_update_check',
        '--',
    ] + APP_CONFIGS)
    server = devappserver2.DevelopmentServer()
    server.start(options)
    self.server = server

def tearDown(self):
    self.server.stop()

rawDescription: How to unit test Google Cloud Endpoints

description: Unit test Google Cloud Endpoints


code: Image = np.asarray(Image)

rawDescription: Sticking two pictures together in python


code:
def get_siblings(l):
    return ((a, b) for a in l
                   for b in l
                   if a < b
                   and a.getparent() == b.getparent())

rawDescription: Determine if two html elements are siblings


code:
from test import Writer
d = { 'a' : u'Zażółć gęślą jaźń', 'b' : u'Och ja Ci zażółcę' }
w = Writer()
w.createXML(d)

rawDescription: Decoding utf-8 in Django while using unicode_literals in Python 2.7


code:
newLevel = Level (self.levelListModel.rowCount() + 1)
newIndex = self.levelListModel.addLevel(newLevel)
self.ui.levelComboBox.setCurrentIndex(newIndex)

rawDescription: PyQt: How to change currentIndex in QComboBox when custom QAbstractListModel data changed


code:
root.after(1000, blink, rect, canv)
root.after(2000, blink, rect, canv)
root.after(3000, blink, rect, canv)

rawDescription: Tkinter, executing functions over time

description: Tkinter, executing functions over time


code:
weather_df = pd.concat([weather_df, weather_df.Events.str.get_dummies(sep='-')], axis=1)
print(weather_df)

rawDescription: Pandas split column into multiple

description: Pandas split column into multiple


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

x1 = x2 = np.arange(5)
y1 = np.array([1,4,25,2,4])
y2 = np.array([4,2,3,32,6])

mask1 = ma.where(y1>=y2)
mask2 = ma.where(y2>=y1)

p1 = plt.bar(x1[mask1], y1[mask1], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)
p2 = plt.bar(x2, y2, color='b', alpha=1, edgecolor='none', linewidth=0,width=0.5, log=False)
p3 = plt.bar(x1[mask2], y1[mask2], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)

rawDescription: How do I keep the smaller value in a bar chart in front (when I cannot place the bars side by side)?

description: Keep the smaller value in a bar chart in front (when I cannot place the bars side by side)


rawDescription: python gather together ascii and utf-8 stuff

description: Python gather together ascii and utf-8 stuff


code:
if desktop_active():
    root.lift()

rawDescription: Python: simple 'if' statement to tell you if the user has no windows maximized


code:
#!/usr/bin/env python
from multiprocessing import freeze_support, Pool
import a

if __name__ == "__main__":
   freeze_support()
   pool = Pool() # use all available CPUs
   result = pool.map(a.search, ['query 1', 'query 2'])

rawDescription: Call python script with input with in a python script using subprocess


rawDescription: Write a Python function that returns the sublist of strings that contain fewer than 4 characters


rawDescription: AVC unable to find view by id even if parameter 'forceviewserveruse': is True,


code:
import unittest

# From the point of view of testing code, our working modules
# are siblings. Imports work accordingly, as seen in module_a.
from app.package_a.module_a import aaa
from app.package_a.module_a import bbb

class TestApp(unittest.TestCase):

    def test_aaa(self):
        self.assertEqual(aaa(77, 88), '77 89')

    def test_bbb(self):
        self.assertEqual(bbb(99), 100)

# Simiarly, we can run our test modules directly as scripts using the -m option,
# or using nose.
#
#    python -m app.test.test_app
#    nosetests app/test/test_app.py

if __name__ == '__main__':
    unittest.main()

rawDescription: Optimal file structure organization of Python module unittests?


code:
s = pd.Series([3, -8, 4, 5, -3, 501, 7, -100, 98, 3])
pd.expanding_apply(s, lambda x: cumsum_limit(x))

rawDescription: Reset cumsum if over limit (python)

description: Reset cumsum if over limit (python)


code:
for line in f:
    nums = map(int, line.split())
    # looks at one line at a time, you can sort it now

rawDescription: How do I use a specific line of a text file in python?

description: Use a specific line of a text file in python


code:
registerType ( int , TheLibrary.Randomizable )
registerType ( str , MyLibrary.MyStringRandomizable )

rawDescription: Is there a way to get ad-hoc polymorphism in Python?


code:
from nltk import pos_tag
sent1 = 'get me now'.split()
sent2 = 'run fast'.split()
pos_tag(['He'] + sent1)
pos_tag(['He'] + sent1)[1:]

rawDescription: NLTK identifies verb as Noun in Imperatives


code:
# create set of sample image and plot them
image = PIL.Image.open("14767594_in.png")
image_data = np.asarray(image)
image_data_blue = image_data[:,:,2]
median_blue = np.median(image_data_blue)
sample_images = create_sample_set(image_data_blue>median_blue)
plt.figure(1)
for i in range(36):
    plt.subplot(6,6,i+1)
    plt.imshow(sample_images[i,...])
    plt.axis("off")
plt.subplots_adjust(0,0,1,1,0,0)

rawDescription: How to detect object on images?

description: Detect object on images


code:
while True:
    try:
        time.sleep(3600) # wait for one hour
        user_input()
    except KeyboardInterrupt: # stop and get input now
        try:
            user_input()
        except KeyboardInterrupt: # graciously leave loop if another interrupt
            break

rawDescription: User Defined Interrupt

description: User Defined Interrupt


rawDescription: Python, all possible combinations of numbers betweens 2 lists


code:
it = iter(range(0, 10))

for i in it:
    if i == 5:
        for j in range(0, 3):
            i = next(it)
    print(i)

rawDescription: How to jump some steps when use python's for statement

description: Jump some steps when use python's for statement


rawDescription: In Jupyter, how can I use the matplotlib ggplot style by default?


rawDescription: Python Variables Referecing - unexpected behavior with zip


code:
class DryBase(object):
    __metaclass__ = DryMeta

    def to_row(self):
        cls = type(self)
        return [desc.__get__(self, cls) for desc in cls._header_descriptors]

rawDescription: OO design: an object that can be exported to a "row", while accessing header names, without repeating myself


code: scores = {el: score(el) for el in l}

rawDescription: Sort a list by a key and get the value out without recomputing


code:
import networkx as nx

def hierarchy_pos(G, root, width=1., vert_gap = 0.2, vert_loc = 0, xcenter = 0.5,
                  pos = None, parent = None):
    '''If there is a cycle that is reachable from root, then this will see infinite recursion.
       G: the graph
       root: the root node of current branch
       width: horizontal space allocated for this branch - avoids overlap with other branches
       vert_gap: gap between levels of hierarchy
       vert_loc: vertical location of root
       xcenter: horizontal location of root
       pos: a dict saying where all nodes go if they have been assigned
       parent: parent of this branch.'''
    if pos == None:
        pos = {root:(xcenter,vert_loc)}
    else:
        pos[root] = (xcenter, vert_loc)
    neighbors = G.neighbors(root)
    if parent != None:
        neighbors.remove(parent)
    if len(neighbors)!=0:
        dx = width/len(neighbors)
        nextx = xcenter - width/2 - dx/2
        for neighbor in neighbors:
            nextx += dx
            pos = hierarchy_pos(G,neighbor, width = dx, vert_gap = vert_gap,
                                vert_loc = vert_loc-vert_gap, xcenter=nextx, pos=pos,
                                parent = root)
    return pos

rawDescription: Can one get hierarchical graphs from networkx with python 3?


code:
for groupname, grouptuples in groups:
    values = [t[1] for t in groupvalues]
    print("{name} {avg}".format(name=groupname, avg=sum(values)/len(values)))

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

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


code:
class Silly(object):
    def __init__(self, v):
        self.v = v

def fib(i):
    if i > 1:
        return Silly(_fibCache(i-1).v + _fibCache(i-2).v)
    elif i: return Silly(1)
    else: return Silly(0)
_fibCache = createLRUCache(fib)

rawDescription: Problems with the GC when using a WeakValueDictionary for caches


code:
from itertools import filterfalse, tee

def partition(pred, iterable):
    'Use a predicate to partition entries into false entries and true entries'
    # partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9
    t1, t2 = tee(iterable)
    return filterfalse(pred, t1), filter(pred, t2)

rawDescription: python equivalent of filter() getting two output lists (i.e. partition of a list)

description: Python equivalent of filter() getting two output lists (i.e. partition of a list)


code: byref(buffer)

rawDescription: How can I convert a BitString to a ctypes Byte Array?

description: Convert a BitString to a ctypes Byte Array


code:
from sqlalchemy import create_engine

engine = create_engine('mysql://test:test@localhost/test', echo=True)
from sqlalchemy.orm import sessionmaker

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Date, Column, Integer

Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    id = Column(Integer, primary_key=True, autoincrement=True)
    day = Column(Date, unique=True)

if __name__ == '__main__':

    Base.metadata.create_all(engine)
    c = engine.connect()
    c.execute("""INSERT INTO users(day) VALUES ('2012-03-05') ON DUPLICATE KEY UPDATE day='2012-03-04'""")

rawDescription: SqlAlchemy OperationalError using Case

description: SqlAlchemy OperationalError using Case


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

data = np.random.normal(0, 1, 1000)

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.hist(data)
ax2.hist(data, cumulative=True)
plt.show()

rawDescription: How to plot an ogive?

description: Plot an ogive


rawDescription: Get count of all unique rows in pandas dataframe


rawDescription: Running external program through python terminal


rawDescription: Variables and Assign range to it in Python


rawDescription: Can I use a variable string to refer to a list?

description: Use a variable string to refer to a list


code:
import locale
locale.setlocale(locale.LC_ALL, '')
locale.format('%d', 1000000, 1)

rawDescription: Add thousands separators to a number

description: Add thousands separators to a number


code: ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in range(N))

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