code:
from re import findall
mystr = "Draft {Test_02_v002_Global_alp_%04d.png 1-12} {Test_02_v002_Global_col_%04d.png 1-12} Thumbs.db"
findall("{(.*?)}", mystr)

rawDescription: Extracting multiple segments from a string in Python


code: #!/usr/bin/env python3

rawDescription: Django - ./manage.py defaults to python 2.x


rawDescription: matplotlib plots one time only

description: Matplotlib plots one time only


code:
import savestate, pickle, __main__
pickle.dump(__main__, open('savestate.pickle', 'wb'), 2)

rawDescription: Restarting a Python Interpreter Quietly

description: Restarting a Python Interpreter Quietly


code:
from datetime import timedelta
td1 = timedelta(1)
td2 = timedelta(2)
td1.total_seconds() / td2.total_seconds() # should give me 0.5
td2 = timedelta(days=4, minutes=50)
td1.total_seconds() / td2.total_seconds()

rawDescription: Percentages in timedelta objects in Python?


code:
rules = (
    Rule(LinkExtractor(
        restrict_xpaths = [
            "//div[@class='pagination']//a[contains(., 'Next')]"
        ]),
    callback = 'parse_start_url',
    follow = True),
)

rawDescription: Need for help in this scrapy regular expression


code:
import Image
sizes = [(120,120), (720,720), (1600,1600)]
files = ['a.jpg','b.jpg','c.jpg']

for image in files:
    for size in sizes:
      Image.open(image).thumbnail(size).save("thumbnail_%s_%s" % (image, "_".join(size)))

rawDescription: What is the fastest way to generate image thumbnails in Python?


code:
with open('File.fasta') as fin, open('OnlyFastaseq.fasta', 'w') as fout:
    for line in fin:
        if line.startswith('>'):
            fout.write(line)
            fout.write(next(fin))

rawDescription: Pulling out only fasta sequences python

description: Pulling out only fasta sequences python


rawDescription: How to replace a string by given a relation of original and return string?

description: Replace a string by given a relation of original and return string


code:
import pylab as pl
from mayavi import mlab

def mlab_imshowColor(im, alpha=255, **kwargs):
    """
    Plot a color image with mayavi.mlab.imshow.
    im is a ndarray with dim (n, m, 3) and scale (0->255]
    alpha is a single number or a ndarray with dim (n*m) and scale (0->255]
    **kwargs is passed onto mayavi.mlab.imshow(..., **kwargs)
    """
    try:
        alpha[0]
    except:
        alpha = pl.ones(im.shape[0] * im.shape[1]) * alpha
    if len(alpha.shape) != 1:
        alpha = alpha.flatten()

    # The lut is a Nx4 array, with the columns representing RGBA
    # (red, green, blue, alpha) coded with integers going from 0 to 255,
    # we create it by stacking all the pixles (r,g,b,alpha) as rows.
    myLut = pl.c_[im.reshape(-1, 3), alpha]
    myLutLookupArray = pl.arange(im.shape[0] * im.shape[1]).reshape(im.shape[0], im.shape[1])

    #We can display an color image by using mlab.imshow, a lut color list and a lut lookup table.
    theImshow = mlab.imshow(myLutLookupArray, colormap='binary', **kwargs) #temporary colormap
    theImshow.module_manager.scalar_lut_manager.lut.table = myLut
    mlab.draw()

    return theImshow

def test_mlab_imshowColor():
    """
    Test if mlab_imshowColor displays correctly by plotting the wikipedia png example image
    """

    #load a png with a scale 0->1 and four color channels (an extra alpha channel for transparency).
    from urllib import urlopen
    url = 'http://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png'
    im = pl.imread(urlopen(url), format='png')
    im *= 255

    mlab_imshowColor(im[:, :, :3], im[:, :, -1])

    mlab.points3d([-200, 300, -200, 300],
                  [-200, 300, 200, -300],
                  [300, 300, 300, 300])
    mlab.show()

if __name__ == "__main__":
    test_mlab_imshowColor()

rawDescription: How to draw a color image in mayavi (imshow)

description: Draw a color image in mayavi (imshow)


code:
a={x for x in range(3)}
a
type(a)
a={x: x for x in range(3)}
a
type(a)

rawDescription: list comprehension vs set comprehension

description: List comprehension vs set comprehension


code:
import copy

for i in range(4):
    p["player"] = i
    players.append(copy.deepcopy(p))

rawDescription: Incrementing list values

description: Incrementing list values


code:
A = np.random.rand(5, 10)
idx = np.array([1, 3, 5])
m = np.zeros_like(A)
m[:,idx] = 1
Am = np.ma.masked_array(A, m)
Am

rawDescription: Mask specific columns of a numpy array

description: Mask specific columns of a numpy array


code: array[..., i] = something

rawDescription: indexing in numpy nd-array

description: Indexing in numpy nd-array


code: root.after(10*1000, root.quit)

rawDescription: Exit Tks mainloop in Python?

description: Exit Tks mainloop in Python


code:
rdd = sc.parallelize([(1,2,3,4), (4,5,6,7)])

# just replace my index with yours
newrdd = rdd.map(lambda x: x + (x[1] + x[2],))

newrdd.collect() # [(1,2,3,4,6), (4,5,6,7,12)]

rawDescription: Column operation on Spark RDDs in Python


code:
t = time.utcnow()
map(lambda x: x.update({'created_at': t}), objects)

rawDescription: Python: add a timestamp to each object in the list


rawDescription: Python: How can I take a list of lists, convert every element into strings, and return the list of lists?


code:
connections = self.request.user.connections.all()
posts = Post.objects.filter(user__in=connections)

rawDescription: List of objects based on user relationships


code:
data = stdout.read()

f = open('file.txt', 'w')
f.write(data)

f.close()
client.close()

rawDescription: Using Paramiko to ssh in and run a command then have the print out parsed


code:
stuff = "Big and small"
stuff.replace(" and ","/")

rawDescription: Replace part of a string in Python?

description: Replace part of a string in Python


code:
import os.path

HERE = os.path.dirname(os.path.abspath(__file__))

somefile = os.path.abspath(os.path.join(HERE, 'subfolder1_with_10_text_files_inside /somefile.txt'))

rawDescription: Python Change Directory Google App Engine


code:
import wx
import wx.richtext as rtc
class test(wx.Dialog):
    def __init__(self, *args, **kwds):
        wx.Dialog.__init__(self, *args, **kwds)
        self.V=rtc.RichTextCtrl(self, size=(400,90),style=rtc.RE_MULTILINE)
        self.V.ApplyAlignmentToSelection(rtc.TEXT_ALIGNMENT_CENTER)

if __name__ == '__main__':
    app = wx.App()
    dialog = test(None, -1)
    dialog.Show()
    app.MainLoop()

rawDescription: set text alignment of rich text ctrl

description: Set text alignment of rich text ctrl


rawDescription: How to update the window during a callback?

description: Update the window during a callback


rawDescription: ArgParse Python Module: Change default argument value for inherted argument


code: itertools.product("ABC", repeat=4)

rawDescription: Using itertools.permutation where r > n

description: Using itertools.permutation where r > n


code:
class Campaigns():

   # column definitions here

   sites = relationship("CampaignSiteList", lazy="joined")

   @property
   def site_ids(self):
       return [d.id for d in self.sites]

rawDescription: SQL Alchemy. has many relation that returns a particular column


rawDescription: Opening firefox with selenium

description: Opening firefox with selenium


code:
from django.db.models import Count

Device.objects.values('build').annotate(count=Count('pk'))
# -> [{'build': '1', 'count': 3}, {'build': '2', 'count': 4}]

rawDescription: Django Queryset Count

description: Django Queryset Count


code:
mychoice = random.choice(list(open('data_files/script_only_files/titles.csv')))
mytag = '
' + mychoice.replace("\n", "") + '
'

rawDescription: Python Get Random Choice From Text File Then Repeat That Choice


code:
from GoogleScraper import basic_usage

def view_fun(request):
    basic_usage()
    return Response

rawDescription: How to run external scripts from django?

description: Run external scripts from django


code:
for i,files_in_folder in enumerate(all_files_in_all_folders):
    # Incase files are too large for memory, we will read 1mb increments
    block_size = 2**20
    # Iterate through each folder to read each file
    for each_file in files_in_folder:
        # Hasher will get the hash value of each files in this folder
        hasher = hashlib.md5()
    # Now i'm opening every file to get it's hash value below
        with open(subfolder_paths[i][0]+"\\"+each_file, 'rb') as to_check_for_duplicates:
            # We send large files bits by bits to the hasher so we can read larger files
            while True:
                file_buffer = to_check_for_duplicates.read(block_size)
                # If we have reached the end of the file, we break out
                if not file_buffer:
                    break
                # Updating the hasher everytime we feed more bytes
                hasher.update(file_buffer)
        # Effectivley putting each hash hex value into a dictionary with the filepath and key
        the_hash_dictionary[subfolder_paths[i][0]+"\\"+each_file] = hasher.hexdigest()

rawDescription: Getting a hash value of a binary file with python by md5, trying to weed out duplicates


code:
proc = subprocess.Popen(['/bin/bash'], stdin=PIPE, stdout=PIPE)
proc.communicate("source path/to/some_file\n"
                 "./some_program\n")

rawDescription: Robustly identify which shell is running


code:
import sys
import signal

from optparse import OptionParser
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import QWebPage

url = "http://www.stackoverflow.com"

def page_to_file(page):
    with open("output", 'w') as f:
        f.write(page.mainFrame().toHtml())
        f.close()

app = QApplication()
page = QWebPage()
signal.signal( signal.SIGINT, signal.SIG_DFL )
page.connect(page, SIGNAL( 'loadFinished(bool)' ), page_to_file)
page.mainFrame().load(QUrl(url))
sys.exit( app.exec_() )

rawDescription: How to use python urlopen scraping after a page finish loading all searching result?

description: Use python urlopen scraping after a page finish loading all searching result


code:
from tkinter import *

class MyWindow(Frame):
    def __init__(self, parent, *pargs, **kwargs):
        Frame.__init__(self, parent, *pargs, **kwargs)

        self.label_text = StringVar()
        self.label_text.set("my label")

        self.label = Label(self, textvariable = self.label_text)
        self.label.pack()

        self.after(1000, self.ask_text)

    def ask_text(self):

        while True:
            new_text = input('Input text here: \n')
            if new_text == 'stop_program':
                self.master.quit()
                break;

            self.label_text.set(new_text)
            self.label.update()

    def change_text(self, new_text):
        self.label["text"] = new_text
        if new_text != 'stop_program':
            self.ask_text()

Gui = Tk()
Gui.geometry('450x450+200+200')
Gui.title = ('lol')

my_window = MyWindow(Gui)
my_window.pack()

mainloop()

rawDescription: How do I change change the text on a label to an input or raw_input from shell in python?

description: Change change the text on a label to an input or raw_input from shell in python


code:
# register the static folder for the application.  Do that even
# if the folder does not exist.  First of all it might be created
# while the server is running (usually happens during development)
# but also because google appengine stores static files somewhere
# else when mapped with the .yml file.
if self.has_static_folder:
    self.add_url_rule(self.static_url_path + '/<path:filename>',
                      endpoint='static',
                      view_func=self.send_static_file)

rawDescription: Why does url_for() works with 'static' as first parameter? There's no static()


rawDescription: Order of items and type convertions with pythons BIF zip() and unzip()


rawDescription: how to read response in python and calling def

description: Read response in python and calling def


rawDescription: Django HTML Page Table Sorting

description: Django HTML Page Table Sorting


rawDescription: re.sub on lists - python 3

description: Re.sub on lists - python 3


