code:
import tkinter as tk
import tkinter.messagebox

Dict={"admin":"admin"}

def mbox(title, text):
    tk.messagebox.showinfo(title, text)

def login():
    if entry_1.get() in Dict and Dict[entry_1.get()] == entry_2.get():
        mbox("Success!", "Login successful!")
    else:
        mbox("Sorry...", "Login unsuccessful.")

root = tk.Tk()

label_1 = tk.Label(root, text="Name")
label_2 = tk.Label(root, text="Pass")
entry_1 = tk.Entry(root)
entry_2 = tk.Entry(root)
button_1 = tk.Button(root, text="Login", command=login)

label_1.grid(row=0)
label_2.grid(row=1)

entry_1.grid(row=0, column=1)
entry_2.grid(row=1, column=1)

button_1.grid(row=2, column=0, rowspan=2)

root.mainloop()

rawDescription: When creating a message box in python with def, it only shows the first letter of each string


code: filter(None, some_list)

rawDescription: How to discard an element from a set without rearranging it?

description: Discard an element from a set without rearranging it


code:
def post(self, request, *args, **kwargs):
    data = deepcopy(request.DATA)
    data['owner'] = request.user
    form = AccountForm(data=data)
    if form.is_valid():
        instance = form.save(commit=false)
        instance.save()
        return Response(dict(id=instance.pk), status=status.HTTP_201_CREATED)
    return Response(form.errors, status=status.HTTP_400_BAD_REQUEST)

rawDescription: Django Rest Framework ModelSerializer Set attribute on create


code:
import itertools
list1=['a','b','c']
list2=[1,2]
[zip(x,list2) for x in itertools.permutations(list1,len(list2))]

rawDescription: combinations between two lists?

description: Combinations between two lists


code:
def handler(signum, frame):
    raise MyError

signal.signal(signal.SIGALRM, handler)

for i in range(0,n):
    p = subprocess.Popen(...)
    try:
        signal.alarm(1) # 1 second timer
        p.wait()
        signal.alarm(0) # clear the timer
    except MyError:
        p.kill()

rawDescription: Simplest way to implement time-out in Python 3


code:
for item in cij.keys():
    setattr(self, item, 0)

rawDescription: Creating instance variables in a for loop


rawDescription: mysql 'LIKE' in Django python

description: Mysql 'LIKE' in Django python


code:
from IPython.display import HTML

