code:
def __init__(self, *args, **kwargs):
    current_user = kwargs.pop('user', None)

    initial = kwargs.get('initial', {})
    if current_user:
        initial.update({'subjects': current_user.subjects.all()})
    kwargs['initial'] = initial

    super(TutorUpdateForm, self).__init__(*args, **kwargs)

    for field in _update_exclude:
        self.fields.pop(field)

rawDescription: django render initial values in form with ModelMultipleChoiceField and CheckboxSelectMultiple() widget

description: Django render initial values in form with ModelMultipleChoiceField and CheckboxSelectMultiple() widget


code: sorted(os.listdir('.'), key=lambda f: int(f.split('.')[0][1:]))

rawDescription: Reference list item as key in sorted for loop


code:
cmap = matplotlib.colors.ListedColormap(['green', 'blue', 'red'])
bounds=[0,125,200,400]
cax = inset_axes(ax3, width="8%", height='70%', loc=4)
cbar = matplotlib.colorbar.ColorbarBase(cax, cmap=cmap, boundaries=bounds)
cax.yaxis.set_ticks_position('left')
cbar.ax.set_yticklabels(['0', '125', '200', '200+'])
cax.yaxis.set_label_position('left')
cbar.set_label('Income (,000s)')

rawDescription: Custom Matplotlib ColorBar for Scatterplot


code:
test_ex5 = np.hstack((test[:,:5],test[:,6:]))
test.shape
test_ex5.shape

rawDescription: Remove column of array via indexing in Python


code:
years = df['date'].dt.year.unique()

dfs = []
for i in range(100):
    dfs.append(df.query("Year == %d and Season == '1'"  %np.random.choice(years, 1)))
    dfs.append(df.query("Year == %d and Season == '2'"  %np.random.choice(years, 1)))
    dfs.append(df.query("Year == %d and Season == '3'"  %np.random.choice(years, 1)))
    dfs.append(df.query("Year == %d and Season == '4'"  %np.random.choice(years, 1)))

rnd = pd.concat(dfs)

rawDescription: Create new dataframe from multiple multi-index dataframes


code:
if __name__ == '__main__':
   import formain as bumpf
else:
   import forscripts as bumpf

bumpf.domagic()

rawDescription: Is there a way to test whether a Python function or method has been invoked directly from a shell?


code:
import threading

def hello_world():
  threading.Timer(60.0, hello_world).start() # called every minute
  print("Hello, World!")

hello_world()

rawDescription: How to repeat a function every N minutes?

description: Repeat a function every N minutes


code:
from itertools import chain

headings = [i.get_text() for i in chain.from_iterable(x.find_all("div") for x in table.find("tr").find_all("td"))]

rawDescription: How to get all elements text in sequential order

description: Get all elements text in sequential order


code:
from email.mime.text import MIMEText

# ...
email_body = """
Module: %s
Installed: %s
Required: %s
""" %(module, installed_version, required_version)

email_body = MIMEText(email_body)
# ...

rawDescription: Remove tabs in email body due to tabs in Python code


code:
def fetch_files_and_directories(path):
    path = os.path.dirname(__file__) + '/files' + path
    if os.path.isdir(path):
        files = [ f for f in os.listdir(path) if os.path.isfile(os.path.join(path,f)) ]
        dirs = [ f for f in os.listdir(path) if os.path.isdir(os.path.join(path,f)) ]
        # Note that the is None check is nonsense.
        # The result of an empty list comprehension is an empty list, not None
    else:
        files = []
        directories = []
    return dict(directories=dirs, files=files)

@view_config(route_name='file', renderer='json')
def file(request):
    response = fetch_files_and_directories(request.json_body['path'])
    # you might want to move this into the fetch_* function.
    response['version']='1.0'
    return response

@view_config(route_name='files', renderer='templates/filesTest.jinja2')
def files(request):
    if 'form.submitted' in request.params:
        path = request.params['path']
        data = fetch_files_and_directories(path)
        # You did not use data below here, so neither did I.
        return dict(dirs=[], files=[], saveURL = request.route_url('files'), pathDefault=path)
    return dict(dirs=[], files=[], saveURL = request.route_url('files'), pathDefault='/')

rawDescription: Pyramid rendered JSON Response returned as a string


code:
cpt1 = sum(1 for x in liste if x != 2)
cpt2 = sum(1 for x in liste if x == 2)

rawDescription: Python list iteration and deletion

description: Python list iteration and deletion


code:
np.isnan(raw_test)
np.all(np.isnan(raw_test), axis=1)
np.where(np.all(np.isnan(raw_test), axis=1))[0]

rawDescription: Numpy - find rows where all elements are finite


rawDescription: vectorized string manipulation in pandas dataframe

description: Vectorized string manipulation in pandas dataframe


code:
df = DataFrame({'Frequency':lenFreq,'Fatigue Thrust    [N]':meqThrust[iexcel],'Extreme Thrust [N]':extremeThrust[iexcel],'Extreme Thrust DMR [N]':extremeThrustDMR[iexcel],\
             'Fatigue Yaw [Nm]':meqYaw[iexcel],'Extreme Yaw [Nm]':extremeYaw[iexcel],'Extreme Flapwise [Nm]':extremeFlapwise[iexcel][ilenFreq]})

df.to_excel(workbookOutput, sheet_name='Results', index=False)

sheet = workbookOutput.sheet_by_name('Results')
nrows = len(sheet.get_rows())
ncolumns = len(sheet.get_cols())

for row_index in range (nrows):
    for column_index in range(ncolumns) :
      cwidth = sheet.col(column_index).width
      column_data = sheet.cell(row_index,column_index).value
      if (len(column_data)*367) > cwidth:
          sheet.col(column_index).width = (len(column_data)*367)

rawDescription: Write data frame into excel with wide column


code: numpy.searchsorted(bins, mzArray)

rawDescription: Combining several arrays into a binned array (performance)


code: [[i-j for i,j in zip(m, rav)] for m in M]

rawDescription: Calculating difference between row vector and average row vector?


code: df.iloc[[0, -1], df.columns.get_loc('mycol')] = [1, 2]

rawDescription: Set first and last row of a column in a dataframe


code:
class AjaxTabularInline(admin.TabularInline):
    def get_formset(self, request, obj=None, **kwargs):
        autoselect_fields_check_can_add(self.form, self.model, request.user)
        return super(AddressInline, self).get_formset(request, obj, **kwargs)

rawDescription: Custom tabular editable data with Autocomplete


code:
summary = [[0,0,0] for _ in sign_list[0]]

for row in sign_list:
  for index,sign in enumerate(row):
    summary[index][sign+1] += 1
return summary

rawDescription: How to rewrite the code more elegant

description: Rewrite the code more elegant


code:
fold_labels = df["fold"]
from sklearn.cross_validation import LeaveOneLabelOut
cv = LeaveOneLabelOut(fold_labels)

lasso_model = LassoCV(cv=cv, alphas=reg_para)

rawDescription: cross validation in sklearn with given fold splits

description: Cross validation in sklearn with given fold splits


code:
def autocomplete(self, request, class_name, attr_name):
    term = request.GET.get('term', '')
    data = Autocomplete.get_json_autocomplete(
        class_name.objects.filter(**{attr_name + '__icontains': term}),
        lambda x: getattr(x, attr_name)
    )
    return HttpResponse(data, 'application/json')

rawDescription: Understanding reflection in django for refactoring


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

fig,ax = plt.subplots(1)
ax.set_aspect('equal')

# Some test points
x = np.random.rand(500)*0.5+0.7
y = np.random.rand(500)*0.5+0.7

# The ellipse
g_ell_center = (0.8882, 0.8882)
g_ell_width = 0.36401857095483
g_ell_height = 0.16928136341606
angle = 30.

g_ellipse = patches.Ellipse(g_ell_center, g_ell_width, g_ell_height, angle=angle, fill=False, edgecolor='green', linewidth=2)
ax.add_patch(g_ellipse)

cos_angle = np.cos(np.radians(180.-angle))
sin_angle = np.sin(np.radians(180.-angle))

xc = x - g_ell_center[0]
yc = y - g_ell_center[1]

xct = xc * cos_angle - yc * sin_angle
yct = xc * sin_angle + yc * cos_angle

rad_cc = (xct**2/(g_ell_width/2.)**2) + (yct**2/(g_ell_height/2.)**2)

colors_array = []

for r in rad_cc:
    if r <= 1.:
        # point in ellipse
        colors_array.append('green')
    else:
        # point not in ellipse
        colors_array.append('black')

ax.scatter(x,y,c=colors_array,linewidths=0.3)

plt.show()

rawDescription: Check if points are inside ellipse faster than contains_point method


code:
import random
import numpy as np
from matplotlib import pyplot

points = [(random.random(), random.random()) for i in range(100)]

bx1, bx2 = sorted([random.random(), random.random()])
by1, by2 = sorted([random.random(), random.random()])

pts = np.array(points)
ll = np.array([bx1, by1])  # lower-left
ur = np.array([bx2, by2])  # upper-right

inidx = np.all(np.logical_and(ll <= pts, pts <= ur), axis=1)
inbox = pts[inidx]
outbox = pts[np.logical_not(inidx)]

# this is just for drawing
rect = np.array([[bx1, by1], [bx1, by2], [bx2, by2], [bx2, by1], [bx1, by1]])

pyplot.plot(inbox[:, 0], inbox[:, 1], 'rx',
            outbox[:, 0], outbox[:, 1], 'bo',
            rect[:, 0], rect[:, 1], 'g-')
pyplot.show()

rawDescription: numpy filter points within bounding box

description: Numpy filter points within bounding box


code: ".\n".join(i.strip() for i in a.split("."))

rawDescription: Python: sentence splitting produces a whitespace


code:
import random
def shuffle():
    aList = []
    i = 0
    for i in range(0, 5):
        elements = input(": ")
        aList.append(elements)
    random.shuffle(aList)
    return aList

rawDescription: Python shuffle list not working

description: Python shuffle list not working


code:
from tastypie.authorization import Authorization
from tastypie.exceptions import Unauthorized

class CustomUserAuthorization(Authorization):
    def read_list(self, object_list, bundle):
        # This you put your filter
        return object_list.filter(id=bundle.request.user.id)

    def read_detail(self, object_list, bundle):
        # This is to check the current user
        return bundle.obj.id == bundle.request.user.id

    def create_list(self, object_list, bundle):
        raise Unauthorized("Sorry, not allowed.")

    def create_detail(self, object_list, bundle):
        raise Unauthorized("Sorry, not allowed.")

    def update_list(self, object_list, bundle):
        raise Unauthorized("Sorry, not allowed.")

    def update_detail(self, object_list, bundle):
        # Only update your details
        return bundle.obj.id== bundle.request.user.id

    def delete_list(self, object_list, bundle):
        raise Unauthorized("Sorry, no deletes.")

    def delete_detail(self, object_list, bundle):
        raise Unauthorized("Sorry, no deletes.")

rawDescription: How do I limit the user API response to the current user with Django Tastypie?

description: Limit the user API response to the current user with Django Tastypie


code:
import subprocess
subprocess.check_output(["which", "test"])

rawDescription: Getting Location of Command in Popen

description: Getting Location of Command in Popen


code:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets

class MyFrame(QtWidgets.QFrame):
    def __init__(self, parent=None,initials=None):
        QtWidgets.QFrame.__init__(self, parent)
        self.table = QtWidgets.QTableWidget(5,3,self)
        self.table.move(30,30)
        self.table.resize(400,300)

        item1 = QtWidgets.QTableWidgetItem('red')
        item1.setBackground(QtGui.QColor(255, 0, 0))
        self.table.setHorizontalHeaderItem(0,item1)

        item2 = QtWidgets.QTableWidgetItem('green')
        item2.setBackground(QtGui.QColor(0, 255, 0))
        self.table.setHorizontalHeaderItem(1,item2)

        item3 = QtWidgets.QTableWidgetItem('blue')
        item3.setBackground(QtGui.QColor(0, 0, 255))
        self.table.setHorizontalHeaderItem(2,item3)

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle(QtWidgets.QStyleFactory.create('Fusion')) # won't work on windows style.
    Frame = MyFrame(None)
    Frame.resize(500,400)
    Frame.show()
    app.exec_()

