code: corr = pd.concat([DF_interactions, DF_interactions.rename(columns={'var1': 'var2', 'var2': 'var1'})])

rawDescription: Convert vertical matrix to correlation matrix. Python


code: convertsmall('I have 5 brothers and 2 sisters, 7 siblings altogether.')

rawDescription: changing a word in a string?

description: Changing a word in a string


rawDescription: Using DataFrame#loc with arguments of trivially different types


rawDescription: How to check for incoming new messages using Gmail API

description: Check for incoming new messages using Gmail API


rawDescription: h5py: Correct way to slice array datasets

description: H5py: Correct way to slice array datasets


code:
def doc(docstr):
    def deco(f):
        f.__doc__ = docstr
        return f
    return deco

rawDescription: Change position of doc string in Python code


code: os.system('setterm -cursor on')

rawDescription: Display Number of Iterations in Output Window


code:
url_path = "https://.../events?" + data
server_request = urllib2.Request(url_path)

rawDescription: HOW TO translate CURL command to Python

description: HOW TO translate CURL command to Python


code:
import re
a = "@luke5sos are you awake now?!!! me #hashtag time! is@ over, now okay....so they're rich....and hopefully available?"
b = re.findall(r"(?<![@#])\b\w+(?:'\w+)?", a)
print(b)

rawDescription: Python how to split a string into words that contain words with a single quote?


code: response = opener.open(url).read()

rawDescription: With reading hebrew in urllib2 python

description: With reading hebrew in urllib2 python


code:
import glob
glob.glob('g*gle*')

rawDescription: Open file knowing only a part of its name


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

import myapp.views

urlpatterns = patterns(
    '',
    url(r'^total_calc/$', myapp.views.TotalCost.as_view(), name='calculate_total'),
)

rawDescription: How create a custom form in django with database values


code: [elem for elem, _ in Counter(m2).most_common()]

rawDescription: Python sort strings by count of appearances of the strings in the list


code:
a = np.arange(10)
a[np.argsort(a)[-3:]]

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

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


code:
def f(x):
    return x * 2

rawDescription: Lambda equivalent from Python in PHP

description: Lambda equivalent from Python in PHP


code:
import time

start_time = time.time()

# code for the game goes here

end_time = time.time()
difference = end_time - start_time      # in seconds

print("You took {} seconds".format(difference))

rawDescription: using a timer as a highscore system

description: Using a timer as a highscore system


code:
[{'contents': [{'contents': [{'contents': [{'name': 'one.png'},
                                           {'name': 'oneb.png'}],
                              'name': 'graphs'},
                             {'contents': [{'name': 'two.png'}],
                              'name': 'tikz'}],
                'name': 'images'},
               {'contents': [{'contents': [{'name': 'three.png'}],
                              'name': 'images'}],
                'name': 'refs'},
               {'name': 'one.txt'},
               {'contents': [{'name': 'two.txt'}], 'name': 'chapters'}],
  'name': 'base'}]

rawDescription: creating nested dictionary from flat list with python

description: Creating nested dictionary from flat list with python


rawDescription: generating subprocess.call arguments from a list

description: Generating subprocess.call arguments from a list


code:
import math
import traceback
import sys

inf = float("inf")
NaN = float("nan")

vals = [inf, NaN, 0.0, 1.0, 2.2, -1.0, -0.0, -2.2, -inf, 1, 0, 2]

tests = set([])

for vala in vals:
  for valb in vals:
    tests.add( (vala, valb) )
    tests.add( (valb, vala) )

for a,b in tests:
  print("math.pow(%f,%f)"%(a,b) )
  try:
    print("    %f "%math.pow(a,b))
  except:
    traceback.print_exc()

  print("__builtins__.pow(%f,%f)"%(a,b) )
  try:
    print("    %f "%__builtins__.pow(a,b))
  except:
    traceback.print_exc()

rawDescription: Difference between the built-in pow() and math.pow() for floats, in Python?


code:
'This is a test line...\n'
'This is a test line...'

rawDescription: python zipfile module with TextIOWrapper

description: Python zipfile module with TextIOWrapper


code:
import zlib
import base64

def pack_utf8_safe(data):
    is_compressed = False
    compressed = zlib.compress(data)
    if len(compressed) < (len(data) - 1):
        data = compressed
        is_compressed = True
    base64_encoded = base64.b64encode(data)
    if is_compressed:
        base64_encoded = '.' + base64_encoded
    return base64_encoded

def unpack_utf8_safe(base64_encoded):
    decompress = False
    if base64_encoded.startswith('.'):
        base64_encoded = base64_encoded[1:]
        decompress = True
    data = base64.b64decode(base64_encoded)
    if decompress:
        data = zlib.decompress(data)
    return data

rawDescription: Store arbitrary binary data on a system accepting only valid UTF8


code:
from nltk.tag.perceptron import PerceptronTagger
tagger = PerceptronTagger()
def __remove_stop_words(self, tokenized_text, stop_words, tagger=tagger):
    sentences_pos = tagger.tag(tokenized_text)
    filtered_words = [word for (word, pos) in sentences_pos
                      if pos not in stop_words and word not in stop_words]

    return filtered_words

rawDescription: Why is pos_tag() so painfully slow and can this be avoided?


code: from google.appengine import api

rawDescription: Making python imports more structured?

description: Making python imports more structured


code: outline = [k for k in lines[i].values() if k is not ''] + [cx,uf,rf,pc]

rawDescription: Python: Outputting the correct value from a list()


code:
path = '/Some/path/to/Pics2'
filename = 'forcing{0}damping{1}omega{2}set2.png'.format(forcing, damping, omega)
filename = os.path.join(path, filename)
fig.savefig(filename)

rawDescription: Python: how do I save a file in a different directory?


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

# Set up a default, sample figure.
fig = plt.figure()
x = np.linspace(-np.pi,np.pi,100)
y = 2*np.sin(x)

ax = fig.add_subplot(1,2,2)
ax.plot(x,y)
ax.set_title('Normal Spines')

def hide_spines():
    """Hides the top and rightmost axis spines from view for all active
    figures and their respective axes."""

    # Retrieve a list of all current figures.
    figures = [x for x in matplotlib._pylab_helpers.Gcf.get_all_fig_managers()]
    for figure in figures:
        # Get all Axis instances related to the figure.
        for ax in figure.canvas.figure.get_axes():
            # Disable spines.
            ax.spines['right'].set_color('none')
            ax.spines['top'].set_color('none')
            # Disable ticks.
            ax.xaxis.set_ticks_position('bottom')
            ax.yaxis.set_ticks_position('left')

hide_spines()
show()

rawDescription: Setting spines in matplotlibrc

description: Setting spines in matplotlibrc


code:
A
grps_R
grps_C

rawDescription: Find a nodes 8 neighbors on a 2D grid

description: Find a nodes 8 neighbors on a 2D grid


code: indices = [i for i, x in enumerate(iterable) if x == v]

rawDescription: How to tell when more than one index matches?

description: Tell when more than one index matches


rawDescription: Python: extracting arrays from DataFrame column


code:
x = np.arange(6)
v = x[1:4]
v -= 1
v
x

rawDescription: - vs -= operators with numpy

description: - vs -= operators with numpy


code:
def minuteMod(x, p=0):
    import datetime
    minute = datetime.datetime.now() + datetime.timedelta(seconds=15)
    minute = int(datetime.datetime.strftime(minute, "%M"))
    if minute % x == p:
        return True
    return False

rawDescription: Python: Check the url request per hour

description: Python: Check the url request per hour


code: output = np.sqrt( np.sum( (A[:,:,np.newaxis,:] - B[:,np.newaxis,:,:])**2, axis=-1) )

rawDescription: Fast distance calculation in scipy and numpy


rawDescription: Best way to apply function to element or to list of elements in python

description: Apply function to element or to list of elements in python


code: pix = a[x,y,:]

rawDescription: What is the difference between accessing image coordinates from image module of python or as a numpy array and storing it?


code:
def stanza(fle):
    with open(fle) as f:
        vals = ("iface", "mapping", "auto", "allow-", "source")
        tmp = []
        for line in f:
            if line.startswith(vals):
                yield tmp
                tmp = [line]
            else:
                tmp.append(line)
    if tmp:
        yield tmp

from pprint import pprint as pp
pp(list(stanza("foo.txt")))

rawDescription: How to split /etc/network/interfaces using a regex in Python

description: Split /etc/network/interfaces using a regex in Python


code:
class Node(object):
    def __init__(self, node_id, neighbours, status):
        # neighbours could be a list of other Node objects
        self.node_id = node_id
        self.neighbours = neighbours
        self.status = status

    def neighbours_status(self):
        # this method would return a list of tuples,
        # where first tuple elem is node_id and the second is its status
        return [(n.node_id, n.status) for n in self.neighbours]

rawDescription: Iterating over 3 dictionaries (focus on speed)


rawDescription: How to encode a long string of hex values in unicode easily in python

description: Encode a long string of hex values in unicode easily in python


