code:
# get the name of all directories starting with 00
dirs = glob.glob('00*')
path = os.getcwd()

for directory in dirs:
    newpath = path + '/' + directory
    os.chdir(newpath)
    # read and append data

rawDescription: loop in directories whose names are consecutive numbers

description: Loop in directories whose names are consecutive numbers


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

fig = plt.figure()

N = 5

A = np.random.rand(N,N)
im = plt.imshow(A)

def updatefig(*args):
    im.set_array(np.random.rand(N,N))
    return im,

ani = animation.FuncAnimation(fig, updatefig, frames=10, interval=200, blit=True)

ani.save('try_animation.mp4', fps=10, dpi=80) #Frame per second controls speed, dpi       controls the quality
plt.show()

rawDescription: matplotlib animation duration

description: Matplotlib animation duration


code:
model = Model('some_title', 'some text')
session.add(model)

session.flush()
return HTTPFound(location='/ads/%s/%s' % (model.id, model.title))

rawDescription: Pyramid: how to get id of just created db row?


code:
from . import someOtherModule
from . import SomeClass

rawDescription: Referencing python package name without hard coding its name


code:
from itertools import islice
picked = set(on_teams)
players = list(islice((p for p in players if p[0] not in picked), 5))

rawDescription: python: select a sublist with a list length limit

description: Python: select a sublist with a list length limit


code:
import matplotlib.pyplot as plt

plt.plot(range(10), dashes='')
plt.show()

rawDescription: setting a solid line using dashes keyword argument in matplotlib?

description: Setting a solid line using dashes keyword argument in matplotlib


code:
strJoin = lambda x:",".join(x.astype(str))
df.groupby(level=[0,1]).agg({"r3":strJoin,"value":np.sum})

rawDescription: How do you merge Pandas DataFrame rows into a string in one column?

description: Merge Pandas DataFrame rows into a string in one column


code:
import android #import android module
droid = android.Android() #class instantation
droid.bluethoothMakeDiscoverable() #make your device visible

rawDescription: How to turn on or off bluetooth in android using python

description: Turn on or off bluetooth in android using python


code:
class Meta:
    ordering = ('office__description',)

rawDescription: determine a model's default order by a field of its foreign key Django

description: Determine a model's default order by a field of its foreign key Django


code:
def table(n):
    if n == 2: return 1
    if n%4 != 1: return

    mod = 0
    a1 = n - 1
    for a in xrange(1, a1, 2):
        mod += a

        while mod >= n: mod -= n
        if mod == a1: return a//2 + 1

rawDescription: Can I reduce the computational complexity of this?

description: Reduce the computational complexity of this


code:
from django.core.cache import cache

def cache_user(userid):
       key = "user_{0}".format(userid)
       value = cache.get(key)
       if value is None:
             # fetch value from db
             cache.set(value)

       return value

rawDescription: Django - queryset caching request-independent?


code:
#initializing a variable with some mock poll data
option1 = "general store"
option2 = "supermarket"
option3 = "mall"
option4 = "small store"

sample_data = [option1,option2,option1,option1,option3,option3,option4,option4,option4,option2]

#a dict that will store the poll results
results = {}

for response in sample_data:
    results[response] = results.setdefault(response, 0) + 1

rawDescription: List - How to find number of times an item appears


code:
from django.db.models.signals import pre_save

# The arguments this function receives are defined by the `pre_save` signal.
def send_task_email(sender, instance, raw, using, update_fields):
    # The logic to send the email goes here. e.g.
    return send_mail(
        subject='New task',
        message = 'You have been assigned to a task',
        from_email = "noreply@gmail.com",
        recipient_list=[instance.assign_to.email]
    )

# Register the pre_save signal with the Job model.
# Please note the `dispatch_uid` kwarg to avoid signal duplication.
pre_save.connect(send_task_email, sender=Job, dispatch_uid="sending_email_uid")

rawDescription: send email notification using pre_save

description: Send email notification using pre_save


code:
klass = A
args = (a, b, c)
obj = klass(*args)

rawDescription: Instantiating different python classes dynamically


code:
import os
import pty

logfile = open('logfile', 'wb')

def read(fd):
    data = os.read(fd, 1024)
    logfile.write(data)
    return data

pty.spawn("ninja", read)

rawDescription: Duplicating terminal output from a Python subprocess


code:
kwargs = {}
title_arg = 'title_%s' % language
kwargs[title_arg] = "some title"

MyModel.objects.filter(**kwargs)

rawDescription: django model translation - filter by translated field

description: Django model translation - filter by translated field


rawDescription: Python regex find all overlapping matches?


code:
start_token = tkSimpleDialog.askstring("Serial Number", "What is the Serial?")
splitInput = start_token.split(' ') #Our Delimiter is space in this case

for inputStrings in splitInput:
   process(infile,outfile,((inputStrings,"end token"),))

rawDescription: Splitting input string into a function to search text file


code:
import math
import numpy as np
a = np.array([4,2,7])
np.linalg.norm(a)
math.sqrt(sum([n**2 for n in a]))
b = a/np.linalg.norm(a)
np.linalg.norm(b)

rawDescription: python numpy vector math

description: Python numpy vector math


code:
from twisted.python import log
observer = log.PythonLoggingObserver()
observer.start()
log.msg('%s %s \033[0m' % (self.__colors[colortype], msg))

rawDescription: How to use native Python logging or/and Twisted logger for multiple daemon/cron scripts?

description: Use native Python logging or/and Twisted logger for multiple daemon/cron scripts


code:
def url_redirect(request,id):
    if id.startswith('!'):
        id = id[1:]
        # do whatever you want with id
    else:
        url = get_object_or_404(Url,short_id=id)
        return HttpResponseRedirect(url.httpurl)

rawDescription: Use different view in Django if the url contains specific character


rawDescription: Black-out Areas of Video Frame in Python


code:
# game_mechanics.py
class game_object(object):
   pass

# enemies.py
from game_mechanics import game_object
class special_object(game_object):
   pass

rawDescription: Quick one: Extending class from main script?


code:
masterAbrevs = ['ASW', 'AS', 'UW']

for i, e in enumerate(masterAbrevs):
    if (e[-1] == 'W') and (e != 'UW'):
        masterAbrevs[i] = masterAbrevs[i][:-1]

# results in ['AS', 'AS', 'UW']

rawDescription: Delete last character in string Python

description: Delete last character in string Python


rawDescription: Replacing values greater than a limit in a numpy array


code:
sortedData = sorted([(t, i) for t, i in zip(data['a'],range(len(data['a'])))])
sortedIndex = [i[1] for i in sortedData]
for key in data.keys():
    data[key] = [ data[key][i] for i in sortedIndex]

rawDescription: Dictionary of Lists: Sort lists and maintain relative index position


code:
#!/usr/bin/env python
from __future__ import absolute_import, division, print_function
import Tkinter as tk
from functools import partial

COLOR, NAVIGATION = 1, 2

class Application(object):

    def __init__(self, master):
        frame = tk.Frame(master)
        frame.pack()

        self.year2data = {
            2017: {
                COLOR: ['China', 'Europe', 'North America'],
                NAVIGATION: ['Australia', 'China', 'Europe'],
            },
            2016: {
                COLOR: ['China ', 'Europe ', 'North America '],
                NAVIGATION: ['Australia ', 'China ', 'Germany'],
            },
            2015: {
                COLOR: ['China ', 'Europe-Russia ', 'North America '],
                NAVIGATION: [
                    'Australia ', 'New Zealand', 'England', 'Israel Region',
                    'Latin America Region', 'Middle East Region',
                    'North America Region', 'Philipines _Region',
                    'South American _Region', 'Turkey _Region'
                ],
            },
            2014: {
                COLOR: ['China', 'Europe-Russia ', 'South America '],
                NAVIGATION: ['Philipines Region', 'Turkey _Region'],
            },
        }

        self.current_data = None

        tk.Label(frame, text='Model Year:', anchor=tk.E).grid(row=0, column=1)
        years = sorted(self.year2data.iterkeys())
        self.model_year_var = tk.IntVar(master)
        self.model_year_var.set(years[0])
        tk.OptionMenu(frame, self.model_year_var, *years).grid(
            row=0, column=2, columnspan=2
        )
        self.model_year_var.trace('w', self.update_region)

        self.color_or_navigation_var = tk.IntVar()
        tk.Radiobutton(
            frame, text='Color', variable=self.color_or_navigation_var, value=1
        ).grid(row=1, column=2)
        tk.Radiobutton(
            frame,
            text='Navigation',
            variable=self.color_or_navigation_var,
            value=2,
        ).grid(row=1, column=3)
        self.color_or_navigation_var.trace('w', self.update_region)

        tk.Label(frame, text='Region:', anchor=tk.E).grid(row=2, column=1)

        self.region_var = tk.StringVar(master)
        self.region_dropdown = tk.OptionMenu(frame, self.region_var, '')
        self.region_dropdown.grid(row=2, column=2, columnspan=2)

        self.update_region()

    def update_region(self, *_args):
        self.current_data = self.year2data[self.model_year_var.get()]
        color_or_navigation = self.color_or_navigation_var.get()
        if color_or_navigation != 0:
            regions = self.current_data[color_or_navigation]
            menu = self.region_dropdown['menu']
            menu.delete(0, tk.END)
            for region in regions:
                menu.add_command(
                    label=region, command=partial(self.region_var.set, region)
                )
            if self.region_var.get() not in regions:
                self.region_var.set(regions[0])

def main():
    root = tk.Tk()
    root.title('application')
    _ = Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: How to update the values of the dictionary in python Tkinter

description: Update the values of the dictionary in python Tkinter


code:
import math
math.sqrt(4)
import cmath
cmath.sqrt(4 + 3j)

rawDescription: Trying to figure out python square root

description: Trying to figure out python square root


rawDescription: spark finding max value and the associated key

description: Spark finding max value and the associated key


code:
import re

filename = "file.txt"
regex = re.compile(r'(memcpy\s*\(\s*buffer\s*,\s*")\s*("\s*,\s*64\s*)')
with open(filename) as in_file:
    in_buffer = in_file.readlines()

data = "foo bar"
with open(filename, "w") as out_file:
    for line in in_buffer:
        out_file.write(regex.sub(r'\g<1>'+data+'\g<2>', line))

rawDescription: How to insert a specific string into a specific location of a specific line in a file using a Python script?

description: Insert a specific string into a specific location of a specific line in a file using a Python script


code:
d = {'hello': 'world', 'with:colon': 'moo'}
'{hello} {}'.format(d['with:colon'],**d)
'{hello} {0}'.format(d['with:colon'],**d)

rawDescription: How do I escape a colon in Python format() when using kwargs?

description: Escape a colon in Python format() when using kwargs


code:
import ctypes
from ctypes.util import find_library
lapack = ctypes.cdll.LoadLibrary(find_library("lapack"))
dgtsv = lapack.dgtsv_

rawDescription: Is it possible to wrap a function from a shared library using F2PY?


code:
def num_of_choices(question):
    return question.choice_set.count()

rawDescription: Django: No of Instances of a Foreign Key


code:
r = requests.get(url, stream=True)
if r.status_code == 200:
    with open('document.doc', 'wb') as f:
        for chunk in r.iter_content():
            f.write(chunk)
    f.close()

rawDescription: how to save .doc file from url in python?

description: Save .doc file from url in python


rawDescription: Difference between ^ Operator in JS and Python


code:
xl = pd.ExcelFile("GCSE IGCSE results v3.xlsx")
df = xl.parse(xl.sheet_names[0], skiprows=14)
df.columns
df.head()

rawDescription: How to process excel file headers using pandas/python

description: Process excel file headers using pandas/python


code:
import datetime
import pytz

start_date = '15-01-2016'
end_date = '16-01-2016'
date_format = '%d-%m-%Y'

