code:
from my_project_pkg import app
app.run(debug=True)

rawDescription: Flask Bug on Python 3.4? Development server can't run if app contains relative imports


code:
with open("fiancee_wordfreq.csv" , "wb") as f:
     writer = csv.writer(f)
     for val in cn:
         writer.writerow([val, cn[val]])

rawDescription: How do I write words and their frequencies into two separate columns in CSV file

description: Write words and their frequencies into two separate columns in CSV file


code:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt

def ode_rhs(y, t, p, full):
    ydot[0] = -p[0]*y[0]*y[1] + p[1]*y[2] + p[2]*y[2]
    ydot[1] = full * (-p[0]*y[0]*y[1] + p[1]*y[2])
    ydot[2] = p[0]*y[0]*y[1] - p[1]*y[2] - p[2]*y[2]
    return ydot

ydot = np.zeros(3)
p = np.array([0.01, 0.25, 0.1])
y0 = [20.0, 100.0, 0.0]
t1 = 20.0  # Equilibration time
tf = 200.0  # Final time

# Solve the equilibration phase.
teq = np.linspace(0, t1, 100)
full = 0
soleq = odeint(ode_rhs, y0, teq, args=(p, full))

# Solve the full system, using the final point of the
# equilibration phase as the initial condition.
y0 = soleq[-1]
# Note: the system is autonomous, so we could just as well start
# at t0=0.  But starting at t1 makes the plots (below) align without
# any additional shifting of the time arrays.
t = np.linspace(t1, tf, 2000)
full = 1
sol = odeint(ode_rhs, y0, t, args=(p, full))

plt.figure(2)
plt.clf()
plt.subplot(3, 1, 1)
plt.plot(teq, soleq[:, 0], t, sol[:, 0])
plt.axvline(t1, color='r')
plt.grid(True)
plt.ylabel('y[0]')

plt.subplot(3, 1, 2)
plt.plot(teq, soleq[:, 1], t, sol[:, 1])
plt.axvline(t1, color='r')
plt.grid(True)
plt.ylabel('y[1]')
plt.ylim(0, 110)

plt.subplot(3, 1, 3)
plt.plot(teq, soleq[:, 2], t, sol[:, 2])
plt.axvline(t1, color='r')
plt.grid(True)
plt.ylabel('y[2]')
plt.xlabel('t')

plt.show()

rawDescription: Update initial condition in ODE solver each time step


code: reduce(lambda x,y: x+[y] if x==[] or x[-1] != y else x, your_list,[])

rawDescription: Make Python List Unique in Functional way (map/reduce/filter)


rawDescription: using numpy reshape for column major in multi-dimensional array in python

description: Using numpy reshape for column major in multi-dimensional array in python


rawDescription: How to collect the value corresponding to a field of an array/list of named tuples

description: Collect the value corresponding to a field of an array/list of named tuples


code:
len(x) == img.ndim
all(a.shape == img.shape for a in x)

rawDescription: Indexing numpy arrays with numpy arrays, in arbitrary dimension


rawDescription: Removing certain files specified in a list


code: Namespace(bar='2', foo='1', remaining='--foo 4 --bar 14')

rawDescription: Python argparse treat arguments in different ways


code:
def read(ser, queue):
    buf = b''
    ser.timeout = 1  # 1 second. Modify according to latency requirements
    while not should_stop.is_set():
         buf += ser.readline()
         if buf.endswith('\n'):
             queue.put(line)
             buf = b''
         # else: Interrupted by timeout

should_stop = threading.Event()
threading.Thread(target=read, args=(ser, queue)).start()
# ... somewhat later
should_stop.set()  # Reading thread will exit within the next second

rawDescription: Confusing 'readline' warning in the documentation


code:
rect = pygame.Rect(25, 25, 100, 50)
screenshot = pygame.Surface(100, 50)
screenshot.blit(screen, area=rect)
pygame.image.save(screenshot, "screenshot.jpg")

rawDescription: How to take screenshot of certain part of screen in Pygame

description: Take screenshot of certain part of screen in Pygame


code: C = [obj.Bar for obj in (A, B)]

rawDescription: Python: Get attribute from a list of objects of the same type in the most efficient way


rawDescription: How can I get all the property names of a GTK Container?

description: Get all the property names of a GTK Container


code: im1 = ndimage.grey_erosion(im, size=(15,15))

rawDescription: Image erosion and dilation with Scipy

description: Image erosion and dilation with Scipy


code:
from operator import itemgetter
div_idx = myData._fields.index('div')
data_divs = map(itemgetter(div_idx), data) # or [r[div_idx] for r in data]

rawDescription: Import Data Into Namedtuple in Python

description: Import Data Into Namedtuple in Python


code:
class Vector(object):
    ''' Performs vector aritmetic
    '''
    def __init__(self, x, y):
        self.x, self. y = x, y

    def add(self, v):
        return Vector(self.x + v.x, self.y + v.y)

    def mult(self, s):
        return Vector(s * self.x, s * self.y)

rawDescription: lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place

description: Lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place


code:
from copy import copy
list = copy(anotherArray)

rawDescription: Python List Indexing or Appending?

description: Python List Indexing or Appending


code:
print(foo.x)
# bar
print(foo.path)
# /tmp
print(foo.debug)
# True
print(foo.args)
# (100, 101)
print(foo.verbose)
# True

rawDescription: Automatically setting class member variables in Python


code:
N = 10
np.argsort(np.random.rand(8,N),axis=0)+1

rawDescription: Random numbers within Array in Python

description: Random numbers within Array in Python


code:
#!/usr/bin/env python
from timeit import default_timer as timer
from twisted.internet import reactor, utils
from twisted.web import xmlrpc, server

class Example(xmlrpc.XMLRPC):
    def xmlrpc_echo(self, x):
        """Sanity check."""
        return x
    def xmlrpc_getoutput(self):
        shell_command = "echo before sleep; sleep 10; echo after sleep"
        start = timer()
        d = utils.getProcessOutput("/bin/sh", ["-c", shell_command])
        print("Deferred created in %.2f seconds" % (timer() - start,)) # instant
        return d

reactor.listenTCP(9657, server.Site(Example()))
reactor.run()

rawDescription: Client/server on python-twisted

description: Client/server on python-twisted


rawDescription: Find and replace a string in Python

description: Find and replace a string in Python


code:
from __init__ import logger

logger.info('message test')

rawDescription: Python logging creates multiple logs

description: Python logging creates multiple logs


code:
def with_metaclass(mcls):
    def decorator(cls):
        body = vars(cls).copy()
        # clean out class body
        body.pop('__dict__', None)
        body.pop('__weakref__', None)
        return mcls(cls.__name__, cls.__bases__, body)
    return decorator

rawDescription: Portable meta class between python2 and python3


code: ignore = ['foo', 'bar', 'buzz']

rawDescription: using 2 sets one ingnore and 1 alert to parse a large set in python

description: Using 2 sets one ingnore and 1 alert to parse a large set in python


code:
from sortedcontainers import SortedDict

l = [[1, 2, 3], [1, 3, 4], [1, 4, 5], [2, 4, 3], [2, 5, 6], [2, 1, 3]]
d = SortedDict()
for sub in l:
    k = sub[0]
    if k not in d or sub[1] < d[k][1]:
        d[k] = sub

print(list(d.values()))

rawDescription: Removing duplicates from a list of lists based on a comparison of an element of the inner lists


code:
# List of numbers: [1, -3, 10, ...]
numbers = [int(n) for n in A.split()]

rawDescription: length of list in python?

description: Length of list in python


code:
s = ctypes.create_string_buffer(100)   #must be large enough!!
msvcrt.sprintf(s, b'%s', b'Hello World!')
val = s.value

rawDescription: Python3k ctypes printf

description: Python3k ctypes printf


rawDescription: Python - Remove "tagged" item from list only if another item with greater "tag" exists


rawDescription: Extracting part of string in parenthesis using python


code:
def correct_hot_bis(hot_image, seg_image):
    # Need this to not index out of bounds when computing border_avg
    hot_image_padded = np.pad(hot_image, 3, mode='constant',
                              constant_values=0)
    new_hot = hot_image.copy()
    sign = np.ones_like(hot_image, dtype=np.int8)
    sign[hot_image > 0] = -1
    s_elem = np.ones((3, 3))

    for j, slice_ in enumerate(ndimage.find_objects(seg_image)):
        hot_image_view = hot_image[slice_]
        seg_image_view = seg_image[slice_]
        new_shape = tuple(dim+6 for dim in hot_image_view.shape)
        new_slice = tuple(slice(dim.start,
                                dim.stop+6,
                                None) for dim in slice_)
        indices = seg_image_view == j+1

        obj_avg = hot_image_view[indices].mean()

        obj = np.zeros(new_shape)
        obj[3:-3, 3:-3][indices] = True

        dilated = ndimage.binary_dilation(obj, s_elem)
        border = mahotas.borders(dilated)
        border &= dilated

        border_avg = hot_image_padded[new_slice][border == 1].mean()

        new_hot[slice_][indices] += (sign[slice_][indices] *
                                     np.abs(obj_avg - border_avg))

    return new_hot

rawDescription: Speed up numpy.where for extracting integer segments?


code:
d = collections.OrderedDict()
lastch, runlength = None, None
for ch in x:
    if ch == lastch:
        runlength += 1
    else:
        try:
            del d[lastch]
        except KeyError:
            pass
        if runlength:
            d[lastch] = runlength
        lastch, runlength = ch, 1
try:
    del d[lastch]
except KeyError:
    pass
if runlength:
    d[lastch] = runlength
x = ''.join(d)

rawDescription: How to remove duplicate characters in a string and print according to the longest occurrence

description: Remove duplicate characters in a string and print according to the longest occurrence


code:
right_ax.axvline(0, color='k', zorder=-1)

patches = [Rectangle(xy=(-1, y0), width=2, height=(y1-y0)) for y0, y1 in boxes]
p = PatchCollection(patches, cmap='jet')
p.set_array(np.array(colors))
right_ax.add_collection(p)

[right_ax.text(1.2, (y0+y1)/2., text, va='center')
    for (y0, y1), text in zip(boxes, box_text)]
right_ax.set_xlim(-2,2)

rawDescription: How to plot heat map with matplotlib?

description: Plot heat map with matplotlib


code: re.findall(r"\{([^}]*)\}", mystring);

rawDescription: Python - Match substring occurrences between { } with regex


code:
import subprocess
proc = subprocess.Popen("/usr/bin/tac", stdin=subprocess.PIPE)  # Output will go to stdout
proc.communicate("hello\nworld\n")  # This data goes to the subprocess.

rawDescription: Reading netCDF and creating "virtual / pseudo" csv files


code:
from subprocess import Popen,PIPE,STDOUT
with open("/proc/meminfo") as f:
    p1 = Popen(["egrep", 'MemTotal|MemFree|Cached|SwapTotal|SwapFree|AnonPages|Dirty|Writeback|PageTables|HugePages_' ], stdin=f, stdout=PIPE)
    p2 = Popen(["awk","{ print $2}"],stdin=p1.stdout,stdout=PIPE)
    p1.stdout.close()
    p3 = Popen(["pr", "-t", "-T", "--columns=15", "--width=240"],stdin=p2.stdout,stdout=PIPE)
    p2.stdout.close()

output = p3.communicate()
print(output[0])

rawDescription: converting bash/shell line into python 2.6

description: Converting bash/shell line into python 2.6


code:
print("".join(["Row{:<3}".format(i) for i in range(1, len(numbers)+1)]))
for w1 in zip(*numbers):
    print("".join(["{:<6}".format(i) for i in w1]))

rawDescription: how to print lists within a tuple in straight line

description: Print lists within a tuple in straight line


code:
def first_true3():
    di={}
    for i, j in zip(*np.where(a>0)):
        if i in di:
            continue
        else:
            di[i]=j

    return di