HTML('''<script>
code_show=true;
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
}
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')

rawDescription: How to hide code from cells in ipython notebook visualized with nbviewer?

description: Hide code from cells in ipython notebook visualized with nbviewer


code:
searchindexnodes = {}
searchindexnodes[1036592] = 'Apparel'
searchindexnodes[672123011] = 'Apparel'
searchindexnodes[165796011] = 'Baby'

rawDescription: How can I define an array in Python with undefined keys?

description: Define an array in Python with undefined keys


code:
import os

DEV = os.environ['SERVER_SOFTWARE'].startswith('Development')

rawDescription: How to determine if your app is running on local Python Development Server?

description: Determine if your app is running on local Python Development Server


code:
import win32gui
handle = win32gui.FindWindow(None, cmd_window_title)
win32gui.ShowWindow(handle, 6)

rawDescription: CMD window minimized for Popen() call?

description: CMD window minimized for Popen() call


code:
a = 1
b = a
c = b
locals()
[key for key, value in locals().items() if value == 1]
globals()
[key for key, value in globals().items() if value == 1]

rawDescription: How can I get a list of references of an object in Python?

description: Get a list of references of an object in Python


code:
# This separates the first and last names
name = name.partition(" ")
firstName = name[0]
# now figure out the first initial
# we're assuming that if it has a dot it's an initialized name,
# but this may not hold in general
if "." in firstName:
    firstInitial = firstName
else:
    firstInitial = firstName[0] + "."
lastName = name[2]
return {"FirstName":firstName, "FirstInitial":firstInitial, "LastName": lastName}

rawDescription: Parsing people's first and last name in Python


code:
from django.template import Library

register = Library()

@register.filter('titleofwidth')
def titleofwidth(post, width):
    """
    Get the title of a given width of a post.

    Sample usage: {{ post|titleofwidth:200 }}
    """

    for i in post['sizes']:
        if i['w'] == width:
            return i['title']
    return None

rawDescription: How do I do parsing in Django templates?

description: Do parsing in Django templates


code:
delim = len(keys)
dict([(key, values[index*delim:index*delim + delim]) if index < len(keys) -1 else (key, values[index*delim:]) for index, key in enumerate(keys)])

rawDescription: Zip lists of unequal size (more values than keys) to form a uniform dictornary


code:
import Tkinter as tk

root = tk.Tk()
choices = ('network one', 'network two', 'network three')
var = tk.StringVar(root)

def refresh():
    # Reset var and delete all old options
    var.set('')
    network_select['menu'].delete(0, 'end')

    # Insert list of new options (tk._setit hooks them up to var)
    new_choices = ('one', 'two', 'three')
    for choice in new_choices:
        network_select['menu'].add_command(label=choice, command=tk._setit(var, choice))

network_select = tk.OptionMenu(root, var, *choices)
network_select.grid()

# I made this quick refresh button to demonstrate
tk.Button(root, text='Refresh', command=refresh).grid()

root.mainloop()

rawDescription: Changing the options of a OptionMenu when clicking a Button


code:
from twisted.web import resource

from twisted.web import server
from twisted.internet import reactor

class MyResource(resource.Resource):
    isLeaf=False

    def __init__(self, color='blue'):
        resource.Resource.__init__(self)
        self.color = color

    def render(self,req):
        return "<body bgcolor='%s' />" % self.color

    def getChild(self,path,request):
        return MyResource('blue' if path == '' else 'red')

f=server.Site(MyResource())
reactor.listenTCP(8888,f)
reactor.run()

rawDescription: The getChild of resource is not calling in twisted


code:
def get_method(name):
    return getattr(random, name, None)

def get_distribution(method, params):
    return method(params['mean'])

method_name = 'exponential'
method = get_method(method_name)
if method:
    results = get_distribution(method, params)
else:
    raise AttributeError('No such method in random: {}'.format(method_name))

rawDescription: function names from config file in python

description: Function names from config file in python


code:
curPos = self.LogWindow.GetInsertionPoint
lineNum = self.LogWindow.GetRange( 0, self.LogWindow.GetInsertionPoint() ).split("\n")
lineText = self.LogWindow.GetLineText(lineNum)

rawDescription: wxpython textctrl How to find out where the text pointer is

description: Wxpython textctrl How to find out where the text pointer is


code: list_tuples = [('0', 'Choose')] + [(str(interest.id), interest) for interest in interests]

rawDescription: Update list to tuples

description: Update list to tuples


code:
import numpy,os,sys
import pylab
from mpl_toolkits.axes_grid1.inset_locator import zoomed_inset_axes
from mpl_toolkits.axes_grid1.inset_locator import mark_inset

# Initializing the curve
fig_cal=pylab.figure()
host_weight = fig_cal.add_subplot(111)
host_mass = host_weight.twinx()
Tension = numpy.linspace(0,0.08,100)
Weight = 0.5* Tension
Mass = Weight/9.81

# Plotting the curve
host_weight.plot(Tension, Weight, 'r', label='Fitted line',lw=2)
host_mass.plot(Tension, Mass, alpha=0)

# Cosmetic on the Figure
host_weight.set_xlabel("Tension U [$V$]")
host_weight.set_ylabel("Weight F [$N$]")
host_mass.set_ylabel("Mass M [$kg$]")
host_mass.set_ylim(host_weight.axis()[-2]/9.81, host_weight.axis()[-1]/9.81)
host_weight.grid(False)

# Zoom on the first measurement
zoom_weight = zoomed_inset_axes(host_weight, zoom = 7.5, bbox_to_anchor=(0.95,0.5), bbox_transform=host_weight.transAxes)
zoom_weight.plot(Tension[:4], Weight[:4], 'r', lw=2)
zoom_weight.set_xticks(zoom_weight.xaxis.get_majorticklocs()[::2])
zoom_weight.set_yticks(zoom_weight.yaxis.get_majorticklocs()[::2])
zoom_mass = zoomed_inset_axes(host_mass, zoom = 7.5, bbox_to_anchor=(0.95,0.5),     bbox_transform=host_mass.transAxes)
zoom_mass.xaxis.set_visible(False)
zoom_mass.spines['left'].set_visible(False)
zoom_mass.spines['top'].set_visible(False)
zoom_mass.patch.set_alpha(00)
zoom_mass.yaxis.tick_right()
zoom_mass.yaxis.set_label_position('right')
zoom_mass.yaxis.set_offset_position('right')
zoom_mass.plot(Tension[:4], Mass[:4],color='w', alpha=0)
zoom_mass.set_ylim(zoom_weight.axis()[-2]/9.81,zoom_weight.axis()[-1]/9.81)

pylab.show()

rawDescription: Adding a second Y-Axis to an inset zoom axes


code:
from django.contrib.admin import AdminSite

class TenantSitesAdminSite(AdminSite):
    def has_permission(self, request):
        user = request.user
        return (
            user.is_active and
            user.is_staff and
            (user.is_superuser or user.site == get_current_site()))

site = TenantSitesAdminSite()

rawDescription: Django hook to deny user access to admin based on site


code:
for i, channel in enumerate(self.image):
    channel_ = spf.fftshift(spf.fft2(channel)) # take FFT of each channel (r,g,b) separately
    channel_ = scipy.multiply(channel_,ff) # multiply each channel by the filter (freq. domain)
    filtered_image[:][:][i] = spf.fftshift(spf.ifft2(channel_)) # inverse FFT each channel separately

rawDescription: Using fft2 with reshaping for an RGB filter


rawDescription: Calculating pi using a series in my book


code:
src_rgb = fg[..., :3].astype(np.float32) / 255.
src_alpha = fg[..., 3].astype(np.float32) / 255.
dst_rgb = bg[..., :3].astype(np.float32) / 255.
dst_alpha = bg[..., 3].astype(np.float32) / 255.

out_alpha = src_alpha + dst_alpha * (1. - src_alpha)
out_rgb = (src_rgb * src_alpha[..., None] +
           dst_rgb * dst_alpha[..., None] * (1. - src_alpha[..., None])) / out_alpha[..., None]

out = np.zeros_like(bg)
out[..., :3] = out_rgb * 255
out[..., 3] = out_alpha * 255

rawDescription: Overlay two numpy arrays treating fourth plane as alpha level


code:
import io

buf = io.BytesIO(b'Hello world!')
buf.read(1) # Returns b'H'

buf.tell()  # Returns 1
buf.read(1) # Returns b'e'

buf.tell() # Returns 2

# Set the pointer to 0.
buf.seek(0)
buf.read() # This will return b'H', like the first call.

rawDescription: Prefer BytesIO or bytes for internal interface in Python?


rawDescription: What is the simplest way to round floats correctly in Python?


code: a = data.groupby('product_id').filter(lambda x: len(x) > 20)

rawDescription: Pandas drop rare entries

description: Pandas drop rare entries


code:
import itertools
lst = [1,2,3,4]
for x in itertools.combinations(lst, 2):
    print(x)

rawDescription: Iterating over every two elements in a list in Python


code:
idx = pd.IndexSlice
df.columns = pd.MultiIndex.from_tuples([(b,a) for (a,b) in df.columns.str.split(' - ')])
df = df.sortlevel(level=(0,1), axis=1)
new_cols = [('% Change', cat) for cat in df.columns.levels[1]]
df[new_cols] = df['Sept'] / df['Aug'] - 1
df = df.loc[:, idx[['Sept', '% Change'], :]]
df.columns = df.columns.swaplevel(0,1)
df = df.sortlevel(level=(0,1), axis=1)
df

rawDescription: More efficient way to reorder pandas columns and perform calculations


code:
from kivy.properties import NumericProperty

class TreasureHuntGrid(GridLayout):
    attempts = NumericProperty(0)
    ...

rawDescription: Text Labels in kivy are not being updated


code:
def get_number(values):
    total = 0
    for val in reversed(values):
        total = (total << 8) + val
    return total

rawDescription: converting python list of integers to a hex number

description: Converting python list of integers to a hex number


code: generate_url(expires_in, method='GET', headers=None, query_auth=True, force_http=False)

rawDescription: How to download a file via the browser from Amazon S3 using Python (and boto) at Google App Engine?

description: Download a file via the browser from Amazon S3 using Python (and boto) at Google App Engine


code:
os.system("bc")
subprocess.call("bc")

rawDescription: How to use python to start an interactive shell program?

description: Use python to start an interactive shell program


rawDescription: Python: how to change (last) element of tuple?


code:
x = (('a',1), (2,3), (4,))
[str(item[0]) for item in x if item and item[0]]

rawDescription: Create a list from a tuple of tuples

description: Create a list from a tuple of tuples


code:
import traceback
traceback.print_exc()

rawDescription: How do I print out the full traceback in my except call?

description: Print out the full traceback in my except call


code:
df2 = df.stack().unstack(-2)
df2["mean"] = df2.mean(axis=1)

rawDescription: Adding means to a pandas dataframe

description: Adding means to a pandas dataframe


code:
import numpy
np_array_data = numpy.zeros(100)
list_of_strs = ['abc'] * 100

import io
import pickle

np_array_data = io.BytesIO()
numpy.save(np_array_data, np_array)
np_array_data.seek(0)
str_data = io.BytesIO()
pickle.dump(list_of_strs, str_data)
str_data.seek(0)
with tarfile.open('output.tar.gz', mode='w:gz') as dest_file:
    dest_file.addfile(tarfile.TarInfo('np_data'), np_array_data)
    dest_file.addfile(tarfile.TarInfo('str_data'), str_data)

rawDescription: python compressing multiple data using gzip or zlib

description: Python compressing multiple data using gzip or zlib


code:
title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)

rawDescription: extract contents of regex

description: Extract contents of regex


code:
#cairovehicle.py

import gtk

class CairoVehicle(gtk.DrawingArea):
    def __init__(self):
        gtk.DrawingArea.__init__(self)
        self.connect("expose-event", self.on_expose_event)

    def get_background(self):
        """Serves as a caching solution."""
        return self.__bg

    def set_background(self, pattern):
        """Serves as a caching solution."""
        self.__bg = pattern

    def get_brush(self):
        """Serves as a caching solution."""
        return self.__brush

    def set_brush(self, pattern):
        """Serves as a caching solution."""
        self.__brush = pattern

    def on_expose_event(self, widget, event):
        context = self.window.cairo_create()

        # Restrict cairo to the exposed area
        context.rectangle(*event.area)
        context.clip()

        self.width, self.height = self.window.get_size()

        self.draw(context)

    def on_configure_event(self, widget, event):
        """Override this in case you want to do something when
           the widget's size changes."""

        return super(CairoVehicle, self).on_configure_event(widget, event)

    def invalidate(self):
        """Force a re-rendering of the window."""

        rect = self.get_allocation()

        # Compensate for parent offset, if any.
        parent = self.get_parent()
        if parent:
            offset = parent.get_allocation()
            rect.x -= offset.x
            rect.y -= offset.y

        self.window.invalidate_rect(rect, False)

    def draw(self, context):
        """Override this."""

        # do custom drawing here

        raise NotImplementedError()

    def make_grid(self, context, fgcolor, bgcolor, gapwidth, linewidth,
                                                        width, height):

         context.set_source_rgba(*bgcolor)
         context.rectangle(0, 0, width, height)
         context.fill()

         context.set_source_rgba(*fgcolor)
         context.set_line_width(linewidth)

         # uneven linewidths lead to blurry displaying when set on integer
         # coordinates, so in that case move coordinates away by half a
         # pixel.
         adjust = 0.5 if linewidth % 2 else 0
         i = 1
         j = 1

         while gapwidth*i-adjust < width:
             context.move_to(gapwidth*i-adjust, 0)
             context.line_to(gapwidth*i-adjust, height)
             context.stroke()
             i += 1

         while gapwidth*j-adjust < height:
             context.move_to(0, gapwidth*j-adjust)
             context.line_to(width, gapwidth*j-adjust)
             context.stroke()
             j += 1

class Grid(CairoVehicle):
    def draw(self, context):
        context.push_group()
        self.make_grid(context, fgcolor=(0, 0, 0, 1), bgcolor=(1, 1, 1, 1),
                    gapwidth=20, linewidth=1, width=self.width,
                    height=self.height)
        self.set_background(context.pop_group())
        context.set_source(self.get_background())
        context.paint()

if __name__ == "__main__":
    w = gtk.Window()
    w.connect("destroy", gtk.main_quit)
    w.show()

    cv = Grid()
    cv.show()
    w.add(cv)
    gtk.main()

rawDescription: PyGTK Custom Widget doesnt redraw

description: PyGTK Custom Widget doesnt redraw


code:
strList = map( str, objList)
strList = map( lambda x: x.replace( 'Volume:', ''), strList)

rawDescription: Remove prefix from python list objects and single quotes


rawDescription: specify soundcard with python-gstreamer

description: Specify soundcard with python-gstreamer


code:
class obj(object):
    __slots__=("data","meta")
    def __init__(self,data=(),meta=[]):
        self.data = data
        self.meta = meta
        for so in data:
            so._objs_using.append(self)
class subobj(object):
    __slots__ = ("_data","_objs_using")
    def __init__(self,data=()):
        self._objs_using=[]
        self._data = data
    @property
    def data(self):
        return self._data
    @data.setter
    def data(self,val):
        self._data = val
        for obj in self._objs_using:
            metadata_changed(obj.meta)

rawDescription: update metadata in objects when changing shared subobjects

description: Update metadata in objects when changing shared subobjects


code:
def load_and_compare(self, input_file1, input_file2, output_file1, output_file2, result_file):
    self.load(input_file1, input_file2, output_file1, output_file2)
    self.compare(output_file1, output_file2)
    self.final(result_file)

rawDescription: Passing values and calling functions from other functions


code: page = requests.get(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'})

rawDescription: Page redirects in browser but not in python


code:
def triplet(row):
    loc = (row[1] + 6) * 3
    return row[3][loc:loc+3]

d[3] = d.apply(triplet, axis=1)

# save the whole file once
d.to_csv(output2, sep='\t', header=False, index=False)

rawDescription: Optimizing a loop extracting substrings from a field based on another field


code:
import re
xmlprocre = re.compile("(\s*<[\?\!])")
def add_toplevel_tag(string):
    """
After all the XML processing instructions, add an enclosing top-level <DOC> tag, and return it.
e.g.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]> <ARTICLE> ...
</ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE>
=>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE FOO BAR "foo.dtd" [ <!ENTITY ...> <!ENTITY ...> <!ENTITY ...> ]><DOC> <ARTICLE> ...
</ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE> <ARTICLE> ... </ARTICLE></DOC>
"""
    def _advance_proc(string, idx):
        # If possible, advance over whitespace and one processing
        # instruction starting at string index idx, and return its index.
        # If not possible, return None
        # Find the beginning of the processing instruction
        m = xmlprocre.match(string[idx:])
        if m is None: return None
        #print "Group", m.group(1)
        idx = idx + len(m.group(1))
        #print "Remain", string[idx:]

        # Find closing > bracket
        bracketdebt = 1
        while bracketdebt > 0:
            if string[idx] == "<": bracketdebt += 1
            elif string[idx] == ">": bracketdebt -= 1
            idx += 1
        #print "Remain", string[idx:]
        return idx
    loc = 0
    while 1:
        # Advance one processing instruction
        newloc = _advance_proc(string, loc)
        if newloc is None: break
        else: loc = newloc
    return string[:loc] + "<DOC>" + string[loc:] + "</DOC>"

rawDescription: Read XML with multiple top-level items using Python ElementTree?


code:
img_nbr = 0  # try to avoid using `i` as the name of an index. It'll save you so much time if you ever find you need to replace this identifier with another one if you chose a better name
data = []
imgTag = '<img ' # no need to redefine this variable each time in the loop
srcAttribute = 'src="' # same comment applies here

for line in webPage:
   line = str(line, encoding)
   if imgTag in line :
      img_nbr += 1  # += saves you typing a few keystrokes and a possible future find-replace.
      #if srcAttribute in line:  # this check and the next do nearly the same: get rid of one
      m = re.search('src="(.+?)"', line)
      if m:
          reline = m.group(1)
          print("[{}: {}]".format(img_nbr, reline)) # `format` is the suggested way to build strings. It's been around since Python 2.6.
          data.append((img_nbr, reline)) # This is what you really missed.

rawDescription: Can't write more than one line to CSV

description: Can't write more than one line to CSV


rawDescription: python split string number in digits

description: Python split string number in digits


code:
p = subprocess.Popen("millions.exe", stdout=subprocess.PIPE)
i = 0
for line in p.stdout:
     i+=1

rawDescription: Python 2.7: run an external program and parse its output (while the ext program runs)


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

X1=np.random.rand(10,10)
X2=np.random.rand(10,10)
K,sigma=10,1.5

vmin = np.minimum(X1,X2).min()
vmax = np.maximum(X1,X2).max()

fig, axes = plt.subplots(1,2)

axes[0].set_title("$K = " + str(K) + " , \sigma = " + str(sigma) + "$")
heatmap1 = axes[0].imshow(X1, interpolation='none',  cmap=plt.get_cmap("seismic"),
                          vmin=vmin,vmax=vmax)

axes[1].set_title(r"$K = " + str(K) + ", \sigma = " + str(sigma) + "$")
heatmap2 = axes[1].imshow(X2, interpolation='none',   cmap=plt.get_cmap("seismic"),
                          vmin=vmin,vmax=vmax)

plt.subplots_adjust(left=None, bottom=None, right=0.8, top=None,
                    wspace=0.4, hspace=.4)

fig.savefig('test.png')
cpos = [axes[0].get_position().bounds[1],
        axes[0].get_position().bounds[3]]

cax = fig.add_axes([0.9,cpos[0],0.01,cpos[1]])

fig.colorbar(heatmap1,cax=cax)

fig.savefig('test.png')

rawDescription: Trouble with the legend

description: Trouble with the legend


code: pic = makePicture(file)

rawDescription: Abbreviating several functions - guidelines?


code: local('sudo find dir -exec chown name {} \;')

rawDescription: Moving hidden files in Fabric

description: Moving hidden files in Fabric


code:
class MyForm(forms.Form):
    my_field = forms.MultipleChoiceField(choices=SOME_CHOICES, widget=forms.CheckboxSelectMultiple())

    def clean_my_field(self):
        if len(self.cleaned_data['my_field']) > 3:
            raise forms.ValidationError('Select no more than 3.')
        return self.cleaned_data['my_field']

rawDescription: In Django is there a way to display choices as checkboxes?


code:
import re

def parse(s):
  args = {}
  n = 1
  # recognizes a double-quoted argument
  q_arg_re = "^\s*,?\s*\"(.*?)\""
  # recognizes a single-word argument
  arg_re = "^\s*,?\s*(\w+)"
  arg = False
  while True:
    m = re.search(arg_re, s)
    if m:
      arg = m.groups()[0]
    else:
      m = re.search(q_arg_re, s)
      if m:
        arg = m.groups()[0]

    if arg:
      if 'cmd' in args:
        args['arg{}'.format(n)] = arg
        n += 1
      else:
        args['cmd'] = arg
      s = s[m.end(0):]
      arg = False
    else:
      break
  return args

rawDescription: Match first word and arguments with optional parameters, quoted or not


code: A - B[:, np.newaxis]

rawDescription: broadcast numpy difference to a third dimension

description: Broadcast numpy difference to a third dimension


code:
class BaseTest(unittest.TestCase):

    def setUp(self):
        # This makes things nicer if the previous test fails
        # - without this all subsequent tests fail
        self.tearDown()

        self.config = testing.setUp()

    def tearDown(self):
        testing.tearDown()
        session.expunge_all()
        session.rollback()

rawDescription: Rolling back database transactions in SQLAlchemy tests with PostgreSQL


code:
import multiprocessing
import Queue

def functionA(return_queue):
    value1 = open()
    if (value1 != None):
        value2 = testcolor()
        return_queue.put(value2)
    else:
        value3 = close()
        return_queue.put(value3)

def functionB():

    return_queue = multiprocessing.Manager().Queue()

    proc = multiprocessing.Process(
        name='send_daemon%d', target=functionA, args=(return_queue,))
    proc.daemon = True
    proc.start()
    res = {'status': 'started' ,}

    try:
        # wait for two seconds for the function to return a value
        return_value = return_queue.get(timeout=2)
    except Queue.Empty:
        proc.terminate()
        return_value = None

    # do something with the return value here

    return json.dumps(res)

rawDescription: Timeout result if nothing returns from started process - Python


code: graph_draw(g, pos=p, bg_color=[1,1,1,1], output="example.png")

rawDescription: Changing background color in graph-tool

description: Changing background color in graph-tool


code:
import wx

class ChoicePanelTwo(wx.Panel):
    def __init__(self, parent, seed):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
        self.SetBackgroundColour('blue')
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.List = wx.ListCtrl(self, -1, style=wx.LC_REPORT)
        for i in range(seed):
            self.List.InsertStringItem(i, str(i))
        sizer.Add(self.List, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)

class ChoicePanelOne(wx.Panel):
    def __init__(self, parent, seed):
        wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY)
        self.SetBackgroundColour('green')
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.RegisterList = wx.Choicebook(self, wx.ID_ANY)
        sizer.Add(self.RegisterList, 1, wx.ALL|wx.EXPAND, 5)
        for i in range(seed):
            self.RegisterList.AddPage(ChoicePanelTwo(self.RegisterList, seed*50),  str(i))
        self.SetSizer(sizer)

class TreePanel(wx.Panel):
    def __init__(self, parent, seed):
        wx.Panel.__init__(self, parent, id=wx.ID_ANY)
        self.SetBackgroundColour('cyan')
        self.Choicbook = wx.Choicebook(self, wx.ID_ANY)
        for i in range(seed):
            self.Choicbook.AddPage(ChoicePanelOne(self.Choicbook, seed*2), str(i))
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.Choicbook, 1, wx.ALL|wx.EXPAND, 5)
        self.SetSizer(sizer)

class AppFrame(wx.Frame):
    """ The main frame of the application
    """
    title = 'Application'
    WindowSize = (1024, 768)
    seed = 2

    def __init__(self):
        wx.Frame.__init__(self, None, -1, self.title, size=self.WindowSize,
                          style=wx.MINIMIZE_BOX|wx.SYSTEM_MENU|wx.CAPTION|wx.CLOSE_BOX|wx.CLIP_CHILDREN)
        self.create_main_panel()

    def create_main_panel(self):
        self.panel = TreePanel(self, self.seed)

if __name__ == '__main__':
    app = wx.PySimpleApp()
    app.frame = AppFrame()
    app.frame.Show()
    app.MainLoop()

rawDescription: wxpython widgets within not responding to events

description: Wxpython widgets within not responding to events


code:
import turtle

def move_me(trt, step, n):
    while n > 0:
        tmp = trt.heading()
        trt.lt(90)
        trt.fd(step)
        trt.rt(90)
        trt.fd(step)
        move_me(trt, step / 2, n - 1)
        trt.fd(-2 * step)
        move_me(trt, step / 2, n - 1)
        trt.fd(step)
        trt.rt(90)
        trt.fd(2 * step)
        trt.rt(90)
        trt.fd(step)
        move_me(trt, step / 2, n - 1)
        trt.fd(-2 * step)
        move_me(trt, step / 2, n - 1)
        trt.fd(step)
        trt.rt(90)
        trt.fd(step)
        n -= 1
        trt.seth(tmp)

my_win = turtle.Screen()
my_turtle = turtle.Turtle()
my_turtle.speed(10)
move_me(my_turtle, 200, 3)

rawDescription: Python Turtle: Recursive function

description: Python Turtle: Recursive function


code:
sorted_by_diff.columns.set_levels([[u'value'], ['email', 'spam', 'diff']], inplace=True)
sorted_by_diff

rawDescription: How to reindex a multi-index pandas dataframe?

description: Reindex a multi-index pandas dataframe


rawDescription: How to get dictionary of RequestContext imported from django.template

description: Get dictionary of RequestContext imported from django.template


code: fruits = [{"name": name, "color": color} for name, color in zip(names, colors)]

rawDescription: the smart way to recombine these two lists in python

description: The smart way to recombine these two lists in python


code:
import os

directory = '/user_data/TEST'

def create_folders(basedir, subfolders):
    for subfolder in subfolders:
        if isinstance(subfolder, (list, tuple)):
            create_folders(os.path.join(basedir, subfolder[0]), subfolder[1])
        else:
            os.makedirs(os.path.join(basedir, subfolder))

create_folders(directory, [
    ('Project_Files', ['scene', 'assets', 'renders', 'textures']),
    'Reference', 'Images'])

rawDescription: Batch creation of folders

description: Batch creation of folders


code:
def redirector_app(environ, start_response):
   param = '' # Set the parameter you want to pass here
   start_response('301 Redirect', [('Location', 'http:/yourphpscript.com/?param=%s' % param),])
   # ...

rawDescription: How to make a python wsgi script return to php?

description: Make a python wsgi script return to php


code: [x for x in k if x.data in f]

rawDescription: Intersection of instance data and list

description: Intersection of instance data and list


code:
x = self.megacity.resourceloader.sound.mcintro
x.play()

rawDescription: Python: How do I prevent long variable names in scope


code:
import datetime
today = datetime.date.today()

userinput = input("Please enter your birthday(MM/DD):")
birthday = datetime.datetime.strptime(userinput, "%m/%d")
birthday = datetime.date(year=today.year, month=birthday.month, day=birthday.day)

if (birthday-today).days<0:
    birthday = datetime.date(year=today.year+1, month=birthday.month, day=birthday.day)

print("%d days to your next birthday!"%(birthday-today).days)

rawDescription: Displaying time in Python using "Strptime()"


rawDescription: Returning a file in uploads directory with web2py - strings issue


code:
my_dict = {}
with open('some file.txt', 'r') as f:
    for line in f:
        key, value = line.split(':')
        my_dict[key.strip()] = int(value)

rawDescription: need to read from a txt file into a dictionary

description: Need to read from a txt file into a dictionary


code:
so_df
so_df.index[3]
so_df2 = so_df.groupby(so_df.index).first()
so_df2
so_df2.index[3]

rawDescription: Pandas groupby strip timezone in index

description: Pandas groupby strip timezone in index


code:
i = 0
locations = [23424977,2459115, 2487956]
onoff = [1,2]
for switch in onoff:
    for location in locations:

     i += 1
     if i < 4:
         trends1 = api.trends_place(location,include='hashtags')
     if i >=4:
         trends1 = api.trends_place(location,exclude='hashtags')

rawDescription: Double for loop

description: Double for loop


code:
m = db.inspect(MyModel)
# all orm attributes
print(list(m.all_orm_descriptors.keys()))
# just the columns
print(list(m.columns.keys()))
# etc.

rawDescription: Accessing all columns from MySQL table using flask sqlalchemy


rawDescription: Applying a probabilistic function over specific element of an array individually with Numpy/Python


code:
def wavg(subdf):
    series = pd.Series()
    subdf = subdf.dropna(subset=['data'])

    series['np.mean'] = np.mean(subdf['data'])
    series['np.average (no weights)'] = np.average(subdf['data'])
    series['np.average (weighted)'] = np.average(subdf['data'], weights=subdf['Weights'])
    series['np.ma.average (weighted)'] = np.ma.average(subdf['data'], weights=subdf['Weights'])

    return series

rawDescription: np.average not working when data is missing when using pandas groupby

description: Np.average not working when data is missing when using pandas groupby


code:
def helpMenuStatusBar(self, event = None):
   if self.parent.call(event.widget, "index", "active") == 0:
      self.statusBar.set("Select available files")
   elif self.parent.call(event.widget, "index", "active") == 2:
      self.statusBar.set("About This Application")
   else:
      self.statusBar.set("")

rawDescription: Python Tkinter: Status bar not working if menu uses add_separator


code:
timeit.timeit('for i in seq: pass', 'seq=range(1000000)', number=100)
timeit.timeit('for i in iter(seq): pass', 'seq=range(1000000)', number=100)

rawDescription: Why would iterating over a list be much slower than iterating over an iterator in python?


rawDescription: rolling mean with python 2.7

description: Rolling mean with python 2.7


code:
def calc_estimated_weight_total(self):
    if self.sale_head <= 0:
        amount = (self.number * self.estimated_weight_hd)
        return amount
    else:
        return something_only_you_know

def save(self):
    self.estimated_total_weight = self.calc_estimated_weight_total()
    super(SaleNote, self).save()

rawDescription: If statement in Django not working in properly


code:
import Tkinter as tk
root = tk.Tk()
data = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9P
          T6Ai8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYY
          fh8GIEvpoUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYw
          YtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEi
          gnKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5Fo
          fsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
       '''
img = tk.PhotoImage(data=data)
label = tk.Label(image=img)
label.pack()
root.mainloop()

rawDescription: Use file like objects for Tk().iconbitmap()


code: return dict(reversed(lst))

rawDescription: How to create a dictionary from a list of tuples without overwriting the first unique key value?

description: Create a dictionary from a list of tuples without overwriting the first unique key value


code:
from bs4 import BeautifulSoup

html = '''

         Agency Fees:
         AED 5000

         Bedrooms:
         Studio

         Bathrooms:
         1

'''

soup = BeautifulSoup(html)
spans = [x.text.strip() for x in soup.select('ul.important-fields li span')]
strongs = [x.text.strip() for x in soup.select('ul.important-fields li strong')]
spans
strongs
for name, value in zip(spans, strongs):
    print('{} {}'.format(name, value))

rawDescription: How to scrap the html data with same kind of tags

description: Scrap the html data with same kind of tags


code:
df = DataFrame({'a': randn(1000, 1)})
df['user_id'] = randint(100, 1000, size=len(df))
df['article_id'] = randint(100, size=len(df))
gb = df.article_id.groupby(df.user_id)
gb.nunique()

rawDescription: Counting unique values in a pandas grouped object


code:
startime = datetime.now()
res = opener.open(url, timeout=timeout)
contents = ''
for item in res:
  contents += item
  if (datetime.now() - starttime).seconds > timeout:
    raise IOError('timeout')

rawDescription: How to use urllib2 to open an 'infinite' jpg?

description: Use urllib2 to open an 'infinite' jpg


rawDescription: Not True, Python similar to R

description: Not True, Python similar to R


code:
comments = []
for (counter, line) in enumerate(visible_texts):
    if line.lstrip().startswith('#'):
        comments.append(line)
    elif "def" in line and not infunction:
        comment = '\n'.join(comments)
        comments = []
        # rest of your code
    else:
        comments = []

rawDescription: How do I reverse my for loop when I'm parsing a text file (python)

description: Reverse my for loop when I'm parsing a text file (python)


rawDescription: Splitting Dataframe based on corresponding numpy array values


code:
class Tag(Base):
    __tablename__ = 'tag'

    id = Column(Integer, primary_key=True)
    label = Column(String)
    parent_id = Column(Integer, ForeignKey('tag.id'))

    parent = relation('Tag', remote_side=[id])

rawDescription: sqlalchemy - Mapping self-referential relationship as one to many (declarative form)

description: Sqlalchemy - Mapping self-referential relationship as one to many (declarative form)


code:
for i in range(len(myList)):

    f.write(str(time.strftime("%Y_%m_%d_%H_%M_%S",
                      time.localtime(currentTime + i))))
    f.write(',')
    f.write(" ")
    f.write(str(myList[i]))
    f.write('\n')

rawDescription: How to log "n" numbers along with their corresponding time? Beginner task

description: Log "n" numbers along with their corresponding time? Beginner task


rawDescription: Python Tornado - making POST return immediately while async function keeps working


code:
import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.line_whole = [tk.IntVar() for _ in range(6)]
        self.createWidgets()

    def createWidgets(self):
        #self.line_whole = [tk.IntVar() for _ in range(6)]
        self.line_whole_cb = list()
        for x in range(6):
            self.line_whole_cb.append(tk.Checkbutton(self,
                variable=self.line_whole[x]))
            self.line_whole_cb[x].pack(side="left")
        self.test_val = tk.IntVar()
        self.test_cb = tk.Checkbutton(self,variable=self.test_val)
        self.test_cb.pack(side="bottom")
        self.output_record_btn = tk.Button(self)
        self.output_record_btn["text"] = "Output Check Values"
        self.output_record_btn["command"] = self.say_hi
        self.output_record_btn.pack(side="top")

        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="bottom")

    def say_hi(self):
        print("checks:",",".join([str(tk_int.get()) for tk_int in self.line_whole]))
        print ("test_check",self.test_val.get())