rawDescription: Color individual horizontal headers of QTableWidget in PyQt


code:
from django.db.models import Count

Profile.objects.values('age').annotate(Count('age'))

Result: [{'age': 10, 'age__count': 52}, ...]

rawDescription: How to determine the count of distinct values in a Django model's field?

description: Determine the count of distinct values in a Django model's field


code:
def getForwardedSSHPort(self, tunnnelHostName):
    forwarderClient = self.getSSHConnection(tunnnelHostName, None)
    transport = forwarderClient.get_transport()
    dest_addr = ('169.254.1.2', 22)
    local_addr = ('127.0.0.1', 10022)
    channel = transport.open_channel('direct-tcpip', dest_addr, local_addr)

    remoteClient = self.getSSHConnection( tunnnelHostName, channel)

rawDescription: paramiko.Proxycommand fails to setup socket

description: Paramiko.Proxycommand fails to setup socket


code:
current_destination = CreateOutputDirectory()
for root, folders, files in os.walk(input_directory):
   for file in files:
       file_size = os.path.getsize(file)
       if os.path.getsize(current_destination) + file_size > limit:
          current_destination = CreateOutputDirectory()
       CopyFileToDirectory(root, file, current_destination)

rawDescription: In python, how do I copy files into a directory and stop once that directory reaches a certain size