code:
class ResizedImageFieldFile(ImageField.attr_class):

    def save(self, name, content, save=True):
        new_content = StringIO()
        content.file.seek(0)
        thumb = Image.open(content.file)

        if thumb.size[0] > 900:
            thumb.thumbnail((
                self.field.max_width,
                self.field.max_height
                ), Image.ANTIALIAS)

            if self.field.use_thumbnail_aspect_ratio:
                img = Image.new("RGBA", (self.field.max_width, self.field.max_height), self.field.background_color)
                img.paste(thumb, ((self.field.max_width - thumb.size[0]) / 2, (self.field.max_height - thumb.size[1]) / 2))
            else:
                img = thumb

            try:
                img.save(new_content, format=thumb.format, **img.info)
            except IOError:
                ImageFile.MAXBLOCK = img.size[0] * img.size[1]
                img.save(new_content, format=thumb.format, **img.info)
        else:
            img = thumb
            try:
                img.save(new_content, format=thumb.format, **img.info)
            except IOError:
                ImageFile.MAXBLOCK = img.size[0] * img.size[1]
                img.save(new_content, format=thumb.format, **img.info)

        new_content = ContentFile(new_content.getvalue())

        super(ResizedImageFieldFile, self).save(name, new_content, save)

rawDescription: How to resize image if max_width exceeds x with PIL?

description: Resize image if max_width exceeds x with PIL


rawDescription: numpy replace negative values in array

description: Numpy replace negative values in array