root = tk.Tk()
app = Application(master=root)
root.mainloop()

rawDescription: Why do PyTk Tkinter control value variables fail to update if stored in a list? What is the alternative?


rawDescription: split string by arbitrary number of white spaces

description: Split string by arbitrary number of white spaces


rawDescription: Numpy way to set all values in a specific dimension of an array


code:
poly = [(0,10),(10,10),(10,0),(0,0)]

def segments(poly):
        """A sequence of (x,y) numeric coordinates pairs """
        return zip(poly, poly[1:] + [poly[0]])

def area(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return 0.5 * abs(sum(x0*y1 - x1*y0
        for ((x0, y0), (x1, y1)) in segments(poly)))

def perimeter(poly):
    """A sequence of (x,y) numeric coordinates pairs """
    return abs(sum(math.hypot(x0-x1,y0-y1) for ((x0, y0), (x1, y1)) in segments(poly)))

rawDescription: Python how calculate a polygon perimeter using an osgeo.ogr.Geometry object


rawDescription: Passing precision as parameter to python format


code:
import operator
import csv
import os
import string

vals = operator.itemgetter(0,2)
lab = string.Template("lab${n}")

with open('path/to/input') as infile, open('path/to/output', 'w') as fout:
    outfile = csv.writer(fout, delimiter='\t')
    for labnum,row in enumerate(csv.reader(infile, delimiter='\t'), 1):
        num, fname = vals(row)
        fpath = os.path.join(num, fname)
        # do file operations with fpath
        row.append(lab.substitute(n=labnum))

        outfile.writerow(row)

rawDescription: Read Text file only first and last column, latter write last column with TAG NAme


code:
import re
s = 'Brand New Song [demonstration]'
bool(re.search (r'\[Demonstration\]', s, re.IGNORECASE))

rawDescription: Can't get a regex to handle brackets properly


code:
def getOutTitleFromTable(htmlSoup):
   for ii, table in enumerate(htmlSoup.findAll("table")):
      h2s = table.findAll("h2") # on cherche tous les

 dans le tableau
      #print h2s
      if len(h2s) > 0: #si on a au moins 1
 dans le tableau
         FirstH2 = True
         LastH2 = False
         newTables = BeautifulSoup() # contiendra nos tableaux reconstitués
         for i, h2 in enumerate(h2s):
            if h2 is not []:
               LastH2 = ( i == len(h2s) - 1 )
               h2.parent.replaceWithChildren() # on supprime le
               h2.parent.replaceWithChildren() # on supprime le

               idT = "table"+str(ii)+str(i) # création d'un id de tableau pour une meilleure lisibilité
               wrapTable = Tag(htmlSoup, "table")
               wrapTable["id"]=idT
               wrapTable["border"]=0
               wrapTable["cellpadding"]=0
               wrapTable["cellspacing"]=0
               #print h2.parent.contents.index(h2) # index du h2 dans l'arbre table
               table.insert(h2.parent.contents.index(h2)+1, wrapTable) # on ajoute

 après chaque
"title"

               #newTable = table.findAll("table")
               newTable = table.find(name="table", attrs={"id" : idT})
               fillTable = False
               #print table.findAll(["h2","tr"])
               for tr in table.findAll(["h2","tr"]):
                  if fillTable:
                     if tr in h2s:
                        #print "fin du nouveau tableau"
                        #print tr
                        fillTable = False
                        break
                     else:
                        if tr.find("h2") not in h2s:
                           #print "ajout d'une nouvelle ligne: "
                           newTable.contents.append(tr)
                           #print newTable.contents

                  if str(tr) == str(h2):
                     #print "Début du nouveau tableau"
                     #print tr
                     fillTable = True

               newTables.append(h2)
               newTables.append(newTable)

               #os.system("pause")

               #print h2
               #print FirstH2
               #print LastH2
               FirstH2 = False

         #print newTables
         table.contents = newTables
         table.name = "div" # On change la balise table en div... on triche mais je n'arrive absolument pas à retirer le wrap

rawDescription: split a table into several with Beautiful Soup [Python]

description: Split a table into several with Beautiful Soup [Python]


code:
class Final(type):
    def __new__(cls, name, bases, classdict):
        for b in bases:
            if isinstance(b, Final):
                raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__))
        return type.__new__(cls, name, bases, dict(classdict))