code:
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/favicon.ico", tornado.web.ErrorHandler, {'status_code': 404}),
        (r".*", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

rawDescription: Python - Tornado : How to return 404 instead 500 for favicon


code: f[1, :, np.newaxis]

rawDescription: Matrix multiplying arrays with Numpy

description: Matrix multiplying arrays with Numpy


code:
def setquit():
    """Define new builtins 'quit' and 'exit'.

    These are objects which make the interpreter exit when called.
    The repr of each object contains a hint at how it works.

    """
    if os.sep == ':':
        eof = 'Cmd-Q'
    elif os.sep == '\\':
        eof = 'Ctrl-Z plus Return'
    else:
        eof = 'Ctrl-D (i.e. EOF)'

    class Quitter(object):
        def __init__(self, name):
            self.name = name
        def __repr__(self):
            return 'Use %s() or %s to exit' % (self.name, eof)
        def __call__(self, code=None):
            # Shells like IDLE catch the SystemExit, but listen when their
            # stdin wrapper is closed.
            try:
                sys.stdin.close()
            except:
                pass
            raise SystemExit(code)
    __builtin__.quit = Quitter('quit')
    __builtin__.exit = Quitter('exit')

rawDescription: difference between quit and exit in python

description: Difference between quit and exit in python


code:
class Example(object):
    def __init__(self):
        self.attribute_one = 1
        self.attribute_two = 'blah blah'
        ...
        self.attribute_large = very_large_object

    def __getstate__(self):
        d = self.__dict__
        self_dict = {k : d[k] for k in d if k != 'attribute_large'}
        return self_dict

    def __setstate__(self, state):
        self.__dict__ = state

rawDescription: Python - Saving Entire Class Object Except For A Large Attribute


code:
import matplotlib.pyplot as plt
import numpy as np
x, y = np.random.randint(1,51,10), np.random.randint(1,51,10)
width = 1e-2
for i in range(len(x)):
    plt.fill([10**(np.log10(x[i])-width), 10**(np.log10(x[i])-width), 10**(np.log10(x[i])+width), 10**(np.log10(x[i])+width)],[0, y[i], y[i], 0], 'r', alpha=0.4)
plt.bar(x,y, bottom = 0, log = True, linewidth=0, align="center",width=.1, alpha=0.4)

rawDescription: Bars width are wrong using log scale of x-axis


code:
import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level
                          # library

d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                # such key)
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = key in d        # true if the key exists
klist = list(d.keys()) # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]    # this works as expected, but...
d['xx'].append(3)      # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()       # close it

rawDescription: Remove or edit entry saved with Python pickle


code:
from enum import Enum
from collections import namedtuple

Color = namedtuple('Color', ['value', 'displayString'])

class Colors(Enum):

    @property
    def displayString(self):
        return self.value.displayString

    yellow = Color(1, 'Yellow')
    green = Color(2, 'Green')

print(Colors.yellow.displayString)

rawDescription: How to define custom properties in enumeration in Python (Javascript-like)

description: Define custom properties in enumeration in Python (Javascript-like)


code:
with open(file_path, 'rb') as f:
  content = f.read().replace('\\', '\\\\').replace('""', '\\"')
  reader = csv.reader(StringIO(content), doublequote=False, escapechar='\\')
  return [row for row in reader]

rawDescription: How to handle double quotes inside field values with csv module?

description: Handle double quotes inside field values with csv module


code:
import csv

with open('/home/tiwari/Desktop/names.csv', 'r+') as csvfile:
    reader = csv.DictReader(csvfile)

    rows = []
    for row in reader:
        if row['first_name'] == 'John':
            row['first_name'] = 'Jason'
            row['last_name'] = 'Statham'
        rows.append(row)

    csvfile.seek(0)  # back to begining of the file.
    fieldnames = ['first_name', 'last_name']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(rows)
    csvfile.truncate()  # In case of updated content is shorter.

rawDescription: Overwriting row in same csv file using dictwriter


code:
@classmethod
def make_from_post(cls, post):
    """ Create an object from another object, possibly of a slightly
    different class (like tree Post).  """
    data = {}
    for field in cls._meta.fields:
        if field.primary_key:
            continue
        # Assuming that all default fields for cls are None and thus
        # skipping 'None's from attribute values.
        attrdata = getattr(post, field.name, None)
        if attrdata is not None:
            data[field.name] = attrdata
    return cls(**data)

rawDescription: Multiple versions (revisions) of objects with django treebeard MP_Node Tree


code:
[x for x in range(5)]
x

rawDescription: Python list comprehension changes initial variable


code: (df.iloc[:, ::2].values * df.iloc[:, 1::2].values).sum()

rawDescription: how do I sum pairwise dot products of columns

description: Sum pairwise dot products of columns


code: lower_right_lat = lower_left_lat = min_lat

rawDescription: how to define same variable for two values using python

description: Define same variable for two values using python


code:
def empty(value):
    try:
        value = float(value)
    except ValueError:
        pass
    return bool(value)

rawDescription: How to check if a variable is empty in python?

description: Check if a variable is empty in python


code:
from operator import attrgetter

sorted_team_list = sorted(team_list, key=attrgetter('school'))
sorted_team_list = sorted(sorted_team_list, key=attrgetter('win_pct'), reverse=True)

rawDescription: Ascending/descending ordering of Django QuerySet when one attribute is a model method


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

def pcolormesh_45deg(C):

    n = C.shape[0]
    # create rotation/scaling matrix
    t = np.array([[1,0.5],[-1,0.5]])
    # create coordinate matrix and transform it
    A = np.dot(np.array([(i[1],i[0]) for i in itertools.product(range(n,-1,-1),range(0,n+1,1))]),t)
    # plot
    plt.pcolormesh(A[:,1].reshape(n+1,n+1),A[:,0].reshape(n+1,n+1),np.flipud(C))

rawDescription: Is there a way to rotate a matplotlib plot by 45 degrees?


code:
import numpy as np
a = np.arange(1,7)
a
np.add.outer(a,a)

rawDescription: How to use numpy to add any two elements in an array and produce a matrix?

description: Use numpy to add any two elements in an array and produce a matrix


code:
rec_lsts = orgi_dict['records']
new_dict = {}
for l_list in rec_lsts:
    new_dict[l_lst[0]] = l_lst[1:]

rawDescription: Dict containing keys with lists of lists


code: sorted(root, key=lambda x: x[0], reverse=True)

rawDescription: Sorting a meta-list by first element of children lists in Python


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

nsteps = 10000000
draws = np.random.randint(0,2,size=nsteps)
steps = np.where(draws>0,1,-1)
walk = steps.cumsum()
plt.plot(arange(nsteps), array(walk), 'r-')
plt.title("Big Set Random Walk with $\pm1$ steps")
plt.show()

rawDescription: matplotlib plot array size limit?

description: Matplotlib plot array size limit


code:
def create_or_update_and_get(model_class, data):
    get_or_create_kwargs = {
        model_class._meta.pk.name: data.pop(model_class._meta.pk.name)
    }
    try:
        # get
        instance = model_class.objects.get(**get_or_create_kwargs)
    except model_class.DoesNotExist:
        # create
        instance = model_class(**get_or_create_kwargs)
    # update (or finish creating)
    for key,value in data.items():
        field = model_class._meta.get_field(key)
        if not field:
            continue
        if isinstance(field, models.ManyToManyField):
            # can't add m2m until parent is saved
            continue
        elif isinstance(field, models.ForeignKey) and hasattr(value, 'items'):
            rel_instance = create_or_update_and_get(field.rel.to, value)
            setattr(instance, key, rel_instance)
        else:
            setattr(instance, key, value)
    instance.save()
    # now add the m2m relations
    for field in model_class._meta.many_to_many:
        if field.name in data and hasattr(data[field.name], 'append'):
            for obj in data[field.name]:
                rel_instance = create_or_update_and_get(field.rel.to, obj)
                getattr(instance, field.name).add(rel_instance)
    return instance

# for example:
from django.utils.simplejson import simplejson as json

data = json.loads(ninja_json)
ninja = create_or_update_and_get(NinjaData, data)

rawDescription: Most elegant approach for writing JSON data to a relational database using Django Models?


code:
def aftersubmit(self, response):
    hxs = Selector(response)

    item = AnItem()
    item['Name'] = "jsc"
    return item

rawDescription: Scrapy Not Returning After Yielding a Request


code:
import networkx
import pylab

#Build a graph (Node attribute 's' determines the node shape here)
G = networkx.Graph()
G.add_node(0, s="^", b=1)
G.add_node(1, s="^", b=2)

G.add_node(2, s="o", b=3)
G.add_node(3, s="o", b=4)

G.add_node(4, s="v", b=5)
G.add_node(5, s="v", b=6)

G.add_path([0,2,5])
G.add_path([1,4,3,0])
G.add_path([2,4,0,5])

#Drawing the graph
#First obtain the node positions using one of the layouts
nodePos = networkx.layout.spring_layout(G)

#The rest of the code here attempts to automate the whole process by
#first determining how many different node classes (according to
#attribute 's') exist in the node set and then repeatedly calling
#draw_networkx_node for each. Perhaps this part can be optimised further.

#Get all distinct node classes according to the node shape attribute
nodeShapes = set((aShape[1]["s"] for aShape in G.nodes(data = True)))

#For each node class...
for aShape in nodeShapes:
    #...filter and draw the subset of nodes with the same symbol in the positions that are now known through the use of the layout.
    networkx.draw_networkx_nodes(G,nodePos,node_shape = aShape, nodelist = [sNode[0] for sNode in filter(lambda x: x[1]["s"]==aShape,G.nodes(data = True))])

#Finally, draw the edges between the nodes
networkx.draw_networkx_edges(G,nodePos)

#And show the final result
pylab.show()

rawDescription: Set dynamic node shape in network with matplotlib


code:
import heapq, random
heapq.nlargest(3, (random.gauss(0, 1) for _ in xrange(100)))

rawDescription: Python: take max N elements from some list


code:
import Tkinter as TK

font = ('Times New Roman', 14, 'bold')
font2 = ('Times New Roman',12, 'bold')

class example3(TK.Toplevel):
    def __init__(self, parent):
        TK.Toplevel.__init__(self)
        self.geometry('380x100')
        self.parent=parent
        self.initalize()

    def initalize(self):
        self.grid()

        def restart():
            self.parent.do_restart = True
            self.parent.destroy()

        Yes = TK.Button(self, text = 'Yes', font = font2, command = restart)
        Yes.grid(column = 0, row = 0, sticky = 'we', padx = (10, 10))

class example2(TK.Toplevel):
    def __init__(self, parent):
        TK.Toplevel.__init__(self)
        self.geometry('770x150')
        self.parent = parent
        self.initalize()

    def initalize(self):
        self.grid()

        #Creates Label Frame
        MstepOne = TK.LabelFrame(self, font = font2)
        MstepOne.grid(row=0, columnspan=7, sticky='w', padx=5, pady=5, ipadx=5, ipady=5)

        def gatherinfo2():
            #self.destroy() #Not sure why your do this
            example3(self.parent) # You need to pass self.parent here

        #Creates Label
        MLabel1 = TK.Label(MstepOne, text = "First Name", font = font)
        MLabel1.grid(column = 2, row = 0, sticky = 'w', padx = (10, 10))
        MLabel2 = TK.Label(MstepOne, text = "Last Name", font = font)
        MLabel2.grid(column = 4, row = 0, sticky = 'w', padx = (10, 10))

        #Creates Button
        MSubmit = TK.Button(self, text = 'Submit', font = font2, command = gatherinfo2)
        MSubmit.grid(column = 3, row = 3, sticky = 'we', padx = (10, 10))

class example(TK.Tk):
    def __init__(self, parent):
        TK.Tk.__init__(self, parent)
        self.parent = parent
        self.do_restart=True
        self.initialize()

    def initialize(self):
        self.grid()

        def gatherinfo():
            example2(self)

        def terminate(event=None):
            self.do_restart = False
            self.destroy()

        self.bind("<Escape>", terminate) # Press ESC to escape the program
        MSubmit = TK.Button(self, text = 'Submit', font = font2, command = gatherinfo)
        MSubmit.grid(column = 3, row = 3, sticky = 'we', padx = (10, 10))

def main():
    do_loop = True        # Loop so we can restart the program if not terminating it
    while do_loop:
        app = example(None)
        app.geometry('400x400')
        app.mainloop()
        do_loop = app.do_restart # Gets if we should restart or terminate
        if do_loop:
            print("Restarting")
        else:
            print("Terminating")

if __name__ == '__main__':
    main()

rawDescription: How to Quit Current Program and recreate the original Gui? Also creating a secret code to close program


code:
from os.path import dirname, join
myfile = open(join(dirname(__file__), "mydatafile.txt"))

rawDescription: Text file not openable in custom module

description: Text file not openable in custom module


code:
with open('test.txt', 'r') as f1, open('test.txt', 'r') as f2:
    for l1 in f1:
        for l2 in f2:
            process(l1, l2)
        f2.seek(0)

rawDescription: Read one file at two different positions simultaneously?


code:
def hashing(header_hash, signature, hash_size):
     for index, i in enumerate(xrange(len(signature), hash_size)):
          header_hash['Some-Authorization-%s' % index] = signature[i:i+hash_size]

rawDescription: Elegant way of chunking data

description: Elegant way of chunking data


code:
import pandas as pd
dataframe1 = pd.DataFrame(dict([(k,pd.Series(v)) for k,v in my_dict.iteritems()]))

rawDescription: Creating a panda DataFrame from dictionary with multiple keys and value (list) of different lengths


code:
def fchar(ch,mi):
    global numLi
    fc=ch
    li=""
    for c in infected[mi:]:
        if fc==c :
            li+=fc
            mi = mi+1
        else:
            break

    if mi<len(infected) :
        return li+" "+fchar(infected[mi],mi)
    else:
        return li

infected =input("Enter DNA sequence\n") ;#"AAATTTTTTTTGCCCCCCA"
x=fchar(infected[0],0)
newSet = x.split(' ')
print(newSet)

rawDescription: How to split a string into parts that each part contains only same characters in python

description: Split a string into parts that each part contains only same characters in python


code:
#!/usr/bin/env python3

import sys
import time

data = "this is a sentence with some words".split()

max_len=max([len(w) for w in data])
pad = " "*max_len
for w in data:
    sys.stdout.write('%s\r' % pad)
    sys.stdout.write("%s\r" % w)
    sys.stdout.flush()
    time.sleep(0.4)

print

rawDescription: How to print one word at a time on one line?

description: Print one word at a time on one line


code:
class WithState(models.Manager):
    def get_query_set(self):
        return super(WithState, self).get_query_set().select_related('state')

class City(models.Model):
    name = models.CharField(max_length=100)
    state = models.ForeignKey(State)
    objects = WithState()

    def __unicode__(self):
        return u'(%s) %d. %s' % (self.state.name, self.id, self.name)

rawDescription: Best method to add foreign key to Django model's unicode output


code:
from tkinter import *
root = Tk()

def make_label(master, x, y, h, w, *args, **kwargs):
    f = Frame(master, height=h, width=w)
    f.pack_propagate(0) # don't shrink
    f.place(x=x, y=y)
    label = Label(f, *args, **kwargs)
    label.pack(fill=BOTH, expand=1)
    return label

make_label(root, 10, 10, 10, 40, text='xxx', background='red')
make_label(root, 30, 40, 10, 30, text='xxx', background='blue')

root.mainloop()

rawDescription: Label width in tkinter

description: Label width in tkinter


code:
from datetime import datetime
from urllib.request import urlretrieve
from urllib.parse import urljoin

import requests
from lxml import etree
from lxml import html

date_part = datetime.now().strftime("%Y-%m")
with requests.Session() as session:
    # get the XML feed and extract the link
    response = session.get("https://www.cms.gov/Research-Statistics-Data-and-Systems/Statistics-Trends-and-Reports/MCRAdvPartDEnrolData/Monthly-Enrollment-by-Contract-Plan-State-County-DL.xml")
    root = etree.fromstring(response.content)
    link = root.xpath("//item/link[contains(., '-%s.html')]/text()" % date_part)[0]

    # follow the link and extract the link to the zip file
    response = session.get(link)
    root = html.fromstring(response.content)
    zip_link = root.xpath("//a[@type='application/zip']/@href")[0]
    link = urljoin(link, zip_link)

    # download zip
    urlretrieve(link, filename="my.zip")

rawDescription: Python Requests Go to Link and Download

description: Python Requests Go to Link and Download


code: s = 'This is string : %d' % (page + 1,)

rawDescription: Can we get the following flexibility in Python as In Perl


code:
condition1 = "((2=2) or (3=1)) and (1=1)"
eval(condition1.replace('=','=='))
eval(condition2.replace('=','=='))

rawDescription: Get conditional string return value : True or False


code:
def get_string(idxlist, item_list):
    return ''.join([item_list[i] for i in idxlist])

def increment_vector(idxlist, max_count):
    idxlist[0] += 1
    for i in xrange(len(idxlist)-1):
        if idxlist[i] < max_count:
            break
        idxlist[i]=0
        idxlist[i+1] += 1

def generate(n, item_list):
    max_count = len(item_list)

    idxlist = [0] * n
    while idxlist[-1] < max_count:
        print ( get_string( idxlist, item_list )),
        increment_vector(idxlist, max_count)
        if idxlist[0]==0:
            print

item_list = map(chr, range(97, 123)) # letters from a-z

generate(3, item_list)

rawDescription: python - get all possible combinations with replacement without recursion

description: Python - get all possible combinations with replacement without recursion


code:
import numpy as np; from mayavi import mlab
data = np.random.random((100,100))
mlab.surf(data)
mlab.show()

rawDescription: How to display a float matrix as elevation values in a 3D plot in Python?

description: Display a float matrix as elevation values in a 3D plot in Python


rawDescription: How to find all terms in an expression in Sympy

description: Find all terms in an expression in Sympy


code:
from datetime import datetime

time_obj1 = datetime.strptime(time1, '%I:%M %p')
time_obj2 = datetime.strptime(time2, '%I:%M %p')

if time_obj1 > time_obj2:
    ...

rawDescription: Convert part of string to integer

description: Convert part of string to integer


code:
pl.figure(figsize=(12, 6))
pl.subplot(1, 2, 1)
for axeid in (3, 4, 7, 8):
    pl.subplot(2, 4, axeid)

rawDescription: Arranging matplotlib subplots into subgrids


code:
startyear = 2014
startmonth = 4
endyear = 2015
endmonth = 2
[datetime.date(m/12, m%12+1, 1) for m in xrange(startyear*12+startmonth-1, endyear*12+endmonth)]

rawDescription: Python list of first day of month for given period


code:
with open('myschema.sql') as fp:
    cur.executescript(fp.read())  # or con.executescript

rawDescription: How to create a db file in sqlite3 using a schema file from within python

description: Create a db file in sqlite3 using a schema file from within python


code:
red = fiona.open("shapefiles/miniRedVial.shp")  # loads road network
puntos = fiona.open("shapefiles/datosgps.shp")  # loads points

# open points with shapely and fiona
Multipoints = MultiPoint([shape(point['geometry']) for point in fiona.open("shapefiles/datosgps.shp")])
# open road network with shapely and fiona
Multilines = MultiLineString([shape(line['geometry']) for line in fiona.open("shapefiles/miniRedVial.shp")])
# open buffered points with shapely and fiona
Polygons = MultiLineString([list(shape(pol['geometry']).exterior.coords) for pol in fiona.open("shapefiles/testBuffer.shp")])

# create list where I'll save the intersections
listaCalles = []

for i in range(0, len(Polygons)):
    for j in range(0, len(Multilines)):
        if Polygons[i].intersection(Multilines[j]):
            idPunto = puntos[i].get("id")
            latPunto = puntos[i].get("properties").get("LATITUDE")
            lonPunto = puntos[i].get("properties").get("LONGITUDE")
            idCalle = red[j].get("id")
            nombreCalle = red[j].get("properties").get("NOMBRE")
            distPuntoCalle = Multilines[j].distance(Multipoints[i])
            listaCalles.append((idPunto, latPunto, lonPunto, idCalle, nombreCalle, distPuntoCalle))

rawDescription: Python - Getting attributes from Line contained in a MultiLineString shapefile that intersects a Polygon


code: item['pcode'] = ' '.join(hxs.select('//*[@id="ctl00_ContentPlaceHolder1_hid_ProductID"]/@value').extract()).strip()

rawDescription: not able to extract content from span using scrapy

description: Not able to extract content from span using scrapy


code:
def search(event=None):
    ...

bttn = Button(..., command=search)
...
entr.bind('<Return>', search)

rawDescription: Bind or Command to get return and button to work


code:
from somewhere import imported_function

@patch(imported_function)
def test_function_to_be_tested(self, imported_function):
    imported_function.return_value = True
    #Your test

rawDescription: Monkey patch a function in a module for unit testing


code:
from io import BytesIO
from xml.etree import ElementTree as ET

document = ET.Element('outer')
node = ET.SubElement(document, 'inner')
et = ET.ElementTree(document)

f = BytesIO()
et.write(f, encoding='utf-8', xml_declaration=True)
print(f.getvalue())  # your XML file, encoded as UTF-8

rawDescription: How to write XML declaration using xml.etree.ElementTree

description: Write XML declaration using xml.etree.ElementTree


code:
df = pd.DataFrame(columns = ['COL1', 'COL2'])
df.ix['test1'] = [20, 30]
df

rawDescription: how to add new record to pandas dataframe

description: Add new record to pandas dataframe


code:
mask = (array2 != 255)
result = array1.copy()
result[mask] += array2[mask]
print(result)

rawDescription: Python merge two arrays based on specific value


code:
def my_decorator(method):
    def redefined_method(*args, **kwargs):
        print('Starting decorator')
        method(args, **kwargs)
        # here ^, no star!
    return redefined_method

rawDescription: Decorating a Python method already decorated with @classmethod which calls another @classmethod


code:
from glob import glob
file = open(glob('report *')[0])

rawDescription: How to know which file to open (and open it) in Python based on its name matching a pattern?

description: Know which file to open (and open it) in Python based on its name matching a pattern


code:
m = re.search(r"(?<=address_is_after_)\d+|\d+(?=_address_is_before)",text)
m.group(0)

rawDescription: python regex for conditional (|) matching

description: Python regex for conditional (|) matching


code:
a = ["question1", "question2", "question3", "question4", "question5"]
b = ["php html", "html", "html", "java", "php"]
merged = zip(a, b)
merged[0:2]

rawDescription: Python how to get a subset of a two-dimensional array?


code:
df['Date'] + ' ' + df['Time']
pd.to_datetime(df['Date'] + ' ' + df['Time'])

rawDescription: Combine Date and Time columns using python pandas


code:
class IndexHandler(tornado.web.RequestHandler):
    @tornado.gen.coroutine
    def get(self):
        self.write("Kingsoft API.")
        k = yield self.fn(2)
        self.write(k)

    @tornado.gen.coroutine
    def fn(self, arg):
        k = 2 * arg
        raise tornado.gen.Return(k)

rawDescription: Does python tornado RequestHandler coroutine safe?


code:
import wx
global btn
def updater():
    p = btn.GetPosition()
    btn.SetPosition((p[0] ,p[1] - 2))
    wx.CallLater(50,updater)
a= wx.App(redirect=False)

f = wx.Frame(None,-1,"Animation",size=(400,600))
p = wx.Panel(f,-1)
btn = wx.Button(p,-1,"Click Me",pos=(175,520))
f.Show()
wx.CallLater(50,updater) #could have used a normal timer just as easy ... maybe even easier
a.MainLoop()

rawDescription: wxPython Animation - Tween Animation

description: WxPython Animation - Tween Animation


code:
bits = []
min_address = False
for row in ws.iter_rows(row_offset=4,column_offset=3):
    c = row[2]
    d = row[3]
    if not d.internal_value: #d will always have a value if the row isn't blank
        if min_address:
            break #bits is what you want it to be now
        bits = [] #reset bits every time we hit a new row
        continue #this will just skip to next row

    for bits_cell in row[4:]:
        if bits_cell.internal_value:
            bits.append(bits_cell.internal_value)
    if c.internal_value:
        if c.internal_value == min(address):
            min_address = True #we set it to true, then kept going until blank row

rawDescription: Move to adjacent cells using openpyxl

description: Move to adjacent cells using openpyxl


code:
mvprintw(COLS-length("msg"),1,"msg");
mvprintw(0,LINES-1,"message number 2");
mvprintw(COLS-length("here is more"),LINES-1,"here is more");

rawDescription: printing to right side or bottom side of terminal using (n)curses

description: Printing to right side or bottom side of terminal using (n)curses


code:
from django.db import transaction

@transaction.commit_manually()
def add_points(request):
    user = User.objects.select_for_update().get(id=request.user.id)
    # you can go back at this point if something is not right
    if user.points > 1000:
        # too many points
        return
    user.points += calculate_points(user)
    user.save()
    transaction.commit()

rawDescription: Race conditions in django

description: Race conditions in django


code:
client = gdata.youtube.service.YouTubeService()
video = client.GetYouTubeVideoEntry(video_id='CoYBkXD0QeU')
video.author[0].name.text

rawDescription: Extracting YouTube Video's author using Python and YouTubeAPI


code: result = min(max_value, max(min_value, result))

rawDescription: Most Pythonic way to fit a variable to a range?


code: variables = {'VarX': 700}

rawDescription: Add variable name to variable

description: Add variable name to variable


code: re.findall("a+", 'sdaaddaa')

rawDescription: python regular expressions to return complete result

description: Python regular expressions to return complete result


code:
from scipy.misc import imread
img = imread("test.jpg")
img.flatten()

rawDescription: flattening an rgb image in python

description: Flattening an rgb image in python


code:
import tty
import sys
import termios

orig_settings = termios.tcgetattr(sys.stdin)

tty.setraw(sys.stdin)
x = 0
while x != chr(27): # ESC
    x=sys.stdin.read(1)[0]
    print("You pressed", x)

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)