unaware_start_date = datetime.datetime.strptime(start_date, date_format)
aware_start_date = pytz.utc.localize(unaware_start_date)

unaware_end_date = datetime.datetime.strptime(end_date, date_format)
aware_end_date = pytz.utc.localize(unaware_end_date)

my_list = MyModel.objects.filter(created_at__range=(aware_start_date, aware_end_date))

rawDescription: Python string to Django timezone (aware datetime)


rawDescription: Python- Reading from multiple text files into dictionary


rawDescription: Meaning of digits after NaN in Python Decimal object


code:
shutil.copytree(source,target,symlinks=False,ignore=ignore_files);

def ignore_files(folder, files):
    return [f for f in files if not is_dir(os.path.join(folder, f))]

rawDescription: Copy only directories in a directory tree using shutil in Python


code:
from tkinter import *
import os

root = Tk()
class MainGui:
    def __init__(self, master):
        self.mypathLabel = Label(master, text="Copy and Paste your filepath here:")
        self.mypathEntry = Entry(master, bg="black", fg="white", relief=SUNKEN)
        self.mypathSaveButton = Button(master, text="Save Path", bg="black", fg="white", command=self.save_path)
        self.mypathList = Listbox(master, bg="black", fg="white")

        self.mypathLabel.pack()
        self.mypathEntry.pack()
        self.mypathSaveButton.pack()
        self.mypathList.pack()
        self.mypathList.bind("<Double-Button-1>", self.open_path)

    def save_path(self):
        fp = self.mypathEntry.get()
        self.mypathEntry.delete(0, 'end')
        self.mypathList.insert(1, fp)

    def open_path(self, event):
        list_item = self.mypathList.curselection()
        fp = self.mypathList.get(list_item[0])
        print(fp)
        try:
            with open(fp, 'r') as result:
                print(result.read())
        except Exception as e:
            print(e)

MainGui(root)
root.mainloop()

rawDescription: Python: What is the syntax for adding a command to a tkinter Listbox item?


code:
import string
from collections import defaultdict
rng = xrange if xrange else range

def filetxt():
    users     = 0
    total_t   = 0
    occ       = 0

    wordcount = defaultdict(int)
    wordpairs = defaultdict(lambda: defaultdict(int))
    for filenum in rng(500):
        try:
            with open("C:/Twitter/json/user_" + str(filenum) + ".json",'r') as inf:
                users += 1
                tweets = json.load(inf)
                total_t += len(tweets)

                for txt in (r['text'] for r in tweets):
                    occ += txt.count('RT') + txt.count('@')
                    prev = None
                    for word in txt.encode('utf-8').translate(None, string.punctuation).lower().split():
                        wordcount[word] += 1
                        wordpairs[prev][word] += 1
                        prev = word
        except IOError:
            pass

rawDescription: Optimization of Function with Dictionary and Zip()


code:
from csv import reader as csv_reader

with open("data.csv", "r") as fd:
    for row in csv_reader(fd):
        userid, firstname, lastname = row

rawDescription: Is there a more efficient way to load 10,000 excel rows into python?


code:
from collections import defaultdict
fq= defaultdict( int )
for w in words:
    fq[w] += 1

rawDescription: Best way to turn word list into frequency dict

description: Turn word list into frequency dict


code:
import time
import sys

for remaining in range(10, 0, -1):
    sys.stdout.write("\r")
    sys.stdout.write("{:2d} seconds remaining.".format(remaining))
    sys.stdout.flush()
    time.sleep(1)

sys.stdout.write("\rComplete!            \n")

rawDescription: Python: How do I display a timer in a terminal


code:
def foo(*args):
   return list(args)

foo(1, 2, 3)

rawDescription: Function header that can contain 0 or more assignments


code:
import datetime
message = "2015-08-26T19:30:00+0200"
fmt = '%Y-%m-%dT%H:%M:%S%z'
d=datetime.datetime.strptime(message, fmt)
print(d.time())

rawDescription: Get time regardless of the Timezone/DST in python using datetime


code:
with open('Task2.txt', 'r') as document, open("receipt.txt", "a") as receipt:
    strquantity = str(quantity)

    for line in document:
        the_line = line.strip().split(",")

        if the_line[0] == GTIN:
            receipt.write(','.join(the_line[0], the_line[1], the_line[2], strquantity) + '\n')

rawDescription: Why does it write to 2 lines in a text file when I only ask it to type 1?


code:
list
list.count(('Car', 'Cadillac', 'Blue'))

rawDescription: Grouping multiple variables and counting number of unique combinations


code:
...

for index,i in enumerate(I_phase):
    F = sum(m*np.cos(2*np.pi*l*x/D) for m,l in zip(i,n))
    f,(ax1,ax2) = plt.subplots(2)
    ax1.plot(x,F,'g')
    ax1.set_title(phase[index])

...

rawDescription: Matplotlib: Same title for 8 plots plotted using loop


code:
uk_sales = Sale.objects.filter(country_type='1')
uk_amount = uk_sales.aggregate(price = Sum('amount'))['price']

rawDescription: Want to Add all amounts for each country


rawDescription: Is it possible to use argparse but pass in a custom argv instead of it using sys.argv?


code:
class env_form(forms.Form):
    env = forms.ChoiceField(choices=ENV, required=True)

class add_uRG(env_form):
    user = forms.CharField(max_length=50)
    group = forms.CharField(required=True)
    role = forms.CharField(required=True)

    def clean_user(self):
        post_user = self.cleaned_data['user']
        post_env = self.cleaned_data['env']
        c = User.objects.filter(user__contains=post_user, env__contains=post_env ).count()
        if (c == 0):
            raise forms.ValidationError(u"User Not Found.")
        else:
            user_info = User.objects.filter(user__contains=post_user).values('password').distinct().count()
            user_env = User.objects.filter(user__contains=post_user).values('env').distinct().count()
            if not (user_env == user_info):
                raise forms.ValidationError(u'User is using same password')
        return(post_user)

    def __init__(self, *args, **kwargs):
        super(env_form, self).__init__(*args, **kwargs)

class SomeOtherForm(env_form):
    some_field = forms.CharField()

    def __init__(self,*args,**kwargs):
        super(env_form, self).__init__(*args,**kwargs)

rawDescription: Validate form A's data by usuing form B's data


rawDescription: pandas plot dataframe as multiple bar charts

description: Pandas plot dataframe as multiple bar charts


code:
a="CS 240, CS 246, ECE 222"
b=tuple(a.strip() for a in a.split(','))
b

rawDescription: How to match a variable list of items separated by commas

description: Match a variable list of items separated by commas


code:
import tempfile, os

from pyx import *
import Tkinter
import Image, ImageTk

# first we create some pyx graphics
c = canvas.canvas()
c.text(0, 0, "Hello, world!")
c.stroke(path.line(0, 0, 2, 0))

# now we use pipeGS (ghostscript) to create a bitmap graphics
fd, fname = tempfile.mkstemp()
f = os.fdopen(fd, "wb")
f.close()
c.pipeGS(fname, device="pngalpha", resolution=100)
# and load with PIL
i = Image.open(fname)
i.load()
# now we can already remove the temporary file
os.unlink(fname)

# finally we can use this image in Tkinter
root = Tkinter.Tk()
root.geometry('%dx%d' % (i.size[0],i.size[1]))
tkpi = ImageTk.PhotoImage(i)
label_image = Tkinter.Label(root, image=tkpi)
label_image.place(x=0,y=0,width=i.size[0],height=i.size[1])
root.mainloop()

rawDescription: Create a graph in a TKinter window?

description: Create a graph in a TKinter window


code:
from Tkinter import *
master = Tk()
master.geometry("300x100")
master.title("Convert Scale To Farenheight")

def convertToFarenheight(var):
    f1= int(var)
    f2.set(f1*9/5+32)

f2=IntVar()
x=Label(master,textvariable=f2)
x.pack()

var = StringVar()
y=Scale(master,from_=-100,to=100,variable=var,orient=HORIZONTAL,command=convertToFarenheight)
y.pack()

mainloop()

rawDescription: Running method on tkinter scale and setting it label


code: query_to_field_mapping = {"Date": "date__contains","Status": "result"}

rawDescription: Django: How can I filter a user input date with a DateTimeField DB in Django passing the filter options as dictionary?


code:
import getpass
getpass.getuser()

rawDescription: how can get the user name of the python script during excution

description: How can get the user name of the python script during excution


code:
def get_values_ignore_current_line(content, keyword):
   content = '\n'.join([x for x in content.splitlines() if keyword not in x])
   tags = re.findall('<.*?>', content)
   return tags

def get_values_ignore_next_line(content, keyword):
    lines = content.splitlines()
    new_content = [lines[0]]
    for i, line in enumerate(lines):
        if (keyword not in line) or (re.match('<.*?>', line) is not None):
            if i < len(lines) - 1:
                new_content.append(lines[i+1])
    new_content = '\n'.join(new_content)
    return re.findall('<.*?>', new_content)

rawDescription: Python duplicates in web crawler

description: Python duplicates in web crawler


code:
class HrpDoors(models.Model):
    door_uid = models.IntegerField(primary_key=True)
    door_owner = models.IntegerField()
    door_ownertype = models.IntegerField()
    door_name = models.CharField(max_length=32)

    class Meta:
        verbose_name = 'Drzwi'
        verbose_name_plural = 'Drzwi'
        managed = True
        db_table = 'hrp_doors'

    def __unicode__(self): #Look at the indentation of unicode - same level as attributes of class model
        return u'%s' % self.door_uid #Also, return unicode explicitly

rawDescription: Django unicode is not working

description: Django unicode is not working


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

rawDescription: numpy array conversion to pairs

description: Numpy array conversion to pairs


code:
class EmailThread(threading.Thread):
    def __init__(self, subject, html_content, recipient_list):
        self.subject = subject
        self.recipient_list = recipient_list
        self.html_content = html_content
        threading.Thread.__init__(self)

    def run (self):
        msg = EmailMessage(self.subject, self.html_content, EMAIL_HOST_USER, self.recipient_list)
        msg.content_subtype = "html"
        msg.send()

def send_html_mail(subject, html_content, recipient_list):
    EmailThread(subject, html_content, recipient_list).start()

rawDescription: how to send asynchronous email using django

description: Send asynchronous email using django


code:
class User(object):
    email = "username"
    password = "********"

    @classmethod
    def all(cls):
        return {"ex": cls.password}

print(User.all())

rawDescription: Python class with static method and reference to self


code:
from collections import Counter
counter = Counter(ids)
[k for k,v in counter.items() if v == 2]

rawDescription: Python: Find element in the list which has frequency = 2


code:
import imp
import os

def module_from_path(path):
    filename = os.path.basename(path)
    modulename = os.path.splitext(filename)[0]

    with open(path) as f:
        return imp.load_module(modulename, f, path, ('py', 'U', imp.PY_SOURCE))

rawDescription: Python Module by Path

description: Python Module by Path


code:
# Implements an in-memory CIC decimator using numpy.

from math import log
from numpy import int32, int64, array

def cic_decimator(source, decimation_factor=32, order=5, ibits=1, obits=16):

    # Calculate the total number of bits used internally, and the output
    # shift and mask required.
    numbits = order * int(round(log(decimation_factor) / log(2))) + ibits
    outshift = numbits - obits
    outmask  = (1 << obits) - 1

    # If we need more than 64 bits, we can't do it...
    assert numbits <= 64

    # Create a numpy array with the source
    result = array(source, int64 if numbits > 32 else int32)

    # Do the integration stages
    for i in range(order):
        result.cumsum(out=result)

    # Decimate
    result = array(result[decimation_factor - 1 : : decimation_factor])

    # Do the comb stages.  Iterate backwards through the array,
    # because we use each value before we replace it.
    for i in range(order):
        result[len(result) - 1 : 0 : -1] -= result[len(result) - 2 : : -1]

    # Normalize the output
    result >>= outshift
    result &= outmask
    return result