code:
from django import forms
#from .models import User
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(widget=forms.TextInput(attrs={'placeholder': 'Email'}),required = True)
    first_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'First Name'}),required = False)
    last_name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Last Name'}),required = False)
    username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'User Name'}),required = True)
    password1 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'}),required = True)
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'}),required = True)
    class Meta:
        model = User
        fields = ['first_name','last_name','email','username', 'password1', 'password2',]

    def save(self,commit = True):
        user = super(RegistrationForm, self).save(commit = False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        if commit:
            user.save()

        return user

rawDescription: Django Placeholders

description: Django Placeholders


code:
query = "SELECT * from tablename where MemberID="
while True:
    loginID=input("Please enter your member ID: ")
    tmp_query=query+loginID
    cursor.execute(tmp_query)
    if cursor.rowcount==1:
        ## Do your thing here
        break
conn.close()

rawDescription: mysql python: check whether an input exists in database

description: Mysql python: check whether an input exists in database


code:
flag = True
for obj in objects:
    if obj == 3:
        found_obj = obj
        print("found the required object ",found_obj)
        flag= False
        break  # no need to continue search

rawDescription: Python scopes in For -Else

description: Python scopes in For -Else


code:
df["y"], df["z"] = my_func(df.x)
df

rawDescription: Using DataFrame.apply with a lambda function to assign returned tuple/list to multiple columns


code:
with open('map.txt', 'rb') as f:
    mapping = {word: index for index, word in enumerate(f.read().split())}
word_list = sorted(word_list, key=lambda word: mapping[word[0]])

rawDescription: Python: Custom sort a list of lists

description: Python: Custom sort a list of lists


code:
shutup = open("/dev/null","w")
subprocess.call(["fbi", "-noverbose", "-a", "-T", "2", "/home/pi/photoframe/photos/"+current_image],
                stdout=shutup,
                stderr=shutup)

rawDescription: Prevent subprocess.call() from displaying text


code:
arrs = list()
for i in xrange(5):
    arrs.append(np.arange(i * i, dtype=int))
code = r"""
    long arrs_size = PyList_Size(arrs);
    for (long i=0; i<arrs_size; i++) {
        PyArrayObject* arr_array = convert_to_numpy(PyList_GetItem(arrs,i), "arr");
        conversion_numpy_check_type(arr_array,PyArray_LONG, "arr");
        npy_intp* Narr = arr_array->dimensions;
        npy_intp* Sarr = arr_array->strides;
        int Darr = arr_array->nd;
        long* arr = (long*) arr_array->data;
        long arr_size = 1;
        for (int n=0; n<Darr; n++) arr_size *= Narr[n];
        for (int j=0; j<arr_size; j++) printf("%ld ", arr[j]);
        printf("\n");
    }
"""
inline(code, ['arrs'])

rawDescription: Iterate over array of arrays with scipy.weave.inline


code:
for child in layer2_element.childNodes:
    if child.tagName == 'element':
        ...  # do something with `child`

rawDescription: Minidom (XML Parsing) with Python - dont want geting any childs child nodes


code:
d
d.A
d.diagonal()

rawDescription: Convert a Diagonal Sparse Matrix in a 1-D vector


code:
next2=input("How many would you like to add? ")
print("")
count = 0
inputs = []
while count < int(next2):
    count = count + 1
    next3=input(str(count) + ". Input: ")
    inputs += [next3]
print("")
check=input("Are you sure? (Y/N) ")
while check not in ("YyYesNnNo"):
    check=input("Are you sure? (Y/N) ")
if check in ("YyYes"):
    for userInput in inputs:
        add(userInput)
else:
    home()

rawDescription: Python Validation with While Loops

description: Python Validation with While Loops


code:
x=linspace(-4,4)
y=linspace(-4,4)
g=meshgrid(x,y)
z=g[0]**2+5*g[1]
ctf=plt.contourf(x, y, z)
cb=plt.colorbar(ctf, shrink=0.5)
cb.ax.text(0.5, 0, 'text', va='top', ha='center')

rawDescription: Align matplotlib Text with colorbar

description: Align matplotlib Text with colorbar


code:
s_min = np.min(surface)
s_max = np.max(surface)

# filter out extra ticks that exceed data limits
ax.set_zticks(filter(lambda x: s_min <= x <= s_max, ax.get_zticks()))

rawDescription: mplot3d: contourf offset, limits and ticks

description: Mplot3d: contourf offset, limits and ticks


code:
from subprocess import call
call(["./idal", "-B", "input-File"])

rawDescription: Calling IDA Pro through python

description: Calling IDA Pro through python


code:
import sys
logfile = open("logfile.txt", "w")
logfile.write(" ".join(sys.argv))
logfile.close()

rawDescription: python: Store the issued commands in log file

description: Python: Store the issued commands in log file


code:
from urllib2 import urlopen

for row in table_1.find_all('tr'):
    tds  = row.find_all('td')
    # Get all the hrefs to make http request
    links = row.find_all('a').get('href')
    try:
        data = [td.get_text() for td in tds]
        for field,value in zip(columns, data):
            print("{}: {}".format(field, value))
        # For every href make a request, get the page,
        # create a BS object
        for link in links:
            link_soup = BeautifulSoup(urlopen(link))

            # Use link_soup BS instance to get the email
            # by navigating the div and p and add it to your data

        table.append(data)
    except:
        print("Bad string value")

rawDescription: Scraping and navigating to links to get more info


code:
import sys
from PyQt5 import QtCore, QtWidgets

def qt_message_handler(mode, context, message):
    if mode == QtCore.QtInfoMsg:
        mode = 'INFO'
    elif mode == QtCore.QtWarningMsg:
        mode = 'WARNING'
    elif mode == QtCore.QtCriticalMsg:
        mode = 'CRITICAL'
    elif mode == QtCore.QtFatalMsg:
        mode = 'FATAL'
    else:
        mode = 'DEBUG'
    print('qt_message_handler: line: %d, func: %s(), file: %s' % (
          context.line, context.function, context.file))
    print('  %s: %s\n' % (mode, message))

QtCore.qInstallMessageHandler(qt_message_handler)

app = QtWidgets.QApplication(sys.argv)

def main():
    QtCore.qDebug('something informative')
    win = QtWidgets.QMainWindow()
    # trigger a Qt debug message
    win.setLayout(QtWidgets.QVBoxLayout())

main()

rawDescription: Redirect qDebug output to file with PyQt5


code:
new_child_entity = ObjectChildEntity(myobject_id=123, some_data='foo', related_stuff_id=456)
new_child_entity.save()

rawDescription: Construct new django model object without loading all related models into memory


code:
class MySpider(BaseSpider):
    ...

    def parse(self, response):
         jsonresponse = json.loads(response)

         item = MyItem()
         item["firstName"] = jsonresponse["firstName"]

         return item

rawDescription: scraping a json response in scrapy

description: Scraping a json response in scrapy


rawDescription: How to Set Multiple Fields in Django Db Record

description: Set Multiple Fields in Django Db Record


rawDescription: numpy array averaging with mask

description: Numpy array averaging with mask


code:
from Tkinter import *

class Window():

    def __init__(self, master):

        self.master = master
        self.v1 = IntVar()
        self.v2 = IntVar()
        self.v3 = IntVar()
        self.v4 = IntVar()
        self.v5 = IntVar()

        Label(master, text="""Which Method do you want to run?""",justify = LEFT, padx = 20).pack()
        Radiobutton(master, text="Positive",padx = 20, variable=self.v1, value=1).pack(anchor=W)
        Radiobutton(master, text="Negative", padx = 20, variable=self.v1, value=2).pack(anchor=W)
        Radiobutton(master, text="Both", padx = 20, variable=self.v1, value=3).pack(anchor=W)

        Label(master, text="""Choose a tray type:""",justify = LEFT, padx = 20).pack()
        self.a1=Radiobutton(master, text="54",padx=20,variable=self.v2,value=1, command = self.disable).pack(anchor=W)
        self.a2=Radiobutton(master, text="96",padx = 20, variable=self.v2, value=2, command = self.disable).pack(anchor=W)

        Label(master, text="""Sort by columns(default) or rows?""",justify = LEFT, padx = 20).pack()
        self.b1=Radiobutton(master, text="columns",padx=20,variable=self.v3,value=1)
        self.b1.pack(anchor=W)
        self.b2=Radiobutton(master, text="rows",padx = 20, variable=self.v3, value=2)
        self.b2.pack(anchor=W)

        Label(master, text="""Choose a tray number:""",justify = LEFT, padx = 20).pack()
        self.c1=Radiobutton(master, text="Stk1-01",padx = 20, variable=self.v4, value=1).pack(anchor=W)
        self.c2=Radiobutton(master, text="Stk1-02", padx = 20, variable=self.v4, value=2).pack(anchor=W)
        self.c3=Radiobutton(master, text="Stk1-03",padx = 20, variable=self.v4, value=3).pack(anchor=W)
        self.c4=Radiobutton(master, text="Stk1-04", padx = 20, variable=self.v4, value=4).pack(anchor=W)
        self.c5=Radiobutton(master, text="MT1-Frnt",padx = 20, variable=self.v4, value=5).pack(anchor=W)

        self.c6=Radiobutton(master, text="MT1-Rear", padx = 20, variable=self.v4, value=6)
        self.c6.pack(anchor=W)
        self.c7=Radiobutton(master, text="MT2-Frnt",padx = 20, variable=self.v4, value=7)
        self.c7.pack(anchor=W)
        self.c8=Radiobutton(master, text="MT2-Rear", padx = 20, variable=self.v4, value=8)
        self.c8.pack(anchor=W)

        Label(master, text="""Would you like to insert a midpoint standard and blank?""",justify = LEFT, padx = 20).pack()
        Radiobutton(master, text="Yes",padx = 20, variable=self.v5, value=1).pack(anchor=W)
        Radiobutton(master, text="No", padx = 20, variable=self.v5, value=2).pack(anchor=W)

        Button(master, text="OK", command=self.ok).pack()

    def ok(self):
        self.master.destroy()

    def disable(self):

        if self.v2.get() == 1:
            self.b1.config(state = 'disabled')
            self.b2.config(state = 'disabled')
            self.c6.config(state = 'disabled')
            self.c7.config(state = 'disabled')
            self.c8.config(state = 'disabled')

        else:
            self.b1.config(state = 'normal')
            self.b2.config(state = 'normal')
            self.c6.config(state = 'normal')
            self.c7.config(state = 'normal')
            self.c8.config(state = 'normal')

master = Tk()
w = Window(master)
master.mainloop()

rawDescription: Python Tkinter Radiobutton narrowing user input


code:
conds = [r <= p1, r <= (p1 + p2), r > (p1 + p2)]
choices = [a1, a2, a3]
a = np.select(conds, choices)

rawDescription: Building one array out of several. Monte-Carlo method


code: s = stdscr.getstr(0,0, 15) #Input is limited to 15 characters, once the limit is hit, it stops accepting more

rawDescription: Limit raw_input length

description: Limit raw_input length


code:
import thread
import pygame
import easygui
from pykinect import nui
import os
import Tkinter as tk
import tkMessageBox
root = tk.Tk()
root.withdraw()

DEPTH_WINSIZE = (640, 480)

screen_lock = thread.allocate()
screen = None

tmp_s = pygame.Surface(DEPTH_WINSIZE, 0, 16)

s=None
global DIR
k = open("DIR.dir", "r")
DIR = k.read()
if (not os.path.exists("Patients\\" + DIR)):
    os.makedirs("Patients\\" + DIR)
k.close()
def video_frame_ready(frame):
    frame.image.copy_bits(screen._pixels_address)
    pygame.display.update()
    global s
    if (s == 4):
        R = open("Patients\\" + DIR + "\\" + "RED.clr", "w")
        G = open("Patients\\" + DIR + "\\" + "GREEN.clr", "w")
        B = open("Patients\\" + DIR + "\\" + "BLUE.clr", "w")
        for i in range(screen.get_height()):
            for i1 in range(screen.get_width()):
                R.write(str(screen.get_at((i1, i))[0]) + " ")
                G.write(str(screen.get_at((i1, i))[1]) + " ")
                B.write(str(screen.get_at((i1, i))[2]) + " ")
            R.write("\n")
            G.write("\n")
            B.write("\n")
        R.close()
        G.close()
        B.close()
def depth_frame_ready(frame):
    with screen_lock:
        global arr
        frame.image.copy_bits(tmp_s._pixels_address)
        arr.append(pygame.surfarray.pixels2d(tmp_s))
        arr2d = (pygame.surfarray.pixels2d(tmp_s) >> 7) & 255

        global s
        s=s+1
        if (s==5):
            click = 0
            coords = []
            while (True):
                action = pygame.mouse.get_pressed()
                if (action[0]):
                    if (click != 0):
                        if (coords[-1] == pygame.mouse.get_pos()):
                            break
                    coords.append([])
                    coords[click] = pygame.mouse.get_pos()
                    pygame.time.wait(300)
                    DEPTH_MULT = arr[3][coords[click][0]][coords[click][1]] / 8800.0
                    MULT_FINAL = 1 / DEPTH_MULT
                    screen.set_at((coords[click][0]-1, coords[click][1]-1), (255, 0, 0))
                    arr2d_N = (pygame.surfarray.pixels2d(tmp_s) >> 7) & 255
                    pygame.display.update()
                    click = click + 1
                    action = pygame.mouse.get_pressed()
            File = open("NM.dta", "w")
            File.write(str(click))
            File.close()
            tkMessageBox.showinfo("Finished", "Scanning Finished, Please Wait...")
            File = open("Patients\\" + DIR + "\\coords_MLT.crd", "w")
            FILE = open("Patients\\" + DIR + "\\coords_MLT_VIDEO.crd", "w")
            for i in range (len(coords)):
                for i1 in range (2):
                    DEPTH_MULT = arr[3][coords[i][0]][coords[i][1]] / 8800.0
                    MULT_FINAL = 1 / DEPTH_MULT
                    if (i1 == 0):
                        File.write(str(coords[i][i1] - int(19 * MULT_FINAL)) + " ")
                        FILE.write(str(coords[i][i1]) + " ")
                    else:
                        File.write(str(coords[i][i1] - int(22 * MULT_FINAL)) + " ")
                        FILE.write(str(coords[i][i1]) + " ")
                File.write("\n")
                FILE.write("\n")
            File.close()
            FILE.close()
            for k in range(len(arr)):
                test = open("Patients\\" + DIR + "\\out"+str(k)+".dpm", "w")
                for i in arr[k]:
                    for i1 in i:
                        test.write(str(i1) + " ")
                    test.write("\n")
                test.close()
            k = open("Finished.FNS", "w")
            k.write("FNS")
            k.close()
            os.startfile("Kinect_Matrix_generation_FINAL_VERSION.exe")
            pygame.time.wait(100)
            global G
            G = False
            os._exit(0)
            pygame.quit()

def main():
    pygame.init()
    global s
    s=0
    global arr
    arr = []

    global G
    G = True

    global screen
    screen = pygame.display.set_mode(DEPTH_WINSIZE, 0, 32)
    pygame.display.set_caption("Skelenct Scan")

    angle = 0
    with nui.Runtime() as kinect:
        kinect.depth_frame_ready += depth_frame_ready
        kinect.depth_stream.open(nui.ImageStreamType.Depth, 2, nui.ImageResolution.Resolution640x480, nui.ImageType.Depth)

        kinect.video_frame_ready += video_frame_ready
        kinect.video_stream.open(nui.ImageStreamType.Video, 2, nui.ImageResolution.Resolution640x480, nui.ImageType.Color)

        while (G):
            try:
                event = pygame.event.wait()

                if (event == pygame.QUIT):
                    break
            except :
                os._exit(0)
if (__name__ == "__main__"):
    import sys
    main()
    sys.exit(app.exec_())

rawDescription: CX_Freeze come up not responding with Pygame and Pykinect


code:
from base64 import b64encode, b64decode

mypw = "mypassword".encode()     # needs to be a binary-string
encrPW = b64encode(mypw)         # equals b'bXlwYXNzd29yZA=='
assert mypw == b64decode(encrPW) # decoding results in the password
strPW = mypw.decode()            # the python-string representation of the password
                                 # (most possibly the one you need later on)

rawDescription: encoding and decoding a string to binary or hex in python 3.5

description: Encoding and decoding a string to binary or hex in python 3.5


code:
words = [("ABC", "ALPHABET"),
         ("A", "APPLE")]

word_series = []

for word, replace in words:
    series = df["company"].str.contains(word)
    word_series.append((series, replace))

for series, replace in reversed(word_series):
    df.loc[series, "company"] = replace

rawDescription: Give priority when replacing strings

description: Give priority when replacing strings


code:
import numpy as np
W1 = np.arange(25*64).reshape(25, 64)
W2 = np.arange(25*64).reshape(64, 25)
b1 = np.arange(25)
b2 = np.arange(64)

theta = np.concatenate([W1.flat, W2.flat, b1, b2])
print(theta.shape)
# (3289,)

rawDescription: How to convert matrices to column vectors and append all together in python

description: Convert matrices to column vectors and append all together in python


code:
from django.db.models import Count
Order.objects.annotate(count = Count('orderitem__id')).filter(count = 1)

rawDescription: Distinct in many-to-many relation

description: Distinct in many-to-many relation


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

x = np.random.normal(0,1,1000)
y = np.random.normal(0,1,1000)

##### BUILDING A GRID FOR THE DATA ########
nodesx,nodesy = 100,100   # PIXELS IN X, PIXELS IN Y
firstx,firsty = x.min(),y.min()
sizex = (x.max()-x.min())/nodesx
sizey = (y.max()-y.min())/nodesy
grid = np.zeros((nodesx+1,nodesy+1),dtype='bool') # PLUS 1 TO ENSURE ALL DATA IS INSIDE GRID

# CALCULATING GRID COORDINATES OF DATA
indx = np.int_((x-firstx)/sizex)
indy = np.int_((y-firsty)/sizey)
grid[indx,indy] = True  # WHERE DATA EXISTS SET TRUE

# PLOT MY FINAL IMAGE
plt.imshow(grid.T,origin='lower',cmap='binary',interpolation='nearest')
plt.show()

rawDescription: Create a binary completeness map

description: Create a binary completeness map


code:
import Tkinter as tk

image_data = '''
    R0lGODlhEAAQAMQZAMPDw+zs7L+/v8HBwcDAwLW1teLi4t7e3uDg4MLCwuHh4e7u7t/f38TExLa2
    tre3t7i4uL6+vu/v77q6uu3t7b29vby8vLm5ubu7u+3t7QAAAAAAAAAAAAAAAAAAAAAAACH5BAEA
    ABkALAAAAAAQABAAAAWNYCaOZFlWV6pWZlZhTQwAyYSdcGRZGGYNE8vo1RgYCD2BIkK43DKXRsQg
    oUQiFAkCI3iILgCLIEvJBiyQiOML6GElVcsFUllD25N3FQN51L81b2ULARN+dhcDFggSAT0BEgcQ
    FgUicgQVDHwQEwc+DxMjcgITfQ8Pk6AlfBEVrjuqJhMOtA4FBRctuiUhADs=
'''

root = tk.Tk()
image = tk.PhotoImage(data=image_data)
dimensions = "image size: %dx%d" % (image.width(), image.height())
label = tk.Label(root, compound="top", image=image, text=dimensions)
label.pack()
root.mainloop()

rawDescription: How to find out size of a PhotoImage in Tkinter?

description: Find out size of a PhotoImage in Tkinter


code:
before_ten = Q(created_at__hour=0)
for hour in range(1, 11):
    before_ten = before_ten | Q(created_at__hour=hour)
query = query.filter(before_ten)

rawDescription: How do I query for objects created before a certain hour in a day in Django?

description: Query for objects created before a certain hour in a day in Django


code:
import numpy as np
old_set = [[0, 1], [4, 5]]
new_set = [[2, 7], [0, 1]]
(np.array(old_set) + np.array(new_set)) / 2

rawDescription: Average values in two Numpy arrays

description: Average values in two Numpy arrays


code:
os.chdir('/path/to/where/sqlfile/resides')
os.system('/usr/bin/tar -cvzf Backup_' + formt + '.tar.gz ' + 'sql_Backup_' + formt + '.sql')
os.system('/bin/rm ' + 'sql_Backup_' + formt + '.sql')

rawDescription: Tar not working from cronjob

description: Tar not working from cronjob


code:
import sys

def run_program():
    print('[*] Palidrome Checker') # move this into the loop if you want it to print before asking for input again after invalid input
    word = ''
    while True:
        word = raw_input('Enter your word: ')
        word = word.lower()

        if len(word) > 1: # quit the loop if we have a word
            break
        print('Please enter a word, not a character')

    def Palindrome(word):
        if len(word) < 2:
            return True
        if word[0] == word[-1]:
            return Palindrome(word[1:-1])
        return False

    print(Palindrome(word))

run_program()

rawDescription: Why do if statements and recursive act this way?


code:
lines= ['<title>The query complexity of estimating weighted averages.</title>', '<title>New bounds for the query complexity of an algorithm that learns DFAs with correction and equivalence queries.</title>', '<title>A general procedure to check conjunctive query containment.</title>']
words=['a','is','and','there','here']
[re.sub(r'</?title>|\b(?:'+'|'.join(words)+r')\b', r'', line) for line in lines]

rawDescription: Removing the specific words from a list

description: Removing the specific words from a list


code:
WORDLIST = "words.txt"

def loadWords():
    with open(WORDLIST, 'r') as inFile:
        wordTuple = tuple(word.lower() for word in inFile.read().split())
    return wordTuple

MYWORDS = loadWords()

rawDescription: Can tuples implement external data from .txt files?


code:
from django.contrib import admin
from .models import Article, Reporter

class ArticleInline(admin.TabularInline):
    model = Article

class ReporterAdmin(admin.ModelAdmin):
    inlines = [
        ArticleInline,
    ]

admin.site.register(Reporter, ReporterAdmin)

rawDescription: How to register models within some other model (which is connected via foreign key) in django-admin?

description: Register models within some other model (which is connected via foreign key) in django-admin


code:
import Tkinter as tk
import thread

def main():
    root = tk.Tk()
    progress_var = tk.StringVar(root)
    progress_var.set('')
    progress = tk.Label(root, textvariable = progress_var)
    progress.pack()
    def thread_helper(): # this can access the local variables in main()
        total = 10000000
        for i in xrange(1, total + 1):
             progress_var.set('Progress: {}%'.format(100 * float(i)/total))
    thread.start_new_thread(thread_helper, ())
    root.mainloop()

rawDescription: Need for nested functions in python

description: Need for nested functions in python


code:
shapes = {'1':Square, '2':Circle, '3':Triangle} # just the class names in the dict

x = shapes[raw_input()]() # get class from dict, then call it to create a shape instance.

rawDescription: Dictionary with classes?

description: Dictionary with classes


code: shlex.split(raw_args, posix=False)

rawDescription: Making shlex.split respect UNC paths

description: Making shlex.split respect UNC paths


code:
from collections import OrderedDict

init_list = [[('not', ('box', 'p')), ('diamond', 'p'), ('box', 'q'), ('diamond', 'q'), ('diamond', 'q')], [('not', 'p'), 'q'], ['p', 'q'], ['q', 'q'], [('not', 'r'), 'q']]

uniq_list = [list(OrderedDict.fromkeys(l)) for l in init_list]

rawDescription: Remove duplicates from the list

description: Remove duplicates from the list


code:
def monitor_log_setup():
    log_monitor = logging.getLogger('monitorlog')
    log_monitor.setLevel(logging.DEBUG)
    log_monitor.propagate = False
    handler = TimedRotatingFileHandler('somedirectory/monitor.log',
                                       when='h',
                                       interval=1,
                                       backupCount=30)
    monitor_format = logging.Formatter('%(asctime)s: %(message)s')
    handler.setFormatter(monitor_format)
    log_monitor.addHandler(handler)

    return log_monitor

rawDescription: Python: Where to put logging.getLogger

description: Python: Where to put logging.getLogger


code:
def purifystring(string_to_analyze):    # string is a really bad variable name as it is a python module's name
   return "".join(digit for digit in string_to_analyze if digit.isdigit())

rawDescription: filtering input from serial port data

description: Filtering input from serial port data


rawDescription: initialising a form with data using django on google appengine

description: Initialising a form with data using django on google appengine


code:
var1 = 257
var2 = 257
id(var1)
id(var2)
var1 = 10
var2 = 10
id(var1)
id(var2)

rawDescription: Is the `id()` of a variable associated to the value assigned to it after the variable lifetime finishes?


rawDescription: How would I implement a Python bit map?

description: How would I implement a Python bit map


code:
def countCarries(n1, n2):
    n1, n2 = str(n1), str(n2) # turn the numbers into strings
    carry, answer = 0, 0 # we have no carry terms so far, and we haven't carried anything yet
    for one,two in itertools.zip_longest(n1[::-1], n2[::-1], fillvalue='0'): # consider the corresponding digits in reverse order
            carry = int(((int(one)+int(two)+carry)//10)>0) # calculate whether we will carry again
            answer += ((int(one)+int(two)+carry)//10)>0 # increment the number of carry terms, if we will carry again
            carry += ((int(one)+int(two)+carry)//10)>0 # compute the new carry term
    return answer

countCarries(127, 123)
countCarries(127, 173)

rawDescription: Python 3.3.2 - Calculating the Carrying of Numbers


code:
import threading
import signal
import sys

def loop():
  while True:
    pass

def exit(signal, frame):
  sys.exit(0)

myThread = threading.Thread(target=loop)
myThread.daemon = True
myThread.start()

myThread2 = threading.Thread(target=loop)
myThread2.daemon = True
myThread2.start()

signal.signal(signal.SIGINT, exit)

loop()

rawDescription: Terminate GObject.Mainloop() threads together with main


rawDescription: Summing up n number matrix in python

description: Summing up n number matrix in python


code:
import json, pickle

with open("data.pickle", "rb") as fpick:
    with open("data.json", "w") as fjson:
        json.dump(pickle.load(fpick), fjson)

rawDescription: How I can deserialize python pickles in C#?


code: axHisty.set_xlabel("this is the x axis")

rawDescription: matplotlib - positioning xlabel/ylabel when using multi axes (hist + scatter)

description: Matplotlib - positioning xlabel/ylabel when using multi axes (hist + scatter)


code:
from itertools import groupby
dataOut = []
dataSorted = sorted(data, key=lambda x: (x["CustName"], x["PartNum"]))
for cust_name, cust_group in groupby(dataSorted, lambda x: x["CustName"]):
    dataOut.append({
        "CustName": cust_name,
        "Parts": [],
    })
    for part_num, part_group in groupby(cust_group, lambda x: x["PartNum"]):
        dataOut[-1]["Parts"].append({
            "PartNum": part_num,
            "deliveries": [{
                "delKey": delivery["delKey"],
                "memo": delivery["memo"],
                "qty": delivery["qty"],
            } for delivery in part_group]
        })

rawDescription: rebuilding arrays with nested defaultdict

description: Rebuilding arrays with nested defaultdict


code:
import csv
csv_file = csv.reader(open("your_file_name.csv"))

dist = 0
for row in csv_file:
    _dist = row[2]
    try:
        _dist = float(_dist)
    except ValueError:
        _dist = 0

    dist += _dist

rawDescription: Sum of a column in python for CSV file

description: Sum of a column in python for CSV file


code: new_list = sorted(statlist, key=lambda x: int(x[1]))

rawDescription: Why can't I sort this list?

description: Why can't I sort this list


code:
from StringIO import StringIO
import re

reader = StringIO("""{
    "title": "Pilot",
    "image": [
        {
            "resource": "http://images2.nokk.nocookie.net/__cb20110227141960/notr/images/8/8b/pilot.jpg",
            "description": "not yet implemented"
        }
    ],
    "content": "
The pilot ...
"
},
{
    "title": "Special Christmas (Part 1)",
    "image": [
        {
            "resource": "http://images1.nat.nocookie.net/__cb20090519172121/obli/images/e/ed/SpecialChristmas.jpg",
            "description": "not yet implemented"
        }
    ],
    "content": "
Last comment...
"
}""")

# to open a file just use reader = open(filename)

text = reader.read()
pattern = r'"resource": ".+/(.+).jpg"'
replacement = '"resource": "../img/\g<1>.jpg"'
text = re.sub(pattern, replacement, text)

print(text)

rawDescription: How to modify a file to replace a string that matches this pattern

description: Modify a file to replace a string that matches this pattern


code:
from datetime import datetime

Time = datetime.now()

print(Time)

rawDescription: Python Program for Visual Reaction Time

description: Python Program for Visual Reaction Time


code:
import time

def get_ints(s):
    return [int(i) for i in s.split()]

t = time.time()

Alen, Blen = get_ints(input())
A = get_ints(input())
B = get_ints(input())

total = sum(abs(Ai - Bj) * (i - j) for i,Ai in enumerate(A) for j,Bj in enumerate(B))

print(total)#, time.time()-t)

rawDescription: Best way to speed up a double summation

description: Speed up a double summation


code:
full_path = "/dir/blah/dog.tldr"
os.path.split(full_path)
os.path.split(full_path)[1]

rawDescription: Is there a way to get the name of the file only from tkFileDialog?


code:
q = Q(**{"categories__slug_" + current_lang + "__contains": slug})
items = Items.objects.filter(q)

rawDescription: A better way than eval() when translating keyword arguments in QuerySets (Python/Django)


code: myseries[myseries  == 'VALUE'].index.tolist()

rawDescription: Search by value in pandas series

description: Search by value in pandas series


code:
ts = time.mktime(time.strptime('20040412234551', '%Y%m%d%H%M%S'))
ts
datetime.datetime.fromtimestamp(ts)

rawDescription: Parsing timestamp with Python2.4

description: Parsing timestamp with Python2.4


code: [(c, a, b) for a, b, c in itertools.product('xy', '01', 'AB')]

rawDescription: Cartesian product whose output is not in lexicographic ordering


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

x = np.linspace(0,5,4)
y = np.sin(x)

xticks = ['0','8','24','72']

plt.plot(x,y)
plt.xticks(x,xticks) # This makes your desired x ticks
plt.show()

rawDescription: Changing x axis ticks to desired value.

description: Changing x axis ticks to desired value.


code:
import sys
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class Window(QWizard):
    def __init__(self):
        super(Window, self).__init__()
        self.accoutPage = AccountPage()
        self.secondPage = Page2()
        self.thirdPage = Page3()
        self.addPage(self.accoutPage)
        self.addPage(self.secondPage)
        self.addPage(self.thirdPage)
        self.button(QWizard.NextButton).clicked.connect(self.accoutPage.setMB)

class AccountPage(QWizardPage):
    def __init__(self, parent=None):
        super(AccountPage, self).__init__(parent)

        self.setTitle("Account Information")

        self.NameLabel = QLabel("&Name:")
        self.NameLineEdit = QLineEdit()
        self.NameLabel.setBuddy(self.NameLineEdit)

        self.EmailLabel = QLabel("&Email Address:")
        self.EmailLineEdit = QLineEdit()
        self.EmailLabel.setBuddy(self.EmailLineEdit)

        self.PwdLabel = QLabel("&Password:")
        self.PwdLineEdit = QLineEdit()
        self.PwdLabel.setBuddy(self.PwdLineEdit)

        self.registerField('Name*', self.NameLineEdit)
        self.registerField('EmailAddress*', self.EmailLineEdit)
        self.registerField('Password*', self.PwdLineEdit)

        layout = QGridLayout()
        layout.addWidget(self.NameLabel, 0, 0)
        layout.addWidget(self.NameLineEdit, 0, 1)
        layout.addWidget(self.EmailLabel, 1, 0)
        layout.addWidget(self.EmailLineEdit, 1, 1)
        layout.addWidget(self.PwdLabel, 2, 0)
        layout.addWidget(self.PwdLineEdit, 2, 1)

        self.setLayout(layout)
        self.i = 0 #if you need to call it once

    def setMB(self):
        if self.i == 0:
            print(self.PwdLineEdit.text(), self.i)
            try:
                with open('mb.ini', 'w') as actInfo:
                    actInfo.write('sj')

            except IOError as err:
                print('mb.ini error:' + str(err))
            finally:
                self.i += 1

class Page2(QWizardPage):
    def __init__(self):
        super(Page2, self).__init__()

class Page3(QWizardPage):
    def __init__(self):
        super(Page3, self).__init__()

def main():
    app = QApplication(sys.argv)
    app.setStyle('plastique')

    window = Window()
    window.setWizardStyle(1)
    window.show()
    app.exec_()

if __name__ == "__main__":
    sys.exit(main())

rawDescription: pyqt:how to emit a signal when NextButton of a QwizardPage was clicked

description: Pyqt:how to emit a signal when NextButton of a QwizardPage was clicked


code:
import re
originalstring = 'fksf var:asfkj;'
pattern = '.*?var:(.*?);'
pattern_obj = re.compile(pattern, re.MULTILINE)
replacement_string="\\1" + 'test'
pattern_obj.sub(replacement_string, originalstring)

rawDescription: Python Regex, re.sub, replacing multiple parts of pattern?


code:
import matplotlib.pyplot as plt
from pylab import *

# fake up some data
spread= rand(50) * 100
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)

# figure related code
fig = plt.figure()
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')

ax = fig.add_subplot(111)
ax.boxplot(data)

ax.set_title('axes title')
ax.set_xlabel('xlabel')
ax.set_ylabel('ylabel')

plt.show()

rawDescription: How to add labels to a boxplot figure (pylab)

description: Add labels to a boxplot figure (pylab)


code:
from django.db.models import Manager
result = Manager.raw(u"""select SUM(royalty_price*conversion_to_usd)from sales_raw where date='2012-06-01'""")

rawDescription: Closest equivalent to SUM in Django

description: Closest equivalent to SUM in Django


rawDescription: regular expressions to extract phone numbers

description: Regular expressions to extract phone numbers


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

plt.plot([1,2,5,4])
ax1 = plt.gca()
ax2 = ax1.twiny()

new_tick_locations = np.array([.1, .3, .5, .7,.9]) # Choosing the new tick locations
inv = ax1.transData.inverted()
x = []

for each in new_tick_locations:
    print(each)
    a = inv.transform(ax1.transAxes.transform([each,1])) # Convert axes-x-coordinates to data-x-coordinates
    x.append(a[0])

c = 2
x = np.array(x)
def tick_function(X):
    V =  c/X
    return ["%.1f" % z for z in V]
ax2.set_xticks(new_tick_locations) # Set tick-positions on the second x-axes
ax2.set_xticklabels(tick_function(x)) # Convert the Data-x-coordinates of the first x-axes to the Desired x', with the tick_function(X)

rawDescription: Matplotlib: plot x/y coordinates with Two x-Axis with inverse scaling


code:
TIMEOUT = 5
start = time.time()
while time.time() - start <= TIMEOUT:
    if any(p.is_alive() for p in procs):
        time.sleep(.1)  # Just to avoid hogging the CPU
    else:
        # All the processes are done, break now.
        break
else:
    # We only enter this if we didn't 'break' above.
    print("timed out, killing all processes")
    for p in procs:
        p.terminate()
        p.join()

rawDescription: Python multiprocessing module: join processes with timeout


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

white = (255,255,255)
black = (0,0,0)

class Pane(object):
    def __init__(self):
        pygame.init()
        self.font = pygame.font.SysFont('Arial', 25)
        pygame.display.set_caption('Box Test')
        self.screen = pygame.display.set_mode((600,400), 0, 32)
        self.screen.fill((white))
        pygame.display.update()

    def addRect(self):
        self.rect = pygame.draw.rect(self.screen, (black), (175, 75, 200, 100), 2)
        pygame.display.update()

    def addText(self):
        self.screen.blit(self.font.render('Hello!', True, (255,0,0)), (200, 100))
        pygame.display.update()

if __name__ == '__main__':
    Pan3 = Pane()
    Pan3.addRect()
    Pan3.addText()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit(); sys.exit();

rawDescription: How to add text into a pygame rectangle

description: Add text into a pygame rectangle


code:
a = [1,4,6,2,3]
[b[0] for b in sorted(enumerate(a),key=lambda i:i[1])]

rawDescription: Sort a list then give the indexes of the elements in their original order


code:
import re
p = re.compile(r'(.)\1+')
test_str = "heeeey"
subst = r"\1"

result = re.sub(p, subst, test_str)

rawDescription: Python regex : detect a word with duplicated chars


code:
N = 500
X = np.arange(2,N)

def k_loop(w,n):
    K = np.arange(0, w+1)
    return (binom(w,K)*(binom(w,K)/2**w)**(float(n)/np.log(n))).sum()

def w_loop(n):
    v = [binom(n,w)*k_loop(w,n) for w in range(1,n+1)]
    return sum(v)

Y = [w_loop(n) for n in X]

rawDescription: Plot function with large binomial coefficients


code:
import numpy as np
from bokeh.plotting import *

output_file('linked_panning.html')

N=300
x = np.linspace(0, 4*np.pi, N)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.sin(x) + np.cos(x)

s1 = figure(plot_width=350, plot_height=350)
s1.scatter(x, y1)

s2 = figure(plot_width=350, plot_height=250, x_range=s1.x_range, y_range=s1.y_range)
s2.scatter(x, y2)

s3 = figure(plot_width=350, plot_height=350, x_range=s1.x_range, y_range=s1.y_range)
s3.scatter(x, y3)

p = gridplot(([[s1, s2, s3]]))
show(p)

rawDescription: Bokeh plot zoom in/out for VBox(ts1, ts2, ts3)


code:
from Tkinter import *

def change_image(*args):
    # Change image of label accordingly
    label.config(image=photos[int(studFiles.get())])

app = Tk()
app.title("Example")
app.geometry('500x200+200+200')
app.configure(background='black')
app.resizable(0,0)

studFiles = StringVar()
studFiles.set('Image')
files =['0', '1'] # Number is corresponding list index
studDropDown = OptionMenu(app, studFiles, *files)
studDropDown.config(font=("Times", 16, "italic"))
studDropDown["menu"].config(font=("Times", 16, "italic"))
studDropDown.pack()

studFiles.trace("w", change_image)

# List of photoimages for each image
photos =(PhotoImage(file='im.gif'), PhotoImage(file='im2.gif'))
label = Label(app,image=photos[0])
label.pack()

app.mainloop()

rawDescription: How do I update a label with an image in tkinter in python?

description: Update a label with an image in tkinter in python


code:
from django.db.models import Q

today = datetime.now().date()
now = datetime.now().time()

future_events = CauseEvent.objects.filter(cause=instance) \
                                  .exclude(Q(date__lt=today) |
                                           Q(date=today, time__lt=now))

rawDescription: filter combined date and time in django

description: Filter combined date and time in django


code:
from django.core.urlresolvers import resolve
foo = resolve('/login/')
foo.func

rawDescription: How to get the view that corresponds to a url in Django (using the url)?

description: Get the view that corresponds to a url in Django (using the url)


code:
from collections import defaultdict

d = defaultdict(list)

for index, line in enumerate(txt.splitlines()):
    for word in line:
        word_strip = word.strip(',.!?')
        d[word_strip].append(index)

rawDescription: what is the most pythoic way of indexing a file?

description: What is the most pythoic way of indexing a file


code:
import os
engine = create_engine(os.environ.get('OPENSHIFT_POSTGRESQL_DB_URL'))

rawDescription: How to use PostgreSQL on a Pyramid App in OpenShift?

description: Use PostgreSQL on a Pyramid App in OpenShift


code:
class CustomText(tk.Text):
    '''A text widget with a new method, highlight_pattern()

    example:

    text = CustomText()
    text.tag_configure("red", foreground="#ff0000")
    text.highlight_pattern("this should be red", "red")

    The highlight_pattern method is a simplified python
    version of the tcl code at http://wiki.tcl.tk/3246
    '''
    def __init__(self, *args, **kwargs):
        tk.Text.__init__(self, *args, **kwargs)

    def highlight_pattern(self, pattern, tag, start="1.0", end="end",
                          regexp=False):
        '''Apply the given tag to all text that matches the given pattern

        If 'regexp' is set to True, pattern will be treated as a regular
        expression according to Tcl's regular expression syntax.
        '''

        start = self.index(start)
        end = self.index(end)
        self.mark_set("matchStart", start)
        self.mark_set("matchEnd", start)
        self.mark_set("searchLimit", end)

        count = tk.IntVar()
        while True:
            index = self.search(pattern, "matchEnd","searchLimit",
                                count=count, regexp=regexp)
            if index == "": break
            if count.get() == 0: break # degenerate pattern which matches zero-length strings
            self.mark_set("matchStart", index)
            self.mark_set("matchEnd", "%s+%sc" % (index, count.get()))
            self.tag_add(tag, "matchStart", "matchEnd")

rawDescription: How to highlight text in a tkinter Text widget

description: Highlight text in a tkinter Text widget


code:
class Completer(gtk.Bin):
    __gtype_name__= "Completer"

    def __init__(self, exts, *args, **kwargs):
        super(Completer, self).__init__(*args, **kwargs)
        child = gtk.VBox(spacing=15)
        self.add(child)

rawDescription: Python GTK: Instantiating a subclass of gtk.Bin


code:
if 'propname' in ent._properties:
  del ent._properties['propname']
  ent.put()

rawDescription: how to cleanly remove ndb properties

description: Cleanly remove ndb properties


code:
available = 'abcdefghijklmnopqrstuvwxyz'
secret = 'apple'
if 'a' in secret:
  available = available.replace('a','')

available

rawDescription: Manipulating strings using slicing in python to add or delete a character


code:
class ReviewSerializer(serializers.ModelSerializer):
    """
    Class to serialize Review objects
    """
    person_name = serializers.SerializerMethodField()
    employee_name = serializers.SerializerMethodField()
    service_name = serializers.SerializerMethodField()

    class Meta:
        model = Review
        fields = ['person', 'service', 'review', 'employee', 'person_name', 'service_name', 'employee_name', 'date_time']
        read_only_fields = 'id'

    def get_person_name(self, obj):
        try:
            person_name = obj.person.first_name + obj.person.last_name
        except AttributeError: # handle case if person is null
            return None
        else:
            return person_name

    def get_employee_name(self, obj):
        try:
            employee_name = obj.employee.first_name + obj.employee.last_name
        except AttributeError: # handle case if employee is null
            return None
        else:
            return employee_name

    def get_service_name(self, obj):
        try:
            service_name = obj.service.title
        except AttributeError: # handle case if service is null
            return None
        else:
            return service_name

rawDescription: Creating new fields in serializer that access another model's attributes


code:
def recursive(data):
   for i,j in enumerate(data):
      if condition:
         recursive(data[i:])

rawDescription: Python: How to select all other items in a for loop


code: line + "\n"

rawDescription: In python whats the opposite of rstrip()


code:
def issue_command(transport, pause, command):
    chan = transport.open_session()
    chan.exec_command(command)

    buff_size = 1024
    stdout = ""
    stderr = ""

    while not chan.exit_status_ready():
        time.sleep(pause)
        if chan.recv_ready():
            stdout += chan.recv(buff_size)

        if chan.recv_stderr_ready():
            stderr += chan.recv_stderr(buff_size)

    exit_status = chan.recv_exit_status()
    # Need to gobble up any remaining output after program terminates...
    while chan.recv_ready():
        stdout += chan.recv(buff_size)

    while chan.recv_stderr_ready():
        stderr += chan.recv_stderr(buff_size)

    return exit_status, stdout, stderr

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, port=22, username=username, password=password, timeout=3,)
transport = ssh.get_transport()
pause = 1

resp1 = issue_command(transport, pause, cmd1)
resp2 = issue_command(transport, pause, cmd2)

rawDescription: Paramiko: how to ensure data is received between commands


code: any(reviewed_object_name == reviewed_object.name for reviewed_object in reviewed_objects_collection)

rawDescription: problem: how to verify affiliation of object in the collection of objects

description: Problem: how to verify affiliation of object in the collection of objects


code: list1 = [ key for key in mydict1.keys() if key in mydict2.itervalues() ]

rawDescription: use dictionary_1's keys to search for a match in dictionary_2's values

description: Use dictionary_1's keys to search for a match in dictionary_2's values


code:
with open('datafile') as f:
    for line in f:
        process(line)

rawDescription: Loading Large File in Python

description: Loading Large File in Python


code:
board = dict()
square = user_input
board[square] = ["value 1"]

rawDescription: Python - How do I use user input as an array name?


rawDescription: Using .loc with a MultiIndex in pandas?

description: Using .loc with a MultiIndex in pandas


code:
class RSLLexer(Qsci.QsciLexerCPP):
    def keywords(self, index):
        keywords = Qsci.QsciLexerCPP.keywords(self, index) or ''
        # primary keywords
        if index == 1:
            return 'foo ' + keywords
        # secondary keywords
        if index == 2:
            return 'bar ' + keywords
        # doc comment keywords
        if index == 3:
            return keywords
        # global classes
        if index == 4:
            return keywords
        return keywords

rawDescription: Customizing PyQt Qscintilla CPP lexer

description: Customizing PyQt Qscintilla CPP lexer


code:
graph = facebook.GraphAPI(oauth_access_token)
tags = json.dumps([{'x':50, 'y':50, tag_uid:12345}, {'x':10, 'y':60, tag_text:'a turtle'}])
graph.put_photo(open('img.jpg'), 'Look at this cool photo!', album_id_or_None, tags=tags)

rawDescription: Facebook Python SDK - Upload image in Event Create


code:
df.session[df[listvals].sum(axis=1) == len(listvals)]
df.session[df[listvals].sum(axis=1) >= 2]
df.session[df[listvals].sum(axis=1) <= 1]

rawDescription: Find list of values available in pandas dataframe with binary values


code:
def prefix_match(sentence, taglist):
    taglist = tuple(taglist)
    for word in sentence.split():
        if word.startswith(taglist):
            return word

rawDescription: prefix matching in python

description: Prefix matching in python


code:
class CategoricalTransformer(TransformerMixin):

    def fit(self, X, y=None, *args, **kwargs):
        self.columns_ = X.columns
        self.cat_columns_ = X.select_dtypes(include=['category']).columns
        self.non_cat_columns_ = X.columns.drop(self.cat_columns_)

        self.cat_map_ = {col: X[col].cat.categories
                         for col in self.cat_columns_}
        self.ordered_ = {col: X[col].cat.ordered
                         for col in self.cat_columns_}

        self.dummy_columns_ = {col: ["_".join([col, v])
                                     for v in self.cat_map_[col]]
                               for col in self.cat_columns_}
        self.transformed_columns_ = pd.Index(
            self.non_cat_columns_.tolist() +
            list(chain.from_iterable(self.dummy_columns_[k]
                                     for k in self.cat_columns_))
        )

    def transform(self, X, y=None, *args, **kwargs):
        return (pd.get_dummies(X)
                  .reindex(columns=self.transformed_columns_)
                  .fillna(0))

rawDescription: Pandas categorical variable transformation


code:
import re
re._MAXCACHE = 1000

rawDescription: Pythonic and efficient way of defining multiple regexes for use over many iterations


code:
import Image
import hashlib

img = Image.open(filename).convert('RGBA')
m=hashlib.md5()
m.update(img.tostring())
print(m.hexdigest())

rawDescription: Unique image hash that does not change if EXIF info updated


code:
for i in range(0, 10):
    v[i] = init()
    if i != 0:
        if v[i].number < v[i-1].number:
            v[i-1], v[i] = v[i], v[i-1]

rawDescription: Sort registers array without default methods


code:
from sqlalchemy import inspect
inspect(User).attrs.keys()
User.addresses.property.backref

rawDescription: how to get backref name in sqlalchemy?

description: Get backref name in sqlalchemy


code:
l=[['a'],[['p','l']]]
[j for i in l for j in i]

rawDescription: Flattening List of Lists in Python

description: Flattening List of Lists in Python


code:
from PyQt4 import QtGui as gui
from PyQt4 import QtCore as core

class Blinker(gui.QWidget):
    def __init__(self, parent=None):
        super(Blinker, self).__init__(parent)

        self.label = gui.QLabel(self)
        self.label.setFixedSize(200, 200)
        self.layout = gui.QHBoxLayout(self)
        self.layout.addWidget(self.label)

        self.timer  = core.QTimer(self)
        self.timer.setInterval(1000)          # Throw event timeout with an interval of 1000 milliseconds
        self.timer.timeout.connect(self.blink) # each time timer counts a second, call self.blink
        self.color_flag = True

    def start(self):
        self.timer.start()

    def stop(self):
        self.timer.stop()

    @core.pyqtSlot()
    def blink(self):
        if self.color_flag:
            self.label.setStyleSheet("background-color: blue;")
        else:
            self.label.setStyleSheet("background-color: yellow;")
        self.color_flag = not self.color_flag

if __name__ == '__main__':
    import sys
    app = gui.QApplication(sys.argv)

    w = Blinker()
    w.show()
    w.start()

    sys.exit(app.exec_())

rawDescription: Use QThread to periodically update a QTableWidget pyqt


code:
import pandas as pd

df=pd.DataFrame({'First': [ 'Sam', 'Greg', 'Steve', 'Sam',
                 'Jill', 'Bill', 'Nod', 'Mallory', 'Ping', 'Lamar'],
                 'Last': [ 'Stevens', 'Hamcunning', 'Strange', 'Stevens',
                 'Vargas', 'Simon', 'Purple', 'Green', 'Simon', 'Simon'],
                 'Address': ['112 Fake St','13 Crest St','14 Main St','112 Fake St','2 Morningwood','7 Cotton Dr','14 Main St','20 Main St','7 Cotton Dr','7 Cotton Dr'],
                 'Status': ['Infected','','Infected','','','','','','','Infected'],
                 'Level': [10,2,7,5,2,10,10,20,1,1],
                 })

df2_index = df.groupby(['Address', 'Last']).filter(lambda x: (x['Status'] == 'Infected').any()).index
df2 = df.copy()
df2.loc[df2_index, 'Status'] = 'Infected'

df3_status = df.groupby('Address', as_index=False, group_keys=False).apply(lambda x: pd.Series(list('Infected' if (row['Status'] == 'Infected') or ((x['Status'] == 'Infected') & (x['Level'] != row['Level'])).any() else '' for _, row in x.iterrows()), index=x.index))
df3 = df.copy()
df3['Status'] = df3_status

rawDescription: Python Pandas Adding conditions on cells with duplicate values


code:
from itertools import groupby
def keyfunc(letter):
    return (test_lang(letter), letter in punc)

cleaned = ' '.join(''.join(g) for k, g in groupby(letters, keyfunc))

rawDescription: Python script to insert space between different character types: Why is this *so* slow?


code:
class CurUserOnlyDetailView(DetailView):
    def get_object(self, *args, **kwargs):
        obj = super(CurUserOnlyDetailView, self).get_object(*args, **kwargs)
        if obj.user != self.request.user:
            raise PermissionDenied()
        else:
            return obj

class CarDetail(CurUserOnlyDetailView):
    context_object_name = 'car'
    template_name = 'my_app/car_details.html'
    model = models.Car

# another view, no DRY violation
class BikeDetail(CurUserOnlyDetailView):
    context_object_name = 'bike'
    template_name = 'my_app/bike_details.html'
    model = models.Bike

rawDescription: Django - object level premission and class based generic views


code: list_display = ('email', 'first_name', 'last_name','userprofile')

rawDescription: Accessing extended User class fields

description: Accessing extended User class fields


code:
import multiprocessing, time, math

def func():
    print('hello its now {}'.format(time.time()))

def wrapper(f, period, event):
    last = time.time() - period
    while True:
        now = time.time()

        # returns True if event is set, otherwise False after timeout
        if event.wait(timeout=(last + period - now)):
            break
        else:
            f()
            last += period

def main():
    period = 2
    # event is the poison pill, setting it breaks the infinite loop in wrapper
    event = multiprocessing.Event()
    process = multiprocessing.Process(target=wrapper, args=(func, period, event))
    process.start()

    # burn some cpu cycles, takes about 20 seconds on my machine
    x = 7
    for i in range(50000000):
        x = math.sqrt(x**2)

    event.set()
    process.join()
    print('x is {} by the way'.format(x))

if __name__ == '__main__':
    main()

rawDescription: Schedule Tasks at Fixed Rate with Python Multiprocessing


code:
pieces = {}
for row in incsv:
    piece = tuple(row)
    if piece not in pieces:
        pieces[piece] = 0
    else:
        pieces[piece] += 1
for item, count in pieces.items():
    row = (count,) + item
    outcsv.writerow(row)

rawDescription: Combining rows in a CSV file and updating quantities with Python


code:
from pylab import *
f = figure()
f.add_subplot(111)
f.tight_layout()
show()

rawDescription: How do I set the size of the axes patch so that the plot labels aren't clipped (matplotlib)

description: Set the size of the axes patch so that the plot labels aren't clipped (matplotlib)


code:
from itertools import product
from string import ascii_uppercase
triplets = map(''.join, product(ascii_uppercase, repeat=3))
triplets[4]

rawDescription: Generate all base26 triplests in the fastest way


code:
import db_module
def func(arg1, arg2):
    database_connection = db_module.get_db_instance()

rawDescription: How can I share the same database connection instance between different modules in a package?

description: Share the same database connection instance between different modules in a package


code:
import numpy as np

import matplotlib.pyplot as plt

# Generate some data
x = np.linspace(0, 10, 1000)
y = np.sin(np.exp(0.3*x))

fig, ax = plt.subplots()

ax.plot(x, y)

ax.set_ylim(-2,2)

ax.annotate('First maxima',
            xy=(np.pi/2., 2),
            xytext=(np.pi/2., 2.3),
            arrowprops = dict(facecolor='black', shrink=0.05))

plt.show()

rawDescription: Using matplotlib and point to specific value on the x-axis


code:
import webbrowser
urls = ['http://www.xkcd.org/',
        'http://stackoverflow.com/questions/22213479/python-text-to-html-link',
        'http://docs.python.org/2/library/webbrowser.html']

for url in urls:
    webbrowser.open_new_tab(url)

rawDescription: Python text to HTML link

description: Python text to HTML link


code:
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# generated by wxGlade 0.6.3 on Tue Jul 21 20:00:54 2009

import wx

# begin wxGlade: extracode
# end wxGlade

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.text_ctrl_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
        self.text_ctrl_1_copy = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)
        self.text_ctrl_1_copy_1 = wx.TextCtrl(self, -1, "", style=wx.TE_MULTILINE)

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: MyFrame.__set_properties
        self.SetTitle("frame_1")
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
        sizer_2.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
        sizer_2.Add(self.text_ctrl_1_copy, 1, wx.EXPAND, 0)
        sizer_2.Add(self.text_ctrl_1_copy_1, 1, wx.EXPAND, 0)
        sizer_1.Add(sizer_2, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

# end of class MyFrame

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, -1, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()

rawDescription: Need assistance with wxPython (newbie)

description: Need assistance with wxPython (newbie)


code:
future = loop.run_in_executor(None, long_running_function)
result = await asyncio.wait_for(future, timeout, loop=loop)

rawDescription: Timeout handling while using run_in_executor and asyncio


code:
from lib import print_ls

class LibTest(unittest.TestCase):

    def test_render_reverse_is_correct(self):
        with patch('django.core.urlresolvers.reverse') as mock_reverse:
            from lib import render_reverse
            mock_f = MagicMock(name='f', return_value='dummy_view')
            mock_kwargs = MagicMock(name='kwargs',return_value={'args':['123']})
            mock_reverse.return_value = '/natrium/cb/details/123'
            response = render_reverse(mock_f, mock_kwargs)

        self.assertTrue('/natrium/cb/details/' in response)

rawDescription: Am I mocking this helper function right in my Django test?


code:
def create(request, model_class):
    forms = {
        'user': UserForm,
        'group': GroupForm
    }

    form_class = forms[model_class]
    ...

rawDescription: Create ModelForm dynamically

description: Create ModelForm dynamically


code:
import requests
from bs4 import BeautifulSoup

with requests.Session() as session:
    session.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"}
    r = session.get("https://www.zomato.com/brewbot")
    soup = BeautifulSoup(r.content, "html.parser")
    itemid = soup.body["itemid"]

    # get reviews
    r = session.post("https://www.zomato.com/php/social_load_more.php", data={
        "entity_id": itemid,
        "profile_action": "reviews-top",
        "page": "0",
        "limit": "5"
    })
    reviews = r.json()["html"]

    soup = BeautifulSoup(reviews, "html.parser")
    k_data = soup.select("div.rev-text")

    for item in k_data:
        print(item.get_text())

rawDescription: web scraping python not fetching results

description: Web scraping python not fetching results


code:
from subprocess import PIPE, Popen

proc = Popen(['git', 'log'], stdout=PIPE)
lines = proc.stdout.readlines()

rawDescription: A better way to get command line outputs with python?


rawDescription: How to strip comma in Python string

description: Strip comma in Python string


code:
def block_data(messy_data, c, gazetteer):

    block_groups = itertools.groupby(gazetteer.blocker(messy_data.viewitems()),
                                 lambda x: x[1])
    for (record_id, block_keys) in block_groups:

        a = [(record_id, messy_data[record_id], set())]

        c.execute("""SELECT DISTINCT record_id
                     FROM blocking_map
                     WHERE block_key IN %s""",
                  (tuple(block_key for block_key, _ in block_keys),))

        values = tuple(row['record_id'] for row in c)

        if values:

            c.execute("""SELECT *
                         FROM canonical_table
                         WHERE record_id IN %s""",
                      (values,))

            b = [(row['record_id'], row, set())
                 for row in c]

            if b:
                yield (a, b)

rawDescription: How do I link records to a large table efficiently using python Dedupe?

description: Link records to a large table efficiently using python Dedupe


code:
import random
from fractions import gcd

def pollardRho(n, seed = None):
    def f(x): return (x**2 + 1) % n
    if seed == None: seed = random.randint(0,n-1)
    t = h = seed
    t = f(t)
    h = f(f(h))
    d = gcd(t-h,n)
    while d == 1:
        t = f(t)
        h = f(f(h))
        d = gcd(t-h,n)
    return d,n//d

rawDescription: Python. Find factor of huge number.

description: Python. Find factor of huge number.


rawDescription: Do you know "sample[::-1]" mean? in Python


code:
# Domain Model:
class Person(object):
    def __init__(self, name, neighbors=[]):
        self.name = name
        self.neighbors = neighbors

class Neighbor(object):
    def __init__(self, r_neigbor, distance):
        # @NOTE: the first argument is not "person" field, but a real
        # object of the relationship. I gave it name "r_neigbor", but it can
        # be anything, but not a nammed of the mapped attribute ("person")
        self.r_neigbor = r_neigbor
        self.distance = distance

# Database Schema / ORM objects:
metadata = MetaData()

person = Table(
    'person', metadata,
    Column('name', String(20), primary_key=True),
)

neighbor = Table(
    'neighbor', metadata,
    Column('name', String(20), ForeignKey(person.c.name), primary_key=True),
    Column('neighbor', String(20), ForeignKey(person.c.name), primary_key=True),
    Column('distance', Integer),
)

# Data Mappings
def datamap():
    # @NOTE: here it is easier and less confusing to define both relationshis
    # from one side. Again, make sure that the names of the relationships do not
    # override names of existing mapped attributes.
    # @NOTE: `foreign_keys` is the piece which solves the actual error message
    # you get
    properties = {'neighbors':
                  relationship(Neighbor, backref="r_person",
                               foreign_keys=neighbor.c.name,),
                  'neighbors_of':
                  relationship(Neighbor, backref="r_neigbor",
                               foreign_keys=neighbor.c.neighbor,)
                  }
    mapper(Person, person, properties=properties)
    mapper(Neighbor, neighbor)

# Unit Test (just to see if we don't throw errors in this case)
class TestMaps(TestCase):
    def test_map(self):
        # Setup
        session = self.get_session()

        # Exercise
        datamap()
        model = self.build_model()
        session.add(model)
        session.flush()

    def build_model(self):
        bill = Person('Bill')
        jack = Person('Jack')
        # @NOTE: fix: `bill.neighbors` instead of `person.neigbors`
        bill.neighbors = [Neighbor(jack, 10)]
        return bill

    def get_session(self):
        from sqlalchemy.orm import sessionmaker
        from sqlalchemy import create_engine
        engine = create_engine('sqlite:///:memory:', echo=True)
        metadata.create_all(engine, tables=[person, neighbor])
        Session = sessionmaker(bind=engine)
        return Session()

rawDescription: Trouble Mapping Recursive Relationship - SQLAlchemy


code: from numpy import array

rawDescription: How to make numpy load faster

description: Make numpy load faster


rawDescription: mean() of column in pandas DataFrame returning inf: how can I solve this?

description: Mean() of column in pandas DataFrame returning inf: how can I solve this


code:
for i,ph,df in zip(residues,ph_set,dfs):
    titration_curves.write("%s " % i)
    for j in ph:
        titration_curves.write("%s " % j)
    for j in df:
        titration_curves.write("%s  " % j)
    titration_curves.write("\n")

rawDescription: How can I write two outputs to the same lines?

description: Write two outputs to the same lines


code:
   # note: to call a remote object with an non-standard name, use
   # result getattr(server, "strange-python-name")(args)

rawDescription: Dynamic method name generation using xmlrpc


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

def plot_clustered_stacked(dfall, labels=None, title="multiple stacked bar plot",  H="/", **kwargs):
    """Given a list of dataframes, with identical columns and index, create a clustered stacked bar plot.
labels is a list of the names of the dataframe, used for the legend
title is a string for the title of the plot
H is the hatch used for identification of the different dataframe"""

    n_df = len(dfall)
    n_col = len(dfall[0].columns)
    n_ind = len(dfall[0].index)
    axe = plt.subplot(111)

    for df in dfall : # for each data frame
        axe = df.plot(kind="bar",
                      linewidth=0,
                      stacked=True,
                      ax=axe,
                      legend=False,
                      grid=False,
                      **kwargs)  # make bar plots

    h,l = axe.get_legend_handles_labels() # get the handles we want to modify
    for i in range(0, n_df * n_col, n_col): # len(h) = n_col * n_df
        for j, pa in enumerate(h[i:i+n_col]):
            for rect in pa.patches: # for each index
                rect.set_x(rect.get_x() + 1 / float(n_df + 1) * i / float(n_col))
                rect.set_hatch(H * (i / n_col))
                rect.set_width(1 / float(n_df + 1))

    axe.set_xticks((np.arange(0, 2 * n_ind, 2) + 1 / float(n_df + 1)) / 2.)
    axe.set_xticklabels(df.index, rotation = 0)
    axe.set_title(title)

    # Add invisible data to add another legend
    n=[]
    for i in range(n_df):
        n.append(axe.bar(0, 0, color="gray", hatch=H * i))

    l1 = axe.legend(h[:n_col], l[:n_col], loc=[1.01, 0.5])
    if labels is not None:
        l2 = plt.legend(n, labels, loc=[1.01, 0.1])
    axe.add_artist(l1)
    return axe

# create fake dataframes
df1 = pd.DataFrame(np.random.rand(4, 5),
                   index=["A", "B", "C", "D"],
                   columns=["I", "J", "K", "L", "M"])
df2 = pd.DataFrame(np.random.rand(4, 5),
                   index=["A", "B", "C", "D"],
                   columns=["I", "J", "K", "L", "M"])
df3 = pd.DataFrame(np.random.rand(4, 5),
                   index=["A", "B", "C", "D"],
                   columns=["I", "J", "K", "L", "M"])

# Then, just call :
plot_clustered_stacked([df1, df2, df3],["df1", "df2", "df3"])

rawDescription: How to have clusters of stacked bars with python (Pandas)

description: Have clusters of stacked bars with python (Pandas)


code:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
opener.open('http://www.example.com/')

rawDescription: Website Treating me as mobile when scraping from html in python


rawDescription: Is it possible to modify PYTHONPATH at runtime?


code:
# a recursive function to flatten arbitrary nested lists into one simple 1D list
def flatten(inlist,outlist):
    for e in inlist:
        if isinstance(e,list) :
            flatten(e,outlist)
        else:
            outlist.append(e)

rawDescription: how to flatten/penetrate an arbitrarily structured nested list in Python?

description: Flatten/penetrate an arbitrarily structured nested list in Python


code:
import inspect
PROVIDER_CHOICES = inspect.getmembers(Foo, lambda x: isinstance(x, int))

rawDescription: What is the preferred technique to convert an object's properties to a sorted list of tuples?


code:
import pandas as pd
from datetime import datetime

def parse(year, month, day, hour, minute, second):
    return year+ '-' +month+ '-' +day+ ' ' +hour+ ':' +minute+ ':' +second

df = pd.read_csv('test.csv', parse_dates={'Date/Time':['year', 'month', 'day', 'hour', 'minute', 'second']},
           date_parser=parse,
           index_col=0)

rawDescription: Parsing year, month, day, hour, minute, second in Python


code:
icon = QIcon()
icon.addPixmap(QPixmap('normal.png'))
icon.addPixmap(QPixmap('disabled.png'), QIcon.Disabled)
icon.addPixmap(QPixmap('clicking.png'), QIcon.Active)
icon.addPixmap(QPixmap('on.png'), QIcon.Normal, QIcon.On)
btn.setIcon(icon)

rawDescription: PyQt4: Changing button icon on action

description: PyQt4: Changing button icon on action


code: assert isinstance(a_list, list)

rawDescription: Pydev Code Completion for everything

description: Pydev Code Completion for everything


code:
df = pd.read_csv(csv_file)
df['Batch'] = df['Batch'].apply(interpret_date)

def interpret_date(code):
   _year = replace_year(code[0])
   _month = replace_month(code[1])
   _date = replace_date(code[2:4])
   return '-'.join([_date, _month, _year])

rawDescription: Decoding the contents of a table using python


code:
questions = forms.MultipleChoiceField(
    required=False,
    label='',
    widget=forms.CheckboxSelectMultiple(attrs={'class': 'my-class'}),
    choices=CHOICES,
)

rawDescription: Django how to modify checkbox labels for MultipleChoiceField?


code:
pattern = re.compile(r'^\d+m2$')  # assuming that m2 == square meter
bool(pattern.search("340m2"))
bool(pattern.search("820m2 bla bla"))

rawDescription: python detect if string contains junk

description: Python detect if string contains junk


code:
import main_code

class COMInterface:
    _public_methods_ = [ 'method1' ]
    _reg_progid_ = "My.Test"
    _reg_clsid_ = "{D6AA2A12-A5CE-4B6C-8603-7952B711728B}"

    def methods(self, input1,input2,input3):
        # force python to reload the code that does the actual work
        reload(main_code)
        return main_code.Runner().go(input1,input2,input3)

rawDescription: How to force Excel VBA to use updated COM server

description: Force Excel VBA to use updated COM server


rawDescription: Get specific element from Groups after applying groupby - PANDAS


code:
import sys
from PySide.QtCore import QUrl, QSize
from PySide.QtGui import QApplication, QMainWindow, QWidget
from PySide.QtWebKit import QWebView

class Browser(QMainWindow):

    def __init__(self):
        QMainWindow.__init__(self)
        self.resize(300, 300)
        self.web_view = QWebView()
        self.setCentralWidget(self.web_view)

        self.web_view.loadFinished.connect(self._load_finished)

    def _load_finished(self):
        frame = self.web_view.page().mainFrame()
        self.web_view.page().setViewportSize(frame.contentsSize())
        self.resize(frame.contentsSize())
        html_data = frame.toHtml()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    browser = Browser()
    r = QUrl("http://www.yahoo.com")
    browser.web_view.load(r)
    browser.show()
    app.exec_()

rawDescription: How to set the size of browser using QtWebKit

description: Set the size of browser using QtWebKit


code:
from random import choice
from numpy import arange

index = [i + 1 for i in range(365)]
choices = []
seen = set()
ar = arange(0.05,.16, .01)
ln = len(index)
sample_size = 0
while sample_size < ln * .30:
    perc = choice(ar)  # get random 5, 10, 15 percent slices
    size = int(ln * perc)
    ch = choice(index[:-size+1]) # avoid falling off the side
    rn = index[ch:ch+size]
    if len(rn) == size and not seen.intersection(rn):
        seen.update(rn)
        choices.append(rn)
        sample_size += len(rn)
print(choices)

rawDescription: Random selection of contiguous elements in an array in Python


code:
from bs4 import BeautifulSoup
content = """

    12090043
    CourseA
    3
    86	2013-Summer

    10420844
    CourseB
    4
    98	2013-Autumn

"""

soup = BeautifulSoup(content, "html.parser")
[i.get_text(' ').split() for i in soup.find_all('tr')]

rawDescription: python re.findall did not find all

description: Python re.findall did not find all


code: re.findall(r"[A-Za-z@#]+|\S", message)

rawDescription: How do You Split String into Words and Special Characters in Python?


code:
def makecov(rho, n):
    out = numpy.eye(n) + rho
    numpy.fill_diagonal(out, 1)
    return out

rawDescription: how to use pandas to create correlation matrix of multivariate normal distribution?

description: Use pandas to create correlation matrix of multivariate normal distribution


rawDescription: Filling region between curve and x-axis in Python using Matplotlib


code:
import mock

DUT = ClassUnderTest()
spy = mock.Mock(spec=DUT)
# test call
ClassUnderTest.higher(spy)

# Assert that lower_1 was called before lower_2
assert spy.mock_calls == [mock.call.lower_1(), mock.call.lower_2()]

rawDescription: Using Python Mock library to spy on internal method calls


code:
column_data = (('myName', 'myType', {'other': 'myOther'}),
               ('myName2', 'myType2', {'other2': 'myOther2'}))

def getColumn(self,name,type,**rest):
    pass

def getColumns(self,columns):
    return [self.getColumn(name, type, **rest) for name, type, rest in columns]

rawDescription: Extended call-syntax: Passing parameters


code:
from PyQt5 import QtCore, QtWebSockets,  QtNetwork, QtWidgets

class MyServer(QtCore.QObject):
    def __init__(self, parent):
        super(QtCore.QObject, self).__init__(parent)
        self.clients = []
        self.server = QtWebSockets.QWebSocketServer(parent.serverName(), parent.secureMode(), parent)
        if self.server.listen(QtNetwork.QHostAddress.LocalHost, 1302):
            print('Connected: '+self.server.serverName()+' : '+self.server.serverAddress().toString()+':'+str(self.server.serverPort()))
        else:
            print('error')
        self.server.newConnection.connect(self.onNewConnection)

        print(self.server.isListening())

    def onNewConnection(self):
        self.clientConnection = self.server.nextPendingConnection()
        self.clientConnection.textMessageReceived.connect(self.processTextMessage)

        self.clientConnection.binaryMessageReceived.connect(self.processBinaryMessage)
        self.clientConnection.disconnected.connect(self.socketDisconnected)

        self.clients.append(self.clientConnection)

    def processTextMessage(self,  message):
        if (self.clientConnection):
            self.clientConnection.sendTextMessage(message)

    def processBinaryMessage(self,  message):
        if (self.clientConnection):
            self.clientConnection.sendBinaryMessage(message)

    def socketDisconnected(self):
        if (self.clientConnection):
            self.clients.remove(self.clientConnection)
            self.clientConnection.deleteLater()

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    serverObject = QtWebSockets.QWebSocketServer('My Socket', QtWebSockets.QWebSocketServer.NonSecureMode)
    server = MyServer(serverObject)
    serverObject.closed.connect(app.quit)
    app.exec_()

rawDescription: WebSocket server in PyQt5, apparently correct, however I can not connect


code:
def try_convert_1D_to_2D(my_list, r, c):
    # Pad with Nones to necessary length
    padded = my_list + [None] * max(0, (r * c - len(my_list)))
    # Slice out rows at a time in a listcomp until we have what we need
    return [padded[i:i+c] for i in range(0, r*c, c)]

rawDescription: Appending keyword None to sublists in lists


code:
import datetime

expiration_date=datetime.datetime.now()

if  type(expiration_date) != datetime.datetime:
    expiration_date = None

rawDescription: Checking if an input is in sql alchemy data-type format


code:
df = pd.DataFrame({'int_col':[0,1,2], 'float_col':[0.0,1.1,2.5], 'bool_col':[True, False, True]})
df.dtypes

rawDescription: The nature of pandas DataFrame

description: The nature of pandas DataFrame


code: sorted(a.keys(), key=a.get)[:10]

rawDescription: top -10 unique dictionary keys to be found on the basis of value

description: Top -10 unique dictionary keys to be found on the basis of value


rawDescription: Send email to multiple addresses (using cc) from different domains


code:
import os
rows, columns = os.popen('stty size', 'r').read().split()

rawDescription: How to get console window width in python

description: Get console window width in python


code:
def image_path(instance, filename):
    return instance.id + os.path.splitext(filename)[1]

class Brand(models.Model):
    ...
    logo = models.ImageField(upload_to=image_path, null=True, blank=True)

rawDescription: Django ImageField/FileField save uploaded file using model's pk


code:
sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), 'customjson'))
import json