code:
a = df.head(1)
b = HTML("
Hello
")
c = df.head(2)

for i in [a,b,fig1,c,fig2]:
    display(i)

rawDescription: Combining Jupyter rich display and matplotlib charts


code: list(leaves(g))

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


code: len(rprim)

rawDescription: Python auto define variables

description: Python auto define variables


code:
# get hostnames as list
with open('/path/to/hostname_file.txt', 'r') as hosts:
    hostnames = [line.strip() for line in hosts.readlines()]

# read config
with open('/path/to/fw/config.txt', 'r') as fw_config:
    # file where matches are written
    with open('/path/to/matches.txt', 'w+') as match:
        # check config
        for line in fw_config:
            if any(name in line for name in hostnames):
                # write match to file
                match.write(line)

rawDescription: Comparing a list in a text file to a second large text file and printing the matches.


rawDescription: How to use malloc and free with python ctypes?

description: Use malloc and free with python ctypes


code: m.title = coalesce(exif.get('Xmp.dc.subject'), exif.get('Xmp.dc.title'), original_filename_noextension)

rawDescription: Efficiently select the best string from keys in a dict


code:
def handler():
    f = open("backup", "w")
    f.write(app_entry.get())
    f.close()
    app_win.quit()

rawDescription: Using entry box data from previous session Tkinter


code:
df2['key1'] = df2.groupby(level='product_name')['val'].transform('sum')
df2['key2'] = df2.index.get_level_values('usage_type')

rawDescription: Pandas sorting by group aggregate

description: Pandas sorting by group aggregate


rawDescription: What is the correct way to reassign a list in Python?


code:
import numpy as np
data = np.arange(1, 7)
groups = np.array([0,0,1,2,2,1])

unique_groups = np.unique(groups)

# Forgive the bad naming here...
# I can't think of more descriptive variable names at the moment...
x, y = np.meshgrid(groups, unique_groups)
data_stack = np.tile(data, (unique_groups.size, 1))

data_in_group = np.zeros_like(data_stack)
data_in_group[x==y] = data_stack[x==y]

sums = data_in_group.sum(axis=1)

rawDescription: Sum array by number in numpy

description: Sum array by number in numpy


rawDescription: Django: how to handle data that doesn't fit in a model


rawDescription: How to use wx.python demos code

description: Use wx.python demos code


code: np.ma.array((a, b, c)).mean(axis=0)

rawDescription: Averaging multiple masked numpy arrays in python


code:
#in mysite/categories/models.py
class Category(models.Model):
    ...

#in mysite/posts/models.py
class Post(models.Model):
    category = models.ForeignKey('categories.Category')

rawDescription: Two-way querying in Django without circular reference


code:
str_list = strIn.split(',')
type_ = str_list[0]
vals = [float(v) for v in str_list[1:]]

rawDescription: Python string get leading characters up to first comma


code:
# Allocate empty array.
bigarray = numpy.empty([width, height, len(filenames)]);
# Load files.
for i in range(len(filenames)):
    bigarray[:,:,i] = numpy.load(filenames[i]);

rawDescription: Import array files with numpy

description: Import array files with numpy


code:
layer_list = []
for rows in range(1, layerSheet.get_highest_row()+1):
    layerObject = Layer(rows)
    print(layerObject.layerContainer())
    layer_list.append(layerObject)

rawDescription: Saving instances when created by an iterator - Python


code:
def add_these_numbers(*args):
    return args[0] + args[1]

def add_these_numbers_too(**kwargs):
    return kwargs['first_number'] + kwargs['second_number']

rawDescription: What is a self-written decorator (like @login_required) actually doing?


rawDescription: reversed() vs. xrange()

description: Reversed() vs. xrange()


code: Something(somedict)

rawDescription: Iteritems return formatted strings

description: Iteritems return formatted strings


code: cursor = conn.cursor(OrderedDictCursor)

rawDescription: PyMySQL and OrderedDict

description: PyMySQL and OrderedDict


code:
import csv
writer = csv.writer(open("some.csv", "wb"))
writer.writerow(the_list)

rawDescription: How can I join a list into a string (caveat)?

description: Join a list into a string (caveat)


code:
class Listing(models.Model):
    def uppercase_listing(self):
       return self.listing.upper()

rawDescription: How to write Python Code in Django

description: Write Python Code in Django


code:
S_p = np.asarray([make_spot_3d_spherical(1000,2, 30,0,phi) for phi in np.linspace(0, 2*np.pi, 20)])
set_of_Sp0 = np.sum(np.sum(S_p, axis =0), axis = 0)
plt.imshow(set_of_Sp0, interpolation = 'nearest')

rawDescription: How to rotate a 3D spot with numpy?

description: Rotate a 3D spot with numpy


rawDescription: PyCharm. Regular expression to replace all script src attributes


rawDescription: Retrieve an existing instance in Python

description: Retrieve an existing instance in Python


code:
import re
p = re.compile(r'( of (?:(?!\band\b)[A-Za-z ])+)?')
s = " of New Mexico and Mrs Smith."
m = p.search(s)
if m:
    print(m.group().strip())

rawDescription: Python RegEx Stop before a Word

description: Python RegEx Stop before a Word


code:
self.mainSocket = SocketIO('localhost', 80)
self.gazeSocket = self.mainSocket.connect('/gaze')
self.gazeSocket.emit('gaze', ...)

rawDescription: Code in Python, communicate in Node.js and Socket.IO, present in HTML


code:
ops = {
    'conjunction': lambda a, b: a & b,
    'disjunction': lambda a, b: a | b,
    # ... etc.
}
def boolean(a, b, operation):
    return ops[operation](a, b)

rawDescription: Python operations

description: Python operations


code:
def calc_iso_surface(my_array, my_value, zs, interp_order=6, power_parameter=0.5):
    if interp_order < 1: interp_order = 1
    from numpy import argsort, take, clip, zeros
    dist = (my_array - my_value)**2
    arg = argsort(dist,axis=2)
    dist.sort(axis=2)
    w_total = 0.
    z = zeros(my_array.shape[:2], dtype=float)
    for i in xrange(int(interp_order)):
        zi = take(zs, arg[:,:,i])
        valuei = dist[:,:,i]
        wi = 1/valuei
        clip(wi, 0, 1.e6, out=wi) # avoiding overflows
        w_total += wi**power_parameter
        z += zi*wi**power_parameter
    z /= w_total
    return z

rawDescription: Using numpy/scipy to calculate iso-surface from 3D array


code:
import numpy as np
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt

# initialize the three axis:
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(left=0.25)

par1 = host.twinx()
par2 = host.twinx()

# secify the offset for the left-most axis:
offset = -60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="left", axes=par2, offset=(offset, 0))
par2.axis["right"].toggle(all=True)

# data ratio for the two left y-axis:
y3_to_y1 = 1/7.5

# y-axis limits:
YLIM = [0.0, 150.0,
        0.0, 150.0]

# set up dummy data
x = np.linspace(0,70.0,70.0)
y1 = np.asarray([xi**2.0*0.032653 for xi in x])
y2 = np.asarray([xi**2.0*0.02857 for xi in x])

# plot data on y1 and y2, respectively:
host.plot(x,y1,'b')
par1.plot(x,y2,'r')

# specify the axis limits:
host.set_xlim(0.0,70.0)
host.set_ylim(YLIM[0],YLIM[1])
par1.set_ylim(YLIM[2],YLIM[3])

# when specifying the limits for the left-most y-axis
# you utilize the conversion factor:
par2.set_ylim(YLIM[2]*y3_to_y1,YLIM[3]*y3_to_y1)

# set y-ticks, use np.arange for defined deltas
# add a small increment to the last ylim value
# to ensure that the last value will be a tick
host.set_yticks(np.arange(YLIM[0],YLIM[1]+0.001,10.0))
par1.set_yticks(np.arange(YLIM[2],YLIM[3]+0.001,10.0))
par2.set_yticks(np.arange(YLIM[2]*y3_to_y1,YLIM[3]*y3_to_y1+0.001, 2.0))

plt.show()

rawDescription: Multiple y-axis conversion scales

description: Multiple y-axis conversion scales


code:
el1 = ''
el2 = ''
list1 = []
list2 = []
while el1 != "exit":
    el1 = input("Insert the words of the first list: ")
    print("write exit to finish")
    list1.append(el1)
while el2 != "exit":
    el2 = input("Insert the words of the second list: ")
    print("write exit to finish")
    list2.append(el2)

if len(list(set(list2)-set(list1)))==len(list2):
    print("List 1 is a sublist of List 2")
else:
    print("List 1 is not a sublist of List 2")

rawDescription: check if the first list is a sublist of the second one python

description: Check if the first list is a sublist of the second one python


rawDescription: pandas, how to filter dataframe by column value

description: Pandas, how to filter dataframe by column value


code:
for i in range(len(name)):
    print("{0:<20}{1:<20}{2:<20}".format(name[i],sport[i],age[i]))

rawDescription: How do I display tuples in columns? [Python]

description: Display tuples in columns? [Python]


rawDescription: Typed JSON serialization/deserialization in Python


code:
def apply_tag(text_widget,phrase,tag,regexp=False):
    countVar = tk.IntVar(text_widge)
    idx = "1.0"
    while idx:
        idx = text_widget.search(phrase,idx, stopindex = "end",
                                 count = countVar, regexp = regexp)
        if idx:
            end_idx = "%s + %sc" %(idx, countVar.get())
            text_widget.tag_add(tag, idx, end_idx)
            idx = end_idx

rawDescription: Converting a string automatically into a link to a pdf document


code:
import cv2
import numpy as np

knight = cv2.imread('knight.jpg', cv2.IMREAD_GRAYSCALE)

rawDescription: How to best create a new image out of existing images in openCV

description: Best create a new image out of existing images in openCV


code:
with open("out.csv", "w") as f:
    wr = csv.writer(f)
    wr.writerow(headers)
    wr.writerows(zipped)

rawDescription: Turn Python list from CSV with multi-value fields into a Python nested list, sort nested list values and export to CSV


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

Xtrain = np.random.randn(100, 50)

pca = PCA(n_components=30)
pca.fit(Xtrain)

U, S, VT = np.linalg.svd(Xtrain - Xtrain.mean(0))

assert_array_almost_equal(VT[:30], pca.components_)

rawDescription: PCA projecting and reconstruction in Scikit


code:
text = '''GET /x.css HTTP/1.1
Host: 192.168.2.12
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/css,*/*;q=0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36
Referer: http://192.168.2.12/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4'''

dic = {}
for line in text.splitlines():
    if ': ' in line:
        key, val = line.split(': ')
        dic[key] = val
    else:
        arr = line.split(' ')
        dic[arr[0]] = ' '.join(arr[1:])

rawDescription: How to convert string to dictionary or some sort (from websocket client)

description: Convert string to dictionary or some sort (from websocket client)


code:
tiger1 = Animals('tiger')
tiger2 = Animals('tiger')
tiger2 is tiger1

rawDescription: Two constructors in a Python Class

description: Two constructors in a Python Class


code:
import pygame, sys
from pygame.locals import *

FPS = 60
fpsClock = pygame.time.Clock()

def main():
    pygame.init()

    DS = pygame.display.set_mode((400, 400), 0, 32)
    pygame.display.set_caption('Drag-n-drop that cat')

    catImg = pygame.image.load('cat.png').convert_alpha()
    catMask = pygame.mask.from_surface(catImg)
    catImgRectObj = catImg.get_rect(center=(200, 200))
    IsMousePressed = False

    while True:

        DS.fill(pygame.color.THECOLORS['white'])
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEBUTTONDOWN and isMouseOverObj(catMask, catImgRectObj):
                IsMousePressed = True
            elif event.type == MOUSEBUTTONUP:
                IsMousePressed = False
            elif event.type == MOUSEMOTION and IsMousePressed:
                catImgRectObj.move_ip(event.rel)

        DS.blit(catImg, catImgRectObj)
        pygame.display.update()
        fpsClock.tick(FPS)

def isMouseOverObj(mask, rect):
    mouse_pos = pygame.mouse.get_pos()
    rel_pos = (mouse_pos[0] - rect.left, mouse_pos[1] - rect.top)
    return rect.collidepoint(mouse_pos) and mask.get_at(rel_pos)

if __name__ == '__main__':
    main()

rawDescription: get_rect() over an image gets shifted in pygame

description: Get_rect() over an image gets shifted in pygame


code:
byte = 0xFC
list_size = 8
[(byte & (1 << (list_size - 1 - k))) >> (list_size - 1 - k) for k in range(list_size)]

rawDescription: Searching a more elegant way for converting a byte to a list of bits


code:
keys_in_order_of_appearance = []
key_frequency = defaultdict(int)

for item in search_terms:
    subquery = SomeEntity.all(keys_only=True)
    subquery.filter('SearchIndex = ', item) #SearchIndex is a StringListProperty
    #more filters...
    subquery.order('-DateCreated')
    for returned_item in subquery:
        key = str(returned_item)
        if key not in key_frequency:
            key_order_of_appearance.append(key)
        key_frequency[key] += 1

keys = keys_in_order_of_appearance[:]   # order of appearance kept as secondary sort
keys.sort(key=key_frequency.__getitem__, reverse=True) # descending freq as primary sort
result = SomeEntity.get(ordered_key_list)

rawDescription: GAE text search with secondary sorting

description: GAE text search with secondary sorting


code:
filterdict = dict((k,i) for i,k in enumerate(filter))
sorted(b, key=lambda x: filterdict[x['id']])

rawDescription: Sorting a list of dicts in python, using another list as a "filter"?


code:
myList = ["a","b","c","d","e"]

myListEnumerated = enumerate(myList)

print(list(myListEnumerated))

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


code:
draw = plt.plot(data[:,0], data[:,range(1,4)], '--o')
plt.legend(draw, ('Col1', 'Col2', 'Col3'))
plt.xlabel("Build")
plt.show()

rawDescription: Use matplotlib to set the x-axis

description: Use matplotlib to set the x-axis


code: atb_mat = numpy.resize(atbvec, (dim, nb))