rawDescription: Filtering signal with Python lfilter

description: Filtering signal with Python lfilter


code:
class ExampleSpider(BaseSpider):
    name = "test_code"
    allowed_domains = ["www.example.com"]

    def start_requests(self):
        for i in xrange(1000):
            yield self.make_requests_from_url("http://www.example.com/bookstore/new/%d?filter=bookstore" % i)

    ...

rawDescription: Constructing a regular expression for url in start_urls list in scrapy framework python


code:
import re
def replace(s):
     return re.sub('foo(.*)', 'foo\1 bar', s)
replace('foo something') #'foo something bar'

rawDescription: Python - string replacement in a weird way;


code: [re.sub(r'^(Mr|Ms|Mrs)\.\s+', '', s) for s in test_csv_line]

rawDescription: Is there a Pythonic way to make this logic more elegant?


code:
from visual.graph import *
graphX = gcurve(color = color.cyan)
gdisplay()
graphY = gcurve(color = color.red)

rawDescription: Generating second graph in different window - VPython


code:
things = ["black", 7, "red", 10, "white", 15]
color = things[::2]
color
size = things[1::2]
size

rawDescription: how do i make two new lists based on what the index is in a list?

description: Make two new lists based on what the index is in a list


code:
pr = subprocess.Popen(['js2coffee'],
                      stdin=subprocess.PIPE,
                      stdout=subprocess.PIPE)
result, stderrdata = pr.communicate('var myNumber = 100;')

rawDescription: How to pass escaped string to shell script in Python

description: Pass escaped string to shell script in Python


code:
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __str__(self):
        return "(%.2f, %.2f)" % (self.x, self.y)
    def __repr__(self):
        return "Point(x=%r, y=%r)" % (self.x, self.y)
    def __eq__(self, other):
        return isinstance(other, Point) and self.x == other.x and self.y == other.y

rawDescription: Convention to print an object in python

description: Convention to print an object in python


rawDescription: Update lists in dictionary based on another list


code:
from django.db.models import Count
un_list = Question.objects.annotate(a_count=Count("answer")).filter(a_count=0)

rawDescription: django many to many field annotate and count

description: Django many to many field annotate and count


code:
def make_scrapy_command_class(base_class):
    class ScrapyCommand(base_class):
        # your methods here
        pass

    return ScrapyCommand

ScrapyCommand = make_command_class(someotherapp.crawl.OtherCommand)

rawDescription: Dynamically importing a base class in Python


code:
x = raw_input("Int array")
map(int, x.split())

rawDescription: How to input Int array in Line in Python

description: Input Int array in Line in Python


code:
import socket

HOST = ''
PORT = 50007

s = socket.socket()
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()

f = open("client.txt", "rb")
while 1:
    data = f.read(1024)
    if not data: break
    conn.send(data)
conn.close()

rawDescription: How to read a binary file?

description: Read a binary file


code:
from django.db.migrations import Migration as DjangoMigration, CreateModel

class Migration(DjangoMigration):
    operations = [
        CreateModel(
            name='ModelName',
            fields=[
                # Model's fields.
            ],
            options={
                # Other options.
                'managed': False
            }
        )
    ]

rawDescription: DJango Migration Classes

description: DJango Migration Classes


code:
d = {}
for x in xs:
    d[x.tag] = x

rawDescription: How to make a list in Python distinct based on a property of the class in the list?

description: Make a list in Python distinct based on a property of the class in the list


code:
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
    copy = False
    for line in infile:
        if line.strip() == "Start":
            copy = True
        elif line.strip() == "End":
            copy = False
        elif copy:
            outfile.write(line)

rawDescription: Extract Values between two strings in a text file using python


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

#Setup a host axis
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(bottom=0.2)

#Add twin y axis with offset from bottom and hide top axis
par = host.twiny()
offset = -30
new_fixed_axis = host.get_grid_helper().new_fixed_axis
par.axis["bottom"] = new_fixed_axis(loc="bottom",
                                    axes=par,
                                    offset=(0, offset))
par.axis["top"].set_visible(False)

# Plot data and add main axis labels/limits
host.imshow(np.random.rand(128,1600))
host.set_xlabel("f/MHz")
host.set_xlim((0,1600))
plt.axis("tight")

#Set limits of parasite axis
#(note this axis is not attached to
# an actual plot so changes nothing)

par.set_xlabel("Ka")
par.set_xlim((0,15.71))

plt.draw()
plt.show()

rawDescription: How to set a double x-axis label?

description: Set a double x-axis label


code:
# -*- coding: utf-8 -*-

def run():
    code_task = get_active_task()

    from os.path import dirname

    def change_directory():
        code_editor = code_task.active_editor
        if not code_editor:
            return
        python_pane = code_task.python_pane
        active_dir = dirname(code_editor.obj.path)
        python_pane.execute_command(u'cd %s\n' % active_dir)

    code_task.on_trait_change(change_directory, 'active_editor')

rawDescription: Setting the working directory of IPython Shell to that of the python file being executed in Canopy


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

fig = plt.figure()
h, = plt.plot([], [])

plt.ion()
plt.show()

for i in range(0, 100):
    t = np.arange(i * 0.05, (i+1) * 0.05, 0.01)
    y = np.sin(2*np.pi*t)
    h.set_xdata(np.append(h.get_xdata(), t))
    h.set_ydata(np.append(h.get_ydata(), t))

    fig.canvas.draw()
    time.sleep(0.05)

    plt.xlim(0,h.get_xdata().max())
    plt.ylim(0,h.get_ydata().max())

rawDescription: Can't update my plot with matplotlib

description: Can't update my plot with matplotlib


code:
for root, dirs, files in os.walk(path, topdown=False):  # Listing the files
    for i, name in enumerate(dirs):
        output = name.replace(pattern, "")              # Taking out pattern
        if output != name:
            os.rename(                                  # Renaming
                os.path.join(root, name),
                os.path.join(root, output))
        else:
            pass

rawDescription: Python - recursive directory hit with os.walk()


code:
parser = argparse.ArgumentParser()
parser.add_argument('input', type=argparse.FileType(), nargs='?', default=sys.stdin)
args = parser.parse_args()
G = defaultdict(list)
for line in args.input:
    ...

rawDescription: Python interactive after reading sys.stdin


code:
import MySQLdb
db = MySQLdb.connect(host="localhost",
                     user="user",
                      passwd="password",
                      db="database")
cur = db.cursor()
cur.execute("SELECT common_name , genus , species  FROM table WHERE sequence LIKE 'MDPSSID%'")

rawDescription: Searching through database with python

description: Searching through database with python


code:
cs = contour(X,Y,A,0)
data = cs.collections[0].get_paths()[1]

rawDescription: Find root of implicit function in Python


code:
import rpy2.robjects as ro

# R SCRIPT
ro.r.source('yourRscript.R')

# R DATA FRAME
ro.globalenv['counts']

# OMIT NA ROWS
ro.r('na.omit(counts$hgnc)')

rawDescription: Omit NA rows with rpy2

description: Omit NA rows with rpy2


code:
od = OrderedDict({i:i for i in range(4)})
# od = OrderedDict([(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])

# Replace the key and value for key == 0:
d = OrderedDict(('replace','key') if key == 0 else (key, value) for key, value in od.items())
# d = OrderedDict([('replace', 'key'), (1, 1), (2, 2), (3, 3), (4, 4)])

# Single value replaces are done easily:
d[1] = 20  # and so on..

rawDescription: Replacing an element in an OrderedDict?

description: Replacing an element in an OrderedDict


code:
payload = {'word': 'yellow'}
r = requests.get("http://server.eu/word.py", params=payload)

rawDescription: Python key adding to url

description: Python key adding to url


code:
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']

rawDescription: Get Cookie By Key?

description: Get Cookie By Key


code:
xml = """\
<?xml version="1.0" encoding="ISO-8859-1"?>
<Book>
  <Page>
    <Text>Blah</Text>
  </Page>
</Book>
"""
import xml.etree.cElementTree as ET
root = ET.fromstring(xml)
element = root.getchildren()[0].getchildren()[0]
element.tag
element.text

rawDescription: Parsing XML using xml.etree.cElementTree


code:
import csv
import shutil
from itertools import groupby

n = 24
time_increment = 1./n
fractions = [("%.3f" % (i*time_increment,)).lstrip('0') for i in xrange(n)]

with open('input.csv', 'rb') as f, open('output.csv', 'wb') as fout:
     writer = csv.writer(fout)
     # assume the file is sorted by timestamp
     for timestamp, group in groupby(csv.reader(f), key=lambda row: row[0]):
         sametime = list(group) # all rows that have the same timestamp
         assert n >= len(sametime)
         for i, row in enumerate(sametime, start=n-len(sametime)):
             row[0] += fractions[i] # append fractions of a second
         writer.writerows(sametime)

shutil.move('output.csv', 'input.csv') # update input file

rawDescription: Python modifying csv column by increments


code:
A=np.array([[2,0,0],[1,1,0],[1,0,1],[0,2,0],[0,1,1],[0,0,2]])
pattern = [0,2,0]
np.where(np.all(pattern==A,1))  # Saullo's where
A.tolist().index(pattern)  # your list find
D={tuple(a):i for i,a in enumerate(A.tolist())}  # dictionary
D[tuple(pattern)]

rawDescription: Index of list within a numpy array

description: Index of list within a numpy array


code:
from PIL import Image
from math import *
import numpy

list1 = []
im = Image.open("313.JPG")
im.show()
list1 = list(im.getdata())
length = len(list1)

# generate random noise data with mean 0 and sd 10
list2 = numpy.random.normal(0, 10, length)
# Add this to the image data
list3 = list1+list2

im.putdata(list3)
im.show()

rawDescription: Image getting dark

description: Image getting dark


code:
from pyspark.statcounter import StatCounter

rdd = sc.parallelize([9, -1, 0, 99, 0, -10])
stats = rdd.aggregate(StatCounter(), StatCounter.merge, StatCounter.mergeStats)
stats.minValue, stats.maxValue

rawDescription: finding min/max with pyspark in single pass over data

description: Finding min/max with pyspark in single pass over data


code:
import os
try:
    os.remove("my.png")
except: pass

rawDescription: Delete an image in OpenCV using Python

description: Delete an image in OpenCV using Python


code:
import xml.etree.cElementTree as etree

def getelements(filename_or_file, tag):
    context = iter(etree.iterparse(filename_or_file, events=('start', 'end')))
    _, root = next(context) # get root element
    for event, elem in context:
        if event == 'end' and elem.tag == tag:
            yield elem
            root.clear() # preserve memory

for host in getelements("test2.nessus", "ReportHost"):
    for cvss_el in host.iter("cvss_base_score"):
        print(cvss_el.text)

rawDescription: iterparse fails to parse a field, while other similar ones are fine

description: Iterparse fails to parse a field, while other similar ones are fine


code:
#!/usr/bin/env python3
import time
from subprocess import Popen, PIPE

LINE_BUFFERED = 1
filename = r"C:\Users\me\...Afton.mp3"
with Popen('mplayer -slave -quiet'.split() + [filename],
           stdin=PIPE, universal_newlines=True, bufsize=LINE_BUFFERED) as process:
    send_command = lambda command: print(command, flush=True, file=process.stdin)
    time.sleep(1)
    for _ in range(2):
        send_command('pause')
        time.sleep(1)
    send_command('quit')

rawDescription: writing commands to mplayer subprocess with python 3 in windows

description: Writing commands to mplayer subprocess with python 3 in windows


rawDescription: Replace two different characters with Regex


code:
from collections import Counter
Counter((f, s) for (_, f), (_, s) in zip(tuples, tuples[1:]))

rawDescription: iterating through tuples, obtaining the next item