class C(metaclass=Final): pass

class D(C): pass

rawDescription: In Python, how can I prohibit class inheritance?


code:
from kivy.core.image import Image as CoreImage
from kivy.uix.image import Image
import sqlite3 as lite
import io

# load an image from db , CREATE TABLE Images(Id INTEGER PRIMARY KEY, Data BLOB); > this was the db created ...

con = lite.connect('images.db') # assume images.db is an sqlite3 db
with con:
    cur = con.cursor()
    cur.execute("SELECT Data FROM Images;") # png is the image extension
    blob_data = cur.fetchone()[0] # fetching one image data only

# load image from memory , as in  http://kivy.org/docs/api-kivy.core.image.html#in-memory-image-loading
data = io.BytesIO(blob_data)
im = CoreImage(data, ext="png")

# using im, as a texture for an Image , for example:
class LoadedImage(Image):
    def __init__(self, **kwargs):
        super(LoadedImage, self).__init__(**kwargs)
        self.texture = im.texture # using the texture

rawDescription: Retrieve Image from sqlite3 database and directly display on kivy window


rawDescription: How get related objects by field name?

description: How get related objects by field name


code:
from werkzeug.serving import BaseRequestHandler
from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return "hi"

class MyRequestHandler(BaseRequestHandler):
    def log_request(self, code='-', size='-'):
        self.log('info', 'custom log! "%s" %s %s', self.requestline, code, size)

if __name__ == '__main__':
    app.run(debug=True, request_handler=MyRequestHandler)

rawDescription: How can I add an id from flask's global 'g' object in the access log?

description: Add an id from flask's global 'g' object in the access log


code:
import datetime
datetime.datetime.today()
datetime.datetime.today().weekday()

rawDescription: which day of week given a date python

description: Which day of week given a date python


code:
def func(df1):
    idx = df1.index.get_level_values(0)[0]
    df1 = df1.loc[idx]
    return (df1['Values'] / df1.loc['Calc']['Values']).to_frame()

df.groupby(level=0).apply(func)

rawDescription: Operations on pandas dataframe between values of specific columns / rows


code:
def ParseSymbol(self, regex):
    attributes = ['Section', 'Class', 'Subclass', 'Group', 'Subgroup']

    Pattern_groups = re.search(regex, self.Symbol)

    for group, attr in zip(Pattern_groups.groups(), attributes):
        setattr(self, attr, group)

rawDescription: How to dynamically assign values to class properties in Python?

description: Dynamically assign values to class properties in Python


code:
text = input('Enter your text: ')

_in = "helo"
out = "Gwki"

print(text.translate(text.maketrans(_in, out)))

rawDescription: Modifying I/O Data in Python

description: Modifying I/O Data in Python


code:
import collections

class FrequencyString(str):
    @property
    def normalized(self):
        try:
            return self._normalized
        except AttributeError:
            self._normalized = normalized = ''.join(sorted(collections.Counter(self).elements()))
            return normalized

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

    def __hash__(self):
        return hash(self.normalized)

rawDescription: Python Overriding String __hash__

description: Python Overriding String __hash__


code:
def retOBJECT(tup):
    for l_name, l in [('a',a),('b',b)]:
        for v in l:
            if tup in l[v]:
                return l_name, v,l[v][1]

rawDescription: Loop through multiple dicionaries and get name of dict in which value is


code:
from collections import Counter
s=['1 12 4', '2 2 3', '23 32 1','1 12 4']
Counter(s)

rawDescription: Python: Populate a large list of string occurences


code: FilteredData = AllData[my_dict.keys()]

rawDescription: Filter a pandas DataFrame using keys from a dictionary


code:
element = driver.find_element_by_class_name('abc')
href = element.get_attribute('href')
href # => u'http://example.com/'

rawDescription: Get link from page - python

description: Get link from page - python


code:
from threading import Timer

from matplotlib import pyplot as plt
import numpy

# Your data generating code here
def get_data():
    data = numpy.random.random(100)
    label = str(data[0]) # dummy label
    return data, label

def update():
    print('update')
    plt.clf()
    data, label = get_data()
    plt.plot(data, label=label)
    plt.legend()
    plt.draw()
    t = Timer(0.5, update) # restart update in 0.5 seconds
    t.start()

update()
plt.show()

rawDescription: Python3x + MatPlotLib - Updating a chart?


code: scipy.stats.pearsonr(x, y)

rawDescription: Calculating Pearson correlation

description: Calculating Pearson correlation


code:
ASXCodes = ('CSL', 'XXX', 'YYY')
for ASXCode in ASXCodes:
    local_filename = "c:\\myfiles\\foobar\\" + ASXCode + ".csv"
    print("Saving to {}".format(local_filename))
    with open(local_filename, 'w', newline='') as outf:
        ...
print("done")

rawDescription: Setting the save file directory and arrays


rawDescription: generating compiled Tkinter python code

description: Generating compiled Tkinter python code


code:
for machine in enable:
    enable[machine] = Variable()
    l = Checkbutton(self.root, text=machine, variable=enable[machine])
    l.pack()

self.root.mainloop()

rawDescription: How do I create multiple checkboxes from a list in a for loop in python tkinter

description: Create multiple checkboxes from a list in a for loop in python tkinter


code:
from django.core.mail import send_mail

def form_valid(self, form):
    super(QuoteView,self).form_valid(form)
    send_mail("Foo", "bar", 'from@example.com', [form.cleaned_data['email']])
    return HttpResponseRedirect(self.get_success_url())

rawDescription: Django contact form confirmation email

description: Django contact form confirmation email


code:
from itertools import groupby
with open("rosalind_gcsamp.txt","r") as gc:
    # group elements using  lines that start with ">" as the delimiter
    groups = groupby(gc, key=lambda x: not x.startswith(">"))
    d = {}
    for k,v in groups:
        # if k is False we a non match to our not x.startswith(">")
        # so use the value v as the key and call next on the grouper object
        # to get the next value
        if not k:
            key, val = list(v)[0].rstrip(), "".join(map(str.rstrip,next(groups)[1],""))
            d[key] = val