rawDescription: What is the easiest way to detect key presses in python 3 on a linux machine?


code:
import pandas as pd

df1 = pd.DataFrame({
    "Name" : ["Dave", "Bill", "Sean"],
    "Pos" : ['QB', 'QB', 'QB'],
    "Opponent" : ["DEN", "GB", "DET"],
    "DPAvPos": ["NaN", "NaN", "NaN"]
})

df2 = pd.DataFrame({
    "Name" : ["DET", "DEN", "GB"],
    "DKP/Game" : [ 20.1, 23, 21]
})

df2.rename(columns={"Name" : "Opponent"}, inplace=True)
df3 = pd.merge(df1, df2, on="Opponent")
df3.drop('DPAvPos', axis=1, inplace=True)
df3.rename(columns={"DKP/Game" : "DPAvPos"}, inplace=True)

rawDescription: How to move data from one dataframe to another based on matching column values with pandas?

description: Move data from one dataframe to another based on matching column values with pandas


code:
session.query(Product).join(User.addresses)\
    .options(subqueryload(Product.orders),\
             subqueryload(Product.tags)).all()

rawDescription: SQLAlchemy eager loading multiple relationships


code:
from functools import partial
g = partial(f, const1=const1, const2=const2)

rawDescription: Create a Function of a Single Variable in Python from a Function of many


code:
t1.join()
t2.join()

rawDescription: Threading and Queues in Python3: sentinel value in input_queue fails to break out of while loop


code:
class MyForm(...):
    readonly_fields = ("afield", "another",)
    def __init__(self, *args, **kw):
         super(MyForm, self).__init__(*args, **kw)
         for field in self.readonly_fields:
             self.fields[field].widget.attrs['readonly']
             def clean(field=field):
                 # assume fieldname == instance attribute name
                 return getattr(self.instance, field)
             setattr(self, "clean_%s" % field, clean)

rawDescription: Dynamically create clean_* methods for readonly fields in Django forms


code:
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

x = np.random.randint(0, 500, 100000)
y = np.random.randn(100000)

# definitions for the axes
left, width = 0.1, 0.65
bottom, height = 0.1, 0.65
bottom_h = left_h = left + width + 0.02

rect_scatter = [left, bottom, width, height]
rect_histx = [left, bottom_h, width, 0.2]
rect_histy = [left_h, bottom, 0.2, height]

fig = plt.figure(1, figsize=(5.5,5.5))

axScatter = plt.axes(rect_scatter)
axHistx = plt.axes(rect_histx)
axHisty = plt.axes(rect_histy)

# the scatter plot:
axScatter.scatter(x, y)

binwidth = 0.25
xymax = np.max( [np.max(np.fabs(x)), np.max(np.fabs(y))] )
lim = ( int(xymax/binwidth) + 1) * binwidth

axScatter.set_xlim((0, lim))
axScatter.set_ylim((-5, 10))       # <-- controls y axis. Values should be calculated.

bins = np.arange(-lim, lim + binwidth, binwidth)
axHistx.hist(x, bins=bins)
axHisty.hist(y, bins=bins, orientation='horizontal')

axHistx.set_xlim(axScatter.get_xlim())
axHisty.set_ylim(axScatter.get_ylim())

#axHistx.axis["bottom"].major_ticklabels.set_visible(False)
for tl in axHistx.get_xticklabels():
    tl.set_visible(False)
axHistx.set_yticks([0, 50, 200])

#axHisty.axis["left"].major_ticklabels.set_visible(False)
for tl in axHisty.get_yticklabels():
    tl.set_visible(False)
axHisty.set_xticks([0, 10000, 20000])

plt.show()

rawDescription: subplot size python

description: Subplot size python


code:
import operator

def mergeiter(*iterables, **kwargs):
    """Given a set of sorted iterables, yield the next value in merged order

    Takes an optional `key` callable to compare values by.
    """
    iterables = [iter(it) for it in iterables]
    iterables = {i: [next(it), i, it] for i, it in enumerate(iterables)}
    if 'key' not in kwargs:
        key = operator.itemgetter(0)
    else:
        key = lambda item, key=kwargs['key']: key(item[0])

    while True:
        value, i, it = min(iterables.values(), key=key)
        yield value
        try:
            iterables[i][0] = next(it)
        except StopIteration:
            del iterables[i]
            if not iterables:
                raise

rawDescription: Sorting text file by using Python

description: Sorting text file by using Python


code:
extras_require = dict(
    parallel = [pyzmq],
    qtconsole = [pyzmq, 'pygments'],
    doc = ['Sphinx>=1.1', 'numpydoc'],
    test = ['nose>=0.10.1', 'requests'],
    terminal = [],
    nbformat = ['jsonschema>=2.0'],
    notebook = ['tornado>=4.0', pyzmq, 'jinja2', 'pygments', 'mistune>=0.5'],
    nbconvert = ['pygments', 'jinja2', 'mistune>=0.3.1']
)

rawDescription: Optional install with pip - ipython example


code:
df2[list('xab')]  # df2 but only with columns x, a, and b

df1.merge(df2[list('xab')])

rawDescription: Python Pandas merge only certain columns


code:
try:
    folder = os.stat("My Stock Data/")
except:
    folder = os.mkdir("My Stock Data/")

for stock in stocks:
    print(stock)
    filename, headers = pulldata(stock, "My Stock Data/" + stock + "-data.csv")

print("Done")

rawDescription: Grabbing stock data from a list

description: Grabbing stock data from a list


code:
from pymongo import MongoClient
cl = MongoClient()
coll = cl["local"]["test2"]

data = [{"_id" : 1, "foo" : "HELLO"}, {"_id" : 2, "Blah" : "Bloh"}]
for d in data:
    coll.update({'_id':d['_id']}, d, True)

rawDescription: Python - Pymongo Insert and Update Documents


code:
import sys
import numpy
import cv
import cv2
from cStringIO import StringIO
from PIL import Image

out_video = cv2.VideoWriter()
fourcc = cv.CV_FOURCC('D', 'I', 'V', 'X')
fps = 30
color = True

size = None
for fname in sys.argv[2:]:
    data = open(fname).read() # Your String

    s = StringIO(data)
    img = Image.open(s)
    if size and img.size != size:
        img = img.resize(size)
    else:
        size = img.size
        out_video.open(sys.argv[1], fourcc, fps, size, color)
    out_video.write(cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR))

rawDescription: OpenCV Python bindings: How do I capture an image from memory


rawDescription: QString: Unicode encoding-decoding problem


code:
def find_segment(self):
    '''Finds the possible segments that correspond to the
       transaction code.
    '''
    with open("transactioncodes.txt", 'r') as _file:
        for line in _file:
            if line.startswith(self._transaction_code):
                return line[len(self._transaction_code):line.rfind("-")]
    return ""

rawDescription: Python Find Method in Strings Seems To Be Failing


code:
def sieve(n):
    m = (n-1) // 2
    b = [True]*m
    i,p,ps = 0,3,[2]
    while p*p < n:
        if b[i]:
            ps.append(p)
            j = 2*i*i + 6*i + 3
            while j < m:
                b[j] = False
                j = j + 2*i + 3
        i+=1; p+=2
    while i < m:
        if b[i]:
            ps.append(p)
        i+=1; p+=2
    return ps

rawDescription: Python Eratosthenes Sieve Algorithm Optimization


code:
import Image
import ImageDraw

imsize = 400
img = Image.new("L", (imsize,imsize), "white")
draw = ImageDraw.Draw(img)

coords = [(100,70), (220, 310), (200,200), (80,20)]
dotSize = 50

for (x,y) in coords:
    draw.rectangle([x,y,x+dotSize-1,y+dotSize-1], fill="black")

## mirror image along the diagonal
img2 = img.rotate(90).transpose(Image.FLIP_TOP_BOTTOM)

## mask
mask = Image.new("L", (imsize,imsize), "black")
maskdraw = ImageDraw.Draw(mask)
# draw a triangle on the mask dividing the image along the diagonal
maskdraw.polygon([(0,0),(0,imsize),(imsize,imsize)], fill="white")

# show the mask overlaid on the original image
Image.blend(mask, img, 0.5).show()