description: Iterating through tuples, obtaining the next item


code: df['DOW'] = df['Date'].map(DOW)

rawDescription: Adding new values to Pandas DataFrame

description: Adding new values to Pandas DataFrame


code:
arrayDict = {}
name = readStringFromFile()
data = readArrayFromFile()
arrayDict[name] = data

rawDescription: How to rename an array in python?

description: Rename an array in python


code:
userInput = raw_input("Give some input: ")

try:
    userInput = int(userInput)
except ValueError:
    pass

rawDescription: Python if conversion str/int

description: Python if conversion str/int


code:
import sh
print(sh.ls("/"))

# same thing as above
from sh import ls
print(ls("/"))

rawDescription: Execute shell command and retrieve stdout in Python


code:
import re
with open(filetoread, "r+b") as inf:
    with open(filetowrite, "w") as fixed:
        for l in re.finditer('(?:.*?\|){4}(?:.*?)\n', inf.read(), re.DOTALL):
            fixed.write(l.group(0).replace('\n','') + '\n')

rawDescription: Replace carriage returns in list python

description: Replace carriage returns in list python


code:
class C(metaclass=ABCMeta):
    @property
    def x(self):
        ...

    @x.setter
    @abstractmethod
    def x(self, val):
        ...

class D(C):
    @C.x.setter
    def x(self, val):
        ...

rawDescription: python abstract property setter with concrete getter

description: Python abstract property setter with concrete getter


code:
text = "Text1 Text2 Text3 Text4 Text5\n\
Here comes more test text\n\
and even more1 more2 more3\n\
tex text textt te tex\n\
1 2 3 4 5"
filecsv = open('csvfile.csv', 'w+')
filecsv.write(text.replace(' ', ';'))
filecsv.close()

rawDescription: Write a CSV file in Python

description: Write a CSV file in Python


code:
class User(AbstractBaseUser, PermissionMixin):
    username = models.CharField('Usuário', max_length=30, unique=True,
        validators=[validators.RegexValidator(re.compile('^[\w.@+-]+$'),
            'O nome de usuário só pode conter letras, digitos ou os '
            'seguintes caracteres: @/./+/-/_', 'invalid')]
    )

    nome = models.CharField('Nome', max_length=100)
    email = models.EmailField('E-mail', unique=True) # blank=True?
    instituicao = models.CharField('Instituição', max_length=200)
    SEXO_CHOICE = ((0, 'Masculino'), (1, 'Feminino'))
    sexo = models.IntegerField('Sexo', choices=SEXO_CHOICE, default=0)
    imagem_perfil = models.ImageField('Imagem do perfil', upload_to='media/img/%Y/%m/%d', blank=True)
    is_active = models.BooleanField('Está ativo?', blank=True, default=True)
    is_staff = models.BooleanField('É administrador?', blank=True, default=False)
    date_joined = models.DateTimeField('Data de Entrada', auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']

    def __str__(self):
        return self.nome

    def get_short_name(self):
        return str(self)

    def get_full_name(self):
        return self.nome

    class Meta:
        verbose_name = 'Usuário'
        verbose_name_plural = 'Usuários'

class Aluno(User):
    mother_name = models.CharField('Mother name ', max_length=100)

    class Meta:
        verbose_name = 'Aluno'
        verbose_name_plural = 'Alunos'

class Professor(User):
    endereco = models.CharField('Endereço', max_lenght=100)

    class Meta:
        verbose_name = 'Professor'
        verbose_name_plural = 'Professores'

rawDescription: Cannot assign "'Mary'":"Aluno.mother_name" must be a "Aluno" instance. When I try to access field in subclass "Aluno"


code:
import re

LOG    = "spammers.txt"
IPV4   = re.compile(r"(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})")
RESULT = "organized_ips.txt"

def get_ips(fname):
    with open(fname) as inf:
        return IPV4.findall(inf.read())

def numeric_ip(ip):
    return [int(i) for i in ip.split(".")]

def write_to(fname, iterable, fmt):
    with open(fname, "w") as outf:
        for i in iterable:
            outf.write(fmt.format(i))

def main():
    ips = get_ips(LOG)
    ips = list(set(ips))      # uniquify
    ips.sort(key=numeric_ip)
    write_to(RESULT, ips, "IP: {}\n")

if __name__=="__main__":
    main()

rawDescription: Extract IPs after specific delimiter

description: Extract IPs after specific delimiter


code:
alist = []

for root, directories, filenames in os.walk('/somedir/full/of/subdirs/and_PDFs'):
    for fn in filenames:
        alist.append(os.path.join(root,fn))

rawDescription: os.walk thinks my directory contains only .DS_Store files

description: Os.walk thinks my directory contains only .DS_Store files


code:
from tkinter import *
index={'Food':['apple', 'orange'], 'Drink':['juice', 'water', 'soda']}
Names=['Food', 'Drink']

def display(list):
    for item in list:
        print(item)

mon=Tk()
app=Frame(mon)
app.grid()

for item in Names:
    Button(mon, text=item, command= lambda name = item: display(index[name])).grid()
mon.mainloop()

rawDescription: How to have parameters to a button command in tkinter python3

description: Have parameters to a button command in tkinter python3


code:
import os
import sys

if len(sys.argv) > 1:
    full_path = os.path.join(os.getcwd(), sys.argv[1])
    print(full_path)

rawDescription: How to find the location of the configuration file passed as argument to Python script?

description: Find the location of the configuration file passed as argument to Python script


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.button = QtGui.QPushButton('Test', self)
        self.button.clicked.connect(self.handleButton)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.button)

    def handleButton(self):
        modifiers = QtGui.QApplication.keyboardModifiers()
        if modifiers == QtCore.Qt.ShiftModifier:
            print('Shift+Click')
        elif modifiers == QtCore.Qt.ControlModifier:
            print('Control+Click')
        elif modifiers == (QtCore.Qt.ControlModifier |
                           QtCore.Qt.ShiftModifier):
            print('Control+Shift+Click')
        else:
            print('Click')

if __name__ == '__main__':

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

rawDescription: How to check if a key modifier is pressed (shift, ctrl, alt)?

description: Check if a key modifier is pressed (shift, ctrl, alt)


code:
import math

class Enemy(object):
    ...
    def move_towards_player(self, player):
        # find normalized direction vector (dx, dy) between enemy and player
        dx, dy = self.rect.x - player.rect.x, self.rect.y - player.rect.y
        dist = math.hypot(dx, dy)
        dx, dy = dx / dist, dy / dist
        # move along this normalized vector towards the player at current speed
        self.rect.x += dx * self.speed
        self.rect.y += dy * self.speed

rawDescription: How to make an enemy follow the player in pygame?

description: Make an enemy follow the player in pygame


code:
kerneldt = np.dtype([('myintname', np.int32), ('myfloats', np.float64, 9)])
arr = np.empty(dims, dtype=kerneldt)

rawDescription: Custom data types in numpy arrays

description: Custom data types in numpy arrays


code:
verifications = Verification.objects.filter(asset_code__range=(10, 100))
verifications.update(product_details=form.cleaned['product_details'])

rawDescription: How to update a single column in a subset of database table records using Django form or ModelForm?

description: Update a single column in a subset of database table records using Django form or ModelForm


code:
class Foo(dict):
    def __init__(self, *args, **kwargs):
        super(Foo, self).__init__(*args, **kwargs)
        self.banana = 'banana'
        self['banana'] = 'not really a banana'

f = Foo()
f.__dict__
f.banana
f['banana']

rawDescription: If you subclass from dict, why is __dict__ always empty?


code:
result = {'LARCENY' : 3, 'BURGLARY' : 2, 'ROBBERY - STREET' : 3}
result = [{k:v} for k,v in result.items()]
result

rawDescription: How can I count occurrences of values in a list of dicts?

description: Count occurrences of values in a list of dicts


code:
from suds import null

Int1 = client.factory.create('ns2:IntersectingRoad')
Int1.RoadName = null()
Int1.RoadType = null()

rawDescription: suds send None attribute

description: Suds send None attribute


code:
g = Gnuplot.Gnuplot(debug=1)
#xpos is always the same
xpos=0.0
for plotnr,datafile in enumerate(glob.glob('*.dat')):
    #ypos as a function of the plot-number, e.g.
    ypos=plotnr*2.0
    g("set key at "+str(xpos)+","+str(ypos))
    d = Gnuplot.File(datafile, using='1:2', with_='l', title=datafile)
    g.plot(d)

rawDescription: python: Gnuplot - variable parameter in 'set key' (for example)

description: Python: Gnuplot - variable parameter in 'set key' (for example)


code:
CRC_TABLE = (0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9,
             0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005,
             0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61,
             0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD)

def dword(value):
    return value & 0xFFFFFFFF

def crc32_fast(crc, data):
    crc, data = dword(crc), dword(data)
    crc ^= data
    for _ in range(8):
        crc = dword(crc << 4) ^ CRC_TABLE[crc >> 28]
    return crc

def crc32_fast_block(crc, buffer):
    for data in buffer:
        crc = crc32_fast(crc, data)
    return crc

def crc32_fast_bytes(crc, bytes_data):
    if len(bytes_data) & 3:
        raise ValueError('bytes_data length must be multiple of four')
    for index in range(0, len(bytes_data), 4):
        data = int.from_bytes(bytes_data[index:index+4], 'big')
        crc = crc32_fast(crc, data)
    return crc

rawDescription: Convert this CRC32 algorithm to Python 3.3


code:
import numpy as np

new = np.array([])

for AV in AVERAGE_files:
   x = np.load(AV) # I assume num in your example is an alias for numpy?
   new = np.concatenate([new,x])

rawDescription: Load and concatenate numpy arrays

description: Load and concatenate numpy arrays


code:
import os, shutil

fromdir = '/home/mac/Desktop'
todir = '/home/mac/Desktop/tmp'
gt = os.path.getmtime  #change if you want something else
oldest = min([(f, gt(f)) for f in os.listdir(fromdir)])[0]
shutil.move(fromdir + '/' + oldest, todir)

rawDescription: Copy oldest file to another directory using Python


code:
adj = gtk.Adjustment(1, 1, 99, 1, 1, 1)
spinBtn = self.builder.get_object("spinbutton1")
spinBtn.configure(adj, 1, 0)

rawDescription: GtkSpinButton disabled by default in Glade


code:
import time
import sys

def delay_print(s):
    for c in s:
        sys.stdout.write( '%s' % c )
        sys.stdout.flush()
        time.sleep(0.25)

delay_print("hello world")

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

description: Print one character at a time on one line


code:
with open("test.fasta", "r") as fasta, open("test.tax", "w") as tax:
    for line in fasta:
        if line.startswith('>'):
            line = line[1:]                   # remove the '>' from start of line
            line = line.replace(' ', '\t', 1) # replace first space with a tab
            line = line.replace(' ', '_')     # replace remaining spaces with '_'
            line = line.strip() + ';\n'       # add ';' to the end
            tax.write(line)                   # write to the output file

rawDescription: How to perform several modification to several string within a file and output to a new file

description: Perform several modification to several string within a file and output to a new file


code: db = sqlite3.connect('file:/path/to/database?mode=ro', uri=True)

rawDescription: sqlite3 read-only on a file system that doesn't support locking

description: Sqlite3 read-only on a file system that doesn't support locking


code:
change_text = lambda x:'changed_'+x
posts = [[1, 'text1', 0], [1, 'text2', 0]]
[[post[0],change_text(post[1]),post[2]] for post in posts]

rawDescription: How to change n-th element in list of lists with python list comprehensions?

description: Change n-th element in list of lists with python list comprehensions


code: x.reshape(-1, 4, 3).sum(axis=2)

rawDescription: Numpy sum every n columns of matrix

description: Numpy sum every n columns of matrix