rawDescription: How to import custom json module instead of the default in python 2.7?

description: Import custom json module instead of the default in python 2.7


rawDescription: Django - sorl-thumbnail - accessing thumbnail image from view functions


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

h = 2     # water depth
D = 0.4   # wave amplitude
k = 1     # wave number

ds = 0.5
x = np.arange(0, 15+ds, ds)
y = np.arange(0, h+ds, ds)
g = 10
w = np.sqrt(g*k*np.tanh(k*h))
T = 2*np.pi/w
xx,yy = np.meshgrid(x,y)
hp = plt.plot(xx[:],yy[:],'x')
plt.axis('equal')
plt.axis([0,15,0,8]) #axis equal
N = 24

fig = plt.gcf()

def update():
    t = 0
    while (True):
        t = t + T/N
        dispx = D/np.sinh(k*h) * np.outer(np.cosh(k*y), np.cos(k*x-w*t))
        dispy = D/np.sinh(k*h) * np.outer(np.sinh(k*y), np.sin(k*x-w*t))
        plt.setp(hp,'XData',xx[:]+dispx[:], 'YData',yy[:]+dispy[:])
        fig.canvas.draw_idle()
        yield

timer = fig.canvas.new_timer(interval=10)
timer.add_callback(update().next)
timer.start()