# compute and show the blended result
img3 = Image.composite(img, img2, mask)
img3.show()

rawDescription: PIL mirror image coodinates

description: PIL mirror image coodinates


code:
code_lengths = {'US':9, 'Canada':10}
df['correct_code_length'] = df.Country.replace(code_lengths)
df['is_correct'] = (df.Code1.apply(lambda x: len(str(x))) == df.correct_code_length) | (df.Code2.apply(lambda x: len(str(x))) == df.correct_code_length)

rawDescription: How to compare values in pandas between two different columns?

description: Compare values in pandas between two different columns


code:
fig = plt.figure()
ax = fig.gca(projection='3d')
z = np.array([1.0 for point in x])
for n, armonic in enumerate(func_list):
    ax.plot(x, armonic, z*n, label='armonic{}'.format(n))
ax.legend()
plt.show()

rawDescription: Plotting multiple 2d curves with matplotlib in 3d


code: os.makedirs(log_dir, 0o664)

rawDescription: (pre)cursive chmod on created directory in Python


code:
projection = ccrs.epsg(32636)
fig, ax = plt.subplots(figsize=(5, 5),
                      subplot_kw=dict(projection=projection))
ax.coastlines(resolution='10m')

rawDescription: Overlay coastlines on a matplotlib plot

description: Overlay coastlines on a matplotlib plot


rawDescription: reliably show matplotlib (0.99 to 1.3.1) figures without blocking

description: Reliably show matplotlib (0.99 to 1.3.1) figures without blocking


code:
from operator import add
map(add, list1,list2)

rawDescription: python: pointwise list sum

description: Python: pointwise list sum


code:
def price(*opts):
    return sum(o[1] for o in opts)

exact_matches = [combo for combo in itertools.product(opt1,opt2,opt3,opt4) if price(*combo) == target]
cheaper_matches = [combo for combo in itertools.product(opt1,opt2,opt3,opt4) if price(*combo) < target]

rawDescription: Permutation/Combination in Python

description: Permutation/Combination in Python


code: [item for item in a if item not in b]

rawDescription: find if any element of list is in another list

description: Find if any element of list is in another list


code:
import sys
if sys.version_info[0] == 2:
   def open_text(filename):
       return open(filename, 'rU')
else:
   def open_text(filename):
       return open(filename, 'r', newline=None)

rawDescription: Elegant way to handle Python file read option rU in both py2 and py3


code:
from lxml import etree

contacts = etree.parse(open("1234.xml"))

for c in contacts.xpath('//contact'):
    if c.xpath('/name')[0].text == 'Johnny Appleseed':
        c.xpath('/phone')[0].text = NEW_PHONE_NUMBER

print >> open("1234.xml", "w"), etree.tostring(contacts)

rawDescription: Confused by which XML processing option to use


code:
def grouper(my_list):
    previous, temp, result = my_list[0], [my_list[0]], []
    for number in my_list[1:]:
        if number - previous > 65:
            result.append(temp)
            temp, previous = [number], number
        else:
            temp.append(number)
    if temp:
        result.append(temp)
    return result

assert(grouper([43, 83, 90, 250, 265, 500]) == [[43, 83, 90], [250, 265], [500]])
assert(grouper([15, 43, 83, 90]) == [[15, 43], [83, 90]])

rawDescription: number of sequences in a list

description: Number of sequences in a list


code:
from .a import A1, A2
from .b import B1, B2, B3
from .c import C

rawDescription: Exposing some Python classes without coupling to file structure


code:
class App (object):
  # ...
  def status_line (self, frame):
    statusline = Tkinter.Label(frame, textvariable = self.status)
    statusline.pack()
  # ...

class App_Menu(object):
  def __init__(self, master, text, status):
    # ...
    self.status = status

  # ...
  def load(self):
    self.file=tkFileDialog.askopenfile()
    self.text.delete(1.0, Tkinter.END)
    if self.file:
      self.text.insert(1.0,self.file.read())
      self.status.set("file loaded")

root = Tkinter.Tk()
status = Tkinter.StringVar(root)
status.set("status")

rawDescription: Python Tkinter: How to get status message about menu action?


code:
a=np.random.random(100)*0.5 #a uniform distribution
b=1-np.random.normal(size=100)*0.1 #a normal distribution
bins=np.histogram(np.hstack((a,b)), bins=40)[1] #get the bin edges
plt.hist(a, bins)
plt.hist(b, bins)

rawDescription: Matplotlib: How to make two histograms have the same bin width?


code: curl.setopt(pycurl.USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0) Gecko/20100101 Firefox/8.0')

rawDescription: Access denied to a website using tor

description: Access denied to a website using tor


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle

xs = np.linspace(0, 100, 51)
ys = np.linspace(0, 10, 21)
ax = plt.gca()
# grid "shades" (boxes)
w, h = xs[1] - xs[0], ys[1] - ys[0]
for i, x in enumerate(xs[:-1]):
    for j, y in enumerate(ys[:-1]):
        if i % 2 == j % 2: # racing flag style
            ax.add_patch(Rectangle((x, y), w, h, fill=True, color='#008610', alpha=.1))
# grid lines
for x in xs:
    plt.plot([x, x], [ys[0], ys[-1]], color='black', alpha=.33, linestyle=':')
for y in ys:
    plt.plot([xs[0], xs[-1]], [y, y], color='black', alpha=.33, linestyle=':')
plt.show()

rawDescription: Plotting a grid with Matplotlib

description: Plotting a grid with Matplotlib


code:
df
df['Title'] = df['Title'].fillna(1 - df['Idx'])
df

rawDescription: How to substitute NaN values of a column based on the values of another column?

description: Substitute NaN values of a column based on the values of another column


code:
def clearsublists(L):
    return [clearsublists(l) for l in L if isinstance(l, list)]

rawDescription: Clearing all elements from all arbitrary lists of sublists in python


code:
from google.appengine.ext import testbed, ndb

class User(ndb.Model):
    name = ndb.TextProperty()
    foo = None