code:
from py4j.java_gateway import java_import, JavaGateway, JavaObject
from py4j.protocol import DEFAULT_JVM_ID

def get_imports(gateway):
    java_jvm_view = JavaObject(DEFAULT_JVM_ID[1:], gateway._gateway_client)
    imports = list(java_jvm_view.getSingleImportsMap().values()) + list(java_jvm_view.getStarImports())
    return imports

java_gateway = JavaGateway()
java_import(gateway.jvm, "java.util.Collection")
java_import(gateway.jvm, "java.sql.*")
java_import(gateway.jvm, "java.util.ArrayList")
imports = get_imports(gateway)
# [u'java.util.ArrayList', u'java.util.Collection', u'java.lang', u'java.sql']

rawDescription: How to view imported classes from py4j gateway

description: View imported classes from py4j gateway


code:
polydata = output
array = vtk.vtkIntArray()
array.SetNumberOfComponents(0)
array.SetName("regionsize")
for i in range(polydata .GetNumberOfPoints()):
    array.InsertNextValue(somecomputedvalue)
polydata.GetPointData().AddArray(array);

rawDescription: How to add a custom array to a polydata in paraview?

description: Add a custom array to a polydata in paraview


rawDescription: Spark add new column to dataframe with value from previous row


code:
class OperParseActionHolder(object):
    def __init__(self):
        # initialize with a do-nothing parse action
        self.fn = lambda s,l,t: None

    def __call__(self, s, l, t):
        return self.fn(s,l,t)

notParseAction = OperParseActionHolder()
andParseAction = OperParseActionHolder()
orParseAction = OperParseActionHolder()

expr = pp.operatorPrecedence(condition, [
    (not_, 1, pp.opAssoc.RIGHT, notParseAction),
    (and_, 2, pp.opAssoc.LEFT, andParseAction),
    (or_, 2, pp.opAssoc.LEFT, orParseAction),
])

# before calling expr.parseString
notParseAction.fn = theRealParseActionToCallForNot
andParseAction.fn = theRealParseActionToCallForAnd
orParseAction.fn = theRealParseActionToCallForOr

rawDescription: Setting parse action for operatorPrecedence in pyparsing


code:
import urlparse
import sys
import posixpath

def relurl(target,base):
    base=urlparse.urlparse(base)
    target=urlparse.urlparse(target)
    if base.netloc != target.netloc:
        raise ValueError('target and base netlocs do not match')
    base_dir='.'+posixpath.dirname(base.path)
    target='.'+target.path
    return posixpath.relpath(target,start=base_dir)

tests=[
    ('http://www.example.com/images.html','http://www.example.com/faq/index.html','../images.html'),
    ('http://google.com','http://google.com','.'),
    ('http://google.com','http://google.com/','.'),
    ('http://google.com/','http://google.com','.'),
    ('http://google.com/','http://google.com/','.'),
    ('http://google.com/index.html','http://google.com/','index.html'),
    ('http://google.com/index.html','http://google.com/index.html','index.html'),
    ]

for target,base,answer in tests:
    try:
        result=relurl(target,base)
    except ValueError as err:
        print('{t!r},{b!r} --> {e}'.format(t=target,b=base,e=err))
    else:
        if result==answer:
            print('{t!r},{b!r} --> PASS'.format(t=target,b=base))
        else:
            print('{t!r},{b!r} --> {r!r} != {a!r}'.format(
                t=target,b=base,r=result,a=answer))

rawDescription: How to construct relative url, given two absolute urls in Python

description: Construct relative url, given two absolute urls in Python


code:
from Tkinter import *

master = Tk()
def vscale_cb(value):
    print('vertical: {v}'.format(v=value))
def hscale_cb(value):
    print('horizontal: {v}'.format(v=value))

w = Scale(master, from_=0, to=100, command=vscale_cb)
w.pack()

w = Scale(master, from_=0, to=200, orient=HORIZONTAL, command=hscale_cb)
w.pack()

mainloop()

rawDescription: TKinter: a slider widget?

description: TKinter: a slider widget


code:
def remove_user(self,user_or_username):
    try:
        #If user_or_username is a User object
        username = user_or_username.name
    except AttributeError:   #Oops -- didn't works.  ask forgiveness ;-)
        #If user_or_username is a string
        username = user_or_username
    remote.remove(username)

rawDescription: Function polymorphism in Python

description: Function polymorphism in Python


code:
class B(A):
    def __init__(self, arg1, *ignored):
        # `ignored` is.. ignored
        A.__init__(self, arg1, None)

rawDescription: __deepcopy__ and inheritance with changing arguments in __init__


code:
a = "0343523"
a.isdigit()
True

b = "934sjsspam"
b.isdigit()
False

rawDescription: Read a file of mixed items and retain their data types


code:
htmlfile = open('database.html', 'w')
htmlfile.write('<html>...')
htmlfile.write('<script>var db = ' + json.encode(database) + ';</script>');

rawDescription: python database search with html

description: Python database search with html


code:
import readline

def make_pre_input_hook(default):

    def pre_input_hook():
        readline.insert_text(default)
        readline.redisplay()

    return pre_input_hook

readline.set_pre_input_hook(make_pre_input_hook('Charles'))

name = input('Edit your name: ')

print('You are now called {}.'.format(name))

rawDescription: Python3 - How to add a name for editing in input?


code:
def previous_quarter(ref):
    if ref.month < 4:
        return datetime.date(ref.year - 1, 12, 31)
    elif ref.month < 7:
        return datetime.date(ref.year, 3, 31)
    elif ref.month < 10:
        return datetime.date(ref.year, 6, 30)
    return datetime.date(ref.year, 9, 30)

rawDescription: Calculate the end of the previous quarter


code:
output_filename = in_put[0:len(in_put)-4] + "_modified.jpg"
pic_im.save(output_filename)

rawDescription: PIL: saving file in python

description: PIL: saving file in python


code:
import datetime
def timeconverter(timestring):
   hour, min, sec = timestring.split(':')
   sec, usec = sec.split('.')
   time = datetime.time(*[int(x, 10) for x in (hour, min, sec, usec)])
   return time

rawDescription: Convert string to time format

description: Convert string to time format


code:
for k in ResListA:
    for n in ResListB:
        for m in k.atoms:
            for z in n.atoms:
                coordDist = distance.distance(m.atoms, z.atoms)

rawDescription: Python: 4 for cycles, comparing list items


code:
def find_in_list_of_list(mylist, char):
    for sub_list in mylist:
        if char in sub_list:
            return (mylist.index(sub_list), sub_list.index(char))
    raise ValueError("'{char}' is not in list".format(char = char))

example_list = [['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h']]

find_in_list_of_list(example_list, 'b')
(0, 1)

rawDescription: Finding the index of an element in nested lists in python


code:
with open('words.txt') as f:
    words = [word.strip() for word in f]

rawDescription: How to strip newlines from each line during a file read?

description: Strip newlines from each line during a file read


code:
my_string = '%s%s%s%s' % (first, second, third, fourth)
byte_string = my_string.encode('utf-8')

rawDescription: How do I turn a Python string stored in a variable into a byte sequence?

description: Turn a Python string stored in a variable into a byte sequence


code:
def do_POST(self):
    # ... some code to get args ... and output ...
    subprocess.Popen([cmd, args])

    self.send_response(201)
    self.send_header("Content-Length", str(len(output))) # This line does the trick!
    self.end_headers()
    self.wfile.write(output)

rawDescription: Background service, SimpleHTTPServer and AJAX


code:
from vtk.util import numpy_support as npvtk
vtkarray = npvtk.numpy_to_vtk(numpy_array)
numpy_array = npvtk.vtk_to_numpy(vtkarray)

rawDescription: Creating a contour plot in paraview from a numpy array


code:
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from numpy import sin, cos, pi, array

spring_constant = 22.93
length = 0.16
mass = 0.1

# initial conditions
init = array([-0.35, 0, 0.08, 1]) # initial values
      #array([theta, theta_dot, x, x_dot])

#Return derivatives of the array z (= [theta, theta_dot, x, x_dot])
def deriv(z, t, spring_k, spring_l, bob_mass):
    k = spring_k
    l = spring_l
    m = bob_mass
    g = 9.8

    theta = z[0]
    thetadot = z[1]
    x = z[2]
    xdot= z[3]

    return array([
        thetadot,
        (-1.0/(l+x)) * (2*xdot*thetadot + g*sin(theta)),
        xdot,
        g*cos(theta) + (l+x)*thetadot**2 - (k/m)*x
        ])

#Create time steps
time = np.linspace(0.0,10.0,1000)

#Numerically solve ODE
y = odeint(deriv,init,time, args = (spring_constant, length, mass))

l = length
r = l+y[:,2]
theta = y[:,0]
dt = np.mean(np.diff(time))

x = r*sin(theta)
y = -r*cos(theta)

##MATPLOTLIB BEGINS HERE##

fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False,
                     xlim=(-1.2*r.max(), 1.2*r.max()),
                     ylim=(-1.2*r.max(), 0.2*r.max()), aspect = 1.0)
ax.grid()

##ANIMATION STUFF BEGINS HERE##

line, = ax.plot([], [], 'o-', lw=2)

time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)
foox = []
fooy = []
#foo.set_data(foox, fooy)

def init():
    global line, time_text, foo
    line.set_data([], [])
#    foo.set_data([], [])
    time_text.set_text('')
    return line, time_text#, foo

def animate(i):
    global foox, fooy, foo
    thisx = [0, x[i]]
    thisy = [0, y[i]]

    foox += [x[i]]
    fooy += [y[i]]

    line.set_data(thisx, thisy)
#    foo.set_data(foox, fooy)

    time_text.set_text(time_template%(i*dt))
    return line, time_text#, foo

ani = animation.FuncAnimation(fig, animate, np.arange(1, len(y)), interval=25, blit=False, init_func=init)

plt.show()

rawDescription: Python matplotlib animating the path of an object


code:
def nexthigher(n):
    for p in permutations(sorted(str(n))):
        i = int("".join(p))
        if i > n:
            return i

rawDescription: combining strings of n length in a list python

description: Combining strings of n length in a list python


code:
while username not in {"cking", "doneal", "mcook"}:
    print ("Invalid username. Please try again.")
    username = input ("Enter username:")
print ("Valid username.")

rawDescription: What's going on with my if-else statement? (Python 3.3)


code:
from collections import MutableMapping, OrderedDict

class FixedOrderedDict(MutableMapping):
    def __init__(self, *args):
        self._d = OrderedDict(*args)

    def __getitem__(self, key):
        return self._d[key]

    def __setitem__(self, key, value):
        if key not in self._d:
            raise KeyError("Must not add new keys")
        self._d[key] = value

    def __delitem__(self, key):
        raise NotImplementedError("Must not remove keys")

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

rawDescription: Mutable dictionary with fixed and ordered keys


code:
sage: var('x y z')
(x, y, z)
sage: expr = x^2*y + 2*z
sage: expr.variables()
(x, y, z)

rawDescription: How to extract the variables from a polynomial in python /Sage

description: Extract the variables from a polynomial in python /Sage


code:
kwargs = {'membership__is_tech': True}
ms_tech = microsoft.filter(**kwargs)

rawDescription: Dynamic SQL join query in django

description: Dynamic SQL join query in django


code:
from datetime import timedelta, datetime

d = timedelta(days=41433.662413)
st = datetime(1899,12,31)
date = st + d
print(date)

rawDescription: Decimal date & time conversion

description: Decimal date & time conversion


code:
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3,14],'ro-')

# set your ticks manually
ax.xaxis.set_ticks([1.,2.,3.,10.])
ax.grid(True)

plt.show()

rawDescription: matplotlib, define size of a grid on a plot

description: Matplotlib, define size of a grid on a plot