plt.show()

rawDescription: Python simulation not working

description: Python simulation not working


code:
x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
solve((Eq(2*y+z,1/x), Eq(2*z+y,x)),y,z)

rawDescription: sympy solve function as function

description: Sympy solve function as function


code:
all_cols = np.arange(old_m.shape[1])
cols_to_keep = np.where(np.logical_not(np.in1d(all_cols, cols_to_delete)))[0]
m = old_m[:, cols_to_keep]

rawDescription: Delete columns of matrix of CSR format in Python


code:
import mod
mod.myfunction()

rawDescription: How to use methods defined in a python scipt from a console like ipython

description: Use methods defined in a python scipt from a console like ipython


rawDescription: How to use ndb in App Engine to query all entities of a kind with a certain value in the key pairs?

description: Use ndb in App Engine to query all entities of a kind with a certain value in the key pairs


code: text = next.strip().replace("\n", "").replace("\t", "").replace("\r", "")

rawDescription: Parsing: How do I strip out Unicode Characters?


code:
import numpy as np
from PIL import Image

def set_hue(img, hue):
    """
    img - a PIL (pillow) image
    hue - an integer in the range [0, 255]

    Returns a new PIL (pillow) image in HSV mode
    """
    hsv = img.convert('HSV')
    hsv_ar = np.array(hsv)
    hsv_ar[...,0] = hue
    out = Image.fromarray(hsv_ar, mode='HSV')
    return out