class TestNDBModel(object):

    def setup(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_memcache_stub()

    def teardown(self):
        self.testbed.deactivate()

    def test_foo(self):
        user = User(name='Andy')
        assert user.name == 'Andy'
        assert user.foo is None
        user.foo = 123
        assert user.foo == 123

        # This prevents the entity to be cached
        user_key = user.put(use_cache=False, use_memcache=False)

        # The entity is now retrieved from DB
        retrieved_user = user_key.get()

        # These two will now pass
        assert retrieved_user is not user
        assert retrieved_user.foo is None

rawDescription: How to Clear/Invalidate NDB Cache in Tests

description: Clear/Invalidate NDB Cache in Tests


code: data[(data['column2'] == "aa1") & (data['column4'] == 21)]

rawDescription: Get data from one column based on another using Python


code:
your_string = "This is a string"
list_of_words = your_string.split()
next_word = list_of_words[list_of_words.index(your_search_word) + 1]

rawDescription: How to find word next to a word in Python

description: Find word next to a word in Python


code: tags = [x.strip() for x in input.split(',') if x and not x.isspace()]

rawDescription: Can this Python list comprehension expression be simplified?


rawDescription: Flatten a tuple of unknown length

description: Flatten a tuple of unknown length


code:
def replace_1(bad:str, good:str) -> bool:
    """Return True if bad can be converted to good by replacing 1 letter.
    """
    if len(bad) != len(good):
        return False

    changes = 0
    for i,ch in enumerate(bad):
        if ch != good[i]:
            return bad[i+1:] == good[i+1:]

    return False

def insert_1(bad:str, good:str) -> bool:
    """Return True if bad can be converted to good by inserting 1 letter.
    """
    if len(bad) != len(good) - 1:
        return False

    for i,ch in enumerate(bad):
        if ch != good[i]:
            return bad[i:] == good[i+1:]

    # At this point, all of bad matches first part of good. So it's an
    # append of the last character.
    return True

def delete_1(bad:str, good:str) -> bool:
    """Return True if bad can be converted to good by deleting 1 letter.
    """
    if len(bad) != len(good) + 1:
        return False
    return insert_1(good, bad)

def correction(word:str, correct_spells:list) -> str:
    if len(word) < 3:
        return word
    if word in correct_spells:
        return word
    for good in correct_spells:
        if replace_1(word, good):
            return good
        if insert_1(word, good):
            return good
        if delete_1(word, good):
            return good

    return word

def spelling_corrector(sentence:str, correct_spells:list) -> str:
    words = sentence.strip().lower().split()
    correct_lower = [cs.lower() for cs in correct_spells]
    result = [correction(w, correct_lower) for w in words]
    return ' '.join(result)

tests = (
    ('Thes is the Firs cas', "that first case car", 'thes is the first case'),
    ('programming is fan and easy', "programming this fun easy hook", 'programming is fun and easy'),
    ('Thes is vary essy', "this is very very easy", 'this is very easy'),
    ('Wee lpve Python', "we Live In Python", 'we live python'),
)

if __name__ == "__main__":
    for t in tests:
        correct = t[1].split()
        print(t[0], "|", t[1], "|", t[2])
        print("Result:", spelling_corrector(t[0], correct))
        assert spelling_corrector(t[0], correct) == t[2]

rawDescription: Write a function named spelling_corrector.


code:
def f():
    return {'a' : 1, 'b' : 2}

def g():
    return dict(a=1, b=2)

g()
f()
import dis
dis.dis(f)
dis.dis(g)

rawDescription: What's the difference between dict() and {}?


code:
def countA(word):
    return word.count('a')

rawDescription: Counting letters in a string with python


code:
req_data = 'someting'

try:
    with open( 'counter.txt', 'r' ) as fle:
        counter = int( fle.readline() ) + 1
except FileNotFoundError:
    counter = 0

with open( 'data/{}'.format(counter), 'w' ) as fle:
    fle.write( req_data )

with open( 'counter.txt', 'w' ) as fle:
    fle.write( str(counter) )

rawDescription: Read and increment counter in file using Python 3


code:
#!/usr/bin/python

import sys

saved_stdin = sys.stdin
sys.stdin = open('/dev/tty', 'r')
result = raw_input('Enter something: ')
sys.stdout.write('Got: ' + result + '\n')
sys.stdin = saved_stdin
result2 = sys.stdin.read()
sys.stdout.write('Also got: ' + result2)

rawDescription: Pipes and prompts in Python CLI scripts

description: Pipes and prompts in Python CLI scripts


code:
s = s.replace("z", "s")
s.split("s")

rawDescription: String splitting in Python

description: String splitting in Python


code:
import xlsxwriter

workbook  = xlsxwriter.Workbook('file.xlsx')
worksheet = workbook.add_worksheet()

data = [13, 24, 15]

for row_num, value in enumerate(data):
    worksheet.write(row_num, 0, value)

row_num += 1
worksheet.write(row_num, 0, '=SUM(A1:A{})'.format(row_num))

workbook.close()

rawDescription: How to determine last row populated for a certain column in xlsxwriter?

description: Determine last row populated for a certain column in xlsxwriter


code:
def function(number):
    x = 1
    while x <= number:
        x *= 2
    return x / 2

rawDescription: Defining function with an argument, employs while loop and returns largest power of 2 that is less than or equal to number


code:
from itertools import product
l = [[0, 3], [1, 4], [2]]

for prod in product(*l):
    print(prod)

rawDescription: Print Combination in an 2D array in python


code: grid = [[0 for col in xrange(w)] for row in xrange(h)]

rawDescription: list (mis?) comprehension in Python2.7 for rows and columns

description: List (mis?) comprehension in Python2.7 for rows and columns


code:
self.sizerTopRight.Hide(self.grid)
self.sizerTopRight.Add(self.new_grid, 1)
self.sizerTopRight.Show(self.new_grid)
self.Layout()

rawDescription: wxPython Reload a grid in a panel

description: WxPython Reload a grid in a panel


code:
import datetime as DT
if (created_date + DT.timedelta(days=30)) < DT.datetime.now():
    print('valid')
else:
    print('expired')

rawDescription: Add and Compare Datetime in Python

description: Add and Compare Datetime in Python


rawDescription: Create save filenames from userinput in Python


code: df = df[~df['MY STATE'].isin(states['Abbreviation'].values)]

rawDescription: Deleting pandas dataframe rows if value in given column not contained in a list


code:
def order_by_score(self):
    q = django.db.models.Q(ratings__score=1)
    documents_with_one_positive_rating = self.filter(q) # Annotation sees only
                                                        # the positive ratings
    documents_without_one_positive_rating = self.filter(~q)

    return (documents_with_one_positive_rating |
            documents_without_one_positive_rating).annotate(
                db_score=django.db.models.Count('ratings')
                ).order_by('-db_score')

rawDescription: Django complex ordering

description: Django complex ordering


code:
class PinboardDetailView(DetailView):
    model = Pinboard
    queryset = Pinboard.objects.prefetch_related(
        Prefetch(
            'notes',
            Note.objects.order_by('pinboard_pins__position'),
        )
    )

rawDescription: How to order by a field from the `through` table for a M2M relationship in Django?

description: Order by a field from the `through` table for a M2M relationship in Django


rawDescription: matplotlib: make plus sign thicker

description: Matplotlib: make plus sign thicker


code:
import json

def on_post_get(resoure, request, payload):
    # get the actual response json out of Flask Response
    json = json.loads(payload.get_data())

    documents = json['_items']
    assert(len(documents) == 0)

app = Eve()
app.on_post_GET += on_post_get

if __name__ == '__main__':
    app.run()

rawDescription: Easiest way to find if a GET request does not find a resource


code:
url(r'^mypage/(?P<q_id>\d+)/$', generate_form_tuples, name='nickname'),

...

def generate_form_tuples(request, q_id=1):
    ...
    return QuizWizard.as_view(...)(request, q_id=q_id)

rawDescription: Django URLs: How to handle a parameter

description: Django URLs: How to handle a parameter


code:
ascii_string = set("""!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""")

user_text = input("Enter a text to analyze: ")

total_count = len(user_text)
ascii_count = sum(c in ascii_string for c in user_text)

print("Total number of characters:", total_count)
print("Total number of ASCII characters:", ascii_count)
print("Total number of non-ASCII characters:", total_count-ascii_count)

rawDescription: Python ASCII Character Count

description: Python ASCII Character Count


code:
class TestModelAdminForm(forms.ModelForm):
    user = forms.MultipleChoiceField(choices=[ (user.id, user.email) for user in User.objects.all()])
    class Meta:
        model = TestModel
        fields = ('user','group')

class TestModelAdmin(admin.ModelAdmin):
    form = TestModelAdminForm

rawDescription: Specify field to be rendered in the django admin


rawDescription: Changing x-axis without changing index in pandas


code:
# connect to database and create table
import sqlite3
conn = sqlite3.connect(":memory:")
conn.execute('''create table my_table (value1 integer, value2 integer, xml text)''')

# read text from file
f = file('/tmp/my_file.xml')
xml_string_from_file = f.read()

# insert text into database
cur = conn.cursor()
cur.execute('''insert into my_table (value1, value2, xml) values (?, ?, ?)''', (23, 42, xml_string_from_file))
cur.commit()

# read from database into variable
cur.execute('''select * from my_table''')
xml_string_from_db = cur.fetchone()[2]

# parse with the XML parser of your choice
from xml.dom.minidom import parseString
dom = parseString(xml_string_from_db)

rawDescription: Storing XML/HTML files inside a SQLite database - Possible?


code:
from socket import *
import threading
import json
import select

print("client")
HOST = input("connect to: ")
PORT = int(input("on port: "))

# create the socket
s = socket(AF_INET, SOCK_STREAM)
s.connect((HOST, PORT))
print("connected to:", HOST)

#------------------- need 2 threads for handling incoming and outgoing messages--

#       1: create out_buffer:
out_buffer = []

# for incoming data
def incoming():
    rlist,wlist,xlist = select.select([s], out_buffer, [])
    while 1:
        for i in rlist:
            data = i.recv(1024)
            if data:
                print("\nreceived:", data.decode())

# now for outgoing data
def outgoing():
    global out_buffer
    while 1:
        user_input=input("your message: ")+"\n"
        if user_input:
            out_buffer += [user_input.encode()]
#       for i in wlist:
            s.send(out_buffer[0])
            out_buffer = []

thread_in = threading.Thread(target=incoming, args=())
thread_out = threading.Thread(target=outgoing, args=())
thread_in.start() # this causes the thread to run
thread_out.start()
thread_in.join()  # this waits until the thread has completed
thread_out.join()

rawDescription: My chat client freezes up after beginning threads


code:
import uno

def create_shape(document, x, y, width, height, shapeType):
    shape = document.createInstance(shapeType)
    aPoint = uno.createUnoStruct("com.sun.star.awt.Point")
    aPoint.X, aPoint.Y = x, y
    aSize = uno.createUnoStruct("com.sun.star.awt.Size")
    aSize.Width, aSize.Height = width, height
    shape.setPosition(aPoint)
    shape.setSize(aSize)
    return shape

def insert_shape():
    document = XSCRIPTCONTEXT.getDocument()
    drawPage = document.getDrawPages().getByIndex(0)
    shape = create_shape(
        document, 0, 0, 10000, 5000, "com.sun.star.drawing.RectangleShape")
    drawPage.add(shape)
    shape.setString("My new RectangleShape");
    shape.setPropertyValue("CornerRadius", 1000)
    shape.setPropertyValue("Shadow", True)
    shape.setPropertyValue("ShadowXDistance", 250)
    shape.setPropertyValue("ShadowYDistance", 250)
    shape.setPropertyValue("FillColor", int("C0C0C0", 16))  # blue
    shape.setPropertyValue("LineColor", int("000000", 16))  # black
    shape.setPropertyValue("Name", "Rounded Gray Rectangle")

# Functions that can be called from Tools -> Macros -> Run Macro.
g_exportedScripts = insert_shape,

rawDescription: Create Flowchart in LibreOffice using Python


code:
import matplotlib.pyplot as plt
plt.plot(range(10), range(10))
ax = plt.gca()

# remove white back ground
ax.set_frame_on(False)

# remove axis and ticks
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)

# No padding
plt.tight_layout(pad=0)

# Make full screen
plt.get_current_fig_manager()
mng.full_screen_toggle()

rawDescription: python - how do i create a figure that fills the screen?

description: Python - how do i create a figure that fills the screen


code:
import gtk

square_sz = 20
pixmap = None
colour = "#FF0000"
gc = None

def configure_event( widget, event):
    global pixmap
    x, y, width, height = widget.get_allocation()
    pixmap = gtk.gdk.Pixmap(widget.window, width, height)
    white_gc = widget.get_style().white_gc
    pixmap.draw_rectangle(white_gc, True, 0, 0, width, height)
    return True

def expose_event(widget, event):
    global pixmap
    if pixmap:
    	x , y, w, h = event.area
    	drawable_gc = widget.get_style().fg_gc[gtk.STATE_NORMAL]
    	widget.window.draw_drawable(drawable_gc, pixmap, x, y, x, y, w, h)
    return False

def button_press_event(widget, event):
    global pixmap, square_sz, gc, colour
    if event.button == 1 and pixmap:
    	x = int(event.x / square_sz) * square_sz
    	y = int(event.y / square_sz) * square_sz
    	if not gc:
    		gc = widget.window.new_gc()
    		gc.set_rgb_fg_color(gtk.gdk.color_parse(colour))
    	pixmap.draw_rectangle(gc, True, x, y, square_sz, square_sz)
    	widget.queue_draw_area(x, y, square_sz, square_sz)

    return True

if __name__ == "__main__":
    da = gtk.DrawingArea()
    da.set_size_request(square_sz*20, square_sz*20)

    da.connect("expose_event", expose_event)
    da.connect("configure_event", configure_event)
    da.connect("button_press_event", button_press_event)

    da.set_events(gtk.gdk.EXPOSURE_MASK | gtk.gdk.BUTTON_PRESS_MASK)

    w = gtk.Window()
    w.add(da)
    w.show_all()
    w.connect("destroy", lambda w: gtk.main_quit())

    gtk.main()

rawDescription: Pygtk graphics contexts and allocating colors


code:
def size(self, a=1):
    for subtree in self.subtrees:
        if isinstance(subtree,Tree):
            a += subtree.size()
        else:
            a += 1
    return(a)

rawDescription: How to recursively get the size of a tree?

description: Recursively get the size of a tree


code:
def _q_getattr(self, attr):
    print("get %s" % attr)
    return getattr(self, 'x')

def override(p, methods):
    oldType = type(p)
    newType = type(oldType.__name__ + "_Override", (oldType,), methods)
    p.__class__ = newType

override(p, { '__getattr__': _q_getattr})
print(p.__getattr__('x')())  # Works!  Prints "0"
print(p.x())                 # Should work!

rawDescription: Python method resolution mystery

description: Python method resolution mystery


code: data = numpy.loadtxt('position.txt')

rawDescription: Reading multidimensional array data into Python


code: data = [x[:-2] for x in data]

rawDescription: Removing elements from a list of a list

description: Removing elements from a list of a list


rawDescription: extracting a double from the middle of a string, can't use replace

description: Extracting a double from the middle of a string, can't use replace


code:
class Candidate(models.Model):
    name = models.CharField(max_length=50)
    surname = models.CharField(max_length=50)

class County(models.Model):
    name = models.CharField(max_length=50)
    population = models.IntegerField(max_length=50)
    eligible_voters = models.IntegerField(max_length=50)

class Result(models.Model):
    name = models.CharField(max_length=50) # you could give an election a name I suppose, i.e. 2016 primary
    county = models.ForeignKey('County',)
    winner = models.ForeignKey('Candidate',)
    loser = models.ForeignKey('Candidate',)
    total_votes = models.IntegerField(max_length=50) # break this out into other fields if you want more detail

rawDescription: Modelling results of an election in Django


rawDescription: Filtering objects by fuzzy word search

description: Filtering objects by fuzzy word search


code:
sage: preparse('a = 1')
'a = Integer(1)'
sage: preparse('2^40')
'Integer(2)**Integer(40)'
sage: preparse('F.<x> = PolynomialRing(ZZ)')
"F = PolynomialRing(ZZ, names=('x',)); (x,) = F._first_ngens(1)"

rawDescription: Creating a customized language using Python


code:
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick
from matplotlib.finance import volume_overlay3
from matplotlib.dates import num2date
from matplotlib.dates import date2num
import matplotlib.mlab as mlab
import datetime

datafile = 'data.csv'
r = mlab.csv2rec(datafile, delimiter=';')

# the dates in my example file-set are very sparse (and annoying) change the dates to be sequential
for i in range(len(r)-1):
    r['date'][i+1] = r['date'][i] + datetime.timedelta(days=1)

candlesticks = zip(date2num(r['date']),r['open'],r['close'],r['max'],r['min'],r['volume'])

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

ax.set_ylabel('Quote ($)', size=20)
candlestick(ax, candlesticks,width=1,colorup='g', colordown='r')

# shift y-limits of the candlestick plot so that there is space at the bottom for the volume bar chart
pad = 0.25
yl = ax.get_ylim()
ax.set_ylim(yl[0]-(yl[1]-yl[0])*pad,yl[1])

# create the second axis for the volume bar-plot
ax2 = ax.twinx()

# set the position of ax2 so that it is short (y2=0.32) but otherwise the same size as ax
ax2.set_position(matplotlib.transforms.Bbox([[0.125,0.1],[0.9,0.32]]))

# get data from candlesticks for a bar plot
dates = [x[0] for x in candlesticks]
dates = np.asarray(dates)
volume = [x[5] for x in candlesticks]
volume = np.asarray(volume)

# make bar plots and color differently depending on up/down for the day
pos = r['open']-r['close']<0
neg = r['open']-r['close']>0
ax2.bar(dates[pos],volume[pos],color='green',width=1,align='center')
ax2.bar(dates[neg],volume[neg],color='red',width=1,align='center')