rawDescription: Finding first non-zero value along axis of a sorted two dimensional numpy array


code:
@recursion_detector
def foo(bar):
    return foo(not bar)

foo(True)
foo(False)

rawDescription: Detecting infinite recursion

description: Detecting infinite recursion


code:
import os

directory_to_check = "your_dir" # Which directory do you want to start with?

def my_function(directory):
      print("Listing: " + directory)
      print("\t-" + "\n\t-".join(os.listdir("."))) # List current working directory

# Get all the subdirectories of directory_to_check recursively and store them in a list:
directories = [os.path.abspath(x[0]) for x in os.walk(directory_to_check)]
directories.remove(os.path.abspath(directory_to_check)) # If you don't want your main directory included

for i in directories:
      os.chdir(i)         # Change working Directory
      my_function(i)      # Run your function

rawDescription: Python: run script in all subdirectories


code:
from matplotlib.pyplot import subplots, draw
from matplotlib.finance import candlestick

seconds_per_day = 60 * 60 * 24
fig, ax = subplots()
candlestick(ax, df[['d', 'open', 'close', 'high', 'low']].values, width=1.0 / seconds_per_day)
ax.xaxis_date()
draw()

rawDescription: How to read and plot time series data files as candlestick chart?

description: Read and plot time series data files as candlestick chart


code:
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--course')
parser.add_argument('-t', '--title')
parser.add_argument('-n', '--name',)
parser.add_argument('-s', '--school', default='My U')

rawDescription: Generating pdf-latex with python script

description: Generating pdf-latex with python script


code:
from bs4 import BeautifulSoup
import  requests
r = requests.get("http://stackoverflow.com/questions/27934387/how-to-retrieve-information-inside-a-tag-with-python/27934403#27934387")
BeautifulSoup(r.content).title.text

rawDescription: How to get inner text value of an HTML tag with BeautifulSoup bs4?

description: Get inner text value of an HTML tag with BeautifulSoup bs4


code: re.match('\r', s)

rawDescription: How python and the regex module handle backslashes


code:
md = md.drop(0, axis=1)
data_final = pd.concat([md, dval], axis=1)

rawDescription: Transposing one column in python pandas with the simplest index possible


rawDescription: iterating over nester tuples to generate specific string

description: Iterating over nester tuples to generate specific string


code:
K = np.arange(1000000).reshape(1000, 1000)
imp_list = range(100)  # [0, 1, 2, ..., 99]
bath_list = range(200) # [0, 1, 2, ..., 199]

def method1():
    s = 0
    for i in imp_list:
        for j in bath_list:
            s += K[i,j]
    return s

def method2():
    return K[np.ix_(imp_list, bath_list)].sum()

def method3():
    return K[:100, :200].sum()

rawDescription: Partial sum over an array given a list of indices


code: cols = each[0], each[1], each[2] + each[3]

rawDescription: splitting lists and values

description: Splitting lists and values


code: R

rawDescription: python: Faster local maximum in 2-d matrix

description: Python: Faster local maximum in 2-d matrix


code: A = np.vstack((array1, array2, array3))

rawDescription: Detect the first unique rows in multiple numpy 2-d arrays


code: html_style = 'css/mystyle.css'

rawDescription: csv-table formatting in Python docstrings (Sphinx) - multiple lines in one cell

description: Csv-table formatting in Python docstrings (Sphinx) - multiple lines in one cell


rawDescription: Display data from models in website

description: Display data from models in website


code:
import datetime
import re
import os

os.chdir(path)
for filename in os.listdir(path):
    match = re.match(r'(IN|OUT)_ \+ (\d+).amr', filename)
    if match:
        file_date = datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
        destination = '%s_%s_%s_Phone number.amr' % (
            match.group(1), # either IN or OUT
            match.group(2),
            file_date.strftime('%Y%m%d%H%M%S'), # adjust the format at your convenience
        )

        os.rename(filename, destination)

rawDescription: Renaming of files for a given pattern

description: Renaming of files for a given pattern


code:
lvl1a = Lvl1a()
lvl1b = Lvl1b()
enemies = [lvl1a,lvl1b]

rawDescription: Python Pygame Enemy Collision

description: Python Pygame Enemy Collision


code:
from io import StringIO

pd.read_csv(StringIO(r.text))

rawDescription: python requests.text to pandas dataframe

description: Python requests.text to pandas dataframe


code:
#!/usr/bin/env python
import time

timestamp = time.strftime('%S')

def test_me():
    print('test_me ' + timestamp)
    assert 0

if __name__ == '__main__':
    import nose # $ pip install nose
    print('main ' + timestamp)
    time.sleep(3)
    nose.main()

rawDescription: Python - String with timestamp changing

description: Python - String with timestamp changing


code: url = url.replace("www.", "", 1) if url.startswith("www.") else url

rawDescription: Getting urls with csv reader and putting them into a list


code:
class Reference(object):
    def __init__(self):
        self.references = {}

    def __setattr__(self, key, value):
        if hasattr(self, 'references'):
            if isinstance(value, Reference):
                if not key in value.references:
                    value.references[key] = []
                value.references[key].append(self)

            elif value is None and hasattr(self, key):
                old = getattr(self, key).references
                if key in old and self in old[key]:
                    old[key].remove(self)

        super(Reference, self).__setattr__(key, value)

rawDescription: Python - how to get class instance reference from an attribute class?


code:
module_dict = {}
for n in dir(module):
 module_dict[n] = eval('module.'+n)

rawDescription: Execute operations given by the user with(out) eval()


code:
SomeProject ==5.4 ; python_version < '2.7'
SomeProject; sys.platform == 'win32'

rawDescription: requirements.txt depending on python version

description: Requirements.txt depending on python version


code: dists.shape # (3, 3, 2)

rawDescription: Joining two 2D numpy arrays into a single 2D array of 2-tuples


code: [c[i] for i in xrange( min(c) , max(c)+1)]

rawDescription: Get frequency count of elements in an array


code: ['Tomato', 'Populus', 'trichocarpa']

rawDescription: strip sides of a string in python

description: Strip sides of a string in python


rawDescription: How to slice and extend a 2D numpy array?

description: Slice and extend a 2D numpy array


code: [[k, v.values()] for k, v in dict_1.iteritems()]

rawDescription: Sorting by the values of a sub-dictionary and then by primary keys


code:
class SomeUSBProtocol(object):
    def __init__(self):
        self.observers = []

    def usbStreamLineReceived(self, line):
        data = MyBrandSpankingNewUSBDeviceData(line)
        # broadcast the data
        for obs in self.observers[:]:
            obs(output)

rawDescription: Producing content indefinitely in a separate thread for all connections?


code:
from contextlib import contextmanager
from smtplib import SMTPResponseException, SMTPServerDisconnected

@contextmanager
def quitting_smtp_cm(smtp):
    try:
        yield smtp
    finally:
        try:
            code, message = smtp.docmd("QUIT")
            if code != 221:
                raise SMTPResponseException(code, message)
        except SMTPServerDisconnected:
            pass
        finally:
            smtp.close()

rawDescription: python: sending a mail, fails when inside a "with" block

description: Python: sending a mail, fails when inside a "with" block


code: month, day, year = re.split(">>| |\. ", s)[1:4]

rawDescription: Python: split string at word

description: Python: split string at word


code:
def foo(self, b=self.b):
    return bar(b)

rawDescription: Refactoring "x if x is not None else y" to "x or y"


code: attachments = [('yourpdf.pdf', pdf_contents)]

rawDescription: Attaching a PDF to an email in Appengine (Python)


code: [(mat[j], mat[k]) for j, k in enum_upperdiag(mat)]

rawDescription: NumPy: Iterating over items to right, bottom of given element w/ its index


code:
myregex = re.compile('(title href="#_ftnref\d+"><span lang="en-us">)(.{1,4}<)', re.IGNORECASE | re.MULTILINE);
myregex.sub('\1xyz<', content);

rawDescription: How do I make this regular expression skip over a new line in Python?

description: Make this regular expression skip over a new line in Python


rawDescription: Ignore white spaces in a regular expression


code:
from PyQt4 import QtGui
from PyQt4 import QtCore

# Create the class 'Communicate'. The instance
# from this class shall be used later on for the
# signal/slot mechanism.

class Communicate(QtCore.QObject):
    myGUI_signal = QtCore.pyqtSignal(str)

''' End class '''

# Define the function 'myThread'. This function is the so-called
# 'target function' when you create and start your new Thread.
# In other words, this is the function that will run in your new thread.
# 'myThread' expects one argument: the callback function name. That should
# be a function inside your GUI.

def myThread(callbackFunc):
    # Setup the signal-slot mechanism.
    mySrc = Communicate()
    mySrc.myGUI_signal.connect(callbackFunc)

    # Endless loop. You typically want the thread
    # to run forever.
    while(True):
        # Do something useful here.
        msgForGui = 'This is a message to send to the GUI'
        mySrc.myGUI_signal.emit(msgForGui)
        # So now the 'callbackFunc' is called, and is fed with 'msgForGui'
        # as parameter. That is what you want. You just sent a message to
        # your GUI application! - Note: I suppose here that 'callbackFunc'
        # is one of the functions in your GUI.
        # This procedure is thread safe.

    ''' End while '''

''' End myThread '''

rawDescription: Simplest way for PyQT Threading

description: Simplest way for PyQT Threading


code: _ = ctypes.memmove(pixarray, im.tostring(), w_px * h_px * 4)

rawDescription: efficiently convert string (or tuple) to ctypes array

description: Efficiently convert string (or tuple) to ctypes array


rawDescription: Deleting files associated with model - django


code:
raw_list = c._meta.get_fields_with_model()
parsed_list = [item[0].__class__.__name__ for item in raw_list._meta.get_fields_with_model()]

rawDescription: How to get a list of datatypes on Django model?

description: Get a list of datatypes on Django model


code: L = L[ndx]

rawDescription: Is there a python method to re-order a list based on the provided new indices?


code:
file = csv.writer(open(localResultPath + ".txt",'ab'),
                  delimiter='|', quoting=csv.QUOTE_NONE, quotechar='')

rawDescription: python csv writer is adding quotes when not needed

description: Python csv writer is adding quotes when not needed


code:
def search_events(request):
    term = request.GET.get('term', '')
    adminDivision = request.GET.get('adminDivision', '')
    events = Event.objects.all()
    if term:
        events = events.filter(event_name__icontains=term)
    if adminDivision:
        events = events.filter(city__admin1=adminDivision)
    data= serializers.serialize('json', events);
    return HttpResponse(data, content_type='application/json')

rawDescription: Django model filter by an empty string

description: Django model filter by an empty string


code:
class Cmd:

    def __init__(self, key, parent=None):
        self.key = key
        self.parent = parent

    def __call__(self, *args, **kwargs):
        return "%s %s" % (self.parent(), self.key) if self.parent else self.key

rawDescription: Hierarchical option tree in python

description: Hierarchical option tree in python


rawDescription: concat two dataframe using python

description: Concat two dataframe using python


code:
def split_by(iterable, split_by):
    group = []
    for elem in iterable:
        if elem == split_by:
            if group:
                yield group
            group = []
        group.append(elem)
    if group:
        yield group

rawDescription: How can I split a List (in python) in different parts (after a certain element)?

description: Split a List (in python) in different parts (after a certain element)


code:
for s in strings:
    for sc in stringscompare:
        if re.search(s, sc):
            same.append(dict)
            break
    else:
        continue
    # only reached if the inner loop broke out
    break

rawDescription: While-loop within a while-loop python

description: While-loop within a while-loop python


rawDescription: Generate lottery numbers - Convert R statement to Python


code:
import re
re.search(r'[32]', '3')
re.search(r'[32]', '2')

rawDescription: Number divided by 4 by python regex

description: Number divided by 4 by python regex


rawDescription: Arranging elements of a list of tuples