print(d)
{'>Rosalind_0808': 'CCACCCTCGTGGTATGGCTAGGCATTCAGGAACCGGAGAACGCTTCAGACCAGCCCGGACTGGGAACCTGCGGGCAGTAGGTGGAAT', '>Rosalind_5959': 'CCATCGGTAGCGCATCCTTAGTCCAATTAAGTCCCTATCCAGGCGCTCCGCCGAAGGTCTATATCCATTTGTCAGCAGACACGC', '>Rosalind_6404': 'CCTGCGGAAGATCGGCACTAGAATAGCCAGAACCGTTTCTCTGAGGCTTCCGGCCTTCCCTCCCACTAATAATTCTGAGG'}

rawDescription: Constantly getting IndexError and am unsure why in Python


code:
daemonSocket = socket.socket()
...
phpListenSocket = socket.socket()
phpListenSocket.bind(...)
phpListenSocket.listen(...)
phpSocket = None

while True:
    rlist = ...
    rready, wready, eready = select(rlist, [], [])
    if phpListenSocket in rready:
        phpSocket, remoteAddr = phpListenSocket.accept()

rawDescription: Multiple socket monitoring

description: Multiple socket monitoring


code:
list1 = [0,1,2]
list2 = [0,1]
list3 = [0,1,2,3]
listOfLists = [list1,list2,list3]
for list in itertools.product(*listOfLists):
    print(list)

rawDescription: Make all possible n length permutations from n lists of integers (of possibly unequal length)


code:
df["n_count"] = df.groupby(["user", "class"]).cumcount() + 1
df

rawDescription: Creating a column of count in pandas dataframe


code:
def find_listcomp(students, value):
    return [student for student in students if student[1] == value or student[2] == value]

def find_filter(students, value):
    return filter(lambda s: s[1] == value or s[2] == value, students)

rawDescription: Using python how to find elements in a list of lists based on a key that is an element of the inner list?


code: grid_u_x, grid_u_y = interpolator.gradient(grid_x, grid_y)

rawDescription: Streamlines on a triangulation with matplotlib


code:
from Tkinter import*

class MyOptionMenu(OptionMenu):
    def __init__(self, master, status, *options):
        self.var = StringVar(master)
        self.var.set(status)
        OptionMenu.__init__(self, master, self.var, *options)
        self.config(font=('calibri',(10)),bg='white',width=12)
        self['menu'].config(font=('calibri',(10)),bg='white')

root = Tk()
mymenu1 = MyOptionMenu(root, 'Select status', 'a','b','c')
mymenu2 = MyOptionMenu(root, 'Select another status', 'd','e','f')
mymenu1.pack()
mymenu2.pack()
root.mainloop()

rawDescription: Python tkinter option menu

description: Python tkinter option menu


code:
import os
"\x00"+os.urandom(4)+"\x00"

rawDescription: random byte string in python

description: Random byte string in python


code: temp = [x[:] for x in originalList]

rawDescription: Original list gets modified in python

description: Original list gets modified in python


code:
box_top = (0, 0, x, y / 2)
top_part = im1.crop(box_top)
result = im2.copy()
result.paste(top_part, box_top)

rawDescription: paste parts of picture - python, PIL module

description: Paste parts of picture - python, PIL module


code:
cell = rnn_cell.BasicLSTMCell(num_nodes)

with tf.variable_scope("LSTM") as vs:
  # Execute the LSTM cell here in any way, for example:
  for i in range(num_steps):
    output[i], state = cell(input_data[i], state)

  # Retrieve just the LSTM variables.
  lstm_variables = [v for v in tf.all_variables()
                    if v.name.startswith(vs.name)]

# [..]
# Initialize the LSTM variables.
tf.initialize_variables(lstm_variables)

rawDescription: Tensorflow: How to get all variables from rnn_cell.BasicLSTM & rnn_cell.MultiRNNCell


rawDescription: Python search and replace in a file

description: Python search and replace in a file


code:
import pylab
pylab.plot(x, y, '.')
pylab.savefig('myfilename.pdf')

rawDescription: create a simple point plot in Python

description: Create a simple point plot in Python


code:
from functools import partial
dec = partial(int, base=36)
r = "AF:IK"
lo, hi = r.split(':')
dec(lo) < dec("BX") < dec(hi)
dec(lo) < dec("BXA") < dec(hi)

rawDescription: Iterate through excel-like range of character combinations


code:
lower = x / 3 + 2
upper = x / 2 + 3
myarray[lower:upper:2]

rawDescription: What is the recommended whitespace for slicing with expression indices in Python?


code:
def __repr__(self):
    ...
    return 'Deck : '+str(self._deck)

rawDescription: How to properly implement/overload "__repr__ "?

description: Properly implement/overload "__repr__ "


code:
xl = pd.ExcelFile("C:\GreenCSV\Calgary\CWater.xlsx")
xl.sheet_names  # in your example it may be different
dfs = {sheet: xl.parse(sheet) for sheet in xl.sheet_names}
dfs['Sheet1'] # access DataFrame by sheet name

rawDescription: Organizing data read from Excel to Pandas DataFrame


code:
import sys
from PyQt4 import QtGui
import urllib.request

class Example(QtGui.QWidget):

    def __init__(self):
        super(Example, self).__init__()

        self.initUI()

    def initUI(self):
        hbox = QtGui.QHBoxLayout(self)

        url = 'http://www.google.com/images/srpr/logo1w.png'
        data = urllib.request.urlopen(url).read()

        image = QtGui.QImage()
        image.loadFromData(data)

        lbl = QtGui.QLabel(self)
        lbl.setPixmap(QtGui.QPixmap(image))

        hbox.addWidget(lbl)
        self.setLayout(hbox)

        self.show()

def main():

    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

rawDescription: PyQt4 and Python 3 - Display an image from URL


code:
data = [row for row in csv.DictReader(open('C:\\my.csv'),
                                      ('num','time','time2'))]
len(data)  # lots of old data :P
data[1].keys()
keyeddata = {}
for row in data[2:]:  # I have some junk rows
    keyeddata[row['num']] = row
keyeddata['32']

rawDescription: using Python to import a CSV (lookup table) and add GPS coordinates to another output CSV

description: Using Python to import a CSV (lookup table) and add GPS coordinates to another output CSV


code:
import tweepy
# http://dev.twitter.com/apps/myappid
CONSUMER_KEY = 'my consumer key'
CONSUMER_SECRET = 'my consumer secret'
# http://dev.twitter.com/apps/myappid/my_token
ACCESS_TOKEN_KEY= 'my access token key'
ACCESS_TOKEN_SECRET= 'my access token secret'

def tweet(status):
    '''
    updates the status of my twitter account
    requires tweepy (https://github.com/joshthecoder/tweepy)
    '''
    if len(status) > 140:
        raise Exception('status message is too long!')
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN_KEY, ACCESS_TOKEN_SECRET)
    api = tweepy.API(auth)
    result = api.update_status(status)
    return result

rawDescription: Twitter API: simple status update (Python)


code:
from itertools import groupby

repos = [(r.report_name, r.updated_on) for r in repo]
repos.sort()  # sorts by name and date

# group by name and collect dates, use as key/value in dict-comprehension
result = {k: [r[1] for r in g] for k, g in groupby(repos, lambda x: x[0])}

rawDescription: How to get multiple rows values in single row using dict and list

description: Get multiple rows values in single row using dict and list


code:
if value in uniqueWordList:
    epicDict.setdefault(value,[]).append(word)

rawDescription: Speed up n-gram processing

description: Speed up n-gram processing


code: new_devid = d.get(old_devid)

rawDescription: use a dictionary to change element text in xml

description: Use a dictionary to change element text in xml


code: '//a[contains(., "{}")]'.format(text)

rawDescription: How to get the element from the text using Selenium Webdriver in Python

description: Get the element from the text using Selenium Webdriver in Python


rawDescription: Refer to a signal whose name is passed as string (new-style signals/slots)?


code:
import collections
person_info = collections.defaultdict(dict)
for person in person_profile:
    person_info[person.id].update({'name': person.name, 'age': person.age})
for person in person_attribute:
    person_info[person.id].update({'occupation': person.occupation, 'gender': person.gender})

rawDescription: Create Dictionary of Dictionary Python

description: Create Dictionary of Dictionary Python


code:
prediction = []

for i in range(len(test_labels)):
    if test_labels[i] == my_labels[i]:
        prediction.append("true")
    else:
        prediction.append("false")

rawDescription: Lİst Value Comparison - For loop iteration


code: "INSERT INTO table (col1,col2,col3,col4) VALUES ('%s','%s','%s','%s')" % tuple(mylist)

rawDescription: INSERT query for python

description: INSERT query for python


code:
def index():
    test1result = test1(request.form['data'])
    test2result = test2(request.form['data'])
    test3result = test3(request.form['data'])
    if not test1result:
        message = 'Failed test 1'
    elif not test2result:
        message = 'Failed test 2'
    elif not test3result:
        message = 'Failed test 3'

    return render_template('index.html', message = message)

rawDescription: Is there a way to “break” or “continue” within a Python function?


code:
y = x[:n]
print(y)

rawDescription: select first n items of a list without using a loop.

description: Select first n items of a list without using a loop.


code:
for toolbar in mainwindow.findChildren(QToolBar):
    print('toolbar: %s' % toolbar.objectName())
    for action in toolbar.actions():
        if not action.isSeparator():
            print('  action: %s (%s)' % (action.text(), action.isChecked()))

rawDescription: Iterate QAction items on a given QToolBar object in PyQt?


code:
sum(1,2)
sum([1,2])
sum(x)
sum([b for b in x if b >0])
reduce(lambda x, y: x+y, x)
reduce(lambda x, y: x+y, [b for b in x if b > 0])
reduce(lambda x, y: x+y, [b for b in x if b > 1])

rawDescription: int object is not iterable python

description: Int object is not iterable python


code:
vel += accel * deltaT
d += vel * deltaT

rawDescription: Python Bungee Cord Simulation

description: Python Bungee Cord Simulation


code:
import sys

for cnt,v in enumerate(range(250,755,5)):
    if cnt%15==14:
        sys.stdout.write("%d\n" % v)
    else:
        sys.stdout.write("%d " % v)

rawDescription: Output formatting based on user parameters


rawDescription: wxPython image with url

description: WxPython image with url


code:
from Tkinter import *
from ttk import *

root = Tk()
noteBook = Notebook(root)
root.focus()
tab1 = Frame(noteBook)
tab2 = Frame(noteBook)
Label(tab2, text='Test', width=15).grid(row=3,column=0, sticky=W)
Entry(tab2, width=40, takefocus=False).grid(row=3,column=1)
noteBook.add(tab1, text = "tab 1", compound=TOP)
noteBook.add(tab2, text = "tab 2")
noteBook.pack()
root.mainloop()

rawDescription: How can I prevent entrybox to get focus when switching to a new ttk notebook tab python?

description: Prevent entrybox to get focus when switching to a new ttk notebook tab python


code:
df
df.drop_duplicates()

rawDescription: iterate rows and print based on condition pandas python

description: Iterate rows and print based on condition pandas python


rawDescription: Is there a way in Python to create a tuple of the components matched in a regular expression?


rawDescription: pandas: find the first shipped product from a DataFrame

description: Pandas: find the first shipped product from a DataFrame


code:
from datetime import datetime
import time

while True:
    now = datetime.now()
    if now.hour == 7 and now.minute == 15:
        foo()
    time.sleep(10)

rawDescription: Python timer script doesn't run when set to long periods later


code:
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(html)

nextNode = soup.find('p', {'class': 'top'})
while True:
    # process
    nextNode = nextNode.nextSibling
    if getattr(nextNode, 'name', None)  == 'p' and nextNode.get('class', None) == 'end':
        break

rawDescription: Use BeautifulSoup to extract sibling nodes between two nodes


code:
import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABC')
row_labels = range(7)
data = np.random.rand(7,3)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1])+0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0])+0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

rawDescription: limit columns in matplotlib heatmap

description: Limit columns in matplotlib heatmap