#scale the x-axis tight
ax2.set_xlim(min(dates),max(dates))
# the y-ticks for the bar were too dense, keep only every third one
yticks = ax2.get_yticks()
ax2.set_yticks(yticks[::3])

ax2.yaxis.set_label_position("right")
ax2.set_ylabel('Volume', size=20)

# format the x-ticks with a human-readable date.
xt = ax.get_xticks()
new_xticks = [datetime.date.isoformat(num2date(d)) for d in xt]
ax.set_xticklabels(new_xticks,rotation=45, horizontalalignment='right')

plt.ion()
plt.show()

rawDescription: Matplotlib - Finance volume overlay

description: Matplotlib - Finance volume overlay


code: itertools.product(*[xrange(i, i+j) for i,j in zip(start, size)])

rawDescription: Iterating over N dimensions in Python

description: Iterating over N dimensions in Python


code: bitmap = bitmap.scaledToHeight(38, Qt.SmoothTransformation)

rawDescription: QT: antialiasing png resize?

description: QT: antialiasing png resize


code:
SCALE_MULTIPLE = 2  # or any positive integer
new_array = []
for orig_row in original:
    new_row = []
    for orig_elem in orig_row:
        new_row.extend([orig_elem] * SCALE_MULTIPLE)
    new_array.extend(new_row[:] for _ in range(SCALE_MULTIPLE))

rawDescription: array resize proportionally in python

description: Array resize proportionally in python


rawDescription: What kind of noise is this?

description: What kind of noise is this


code:
no_players = input("How many people are playing? ")
players = []
for _ in range(int(no_players)):
    name = input("What is your name? ")
    players.append(Player(name))

rawDescription: Python: Create an instance of a class at runtime based on user input


code:
# django.test.testcases.py:809
def _reset_sequences(self, db_name):
    conn = connections[db_name]
    if conn.features.supports_sequence_reset:
        sql_list = conn.ops.sequence_reset_by_name_sql(
            no_style(), conn.introspection.sequence_list())
    # ....

rawDescription: Django reset_sequences doesn't work in LiveServerTestCase


code:
for txt in soup.find_all(text=True):
    if re.search(pattern, txt, re.I) and txt.parent.name != 'a':
        newtag = soup.new_tag('a')
        newtag.attrs['href'] = "#{}".format(pattern)
        newtag.string = pattern
        txt.replace_with(newtag)
        newtag.insert_after(txt.replace(pattern, ""))

rawDescription: Replace text without escaping in BeautifulSoup


code: String.format("Got value: %s", variable);

rawDescription: Java's equivalence to Python's "Got value: %s" % variable?


code:
f = open("path_to_file", "r")
contents = f.readlines()
f.close()

contents.insert(index, value)

f = open("path_to_file", "w")
contents = "".join(contents)
f.write(contents)
f.close()

rawDescription: Insert line at middle of file with Python?


code:
from datetime import datetime
from calendar import timegm

current_time = datetime.utcnow()
epoch_time = timegm(current_time.utctimetuple())

rawDescription: how do you convert current date time in NY time to epoch in python

description: Convert current date time in NY time to epoch in python


rawDescription: Change path's in yaml files

description: Change path's in yaml files


code:
f = open('file.txt')
for line in f:
    line = line.replace('\n', '')
    if 'STN_NO' in line:
        stn_no = line.split(',')[-1]
        print(line)
    elif 'STN_ID' in line:
        stn_id = line.split(',')[-1]
        print(line)
    elif 'INST_HT' in line:
        inst_ht = line.split(',')[-1]
        print(line)
    else:
        print(line[:-1] + ',' + stn_no + ',' + stn_id + ',' + inst_ht)

rawDescription: add different data at the end of different lines in a file

description: Add different data at the end of different lines in a file


code:
newfile = open("test.csv", "w")
for row in readerObj:
  newrow = []
  for item in row:
    if " TB" in item:
      item = item.replace(" TB", "")
      item = re.sub('[^0-9]', '', item)
      item = float(item) * 1024
      item = round(item, 2)
    elif " MB" in item:
      item =  item.replace(" MB", "")
      item = re.sub('[^0-9]', '', item)
      item = float(item) / 1000
      item = round(item, 2)
    elif " GB" in item:
      item = item.replace(" GB", "")
      item = re.sub('[^0-9]', '', item)
      item = float(item)
      item = round(item, 2)
    newrow.append(str(item))
  newfile.write(','.join(newrow) + '\n')
newfile.close()
fileToClean.close()

rawDescription: Read, change, then write csv data in python


rawDescription: How do I ADD accents to a letter?

description: ADD accents to a letter


code:
sentence = input("Say a sentence: ").split()
vowels = 'aeiouAEIOU'
for idx in range(len(sentence)):
    to_replace = sentence[idx]
    if to_replace.isalpha() == True:
        if to_replace[0] in vowels:
            print(to_replace + "way")
            new = i + "way"
        else:
            print(to_replace[1:] + to_replace[0] + "ay")
            new = to_replace[1:] + to_replace[0] + "ay"
        sentence[idx] = new
    else:
        print(to_replace)
print(sentence)

rawDescription: Python list, .replace() problems

description: Python list, .replace() problems


code:
record.loc['2014-01-02'] = np.array([dat1, dat2, dat3])
record

rawDescription: appending to a dataframe that is indexed by datetime

description: Appending to a dataframe that is indexed by datetime


code:
df = DataFrame({'A' : pd.Categorical(list('bbeebbaa'),categories=['e','a','b']), 'B' : np.arange(8) })
df
df.dtypes
df.sort(['A','B'])
df.sort(['A','B'],ascending=False)

rawDescription: how to sort categorical data in a pandas dataframe

description: Sort categorical data in a pandas dataframe


code:
@auth_blueprint.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():

        user = User.query.filter_by(username=form.username.data).first()

        if user is not None and user.verify_password(form.password.data):
            login_user(user, True)
            next = request.args.get('next')
            #if not next_is_valid('next'):
            #    return abort(400)

            return redirect(next or url_for('simple.index'))
        flash('Invalid username or password')

    return render_template('/auth/login.html', form=form)

rawDescription: Proper way to handle two different types of user session in one app in flask


code:
class ModelB(models.Model):
  user = models.ForeignKey(User)
  modelA = models.ForeignKey('ModelA', related_name = 'modelbs')
  other_field = models.CharField(max_length=50)

  def clean(self):
    if (self.modelA.modelbs.all().count() > 2):
        raise ValidationError(
            "ModelA may create may only create 3 modelBs "
        )
    super(ModelB, self).clean()

class ModelA(models.Model):
  user = models.ForeignKey(User, related_name = 'modelas')
  other_field = models.CharField(max_length=50)

  def clean(self):
    if (self.user.modelas.all().count() > 2):
        raise ValidationError(
            "User may create may only create 3 modelAs "
        )
    super(ModelA, self).clean()

rawDescription: I have a complicated model issues... more info inside


code:
from __future__ import print_function
import shlex
import subprocess
import sys

python_version = sys.version_info
if python_version < (3,0,0): user_input = str(raw_input('Enter command: '))
else: user_input = str(input('Enter command: '))

print("Running : %s" % user_input)
cmd = shlex.split(user_input)
subprocess.call(cmd, shell=True)

rawDescription: Installing modules in Python without command line


rawDescription: How to refresh tkinter entry value? I get a 1-click lag

description: Refresh tkinter entry value? I get a 1-click lag


code:
re.split(r'(?=\s+Change \d+ on \d{4})\s+', '''    Change 421387 on 2011/09/20 by person@domain.com
    Some random text including line breaks
    Change 421388 on 2011/09/20 by person2@domain.com
    Some other random text including line breaks''')

rawDescription: Some help with a regular expression in Python


code:
def decider(x, y, condition, val):
    if condition:
        return val, y
    return x, val

a, b = decider(a, b, cond, value)

rawDescription: Python assignment to conditional LHS

description: Python assignment to conditional LHS


code:
import Tkinter, ttk, tkFileDialog, tkSimpleDialog, time, threading

class App:
    def __init__(self, master):
        self.progress_line(master)

    def progress_line(self, master):
        # the value of "maximum" determines how fast progressbar moves
        self._progressbar = ttk.Progressbar(master, mode='indeterminate',
                                            maximum=4) # speed of progressbar
        self._progressbar.place(anchor='ne', height="20", width="150",
                                x="175", y="30")
    @property
    def progressbar(self):
        return self._progressbar # return value of private member

class AppMenu(object):
  def __init__(self, master, progressbar):
      self.master = master
      self.menu_bar()
      self.progressbar = progressbar

  def menu_bar(self):
      self.menu_bar = Tkinter.Menu(self.master)
      self.master.config(menu=self.menu_bar)
      self.create_menu = Tkinter.Menu(self.menu_bar, tearoff=False)
      self.create_menu.add_command(label="do", command=self.do)
      self.menu_bar.add_cascade(label="now", menu=self.create_menu)

  def do(self):
      Dialog(self.master, self.progressbar) # display the dialog box

class Dialog(tkSimpleDialog.Dialog):
    def __init__(self, parent, progressbar):
        self.progressbar = progressbar
        tkSimpleDialog.Dialog.__init__(self, parent, title="Do foo?")

    def apply(self):
        self.start_foo_thread()

    # added dialog methods...
    def start_foo_thread(self):
        self.foo_thread = threading.Thread(target=self.foo)
        self.foo_thread.daemon = True
        self.progressbar.start()
        self.foo_thread.start()
        master.after(20, self.check_foo_thread)

    def check_foo_thread(self):
        if self.foo_thread.is_alive():
            master.after(20, self.check_foo_thread)
        else:
            self.progressbar.stop()

    def foo(self): # some time-consuming function...
        time.sleep(3)

master = Tkinter.Tk()
master.title("Foo runner")
app = App(master)
appmenu = AppMenu(master, app.progressbar)
master.mainloop()

rawDescription: Python: How to get progressbar start() info from one window (class) to other


code:
placeholder= '?' # For SQLite. See DBAPI paramstyle.
placeholders= ', '.join(placeholder for unused in l)
query= 'SELECT name FROM students WHERE id IN (%s)' % placeholders
cursor.execute(query, l)

rawDescription: python list in sql query as parameter

description: Python list in sql query as parameter


rawDescription: Scrapy crawling issue

description: Scrapy crawling issue


code:
for label in cbar.ax.xaxis.get_ticklabels()[::2]:
    label.set_visible(False)

rawDescription: Cleanest way to hide every nth tick label in matplotlib colorbar?


code:
uif = "images/userGray.png"
bif = "images/bg.jpg"
cif = "images/chair3.png"
i = 0
playerX = 1
playerY = 1
pX = 1
pY = 1
bX = 0
bY = 0
moveX = 0
moveY = 0
windowX = 640
windowY = 480
lowerY = 1024
lowerX = 1024
bullets = []
x = 0
y = 0
rotate = False

objects = []

objects.append([256,260,410,511])

import pygame, sys
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((640,480),0,32)

background = pygame.image.load(bif).convert()
user = pygame.image.load(uif).convert_alpha()
chair = pygame.image.load(cif).convert_alpha()
chair1 = pygame.image.load(cif).convert_alpha()

pygame.time.set_timer(USEREVENT + 1, 100)

def shoot(inLoc, clLoc, weapon):
    bulletId = len(bullets)
    bullets[bulletId] = [inLoc, clLoc, 200, 3]