rawDescription: Python equivalent code to MATLABs vec2mat


code: new_urls = [urllib.quote(url) for url in urls]

rawDescription: How do I create a list of files stored in my Amazon S3 bucket and display them as download links?

description: Create a list of files stored in my Amazon S3 bucket and display them as download links


code: x = x.reshape(-1, 2)

rawDescription: Repeating numpy values and specifying dtype


code:
class Page(models.Model):
     title = models.CharField(max_length=80)
     stuff = GenericRelation('app_name_model_here')

rawDescription: Creating a Serialiser for a Reverse Generic Relationship


code:
df_m = pd.melt(df, id_vars="y")
df_m.pivot_table(index="variable", columns="y")

rawDescription: What is the effective way to have a pivot-table having pandas dataset columns as its rows?


code: f = os.path.join(path, name)

rawDescription: python grep reverse matching

description: Python grep reverse matching


code:
c = C()
c.__dict__
c.__dict__.keys()

rawDescription: Python dict.keys to list results in duplicates


code:
from PyQt4 import QtGui, QtCore
from btngroup_ui import Ui_ButtonGroup

class Window(QtGui.QWidget, Ui_ButtonGroup):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.buttonGroup = QtGui.QButtonGroup(self)
        for button in self.buttonBox.findChildren(QtGui.QAbstractButton):
            self.buttonGroup.addButton(button)
        self.buttonGroup.buttonClicked.connect(self.handleButtonClicked)

    def handleButtonClicked(self, button):
        print('"%s" was clicked' % button.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

rawDescription: Single button event handler for buttons

description: Single button event handler for buttons


code:
sample = """
{
 stage = 3;
 some.param1 = [10,20];
}
{
 stage = 4;
 param3 = [100,150,200,250,300];
}
 endparam = [0,1];
 """

parsed = tree.parseString(sample)
parsed.pprint()

rawDescription: Convert BNF grammar to pyparsing

description: Convert BNF grammar to pyparsing


code:
def count(A, MIN_OBS):
    temp_dict = collections.Counter()
    for k, v in A.iteritems():
        temp_list = v.split(',')
        for item in temp_list:
            temp_dict[item] += 1
    temp_dict = {k:v for k, v in temp_dict.items() if v > MIN_OBS}
    return temp_dict

rawDescription: Transform pandas Series with variable length comma separated values to Dataframe


code:
from pyspark.mllib.stat import Statistics
from pyspark.mllib.linalg import Vectors

tf_col = "x"
dataset = sc.parallelize([
    "(262144,[3738,3739,3740,3741],[0.25,0.50,0.75,1.0])",
    "(262144,[3738,3739,3740,3741],[0.25,0.50,0.75,1.0])"
]).map(lambda s: (Vectors.parse(s), )).toDF(["x"])

vs = (dataset.select(tf_col)
    .flatMap(lambda x: x)
    .map(lambda v: Vectors.sparse(v.size, v.indices, [1.0 for _ in v.values])))

stats = Statistics.colStats(vs)

document_frequency = stats.mean()
document_frequency.max()
## 1.0
document_frequency.min()
# 0.0
document_frequency.nonzero()
## (array([3738, 3739, 3740, 3741]),)

rawDescription: Create a Python transformer on sparsevector data type column in Pyspark ML


code:
fx = Contract()
fx.m_secType = "CASH"
fx.m_symbol = "USD"
fx.m_currency = "CAD"
fx.m_exchange = "IDEALPRO"
#tws.reqMktData(1,fx,"",False)

ord = Order()
ord.m_orderType = 'MKT'
ord.m_totalQuantity = 100000
ord.m_action = 'SELL'
tws.placeOrder(123,fx,ord) #increment this every order

rawDescription: How to get the trading price and commission in Interactive Brokers (IBPY) after placing an order?

description: Get the trading price and commission in Interactive Brokers (IBPY) after placing an order


rawDescription: Python Tkinter attribute error entry in random letter typing test


code: re.split(r'\s+(?:AND|OR)\s+', 'Romeo Or Juliet', flags=re.I)

rawDescription: Recognize the words "AND" and "OR" into a string


code:
from decimal import *

from math import sqrt

getcontext().prec = 102

def digitalsum(n):
    sum = 0
    for a in n:
        sum += int(a)
    return sum

total = 0

for a in range(100):
    if not sqrt(a) % 1 == 0:
        ans = str(Decimal(a).sqrt()).replace('.', '')[:100]
        print(a)
        print(digitalsum(ans))
        print("-------")

rawDescription: Correctly compute square root digital expansions


code:
class Point:
  def __init__(self, x, y):
    self.x, self.y = x, y

  def __str__(self):
    return "{}, {}".format(self.x, self.y)

  def __neg__(self):
    return Point(-self.x, -self.y)

  def __add__(self, point):
    return Point(self.x+point.x, self.y+point.y)

  def __sub__(self, point):
    return self + -point

rawDescription: How can I manipulate cartesian coordinates in Python?

description: Manipulate cartesian coordinates in Python


code: sorted(Author.objects.all(), key=lambda a: a.full_name)

rawDescription: Using a Django custom model method property in order_by()


rawDescription: Changing number representation in IDLE

description: Changing number representation in IDLE


rawDescription: call a Frame2 from a button in Frame1

description: Call a Frame2 from a button in Frame1


code:
table_name_list = tables_df.table_name

select_template = 'SELECT * FROM {table_name}'
frames_dict = {}
for tname in table_name_list:
    query = select_template.format(table_name = tname)
    frames_dict[tname] = pd.read_sql(query, conn)

rawDescription: Importing multiple SQL tables using pandas


code:
my_colors = ['g', 'b']*5 # <-- this concatenates the list to itself 5 times.
my_colors = [(0.5,0.4,0.5), (0.75, 0.75, 0.25)]*5 # <-- make two custom RGBs and repeat/alternate them over all the bar elements.
my_colors = [(x/10.0, x/20.0, 0.75) for x in range(len(df))] # <-- Quick gradient example along the Red/Green dimensions.

rawDescription: How to give a pandas/matplotlib bar graph custom colors

description: Give a pandas/matplotlib bar graph custom colors


code:
options = [
    {
        'name': 'Option 1',
        'plan': {1: True,},
    },
    {
        'name': 'Option 2',
        'plan': {2: True,},
    },
    {
        'name': 'Option 3',
        'plan': {2: True, 3: True,},
    },
]

rawDescription: Django - Template bitmask check

description: Django - Template bitmask check


code: config = [line.split(',') for line in open("config")]

rawDescription: Python: Best way to dynamically instantiate Player class in a loop?


code:
import os

class Counter:
    def __init__(self):
        print('init')
        self.value = 0

    def increment(self):
        self.value += 1
        print('inc -> {}'.format(self.value))

counter = Counter()

def multi():
    if not os.fork():
        # child starts with copy of parent memory
        for _ in range(3):
            # increments three times
            counter.increment()

        # child is done
        os._exit(0)

# three processes run
for _ in range(3):
    multi()

rawDescription: Werkzeug and class state with Flask: How are class member variables resetting when the class isn't being reinitialized?


code:
cols = ['X', 'Y']
df[cols] = df[cols].ffill()

rawDescription: forward fill specific columns in pandas dataframe

description: Forward fill specific columns in pandas dataframe


rawDescription: Creating a gradebook with the pandas module


code:
soup = BeautifulSoup(html)
anchors = soup.find_all('a', {'class': 'Unique_Class_Name', 'href': True})

for anchor in anchors:
    print (anchor['href'])

rawDescription: Get the href text of a link that has a certain class attribute using BeautifulSoup in Python


code:
def expire():
    del cache[:]
    cache.append(None)

rawDescription: Get attribute of a property in python

description: Get attribute of a property in python


rawDescription: os.chdir() is not working in mac

description: Os.chdir() is not working in mac


rawDescription: Passing textfile and Creating new Tuple when there is space


code: map(min, zip(*data))

rawDescription: Best way to find minimum x and y values in a list of pairs in python?

description: Find minimum x and y values in a list of pairs in python


code: b = {a[i]: a[i+1] for i in range(0, len(a), 2)}

rawDescription: Convert a list to a dictionary in Python


code:
py25-libgmail
py26-icalendar
py26-vobject
py27-appscript
py27-asciitable
py27-beautifulsoup
py27-beautifulsoup4
py27-blist
py27-bpython
py27-chm
py27-configobj
py27-dateutil
py27-epydoc
py27-game
py27-gdal
py27-gtk
py27-ipython
py27-lxml
py27-matplotlib
py27-mechanize
py27-mysql
py27-numpy
py27-pdfminer
py27-pil
py27-prettytable
py27-progressbar
py27-psutil
py27-py2app
py27-pylint
py27-pyobjc
py27-pyobjc-cocoa
py27-pypdf
py27-pyqt4
py27-simplejson
py27-sphinx
py27-sqlalchemy
py27-sqlite
py27-termcolor
py27-tkinter
py27-tz
py27-wxpython
py31-appscript
py31-asciitable
py31-beautifulsoup4
py31-blist
py31-bpython
py31-game
py31-lxml
py31-psutil
py32-asciitable
py32-beautifulsoup4
py32-blist
py32-bpython
py32-game
py32-ipython
py32-lxml
py32-psutil

rawDescription: Python filtering: only keep most recent python MacPort


code:
find_price = lambda x: {k:v for (k,v) in inventory.iteritems() if v[1] == x}
price_match = find_price(19)

rawDescription: modifying list element in Python dictionary

description: Modifying list element in Python dictionary


code:
class DetailBuildView(SingleTableView):
    template_name = 'shoppinglist/detailbuild.html'
    table_class = BuildLineTable
    table_pagination = False

rawDescription: How do I control pagination using a class-based view in django-tables2?

description: Control pagination using a class-based view in django-tables2


code:
import itertools as it

varNames = sorted(variants)
combinations = [dict(zip(varNames, prod)) for prod in it.product(*(variants[varName] for varName in varNames))]

rawDescription: Combinations from dictionary with list values using Python


code: 'builtins'

rawDescription: IPython Notebook doesn't show full namespace


code:
pkg_name = 'byobu'
cache = apt.cache.Cache()
package = cache[pkg_name]
version = apt.apt_pkg.Cache()[pkg_name].version_list[1]
candidate = apt.package.Version(package, version)
package.candidate = candidate
package.mark_install()
cache.commit()

rawDescription: Python-apt: install package with specific version


code:
async def main():
    import threading
    e = Event_ts()
    threading.Thread(target=threaded, args=(e,)).start()
    while True:
        await e.wait()
        e.clear()
        print('whatever')

rawDescription: asyncio: Wait for event from other thread

description: Asyncio: Wait for event from other thread


code:
import string
p_regex = re.compile('[%s]' % re.escape(string.punctuation))
outtext2 = p_regex.sub('', outtxt)

rawDescription: Stanford Word Segmenter for Chinese in Python how to return results without punctuation


code:
m = MagicMock()
d = {"a":"A", "b":"B", "c":"C"}
m.keys.return_value.__iter__.return_value = ["a", "b", "c"]
m.__getitem__.side_effect = ["A","B","C"]
dict(m)
#Little bit generic
m.keys.return_value.__iter__.return_value = d.keys()
m.__getitem__.side_effect = lambda k:d[k]
dict(m)

rawDescription: calling python builtin dict on a mock

description: Calling python builtin dict on a mock


code:
size = (3, 5)

def method1():
    np.random.seed(123)
    return np.random.normal(0, 1, size)

def method2():
    np.random.seed(123)
    x = np.zeros(size, dtype=float)
    for i  in range(size[1]):
        x[:,i] = np.random.normal(0, 1, size[0])
    return x

rawDescription: numpy random usage validity

description: Numpy random usage validity


code:
def create_image():
    """ dummy code that generates an image, simulating some actual code """
    im = Image.new('RGB', (100, 100), (0, 0, 0))
    draw = ImageDraw.Draw(im)
    draw.ellipse((10, 10, 90, 90), outline=(0, 0, 255),
                 fill=(255, 255, 255))
    return im

def test_generated_image(image_diff):
    im = create_image()
    image_diff.check(im)

rawDescription: Carrying out unit testing in python on a method that implements ImageDraw


code: os.chdir('/home/' + y + '/newdir/')

rawDescription: How can I download a file to a specific directory?

description: Download a file to a specific directory


code:
langs = [lang.iso639_1_code
         for lang in pycountry.languages
         if hasattr(lang, 'iso639_1_code')]

rawDescription: List of language codes (ISO639-1) in Python?


code:
df1a,df2a = df1.align(df2)
df1a.ffill().fillna(0) + df2a.fillna(0)

rawDescription: Pandas adding two Multiindex Dataframes

description: Pandas adding two Multiindex Dataframes


rawDescription: Transfer matrix elements to another matrix's diagonal


code:
def setUp(self):
    self.to_be_removed = []

rawDescription: Unittest tearDown() method depends on finished test


rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


code:
from io import StringIO
import pandas as pd
data = StringIO(u"""
121301234
121300123
121300012
""")

pd.read_fwf(data, colspecs=[(0,3),(4,8)], converters = {1: str})

rawDescription: python read_fwf error: 'dtype is not supported with python-fwf parser'

description: Python read_fwf error: 'dtype is not supported with python-fwf parser'


code:
import atexit
import os

ip = get_ipython()
LIMIT = 1000 # limit the size of the history

def save_history():
    """save the IPython history to a plaintext file"""
    histfile = os.path.join(ip.profile_dir.location, "history.txt")
    print("Saving plaintext history to %s" % histfile)
    lines = []
    # get previous lines
    # this is only necessary because we truncate the history,
    # otherwise we chould just open with mode='a'
    if os.path.exists(histfile):
        with open(histfile, 'r') as f:
            lines = f.readlines()

    # add any new lines from this session
    lines.extend(record[2] + '\n' for record in ip.history_manager.get_range())

    with open(histfile, 'w') as f:
        # limit to LIMIT entries
        f.writelines(lines[-LIMIT:])

# do the save at exit
atexit.register(save_history)

rawDescription: How to log IPython history to text file?

description: Log IPython history to text file


code:
class Message(models.Model):
    text = models.CharField(max_length=200)
    date_send = models.DateTimeField(auto_now_add=True,editable=False)
    emeteur = models.ForeignKey(User,null=True,related_name="+")

    class Meta :
        abstract = True
        ordering = ['date_send'] # default ordrer while fetching data

rawDescription: Django : get the last item of manytomanyfield


rawDescription: String.replace() Python remove first coincidence


code:
import regex

common = r"""(?(DEFINE)
             (?<VALID_NAME>\b[_a-zA-Z][_a-zA-Z0-9]*)
             (?<SOMETHING_ELSE>[-+/*])
         )"""

pattern = regex.compile(common + r"((?&VALID_NAME)\.)*(?&VALID_NAME)")

result = pattern.search("42hello! foo.bar.baz")

print(result[0])

rawDescription: Build regular expressions using previously compiled regular expressions


code:
s = [sum(i) for i in b]
l = [sum(v != 0 for v in i) for i in a]
result = [[0 if not v else v + (float(sumb) / count) for v in i]
          for i, sumb, count in zip(a, s, l)]

rawDescription: Sum and length of lists of list

description: Sum and length of lists of list


code:
from kivy.properties import ListProperty
class ColourLabel(Label):
    ellipse_colour = ListProperty([1, 0, 0, 1])

rawDescription: kivy: press button -> change color of a label

description: Kivy: press button -> change color of a label


code:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
            'builtins': [
                'django.contrib.staticfiles.templatetags.staticfiles',
            ],
        },
    },
]