code: subprocess.call(['/dir6/dir5/dir4/openssl', 'enc', '-d', '-aes-256-cbc', '-a', '-in', '/home/dir2/dir3/XXX.enc' ,'-pass' , 'pass:password'])

rawDescription: Running a UNIX command via python script


code:
from IPython.display import display
import sympy as sy
from sympy.solvers.ode import dsolve
import matplotlib.pyplot as plt
import numpy as np

sy.init_printing()  # LaTeX like pretty printing for IPython

t = sy.symbols("t", real=True)
f = sy.symbols("f", function=True)

eq1 = sy.Eq(f(t).diff(t), f(t)**4)  # the equation
sls = dsolve(eq1)  # solvde ODE

# print solutions:
print("For ode")
display(eq1)
print("the solutions are:")
for s in sls:
    display(s)

# plot solutions:
x = np.linspace(0, 2, 100)
fg, axx = plt.subplots(2, 1)
axx[0].set_title("Real part of solution of $\\frac{d}{dt}f(t)= (f(t))^4$")
axx[1].set_title("Imag. part of solution of $\\frac{d}{dt}f(t)= (f(t))^4$")
fg.suptitle("$C_1=0.1$")
for i, s in enumerate(sls, start=1):
    fn1 = s.rhs.subs("C1", .1)  # C_1 -> 1
    fn2 = sy.lambdify(t, fn1, modules="numpy")  # make numpy function
    y = fn2(x+0j)  # needs to be called with complex number
    axx[0].plot(x, np.real(y), label="Sol. %d" % i)
    axx[1].plot(x, np.imag(y), label="Sol. %d" % i)
for ax in axx:
    ax.legend(loc="best")
    ax.grid(True)
axx[0].set_ylabel("Re$\\{f(t)\\}$")
axx[1].set_ylabel("Im$\\{f(t)\\}$")
axx[-1].set_xlabel("$t$")
fg.canvas.draw()
plt.show()

rawDescription: Solving nonlinear differential first order equations using Python


code:
# Define the indices
myList = [(1,2,2), (0,0,2), (100,122,200), (3, 4, 5)]
# Define the array (just random numbers)
myArray = np.random.uniform(size=(101, 201, 201))
# Extract the indices
a, b, c = np.transpose(myList)
# Slice the numpy array and sum
mySum = np.sum(myArray[a, b, c])

rawDescription: Getting elements within a numpy array by using a list of tuples as indices in python


rawDescription: How to round to a certain amount of decimals while leaving a 0

description: Round to a certain amount of decimals while leaving a 0


code:
with open('File1') as f1, open('File2') as f2:
    columns_a = set(tuple(sorted(l.split())) for l in f1)
    columns_b = set(tuple(sorted(l.split())) for l in f2)

with open('matching', 'w') as out:
    for elem in columns_a  & columns_b:
        out.write('{a} \n'.format(a = '\t'.join(elem)))

rawDescription: efficient way to compare elements between very long lists

description: Efficient way to compare elements between very long lists


code:
maxs, mins = {}, {}
for line in fd:
    category, small, big = line.split()
    if category not in maxs or big > maxs[category]:
        maxs[category] = big
    if category not in mins or small < mins[category]:
        mins[category] = small

# final printings
for category in maxs:
    print(category, mins[category], maxs[category], sep='\t')

rawDescription: Collapse information according to certain column of a line


code: errorThread = Thread(target=lambda: tkMessageBox.showerror("Error", b[-1][z:]))

rawDescription: Can you execute a single line as a target of a python Thread?

description: Execute a single line as a target of a python Thread


code:
class LivingThing(object):
    def __init__(self, lifespan):
        self.lifespan = lifespan

    def lifespan_info(self):
        print("this object's lifespan is {}".format(lifespan))

class Person(LivingThing):
    # inherits from LivingThing
    def __init__(self, gender):
        LivingThing.__init__(self, 80)
        self.gender = gender

    def gender_info(self):
        print("this object's gender is {}".format(gender))

person1 = Person("male")
person1.lifespan_info()
person1.gender_info()

rawDescription: Object with class in python

description: Object with class in python


code:
from django.db.models import F

Obj.objects.filter(customid__gt=3).update(customid=F('customid') - 1)

rawDescription: How to update multiple objects and increment from 0 to first if filtered to last

description: Update multiple objects and increment from 0 to first if filtered to last


code:
import pandas as pd
df = pd.read_pickle('flux.df')

rawDescription: how to read a data file including "pandas.core.frame, numpy.core.multiarray"

description: Read a data file including "pandas.core.frame, numpy.core.multiarray"


code:
key = "testtest12"
mapping = range(256)

keylen = len(key)
maplen = len(mapping)

for i, v in enumerate(mapping):
    c = ord(key[i % keylen])
    t = (i + c) % maplen
    mapping[i] = mapping[t]
    mapping[t] = v

rawDescription: Create a pseudo random table based on user input


code:
code
import csv
import itertools
from operator import itemgetter
import StringIO

def filter_data(data):
    for classname, group in itertools.groupby(data, itemgetter(2)):
        filtered_group = [line for line in group]
        new_count = len(filtered_group)
        for line in filtered_group:
            if line[5] == "Count":
                line[5] = "Counter"
            else:
                line[5] = new_count
            yield ','.join(map(str, line)) + '\n'

output = StringIO.StringIO()

with open('../main.csv', 'rb') as f_in:
    reader = csv.reader(f_in)
    output.writelines(filter_data(reader))

contents = output.getvalue()
output.close()

with open('../main.csv', 'wb') as f_out:
    f_out.writelines(contents)

rawDescription: Using csv.reader and csv.writer to write to the same file instead of different files?


code:
from collections import namedtuple
value = namedtuple('Value', 'N')(len(roots["roots"]))

rawDescription: Can you create a value referenced with dot "." python

description: Create a value referenced with dot "." python


code:
CA = [0,4,0,3,0,5]
CB = [0,0,4,4,2,2,2,2,3,0,5]
CC = [0.08423, 4.0078, 0.02936, 0.04862, 3.2105, 3.7796, 1.9974, 1.6986, 1.7443, 1.6615, 1, 1, 1]

lists = [CA, CB, CC]

x = []
y = []
for index1, my_list in enumerate(lists):
    scores_bins = {}
    for index2, score in enumerate(my_list):
        binx = round(score, 1)
        if binx not in scores_bins:
            scores_bins[binx] = []
        scores_bins[binx].append(score)

    for key, val in sorted(scores_bins.items()):
        values = scores_bins[key]
        points = len(values)
        pos = 1 + index1 + (1 - points) / 50.
        for value in values:
            x.append(pos)
            y.append(value)
            pos += 0.05

plt.plot(x, y, 'o')
plt.xlim((0,4))
plt.ylim((-1,6))

plt.show()

rawDescription: Matplotlib: Non-random jitter

description: Matplotlib: Non-random jitter


rawDescription: Matching all Full Quotes with Regex

description: Matching all Full Quotes with Regex


rawDescription: Two different plots from same loop in matplotlib?


code:
import threading, time
from gi.repository import Gtk, Gdk, GLib # need GLib for GLib.PRIORITY_DEFAULT

# a short utility function that I like to use.
# makes the Gtk thread execute the given callback.
def add_mainloop_task(callback, *args):
    def cb(args):
        args[0](*args[1:])
        return False
    args= [callback]+list(args)
    Gdk.threads_add_idle(GLib.PRIORITY_DEFAULT, cb, args)

def background(label, parent):
    for t in range(5):
        #~ label.set_text(str(t)) # let the gtk thread do this.
        add_mainloop_task(label.set_text, str(t))
        time.sleep(1)
    #~ Gdk.threads_enter() # don't need this.
    dlg = Gtk.MessageDialog(
                type=Gtk.MessageType.INFO,
                buttons=Gtk.ButtonsType.OK,
                message_format="Time is gone.",
                title="Info")

    # put these two functions calls inside a little function, and let the gtk thread execute it.
    def run_dialog(dlg):
        dlg.run()
        dlg.destroy()
    add_mainloop_task(run_dialog, dlg)
    #~ Gdk.threads_leave() # don't need this.

def main():
    window = Gtk.Window()
    window.connect("delete-event", Gtk.main_quit)
    label = Gtk.Label()
    window.add(label)
    window.show_all()
    thread = threading.Thread(target=background, args=(label, window))
    Gdk.threads_init()
    #~ Gdk.threads_enter() # don't need this.
    thread.start()
    Gtk.main()
    #~ Gdk.threads_leave() # don't need this.

if __name__=="__main__":
    main()

rawDescription: Dialog in thread freeze whole app despite Gdk.threads_enter/leave()


code:
# Read the file first and split lines in a list
with open('temp.txt', 'r') as f:
    lines = f.read().splitlines()

# Loop through lines, two at a time
for i in range(0, len(lines), 2):   # Notice the last argument '2', it makes the loop step 2 at a time
    val1 = lines[i]
    val2 = lines[i+1]
    # Perform calculation on val1 and val2

rawDescription: fetch two values in python from .txt file

description: Fetch two values in python from .txt file


rawDescription: Index with an unknown number of indices

description: Index with an unknown number of indices


code:
import math
import anothermodule
import anotherothermodule

rawDescription: preload some libraries and scripts in python

description: Preload some libraries and scripts in python


code:
rand_str = lambda n: ''.join([random.choice(string.lowercase) for i in xrange(n)])
# Now to generate a random string of length 10
s = rand_str(10)

rawDescription: How to generate a random string

description: Generate a random string


code:
def determine_grade(grade):
    if 90 <= grade <= 100:
        return "A"
    if 80 <= grade <= 89:
        return "B"
    if 70 <= grade <= 79:
        return "C"
    if 60 <= grade <= 69:
        return "D"
    if grade < 60:
        return "F"
    return "error"

def main():
    grades = []
    cont = input("continue ('y')?")
    while cont == "y" or cont == "Y":
        grade = float(input("Enter score: "))
        print("Grade: " + determine_grade(grade))
        grades.append(grade)
        cont = input("continue ('y')?")
    print("Average: {0:.2f}" .format(sum(grades) / len(grades)))

rawDescription: Python Logic Issue: Test Scores

description: Python Logic Issue: Test Scores


code:
import matplotlib.pyplot as plt
plt.figure(0)
xlbl = plt.xlabel("foo")
pos = xlbl.get_position()
pos = (pos[0]+0.3, pos[1]+0.5)
ax = plt.gca()
ax.xaxis.set_label_coords(pos[0], pos[1])
plt.draw()
plt.show()

rawDescription: move axes text in matplotlib

description: Move axes text in matplotlib


code:
from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

rawDescription: Django URL Redirect

description: Django URL Redirect


rawDescription: Running Commands in Python

description: Running Commands in Python


code:
from bottle import route, run, request
@route('/deleteauthor', method='POST')
def index():
    request.body.seek(0)
    data = request.body.read()
    #do something with data

run(host='localhost', port=8080, debug=True)

rawDescription: Python bottle accept data send by jquery


code:
import StringIO
from flask import Flask, send_file, render_template

def page_code():
    strIO = StringIO.StringIO()
    strIO.write(render_template('hello.html', name='World'))
    strIO.seek(0)
    return send_file(strIO,
                     attachment_filename="testing.txt",
                     as_attachment=True)

rawDescription: Downloading flask-generated html page

description: Downloading flask-generated html page


code:
from itertools import izip_longest
with open("filea.csv") as source1,open("fileb.csv")as source2,open("filec.csv","a") as dest2:
    zipped = izip_longest(source1,source2) # use izip_longest which will add None as a fillvalue where we have uneven length files
    for line in zipped:
        if line[1]: # if we have two lines to join
            dest2.write("{},{}\n".format(line[0][:-1],line[1][:-1]))
        else: # else we are into the longest file, just treat line as a single item tuple
             dest2.write("{}".format(line[0]))

rawDescription: How to append one csv file to another with python

description: Append one csv file to another with python