description: Arranging elements of a list of tuples


code:
import re

s = """NAME_1{a bunch of text|more text}
 1  -22.17
1 lol //
2 wtf //
NA_ME2{text|text}
 1  -25.50
1 gtfo //
NAME3{text|text}
 1  -17.50
1 brb //
2 lol //
3 wtf //
"""

guards = ["NAME_1", "NAME3"]
r = re.compile(r"^([A-Z][A-Z0-9_]+){")
printing = False

for line in s.splitlines():
    m = r.match(line)
    if m:
        if m.groups(1) and m.groups(1)[0] in guards:
            printing = True
        else:
            printing = False
    if printing:
        print(line.strip())

rawDescription: How to parse varying amounts of lines from a text file in Python?

description: Parse varying amounts of lines from a text file in Python


code:
import string
string.punctuation

rawDescription: Writing a program to print hapax's from a string


code:
from xml.etree import ElementTree as et

t = et.fromstring(df.to_html())
t.set('id', 'mytable')
et.tostring(t)

rawDescription: How to define html id for Pandas Dataframe

description: Define html id for Pandas Dataframe


code:
from matplotlib import pyplot as plt

fig = plt.figure()
plt.plot(data)
fig.suptitle('test title', fontsize=20)
plt.xlabel('xlabel', fontsize=18)
plt.ylabel('ylabel', fontsize=16)
fig.savefig('test.jpg')

rawDescription: How do I set the figure title and axes labels font size in Matplotlib?

description: Set the figure title and axes labels font size in Matplotlib


code:
a = [{'name': "Zoe", 'age': 13}, {'name': "Adam", 'age': 31}]
{key: sorted(range(len(a)), key=lambda i: a[i][key]) for key in ('name', 'age')}

rawDescription: Get sorted list of indices, for a list of dictionaries sorted by a given key


code:
from threading import Thread, enumerate
from subprocess import Popen, PIPE
from time import sleep

class nonBlockingStderr(Thread):
    def __init__(self, handle):
        self.handle = handle
        self.stderrOutput = []
        Thread.__init__(self)
        self.start()
    def stderr(self):
        if len(self.stderrOutput) <= 0:
            return ''
        else:
            ret = self.stderrOutput[0]
            self.stderrOutput = self.stderrOutput[1:]
            return ret
    def run(self):
        while 1:
            line = self.handle.readline()
            if len(line) > 0:
                self.stderrOutput.append(line)
            sleep(0.1)

from subprocess import PIPE, Popen
x = Popen(['ls', '-l'], stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False)
errHandle = nonBlockingStderr(x.stderr)
while 1:
    if x.poll() != None:
        break
    _queue.put(errHandle.stderr())
    _queue.put(x.stdout.readline())
    sleep(0.2)

rawDescription: Popen mixed data stream?

description: Popen mixed data stream


rawDescription: Replace element with a list in python

description: Replace element with a list in python


code:
import struct
struct.pack('!I', 0xAD12)

rawDescription: Sending hex packets in python

description: Sending hex packets in python


code:
Py_INCREF(Py_None);
return Py_None;

rawDescription: How to return a tuple containing a None value from the C API?

description: Return a tuple containing a None value from the C API


code:
from scipy.io import loadmat

data = loadmat('filename.mat', squeeze_me=True, struct_as_record=False)

leaf1 = data['tree1'].leaf1
# 1

leaf2 = data['tree1'].leaf2
# 2

rawDescription: Importing matlab structs within structs in python


code: exclude_set = {v for i,v in enumerate(tuple_list) if (i % 3) == 0}

rawDescription: Why is using a dict so much faster to exclude one list from another?


code:
class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

    __metaclass__ = CustomModelMetaClass

rawDescription: Django admin model plural mode global settings, not adding suffix 's'


code:
email = self.request.get('email')
product = self.request.get('product')

rawDescription: passing variables to a template on a redirect in python

description: Passing variables to a template on a redirect in python


code:
d = {}
list_of_ints = [1, 20, 3, 4]
d[frozenset(list_of_ints)] = "some value"

rawDescription: Make a list of ints hashable in python

description: Make a list of ints hashable in python


code:
import sys
import PyQt4.QtGui as QtGui