code:
ip=open(nonascii.txt,'r')
#Edit should be in w mode
op=open(ascii.txt,'w')
for line in ip:
        line=line.strip().decode("ascii","ignore").encode("ascii")
        if line=="":continue
        op.write(line)
ip.close()
op.close()

rawDescription: Removing non ASCII from corpus

description: Removing non ASCII from corpus


code:
plt.rcParams['figure.figsize'] = (9,9)
x = np.linspace(55478, 55486, 100)
y = np.random.random(100) - 0.5
y = np.cumsum(y)
plt.ticklabel_format(style='sci', axis='both', scilimits=(0,0),useOffset=False)
plt.plot(x,y,'b-')

rawDescription: Offset value in Matplotlib (Python)

description: Offset value in Matplotlib (Python)


code:
def b():
    return 3 * a

rawDescription: Python getting a variable to change as what it's assigned to changes


code: [item for index, item in enumerate(lst) if index not in plist]

rawDescription: How to maintain consistency in list?

description: Maintain consistency in list


code:
df = pd.DataFrame()
sym_len = len(snapshot[sym])
for i, sym in enumerate(sorted(snapshot)):
    for j, lp in enumerate(sorted(snapshot[sym])):
        idx = i*sym_len + j
        df.loc[idx, 'trader'] = lp
        df.loc[idx, 'bid'] = snapshot[sym][lp][":b"]["LUC"]["price"] if ":b" in snapshot[sym][lp] else "0"
        df.loc[idx, 'ask'] = snapshot[sym][lp][":a"]["LUC"]["price"] if ":a" in snapshot[sym][lp] else "0"

rawDescription: Creating dataframe columns within a for loop


code:
s = "welcome"
l = ['welc', 'hey', 'sto']
any(s.startswith(i) for i in l)

rawDescription: text.startswith method with multi words

description: Text.startswith method with multi words


code:
class Application(object):
    process_class = Processes
    ...
    def instances(self):
        return self.process_class.all().filtered(lambda process: process.name() == self.name)

rawDescription: Dependency injection on data objects

description: Dependency injection on data objects


code:
dist = pkg_resources.get_distribution('your-app')
if dist.precedence == pkg_resources.DEVELOP_DIST:
    # package is in development mode
    ...

rawDescription: figure out whether python module is installed or in develop mode programmatically

description: Figure out whether python module is installed or in develop mode programmatically


code:
@notfound_view_config(containment=Foo)
def notfound(request):
    return HTTPNotFound('no views for Foo detected for view %s' % request.view_name)

rawDescription: Defining a fallback view in traversal

description: Defining a fallback view in traversal


code: emails = re.findall('[^@ ]+@[^@ ]+\.[^@ ]+', stringWithEmails)

rawDescription: printing all email addresses of a string

description: Printing all email addresses of a string