rawDescription: Load static files for all templates in django


rawDescription: List of numbers

description: List of numbers


code:
from collections import namedtuple

Point = namedtuple('Point', 'x y z')

class Parcel(object):
   def __init__(self, *points):
       self.points = points

   def get_area(self):
       pass

   def get_perimeter(self):
       pass

   def get_mean_elevation(self):
       pass

p1 = Point(0, 0, 10)
p2 = Point(1, 1, 20)
p3 = Point(2, 0, 15)

p = Parcel(p1, p2, p3)

rawDescription: Classes in python, get attribute

description: Classes in python, get attribute


rawDescription: Python. BigData. Need to extract Web-Browser and OS users' preferences from cells. Best-performance method?


code:
import time
from selenium import webdriver

driver = webdriver.Chrome() # or webdriver.Firefox()
driver.set_window_size(1120, 550)
driver.get("http://www.csgodouble.com/index.php")
driver.add_cookie({'name': 'PHPSESSID', 'value': 'abcd2efg3hijk62lmn1op'})
print(driver.get_cookie('PHPSESSID'))
driver.get("http://www.csgodouble.com/index.php")

time.sleep(3)

rolls = driver.find_element_by_id('past').text
print('Rolls: ', rolls)

rawDescription: Python and Selenium - PHPSESSID cookie is logging me in


code:
self.some_long_attribute_name = {
    'someLongKeyName': 'someLongValueName',
    'anotherLongKeyName': 'anotherLongValueName'
}

rawDescription: I know I'm supposed to keep Python code to 79 cols, but how do I indent continuations of lines?


code:
response = response.replace(body=response.body.replace('<br />', '\n'))
hxs = HtmlXPathSelector(response)

rawDescription: Preserving line breaks when parsing with Scrapy in Python


code:
# script1.py
import pandas as pd
import numpy as np
import time
import fcntl

df = pd.DataFrame.from_dict({"script_id": [0], "val1": [0], "val2": [0]})
df.to_pickle("data.pkl")

for i in range(500):
    with open("lock.lck", "r") as f_lock:
        fcntl.flock(f_lock, fcntl.LOCK_EX)
        time.sleep(np.random.uniform(0, 0.05))

        df = pd.read_pickle("data.pkl")
        df.loc[i, :] = np.concatenate([np.array([1]), np.random.sample(2)])
        df.to_pickle("data.pkl")

rawDescription: fcntl file lock example not working

description: Fcntl file lock example not working


code:
from django.conf import setings
class Link(models.Model):
    link_model = models.ForeignKey(settings.LINK_MODEL)

rawDescription: How to Model a Foreign Key in a Reusable Django App?


code:
f = Foo(some_argument="I am a customized int", value=10)
f
f + 8
f * 0.25
f.print_some_argument()

rawDescription: Python Class with integer emulation

description: Python Class with integer emulation


code:
def subfunc(row,col_reference=None,col_target=None):
    if not row[col_reference] in ['Y','W','1','E']:
        row[col_target] = 0
    return row

rawDescription: Replacing item values in a data frame on certain condition in other columns


rawDescription: How to call a data member of the base class if it is being overwritten as a property in the derived class?

description: Call a data member of the base class if it is being overwritten as a property in the derived class


code:
from itertools import product

def reorder_product(*a):
    for tup in product(*a[::-1]):
        yield tup[::-1]

rawDescription: How to sort itertools.product in Python?

description: Sort itertools.product in Python


code:
from csv import reader
d = dict(row for row in reader(open('/path/to/my/file'), delimiter=',', quotechar='"'))
print(d['a'])
# Cheif manager

rawDescription: How do I read data from a file using Python?

description: Read data from a file using Python


code:
from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from twisted.protocols.basic import LineReceiver

import pygame

class ChatClientProtocol(LineReceiver):

    def __init__(self, recv):
        self.recv = recv

    def lineReceived(self,line):
        self.recv(line)

class ChatClient(ClientFactory):
    def __init__(self, recv):
        self.protocol = ChatClientProtocol
        self.recv = recv

    def buildProtocol(self, addr):
        return ChatClientProtocol(self.recv)

class Client(object):

    def __init__(self):
        self.line = 'no message'
        pygame.init()
        self.screen = pygame.display.set_mode((200, 200))
        reactor.callLater(0.1, self.tick)

    def new_line(self, line):
        self.line = line

    def tick(self):
        self.screen.fill((0,0,0))
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                reactor.stop() # just stop somehow
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                reactor.stop() # just stop somehow
        self.screen.blit(pygame.font.SysFont('mono', 12, bold=True).render(self.line, True, (0, 255, 0)), (20,20))
        pygame.display.flip()
        reactor.callLater(0.1, self.tick)

if __name__ == '__main__':
    c = Client()
    reactor.connectTCP('127.0.0.1',6000, ChatClient(c.new_line))
    reactor.run()

rawDescription: Twisted clients within pygame mainloop?

description: Twisted clients within pygame mainloop


code:
df
df[df_sorted[(pd.rolling_sum((df_sorted==0), window=2) == 2)].first_valid_index()+1:]

rawDescription: Pandas: complex filtering with apply

description: Pandas: complex filtering with apply


rawDescription: How can I automatically run all the functions in the module?

description: Automatically run all the functions in the module


code: pipe(range(4), map(lambda i: repeat(i, i + 1)), concat, list)

rawDescription: Extracting a dictionary from an RDD in Pyspark


code:
#Add count row to the groups
def addcount(x):
    x['COUNTS'] = range(1,x.COMM_ID.count()+1)
    return x

rawDescription: How to bin groupeby counts in pandas?

description: Bin groupeby counts in pandas


rawDescription: Add two 3D numpy arrays with a 2D mask

description: Add two 3D numpy arrays with a 2D mask


rawDescription: How to assign one value to the entire (or partial) list in Python?

description: Assign one value to the entire (or partial) list in Python


rawDescription: IPython and __doc__

description: IPython and __doc__


code: sorting = check_output(["sort", field, output, append, new_path])

rawDescription: How to store output from linux call in Python

description: Store output from linux call in Python


code: dict((k, v) for k, v in hand.iteritems() if v)

rawDescription: Removing entries from a dictionary based on values


code:
import lxml.html

html = '''
    Keep all of this
But remove this including the tags
 this is still good, but

there also might be new lines like this that need to be removed

 and even other lines like this all the way down here with whitespace after being  parsed from email that need to be removed.

    But this is still okay.
'''