rawDescription: Speed up image manipulation calculation with numpy


code: os.system("script2.py 1")

rawDescription: Run a python script from another python script, passing in args


code: request.GET.get('expr', [])[:1]

rawDescription: on django, request.GET["paramName"] on ajax requests returns lists

description: On django, request.GET["paramName"] on ajax requests returns lists


code:
class Article(models.Model):
    foo = models.CharField(max_length=50)
    bar = models.CharField(max_length=100,blank=True)
    DISPLAY_CHOICES = (
        ('N', 'None'),
        ('C','Carousel'),
        ('M','Marketing'),
        ('F','Featurette')
    )
    display = models.CharField(max_length=1, choices = DISPLAY_CHOICES)
    ARTICLE_TYPE_CHOICES = (
        ('artist', 'Artist'),
        ('venue', 'Venue'),
        ('event', 'Event'),
    )
    type = models.CharField(max_length=32, choices = ARTICLE_TYPE_CHOICES)
    website = models.URLField(max_length=200,blank=True, null=True)
    location = models.CharField(max_length=150, blank=True, null=True)
    map_link = models.URLField(max_length=200,blank=True, null=True)
    time = models.DateTimeField(null=True)
    venue = models.ForeignKey('self', null=True)
    performers = models.ManyToManyField('self', null=True)