code:
query = User.all()
users = query.fetch(10)
self.response.out.write("
")
for user in users:
    self.response.out.write("
")
    self.response.out.write(user.userEmail)
    self.response.out.write("
")
    # Iterate over the venues
    for venue in user.venues:
        self.response.out.write("
%s
" % venue.venue)
    self.response.out.write("

")
self.response.out.write("
")

rawDescription: How to access items in a model with ReferenceProperty?

description: Access items in a model with ReferenceProperty


code:
with open("bigfile", mode="r") as bigfile:
    reader = bigfile.read()
    for i,part in enumerate(reader.split("Racecar")):
        with open("File_" + i+1, mode="w") as newfile:
            newfile.write("Racecar"+part)

rawDescription: Split file into files with keyword in Python?


code:
def venn_circle(circle_color, circle_radius):
    """ Draws a colored circle, returns the points within. """
    turtle.color(circle_color)
    # <fill in: code to move, orient the turtle>
    center = turtle.position()
    # <fill in: code to draw the circle>
    return circle_coords(center, circle_radius)

def circle_coords(center, radius):
    """ Return the set of pixels within the circle. """
    raise NotImplementedError()

rawDescription: How can I make Turtle recognize a circle?

description: Make Turtle recognize a circle


code:
#/usr/bin/python

if condition():

    fo=open('tempfile.txt','a')
    fo.write('This content\n')

rawDescription: How do I exit without saving a file in Python

description: Exit without saving a file in Python


code:
import os
import sys
sys.path.append(os.getcwd())

rawDescription: import a module in current working directory

description: Import a module in current working directory


code: "{name} is a {adjective} {noun} that {verb}".format(**locals())

rawDescription: How do I use Python to easily expand variables to strings?

description: Use Python to easily expand variables to strings


code:
c = a.copy()
c[np.in1d(a.ravel(), b).reshape(a.shape)] = 0

rawDescription: Python fast way to substitute specific values in array


code:
list_keys = [ListUser.list.get_value_for_datastore(list_user)
              for list_user in list_users]
lists = db.get(list_keys)

rawDescription: How to make a light query for a many to many relationship in Google Apps Engine?

description: Make a light query for a many to many relationship in Google Apps Engine


code:
items = [1, 2]
a = convert_val(items)
b = map(convert_val, items)

rawDescription: Way to Treat Python single vals and lists of vals identically?


code:
import matplotlib.pyplot as plt

# create fig1 (of type plt.figure)
# create fig2

plt.show()  # will display fig1 and fig2 in different windows

rawDescription: How to show an AxesSubplot in Python?

description: Show an AxesSubplot in Python


code:
import pandas as pd
pd.set_option('display.height', 1000)
pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)

rawDescription: Python pandas, widen output display?

description: Python pandas, widen output display


code: df[['B', 'C']].stack().reset_index()

rawDescription: pandas stack with row numbers

description: Pandas stack with row numbers


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

f = np.random.random(100)
g = np.random.random(100)
fig = plt.figure()
fig.suptitle('Long Suptitle', fontsize=24)
plt.subplot(121)
plt.plot(f)
plt.title('Very Long Title 1', fontsize=20)
plt.subplot(122)
plt.plot(g)
plt.title('Very Long Title 2', fontsize=20)
plt.subplots_adjust(top=0.85)
plt.show()

rawDescription: Matplotlib tight_layout() doesn't take into account figure suptitle


code:
year = int(date.Year.text)
month = int(date.Month.text)
day = int(date.Day.text)

rawDescription: Python XML BeautifulSoup get text of children nodes


code:
...
if cursor and table_name_converter(model._meta.db_table) in table_names:
    # Drop the table now
    output.append('%s %s %s;' % (style.SQL_KEYWORD('DROP TABLE IF EXISTS'), #<-!
                                 style.SQL_TABLE(qn(model._meta.db_table)),
                                 style.SQL_KEYWORD('CASCADE')))    #<-!
...

rawDescription: How to make Django sqlclear output CASCADE for dependent relationships

description: Make Django sqlclear output CASCADE for dependent relationships


code:
for i in range(0, 20):
    # Put the full URL below, I've put ... to shorten it
    url = 'http://ecorp.azcc.gov/...CurrentPageIndex={}...'.format(i)
    fhand = urllib.urlopen(url)
    # do something with fhand

rawDescription: Python Urllib Query

description: Python Urllib Query


code:
# create a sound from NumPy array of file
snd = pygame.mixer.Sound(my_sound_source)

# open new wave file
sfile = wave.open('pure_tone.wav', 'w')

# set the parameters
sfile.setframerate(SAMPLINGFREQ)
sfile.setnchannels(NCHANNELS)
sfile.setsampwidth(2)

# write raw PyGame sound buffer to wave file
sfile.writeframesraw(snd.get_buffer().raw)

# close file
sfile.close()

rawDescription: pygame mixer save audio to disk?

description: Pygame mixer save audio to disk


rawDescription: How to get latest timestamp in a column?

description: Get latest timestamp in a column


code: from paste.httpheaders import *

rawDescription: What does this code from AuthKit do? (where are these functions and methods defined?)


code:
import copy_reg
import types
import multiprocessing

def _pickle_method(m):
    if m.im_self is None:
        return getattr, (m.im_class, m.im_func.func_name)
    else:
        return getattr, (m.im_self, m.im_func.func_name)

copy_reg.pickle(types.MethodType, _pickle_method)

class Controler(object):
    def __init__(self):
        nProcess = 10
        pages = 10
        self.__result = []
        self.manageWork(nProcess, pages)

    def BarcodeSearcher(self, x):
        return x*x

    def resultCollector(self, result):
        self.__result.append(result)

    def manageWork(self, nProcess, pages):
        pool = multiprocessing.Pool(processes=nProcess)
        for pag in range(pages):
            pool.apply_async(self.BarcodeSearcher, args=(pag,),
                             callback=self.resultCollector)
        pool.close()
        pool.join()

        print(self.__result)

if __name__ == '__main__':
    Controler()

rawDescription: Can't pickle <type 'instancemethod'> using python's multiprocessing Pool.apply_async()


rawDescription: get local path of an uploaded file in django

description: Get local path of an uploaded file in django


code: pathList = glob.glob("./%s/19??@60??_npo/" % path)

rawDescription: Python: function to identify all subfolders that match a pattern


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

class MyXmlParser(object):

    def __init__(self, xml_file_name):
        self.doc  = ET.parse(xml_file_name)
        self.root = doc.getroot()

    def do_something(self, output = sys.stdout):
        root_new  = ET.Element("users")
        for child in self.root:
            username             = child.attrib['username']
            password             = child.attrib['password']
            # create "user" here
            user    = ET.SubElement(root_new, "user")
            user.set("username",username)
            user.set("password",password)
            # checking attribute - skip KeyError
            try:
                remote_access   = child.attrib['remote_access']
                user.set("remote_access", remote_access)
            except KeyError:
                pass

            for g in child.findall("group"):
                # create "group" here
                group     = ET.SubElement(user,"group")
                if g.text != "lion":
                    group.text = g.text
        tree = ET.ElementTree(root_new)
        tree.write(output)

def main():
    my_parser = MyXmlParser("users.xml")
    my_parser.do_something()

if __name__ == '__main__':
    main()

rawDescription: how add python class to a xml parsing program

description: How add python class to a xml parsing program


code:
import numpy as np

# prepare test data
A = np.random.normal(size=(10,10))
A = np.dot(A,A.T)
L = np.tril(A)

# actual in-place cholesky
assert L.dtype is np.dtype(np.float64)
assert L.flags['C_CONTIGUOUS']
n, m = L.shape
assert n == m
result = np.linalg.lapack_lite.dpotrf('U', n, L, n, 0)
assert result['info'] is 0

# check if L is the desired L cholesky factor
assert np.allclose(np.dot(L,L.T), A)
assert np.allclose(L, np.linalg.cholesky(A))

rawDescription: How to do in place Cholesky factorization in Python

description: Do in place Cholesky factorization in Python


code:
needed_keys = {key1, key2}

for d in data:
    if needed_keys.intersection(d):
        valid_data.append(d)

rawDescription: Check if at least one key of dict is contained in another dict


code:
while True:
    N = input("Please input factorial you would like to calculate: ")
    try: # try to ...
        N = int(N) # convert it to an integer.
    except ValueError: # If that didn't succeed...
        print("Invalid input: not an integer.")
        continue # retry by restarting the while loop.
    if N > 0: # valid input
        break # then leave the while loop.
    # If we are here, we are about to re-enter the while loop.
    print("Invalid input: not positive.")

rawDescription: Factorial calculation using Python

description: Factorial calculation using Python


code:
import subprocess
import threading
import random

def killer_func(event):
    possible_cmds = [['echo', 'hello'],
                     ['echo', 'world'],
                     ['/home/cycdev/killer.py']
                     ]
    random.shuffle(possible_cmds)
    for cmd in possible_cmds:
        subprocess.check_call(cmd)
        event.wait(4)
        if event.is_set():
            print("Main thread got a signal. Time to clean up")
            # save state here.
            return

event = threading.Event()
killer_thread = threading.Thread(target=killer_func, args=(event,))
killer_thread.start()
try:
    killer_thread.join()
except KeyboardInterrupt:
    print("Caught the kill -2 in the main thread :)")
    event.set()
    killer_thread.join()

print("Main program shutting down")

rawDescription: Catch KeyboardInterrupt or handle signal in thread


rawDescription: Splitting several days long dataframe into half-hourly dataframes using pandas and save them as csv-files


code:
spawnedBash = pexpect.spawn('bash')
print(spawnedBash.pid)

rawDescription: is there any way to know the pid of spawned process using pexpect

description: Is there any way to know the pid of spawned process using pexpect


code:
from kivy.event import EventDispatcher

class DataModel(EventDispatcher):
    a = StringProperty('')
    b = StringProperty('')
    c = StringProperty('')

    def __init__(self, *args, **kwargs):
        super(DataModel, self).__init__(*args, **kwargs)
        self.a = 'This is a'
        self.b ='This is b'
        self.bind(a=self.set_c)
        self.bind(b=self.set_c)

    def set_c(self, instance, value):
        self.c = self.a + ' and ' + self.b

rawDescription: Kivy ObjectProperty to update label text


code: iid = e.Item.Cells[2].Text

rawDescription: Tablecellcollection is not callable

description: Tablecellcollection is not callable


code:
p = subprocess.Popen(command, shell=True,
                     stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output = p.communicate()[0]

rawDescription: Why does calling ffmpeg from python block?


code:
pnt = Point(address.longitude, address.latitude)
district = District.objects.filter(mpoly__intersects=pnt).annotate(emps=Count('employees')).only('name').first()
if district:
    if district.emps:
        return True
    return False, district.name
else:
    return False

rawDescription: Simplifying a django ORM query

description: Simplifying a django ORM query


code:
from selenium import webdriver

browser = webdriver.Chrome() # Get local session of Chrome
browser.get("http://www.somepage.com") # Load page

elem = browser.find_element_by_id("show_links") # Find javascript button
elem.click() # Click on the button that 'populates the div'

rawDescription: Javascript with Selenium

description: Javascript with Selenium


code:
tree = ElementTree(fromstring(xml))
tree.findall('./{http://www.xyz.com}Message'
             '/{http://www.xyz.com}Body'
             '/{http://uri.xyz.com/Chorus/Message}CHMasterbook'
             '/{http://uri.xyz.com/Chorus/Message}event')

rawDescription: Python 2.5 ElementTree handle xml node with namespace


code:
cmd = """sort -n -r -k5 %s |
      head -n 500|
      awk 'OFS="\t"{{if($2-{1}>0){{print $1,$2-{1},$3+{1},$4,$5}}}}'""".format(summit, top_count)

subprocess.check_call(cmd, shell=True, stdout=file)

rawDescription: Why not just use `shell=True` in subprocess.Popen in Python?


code:
import redis

POOL = redis.ConnectionPool(host='10.0.0.1', port=6379, db=0)

def getVariable(variable_name):
    my_server = redis.Redis(connection_pool=POOL)
    response = my_server.get(variable_name)
    return response

def setVariable(variable_name, variable_value):
    my_server = redis.Redis(connection_pool=POOL)
    my_server.set(variable_name, variable_value)

rawDescription: Managing connection to redis from Python


code:
from itertools import takewhile,izip

x = [[3,2,1], [3,2,1,4,5], [3,2,1,8,9], [3,2,1,5,7,8,9]]

def allsame(x):
    return len(set(x)) == 1

r = [i[0] for i in takewhile(allsame ,izip(*x))]

rawDescription: What is the Pythonic way to find the longest common prefix of a list of lists?


code:
import json

try:
    with open('players.json', 'r') as file:
        accounts = json.load(file)
except (OSError, ValueError):  # file does not exist or is empty/invalid
    accounts = {}

# do something with accounts

with open('players.json', 'w') as file:
    json.dump(accounts, file, indent=2)

rawDescription: Write dict to file with each key/value pair on a separate line


code:
df1 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3))
df2 = pd.DataFrame(np.random.randn(3,2),columns=list('AB'),index=pd.date_range('20000101',periods=3))
df1
df2
pd.concat(dict(df1 = df1, df2 = df2),axis=1)

rawDescription: python/pandas: how to combine two dataframes into one with hierarchical column index?

description: Python/pandas: how to combine two dataframes into one with hierarchical column index


code:
#! /usr/bin/python3.2

import itertools

def queens ():
    for p in itertools.permutations (range (8) ):
        yield [x for x in enumerate (p) ]

for q in queens ():
    err = False
    for a, b in ( (a, b) for a in q for b in q if a [0] < b [0] ):
        if abs (a [0] - b [0] ) == abs (a [1] - b [1] ):
            err = True
            break
    if not err: print (q)

rawDescription: Putting 8 Queen in a Chess (without treating each other) ! [I Want All the possible result!]


code: sorted_list = sorted(my_dict, key=lambda k: (my_dict[k], k))

rawDescription: how does sorted(dict, dict.get) work for duplicate values

description: How does sorted(dict, dict.get) work for duplicate values


code:
from StringIO import StringIO
import struct

class BinaryIO(StringIO):
    def writepack(self, fmt, *values):
        self.write(struct.pack('<' + fmt, *values))

def to_binary_example():
    data = BinaryIO()
    data.writepack('I', 42)
    data.writepack('II', 1, 2)
    return data.getvalue()

rawDescription: More Pythonic conversion to binary?

description: More Pythonic conversion to binary


code:
Example
print('{1:>{0}}: {2}'.format(line_number_max_digits, lineno + i, chunk))

rawDescription: How to parametrize string.format() format specification?

description: Parametrize string.format() format specification


code:
re.search(r'id\=\d+', fieldname).group(0)      # return 'id=0123456'
re.search(r'(?<=id\=)\d+', fieldname).group(0) # return '0123456'

rawDescription: regex pattern replacement in python/jinja

description: Regex pattern replacement in python/jinja


code:
class Foo(object):
    def __init__(self, a, b):
            self.a = a
            self.b = b
    def __repr__(self):
            return 'Foo(a=%s)' % self.a
f = Foo(a=1, b=2)
vars(f)
pprint.pprint(f)
vars(f) is f.__dict__

rawDescription: Python pprint issues

description: Python pprint issues


code:
from urllib2 import Request, urlopen

req = Request('https://bugzilla.mozilla.org/index.cgi')
req.add_header('Accept', 'application/x-ms-application, image/jpeg, application/xaml+xml, image/gif, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, */*')
req.add_header('User-Agent', "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)")
response = urlopen(req) #NOTE: it doesn't check server's ssl certificate
print(response.headers)
content = response.read()

rawDescription: python httplib.HTTPSConnection not connected properly (to bugzilla.mozilla.org)?

description: Python httplib.HTTPSConnection not connected properly (to bugzilla.mozilla.org)


code: d = Dog(**make_dog())

rawDescription: Creating objects based on user input

description: Creating objects based on user input


code:
import types
SHIFT = 10. # Data coordinates
for label in ax2.xaxis.get_majorticklabels():
    label.customShiftValue = SHIFT
    label.set_x = types.MethodType( lambda self, x: matplotlib.text.Text.set_x(self, x-self.customShiftValue ),
                                    label, matplotlib.text.Text )

rawDescription: How to move a tick's label in matplotlib?

description: Move a tick's label in matplotlib


rawDescription: Divide RGB image by grayscale elementwise in numpy


rawDescription: Unmasking last printed expression variable


code:
class ThingRelationAdmin(admin.ModelAdmin):
    list_display = ('related_thing1', 'related_thing1_name',
                    'related_thing2', 'related_thing2_name')

    def queryset(self, request):
        qs = super(ThingRelationAdmin, self).queryset(request)
        # change appname to your application name in which this models placed
        qs = qs.extra(
            select = {
                'rt1name': 't1.name',
                'rt2name': 't2.name'
            },
            tables=['"appname_thing" as "t1"', '"appname_thing" as "t2"'],
            where=['appname_thingrelation.related_thing1=t1.id',
                   'appname_thingrelation.related_thing2=t2.id']
        )
        return qs

    def related_thing1_name(self, obj):
        return obj.rt1name

    def related_thing2_name(self, obj):
        return obj.rt2name

    related_thing1_name.admin_order_field = 'rt1name'
    related_thing2_name.admin_order_field = 'rt2name'

rawDescription: How to join two models by id (without ForeignKey) and sort by linked model fields in admin

description: Join two models by id (without ForeignKey) and sort by linked model fields in admin


rawDescription: python 3 ftp dir into a list

description: Python 3 ftp dir into a list


code:
def isPrime (n):
    if n < 2:
        return False
    for x in range (2, n):
        if n % x == 0:
            return False
    return True

rawDescription: python check prime, stuck at one point

description: Python check prime, stuck at one point


code:
def palindrome(listnum):
    for j in range(0, len(listnum)):
        t = len(listnum) - j - 1
        if listnum[j] != listnum[t]:
            return False

    return True

assert palindrome([9,0,6,6,0,9])
assert palindrome("ABBA")
assert palindrome([])
assert palindrome("1")
assert palindrome([1.0, 2, 1])
assert not palindrome("lolz")
assert not palindrome([1,2,3])

rawDescription: Python: Checking for palindrome returns False for some reason


code:
wc4 = tf.reshape(_weights['out'], [1, 1, d1, out])
conv4 = conv2d_valid(conv3, wc4, _biases['out'])

rawDescription: How to convert trained convolutional network (CNN) to use as a detector?

description: Convert trained convolutional network (CNN) to use as a detector


code:
import re
from collections import OrderedDict

with open(r'file') as f:
    h = OrderedDict()
    l = []
    for line in f:
        d = {}
        f = line.split()
        for i in f:
            if i.isdigit() and len(i) == 4:
                d['number'] = i
            else:
                d['text'] = i
        l.append(d)

    print(l)

rawDescription: Retrieve multiple capture group in different order?


code:
from random import random

def randint(minno, maxno, nooftime):
    a = sum([random() * (maxno-minno) + minno for _ in range(nooftime)])
    return a // nooftime

rawDescription: how to call a function a specific no. of times in python

description: Call a function a specific no. of times in python


code: test.strftime("%B")[:4] + str(test.day)

rawDescription: Convert numerical based date to alphabetical based in Python


code: re.sub("#(..)", lambda match: chr(int(match.group(1), 16)), s)

rawDescription: hex and string in python

description: Hex and string in python


code:
def get_private_key(filepath, password):
    pkey = chilkat.CkPrivateKey()
    pkey.LoadPkcs8EncryptedFile(filepath, password)
    return pkey.getPkcs8Pem()

def get_certificate_and_serial(filepath):
    cert = chilkat.CkCert()
    cert.LoadFromFile(filepath)
    serial = unhexlify(cert.serialNumber())
    return cert.exportCertPem(), serial.decode('utf-8')

rawDescription: openssl commands equivalent in python?

description: Openssl commands equivalent in python


code:
app_label = obj._meta.app_label
model = obj._meta.module_name

reverse('admin:%s_%s_change' % (app_label, model), args=(obj.id,))

rawDescription: Lookup admin change url for arbitrary Django model


code:
s = Series([list('ABC'),list('DEF'),list('ABEF')])
s
s.apply(lambda x: Series(1,index=x)).fillna(0)

rawDescription: Pandas: reshaping data

description: Pandas: reshaping data


code: process_group(group_list)  # process the last group

rawDescription: How to read a line a few lines down while looping in Python?

description: Read a line a few lines down while looping in Python


code: os.system('vap -c "mjd" {0} >> mjd.txt'.format(new_y[i]))

rawDescription: Writing into a file without overwriting

description: Writing into a file without overwriting


code:
from numpy import mod, floor
withinTolAbove=[int(mod(number, myNumber) <= myTolerance and
                mod(floor(number / myNumber), 2) == 0) for number in myList]
withinTolBelow=[int(mod(number + myTolerance, myNumber) <= myTolerance and
                mod(floor((number + myTolerance) / myNumber), 2) == 0) for number in myList]
myResult=[max(i1, i2) * int(number > myTolerance) for i1, i2, number in zip(withinTolAbove, withinTolBelow, myList)]

rawDescription: Find even multiples of a number in a list using Python


code:
import re
s = "The quick    brown\nfox"
for m in re.finditer('\S+', s):
    print(m.span(), m.group(0))

rawDescription: Splitting a string into an iterator

description: Splitting a string into an iterator


rawDescription: Python Pandas: String Method to str

description: Python Pandas: String Method to str


code: a = numpy.memmap("data", dtype="S10")

rawDescription: numpy.memmap for an array of strings?

description: Numpy.memmap for an array of strings


code:
signal_power = 100
noise_power = 17

rawDescription: Python's math module & "Think Python"

description: Python's math module & "Think Python"


code:
# --- get your data into a DataFrame so I can play with it ...
#     first, put the data in a multi-line string (I would read it from a file
#     if I had it in a file - but for my purposes a string will do).
data = """
time name
20150426010203 name1
20150426010303 name2
20150426010307 name3
20150426010409 name1
20150426010503 name4
20150426010510 name1"""
#    second I will use StringIO and pandas.read_csv to pretend I am
#    reading it from a file.
from StringIO import StringIO # import from io in Python 3
df = pd.read_csv(StringIO(data), header=0, index_col=0, sep='\s+')
#    third, because pandas did not recognise the date-time format
#    of the column I made the index, I will force the string to be
#    converted to a pandas Timestamp come DatetimeIndex.
df.index = pd.to_datetime(df.index, format='%Y%m%d%H%M%S')

# number of events per minute
df['event'] = 1 # we will sum this to get events per time-period
dfepm = df.resample('1min', how=sum)

# number of events per hour
dfeph = df.resample('1h', how=sum)

# time differences by name
del df['event'] # we don't need this anymore
df['time'] = df.index
df['time_diff_by_name'] = df.groupby('name')['time'].diff()

rawDescription: Working with datetime in Python

description: Working with datetime in Python


code:
class Inner(EmbeddedDocument):
  name = StringField()

class Outer(Document):
  outer_data = StringField()
  embed = MapField(EmbeddedDocumentField(Inner))

rawDescription: MongoEngine: storing EmbeddedDocument in DictField


code:
import re

def reducePrice(price):
    match = re.search(r'\d+', u'  $500  ')
    price = match.group()  # returns u"500"
    price = str(price) # convert "500" in unicode to single-byte characters.
    return price

rawDescription: Python: Transform a unicode variable into a string variable


code:
fake_server.py
import os
import SimpleHTTPServer

class SuffixHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    """
    Overrides the default request handler to assume a suffixless resource is
    actually an html page of the same name. Thus, http://localhost:8000/foo
    would find foo.html.

    Inspired by:
    https://github.com/clokep/clokep.github.io/blob/source/fake_server.py
    """
    def do_GET(self):
        path = self.translate_path(self.path)

        # If the path doesn't exist, assume it's a resource suffixed '.html'.
        if not os.path.exists(path):
            self.path = self.path + '.html'

        # Call the superclass methods to actually serve the page.
        SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)

SimpleHTTPServer.test(SuffixHandler)

rawDescription: Configuring SimpleHTTPServer to assume '.html' for suffixless URLs


code:
class NamedFunction:
    def __init__(self, name, f):
        self.f = f
        self.name = name

    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

    def __str__(self):
        return self.name

f = NamedFunction("lambda: 'blah'", lambda: 'blah')
print(f())
print(f)

rawDescription: How to replace __str__ for a function

description: Replace __str__ for a function


code:
def index(request):
    userid = None
    if request.user.is_authenticated():
        userid = request.user.id
    queryset = UserFile.objects.filter(userid=userid).values_list('fileid', 'grant_date', 'revoke_date')
    return JSONResponse(queryset)

rawDescription: django - running query filter by user

description: Django - running query filter by user


code:
def updateHost(host_id, new_hostgroup_id):
    url = "https://foreman.mydomain.com:443/api/hosts/" + host_id
    payload = {'host[hostgroup_id]': new_hostgroup_id}
    headers = {'Accept': 'application/json'}
    r = requests.put(url, data=payload, headers=headers, verify=False, uth=HTTPKerberosAuth())
    if (r.status_code != requests.codes.ok):
        raise BadStatusCodeRequest("HTTP Request status code error: " + r.raise_for_status())

rawDescription: Python script to update host using Foreman's API


code:
import os, time, sys

pr, pw = os.pipe()
pid = os.fork()

if pid == 0:
    os.close(pw)
    os.dup2(pr, sys.stdin.fileno())
    os.close(pr)
    os.execv('/usr/bin/tee', ['tee', 'log.txt'])
else:
    os.close(pr)
    os.dup2(pw, sys.stdout.fileno())
    os.close(pw)

    pid2 = os.fork()

    if pid2 == 0:
        # Replace with your custom process call
        os.execv('/usr/bin/yes', ['yes'])
    else:
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            pass

rawDescription: Python `tee` stdout of child process

description: Python `tee` stdout of child process


rawDescription: how to parse multi-line in a clean way using python?

description: Parse multi-line in a clean way using python


code:
f1 = open ("inFile","r") # open input file for reading

with open('out.csv', 'wb') as f: # output csv file
    writer = csv.writer(f)
    with open('in.csv','r') as csvfile: # input csv file
        reader = csv.reader(csvfile, delimiter=',')
        for row in reader:
            row[7] = f1.readline() # edit the 8th column
            writer.writerow(row)
f1.close()

rawDescription: Use Python to write on specific columns in csv file


code:
tbl = table(ax, df2, loc='center', cellLoc='center',
            cellColours=colors.as_matrix(),
            colColours=['black']*len(colors.columns),
            rowColours=['black']*len(colors))

# set white text for the index
[tbl._cells[row, -1]._text.set_color('white') for row in range(1, len(colors)+1)]

# set white text for headers
[tbl._cells[0, col]._text.set_color('white') for col in range(len(colors.columns))]

rawDescription: Python Pandas Align text in cells

description: Python Pandas Align text in cells


code: cursor.execute("update characters set characterName = ?, characterID = ?, corporationName =?, corporationID = ?, allianceID = ?, allianceName = ?, factionID = ?, factionName =? where keyID = ? and vCode = ?;", (character.name, character.characterID, character.corporationName, character.corporationID, character.allianceID, character.allianceName, character.factionID, character.factionName, row.keyID, row.vCode))

rawDescription: update python last record only

description: Update python last record only


code:
mydict = {'a':1,'b':3,'c':2}
sorted(mydict, key=lambda key: mydict[key])

rawDescription: Sorting dictionary keys in python

description: Sorting dictionary keys in python


code:
import random
if random.random() > 0.6:
  x = 2
else:
  x = 1

rawDescription: Set variable to different value based on probability


code:
for i in range(645):
    id = 'listContainer_row:' + str(i)

rawDescription: Iterating over a string by only changing one element in the string


rawDescription: Is this the right way to get a randomized rounding solution?


code:
options={
    'py2exe':{'includes':['yourextensionname_without_pyd']}
}

rawDescription: Including a pyd directly in a setup.py file


code:
class MySession(object):
    def __init__(self, session):
        session['my-data'] = {}
        super(MySession, self).__setattr__("_session", session) # avoid our __setattr__

    def __getattr__(self, name):
        return self._session['my-data'][name] # this doesn't recurse if _session exists

    def __setattr__(self, name, value):
        my_data = self._session['my-data']
        my_data[name] = value
        self._session['my-data'] = my_data

rawDescription: Normal attributes in a class implementing getattr / setattr


code:
def quiz_average(quiz1, quiz2, quiz3):
    average = (quiz1 + quiz2 + quiz3) / 3
    return average

quiz1 = int(input("Enter Quiz 1 score: "))
quiz2 = int(input("Enter Quiz 2 score: "))
quiz3 = int(input("Enter Quiz 3 score: "))

print(quiz_average(quiz1, quiz2, quiz3))  #Yes, variables can match the parameters

rawDescription: Python- Function that returns a value

description: Python- Function that returns a value


code: self.keyPress = QKeyEvent(QEvent.KeyPress, Qt.Key_A, Qt.NoModifier, "A")

rawDescription: QLineEdit not updating text with QKeyEvent


code:
class stru:
    def __init__(self):
        self.a = 0
        self.b = 0

s = stru()
s.a = 10

func_a(s)

rawDescription: python: how to define a structure like in C

description: Python: how to define a structure like in C


code:
if self.pre_app.url_map.bind_to_environ(environ).test(environ['PATH_INFO']):
    return self.pre_app(environ, start_response)

return self.main_app(environ, start_response)

rawDescription: Detecting whether a Flask app handles a URL


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

t = np.linspace(0, 2*np.pi, 150)
plt.figure()
theGrid = np.outer(np.sin(t), np.sin(t))
plt.xlim(0, 2*np.pi) #forces an exact fit!
plt.ylim(0, 2*np.pi) #ditto!
plt.xticks(np.linspace(0, 2*np.pi, 5),['0','$\pi/2$','$\pi$','$3\pi/2$','$2\pi$'])
plt.yticks(np.linspace(0, 2*np.pi, 5),['0','$\pi/2$','$\pi$','$3\pi/2$','$2\pi$'])
plt.pcolormesh(t, t, theGrid)

rawDescription: custom labels pyplot matplotlib

description: Custom labels pyplot matplotlib


code:
testcases = int(input().strip())
stuff = [[int(x) for x in input().strip().split()] for case in range(testcases)]

rawDescription: Is there a way to pass a command line argument when running a cell in Jupyter Notebook?


code:
x = [13, 3, 9, 41]
for i in x[:]:
    x.remove(i)
print(x)

rawDescription: Why does python remove behave like that?

description: Why does python remove behave like that


code:
def wordFrequencies(words):
    count = []
    for item, val in words.items():
        c = 0
        for i in val:
            c+=int(i.count)
        wc = createWordCount(str(item), c)
        count.append(wc)
    newcount = count
    newcount.sort(key = lambda x: x.count,reverse=True)
    print(newcount)

rawDescription: Creating list of objects from a dictionary


code:
import urllib3
import certifi

http = urllib3.PoolManager(
    cert_reqs='CERT_REQUIRED', # Force certificate check.
    ca_certs=certifi.where(),  # Path to the Certifi bundle.
)

# You're ready to make verified HTTPS requests.
try:
    r = http.request('GET', 'https://example.com/')
except urllib3.exceptions.SSLError as e:
    # Handle incorrect certificate error.
    ...

rawDescription: Easily upgrade Requests's vendored version of urllib3?


code:
from django_filters.views import FilterView

@method_decorator(login_required, name='dispatch')
class BuyView(FilterView):
    filterset_class = CCFilter
    template_name = "buy.html"
    context_object_name = "ccs"

    def get_queryset(self):
        queryset = super(BuyView, self).get_queryset()
        queryset = CCFilter(self.request.GET, queryset)
        return queryset

    def get_context_data(self, **kwargs):
        context = super(BuyView, self).get_context_data(**kwargs)
        context['cart'] = Cart.objects.get(user=self.request.user)
        return context

rawDescription: Form isn't available in template with django_filters


code:
from itertools import product

vals = [0.85, 0.9, 0.95, 0.98]
perm_vals = list(product(vals, repeat=5))

rawDescription: Generate permutations of values in fixed intervals


code:
from operator import itemgetter

a=[10,5,6,8]
b=[1,3]
res = itemgetter(*b)(a)
# (5, 8)

rawDescription: List indexing in Python

description: List indexing in Python