root = lxml.html.fromstring('
' + html + '
')
text = ' '.join(t.strip() for t in root.xpath('text()') if t.strip())

rawDescription: Strip all html lines/code from string in python


code:
def parseRange (expr):
    if not expr or not re.match('^\d*-?\d*$', expr):
        raise ValueError('Not a correct range')

    # single number
    if '-' not in expr:
        return int(expr), int(expr)
    else:
        begin, end = expr.split('-')
        begin = float('-inf') if begin == '' else int(begin)
        end = float('inf') if end == '' else int(end)
        return begin, end

rawDescription: Python regular expressions: match a range of numbers with a separator


code:
def start_game(event):
    global lost, count, ball #added ball here
    if lost == True: # added this if
        ball = Ball(canvas, paddle, "red")

    lost = False #and finally changed the lost var BEFORE drawing the paddle which has a check of lost var in order to move.
    paddle.draw()
    ball.draw()
    count = 0

    score()
    canvas.itemconfig(game, text=" ")

    time.sleep(1)

rawDescription: Python Tkinter bounce ball game restart

description: Python Tkinter bounce ball game restart


code:
for x in wordlist:
    " ".join(x)

rawDescription: Trying to convert a list of tuples to a list of lists


code: df.loc[df[filt.keys()].apply(lambda x: x.tolist() == filt.values(), axis=1), req]

rawDescription: Pandas Multi-Colum Boolean Indexing/Selection with Dict Generator


code:
N = 5000

# Sparse matrices
A = make_csr(10*10, N)     # ~100 non-zero
B = make_csr(100*100, N)   # ~10000 non-zero
C = make_csr(1000*1000, N) # ~1000000 non-zero
D = make_csr(5000*5000, N) # ~25000000 non-zero
E = csr_matrix(np.random.randn(N,N), dtype=np.float32) # non-sparse

# Numpy dense arrays
An = A.todense()
Bn = B.todense()
Cn = C.todense()
Dn = D.todense()
En = E.todense()

b = np.random.randn(N)

rawDescription: Csr_matrix.dot vs. Numpy.dot

description: Csr_matrix.dot vs. Numpy.dot


code:
def method3(x):
    while x < 0.01:
        x *= 100
    while x < 0.1:
        x *= 10
    return x

rawDescription: Faster way to shift a decimal in Python to remove zeros?


code:
with open(filename) as f:
    text = f.read()

sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)

rawDescription: open file and read sentence

description: Open file and read sentence


code:
item_list = []
info = {} # <---- Move this to inside the loop.

for row in rows:
    itemId = row[0]
    itemDesc = row[10]

rawDescription: Python Append List Repeats Last Element?

description: Python Append List Repeats Last Element


code:
validate_type(3.4, float)
Out[1]: True

rawDescription: Python: type checking of complex returned values


rawDescription: Celery Logging: consistent way to log inside and outside of a task


rawDescription: Are unittest attributes mutable in Python?


rawDescription: pygame circle not changing

description: Pygame circle not changing


code:
class my_void_p(c_void_p):
    pass

gtlib.gt_gff3_out_stream_new.restype = my_void_p

class GFF3OutStream(GenomeStream):
    def __init__(self, genome_stream):
        self.gs = gtlib.gt_gff3_out_stream_new(genome_stream, None)
        self._as_parameter_ = self.gs # my_void_p instance

rawDescription: Issues with Python ctypes '_as_parameter_' and 'from_param' on OS X


code: return JsonResponse({'message': 'a string', 'val': val})

rawDescription: How to return both string and value within HttpResponse?

description: Return both string and value within HttpResponse


code:
path = collections.deque()
trail = collections.deque()
parents = {} # New line

rawDescription: Made Breadth First Search algorithm in Python. Don't know how to return solution


code:
import pandas as pd
from datetime import timedelta

df = pd.read_csv("hourmelt.csv", sep=r"\s+")

df = pd.melt(df, id_vars=["Date"])
df = df.rename(columns={'variable': 'hour'})
df['hour'] = df['hour'].apply(lambda x: int(x.lstrip('h'))-1)

combined = df.apply(lambda x:
                    pd.to_datetime(x['Date'], dayfirst=True) +
                    timedelta(hours=int(x['hour'])), axis=1)

df['Date'] = combined
del df['hour']

df = df.sort("Date")

rawDescription: How to rearrange a python pandas dataframe?

description: Rearrange a python pandas dataframe


code: sorted_mails = sorted(mbox, key=extract_date)

rawDescription: python, reducing memory consumption and making this code more efficient?

description: Python, reducing memory consumption and making this code more efficient


code:
result = pd.concat([df, df['Data'].apply(json_to_series)], axis=1)
result

rawDescription: Pandas expand json field across records

description: Pandas expand json field across records


code: xyz.objects.extra(where=["col3 != CONCAT(col1, col2)"])

rawDescription: using sql concat() in django for concatenating two columns

description: Using sql concat() in django for concatenating two columns


code:
# I'm just guess what event types you have...
cancellation = TrackingEventType.objects.get(name='cancel')
Tracking.objects.filter(last_event__event_type=cancellation)

rawDescription: Django Admin filter by function / filter only by first object in reverse foreign key lookup


code:
from bs4 import BeautifulSoup
BeautifulSoup('<html><body><name>Fred</name><html><body>')
soup = BeautifulSoup('<html><body><name>Fred</name><html><body>')
name = soup.find('name')
name

rawDescription: Replace text content of XML element in Python


code:
import re

name = re.search(' by (.+) to /r/books', s).group(1)

rawDescription: Removing a certain part of a string in python


code:
from project.config import configurations as c

def create_app(config=None):
  " make the app "
  app = Flask(__name__)
  app.config.from_object(c.get(config, None) or c['default'])

  configure_blueprints(app)

  return app

def configure_blueprints(app):
  " register the blueprints on your app "
  if app.testing:
    from project.test_bp import bp
    app.register_blueprint(bp)
  else:
    from project.not_test_bp import bp
    app.register_blueprint(bp)

rawDescription: Flask: are blueprints necessary for app factories?


code:
import importlib
coolmod = importlib.import_module('coolm', 'cool')

rawDescription: Dynamic Module Python

description: Dynamic Module Python


code: {'Country': '', ' Rate': '0.010', ' Name': 'UNITED STATES Inbound SMS - Other'}

rawDescription: Why does the parsing of csv file not break things into their 'logical' order?


code:
def my_insert(self, widget, report, text):

  report.insert_at_cursor(text)
  while gtk.events_pending():
    gtk.main_iteration()

rawDescription: gtk TextView widget doesn't update during function

description: Gtk TextView widget doesn't update during function


code:
import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write('a'*i)
    sys.stdout.flush()

rawDescription: Need to append output from the python script to the file


code:
from myapp.customer.models import Customer
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.contrib.admin.views.decorators import staff_member_required

def customerView(request):
    return render_to_response(
        "admin/customer/template.html",
        {'custom_context' : {}},
        RequestContext(request, {}),
    )
customerView = staff_member_required(customerView)

rawDescription: Include template form to django admin

description: Include template form to django admin


code:
df.loc[df['bin'] == val.index[0], 'new_bins'] = 'MOD'
df

rawDescription: python grouping similar categorical values

description: Python grouping similar categorical values


code:
from ctypes import *

class PowerClass(Structure):
    _fields_ = [('ACLineStatus', c_byte),
            ('BatteryFlag', c_byte),
            ('BatteryLifePercent', c_byte),
            ('Reserved1',c_byte),
            ('BatteryLifeTime',c_ulong),
            ('BatteryFullLifeTime',c_ulong)]

powerclass = PowerClass()
result = windll.kernel32.GetSystemPowerStatus(byref(powerclass))
print(powerclass.BatteryLifePercent)

rawDescription: Get battery status using wmi in python?

description: Get battery status using wmi in python


code:
try:
  from local_settings import *
except ImportError:
  pass

rawDescription: "real" global variables in Python for programwide settings


code:
class GroupMembers(models.Model):
    group = models.ForeignKey(Group)
    person = models.ForeignKey(Person, through='GroupMembers')

rawDescription: Getting the first item item in a many-to-many relation in Django


code:
yourcounter = itertools.count()

next_counted_value = yourcounter.next()

rawDescription: Suggestions to implement an automatic counter in Python


code:
L = [0, 0, 0, 0]
things_to_add = [0, 1, 1, 0]
for idx, amount in enumerate(things_to_add):
    L[idx] += amount

L

rawDescription: Add to integers in a list

description: Add to integers in a list


code:
def date2float(datestr):
    format = "%Y-%m-%d %H:%M:%S.%f"
    dateobj = datetime.datetime.strptime(datestr, format)
    dtfloat = mktime(dateobj.timetuple())
    dtfloat += dateobj.microsecond / 1000000.0
    return dtfloat

rawDescription: datetime to float not include milliseconds

description: Datetime to float not include milliseconds


rawDescription: Efficient item binning algorithm (itertools/numpy)


code:
SS = normalize("NFD", SS)
LS = normalize("NFD", LS)

rawDescription: How should I remove one string from the start of another given that I know the longer string matches case-insensitively?


code:
import asciitable
import numpy as np

keys = ['RA', 'DEC']
data = {}

# Initialize "data" with empty lists for each key
for k in keys:
    data[k] = []

# Collect all data in the "data" dictionary
for i in range(0, 50):
    data['RA'].append(np.array(i))
    data['DEC'].append(np.array(i+1))

asciitable.write(data, "coords.dat", names=keys)

rawDescription: Making an Ascii table from a FITS file header


code:
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column , Integer
from sqlalchemy.orm import sessionmaker
import pyexcel as pe

engine=create_engine("sqlite:///tmp.db")
Base=declarative_base()

class Sample(Base):
    __tablename__="Sample"
    X=Column(Integer, primary_key=True)
    Y=Column(Integer)
    Z=Column(Integer)

Session=sessionmaker(bind=engine)
Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
session = Session()
# produce test csv
adict = {
    "X": [1, 4],
    "Y": [2, 5],
    "Z": [3, 6]
}
sheet = pe.get_sheet(adict=adict)
sheet.save_as("test.csv")
# end production
# bulk import
pe.save_as(file_name="test.csv", dest_session=session, dest_table=Sample)
result = pe.get_dict(session=session, table=Sample)

# verify result
print(result)

rawDescription: Bulk import/load csv to sqlite using Python


code:
def runGame():
    # Set a random start point.
    startx = random.randint(5, Cell_W - 6)
    starty = random.randint(5, Cell_H - 6)
    wormCoords = [{'x': startx,     'y': starty},
                  {'x': startx - 1, 'y': starty},
                  {'x': startx - 2, 'y': starty}]
    direction = RIGHT

    # Start the apple in a random place.
    apple = getRandomLocation()

    while True: # main game loop
        for event in pygame.event.get(): # event handling loop
            if event.type == QUIT:
                terminate()
            elif event.type == KEYDOWN:
                if (event.key == K_LEFT ) and direction != RIGHT:
                    direction = LEFT
                elif (event.key == K_RIGHT ) and direction != LEFT:
                    direction = RIGHT
                elif (event.key == K_UP ) and direction != DOWN:
                    direction = UP
                elif (event.key == K_DOWN ) and direction != UP:
                    direction = DOWN
                elif event.key == K_ESCAPE:
                    terminate()

        # check if the Snake has hit itself
        for wormBody in wormCoords[1:]:
            if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]    ['y']:
                return # game over

        # check if Snake has eaten an apple
        if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
            # don't remove worm's tail segment
            apple = getRandomLocation() # set a new apple somewhere
        else:
            del wormCoords[-1] # remove worm's tail segment

        # move the worm by adding a segment in the direction it is moving
        if direction == UP:
            if wormCoords[HEAD]['y'] == -1: #if upper wall then move the head to emerge from lower wall
                newHead = {'x': wormCoords[HEAD]['x'], 'y': Cell_H-1}
            else:
                newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}

        elif direction == DOWN:
            if wormCoords[HEAD]['y'] == Cell_H: #if lower wall then move the head to emerge from upper wall
                newHead = {'x': wormCoords[HEAD]['x'], 'y': 0}
            else:
                newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}

        elif direction == LEFT:
            if wormCoords[HEAD]['x'] == -1: #if left wall then move the head to emerge from right wall
                newHead = {'x': Cell_W-1, 'y': wormCoords[HEAD]['y']}
            else:
                newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}

        elif direction == RIGHT:
            if wormCoords[HEAD]['x'] == Cell_W: #if right wall then move the head to emerge from left wall
                newHead = {'x': 0, 'y': wormCoords[HEAD]['y']}
            else:
                newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
        wormCoords.insert(0, newHead)

        DISPLAYSURF.fill(BGCOLOR)
        drawGrid()
        drawWorm(wormCoords)
        drawApple(apple)
        drawScore(len(wormCoords) - 3)
        pygame.display.update()
        SnakespeedCLOCK.tick(Snakespeed)