class Form(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        button = QtGui.QPushButton('Button')
        button.clicked.connect(self.my_method)

        self.radiobutton1 = QtGui.QRadioButton('1')
        self.radiobutton2 = QtGui.QRadioButton('2')

        layout = QtGui.QHBoxLayout()
        layout.addWidget(button)
        layout.addWidget(self.radiobutton1)
        layout.addWidget(self.radiobutton2)
        self.setLayout(layout)

        self.group = QtGui.QButtonGroup()
        self.group.addButton(self.radiobutton1)
        self.group.addButton(self.radiobutton2)

    def my_method(self):
        self.group.setExclusive(False)
        self.radiobutton1.setChecked(False)
        self.radiobutton2.setChecked(False)
        self.group.setExclusive(True)

app = QtGui.QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

rawDescription: uncheck radiobutton - PyQt4

description: Uncheck radiobutton - PyQt4


code:
# note, this must be done in the class definition;
# not User.get_full_name.short_description
get_full_name.short_description = 'my label'

rawDescription: How can I rename a column label in Django Admin for a field that is a method//property?

description: Rename a column label in Django Admin for a field that is a method//property


code:
class Player:
    def __init__(self, **kwargs):
        self.last_name = kwargs.get('last_name')
        # .. etc.

rawDescription: What is a better way to define a class' __init__ method with optional keyword arguments?


code:
def ModeList(lst):
    counts = {}
    for item in lst:
        counts[item] = counts.get(item, 0) + 1
    return sorted(counts, key=counts.get, reverse=True)[0]

rawDescription: Mode of a List - Python

description: Mode of a List - Python


code:
def gauss(X):
  return np.exp(-X**2 / 2.0)

#create data
X = np.linspace(-10, 10, 100)
data = []
for i in xrange(10):
  arr = np.zeros(1000)
  arr[i * 100: i * 100 + 100] = gauss(X)
  data.append(arr)
data.reverse()

rawDescription: Plot staggered histograms/lines as in FACS


code:
import hadoopy
from thrift.protocol import TBinaryProtocol
from thrift.TSerialization import deserialize
import sys

class Mapper(object):
    def __init__(self):
        sys.path.append('lib/test.zip/gen-py')
        from Test.ttypes import Test
        self.protocol_factory = TBinaryProtocol.TBinaryProtocolFactory
        self.test = Test()
    def map(self, key, value):
        deserialize(self.test, key, protocol_factory=self.protocol_factory())
        yield 1, self.test.foo + " "  + self.test.bar

if __name__ == '__main__':
    hadoopy.run(Mapper)

rawDescription: Read/Write Sequence Files Containing Thrift Records Using Hadoop Streaming with Python


code:
class Book(models.Model):
    ...
    def get_admin_url(self):
        content_type = ContentType \
            .objects \
            .get_for_model(self.__class__)
        return reverse("admin:%s_%s_change" % (
            content_type.app_label,
            content_type.model),
            args=(self.id,))

 # {{ book.get_admin_url }}

rawDescription: Why is the get_absolute_url() defined in the models.py?


code: s = set(); has_dupe = any(x in s or s.add(x) for x in l)

rawDescription: Python: Compare more numbers

description: Python: Compare more numbers


code: np.random.binomial(1, p=ps)

rawDescription: numpy draw a few bernoulli distributions at once

description: Numpy draw a few bernoulli distributions at once


code:
import datetime
from functools import partial

comb = partial(datetime.datetime.combine, datetime.date.min)

result = [comb(t1) - comb(t2) for t1, t2 in zip(list1, list2)]

rawDescription: Subtract datetime.time objects stored in two separate lists


code: wines_query = Wine.all().filter('variety =', 'merlot')

rawDescription: Modeling Hierarchical Data - GAE

description: Modeling Hierarchical Data - GAE


code:
urlpatterns = [
    url(r'^cq/', include('cq.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^(?P<team_id>[0-9]+)$', views.team, name='team') #without trailing slash for /team_id, but with for /team_id/
]

rawDescription: Django admin custom view and urls

description: Django admin custom view and urls


code:
def f(dt):
    return datetime.time(9, 15) <= dt.time() <= datetime.time(11, 20)

rawDescription: Filter with hour and minutes

description: Filter with hour and minutes


code:
for line in file_text.splitlines():
    contained = [i for i in li.split(",") if i in line.casefold()]
    if contained:
        print(line, "contains", contained)
    else:
        print(line, "contains none of those words")

rawDescription: if not a string in a file text

description: If not a string in a file text


code:
import re
def get_name_and_number(text):
    return re.match(r'(\D+)(\d+).*', text).groups()

rawDescription: How can I separate the numeric parts of filenames using Python?

description: Separate the numeric parts of filenames using Python


code:
df = pd.DataFrame(ss)
df.all()

rawDescription: Element-wise logical AND on indeterminate number of Pandas Series


code:
from subprocess import Popen

Popen(['google-chrome'])

rawDescription: Using subprocess.call to open a program

description: Using subprocess.call to open a program


code:
import numpy as np
history = np.tile(np.array([0.1, 0.3, 0.2, 0.15, 0.13])[np.newaxis,np.newaxis,:], (10, 20, 1))
remainder = -1*np.ones((10, 20))

a = history

# b is a sorted ndarray excluding the most recent observation
# it is sorted along the observation axis
b = np.sort(a[..., :-1], axis=-1)

# mask is a boolean array, comparing the (sorted)
# previous observations to the current observation - [..., -1:]
mask = b > a[..., -1:]

# The next 5 statements build an indexing array.
# True evaluates to one and False evaluates to zero.
# argmax() will return the index of the first True,
# in this case along the last (observations) axis.
# index is an array with the shape of z (2-d for this test data).
# It represents the index of the next greater
# observation for every 'element' of z.
index = np.argmax(mask, axis=-1)

# The next two statements construct arrays of indices
# for every element of z - the first n-1 dimensions of history.
indices = tuple([np.arange(j) for j in b.shape[:-1]])
indices = np.meshgrid(*indices, indexing='ij', sparse=True)

# Adding index to the end of indices (the last dimension of history)
# produces a 'group' of indices that will 'select' a single observation
# for every 'element' of z
indices.append(index)
indices = tuple(indices)
higherZ = b[indices]

mask = b >= a[..., -1:]
# Since b excludes the current observation, we want the
# index just before the next highest observation for lowerZ,
# hence the minus one.
index = np.argmax(mask, axis=-1) - 1
indices = tuple([np.arange(j) for j in b.shape[:-1]])
indices = np.meshgrid(*indices, indexing='ij', sparse=True)
indices.append(index)
indices = tuple(indices)
lowerZ = b[indices]
assert np.all(lowerZ == .1)
assert np.all(higherZ == .15)

rawDescription: Gridwise application of the bisection method


code:
import numpy as np

def get_lerp_factor(a, x, b):
    a, x, b = np.asarray(a), np.asarray(x), np.asarray(b)
    return ((x - a) / (b - a)).clip(0, 1)

rawDescription: How to code a Python function that accepts float, list or numpy.array?

description: Code a Python function that accepts float, list or numpy.array


code:
import sys

__import__('os')
'os' in sys.modules # True

rawDescription: NameError when trying to use module that has been imported


code:
import requests

# Write server response to file
with open("nasdaq.csv", 'wb') as f:
       f.write(requests.get(url).content)

rawDescription: Using python requests to mask as a browser and download a file


code:
hs = [1,2,3,4]
x = 7
for h in hs:
    print(derivative(x, h))

rawDescription: Repeating calculations in Python

description: Repeating calculations in Python


code:
with open ("from_baryon.csv", "r") as inFile:
    with open (self.filename, "a") as outFile:
        out_file = csv.writer (outFile)
        in_reader = csv.reader(inFile)
        for row in in_reader:
            out_file.writerow(row)

rawDescription: Write CSV Python

description: Write CSV Python


code:
def constrained_product_nonneg(target, *args):
    pools = map(tuple, args)
    if len(pools) == 1:
        for y in pools[0]:
            if y == target:
                yield (y,)
    else:
        for y in pools[-1]:
            if target-y >= 0:
                for x in constrained_product_nonneg(target-y, *pools[:-1]):
                    yield x + (y,)

rawDescription: Challenge: Creating a list of tuples of different combinations with different value 'options' in each location of the tuple.


code:
import unittest.mock
m = unittest.mock.Mock()
m.role.role = "some_value"
m.role.role

rawDescription: How to write clean python mock code with nested property mock

description: Write clean python mock code with nested property mock


code: prediction_val = sess.run(prediction, feed_dict={x: dataset.images})

rawDescription: Using TensorFlow to classify Handwritten Digits without validation labels


code: hashes = [hashlib.md5(a+b).digest() for a, b in zip(f,l)]

rawDescription: Python hashlib - Update and Digest for list comprehension


code:
class Base():

    # add class dictionary mapping uids to instances
    uid_to_obj = defaultdict(dict)

    def __init__(self, uid):
        self.uid = uid
        self.__hash = hash(self.uid)

        # add specific sub-class mapping for each sub-class
        Foo.uid_to_obj[type(self).__name__][uid] = self

    def __hash__(self):
        return self.__hash

    def __eq__(self, other):
        return self.__hash == other.__hash

rawDescription: Find item in set via hash

description: Find item in set via hash


code:
data = [['NEW', 'kylie', 'OPERATOR', '/sbin/nologin'],
        ['DELETE', 'ron', 'ADMINISTRATOR', '/sbin/bash'],
        ['NEW', 'jessie', 'GUEST', 'sbin/nologin']]

for record in data:
    if record[0] == 'NEW':
        b.USER.create([get_user_object(*record[1:])])
    else:
        b.USER.delete([record[1]])

rawDescription: Creating a mixed python data structure by iterating over a list of lists


rawDescription: convert Ghostscript from os.popen to subsession.popen python

description: Convert Ghostscript from os.popen to subsession.popen python


code:
g = sns.FacetGrid(data=df, col='group')
g.map(plt.hist, 'val', color='black', lw=0)
g.map(vertical_mean_line, 'val')
g.set_titles('{col_name}')

rawDescription: Customizing annotation with Seaborn's FacetGrid


code: map(lambda x: x.pop(1), triangle)

rawDescription: Python - Delete column from a matrix without numPy


code:
class AutoJoiningProcess(multiprocessing.Process):
    def start(self):
        thread = AutoJoiningThread(target=self.start_process)
        thread.start() # automatically joins

    def start_process(self):
        multiprocessing.Process.start(self)
        self.join()

rawDescription: In Python, how do I know when a process is finished?


code: [None, 'foo', 'bar', 'foofoo', ...]

rawDescription: Sorting dictionary for printing

description: Sorting dictionary for printing


code:
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import io

temp=u"""tweetcricscore 51 high active
tweetcricscore 46 event based
tweetcricscore 12 event based
tweetcricscore 46 event based
tweetcricscore 1 viewers
tweetcricscore 178 viewers
tweetcricscore 46 situational
tweetcricscore 23 situational
tweetcricscore 1 situational
tweetcricscore 8 situational
tweetcricscore 56 situational"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp),
                 sep="\s+", #separator is arbitrary whitespace
                 names=['keyword','freq','class1','class2']) #set new col names

rawDescription: Pandas Seaborn Swarmplot doesn't plot

description: Pandas Seaborn Swarmplot doesn't plot


code:
import re

with open("in.txt") as i, open("out.txt", "w") as o:
    for line in i:
        if re.search("ENTRY|VERSION", line):
           o.write(line)

rawDescription: python sed not working

description: Python sed not working


code:
import pprint

from querystring_parser import parser as qsparser

# I had to modify the query string you provided by adding a value
# search[6]; it didn't have one before, which caused an exception
query_string = (
    'cmd=get-records&limit=100&offset=0&search[0][field]=number&'
    'search[0][type]=text&search[0][operator]=contains&'
    'search[0][value]=Mike+Jones&search[1][field]=name&search[1][type]=text&'
    'search[1][operator]=contains&search[1][value]=Mike+Jones&'
    'search[2][field]=role&search[2][type]=text&search[6]=SEARCH6&'
    'searchLogic=OR'
    )  # NOTE: I had

query_string_as_dict = qsparser.parse(query_string)

pprint.pprint(query_string_as_dict)

rawDescription: Parse the following query string into json using python


code: d = np.diff(points, axis=0)

rawDescription: Calculating euclidean distance between consecutive points of an array with numpy


rawDescription: What is a "slug" in Django?

description: What is a "slug" in Django


code:
my_list = [[2, 0.84], [2, 0.75], [2, 0.63], [2, 0.6]]
my_array = np.array(my_list)
timeit.timeit("my_array[:, 1]", setup="from __main__ import my_array", number=10000)
timeit.timeit("[item[1] for item in my_list]", setup="from __main__ import my_list", number=10000)
timeit.timeit("list(zip(*my_list)[1])", setup="from __main__ import my_list", number=10000)

rawDescription: Python list of lists -> make sublists of element n


code:
import Image, numpy
i = Image.open('img.png')
i = i.convert('L')    #convert to grayscale
a = numpy.asarray(i)

b = numpy.fft.rfft2(a)
c = numpy.fft.irfft2(b)

j = Image.fromarray(c.astype(numpy.uint8))
j.save('img2.png')

rawDescription: fft and array-to-image / image-to-array-conversion

description: Fft and array-to-image / image-to-array-conversion


code:
def search_dictionary(user_input, haystack):
    for key,value in haystack.items():
        if user_input == key:
            return value
        if user_input == value:
            return key

rawDescription: How to access part of a dictionary in python?

description: Access part of a dictionary in python


code: {score: 5}

rawDescription: Passing data between python and javascript using JSON


code:
class PageSerializer(serializers.ModelSerializer):
    stuff = YOURColltionserializer(many=True)
    class Meta:
        model = Page
        fields = ("title", "stuff" )

rawDescription: Creating a Serialiser for a Reverse Generic Relationship


rawDescription: Create empty csv file with pandas

description: Create empty csv file with pandas


code: zz

rawDescription: How to convert JavaScript dictionary into Python syntax

description: Convert JavaScript dictionary into Python syntax


code:
lines = [ ... ]

with open('sometextfile', 'a') as outfile:
    outfile.write('\n'.join(lines) + '\n')

rawDescription: Append a list of strings to a file in a single line? - Python


code: c = (b.reshape(2,4)+a).ravel()

rawDescription: numpy tile without memory allocation

description: Numpy tile without memory allocation


code:
import os
import functools

def low_priority(f):
    @functools.wraps(f)
    def reniced(*args, **kwargs):
        os.nice(5)
        try:
            f(*args,**kwargs)
        finally:
            os.nice(-5)
    return reniced

rawDescription: Is there a way to "nice" a method of a Python script


code:
g = df.groupby('person')
g['value'].apply(lambda s: s.shift())

rawDescription: Pandas data frame: adding columns based on previous time periods


code:
dat
dat_dtype
np.genfromtxt(dat, dtype=dat_dtype)

rawDescription: How to convert an array of strings to a record array?

description: Convert an array of strings to a record array


code: columns.loc[columns[0].str.startswith('Unnamed:'), 0] = np.nan

rawDescription: Pandas read multiindexed csv with blanks


code: df1['year'] = df1['timestamp'].apply(lambda x: x.year)

rawDescription: python pandas time series year extraction

description: Python pandas time series year extraction


code:
def OnClick(self, event):
    name = event.GetEventObject().myname

rawDescription: Best way to get the name of a button that called an event?

description: Get the name of a button that called an event


code:
import enchant
d = enchant.Dict('de_DE')
d.check("Hello") # False
d.check("Guten") # True

rawDescription: How to add dictionary to PyEnchant?

description: Add dictionary to PyEnchant


code:
class JobOpeningIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    recipe_ingredient = indexes.MultiValueField()

    def prepare_recipe_ingredient(self, obj):
        return [i.name for i in obj.recipe_ingredient.all()]

    def get_model(self):
        return job_opening

    def index_queryset(self, using=None):
        return self.get_model().objects.all()

rawDescription: Django manytomany field, how to get check for 80% subset/ match?


code:
datapoints = [{'a': 1, 'b': 2, 'c': 6},
              {'a': 2, 'd': 8, 'p': 10},
              {'c': 9, 'd': 1, 'z': 12}]

# get all the keys ever seen
keys = sorted(set.union(*(set(dp) for dp in datapoints)))

with open("outfile.txt", "wb") as fp:
    # write the header
    fp.write("{}\n".format(' '.join([" "] + keys)))
    # loop over each point, getting the values in order (or 0 if they're absent)
    for i, datapoint in enumerate(datapoints):
        out = '{} {}\n'.format(i, ' '.join(str(datapoint.get(k, 0)) for k in keys))
        fp.write(out)

rawDescription: Building a dictionary of words from multiple lists in python


code: fn = (lambda x: x) if True else (lambda x: x*x)

rawDescription: anonymous function assignment using a one line if statement

description: Anonymous function assignment using a one line if statement


code:
from dis import dis
list1, list2, list3 = [0, 1], ['a', 'b'], [2, 3]

def func():
    for item in list1 + list2 + list3:
        print(item)

dis(func)

rawDescription: Iterate two lists in the same loop

description: Iterate two lists in the same loop


code: map(str, l)

rawDescription: Why use the map() function?

description: Why use the map() function


code:
import networkx as nx
megalist = [['a', 'b'], ['a', 'd'], ['b', 'd'],['b', 'f'], ['r', 's'], ['t', 'r']]
G = nx.Graph()
G.add_edges_from(megalist)

rawDescription: Split a tuple of tuples (or list of lists) of paired values into independent complete sets?


code:
from toolz.functoolz import curry

@curry
def processDataLine(arg1, arg2, dataline):
    return ... # Do something with dataline, arg1, arg2

json_data_rdd.flatMap(processDataLine(arg1, arg2))

rawDescription: Spark RDD - Mapping with extra arguments


code:
def foo(lst):
    total_sum = sum(lst)
    i = 1
    while sum(lst[:i]) < total_sum / 2:  # iterate over the list slices until we hit the "middle"
        if sum(lst[:i+1]) >= total_sum / 2:  # also make sure that we won't go further
            break

        i += 1

    return [lst[:i], lst[i:]]

rawDescription: Split array to approximately equal chunks


code:
# deltas.shape = (n_set_points, n_test_point, n_dims)
deltas = (set_points[:, np.newaxis, :] -
          test_points[np.newaxis, ...])

# dist[j, k] holds the squared distance between the
# j-th set_point and the k-th test point
dist = np.sum(deltas*deltas, axis=-1)

# nearest[j] is the index of the set_point closest to
# each test_point, has shape (n_test_points,)
nearest = np.argmin(dist, axis=0)

rawDescription: Fast evaluation of a product

description: Fast evaluation of a product


rawDescription: Python reads data from webpages

description: Python reads data from webpages


code:
class GenCl(object):
    def __init__(self, a, b, c):
        self.startPt = fn(a, b, c)

    def gen(self):
        startPt = self.startPt  # get the startPt calculated in __init__
        data = (yield None)
        while True:
            # perform some computation
            data = (yield result)

o = genCl(5, 6, 7)
startPt = o.startPt
f = o.gen()  # create the generator object
f.send(None)
for data in dataseries[startPt:]:
    k = f.send(data)

rawDescription: How to store and retrieve meta-information in generator function object instance?

description: Store and retrieve meta-information in generator function object instance


code:
data_structure = [{'Name':'John','Age':'20'},{'Name':'John','Age':'22'},{'Name':'John','Age':'23'},{'Name':'Marie','Age':'20'}]

while 1:
    name = raw_input("Enter Name: ")
    if not len(name): break
    age = int(raw_input("Enter Age: "))
    flag=1
    while flag:
        for idx, d in enumerate(data_structure):
            if 'Name' in d and \
                'Age' in d and \
                int(d['Age']) != age and \
                d['Name'] == name:
                data_structure.pop(idx)
                flag=2
                break
        flag-=1

rawDescription: Deleting equal values of dict in list python


rawDescription: Python pandas Filtering out nan from a data selection of a column of strings


code: myfunc()

rawDescription: how can I print this dictionary in the correct order and print the total amount? (python)

description: Print this dictionary in the correct order and print the total amount? (python)


code:
#!/usr/bin/env python
import json
import sys

args = json.load(sys.stdin)   # read input data from stdin
result = [x*x for x in args]  # compute result
json.dump(result, sys.stdout) # write result to stdout

rawDescription: Getting return infromation from another python script


code:
min(colors.items(), key=NearestColorKey((10,10,100)))
min(colors.items(), key=NearestColorKey((10,10,200)))
min(colors.items(), key=NearestColorKey((100,10,200)))

rawDescription: Color classification library

description: Color classification library


rawDescription: Mapping a table function to a model using SQLAlchamy


code:
def __str__(self):
    return "Attr1: {0.attr1}, Attr2: {0.attr2}, ...".format(self)

rawDescription: Printing all objects from a class

description: Printing all objects from a class


code:
messages = validate_emails(["a", "b", "c"], "somedomain.com", "sales")
return render_template("validation.html", data=messages)

rawDescription: Surfacing results as they are printed on HTML Page


code: converted = [dict(zip(stock, column)) for column in zip(*stock.values())]

rawDescription: How to convert lists in a dictionary to dictionaries in a lists (Python)

description: Convert lists in a dictionary to dictionaries in a lists (Python)


code:
if option != 0:
    return []
return [element for element in nList if element > 5]

rawDescription: Trying to return numbers in a list

description: Trying to return numbers in a list


code:
class Seller(models.Model):
    name = models.CharField(max_length=200)

class Customer(models.Model):
    name = models.CharField(max_length=200)
    feedbacks = models.ManyToManyField(Seller, through='Feedback', related_name='feedbacks')

class Feedback(models.Model):
    seller = models.ForeignKey(Seller)
    customer = models.ForeignKey(Customer)
    seller_feedback = models.IntegerField()
    customer_feedback = models.IntegerField()

rawDescription: Django: Efficient model for ordered list of objects


rawDescription: How to use zip and map to write csv file in Python?

description: Use zip and map to write csv file in Python


code:
while GPIO.input(ECHO1) == 0:
    pass #This is here to make the while loop do nothing and check again.

start = time.time() #Here you set the start time.

while GPIO.input(ECHO1) == 1:
    pass #Doing the same thing, looping until the condition is true.

stop = time.time()

print (stop - start) * 170 #Note that since both values are integers, python would multiply the value with 170. If our values were string, python would write the same string again and again: for 170 times.

rawDescription: Single Ultrasonic Sensor for Raspberry pi 2B+ not functioning from Pi Terminal


code:
import itertools
myset = set(itertools.chain(A, B, C))

rawDescription: What is the preferred way to compose a set from multiple lists in Python


code:
def group_dates(dates, delta):
    it = iter(dates)
    prev = next(it)
    grouped, total = (prev,),delta.total_seconds()
    for dte in it:
        if (dte - prev).total_seconds() <= total:
            grouped = grouped + (dte,)
        else:
            yield td(grouped)
            grouped = (dte,)
        prev = dte
    yield td(grouped)

pp(list(group_dates(dates,  delta=dt.timedelta(minutes=2))))
[datetime.datetime(1970, 1, 1, 0, 2, 30),
 datetime.datetime(1970, 1, 1, 0, 12),
 datetime.datetime(1970, 1, 1, 0, 8),
 datetime.datetime(1970, 1, 1, 0, 13)]

rawDescription: reduce datetime list by timedelta

description: Reduce datetime list by timedelta


code:
# Create an input list of arrays
np.stack(list_of_matrices,axis=0).shape

rawDescription: Converting a list of 3d matrix into 4d matrix


code:
class C(object):
    def __init__(self, fitness):
        self.fitness=fitness
    def __repr__(self):
        return "fitness: %s"%self.fitness

from operator import attrgetter
L=[C(10),C(4),C(1),C(99)]
sorted(L, key=attrgetter('fitness'))
S=set(L)
sorted(S, key=attrgetter('fitness'))

rawDescription: How to sort a collection of objects by an variable they all hold?

description: Sort a collection of objects by an variable they all hold


code:
import os
oldFile = r'C:\folder\subfolder\inFile.txt'  # note the r character for raw string
os.path.normpath(oldFile)

rawDescription: Rename files using python

description: Rename files using python


rawDescription: Delete column if items don't contain a Number


rawDescription: Java's TreeSet equivalent in Python?

description: Java's TreeSet equivalent in Python


code:
import matplotlib.pyplot as plt
plt.xlabel('my x label', size = 20)
plt.ylabel('my y label', size = 30)
plt.title('my title', size = 40)
plt.xticks(size = 50)
plt.yticks(size = 60)

rawDescription: how to make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger

description: Make the text size of the x and y axis labels and the title on matplotlib and prettyplotlib graphs bigger


code:
import Tkinter as tk
import tkFont

label = tk.Label(...)
original_font = tkFont.nametofont(label.cget("font"))
custom_font = tkFont.Font()
custom_font.configure(**original_font.configure())
label.configure(font=custom_font)

rawDescription: TkInter Label Change Font Size by Text Length


code:
import urlparse
import urllib

s = 'w=123&q=456&tw=123&w=123abc&foo=bar&w=12'

# s here must be key=value&key=value only
parsed = urlparse.parse_qsl(s, keep_blank_values=True)
filtered = [ i for i in parsed if not (i[0] == 'w' and i[1].isdigit()) ]
s = urllib.urlencode(filtered)

rawDescription: Using a regexp to match my string content?


code: any(url in link for link in links)

rawDescription: Check if url that belongs to the same domain exists in list with python?


code:
data = []
for cars in soup.find_all('div', {'class': 'car-info-wrapper'}):
    car_info = {} # Start with an empty dictionary for each car.

    car_info['name'] = cars.find("div", {"class": "car-name-wrapper"}).find('a').get_text()
    car_info['year'] = cars.find("p", {"class": "cr-levy car-year"}).get_text()
    car_info['engine'] = cars.find("div", {"class": "cr-det-in cr-engine"}).p.get_text()
    car_info['mileage'] = cars.find("div", {"class": "cr-det-in cr-road"}).p.get_text()

    data.append(car_info)

return render_template("index.html", data=data)

rawDescription: Parsing List or dict to Flask from Beautifulsoup


rawDescription: Conditional Cell Substitution in Pandas, Python 2.7


rawDescription: Scrape data from reduced table

description: Scrape data from reduced table


code: data = scipy.stats.norm.rvs(loc=5, scale=10, size=(1000,))

rawDescription: Using Scipy's stats.kstest module for goodness-of-fit testing


code:
with open('file01.txt', 'w') as fobj_out:
    for line in data1:
        if line.split('|', 1)[0] == code:
            fobj_out.write(data2 + '\n')
        else:
            fobj_out.write(line)

rawDescription: Replacing data to different file

description: Replacing data to different file


code:
df1 = (sqlContext.read
    .format('com.databricks.spark.csv')
    .options(header='true', inferSchema='true')
    .load(file1))

rawDescription: Python Spark How to Map Fields of one rdd to another rdd


code:
string = """ Hello "XYZ" this 'is' a test & so on """
import html
html.escape(string)

rawDescription: Escape special HTML characters in Python


code:
class FooView(View):
    def get(self, request, *args, **kwargs):
        obj = Foo.objects.get(pk=1)
        obj_difference = obj.loan_amount - obj.service_charge
        return render(request, 'index.html', {'obj': obj,
                                              'obj_difference': obj_difference})

rawDescription: Subtracting two variables in django template


rawDescription: How to create dummy variable and then aggregate using scikit-learn?

description: Create dummy variable and then aggregate using scikit-learn


code:
following_company = models.ManyToManyField(Company, blank=True, null=True)
following_hc = models.ManyToManyField(Institution, blank=True, null=True)

rawDescription: Model Many to Many relations with Abstract Class


code:
Cards = [[["QS","5H","AS"],["2H","8H"],["7C"]],[["9H","5C"],["JH"]],["7D"]]
from compiler.ast import flatten
flatten(Cards)

rawDescription: How to get every element in a list of list of lists?

description: Get every element in a list of list of lists


code: df['time_group'] = df['back_to_0'].cumsum() + 1

rawDescription: parsing pandas data frame base on conditions and save it to a csv

description: Parsing pandas data frame base on conditions and save it to a csv


rawDescription: Python Text Document Translation Comparison


rawDescription: How can I add an additional row and column to an array?

description: Add an additional row and column to an array


code: this_year = ("'"+str(this_year)+"'")

rawDescription: Python SQLITE3 SELECT query with datetime calculated string not working


code:
import numpy as np
timepoints = [1,3,7,15,16,17,19]
myarray = np.array(timepoints)
def mypolynomial(bins, pfinal):   #pfinal is just the estimate of the final array (i'll do quadratic)
    hist = np.zeros((1, len(myarray)))    # define blank return
    for i in range(len(pfinal)):
        # fixed a typo here, was pfinal[-i] which would give -0 rather than -1, since negative indexing starts at -1, not -0
        const = pfinal[-i-1]    # negative index to go from 0 exponent to highest exponent
        hist += const*(bins**i)
    return hist
mypolynomial(myarray, (1,1,0))

rawDescription: Obtaining Legendre polynomial form once Legendre coefficients are determined


rawDescription: Finding the index of the second match of a regular expression in python


code:
from itertools import product

def generate_edges(iterable, control):
    edges = []
    control_set = set(control)
    for e in iterable:
        e_set = set(e)
        common = e_set & control_set
        to_pair = e_set - common
        edges.extend(product(to_pair, common))
    return edges

rawDescription: Search a list of list of strings for a list of strings in python efficiently


code:
with open(os.path.join(curdir, 'OAUTH.txt')) as f:
  lines = f.readlines()
  # line regex, to test that the line can be split correctly.
  line_regex = re.compile('^\w*[=]{1}\w*$')
  api = { line.split('=')[0]: line.split('=')[1] for line in lines if line_regex.match(line) }

rawDescription: Removing \n from list being split into variables - Python


code: dict( (n, a.get(n, 0)+b.get(n, 0)) for n in set(a)|set(b) )

rawDescription: "Adding" Dictionaries in Python?

description: "Adding" Dictionaries in Python


code: open('new', 'w').writelines(header + list_of_lines)

rawDescription: Pythonic way to ignore for loop control variable


rawDescription: Find max since condition in pandas timeseries dataframe


code: output = output[:,::-1]

rawDescription: How do I telescope the columns of a numpy array?

description: Telescope the columns of a numpy array


code: outputFile = open('out'+uniprotID+'.txt','w')#file for result output

rawDescription: file output error with correct values

description: File output error with correct values


code:
x.max(0)
x.min(0)

rawDescription: Fastest Way to generate 1,000,000+ random numbers in python


code:
df["strike"] > (df["strike"].shift() + 100)
(df["strike"] > (df["strike"].shift() + 100)).cumsum()

rawDescription: How to split pandas dataframe based on difference of values in a column

description: Split pandas dataframe based on difference of values in a column


code:
from ansible import errors
from jinja2.filters import environmentfilter
import re

class FilterModule(object):
    def filters(self):
        return {
            'scrubmac': self.scrubmac
        }
    def scrubmac(*args):
        data = args[1]
        for item in data:
            mac = re.sub('[^A-z0-9]', '', item['mac'])
            item['mac'] = re.sub('(.{2})(?=.)', '\\1-', mac)
        return data

rawDescription: How to use jinja2 filters to scrub dict values in ansible playbook

description: Use jinja2 filters to scrub dict values in ansible playbook


code: from Indicators import Stochastics

rawDescription: How to organize a Python Project?

description: Organize a Python Project


rawDescription: How can I correctly pass Content-MD5 headers when putting files on S3 using boto's Key.generate_url method?

description: Correctly pass Content-MD5 headers when putting files on S3 using boto's Key.generate_url method


code:
setup(
    name="mypackage",
    version="R2014",
    description='My module',
    author='me',
    url='http://www.example.com/',
    platforms=['Linux', 'Windows', 'MacOS'],
    package_dir={'': 'dist'},
    packages=['my_package'],
    cmdclass={'build_py': BuildMyPackage},
    data_files=[('my_data', ['path/in/my/source/tree/to/some_large_file.txt'])]
)

rawDescription: Is it all right to put a large non-Python file into site-packages?


rawDescription: IPython "Column not found error"

description: IPython "Column not found error"


code:
affy_reader = csv.DictReader(filter(filter_plus_print, file_pointer),
                             delimiter='\t',
                             fieldnames=affy_column_headers)

rawDescription: Python - Use a print/debug statement within a Lambda


code:
import re
s = "pattern foo start fkdsjflsd pattern jdflsdjf pattern end pattern"
re.sub(r'(?<!\S)pattern(?!\S)(?=(?:(?!(?<!\S)(?:start|end)(?!\S)).)*?(?<!\S)end(?!\S))', r'replace_pattern', s)

rawDescription: python re replace all between tags

description: Python re replace all between tags


rawDescription: manipulating lists to find different variables

description: Manipulating lists to find different variables


rawDescription: Extracting Groups

description: Extracting Groups


code:
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.elasticsearch_backend.ElasticsearchSearchEngine',
        'URL': 'http://<ip-of-redis-server>:9200/',
        'TIMEOUT': 60 * 5,
        'INCLUDE_SPELLING':True,
        'INDEX_NAME': '<name-of-index>'
        }
    }

rawDescription: Django: Use MySQL and ElasticSearch in single application


code:
st='wordW wordX wordY wordZ'
re.findall(r'(?=(\b\w+\s\b\w+))', st)

rawDescription: Check if string contains a certain amount of words of another string


code:
df # pandas.DataFrame
s  # pandas.Series

df[s.values] # df, filtered by the bool array in s

rawDescription: Select from pandas dataframe using boolean series/array


code: numpy.mgrid[:m:(m+1)*1j, :n:(n+1)*1j]  # m+1 values from 0 to m, n+1 values from 0 to n

rawDescription: Multiple copies of array returned by numpy.arange?


code: img = request.json['imageData'] # Store this in DB (use blob)

rawDescription: Flask with Javascript

description: Flask with Javascript


code:
fn = getattr(foo_obj, str_command, None)
if callable(fn):
    fn()

rawDescription: How to dynamically select a method call in Python?

description: Dynamically select a method call in Python


rawDescription: How to move a line diagonally (on a canvas) in python?

description: Move a line diagonally (on a canvas) in python


code: {key: (value[0] if len(value) == 1 else tuple(value)) for key, value in d.items()}

rawDescription: Create a dictionary with different length for values using dictionary comprehension


code:
import nameInput
nameInput.main()

rawDescription: Files only importing if opened from certain place


code:
def copy_four(s):
    return s[-4:].rjust(4,'A')

rawDescription: How to make this simple string function "pythonic"

description: Make this simple string function "pythonic"


rawDescription: Filling continuous pandas dataframe from sparse dataframe


rawDescription: running average of items list in python in reverse order

description: Running average of items list in python in reverse order


code:
lst = ('apple', 'pizza', 'x', 'joke')
[s[:2] + s[-2:] if len(s) > 4 else s for s in lst]

rawDescription: How do I loop through each string in my list?

description: Loop through each string in my list


code:
import modA
class A1(modA.A):
   ...

rawDescription: How to split a Python module into multiple files?

description: Split a Python module into multiple files


rawDescription: Reshaping arrays in an array of arrays

description: Reshaping arrays in an array of arrays


code:
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)

rawDescription: scipy: savefig without frames, axes, only content

description: Scipy: savefig without frames, axes, only content


rawDescription: swap one element list to int

description: Swap one element list to int


rawDescription: Numpy matrix combination

description: Numpy matrix combination


rawDescription: Schedule Maximum Number Tasks That have Fixed Start and End times


code:
def s(n):
    tsum = 0
    i = 1
    con = n
    while i < con:
        if n % i == 0:
            temp = n / i
            tsum += i
            if temp != i:
                tsum += temp
            con = temp
        i += 1
    return tsum

rawDescription: How would I go about improving/making this run faster?


code:
d = {'father_id':"No.1", 'a_have_list':[{'child_id':1},{'child_id':2}]}
[dict(child, father_id=d['father_id']) for child in d['a_have_list']]

rawDescription: In python how can I hoist key from a dict without loop?


code:
import itertools

def dict_gen(n):
    letr = 'abcdefghijklmnopqrstuvwxyz'
    return itertools.chain(''.join(j) for i in range(n)
                           for j in itertools.product(letr, repeat=i+1))

rawDescription: improve this very-simple dictionary generator in python

description: Improve this very-simple dictionary generator in python


code:
def parse(self, response):
    return scrapy.FormRequest.from_response(
        response,
        formxpath="//form[@id='search-form']",
        formdata={
            "search_terms": "business",
            "geo_location_terms" : "78735"},
        callback=self.after_results
    )

rawDescription: Scrapy web crawling going bad

description: Scrapy web crawling going bad


code:
MY_SLEEP = 1

def my_pause():
    time.sleep(MY_SLEEP)

my_pause() # waits 1 second
my_pause() # waits 1 second again.

rawDescription: Python can i access a class method from another class without passing it as a parameter?


code:
name = input("So, what is your name? ")
while not name.isalpha():
    print ("That's not a real name! Try again...")
    name = input("So, what is your name? ")
print ("So your name is " +(name) + "? Awesome.")

rawDescription: How do I force the player in a text-based game to use an alphabet-only name?

description: Force the player in a text-based game to use an alphabet-only name


code:
import numpy
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot
from matplotlib.collections import PolyCollection

def drawPropagation(beta2, C, z):
    """ beta2 in ps / km
        C is chirp
        z is an array of z positions """
    T = numpy.linspace(-10, 10, 100)
    sx = T.size
    sy = z.size

    T = numpy.tile(T, (sy, 1))
    z = numpy.tile(z, (sx, 1)).T

    U = 1 / numpy.sqrt(1 - 1j*beta2*z * (1 + 1j * C)) * numpy.exp(- 0.5 * (1 + 1j * C) * T * T / (1 - 1j*beta2*z*(1 + 1j*C)))

    fig = pyplot.figure()
    ax = fig.add_subplot(1,1,1, projection='3d')
    U = numpy.abs(U)

    verts = []
    for i in xrange(T.shape[0]):
        verts.append(zip(T[i, :], U[i, :]))

    poly = PolyCollection(verts, facecolors=(1,1,1,1), edgecolors=(0,0,1,1))
    ax.add_collection3d(poly, zs=z[:, 0], zdir='y')
    ax.set_xlim3d(numpy.min(T), numpy.max(T))
    ax.set_ylim3d(numpy.min(z), numpy.max(z))
    ax.set_zlim3d(numpy.min(U), numpy.max(U))

drawPropagation(1.0, 1.0, numpy.linspace(-2, 2, 10))
pyplot.show()

rawDescription: Matplotlib plot pulse propagation in 3d

description: Matplotlib plot pulse propagation in 3d


code:
def divisible_numbers(a_list, a_list_of_terms):
    return [i for i in a_list if all(i%j==0 for j in a_list_of_terms)]

rawDescription: Check what numbers in a list are divisible by certain numbers?


code:
import brewer2mpl
bmap = brewer2mpl.get_map('Set2','qualitative',3,reverse=True)
colors = bmap.mpl_colors
data.plot('name','value',color=colors,kind='bar')

rawDescription: Pandas/matplotlib bar chart with colors defined by column


code:
from bs4 import BeautifulSoup

html_table_string = """

        Something else

"""
table = BeautifulSoup(html_table_string, "html.parser")

# Select first td element and set it's content to 'Something'
table.select_one('td').string = 'Something'  # or table.find('td').string = 'Something'

print(table.prettify())

rawDescription: Modifying HTML using python html package


code: struct.unpack('=HHf255s', bytes)

rawDescription: Reading a binary file into a struct in Python


code:
import json

test = {'foo':1, 'bar':[2,3]}
json_str = json.dumps(test)
print(json.loads(json_str, parse_int=str))

rawDescription: how to convert all int to str in a nested dict with json.dumps()?

description: Convert all int to str in a nested dict with json.dumps()


code: set(x) == set(y)

rawDescription: Check if two unordered lists are equal

description: Check if two unordered lists are equal


rawDescription: Load python module not from a file

description: Load python module not from a file


code:
col1 = cuteCatNum[0]    # access via integer position
col2 = cuteCatNum['COUNT']   # access via name

rawDescription: Have sqlalchemy count how many rows are in the table and print it out


code:
if now.tzinfo is not None:
    now = now.astimezone(utc).replace(tzinfo=None)
return now

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:
for idx, val in enumerate(main_counts[0]):
    canvas.create_rectangle(idx*10, 200 -val, 10 +(idx*10), 200, fill = "medium sea green", outline = "firebrick")
    canvas.create_text(idx*10 + 8, 210, text = idx + 1, font = ("Comic sans MS",8), fill = "firebrick")

rawDescription: tkinter histogram prints downwards

description: Tkinter histogram prints downwards


code: df

rawDescription: copy and paste part of the tab-type data to create new document

description: Copy and paste part of the tab-type data to create new document


rawDescription: Working with bit streams

description: Working with bit streams


code:
def avg2(x):
    res = []
    total = 0
    for idx, i in enumerate(x, 1):
        total += i
        res.append(total / idx)
    return res

rawDescription: Average Iterating through list

description: Average Iterating through list


code:
import sys
import csv

data=[]
code = sys.argv[1]
newval= int(sys.argv[2])
f=open("stockcontrol.csv")
reader=csv.DictReader(f,fieldnames=['code','level'])
for line in reader:
  if line['code'] == code:
    line['level']= newval
  data.append('%s,%s'%(line['code'],line['level']))
f.close()

f=open("stockcontrol.csv","w")
f.write("\n".join(data))
f.close()

rawDescription: String Replace in csv

description: String Replace in csv


code:
class Foo(object):
    pass

if isinstance(Foo, type):
    print("Yep, it's new-style class")

rawDescription: How to check if module attribute is a Class

description: Check if module attribute is a Class


rawDescription: Truncating column width in pandas

description: Truncating column width in pandas


code:
class Driver(models.Model):
    name = models.CharField(max_length=200)
    executable = models.CharField(max_length=200)

class Device(models.Model):
    name = models.CharField(max_length=200)
    bound_driver = models.ForeignKey(Driver, related_name="bound_to")
    available_drivers = models.ManyToManyfield(Driver)

rawDescription: Django reverse foreign key in admin

description: Django reverse foreign key in admin


code:
def delete_slice(d, start, stop):
    stop = min(stop, len(d)) # don't go past the end
    start = min(start, stop) # don't go past stop
    if start < len(d) // 2:
        d.rotate(-start)
        for i in range(stop-start): # use xrange on Python 2
            d.popleft()
        d.rotate(start)
    else:
        n = len(d) - stop
        d.rotate(n)
        for i in range(stop - start):
            d.pop()
        d.rotate(-n)

rawDescription: Python: Removing elements near the front of a list efficiently?


code:
from collections import defaultdict, Counter
from itertools import combinations

likes = defaultdict(set)
for person, fruit in zip(persons, fruits):
    likes[person].add(fruit)

counts = Counter()
for person in likes:
    for combo in combinations(likes[person], 2):
        counts[frozenset(combo)] += 1

result = counts.most_common(1)[0][0]

rawDescription: comparing two lists and finding most preferred pairs

description: Comparing two lists and finding most preferred pairs


rawDescription: Python print " character

description: Python print " character


code:
a = [ [1, 'test', 12, 'toronto'], [2, 'test', 145, 'montreal'] ]
a = [ [e [:5] if i == 3 else e for i, e in enumerate (line)] for line in a]
print (a)

rawDescription: re-size elements in a list based on index

description: Re-size elements in a list based on index


code:
from sympy import *

x = Symbol('x')
y = Symbol('y')
A = 1
B = 3
C = 6

xeq = solve(A*(1-x-y) + B*x + C*y - 4,x)[0]
print ('x = %s' % xeq)
yeq = solve(A*(1-x-y) + B*x - (8-C)*y,y)[0]
print ('y = %s' % yeq)

ysolve = 0.5
xval = xeq.subs(y, ysolve)
print ('If y = %f, x = %f' % (ysolve, xval))
yval = yeq.subs(x, xval)
print ('If x = %f, y = %f' % (xval, yval))

rawDescription: Solving a System of Algebraic Equations with SymPy


rawDescription: Django - Multiple apps on one webpage?

description: Django - Multiple apps on one webpage


code:
colors = [(u'blue', ), (u'green', ), (u'black', )]
tuple((color, color) for color, in colors)
[(color, color) for color, in colors]

rawDescription: Two Column Data Structure - Python

description: Two Column Data Structure - Python


code:
from multiprocessing import *
import time

def main():
    array, loops = list(range(1000)), 1000
    event = Event()
    p = Process(target=sample, args=(array, loops, event))
    p.start()
    event.wait()
    print('Must be at least 1000')
    p.join()

def sample(array, loops, event):
    for number in range(loops):
        if number >= 100 and not event.is_set():
            event.set()
            time.sleep(0.001)
    print('Sample is done')

if __name__ == '__main__':
    main()

rawDescription: Return value while executing paralel processes with python


rawDescription: clear and comprehensible way to calculate the string [12:3]

description: Clear and comprehensible way to calculate the string [12:3]


code: [x for x in filename.split('\n') if not re.match(r'.*(\.jpg|\.png|...).*',x)]

rawDescription: Pythonic way invert matching

description: Pythonic way invert matching


code: [['John', 'Smith', 'Red'], ['Sarah', 'Nichols', 'Green'], ['Alex', 'Johnson', 'Red']]

rawDescription: Python append value at array increment to a list


code:
def __add__(self, g):
    summed = 0
    for v in (self.whole_number, g.whole_number, self.fraction, g.fraction):
        summed = Fraction(summed.numerator * v.denominator +
                          v.numerator * summed.denominator,
                          summed.denominator * v.denominator)
    whole = summed._numerator // summed._denominator
    remainder = Fraction(summed.numerator * whole.denominator -
                         whole.numerator * summed.denominator,
                         summed.denominator * whole.denominator)
    return '{} and {}'.format(whole, remainder)

rawDescription: adding fractions class python

description: Adding fractions class python


rawDescription: How to "scale" a numpy array?

description: "scale" a numpy array


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

X = np.arange(1, 10)
Y = np.arange(1, 10)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='hot', linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

rawDescription: matplotlib - 3d surface from a rectangular array of heights

description: Matplotlib - 3d surface from a rectangular array of heights


code:
sp_mat.shape
# (2, 5)

rawDescription: Check Density of a Scipy Sparse Matrix

description: Check Density of a Scipy Sparse Matrix


rawDescription: Performance comparison of OpenCV-Python interfaces, cv and cv2


code:
[mysettings]
cond1: x >= 10
cond2: y < 5
cond3: x + y >= 6

rawDescription: reading boolean condition from config file in Python

description: Reading boolean condition from config file in Python


code:
my_svr = svm.SVR(C=1000, epsilon=0.0001)
my_svr.fit(x_training,y_trainr)

p_regression = my_svr.predict(x_test)

rawDescription: Sklearn SVM: SVR and SVC, getting the same prediction for every input


code: client = RBClient('server_url', verify_ssl=False)

rawDescription: How can I disable SSL verification with Reviewboards Python API?

description: Disable SSL verification with Reviewboards Python API


rawDescription: Converting float strings with 0 tenths and hundredths to integers in python 2.7


code:
import gviz_api

scheme = [('col1','string','SURNAME'),('col2','number','ONE'),('col3','number','TWO')]
data_table = gviz_api.DataTable(scheme)

#  --- lines in surnames.csv are : ---
#  surname,percent,cumulative percent,rank\n
#  SMITH,1.006,1.006,1,\n
#  JOHNSON,0.810,1.816,2,\n
#  WILLIAMS,0.699,2.515,3,\n

with open('surnames.csv') as f:

    def transf(surname,x,y):
        return (surname,float(x),float(y))

    f.readline()
    # to skip the first line surname,percent,cumulative percent,rank\n

    data_table.LoadData( transf(*line.split(',')[0:3]) for line in f )
    # to populate the data table by iterating in the CSV file

rawDescription: Fastest way to do data type conversion using csv.DictReader in python


code:
for d in args:
    for f in os.listdir(d):
        process(f)

rawDescription: Modify python script to run on every file in a directory


rawDescription: Set height and width of figure created with plt.subplots in matplotlib?


code:
with RewindableFile('csv.csv', 'rb') as f:
    def test_kwd_and_rewind(x):
        if x[0] != 'KEYWORD':
            return True
        else:
            f.rewind()
            return False

    reader = csv.reader(f)
    header = takewhile(test_kwd_and_rewind, reader)
    for row in header:
        print(row)
    print('End of header')
    for row in reader:
        print(row)

rawDescription: Iterator using itertools is skipping a line


code:
import logging
import logging.config
import time

class UTCFormatter(logging.Formatter):
    converter = time.gmtime

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'utc': {
            '()': UTCFormatter,
            'format': '%(asctime)s %(message)s',
        },
        'local': {
            'format': '%(asctime)s %(message)s',
        }
    },
    'handlers': {
        'console1': {
            'class': 'logging.StreamHandler',
            'formatter': 'utc',
        },
        'console2': {
            'class': 'logging.StreamHandler',
            'formatter': 'local',
        },
    },
    'root': {
        'handlers': ['console1', 'console2'],
   }
}

if __name__ == '__main__':
    logging.config.dictConfig(LOGGING)
    logging.warning('Look out!')

rawDescription: How to reconfigure a logger formatter when using dictConfig

description: Reconfigure a logger formatter when using dictConfig


code:
inputstring = 'A=Astring,B=Bstring,C=Cstring'
dict(entry.split('=') for entry in inputstring.split(','))

rawDescription: Python - Convert a key-value string to a dictionary


rawDescription: Pandas Melt on Multi-index Columns Without Manually Specifying Levels (Python 3.5.1)


code:
cmp_getters(itemgetter('foo'), itemgetter('bar'))
cmp_getters(itemgetter('foo'), itemgetter('bar','foo'))
cmp_getters(itemgetter('foo','bar'), itemgetter('bar','foo'))
cmp_getters(itemgetter('bar','foo'), itemgetter('bar','foo'))

rawDescription: comparing itemgetter objects

description: Comparing itemgetter objects


code:
def MonteCarlo(T, S, x):
    for i in range(0, x):
        starterTrans(T, S)

rawDescription: Trouble with zip when running for loop monte carlo sim; python


code:
test = subprocess.Popen(
         "find /home/disk1 -maxdepth 1 -name file1* -o -name file7*"
         , stdout=subprocess.PIPE, shell=True)
test = subprocess.Popen(
         ["find /home/disk1 -maxdepth 1 -name file1* -o -name file7*"]
         , stdout=subprocess.PIPE, shell=True)
test = subprocess.Popen(
         shlex.split(
             "find /home/disk1 -maxdepth 1 -name file1* -o -name file7*")
         , stdout=subprocess.PIPE)
test = subprocess.Popen(["find", "/home/disk1"
                               , "-maxdepth", "1"
                               , "-name", "file1*"
                               , "-o"
                               , "-name", "file7*"]
                        , stdout=subprocess.PIPE)

rawDescription: Python subprocess call is not working

description: Python subprocess call is not working


code: s = str(int(s))

rawDescription: Removing decimal place from int or string in Python


code:
class UserReferralProfile(models.Model):
    x = models.OneToOneField(User, related_name='referal')
    y = models.CharField()

rawDescription: Accessing an additional profile from templates


code: longitude = [-i for i in longitude]

rawDescription: Lines not plotting on graph using Python/Basemap


code: "\n".join([", ".join(entry) for entry in data])

rawDescription: How can I use python to display nested lists in separate lines in kv label?

description: Use python to display nested lists in separate lines in kv label


code:
def first_tuple(t):
    return t if isinstance(t,tuple) else next(x for x in t if isinstance(x,tuple))

rawDescription: Find the first tuple in anything that is or might contain a tuple?


rawDescription: Putting biographical data in order from 4 parameters using python 3.3


code:
import os
import stat

class FileAssertions(object):
    FILE_PERMS = {
        'user': {'r': stat.S_IRUSR, 'w': stat.S_IWUSR, 'x': stat.S_IXUSR, 's': stat.S_ISUID},
        'group': {'r': stat.S_IRGRP, 'w': stat.S_IWGRP, 'x': stat.S_IXGRP, 's': stat.S_ISGID},
        'others': {'r': stat.S_IROTH, 'w': stat.S_IWOTH, 'x': stat.S_IXOTH},
    }

    def assertFileMode(self, path, **kwargs):
        mode = os.stat(path).st_mode
        for key, perm_defs in self.FILE_PERMS.items():
            expected = kwargs.pop(key, None)
            if expected is not None:
                actual_perms = mode & sum(perm_defs.values())
                expected_perms = sum(perm_defs[flag] for flag in expected)

                if actual_perms != expected_perms:
                    msg = '{key} permissions: {expected} != {actual} for {path}'.format(
                        key=key, path=path,
                        expected=''.join(sorted(expected)),
                        actual=''.join(sorted(flag for flag, value in perm_defs.items()
                                              if value & mode != 0))
                    )
                    raise self.failureException(msg)
        if kwargs:
            raise TypeError('assertFileMode: unknown arguments %s' % ', '.join(kwargs))

rawDescription: Better assertEqual() for os.stat(myfile).st_mode


code:
arr2_pairs = arr2.T[numpy.array(zip(range(0, 3), range(1, 4)))]
dist = arr2_pairs - arr1.T
(dist ** 2).sum(axis=2) ** 0.5

rawDescription: Distance between numpy arrays, columnwise


rawDescription: How to use dependency injection to inject object into module?

description: Use dependency injection to inject object into module


rawDescription: Unable to locate files with long names on Windows with Python


code:
result = grouped['Period'].apply(
    lambda x: x.loc[:(x.diff() > 1).argmax()].iloc[:-1])

rawDescription: How to filter a Dataframe based on a criteria using .shift()

description: Filter a Dataframe based on a criteria using .shift()


code:
def delegate(method, prop):
    def decorate(cls):
        setattr(cls, method,
            lambda self, *args, **kwargs:
                getattr(getattr(self, prop), method)(*args, **kwargs))
        return cls
    return decorate

rawDescription: Easy way of overriding default methods in custom Python classes?


code:
# start up xclock, wait for some time to pass, kill it.
s.send("xclock&\n")
time.sleep(1)
s.send("XCLOCK_PID=$!\n")  # stash away the process id (into a bash variable)
time.sleep(30)
s.send("echo \"killing $XCLOCK_PID\"\n")
s.send("kill $XCLOCK_PID\n\n")
time.sleep(5)

rawDescription: Remote executing of program via xterm run using paramiko python ssh library


code: csv_dict_writer(filePath + 'textFirst.csv', setAndSpike, second)

rawDescription: String explosion when using Dict(zip(fieldnames, data)) function and csv.DictWriter


code:
def zeroify_if_has_zero(matrix):
    return [[0]*len(row) if 0 in row else row for row in matrix]

rawDescription: How Can One Make This Code More Pythonic?


rawDescription: Replace multiple characters in a string with one from a generator


rawDescription: Why does python allow you to create dictionaries with duplicate keys


code:
data = """Group("GroupName") {
    /* C-Style comment */
    Group("AnotherGroupName") {
        Entry("some","variables",0,3.141);
        Entry("other","variables",1,2.718);
    }
    Entry("linebreaks",
          "allowed",
          3,
          1.414
         );
} """

from pyparsing import *

# define basic punctuation and data types
LBRACE,RBRACE,LPAREN,RPAREN,SEMI = map(Suppress,"{}();")
GROUP = Keyword("Group")
ENTRY = Keyword("Entry")

# use parse actions to do parse-time conversion of values
real = Regex(r"[+-]?\d+\.\d*").setParseAction(lambda t:float(t[0]))
integer = Regex(r"[+-]?\d+").setParseAction(lambda t:int(t[0]))

# parses a string enclosed in quotes, but strips off the quotes at parse time
string = QuotedString('"')

# define structure expressions
value = string | real | integer
entry = Group(ENTRY + LPAREN + Group(Optional(delimitedList(value)))) + RPAREN + SEMI

# since Groups can contain Groups, need to use a Forward to define recursive expression
group = Forward()
group << Group(GROUP + LPAREN + string("name") + RPAREN +
            LBRACE + Group(ZeroOrMore(group | entry))("body") + RBRACE)

# ignore C style comments wherever they occur
group.ignore(cStyleComment)

# parse the sample text
result = group.parseString(data)

# print out the tokens as a nice indented list using pprint
from pprint import pprint
pprint(result.asList())

rawDescription: How to parse code (in Python)?

description: Parse code (in Python)


code:
def TrueXor(*args):
    return sum(args) == 1

rawDescription: Check if only one variable in a list of variables is set


code:
def f(A):
    return A in ["a", "b", "c"]

rawDescription: What's the convinient way to evaluate multiple string equality in Python?


code: spam_values = [v.strip() for v in parser.get('Some Section', 'spam').split(',')]

rawDescription: Python's ConfigParser unique keys per section


code:
original = [1, 2, 3, 4]
backup = list(original) # Make a shallow copy of the original.
backup.remove(3)
assert original == [1, 2, 3, 4] # It's okay!

rawDescription: How do I copy only the values and not the references from a Python list?

description: Copy only the values and not the references from a Python list


code: rule_list = [cls() for cls in Rule.__subclasses__()]

rawDescription: Initialize all the classes in a module into nameless objects in a list


code:
def say(req, what="NOTHING"):
    return "I am saying %s" % what

rawDescription: .htaccess with python scripts

description: .htaccess with python scripts


code:
lines = in_file.read()
segment_tab = re.split(r'\t|\n+', lines)

rawDescription: How to not include '\n' and the next index entry while appending values from a certain index to a list

description: Not include '\n' and the next index entry while appending values from a certain index to a list


rawDescription: Python: Parse elapsed time (minutes : seconds) to seconds


rawDescription: Function Arguments in Square Brackets

description: Function Arguments in Square Brackets


rawDescription: Sorting and Grouping Nested Lists in Python


code:
# Both of the below work on Py2 and Py3
a = [list(map(float, suba)) for suba in a]
a = [[float(x) for x in suba] for suba in a]

rawDescription: "Map" a nested list in Python

description: "Map" a nested list in Python


code: result = df.groupby('cat').sum().sort_values('value', ascending=False)

rawDescription: pandas: how to aggregate a subset of groupby rows into a single row?

description: Pandas: how to aggregate a subset of groupby rows into a single row


rawDescription: How to save a Data Frame column as a list? [Pandas]

description: Save a Data Frame column as a list? [Pandas]


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

inner_edge = np.linspace(0.1, 5.0, 10)
outer_edge = inner_edge * 0.3
mass = np.linspace(0.1, 1.2, 10)

ax = plt.subplot(111)
plt.ylim(0.1, 1.2)
plt.xlim(0.03, 5.0)

ax.fill_betweenx(mass, inner_edge, outer_edge, facecolor='b')

plt.loglog(inner_edge, mass, 'r-')
plt.loglog(outer_edge, mass, 'r-')

plt.show()

rawDescription: Using fill_between for a band

description: Using fill_between for a band


code:
def data(self, index, role):
    ...
    if role == Qt.BackgroundRole:
        return QBrush(Qt.yellow)

rawDescription: pyqt - Change row~cell collor in TableView

description: Pyqt - Change row~cell collor in TableView


rawDescription: python dict to numpy structured array

description: Python dict to numpy structured array


code:
tag = 'my_filter_tag'
q = (
    db.session
    .query(Video)
    .filter(Video.Parent.has(MediaItem.tags.any(Tags.tag == tag)))
)

rawDescription: Flask-SQLAlchemy filter on many to many relationship with parent model


code:
with open('example.csv', 'rb') as f:
    csv = f.read().decode("utf-8")

rawDescription: how to assign hierarchical column names in pandas dataframe

description: Assign hierarchical column names in pandas dataframe


rawDescription: Cases where use of tuple is a must

description: Cases where use of tuple is a must


code: s = pd.Series(df.Price * 2, name='PriceSquared')

rawDescription: DataFrameGroupBy object Column Name

description: DataFrameGroupBy object Column Name


code:
import numpy as np
import pandas as pd

nan = np.nan
df = pd.DataFrame([
    (nan, nan, nan, 'Auto loan', nan)
    , ('Branch Code', 'Branch Name', 'Region', 'No of accounts'
       , 'Portfolio Outstanding')
    , (3000, 'Name1', 'Central', 0, 0)
    , (3001, 'Name2', 'Central', 0, 0)
])
df.iloc[0:2] = df.iloc[0:2].fillna(method='ffill', axis=1)
df.iloc[0:2] = df.iloc[0:2].fillna('Area')

df.columns = pd.MultiIndex.from_tuples(
    zip(*df.iloc[0:2].to_records(index=False).tolist()))
df = df.iloc[2:]

rawDescription: Pandas: parse merged header columns from Excel


code:
def g0(x):
    r = x[:,:,0] == x[:,:,1]
    for iy in range(x[:,:,2:].shape[2]):
        r &= x[:,:,0]==x[:,:,iy]

def g1(x):   # from @Divakar
    r = ~np.any(np.diff(x,axis=2),axis=2)

def g2(x):
    r = np.amax(x,axis=2)==np.amin(x,axis=2)

rawDescription: Python: Elementwise comparison of same shaped arrays


code:
from collections import defaultdict
from pprint import pprint

D = defaultdict(list)
keyScores = set([5,4,3,2,1])
fetchData = [
             [141, [30, 26, 7, 25, 35, 20, 7], 5],
             [161, [36, 13, 29], 5],
             [166, [15, 11, 25, 7, 34, 28, 17, 28],3]
            ]
for id,data,score in fetchData:
    if score in keyScores:
        D[score].append([id,data])
pprint(D)

rawDescription: How to build a dictionary with a key and value being a list of list containing a list and matched to a value within a list

description: Build a dictionary with a key and value being a list of list containing a list and matched to a value within a list


code:
import os
from moviepy.editor import *

def resize_func(t):
    if t < 4:
        return 1 + 0.2*t  # Zoom-in.
    elif 4 <= t <= 6:
        return 1 + 0.2*4  # Stay.
    else: # 6 < t
        return 1 + 0.2*(duration-t)  # Zoom-out.

duration = 10
screensize = (640,360)

clip_img = (
    ImageClip('test.png')
    .resize(screensize)
    .resize(resize_func)
    .set_position(('center', 'center'))
    .set_duration(duration)
    .set_fps(25)
    )

clip = CompositeVideoClip([clip_img], size=screensize)
clip.write_videofile('test.mp4')

rawDescription: Moviepy zooming effects need tweaking

description: Moviepy zooming effects need tweaking


code: output_data = pool.map(function,input)

rawDescription: Where to write parallelized program output to?


code: sum(L[i:i+len(s)]==s for i in range(len(L)))

rawDescription: Counting sublists in a list

description: Counting sublists in a list


rawDescription: Counting permuations in Python

description: Counting permuations in Python


code:
input = [1,2,3,4]
tested = [i for i in input if i > 2]
len(tested) == len(input)

rawDescription: iterating through a list with an if statement

description: Iterating through a list with an if statement


code: list_words, list_scores, list_names = zip(*sorted(zip(list_words, list_scores, list_names)))

rawDescription: Re-order three lists and maintain relation between indices?


code:
cd
ls -a

rawDescription: Where do I find the bashrc file on Mac?

description: Where do I find the bashrc file on Mac


code: ["LimeCD - Lime's Code Library", 'YouTube', 'Big Solutions - Aqui nós pensamos grande!']

rawDescription: Crawler only loads one title

description: Crawler only loads one title


code:
class ClassWithGlobalFunction:
    global spam
    def spam(): return 'eggs'

    def method(self):
        global monty
        def monty(): return 'python'

rawDescription: How to define global function in Python?

description: Define global function in Python


code:
import re

def apply_backspace(s):
    while True:
        # if you find a character followed by a backspace, remove both
        t = re.sub('.\b', '', s, count=1)
        if len(s) == len(t):
            # now remove any backspaces from beginning of string
            return re.sub('\b+', '', t)
        s = t

rawDescription: python - how to apply backspaces to a string

description: Python - how to apply backspaces to a string


code:
import StringIO
from xml.etree.ElementTree import ElementTree

s = """<?xml version="1.0"?>
<servicexml>
    <action>
        <command>Add</command>
        <partnumber>1223</partnumber>
        <partname>Battery</partname>
        <partdescription>Holds charge</partdescription>
    </action>

    <action>
        <command>Add</command>
        <partnumber>4444</partnumber>
        <partname>Pump</partname>
        <partdescription>Pumps stuff</partdescription>
    </action>

</servicexml>"""

st = StringIO.StringIO(s)

tree = ElementTree()
tree.parse(st)
actions = tree.findall('action')

parsed = [{field.tag: field.text for field in action} for action in actions]

rawDescription: Multidimensional dictionary in Python

description: Multidimensional dictionary in Python


code: return dell(2, k)[1,1]

rawDescription: I am stuck at the process of retrieving a value from a matrix


code:
lower_floors = Floor.objects.filter(previous_floor__isnull=False).values_list('previous_floor', flat=True)
top_floors = Floor.objects.exclude(id__in=list(covered_floors))

rawDescription: Complicated Django annotation with self reference


code:
def execute_low_level(command, *args, **kwargs):
    connection = redis.Connection(**kwargs)
    try:
        connection.connect()
        connection.send_command(command, *args)

        response = connection.read_response()
        if command in redis.Redis.RESPONSE_CALLBACKS:
            return redis.Redis.RESPONSE_CALLBACKS[command](response)
        return response

    finally:
        del connection

rawDescription: Redis in python, how do you close the connection?


code:
D = {}
if 5 in D: # key present, use that value
    val = D[5]
else:      # otherwise create a default value and sets it
    val = list()
    D[5] = val

val.append(3)
D[5]

rawDescription: How to read python dictionary and tuples

description: Read python dictionary and tuples