code:
import datetime

def get_n_weekday(year, month, day_of_week, n):
    count = 0
    for i in xrange(1, 32):
        try:
            d = datetime.date(year, month, i)
        except ValueError:
            break
        if d.isoweekday() == day_of_week:
            count += 1
        if count == n:
            return d
    return None

rawDescription: How to get the Nth occurrence of a day of the week for a given month?

description: Get the Nth occurrence of a day of the week for a given month


code:
#this is your standard method definition
def r_f(fn, n, vl):
        #these are local variables
        cn, rd = 0, 0
        #we are saying;
        #in the scope of this with statement, the variable f
        #is equal to the file object returned by open
        with open(fn, 'r') as f:
            #for every line in the file
            #(because readlines returns a list of all the lines)
            for value in f.readlines():
                #increment this variable by 1
                rd += 1
                #if rd is greater than n
                if rd > n:
                    #break out of this loop
                    break
                #if the integer representation of the line we read
                #is equal to v1
                if int(value) == vl:
                    #then increase this variable by 1
                    cn += 1
        #we return this value to the function that called us
        return cn

rawDescription: what does the codes with the 'with' statement do?

description: What does the codes with the 'with' statement do


code:
r = requests.get(url)
if r.headers['content-type'] == 'text/html':
    data = r.text
elif r.headers['content-type'] == 'application/ogg':
    data = r.content

rawDescription: Check for binary content with Python requests library


code:
l = [
  {'key1': 'value1', 'key2': 'some_object'},
  {'key1': 'value21', 'key2': 'some_object2'},
  {'key1': 'value133', 'key2': 'some_object3'}
]

d = any(d for d in l if d['key1'] == 'value133')
if  d:
    d['key2'] = 'some_object333'
else :
    l.append({'key1': 'value133', 'key2': 'some_object3'})

print(d)

rawDescription: Check if an element-hash exists in an array and update it, otherwise insert it


code:
import matplotlib.pyplot as plt

data = [52.14535518, 6.22793227, 6.08643652, ...] # <- your data
num_bins = 200 # <- number of bins for the histogram
plt.hist(data, num_bins)
plt.show()

rawDescription: Bin/Histogram making

description: Bin/Histogram making


code:
fn = lambda obj: obj[obj.status == 1] if any(obj.status == 1) else obj
df.groupby(['id', 'letter'], as_index=False).apply(fn)

rawDescription: Pandas dataframe manipulation

description: Pandas dataframe manipulation


code: div.myDivClass > table.myTableClass > tr > td

rawDescription: BeautifulSoup4/CSS selector how to select the


code:
from cStringIO import StringIO
from PIL import Image, ImageOps, ImageDraw

size = (591, 608)
mask = Image.new('L', size, 0)
draw = ImageDraw.Draw(mask)
draw.rectangle((0, 0) + size, fill=255)

# From base64 to PIL
image_string = StringIO(my_image.decode('base64'))
im = Image.open(image_string)
output = ImageOps.fit(im, mask.size, centering=(0.5, 0.5))
output.putalpha(mask)

# From PIL to base64
output2 = StringIO()
output.save(output2, format='PNG')
im_data = output2.getvalue()
im_data = im_data.encode('base64')
# data_url = 'data:image/png;base64,' + im_data.encode('base64')

rawDescription: How to resize an image an cut the excess area of it in Python?

description: Resize an image an cut the excess area of it in Python


code:
def chkint(msg):
    while 1:
        try:
            n = input(msg)
            return(int(n))
        except ValueError:
            print("Please enter an integer.")

number1 = chkint("Please enter first value:")

number2 = chkint("Please enter second value:")

results = [number1, number2]

print ("I have accepted: " + str (results))

rawDescription: showing result of try except integer check as a string

description: Showing result of try except integer check as a string


code:
zip_file = zipfile.ZipFile('toto.zip')
target_path = 'C:\test\object'

for i, filename in enumerate(zip_file.namelist()):
    target = os.path.join(target_path, "%05d_%s" % (i, filename))
    file_obj = open(target, 'wb')
    try:
        shutil.copyfileobj(zip_file.open(filename, 'r'), file_obj)
    finally:
        file_obj.close()

rawDescription: Changing name of files with zipfile python


code:
result = ""

for m in match:

    result = result + " " + m

rawDescription: how can I match only the word and make them string within the string with tag-set?

description: Match only the word and make them string within the string with tag-set


rawDescription: Python how to read multiple values in a dictionary


code:
def setUp(self):
    self.test_passed = false

def tearDown(self):
    if not self.test_passed:
        log()

def test_something(self):
    self.assertEquals(something())
    self.test_passed = true

rawDescription: Performing an action whenever a unit test fails


code:
import re
p = re.compile('\$(.*?)\$')
s = "apple $banana$ coconut $delicious ethereal$ funkytown"
p.findall(s)

rawDescription: Regex for getting content between $ chars from a text


code:
obj = form.save(commit=False)
# [...] your encryption stuff [...]
obj.some_file_field = ContentFile(secret.serialize(), uuid.uuid4().get_hex())
obj.save()
form.save_m2m()

rawDescription: Django InMemoryUploadFile content and name manipulation


code:
from collections import Sequence  # ABC for lists and tuples

def tosequence(it):
    """Convert iterable to sequence, avoiding unnecessary copies."""
    return it if isinstance(it, Sequence) else list(it)

rawDescription: Is this a good way to make my function, which previously expected lists, to work with all iterables?


code: obj = datatype()

rawDescription: python WSME and thread safety

description: Python WSME and thread safety


code:
def getdocloc(self, object):
    """Return the location of module docs or None"""

    try:
        file = inspect.getabsfile(object)
    except TypeError:
        file = '(built-in)'

    docloc = os.environ.get("PYTHONDOCS",
                            "http://docs.python.org/library")
    basedir = os.path.join(sys.exec_prefix, "lib",
                           "python"+sys.version[0:3])
    if (isinstance(object, type(os)) and
        (object.__name__ in ('errno', 'exceptions', 'gc', 'imp',
                             'marshal', 'posix', 'signal', 'sys',
                             'thread', 'zipimport') or
         (file.startswith(basedir) and
          not file.startswith(os.path.join(basedir, 'site-packages'))))):
        if docloc.startswith("http://"):
            docloc = "%s/%s" % (docloc.rstrip("/"), object.__name__)
        else:
            docloc = os.path.join(docloc, object.__name__ + ".html")
    else:
        docloc = None
    return docloc

rawDescription: How to define the "MODULE DOCS" for display with pydoc?

description: Define the "MODULE DOCS" for display with pydoc


code:
SEND_REPORT_TUPLE = ('wet', 'water', 'liquid', 'mobile')
#make a list from the input
input_list = answer.split(" ")
#And then the use any function with comprehension list
if any(e in SEND_REPORT_TUPLE for e in input_list):
    print("The program has detected a query...")

rawDescription: Python checking users input

description: Python checking users input


rawDescription: Select element whose child/grandchildren/.. contains an element with a specified pattern


code:
import lxml.html as LH
content = '<root>
....Page Break....
</root>'
root = LH.fromstring(content)
tree = root.getroottree()
tree.getpath(root[0])

rawDescription: lxml - how to get xpath of HtmlElement?

description: Lxml - how to get xpath of HtmlElement


code: names = [child['institution_name'] for child in inst_array[0]['children']]

rawDescription: Python: extracting a list from an array of dictionaries with arrays in them


rawDescription: How to hide QProgressBar digits progress feedback

description: Hide QProgressBar digits progress feedback


code:
def fix_url(url):
    marker1 = url.find("?") + 1
    marker2 = url.find("page")
    fixed_url = url[:marker1] + url[marker2:] + "&" + url[marker1:marker2 - 1]
    fixed_url = fixed_url.replace("+"," ")
    return fixed_url

class MySpider(CrawlSpider):
    name = 'ContentSpider'
    allowed_domains = ['bbc.co.uk']
    start_urls = ['http://www.bbc.co.uk/search/news/?q=credit card']

    rules = (
        Rule(
            SgmlLinkExtractor(
                restrict_xpaths=('//div[@class="cmWidget news"]/div[@id="news-content"]'),
                allow=('http\:\/\/www\.bbc\.co\.uk\/news\/.')),
            callback='parse_item',
            follow=False),
        Rule(
            SgmlLinkExtractor(
                restrict_xpaths=('//div[@class="pagination"]'),
                process_value=fix_url)),
    )

    def __init__(self, **kwargs):
        CrawlSpider.__init__(self, **kwargs)
        logfile = open('testlog.log', 'w')
        log_observer = ScrapyFileLogObserver(logfile, level=logging.DEBUG)
        log_observer.start()
        log.start(loglevel=logging.DEBUG)

    def parse_item(self, response):
        item = CreditcrawlerItem()
        item['url'] = response.url
        return item

rawDescription: Scrapy: How can I fix a URL and then have that page crawled as usual?


code:
def browse_directory():
    filename = tkFileDialog.askopenfilename()

    print(filename)

    inputBox.configure(state=NORMAL)
    inputBox.delete(0, "end")
    inputBox.insert(0, filename)
    inputBox.configure(state=DISABLED)

rawDescription: Update textbox with text from browsed file. python


code:
students = []
scores = []
count = 0

number_of_students = int(input("Enter the number of students: "))

while count < number_of_students:
    new_student = input("Student name: ")
    students.append(new_student)
    count = count + 1

print("Enter the test scores of the students:")

for name in students:
    new_score = input("Score for " + name + ": ")
    scores.append(new_score)

rawDescription: Control conditional loop in Python

description: Control conditional loop in Python


code:
class UserData(db.Model) :
    user = db.UserProperty()
    name = db.StringProperty()
    flag = db.IntegerProperty()

rawDescription: GAE Python: How to acquire user name and additional information?


code:
class CourseSerializer(serializers.ModelSerializer):
    category_id = serializers.PrimaryKeyRelatedField(source='category', queryset=Category.objects.all())
    class Meta:
        model = Course

rawDescription: Django rest framework Serialzer ForeignKeyField output as field_id


code: letterLocation = (letterLocation + key[keyCount]) % 26

rawDescription: How to select a value from an array (See discription for more info)

description: Select a value from an array (See discription for more info)


code:
from pywinauto.controls.win32_controls import ButtonWrapper
checkbox = ButtonWrapper(madvr.TCheckBox.WrapperObject())
checkbox.GetCheckState()

rawDescription: Checking a checkbox with pywinauto doesn't work


code:
dict_a = dict(list_a)
dict_x = dict(list_x)

shared_keys = set(dict_a).intersection(set(dict_x))

result = dict((k, (dict_a[k], dict_x[k])) for k in shared_keys)

rawDescription: Merge two lists of lists - Python

description: Merge two lists of lists - Python


code:
#your root urls.py
from django.conf.urls.defaults import *
from haystack.forms import FacetedSearchForm
from haystack.query import SearchQuerySet
from haystack.views import FacetedSearchView

sqs = SearchQuerySet().filter(author='john')

urlpatterns = patterns('haystack.views',
url(r'^/my_custom_very_special_url$', FacetedSearchView(
    template='my/special/path/to/faceted_search.html',
    searchqueryset=sqs,
    form_class=FacetedSearchForm
), name='haystack_search'),
)

rawDescription: Django - How use generic views from a Django external App in my own App?


code:
from tkinter import *
root = Tk()

from tkinter.scrolledtext import ScrolledText

def go():
    print(text.get(0.0, END)) #you need  to get the current value from line 0 letter 0 to the end

text = ScrolledText(root)
text.pack()

btn = Button(root, text='GO', command=go)
btn.pack()

root.mainloop()

rawDescription: text in tkinter not working

description: Text in tkinter not working


code:
import os
filename, file_extension = os.path.splitext('/path/to/somefile.ext')
filename
file_extension

rawDescription: Extracting extension from filename in Python


code:
li = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
same = False
for nbr in li:
    if li.count(nbr) > 1:
        same = True