moveSpeed = .1

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == USEREVENT + 1:
            rotate = True;
        if event.type == KEYDOWN:
            if event.key == K_LEFT or event.key == K_a:
                moveX = -1*moveSpeed
            elif event.key == K_RIGHT or event.key == K_d:
                moveX = moveSpeed
            if event.key == K_DOWN or event.key == K_s:
                moveY = moveSpeed
            elif event.key == K_UP or event.key == K_w:
                moveY = -1*moveSpeed
        if event.type == KEYUP:
            if event.key == K_LEFT or event.key == K_a or event.key == K_RIGHT or event.key == K_d:
                moveX = 0
            if event.key == K_DOWN or event.key == K_s or event.key == K_UP or event.key == K_w:
                moveY = 0

    dontMoveX = 0
    dontMoveY = 0

    for obj in objects:

        if playerX + moveX > obj[0]-user.get_width() and playerX + moveX < obj[1] and playerY + moveY > obj[2]-user.get_height() and playerY + moveY < obj[3]:
            if playerY + moveY == obj[2]-user.get_height()-1 or playerY + moveY == obj[3]+1:
                dontMoveX = 0
            else:
                dontMoveX = 1

        if playerX + moveX > obj[0]-user.get_width() and playerX + moveX < obj[1] and playerY + moveY > obj[2]-user.get_height() and playerY + moveY < obj[3]:
            if playerX + moveX == obj[0]-user.get_width()-1 or playerX + moveX == obj[1]+1:
                dontMoveY = 0
            else:
                dontMoveY = 1

    if dontMoveX == 0:
        playerX += moveX

        if (playerX >= 0 and playerX <= windowX/2) or (playerX >= lowerX-(windowX/2) and playerX <= lowerX-user.get_width()):
            pX+=moveX
        if playerX > windowX/2 and playerX < lowerX-(windowX/2):
            bX+=-1*moveX

    if dontMoveY == 0:
        playerY += moveY

        if (playerY >= 0 and playerY <= windowY/2) or (playerY >= lowerY-(windowY/2) and playerY <= lowerY-user.get_width()):
            pY+=moveY
        if playerY > windowY/2 and playerY < lowerY-(windowY/2):
            bY+=-1*moveY

    screen.blit(background,(bX,bY))

    screen.blit(user,(pX,pY))

    pygame.mouse.set_visible(False);

    if rotate == True:

        if i < 360:
            i = i + 18
        else:
            i = 0

        orig_chair_rect = chair.get_rect()
        chair1 = pygame.transform.rotate(chair, i);
        rot_chair_rect = orig_chair_rect.copy()
        rot_chair_rect.center = chair1.get_rect().center
        chair1 = chair1.subsurface(rot_chair_rect).copy()

        rotate = False

    x,y = pygame.mouse.get_pos()
    x -= chair.get_width()/2
    y -= chair.get_height()/2

    screen.blit(chair1,(x,y))

    pygame.display.update()

rawDescription: check for event midway through running while loop?

description: Check for event midway through running while loop


code: body.send_keys(Keys.COMMAND + 't')

rawDescription: Open new tab in Firefox using Selenium WebDriver on Mac


code:
zf = zipfile.ZipFile(file_to_search, mode='w')
zf.write(bin_file_path, custom_name)
zf.close()

rawDescription: python zipfile module: How to change the structure of zip archive created?

description: Python zipfile module: How to change the structure of zip archive created


code:
from smart_selects.db_fields import ChainedForeignKey

class Location(models.Model):
    continent = models.ForeignKey(Continent)
    country = ChainedForeignKey(
        Country,
        chained_field="continent",
        chained_model_field="continent",
        show_all=False,
        auto_choose=True
    )
    area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
    city = models.CharField(max_length=50)
    street = models.CharField(max_length=100)

rawDescription: Add info to model instance referenced in ManyToMany in Django


code:
f = open('data.txt', 'r')

data = f.read()
array1 = []
array2 = []
array3 = []
splat = data.split("\n\n")
for number, paragraph in enumerate(splat, 1):
    if number % 3 == 1:
        array1 += [paragraph]
    elif number % 3 == 2:
        array2 += [paragraph]
    elif number % 3 == 0:
        array3 += [paragraph]

rawDescription: read file into array seperated by paragraph Python

description: Read file into array seperated by paragraph Python


code:
import numpy as np
x = [1., 2., 3., 4., 5.]
y = [0, 0, 0, 0, 1.]
corrCoef = np.correlate(x, y, 'full')
lagsOut = np.arange(-len(x)+1, len(x))

rawDescription: Suppress the plot and only get the result


rawDescription: Deleting list elements based on condition


code:
class ArticleViewCount(model):
    counter = models.PositiveIntegerField()
    article = models.OneToOneField(Article)

rawDescription: Django model - Updating a attribute without touching lastmodified_at


code:
import numpy

#Generate Random Data
M = numpy.random.normal(0,1,9).reshape(3,3)
A = numpy.random.normal(0,1,3)
B = numpy.random.normal(0,1,3)

#The Operation
numpy.dot(A, numpy.dot(M,B) )

rawDescription: matrix product with numpy.dot()

description: Matrix product with numpy.dot()


code: re.findall(r"(^.*?%s.*?$)" %expression, text, re.MULTILINE)

rawDescription: python regex to match whole line with a particular regex pattern

description: Python regex to match whole line with a particular regex pattern


code:
count = 3
for line in filtered_input:
    if "silence.wav" in line:
        count = 0
    else:
        count += 1

    if count <= 2:
        filtered_output.write(line)

rawDescription: Issue with selecting multiple lines of a txt document and write to new text doc in python


code:
mylist = []
for col in ws.columns[0]:
    mylist.append(col.value)

rawDescription: Working with openpyxl. making a list out of a column


rawDescription: Python Pandas data frame with column value as a dictionary


code:
p = np.polyfit(np.log(xm), mcherryp, 1)
ax1.semilogx(xm, p[0] * np.log(xm) + p[1], 'r-')

rawDescription: Using polyval and polyfit to plot linear regression on semi-log charts


code:
endpoint = TCP4ClientEndpoint(reactor, host, port)
agent = ProxyAgent(endpoint)

headers = {}
auth = base64.b64encode("%s:%s" % (username, password))
headers["Proxy-Authorization"] = ["Basic " + auth.strip()]

body = agent.request("GET", path, Headers(headers))

rawDescription: Proxy username/password with Twisted

description: Proxy username/password with Twisted


code: A.T * A

rawDescription: Efficiently populate SciPy sparse matrix from subset of dictionary


code:
from PyQt4.QtSql import QSqlQueryModel,QSqlDatabase,QSqlQuery
from PyQt4.QtGui import QTableView,QApplication
import sys

app = QApplication(sys.argv)

db = QSqlDatabase.addDatabase("QSQLITE")
db.setDatabaseName("patientData.db")
db.open()

projectModel = QSqlQueryModel()
projectModel.setQuery("select * from patient",db)

projectView = QTableView()
projectView.setModel(projectModel)

projectView.show()
app.exec_()

rawDescription: how to display data from database in table view in python

description: Display data from database in table view in python


code:
my_list = ['foo','bar','baz','>=','5.2']

# With
only_words = [token for token in my_list if token.isalpha()]

# Without
only_words = filter(str.isalpha, my_list)

rawDescription: How can I filter items from a list in Python?

description: Filter items from a list in Python


code:
import matplotlib.pyplot as plt
import itertools
markers = itertools.cycle([ '+', '*', ',', 'o', '.', '1', 'p', ])
while x <= stopFrequency:
    y = startVoltage
    ys = []
    vals = []
    while y <= stopVoltage:
        ys.append(y)
        vals.append(getCapacity)
        getCapacity = y * 2
        y += stepValueVoltage
    plt.plot(ys, vals,
             label = 'x: {0}'.format(x),
             marker = next(markers))
    x += stepValueFrequency
plt.legend(loc = 'best')
plt.show()

rawDescription: Multiple plots with matplotlib in a nested while loop


code:
filename = 'somefile.txt'

with open(filename, 'r') as input:
   for line in input:
       if 'indicator' in line:
            break

rawDescription: Read file until specific line in python

description: Read file until specific line in python


rawDescription: How to extract a list of strings out of single string by using regex?

description: Extract a list of strings out of single string by using regex


code:
import re
text = '10DEUTSCH        GGS Neue Heide 25-27     Wahn-Heide   -1      -1'
re.split(r'\s{2,}', text)

rawDescription: python split a string with at least 2 whitespaces

description: Python split a string with at least 2 whitespaces


code:
import webbrowser
url = 'http://www.python.org/'
webbrowser.open_new(url)

rawDescription: Opening and Closing a webpage in browser from Python


code:
data = np.arange(10)+np.arange(0, 100, 10)[:,None]
print(data)
inds1 = np.array([[0, 2, 2], [3, 5, 8]])
inds2 = np.array([[2, 7, 1], [8, 2, 8]])
data2 = data[inds1, inds2]
print(data2)

rawDescription: How to efficiently apply an arbitrary remapping to a matrix in Python

description: Efficiently apply an arbitrary remapping to a matrix in Python


code:
models.py
from hashlib import md5

class Stop(models.Model):
    line = models.CharField(max_length=12)
    street = models.CharField(max_length=32, choices=STREET_CHOICES)
    order = models.PositiveIntegerField(blank=True, null=True)
    location_hash = models.CharField(max_length=32, null=True)

    def save(self):
        location_hash = md5('%s@%s' % (self.line, self.street))
        if self.location_hash != location_hash:
            self.order = calculate_order(line=self.line, street=self.street)
            self.location_hash = location_hash
        super(Stop, self).save()

rawDescription: Django: Detecting changes of a set of fields when a model is saved


code:
my_dictionary = collections.defaultdict(
                lambda: collections.defaultdict(
                lambda: (None, datetime.datetime.min, None)))

# populate my_dictionary

_, old_time, _ = my_dictionary[example_id][color]
if time > old_time:
    # NB: tuples make more sense here than lists
    my_directory[example_id][color] = (text, time, status)

rawDescription: What's the correct way to re-write this nested IF statement in Python


code: buffer += struct.pack("L", crc)

rawDescription: Python network convert byte

description: Python network convert byte


code:
with open(filename) as fin:
    fin.seek(start_index)
    data = fin.read(end_index - start_index)

rawDescription: How to read specific part of large file in Python

description: Read specific part of large file in Python


code:
results = [[index, line] for index, line in enumerate(lines)
            if search_item in line.lower()]

rawDescription: for/in/if List Comprehension Becomes Very Slow With Large Number of Matches

description: For/in/if List Comprehension Becomes Very Slow With Large Number of Matches


rawDescription: Finding indices of the lowest 5 numbers of an array in Python


code:
import sys
import os
from selenium import webdriver
from pyvirtualdisplay import Display
from selenium.webdriver.common.keys import Keys

orig = os.environ["DISPLAY"]

display = Display(visible=1, size=(800, 600))
display.start()
driver = webdriver.Chrome()
driver.get("https://news.bbc.co.uk")

# You have to do this between each new Display.
os.environ["DISPLAY"] = orig

display2 = Display(visible=1, size=(800, 600))
display2.start()
driver2 = webdriver.Chrome()
driver2.get("https://www.google.com")

rawDescription: Python open multiple display windows from a loop


code:
import glob
import os

outfile = open('output.csv', 'w')
outfile.write('X ; Y ; Z ; filename\n')
for filename in glob.glob('*.csv'):
  if filename == 'output.csv': # Skip the file we're writing.
    continue
  with open(filename, 'r') as infile:
    count = 0
    lineno = 0
    for line in infile:
      lineno += 1
      if lineno == 1: # Skip the header line.
        continue
      fields = line.split(';')
      x = int(fields[0])
      y = int(fields[1])
      z = float(fields[2])
      if x == 1 and y == 2:
        outfile.write('%d ; %d ; %g ; %s\n' % (x, y, z, filename))
        count += 1
    if count == 0: # Handle the case when no lines were found.
      outfile.write('1 ; 2 ; NA ; %s\n' % filename)
outfile.close()

rawDescription: extract rows and filenames from multiple csv files

description: Extract rows and filenames from multiple csv files


code:
fileLines = []
with open('field.txt') as f:
    for line in f:
        # mysql query to get 'query_result'
        if query_result != 1:
            fileLines.append(line) # These will be the lines you actually want

with open('field.txt', 'w') as f:
    for line in fileLines:
        f.write(line)

rawDescription: In python, how would I delete a line in a file if query matches a result