def __unicode__(self):
    return self.title

#views.py
def index(request):
    carousel = Article.objects.filter(display='C')
    marketing = Article.objects.filter(display='M')
    featurettes = Article.objects.filter(display='F')
    return render_to_response('frontpage.html',{'carousel': carousel, 'marketing':marketing, 'featurettes': featurettes})

rawDescription: django model inheritance & casting to subtype in a view

description: Django model inheritance & casting to subtype in a view


code:
rarr = np.zeros((r_len, nnn)) # r_len rows, nnn columns
for i in range(nnn):
    rarr[:,i] = r_calc()
numpy.savetxt('test.csv', rarr, delimiter=',')

rawDescription: Python/numpy append arrays, transpose, and save as csv


rawDescription: How do I get the list of attributes of an object not returned by dir

description: Get the list of attributes of an object not returned by dir


code:
ws.Range(ws.Cells(1,1),ws.Cells(8+rows,total_length)).CopyPicture()
wb = excel.Workbooks.Add()
ws = wb.ActiveSheet
ws.Paste()
ws.Shapes('Picture 1').Copy()
img = ImageGrab.grabclipboard()
imgFile = os.path.join(r'C:\Windows\Temp\WS_Template_Images','test.png')
img.save(imgFile)

rawDescription: Python save xlPicture from clipboard