rawDescription: Pygame : Snake game How to make making snake go throught walls or creating a fram around the edge?


code:
coords = np.vstack([np.random.multivariate_normal(coordstest[i,:], covs, 200)
                         for i in range(10)])

rawDescription: Localized random points using numpy and pandas


code: out

rawDescription: using numpy repeat simultaneously on arrays with distinct multiplicities but same dimension

description: Using numpy repeat simultaneously on arrays with distinct multiplicities but same dimension


code:
class BetterLambertConformal(ccrs.LambertConformal):
    def __init__(self, *args, **kwargs):
        ccrs.LambertConformal.__init__(self, *args, **kwargs)
        self._threshold = 1e4

    @property
    def threshold(self):
        return self._threshold

ax = plt.axes(projection=BetterLambertConformal())

rawDescription: Cartopy background color (outside of data domain)


code: pdf_fitted = t.pdf(x, loc=param[1], scale=param[2], df=param[0])

rawDescription: Anomalies when trying to fit student's t distribution using scipy


code:
# the site admins on every HTTP 500 error.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'root': {
        'level': 'WARNING',
        'handlers': ['sentry'],
    },
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %    (message)s'
        },
    },
    'handlers': {
        'sentry': {
            'level': 'DEBUG',
            'class': 'raven.contrib.django.handlers.SentryHandler',
        },
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose'
        }
    },
    'loggers': {
        'django.db.backends': {
            'level': 'ERROR',
            'handlers': ['console'],
            'propagate': False,
        },
        'raven': {
            'level': 'DEBUG',
            'handlers': ['console'],
            'propagate': False,
        },
        'sentry.errors': {
            'level': 'DEBUG',
            'handlers': ['console'],
            'propagate': False,
        },
        'celery': {
            'level': 'WARNING',
            'handlers': ['sentry'],
            'propagate': False,
        },
    },
}

rawDescription: sentry, raven and django celery

description: Sentry, raven and django celery


code:
def y(u):
    """
    Bloopinate the input

    u should be a positive integer for fastest results.
    """
    offset = 8
    bloop = u ** (-2)
    return bloop + offset

rawDescription: Adding lambda functions with the same operator in python


code:
SERVER = "smtp.google.com"
FROM = "johnDoe@gmail.com"
TO = ["JaneDoe@gmail.com"] # must be a list

SUBJECT = "Hello!"
TEXT = "This is a test of emailing through smtp in google."

# Prepare actual message
message = """From: %s\r\nTo: %s\r\nSubject: %s\r\n\

%s
""" % (FROM, ", ".join(TO), SUBJECT, TEXT)

# Send the mail
import smtplib
server = smtplib.SMTP(SERVER)
server.login("MrDoe", "PASSWORD")
server.sendmail(FROM, TO, message)
server.quit()

rawDescription: Send Outlook Email Via Python?

description: Send Outlook Email Via Python


code:
v = open("users.txt","r").readlines()
v = [line.strip() for line in v]

rawDescription: Preserve newlines in file rendered to HTML with Jinja


code:
x = 'google.com'
y = 'google.com'
id(x), id(y)

rawDescription: Why does the "is" keyword have a different behavior when there is a dot in the string?


code:
toolbar = Toolbar(screen_width, 80)

while True:
    toolbar.update()
    toolbar.draw(screen)

    #Other stuff
    ## Events:
    ## on left click call toolbar.click(pos)

rawDescription: Creating a ToolBar in pygame window

description: Creating a ToolBar in pygame window


rawDescription: merging two pandas dataframes on nearest time stamp

description: Merging two pandas dataframes on nearest time stamp


rawDescription: Why isn't my dictionary printing correctly?


rawDescription: setdefault - add more than one value to the key

description: Setdefault - add more than one value to the key


code:
swapped_example = [sublst if idx%2 else sublst[::-1] for
                   idx,sublst in enumerate(example)][::-1]

rawDescription: Flipped an array and reversing every second row


code: mydict = dict(request.GET._iterlists())

rawDescription: Django template iterate over list inside request.GET


code:
import math
x = 2<<600
int(math.sqrt(x*x)) == x

rawDescription: Exactness of integer square root in Python


code:
# encoding: utf-8
import xmltodict

def listify(obj):
    if isinstance(obj, list):
        return obj
    return [obj]

def get_details(soap):
    # Parse the SOAP
    soap = xmltodict.parse(soap, process_namespaces=True)

    # Deal with namespaces
    env = 'http://schemas.xmlsoap.org/soap/envelope/:'
    doorway = 'http://www.derbysoft.com/doorway:'

    # Everything we care about is in "Availability"
    availability = listify(
        soap[env+'Envelope']
            [env+'Body']
            [doorway+'MultiAvailabilityResponse']
            [doorway+'Availabilities']
            [doorway+'Availability'])

    # Intermediate data structure to hold room names
    names = {
        roomtype['@RoomTypeCode']: roomtype['@RoomTypeName']
        for _availability in availability
        for roomtype in listify(_availability
            [doorway+'RoomTypes']
            [doorway+'RoomType'])
    }

    # Result!
    return {
        'roomlist': sorted([
            {
                'RoomTypeCode': roomrate['@RoomTypeCode'],
                'RatePlanCode': roomrate['@RatePlanCode'],
                'RoomTypeName': names[roomrate['@RoomTypeCode']],
                'AmountBeforeTax': rate['@AmountBeforeTax'],
            }
            for _availability in availability
            for roomrate in listify(_availability
                [doorway+'RoomRates']
                [doorway+'RoomRate'])
            for rate in listify(roomrate
                [doorway+'Rates']
                [doorway+'Rate'])],
            key=lambda x:float(x['AmountBeforeTax']))
    }

if __name__ == "__main__":
    soap = '''
    <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
    <SOAP-ENV:Header/>
    <SOAP-ENV:Body>
        <ns2:MultiAvailabilityResponse xmlns:ns2="http://www.derbysoft.com/doorway" Status="Successful" Token="187be58c62c2f2515b5d78ee">
            <ns2:Availabilities>
                <ns2:Availability CurrencyCode="USD" HotelCode="HY-CHIRC">
                    <ns2:GuestCount AdultCount="1" ChildCount="0"/>
                    <ns2:RoomTypes>
                        <ns2:RoomType RoomTypeCode="JRSQ" RoomTypeName="JR SUITE 2 QUEEN BEDS">
                            <ns2:RoomTypeDescription>Rest in sublime comfort on one of two queen signature Hyatt Grand BedsÂ®, fitted with fine linens, down blanket and plump pillows.</ns2:RoomTypeDescription>
                        </ns2:RoomType>
                        <ns2:RoomType RoomTypeCode="CLBD" RoomTypeName="REG CLUB 2 DOUBLE BEDS">
                            <ns2:RoomTypeDescription>one King or two double-sized Hyatt Grand Beds, fitted with luxurious linens, a down blanket and plush pillows</ns2:RoomTypeDescription>
                        </ns2:RoomType>
                        <ns2:RoomType RoomTypeCode="VW2Q" RoomTypeName="PREMIUM VW 2 QEN">
                            <ns2:RoomTypeDescription>Relax and unwind in our sophisticated downtown Chicago guestrooms with city, river and lake views</ns2:RoomTypeDescription>
                        </ns2:RoomType>

                    </ns2:RoomTypes>

                    <ns2:RoomRates>
                        <ns2:RoomRate RatePlanCode="49584IPRTF" RoomTypeCode="JRSQ">
                            <ns2:Rates>
                                <ns2:Rate AmountAfterTax="523.348" AmountBeforeTax="449.650" EffectiveDate="2016-04-28" ExpireDate="2016-04-29"/>
                            </ns2:Rates>
                            <ns2:Fees>
                                <ns2:Fee ChargeType="Tax" Percent="16.390" Type="Exclusive"/>
                            </ns2:Fees>
                        </ns2:RoomRate>
                        <ns2:RoomRate RatePlanCode="49584IPRTF" RoomTypeCode="CLBD">
                            <ns2:Rates>
                                <ns2:Rate AmountAfterTax="350.218" AmountBeforeTax="300.900" EffectiveDate="2016-04-28" ExpireDate="2016-04-29"/>
                            </ns2:Rates>
                            <ns2:Fees>
                                <ns2:Fee ChargeType="Tax" Percent="16.390" Type="Exclusive"/>
                            </ns2:Fees>
                        </ns2:RoomRate>
                        <ns2:RoomRate RatePlanCode="49584IPRTF" RoomTypeCode="VW2Q">
                            <ns2:Rates>
                                <ns2:Rate AmountAfterTax="305.699" AmountBeforeTax="262.650" EffectiveDate="2016-04-28" ExpireDate="2016-04-29"/>
                            </ns2:Rates>
                            <ns2:Fees>
                                <ns2:Fee ChargeType="Tax" Percent="16.390" Type="Exclusive"/>
                            </ns2:Fees>
                        </ns2:RoomRate>

                    </ns2:RoomRates>
                </ns2:Availability>
            </ns2:Availabilities>
        </ns2:MultiAvailabilityResponse>
    </SOAP-ENV:Body>
    </SOAP-ENV:Envelope>'''

    from pprint import pprint
    pprint(get_details(soap))

rawDescription: Fetch the required details from SOAP xml response


code:
name, path, args, kwargs = field.deconstruct()
print(kwargs)

rawDescription: Is it possible getting all parameters of a field


rawDescription: Regex: How to leave out string + space before a domain or IP address?


code: numbersList = re.findall('{"number":(\d{5,9})', myFile.read(), re.DOTALL)

rawDescription: python, regex: What RegEx do I need?

description: Python, regex: What RegEx do I need


code:
db = MySQLdb.connect(host=hostName,user=userName,passwd=password,db=database)

cursor=db.cursor()

rawDescription: How can I update the cursor and get real state?

description: Update the cursor and get real state


rawDescription: A templated constructor cursor and a templated member cursor have kind FUNCTION_TEMPLATE in libclang


rawDescription: How do I shift rows of consecutive numbers. Python 3.3.2

description: Shift rows of consecutive numbers. Python 3.3.2


code:
import inspect

class Student(object):
    def __init__(self, name, grade, classes):
        self.name = name
        self.grade = grade
        self.classes = classes
    def __repr__(self):
        return '{}\n{}'.format(type(self).__name__,
            '\n'.join(['  {}: {!r}'.format(name, getattr(self, name))
                       for name in inspect.getargspec(self.__init__).args[1:]]))

rawDescription: represent a class in the order that was shown in init, without hardcoding

description: Represent a class in the order that was shown in init, without hardcoding


code:
results = []
for item in request_tuples:
    results.append(pool.apply_async(get_api_response, args=item, callback=check_response_amount))

for result in results:
    result.wait()

rawDescription: Python 3: Multiprocessing API calls with exit condition


code:
mylist = ["8 - 9 -", "7 - 6 -", "5 - 4 -"]
mylist = [x[:-1] for x in mylist]
mylist

rawDescription: Add a word at the end of elements of a list