rawDescription: check identical for list in list(python)

description: Check identical for list in list(python)


code:
s = "Shuffling in Python"
shuffled = random.sample(list(enumerate(s)), len(s))
''.join([e[1] for e in shuffled])
''.join(s[e[0]] for e in shuffled)
''.join([e[1] for e in sorted(shuffled, key=lambda x:x[0])])

rawDescription: Unshuffling a shuffled string

description: Unshuffling a shuffled string


code:
def capitalize_word_in_crossword(crosswords,word):
     i_v=-1
     j_v=-1
     i_h=-1
     j_h=-1
     index_cap = find_word_horizontal(crosswords,word)
     if index_cap is not None:
        i_h,j_h=index_cap
     else:
        index_cap = find_word_vertical(crosswords,word)
        if index_cap is not None:
           i_v,j_v=index_cap

     for row_index in range(len(crosswords)):
         for col_index in range(len(crosswords[row_index])):

             for w in range(len(word)):
                 if i_h is not -1:
                    if row_index==i_h and col_index==j_h+w:
                       crosswords[row_index][col_index] = (crosswords[row_index][col_index]).upper()

                 if i_v is not -1:
                    if row_index==i_v+w and col_index==j_v:
                       crosswords[row_index][col_index] = (crosswords[row_index][col_index]).upper()
                    else:
                       crosswords[row_index][col_index] = (crosswords[row_index][col_index])

     return (crosswords)

rawDescription: Find a word in a crossword

description: Find a word in a crossword


code:
# Get the set of unique boroughs in which people want rooms:
wantedboroughs = set( w.borough for w in wantrooms )

# Get all records for people who have rooms in those boroughs:
result = [ h for h in haverooms if h.borough in wantedboroughs ]

rawDescription: Intersection of Object Attributes in Python


rawDescription: Explicitly labeling end points in matplotlib graph


rawDescription: Python Dijkstra Algorithm

description: Python Dijkstra Algorithm


code:
category = request.GET.get('category', '')
results = NewTable.objects.filter(headline__contains=name)
if category:
    results = results.filter(category=category)

rawDescription: Search from model in Django

description: Search from model in Django


code: shutil.copy("HI.xlsx", "BYE.xlsx")

rawDescription: Copying and renaming excel files with Python


code:
import networkx as nx
G=nx.path_graph(4)
A=nx.to_agraph(G)
A.layout(prog='dot')
png=A.draw(format='png')
png[0:10]

rawDescription: Draw graphs using Networkx to_agraph()

description: Draw graphs using Networkx to_agraph()


code: count = count + 1 if str(digit) in str(i) else count

rawDescription: Python 3 - Check if digit inside a number with if comprehension


code:
import itertools
import operator

L = [('HSBC8999', 4, 179447), ('HSBC1199', 81, 864108), ('HSBC1199', 32, 715121),('HSBC8999', 4, 1447),('HSBC1199', 32, 61521) ]

L.sort(key=operator.itemgetter(0))
for _k, stackoverflow in itertools.groupby(L, operator.itemgetter(0)):
    subl = list(stackoverflow)
    subl.sort(key=operator.itemgetter(1))
    for k, subg in itertools.groupby(subl, operator.itemgetter(1)):
        subs = list(subg)
        print("the average of {} is {}".format(k, sum(s[2] for s in subs)/len(subs)))

rawDescription: Group and compute the average in list of tuples


rawDescription: Python. Comparing two text document's contents


code:
rng = pd.date_range('1/31/2015', periods=3, freq='1m')
df2 = pd.DataFrame({ 'Amount': 0 * len(rng) }, index=rng )
df.append(df2)

rawDescription: Padding a Pandas Dataframe with Entries Based on Date


code:
import os, sys

from twisted.internet.protocol import ProcessProtocol
from twisted.internet import reactor
from twisted.internet.defer import Deferred, gatherResults

script = """
import time
for x in range(3):
    time.sleep(1)
    print(x)
"""

class SimpleProcess(ProcessProtocol):
    def __init__(self, id, d):
        self.id = id
        self.d = d
    def outReceived(self, out):
        print('Received output: {out} from: {proc}'
              .format(out=repr(out), proc=self.id))
    def processEnded(self, reason):
        self.d.callback(None)

ds = []
for x in range(3):
    d = Deferred()
    reactor.callLater(
        x * 0.5, reactor.spawnProcess, SimpleProcess(x, d),
        sys.executable, [sys.executable, '-u', '-c', script],
        os.environ)
    ds.append(d)

gatherResults(ds).addBoth(lambda ignored: reactor.stop())

reactor.run()

rawDescription: Using Twisted to run command on remote system


code:
import csv
import requests
import bs4

res = requests.get('http://www.ebay.com/sch/i.html?LH_Complete=1&LH_Sold=1&_from=R40&_sacat=0&_nkw=gerald%20ford%20autograph&rt=nc&LH_Auction=1&_trksid=p2045573.m1684')
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)

# grab all the links and store its href destinations in a list
links = [e['href'] for e in soup.find_all(class_="vip")]

# grab all the bid spans and split its contents in order to get the number only
bids = [e.span.contents[0].split(' ')[0] for e in soup.find_all("li", "lvformat")]

# grab all the prices and store those in a list
prices = [e.contents[0] for e in soup.find_all("span", "bold bidsold")]

# zip each entry out of the lists we generated before in order to combine the entries
# belonging to each other and write the zipped elements to a list
l = [e for e in zip(links, prices, bids)]

# write each entry of the rowlist `l` to the csv output file
with open('ebay.csv', 'w') as csvfile:
    w = csv.writer(csvfile)
    for e in l:
        w.writerow(e)

rawDescription: Saving scraped result set into a csv file


code:
J
Transpose(J)
#'
J.T

rawDescription: How to transpose a sympy matrix

description: Transpose a sympy matrix


code:
# Subplot 2D
ax2 = fig.add_subplot(1, 2, 2, aspect='equal')
ax2.contourf(x, y, z, facecolors=colors)

rawDescription: matplotlib : project 3d surface on 2d plot

description: Matplotlib : project 3d surface on 2d plot


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

fig, axes = plt.subplots(1, 2)

np.random.seed([3,1415])
df = pd.DataFrame(np.random.randn(100, 6), columns=list('ABCDEF'))
df = df.div(100).add(1.01).cumprod()

df.iloc[:, :3].plot(ax=axes[0])
df.iloc[:, 3:].plot(ax=axes[1])

rawDescription: Plot multiple lines on subplots with pandas df.plot


code:
import xml.etree.ElementTree as ET
import csv

tree = ET.parse('registerreads_EE.xml')

root = tree.getroot()[3]

with open('registerreads_EE.csv', 'w', newline='') as r:
    writer = csv.writer(r)
    writer.writerow(['read', 'date', 'entityid'])  # WRITING HEADERS

    for channel in tree.iter('Channel'):
        for exportrequest in channel.iter('ExportRequest'):
            entityid = exportrequest.attrib.get('EntityID')
            for meterread in channel.iter('Reading'):
                read = meterread.attrib.get('Value')
                date = meterread.attrib.get('ReadingTime')

                # WRITE EACH ROW ITERATIVELY
                writer.writerow([read[:-2],date[:10],entityid])

rawDescription: Python ElementTree xml output to csv

description: Python ElementTree xml output to csv


code:
class Test:
    @staticmethod
    def method():
        return 'called static method'

assert locals()['Test'].method() == 'called static method'

rawDescription: Python: Using reflection to invoke class members from the class name


code:
import tkinter

class Application(tkinter.Frame):

    @classmethod
    def main(cls):
        tkinter.NoDefaultRoot()
        root = tkinter.Tk()
        root.title('Recipes')
        root.geometry('400x300')
        root.resizable(False, False)
        app = cls(root)
        app.grid()
        root.mainloop()

    def __init__(self, master):
        super().__init__(master)
        self.create_first_screen()
        self.first_screen.grid_remove()
        self.create_second_screen()
        self.second_screen.grid_remove()
        self.first_screen.grid()

    def create_first_screen(self):
        self.first_screen = s1 = tkinter.Frame(self)
        self.first_screen.grid(row=0, column=0)
        # Create widgets.
        s1.name_label = tkinter.Label(s1, text='What is your recipe called?')
        s1.name_entry = tkinter.Entry(s1)
        s1.con_button = tkinter.Button(s1, text='Confirm',
                                       command=self.name_recipe)
        # Grid each widget.
        s1.name_label.grid(row=0, column=0)
        s1.name_entry.grid(row=0, column=1)
        s1.con_button.grid(row=0, column=2)

    def create_second_screen(self):
        self.second_screen = s2 = tkinter.Frame(self)
        self.second_screen.grid(row=0, column=0)
        # Create widgets.
        s2.name_label = tkinter.Label(s2, text='What is your name?')
        s2.name_entry = tkinter.Entry(s2)
        s2.con_button = tkinter.Button(s2, text='Confirm',
                                       command=self.name_yourself)
        # Grid each widget.
        s2.name_label.grid(row=0, column=0)
        s2.name_entry.grid(row=0, column=1)
        s2.con_button.grid(row=0, column=2)

    def name_recipe(self):
        name = self.first_screen.name_entry.get()
        with open(name + '.txt', 'w') as file:
            print('Recipe name:', name, file=file)
        self.first_screen.grid_remove()
        self.second_screen.grid()

    def name_yourself(self):
        name = self.second_screen.name_entry.get()
        with open(name + '.txt', 'w') as file:
            print('Your name:', name, file=file)
        self.second_screen.grid_remove()
        self.first_screen.grid()

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

rawDescription: Hide all these grids so I can make another 'page'


code:
import random
import operator

try:
    input = raw_input
except:
    pass

ops={
    '+' : operator.add,
    '-' : operator.sub,
    '*' : operator.mul,
    '/' : operator.truediv
}

def question():
    b=random.randint(1,10)
    a=random.randint(1,10)
    op = random.choice(list(ops))
    raw = input("What is %s %s %s? " % (a, op, b))
    try:
        c=float(raw)
    except:
        return 0

    # calls operator functions you defined
    if c == ops[op](a,b):
        return 1
    else:
        return 0

if __name__ == '__main__':
    score = 0
    for n in range(10):
        score = score + question()
    print('Your socre: %s' % score)

rawDescription: how can i Loop this program

description: Loop this program


rawDescription: Write a Dictionary to a CSV file

description: Write a Dictionary to a CSV file


code:
import collections
import bisect

class MyDict(collections.Mapping):
  def __init__(self, contents):
    "contents must be a sequence of key/value pairs"
    self._list = sorted(contents)
  def __iter__(self):
    return (k for (k, _) in self._list)
  def __contains__(self, k):
    i = bisect.bisect_left(self._list, (k, None))
    return i < len(self._list) and self._list[i][0] == k
  def __len__(self):
    return len(self._list)
  def __getitem__(self, k):
    i = bisect.bisect_left(self._list, (k, None))
    if i >= len(self._list): raise KeyError(k)
    return self._list[i][1]

rawDescription: Python dictionary - binary search for a key?


code:
a = [1, 2]
b = [3, 4]
from itertools import product
list(product(a, b, a, b))
test_list = [a, b, a, b]
list(product(*test_list))

rawDescription: How to operate on parameters of python itertools.product

description: Operate on parameters of python itertools.product


code:
new_col_list = ['city','state','regions','country']
for n,col in enumerate(new_col_list):
    df[col] = df['location'].apply(lambda location: location[n])

df = df.drop('location',axis=1)

rawDescription: From tuples to multiple columns in pandas


rawDescription: API for inline graphics in ipython

description: API for inline graphics in ipython


code:
from BeautiulSoup import NavigableString
soup = BeautifulSoup("Foo")
soup.a.contents = [NavigableString(str(soup.a.contents[0]) + 'Bar')]
soup

rawDescription: Confusion regarding BeautifulSoup's append method