description: Python save xlPicture from clipboard


code:
image = gtk.Image()
img_pixbuf = gtk.gdk.pixbuf_new_from_data(img.tostring(),
                                          gtk.gdk.COLORSPACE_RGB,
                                          False,
                                          img.depth,
                                          img.width,
                                          img.height,
                                          img.width*img.nChannels)

image = gtk.gdk.set_image_from_pixbuf(img_pixbbuf)

rawDescription: How to add opencv window in pygtk?

description: Add opencv window in pygtk


code:
attr = wx.TextAttr()
attr.SetFlags(wx.TEXT_ATTR_TEXT_COLOUR)
r = rtc.GetSelectionRange()
attr.SetFlags(wx.TEXT_ATTR_TEXT_COLOUR)
attr.SetBackgroundColour(colour)
rtc.SetStyle(r, attr)

rawDescription: wxpython RichTextCtrl. How to set a background color to a text selection

description: Wxpython RichTextCtrl. How to set a background color to a text selection


code:
last_heard = db.collection.distinct("coreInfo.last_heard")
result = db.collection.distinct("result")

rawDescription: How to find all values for a specific key in pymongo?

description: Find all values for a specific key in pymongo


code:
def get_d_minus_one_pacific_local_date():
    return datetime.datetime.now(
            pytz.timezone('US/Pacific')).date() - relativedelta(days=1)

def get_relative_date(init=get_d_minus_one_pacific_local_date(), *args, **kwargs):
    return init + datetime.timedelta(*args, **kwargs)

# ...
get_relative_date(days=-7)

rawDescription: Nondeterministic behavior in python's relativedelta


rawDescription: Django - Checking for two models if their primary keys match


code:
with open('ip_list.txt') as f:
    for ip in f.read().splitlines():
        report = do_scan(ip, "-sV")
        if report:
            print_scan(report)

rawDescription: Passing a List of IP address to get port scanned in python (libnmap)


code: content = [x for x in content if not x.startswith('#')]

rawDescription: remove all list elements starting with a hash

description: Remove all list elements starting with a hash


code:
import numpy as np
array = numpy.array((matrix))
answer = np.apply_along_axis(sum,0,array[1::])
my_dict = dict(zip(matrix[0],answer))

rawDescription: I have a list of words. I want to add a counter variable associated with each word. How do I do this?


code:
import sys
' '.join(sys.argv[1:])

rawDescription: Get command line arguments as string

description: Get command line arguments as string


code:
from django.db.models import Lookup

class AbsoluteValueLessThan(Lookup):
    lookup_name = 'lt'

    def as_sql(self, qn, connection):
        lhs, lhs_params = qn.compile(self.lhs.lhs)
        rhs, rhs_params = self.process_rhs(qn, connection)
        params = lhs_params + rhs_params + lhs_params + rhs_params
        return '%s < %s AND %s > -%s' % (lhs, rhs, lhs, rhs), params

AbsoluteValue.register_lookup(AbsoluteValueLessThan)

rawDescription: Creating custom Field Lookups in Django

description: Creating custom Field Lookups in Django


code:
from bs4 import BeautifulSoup
data = 'Glenn Miller & His Orchestra	'
soup = BeautifulSoup(data, "html.parser")
tag = soup.td
tag.get_text()

rawDescription: How do I get all text from within this tag?

description: Get all text from within this tag


code:
def dec2bin(n):
    if n == 0:
        return []
    else:
        r = dec2bin(n//2)
        r.append(n%2)
        return r

print(dec2bin(10))
print(dec2bin(42))

rawDescription: Converting an integer number into a binary number using recursion