rawDescription: split a list into three lists with a stepsize and a starting point

description: Split a list into three lists with a stepsize and a starting point


code:
def chunks(l, n):
    """ Yield successive n-sized chunks from l.  """
    for i in xrange(0, len(l), n):
        yield l[i:i+n]

rawDescription: Save data to csv file using Python

description: Save data to csv file using Python


rawDescription: How to do a django select sql or statement?

description: Do a django select sql or statement


code: cmdclass = { 'clean': clean, 'build_py': build_py }

rawDescription: Python project using protocol buffers, Deployment issues


rawDescription: What is the most efficient method to assign an X and Y header for a list of the following nature?


code:
index = combo.findData(456)
if index >= 0:
    print(combo.itemData(index, QtCore.Qt.UserRole + 1)) # prints "other data"

rawDescription: Inserting hidden data into a combobox pyqt


rawDescription: Efficient reverse of queryset

description: Efficient reverse of queryset


code:
# minDepthLevel = 0
# grid = {}
# grid[(1.5,0,0)] = [1,2]
# not sure what this ^ 1 means

cube = Cube((1.5, 0, 0), 4, 2)
grid = {c.center: [1, c.depth] for c in cube.divide(0)}

rawDescription: Break down cubes into 8 smaller cubes recursively (when the cubes are defined by a mid point and size)


code:
d = {} # alternatively, d = dict()
for item in a.split(','):
    d[item] = item

rawDescription: How to convert a list into a required dictionary format

description: Convert a list into a required dictionary format


code:
s = '12345678'
t = iter(s)
'-'.join(a+b for a,b in zip(t, t))

rawDescription: Pythonic way to insert every 2 elements in a string


code: M = loadtxt (filename, delimiter=delimiter, usecols=range(C1,C2+1)) [R1:R2+1,:]

rawDescription: numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file

description: Numpy: How to load a bounded (R1 C1 to R2 C2) matrix from file


code:
import operator
final_data = sorted(scores.items(),
                    key=operator.itemgetter(1),
                    reverse=True)
print(final_data)

rawDescription: Python: reading txt file containing (alphabet and number) and updating the number


code:
urlpatterns = patterns('',
    #...
    (r'^search/$', 'searchapp.views.search'),
)

rawDescription: passing data between class based forms

description: Passing data between class based forms


code:
for ind, line in enumerate(input("test.txt", inplace=True), 1):
    if ind == r:
        new = line[:st-1] + val + line[ed:]
        stdout.write(new)
    else:
        stdout.write(line)

rawDescription: change a value in a specific location in a text file in python

description: Change a value in a specific location in a text file in python


rawDescription: How assignment works with python list slice


code: a = [s.replace('1','3') for s in self.test_lockCheck()]

rawDescription: Python; Search and Replace; Lists; Strings


code:
# Show the best hit's stored fields
results[0]
results[0:2]

rawDescription: Instant search with Whoosh - Index and search a MySQL table using Whoosh outputing JSON results


code:
class A(object):
    def __init__(self):
        self.b = B(self)
        self.c = C(self)

class B(object):
    def __init__(self, parent):
        self.parent = parent

    def call_c(self):
        self.parent.c.a_method_of_c()

class C(object):
    def __init__(self, parent):
        self.parent = parent

    # whatever...

rawDescription: How can I call methods between two classes?

description: Call methods between two classes


code:
no_minutes = 5 #say 5 minutes
array_collect = np.zeros((no_minutes,array_a.shape[0],array_a.shape[1]))

rawDescription: how to transfer an numpy array into another array

description: Transfer an numpy array into another array


rawDescription: In Django, how do I join a table with a composite primary key to another table?


rawDescription: Find the occurrences of unique element in list in python


rawDescription: Convert u'\xe0' to '\u00E0' in Python 2.x?


code:
t = transposer()
t.transpose('in', 'out')

rawDescription: Python - CSV time oriented Transposing large number of columns to rows


code: pd.read_hdf('test.h5','df',where='date>start_date & date<end_date & id=ids & id2>500 & id2<600')

rawDescription: Query HDF5 in Pandas

description: Query HDF5 in Pandas


code:
def format_row(row):
    result = row[:]   #make a copy of the row
    # format should be preferred over %.
    # Also, you don't have to escape the %.
    result[1] = "USD {:.2f}".format(result[1])
    result[2] = "USD {:.2f}".format(result[2])
    # do whatever else you have to do for a single row
    return result

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


code:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 10)

live_games_link = wait.until(EC.element_to_be_clickable((By.LINK_TEXT, "LIVE Games")))
live_games_link.click()

rawDescription: Webscrape Flashscore with Python/Selenium


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

description: Generate numbers based on a pattern in python


code: sum([len(x["users"]) for x in d["work"]])

rawDescription: Counting how many specific items exist in a YAML file?


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

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


code:
import httplib
i = ['www.nri.com','www.kundis.com']
for b in i:

    print('Checking ' + b)

    c = httplib.HTTPConnection(b)
    c.request("HEAD", '')

    if c.getresponse().status == 200:
        print('web site exists')

    if c.getresponse().status == 302:
        print('website not exists')

rawDescription: Checking if a link is active from an array


code:
import itertools

string = "AABC"
count = len(set(itertools.permutations(string)))
print(count)

rawDescription: Calculate the number of unique strings that can be made from a string


code:
#remember items() is a tUple list :
myDict = dict(element.attributes.items())

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


code: new = [x ** 2 for x in old if not x % 2]

rawDescription: understanding "item for item in list_a if ..." PYTHON

description: Understanding "item for item in list_a if ..." PYTHON


rawDescription: Text file number to Python number how?

description: Text file number to Python number how


code:
stmt = select([Addresses.email_address]).\
            where(Addresses.user_id == Users.id).\
            limit(1)
conn.execute(Users.__table__.update().values(fullname=stmt))

rawDescription: Sqlalchemy: bulk correlated update to link tables


rawDescription: python RE: Non greedy matches, repitition and grouping

description: Python RE: Non greedy matches, repitition and grouping


code: vulns[0] = vulns[0] + 1

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


code: '{"text": "A dummy text", "id": 83}'

rawDescription: Trying to use a JSON object as a argument (Python)


code:
import itertools

with open('bigfile_1') as bf1:
    with open('bigfile_2') as bf2:
        for line1, line2 in itertools.izip(bf1, bf2):
            process(line1, line2)

rawDescription: Iterate over the lines of two files simultaneously


code:
for i in range(5, 16):
    combinations = itertools.product(*itertools.repeat(nucleotides, i))
    for j in combinations:
        print(j)

rawDescription: Generate all combinations of nucleotide k-mers between range(i, j)


code: df = df.rename(columns=lambda x: x.replace('.', '_'))

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

description: Import a Qualtrics csv file into a pandas dataframe


rawDescription: Python: Intersection of two lists of lists


code:
config.add_view(route_name='item_options', view='.views.options_view',
                permission='view', renderer='item_options.mako')

rawDescription: Pyramid authorization for stored items

description: Pyramid authorization for stored items


code:
from itertools import repeat

def recreate(callable, count=None):
    for c in repeat(callable, count):
        yield from c()

rawDescription: Chain repetitions of same generator in python


code:
x = np.array([0, 8, 10, 15, 50]).reshape((-1, 1))
ncols = 5
x + np.arange(ncols)

rawDescription: Numpy: Array of `arange`s

description: Numpy: Array of `arange`s


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

rawDescription: Scale the real part of complex numpy array


code:
d = {'player1':'Bob' , 'player2':'John', 'player3':'Greg', 'player4':'Tim'}

players = list(d.values())
print(', '.join('{} and {}'.format(players[i], players[i+1]) for i in range(0, len(players), 2)))

rawDescription: Is there a way to pair dictionary items?

description: Is there a way to pair dictionary items


code:
import numpy as np
(m, n) = (4, 5)
a = np.zeros((m, n))
a[2, 3] = 1.
a_eq_1 = a == 1
repetitions = a_eq_1.sum(axis=0)
np.argmax(repetitions)

rawDescription: How can i do this numpy array operation in an efficient manner?

description: Do this numpy array operation in an efficient manner


code:
import sys
for i in range(sys.maxint):
  if thereIsAReasonToBreak(i):
    break

rawDescription: Looping from 1 to infinity in Python

description: Looping from 1 to infinity in Python


code:
class Monitor(object):

    def __init__(self, dispatcher):
        self._stop = False
        self._dispatcher = dispatcher

    def run(self, inputFile, secs=3):
        ...
        ...

        # should notify video of new value
        line = int(line_from_file)
        self._dispatcher.updateIndex(line)

        ...
        ...

rawDescription: Play Different Video Files Depending On Value of a Variable At Runtime


rawDescription: Calculating the Letter Frequency in Python


code: from packages.files import fileChecker

rawDescription: importing a package from within another package in python

description: Importing a package from within another package in python


code:
with open('websites.csv') as f:
    websites = [Website(**row) for row in csv.DictReader(f)]

rawDescription: Most appropriate way to combine features of a class to another?


code: fields = ['product ', 'number', ]

rawDescription: Django form - filter foreignkey in model


rawDescription: Confusing characters in a file

description: Confusing characters in a file


code:
list = [1,2,3,4,5]
for each in range(len(list)):
    list[each] = 4
print(list)

rawDescription: Why doesn't this Python 3 for loop change every variable to 4?


code:
from collections import Counter
d1 = Counter({'a':1,'b':1})
d2 = Counter({'a':2,'c':3})
d1.update(d2)
d1

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


code: data_mean = pd.rolling_mean(data, window=5).shift(-2)

rawDescription: Rolling mean with customized window with Pandas


code:
class ProjectTerms(models.Model):
    terms = models.CharField(max_length=100)

class ProjectLinks(models.Model):
    links = models.CharField(max_length=100)
    relations = models.ManyToManyField(ProjectTerms)

rawDescription: Django Integrity Error - id cannot be null


code: nouns = [x for key, value in pos_dictionary.iteritems() if key.startswith('NN') for x in value]

rawDescription: how to write a conditional list comprehension, with "extend" functionality

description: Write a conditional list comprehension, with "extend" functionality


rawDescription: Google cloud endpoint RequestMessage with multiple fields resolution


code:
with file('partsList.txt') as myfile:
    data = json.load(myfile)

names = data['names']
# etc.

rawDescription: Saving BOM (parts list) for multiple builds to a file in Python


rawDescription: Check if discrete signal is periodic (or close to), given discrete event times


code:
import time

def handler(env, start_response):
    start_response("200 OK", [('Content-Type', 'text/html')])
    cr = lambda s='': s + '\n'
    yield cr("<title>Hello world!</title>")
    yield cr("
Bargle Bargle Bargle
")
    yield cr("
From the handler...
")
    yield cr("
(bargle)
")
    yield cr("
The time is now: " + time.asctime() + "
")
    yield cr("")

__all__ = ['handler']

rawDescription: How to properly install isapi_wsgi on IIS for Python2.7?

description: Properly install isapi_wsgi on IIS for Python2.7


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

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


code:
def getIncrementedFileName (fileName):
    baseName, extension = os.path.splitext(fileName)
    suffix = 0

    while os.path.exists(os.path.join(directory, fileName)):
        suffix += 1
        fileName = '{}_{:02}.{}'.format(baseName, suffix, extension)
    return fileName

rawDescription: Python : Rename files

description: Python : Rename files


code:
self.window.get_toplevel().show() # must call show() before property_change()
self.window.get_toplevel().window.property_change("_NET_WM_STRUT",
    "CARDINAL", 32, gtk.gdk.PROP_MODE_REPLACE, [0, 0, 0, bottom_width])

rawDescription: Preventing window overlap in GTK

description: Preventing window overlap in GTK


code:
high_results = [(3,) + row for row in high_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name'))]
medium_results =  [(2,) + row for row in medium_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name'))]
low_results = [(1,) + row for row in low_structures.values_list('bldg_name', 'bldg_type').annotate(count=Count('bldg_name'))]

rawDescription: Inserting item in list in python

description: Inserting item in list in python


code:
class Foo(object):
    def __init__(self, num):
        self.numSquared = self.square(num)

    @staticmethod
    def square(num):
        return num**2
Foo.square(2) # you can test the square "method" this way without instantiating Foo
Foo(8).numSquared

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


code: [sum(1 for t in tups if t[1] == '') for tups in obj]

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

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


code: import tkinter as tk

rawDescription: tkinter wrap text if larger than column width

description: Tkinter wrap text if larger than column width


code:
import random

def gen():
    for _ in range(10):
        i=random.randint(0,100)
        if i%2:
            yield process1, str(i)
        else:
            yield process2, str(i)

def test():
    for fn, i in gen():
        fn()

rawDescription: better treatment for 2 kind of generator results in python

description: Better treatment for 2 kind of generator results in python


code:
# here I use Test in all the places I think you could want to use it:
#   as a function argument
#   as a variable in a function
#   in a class
import a

def f(x):
    return x

def g():
    t = a.Test()
    return t

class C:
    pass

rawDescription: Cython: share pure python module

description: Cython: share pure python module


code: Acct = choose_account()

rawDescription: How to change a global variable in python?

description: Change a global variable in python


code:
import re
from collections import defaultdict

matches = defaultdict(list)
needles = ['accept','freed','partie','accepta','freeing','party']
haystack = "I am accepting your invitation for the party. No, really, I accept!"
words = re.findall(r'(\w+)', haystack)

for key in needles:
    for word in words:
       if key in word:
           matches[key].append(word)

for key, found in matches.iteritems():
    print('Key: {} - Total Matches: {}'.format(key, len(found)))
    for match in found:
        print('\t{}'.format(match))

rawDescription: substring of a string using python?

description: Substring of a string using python


rawDescription: Rescale number range which keeps orginal spacing


code:
def quantityFunction():
    while True:
        quantity = input("Please enter the amount of this item you would like to purchase: ")
        if quantity.isdigit():
            return int(quantity)
        else:
            print("We didn't recognise that number. Please try again.")

rawDescription: Incorrect Looping and returning of variable


code:
class Item(models.Model):
    ...
    @property
    def percentage_met(self):
        if hasattr(self, 'total_amount'):
            return (self.total_amount / float(self.target_amount)) * 100
        return None

rawDescription: Django "extra" query

description: Django "extra" query


code:
with open("test.txt") as f:
    index = collections.defaultdict(set)
    num = None
    for line in f:
        m = re.match(r"<POST (\d+)", line)
        if m is not None:
            num = m.group(1)
        else:
            for word in re.findall(r"\w+", line):
                index[word].add(num)

rawDescription: Assign "ID" to a string in a "post"

description: Assign "ID" to a string in a "post"


code:
with open('test.txt') as f:
    x = {y.split('\n')[0]:[z.split() for z in y.strip().split('\n')[1:]] for y in f.read().split('*')[1:]}

rawDescription: How to read and organize text files divided by keywords

description: Read and organize text files divided by keywords


code:
import sys
class ListStream:
    def __init__(self):
        self.data = []
    def write(self, s):
        self.data.append(s)
    def __enter__(self):
        sys.stdout = self
        return self
    def __exit__(self, ext_type, exc_value, traceback):
        sys.stdout = sys.__stdout__

rawDescription: Redirect print to string list?

description: Redirect print to string list


code:
parent = tree.find('./DIMENSION/DIMENSION_NODE')
for tag in removeList:
    parent.remove(tag)

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

description: Remove child node from XML in Python


code:
color_query = cursor.execute("SELECT R, G, B FROM Colors").fetchall()
name_query = cursor.execute("SELECT name FROM Colors").fetchall()
desc = {'names':('name','Color'),'formats':('a3','3f')}
colorlist = np.rec.fromarrays([color_query, name_query], desc)

rawDescription: Tuple Numpy Data Type

description: Tuple Numpy Data Type


code:
def iDictOfListsToDicts(d):
    keys = list(d)
    for vs in zip(*d.values()):
        yield dict(zip(keys, vs))

rawDescription: iterating dicts out of a dict of matched-length lists

description: Iterating dicts out of a dict of matched-length lists


code: {''.join(sorted([a,b])): list(set(dic[a]+dic[b])) for a,b in IT.combinations(dic, 2)}

rawDescription: Get a dict whose keys are combinations of a given dict without duplicate values


code:
for item in list:
    if item != 10:
        do_something

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


code: M[...,np.arange(w.size),:] *= w[:,None]

rawDescription: What is the nicest way to weight planes in a numpy array?


code:
data
df = pd.concat(data, axis=1, keys=['a', 'b', 'c'])
df
df2 = pd.concat([df, df], axis=1, keys=['group1', 'group2'])
df2

rawDescription: How can I generalize my pandas data grouping to more than 3 dimensions?

description: Generalize my pandas data grouping to more than 3 dimensions


code: process = subprocess.Popen("git diff --name-only mybranch `git merge-base mybranch develop`", stdout=subprocess.PIPE, shell=True)

rawDescription: Using back-ticks in Python subprocess

description: Using back-ticks in Python subprocess


code:
import requests

url_to_txt_file = ""
print(requests.get(url_to_txt_file).text)

rawDescription: Can A Python Program Open An Text File On The Web?


code:
for item in soup.contents:
    if type(item) is Tag and u'a' != item.name:
        parsed_soup += ''.join(item.findAll(text = True))
    else:
        parsed_soup += unicode(item)

rawDescription: Finding Tags And Text In BeautifulSoup

description: Finding Tags And Text In BeautifulSoup


rawDescription: Random Forest not working in opencv python (cv2)


code:
X_train = scaler.fit_transform(X_train)

X_test = scaler.transform(X_test)

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

description: Apply standardization to SVMs in scikit-learn


code:
from scipy.spatial import distance as ssd
Z = linkage(ssd.squareform(arr), method="average")

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


code:
from __future__ import print_function
with open('testfile.txt') as f:
    for line in f:
            fields = line.split()
            fields3 = fields[2].split('@')
            fields6 = fields[5].split('@')
            if fields3[0] == fields6[0]:
                    print(line, end='')

rawDescription: selecting lines according certain criteria

description: Selecting lines according certain criteria


code:
from itertools import product

list1 = ["a ", "b ", "c ", "d ", "e ", "f ", "g "]
list2 = ["a ", "b*", "c*", "d ", "e*", "f*", "g "]

# figure out which offsets have alternable values
crosses = [a != b for a,b in zip(list1, list2)]
offsets = [i for i,cross in enumerate(crosses) if cross]

# decide which offsets will be swapped
basis = [[0,1] for ofs in offsets]
basis[0] = [0]       # only the first half - remainder are mirrors
swaps = product(*basis)
next(swaps, None)    # skip base state == (list1, list2)

# print all viable swaps
list3 = list1[:]
list4 = list2[:]
for sw in swaps:
    # build output lists
    for which,offs in zip(sw, offsets):
        list3[offs] = [list1, list2][which][offs]
        list4[offs] = [list2, list1][which][offs]
    # display output
    print("\n{}\n{}".format(list3, list4))

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


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

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


rawDescription: How to deal with indeterminate form in Python

description: Deal with indeterminate form in Python


rawDescription: Parsing large JSON - Python

description: Parsing large JSON - Python


code:
selectBtn = wx.Button(self, wx.ID_FILE, label="Select File")
selectEvent = lambda event, ctrl=txt: self.OnSelect(event, ctrl)
selectBtn.Bind(wx.EVT_BUTTON, selectEvent)

rawDescription: wxPython - Using filedialog to update a textctrl

description: WxPython - Using filedialog to update a textctrl


rawDescription: how to convert string like "5cm" into an integer

description: Convert string like "5cm" into an integer


rawDescription: slice in python, is a copy or just a pointer

description: Slice in python, is a copy or just a pointer


code:
from videoFunctions import VideoFeedMixin

class MainWindow(VideoFeedMixin, QtGui.QMainWindow, mainWindowUI.Ui_MainWindow):
    ...

rawDescription: Can't connect function imported outside of class qt


code:
documents = sc.textFile("README.md").map(lambda line: line.split(" "))
tf = HashingTF().transform(documents)
idf = IDF().fit(tf)
tfidf = idf.transform(tf)

v = tfidf.first()
v
## SparseVector(1048576, {261052: 0.0, 362890: 0.0, 816618: 1.9253})

type(v)
## pyspark.mllib.linalg.SparseVector

v[0]
## 0.0

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


code:
import watcher,wx
a = wx.App(redirect=False)
TARGET_DIR="/py_exp/testing"
def real_callback(*args):
    wx.MessageBox(str(args),"QQQQ")
def callback(*args):
    wx.CallAfter(real_callback,*args)
w = watcher.Watcher(TARGET_DIR, callback)
w.flags = watcher.FILE_NOTIFY_CHANGE_FILE_NAME
w.start()
f = wx.Frame(None)
a.MainLoop()

rawDescription: Simultaneous Message Boxes

description: Simultaneous Message Boxes


code:
import sys
import io
oldstdout = sys.stdout
sys.stdout = io.StringIO()
'hello'
def func1():
    s = 'abcdefghijklmnoqrstuwxyz'
    for c in s:
            print(c,end=',')
def func2():
    s = 'abcdefghijklmnoqrstuwxyz'
    res = ''
    for c in s:
            res += c + ','
    print(res,end='')
import timeit
x = timeit.timeit(func1,number=100000)
y = timeit.timeit(func2,number=100000)
sys.stdout = oldstdout
x
y

rawDescription: Is there a faster way to convert characters to ints and print it to console for python?


code: Series(date_range('now', periods=5))

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


code: True

rawDescription: Test if two lists of lists are equal

description: Test if two lists of lists are equal


code:
a = 'birthday'
[a[:i] for i in range(2,len(a)+1)]

rawDescription: index of a letter in string - python 2.7

description: Index of a letter in string - python 2.7


rawDescription: Sort NumPy float array column by column

description: Sort NumPy float array column by column


code:
a = [1, 2, 3]
b = [4, 5, 6]
sum = [a, b]
print(sum)
a.append(8)
print(sum)

rawDescription: How to create dynamic link between list variables

description: Create dynamic link between list variables


rawDescription: Iterate with binary structure over numpy array to get cell sums


code:
self.VALUES_OPTION['menu'].delete(0, 'end')
for item in values:
    self.VALUES_OPTION['menu'].add_command(label=item)

rawDescription: Tkinter how to make a dynamic optionmenu without using a dictionary


rawDescription: List comprehension against tuple of sets


code:
for student, scorelist in sorted(scores.items()):
    print("%s : %d" % (student, max(scorelist)))

rawDescription: Python - Highest with alphabetical order from text file


rawDescription: Python list reordering, remember original order?


code:
from nltk.book import *
from nltk import FreqDist
fdist1 = FreqDist(text1)
vocabulary1 = fdist1.keys()
vocabulary1[:50]

rawDescription: FreqDist in NLTK not sorting output

description: FreqDist in NLTK not sorting output