code:
#add noise by 0
a=num.array([7,1,10,0,5,4,5,0,9,9,3,3])
b=num.array([10,9,3,0,4,7,7,0,8,1,10,9])
a=a.reshape(12,1)
b=b.reshape(12,1)
maa = ma.masked_array(a, mask=[0, 0, 0, 1,0, 0,0,1,0,0,0,0])
mbb = ma.masked_array(b, mask=[0, 0, 0, 1,0, 0,0,1,0,0,0,0])
maa=ma.compressed(maa).reshape(10,1)
mbb=ma.compressed(mbb).reshape(10,1)
regr = linear_model.LinearRegression()
regr.fit(maa,mbb)
regr.coef_ #-0.616504854
regr.intercept_ #10.25242718

rawDescription: How to mask clouds from Python numpy array for a linear regression model?

description: Mask clouds from Python numpy array for a linear regression model


code:
import wx
import sys
username = ""
from wx.lib.pubsub import pub

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, title = 'Application Title',style = wx.SYSTEM_MENU)

        pub.subscribe(self.myListener, "update_frame")

        panel = wx.Panel(self)
        menubar = wx.MenuBar()
        panel.SetBackgroundColour((200,200,200))
        vbox = wx.BoxSizer(wx.HORIZONTAL)
        midPan = wx.Panel(panel)
        midPan.SetBackgroundColour((100,0,0))
        pan2 = wx.Panel(panel)
        pan2.SetBackgroundColour((0,100,0))
        vbox.Add(pan2, 1, wx.EXPAND | wx.ALL)
        vbox.Add(midPan, 5, wx.EXPAND | wx.ALL)
        hbox = wx.BoxSizer(wx.VERTICAL)
        hbox1=wx.BoxSizer(wx.VERTICAL)
        h1=wx.Panel(midPan)
        h1.SetBackgroundColour((200,0,100))
        h2=wx.Panel(midPan)
        h2.SetBackgroundColour((0,100,200))
#######################################################################
        self.text1 = wx.StaticText(h1, label="Welcome ") #insert the global variable in this label after the user has successfully logged in
        text2 = wx.StaticText(h1, label="Label2")
        hbox.Add(h1,3,wx.EXPAND|wx.ALL,20)
        hbox.Add(h2,1,wx.EXPAND|wx.ALL,20)
        hbox1.Add(self.text1,1,wx.ALIGN_LEFT)
        hbox1.Add(text2,1,wx.ALIGN_RIGHT)
        panel.SetSizer(vbox)
        midPan.SetSizer(hbox)
        h1.SetSizer(hbox1)
        self.statusbar = self.CreateStatusBar()
        self.SetMenuBar(menubar)
        self.Centre()
        self.Maximize()
        self.Show(True)
        frame = LoginFrame(self)
        frame.Show(True)
        frame.MakeModal(True)

    #----------------------------------------------------------------------
    def myListener(self, msg):
        """"""
        self.text1.SetLabel("Welcome %s" % msg)

    def OnExit(self, e):
        self.Close()

class LoginFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent,style=wx.DEFAULT_FRAME_STYLE & ~(wx.RESIZE_BORDER | wx.MAXIMIZE_BOX | wx.CLOSE_BOX | wx.MINIMIZE_BOX ), title = "System Login")
        self.panel = wx.Panel(self)
        self.userlabel = wx.StaticText(self.panel, label="Username:")
        self.passlabel = wx.StaticText(self.panel, label="Password:")
        self.userbox = wx.TextCtrl(self.panel, size=(140, -1))
        self.passbox = wx.TextCtrl(self.panel, size=(140, -1), style=wx.TE_PASSWORD)
        self.login = wx.Button(self.panel, label="Login")
        self.exit = wx.Button(self.panel, label="Exit")
        self.Centre()
        self.windowSizer = wx.BoxSizer()
        self.windowSizer.Add(self.panel, 1, wx.ALL | wx.EXPAND)
        self.sizer = wx.GridBagSizer(5, 5)
        self.sizer.Add(self.userlabel, (0, 0))
        self.sizer.Add(self.userbox, (0, 1))
        self.sizer.Add(self.passlabel, (1, 0))
        self.sizer.Add(self.passbox, (1, 1))
        self.sizer.Add(self.login, (2, 0))
        self.sizer.Add(self.exit, (2, 1))
        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, 1, wx.ALL | wx.EXPAND, 5)
        self.panel.SetSizerAndFit(self.border)
        self.SetSizerAndFit(self.windowSizer)
        self.login.Bind(wx.EVT_BUTTON, self.OnLogin)
        self.exit.Bind(wx.EVT_BUTTON, self.onClose)
        self.Bind(wx.EVT_CLOSE, self.onClose)

    def OnLogin(self, e):
        #db = MySQLdb.connect("localhost","root","","test" )
        #cursor = db.cursor()
        username = self.userbox.GetValue()
        password = self.passbox.GetValue()
        #self.MakeModal(False)

        self.Close()
        #try:
            #cursor.execute("SELECT * FROM useraccounts WHERE username=%s" ,username)
            #data = cursor.fetchall()
            #for row in data:
                #dbpass = row[2]
            #if dbpass == password:
                #
                #e.Skip()
                #self.Close()
                #wx.MessageBox('You are now logged in', 'Info', wx.OK | wx.ICON_INFORMATION)
            #else:
                #wx.MessageBox('Username or Password is incorrect', 'Info', wx.OK | wx.ICON_INFORMATION)
        #except:
            #wx.MessageBox('Username or Password is incorrect', 'Info', wx.OK | wx.ICON_INFORMATION)

    def onClose(self,e):
        username = self.userbox.GetValue()
        pub.sendMessage("update_frame", msg=username)
        self.Destroy()

if __name__ == '__main__':
    app = wx.App()
    MainFrame()
    app.MainLoop()

rawDescription: Global variable between frames in wxPython


code:
a='math'
import importlib
i=importlib.import_module(a)
i.sqrt(4)

rawDescription: In python, How to import a module by user input string of a module name


rawDescription: How to select ticks at n-positions in a log plot?

description: Select ticks at n-positions in a log plot


code:
import sys
from PySide.QtGui import *
from PySide.QtCore import *

class Window(QMainWindow):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.button = QPushButton()
        self.button.setText("Test")
        self.setCentralWidget(self.button)

    def GetButton(self):
        return self.button

class MyController(QObject):
    def __init__(self, parent=None):
        super(MyController, self).__init__(parent)

        self.button = parent.GetButton() #(returns QPushButton)
        self.button.clicked.connect(self.button_clicked)

    @Slot()
    def button_clicked(self):
        print('button clicked: ', self.sender())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Window()
    controller = MyController(window)
    window.show()
    app.exec_()
    sys.exit(0)

rawDescription: QPushButton won't fire clicked slot (method of QObject)


rawDescription: Replace slice of a numpy array with values from another array


code: url.find(lambda tag: tag.name == 'span' and tag.get('class', []) == ['bday'])

rawDescription: multiple values for class attribute

description: Multiple values for class attribute


code:
import numpy as np
import math

#setup the desired calibration transformation (hmd orientation that will result in looking straight ahead

#Euler angles for the hmd at desired "zero" orientation
a0 = -177.9*math.pi/180
b0 = 31.2*math.pi/180
g0 = 90.4*math.pi/180

#make the matrices
Ra0 = np.matrix([[1,0,0],[0, float(math.cos(a0)),float(-1*math.sin(a0))],[0,float(math.sin(a0)),float(math.cos(a0))]],dtype=np.float)
Rb0 = np.matrix([[math.cos(b0),0,math.sin(b0)],[0,1,0],[-1*math.sin(b0),0,math.cos(b0)]],dtype=np.float)
Rg0 = np.matrix([[math.cos(g0),-1*math.sin(g0),0],[math.sin(g0),math.cos(g0),0],[0,0,1]],dtype=np.float)

#the hmd rotation matrix in the "zero" orientation
global RhmdU0
RhmdU0 = Ra0*Rb0*Rg0
#the view orientation when the hmd is in the "zero" orientation (basically a zero degree turn about the Z axis)
global RdU0
RdU0 = np.matrix([[1,0,0],[0,1,0],[0,0,1]],dtype=np.float)

#this can be called in a loop, inputs are Euler angles of the hmd
def InverseK(at,bt,gt):
    global RdU0
    global RhmdU0

    #given 3 Euler sequence of the hmd in universal space, determine the viewpoint
    Rat = np.matrix([[1,0,0],[0, float(math.cos(at)), float(-1*math.sin(at))],[0,float(math.sin(at)),float(math.cos(at))]],dtype=np.float)
    Rbt = np.matrix([[math.cos(bt),0,math.sin(bt)],[0,1,0],[-1*math.sin(bt),0,math.cos(bt)]],dtype=np.float)
    Rgt = np.matrix([[math.cos(gt),-1*math.sin(gt),0],[math.sin(gt),math.cos(gt),0],[0,0,1]],dtype=np.float)

    RhmdUt = Rat*Rbt*Rgt

    RdUt = RhmdUt*RhmdU0.transpose()*RdU0

    #do inverse K to get euler sequence out:
    beta = math.atan2(RdUt[0,2],math.sqrt(RdUt[1,2]**2+RdUt[2,2]**2))
    alpha = math.atan2(-1*RdUt[1,2]/math.cos(beta),RdUt[2,2]/math.cos(beta))
    gamma = math.atan2(-1*RdUt[0,1]/math.cos(beta),RdUt[0,0]/math.cos(beta))

    return(alpha,beta,gamma)

rawDescription: Offset Euler Angles using rotation matrix


code:
import urlparse
url1 = 'http://google.com/?a=1&b=2'
url2 = 'http://google.com/?b=2&a=1'
# parse url ignoring query params order
def parse_url(url):
  u = urlparse.urlparse(url)
  q = u.query
  u = urlparse.urlparse(u.geturl().replace(q, ''))
  return (u, urlparse.parse_qs(q))

parse_url(url1)
def assert_url_equals(url1, url2):
  return parse_url(url1) == parse_url(url1)
assert_url_equals(url1, url2)

rawDescription: Looking for assertURLEquals

description: Looking for assertURLEquals


code:
import zlib
zlib.ZLIB_VERSION

rawDescription: Tell what version of zlib python was built with


code:
[expression(x, y) for x in expression_that_creates_a_container
                  for y in some_other_expression_that_creates_a_container(x)
                  if predicate(y, x)]

rawDescription: Naming variables within nested list comprehensions in Python?


code:
li = ['paris', 'paris', 'marseille', 'marseille', 'marseille', 'paris', 'paris', 'paris', 'lille', 'marseille', 'toulouse', 'marseille', 'lille', 'mont saint martin', 'mont de marsan', 'lyon', 'lyon', 'lille', 'lille', 'lyon']
[c for e in li for c in e.split(" ")]

rawDescription: Python regroup item in dictionary

description: Python regroup item in dictionary


code:
def read_from_hex_offset(file, hex_offset):
    """Fetch a single byte (or character) from file at hexadecimal offset hex_offset"""
    offset = int(hex_offset, base=16)
    file.seek(offset)
    return file.read(1)

rawDescription: Python 2.7.11: How to read (big) binary file from/at hex offset


code:
a = np.array([1, 0, 2, 1])
z = np.zeros(12, dtype=int).reshape(4,3)
z[np.arange(a.size), a] = 1

rawDescription: Expand numpy array of indices into a matix


code:
import re
def extract_data2(s):
    pattern = re.compile(r"""\|\s*                 # opening bar and whitespace
                             '(?P<name>.*?)'       # quoted name
                             \s*\|\s*(?P<n1>.*?)   # whitespace, next bar, n1
                             \s*\|\s*(?P<n2>.*?)   # whitespace, next bar, n2
                             \s*\|""", re.VERBOSE)
    match = pattern.match(s)

    name = match.group("name")
    n1 = float(match.group("n1"))
    n2 = float(match.group("n2"))

    return (name, n1, n2)

rawDescription: Python Regex to Parse String and Return Tuple


code:
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x -= 10

            if event.key == pygame.K_RIGHT:
                lead_x +=10

    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black,[lead_x,lead_y,10,100])
    pygame.display.update()

rawDescription: Background Color Assistance

description: Background Color Assistance


rawDescription: How to covert json string to avro in python?

description: Covert json string to avro in python


code:
import random

class Node(object):

    def __init__(self, other=None):
        self.other = other
        self.next = None # next -> None
        self.previous = None # previous -> None

    def __str__(self):
        return str(self.other)

class List(object):

    def __init__(self):
        self.head = None
        self.tail = None

    def append(self, value):
        newNode = Node(value)

        if self.head == None:
            self.head = newNode
            self.tail = newNode

        else:
            self.tail.next = newNode
            newNode.previous = self.tail
            self.tail = newNode

    def __str__(self):
        someString = ""
        current = self.head
        while current != None:
            someString = someString + current.other
            current = current.next
        return someString # declease indent (get it out of the while loop)

class Queue(List):

    def enqueue(self, value):
        self.append(value)

    def dequeue(self):
        self.temp = self.head
        self.head = self.head.next
        if self.head is None: # add
            self.tail = None # add
        else: # add
            self.head.previous = None # add (cut the link to the dequeued node)
        return self.temp # temp -> self.temp

class Stack(List):

    def push(self, value):
        self.append(value)

    def pop(self):
        self.temp = self.tail
        self.tail = self.tail.previous
        if self.tail is None: # add
            self.head = None # add
        else: # add
            self.tail.next = None # add (cut the link to the popped node)
        return self.temp

def main():

    list1 = List()
    for i in range(0, 100):
        list1.append(str(random.randrange(0, 100)))
        print(list1)

    queue = Queue()
    for i in range(0, 100):
        queue.enqueue(str(random.randrange(0, 100)))

    for i in range(0, 100):
        print(queue.dequeue()) # dequeue -> dequeue()

    # I have no idea why this for is here.
    # for i in range(0, 10):
    print("----------------------------------------") # adjust indent
    stack = Stack() # adjust indent
    for i in range(0, 100):
        stack.push(str(random.randrange(0, 100)))

    for i in range(0, 100):
        print(stack.pop())

if __name__ == "__main__":
    main()

rawDescription: Stack and queue error in my program

description: Stack and queue error in my program


rawDescription: How to print on the same line in python without using ,

description: Print on the same line in python without using ,


code:
from celery.task import task
from celery.exceptions import SoftTimeLimitExceeded

@task
def mytask():
    try:
        do_work()
    except SoftTimeLimitExceeded:
        clean_up_in_a_hurry()

rawDescription: Is there distributed task queue in Python that enables me to kill hanging tasks that are not willing to cooperate


code:
from django.core import serializers
data = serializers.serialize("xml", SomeModel.objects.all())

rawDescription: Creating xml file in django

description: Creating xml file in django


code:
var_list = ['var1', 'var2', 'var3'] # create list of variable string names

for var in var_list: # iterate over list of variable names

    try:
        # use exec to execute assignments, assuming attribute exists
        exec('{0} = {1}'.format(var, getattr(self, var)))

    except AttributeError: # catch the Exception if the attribute does not exist

        exec('{0} = None'.format(var)) # set var to some default value, whatever
                                       # is convenient for later code to check
                                       # for and handle

rawDescription: For loop and Storing variables

description: For loop and Storing variables


code:
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QTableView, QApplication
import sys

app = QApplication(sys.argv)

db = QSqlDatabase.addDatabase("QMYSQL")
db.setHostName("localhost")
db.setDatabaseName("usrdb")
db.setUserName("usr")
db.setPassword("passwrd")
db.open()

testModel = QSqlTableModel()
testModel.setTable("test")
testModel.setEditStrategy(QSqlTableModel.OnFieldChange)
testModel.select()

testView = QTableView()
testtView.setModel(testModel)

app.exec_()

rawDescription: PyQt5 QSqlTableModel not updating changes to database


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

def dot(v1, v2):
    return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z

def cross(v1, v2):
    return Vector(v1.y * v2.z - v1.z * v2.y,
                  v1.z * v2.x - v1.x * v2.z,
                  v1.x * v2.y - v1.y * v2.x)

def det(v1, v2, v3):
    return dot(v1, cross(v2, v3))

class Pair:
    def __init__(self, v1, v2):
        self.v1 = v1
        self.v2 = v2

# Returns True if the great circle segment determined by s
# straddles the great circle determined by l
def straddles(s, l):
    return det(s.v1, l.v1, l.v2) * det(s.v2, l.v1, l.v2) < 0

# Returns True if the great circle segments determined by a and b
# cross each other
def intersects(a, b):
    return straddles(a, b) and straddles(b, a)

# Test. Note that we don't need to normalize the vectors.
print(intersects(Pair(Vector(1, 0, 1), Vector(-1, 0, 1)),
                 Pair(Vector(0, 1, 1), Vector(0, -1, 1))))

rawDescription: Intersections between Geodesics (shortest distance paths) on the surface of a sphere


rawDescription: Hard copying dicts in a list

description: Hard copying dicts in a list


code:
class Entry(models.Model):
    name = models.CharField()

class EntryForm(forms.ModelForm):
    class Meta:
        model = Entry

for line in lines:
    data = parse_line(line)
    form = EntryForm(data)
    if form.is_valid():
        form.save()
    else:
        print("form not valid: %s" % form.errors)

rawDescription: Is this good practice for inserting contents of a CSV file in database using Django?


code:
for line in phonenumbers:
    if number in line:
        print (line)
        break
else:
    print ("phone number not found")

rawDescription: Converting txt file to list and returning line after user input search


code:
def mergesort(arr):
    if len(arr) == 1:
        return arr

    else:
        mid = len(arr)//2
        left = arr[0:mid]
        right = arr[mid:len(arr)]

        sorted = []
        i = 0
        j = 0
        left = mergesort(left) #left is now sorted
        right = mergesort(right)

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                sorted.append(left[i])
                i += 1
            else:
                sorted.append(right[j])
                j += 1

        while i < len(left):
            sorted.append(left[i])
            i += 1

        while j < len(right):
            sorted.append(right[j])
            j += 1

        return sorted

print (mergesort([8,7,6,5,4,3,2,1,3]))

rawDescription: Why doesn't this python implementation of mergesort work?


code:
import time, datetime
x_range = (
    time.mktime(datetime.datetime(2014, 1, 1).timetuple())*1000,
    time.mktime(datetime.datetime(2016, 1, 1).timetuple())*1000
)
p = bk.figure(
    title='title', tools=TOOLS,x_axis_type="datetime",
    plot_width=600, plot_height=300, x_range=x_range
)

rawDescription: Display only part of Y-axis on Bokeh

description: Display only part of Y-axis on Bokeh


code:
import subprocess

def bash_command(cmd):
    subprocess.Popen(cmd, shell=True, executable='/bin/bash')

bash_command('[your_command]')

rawDescription: Linux commands in Python subprocesses

description: Linux commands in Python subprocesses


code: result=[dictionary[k] for k in keys if k in dictionary]

rawDescription: How to get dictionary values having its keys as a list

description: Get dictionary values having its keys as a list


code:
import soundfile as sf
import sounddevice as sd

weight = 1.7

data, fs = sf.read('myfile.wav')
sd.play(data * weight, fs, blocking=True)

rawDescription: Increase volume before streaming with Python


code:
def login(login_str):
    conn = socket.create_connection([host, port])

    for i in login_str:
        conn.sendall(i + line_term)

    conn.send(line_term)

    # Wait until the other end has finished sending data

    while conn.recv(1024):
      pass

    # Everything works, as soon as I uncomment this line below :/
    # gevent.sleep(1)
    conn.close()

rawDescription: Close TCP socket in the Greenlet only after successful transfer


code:
#!/usr/bin/python
import csv

def navigation(iterable):
    iterator = iter(iterable)
    prev = None
    item = iterator.next()

    for next in iterator:
        yield (prev, item, next)
        prev = item
        item = next

    yield (prev, item, None)

with open('input.csv') as csv_input:
    with open('output.csv', 'w') as csv_output:
        old_data = []
        new_data = []

        for row in csv.reader(csv_input):
            old_data += row

        for index, (_prev, item, _next) in enumerate(navigation(old_data)):
            if _next != item:
                if _prev != item:
                    row = [item, 'missing value']
                    new_data.append(row if index % 2 == 0 else row[::-1])
            else:
                new_data.append([item, _next])

        writer = csv.writer(csv_output, delimiter=',', lineterminator='\n')
        writer.writerows(new_data)

rawDescription: line-up data in two colums of a csv file using python

description: Line-up data in two colums of a csv file using python


code:
@property
def my_attribute():
    if not hasattr(self, '_my_attribute'):
        do_expensive_operation_to_get_attribute()
    return self._my_attribute

rawDescription: Lazy loading of attributes

description: Lazy loading of attributes


code: [i for i, elem in enumerate(bool_list, 1) if elem]

rawDescription: Get the indexes of truthy elements of a boolean list as a list/tuple


code:
def __new__(cls, baseunit='1', num=1.):
    return super(Unit, cls).__new__(self, num)

def __init__(self, baseunit='1', num=1.):
    """set up base unit"""

    self.baseunit = baseunit

    for _key,_val in self.baseconv.items():
        if baseunit in _val.dtype.names:
            utype = _key
            break
    else:
        raise TypeError('Unit not defined: {:s}'.format(baseunit))
    self.conv = np.array(tuple(np.array(self.baseconv[utype].tolist())
                            / self.baseconv[utype][baseunit]),
                        dtype=self.baseconv[utype].dtype)

rawDescription: How to correctly work with derived immutable class?

description: Correctly work with derived immutable class


code:
def square_wrapper(i):
    result = [None]
    cProfile.runctx("result[0] = square(i)", globals(), locals(), "file_%d" % i)
    return result[0]

rawDescription: Profiling a python multiprocessing pool

description: Profiling a python multiprocessing pool


code:
with open('textfile.txt', 'rt') as inf:
    for linenum, line in enumerate(inf, start=1):
        filename = 'string {}.txt'.format(linenum)
        with open(filename, 'wt') as outf:
            outf.write(line)

rawDescription: Divide one text file to multiple text file accord to how many string in python


rawDescription: Can Selenium web driver have access to javascript global variables?


code:
for tup in list:
    a,b,c,d,e = tup

rawDescription: iterate over list of tuples in two notations

description: Iterate over list of tuples in two notations


code:
def peaks(L):
    answer = []
    a,b,c = itertools.tee(L, 3)
    next(b)
    next(c)
    next(c)
    for first, second, third in zip(a,b,c):
        if first <= second >= third:
            answer.append(second)
    return answer

In [61]: peaks([0,1,-1,3,8,4,3,5,4,3,8])
Out[61]: [1, 8, 5]

In [62]: peaks([5,2,4,9,6,1,3,8,0,7])
Out[62]: [9, 8]

rawDescription: How to use iter and next in a function to return a list of peaks?

description: Use iter and next in a function to return a list of peaks


code: centers_x = [np.mean([q[0] for q in coordinates if q[-1]==n]) for n in range(3)]

rawDescription: condensing serial for loops

description: Condensing serial for loops


rawDescription: How to set Selenium Python WebDriver default timeout?

description: Set Selenium Python WebDriver default timeout


code:
import itertools
keys = [1, 2, 3, 4, 5, 6]
values = [7, 8, 9]
d = [dict(zip(kperm, values)) for kperm in itertools.permutations(keys, len(values))]
len(d)
d[:10]

rawDescription: All possible permutations of dictionaries combinations out of 2 lists


code: locs = (np.diff(np.sign(np.diff(v_1))) < 0).nonzero()[0] +1

rawDescription: How can I find where a vector value passes a threshold and the n+1 value meets a condition?

description: Find where a vector value passes a threshold and the n+1 value meets a condition


code:
def importImage(fileName):
    with open(fileName, 'rb') as imgText:
        return imgText.read()

screenSurf = initializeScreen(800,600)
textOfImg = importImage(r'path/to/file')

with open(r'path/to/otherfile', 'wb') as newFile:
    newFile.write(textOfImg)

newimgSurf = pygame.image.load(r'path/to/otherfile')
screenSurf.blit(newimgSurf, (0,0))
pygame.display.flip()

rawDescription: Python/Pygame Converting a .jpg to a string and back to a .jpg: Corruption Issue


code: sum(n == fresh for n in buckets['actual'][e])

rawDescription: Count all that satisfy a condition in Python


code:
if route.distance(p) <= r:
    return route.project(p)

rawDescription: Finding the distance of a coords from the begning of a route in Python


code:
from bs4 import BeautifulSoup
txt = """<ENAMEX TYPE="PERSON">Edward R. Kimmel</ENAMEX>, one of Admiral <ENAMEX TYPE="PERSON">Jack</ENAMEX>'s twosurviving sons and..."""
soup = BeautifulSoup(txt,"html.parser")
for i in soup.findAll(attrs={'type' : 'PERSON'}):
    print(i.text)

rawDescription: information extraction of NAMED ENTITIES python 2.7

description: Information extraction of NAMED ENTITIES python 2.7


code:
def myslugify(value):
    return slugify(value.replace(":", "-"))

rawDescription: Django, how to override slugify function


code:
import re
import csv
import time
import StringIO

print(time.ctime())

input_name = "C:/Users/User/Desktop/File with No Extension That's Very Similar to CSV"
output_name = "C:/Users/User/Desktop/testoutput.csv"

with open(input_name, 'r') as f_input, open(output_name, 'wb') as f_output:
    # Read whole file in
    all_input = f_input.read()

    # Extract interesting lines
    ab_input = re.findall(r'Point A(.*?)Point B', all_input, re.DOTALL)[0]

    # Convert into a file object and parse using the CSV reader
    fab_input = StringIO.StringIO(ab_input)
    csv_input = csv.reader(fab_input)
    csv_output = csv.writer(f_output)

    # Iterate a row at a time from the input
    for input_row in csv_input:
        # Skip any empty rows
        if input_row:
            # Write row at a time to the output
            csv_output.writerow(input_row)

print(time.ctime())

rawDescription: Extracting Rows of Data from a CSV-like File Using Python


code:
def _define_checker(name, args, contract, path):
    """Define a function that does contract assertion checking.

    args is a string argument declaration (ex: 'a, b, c = 1, *va, **ka')
    contract is an element of the contracts list returned by parse_docstring
    module is the containing module (not parent class)

    Returns the newly-defined function.

    pre::
        isstring(name)
        isstring(args)
        contract[0] in _CONTRACTS
        len(contract[2]) > 0
    post::
        isinstance(__return__, FunctionType)
        __return__.__name__ == name
    """
    output = StringIO()
    output.write('def %s(%s):\n' % (name, args))
    # ttw001... raise new exception classes
    ex = _EXCEPTIONS.get(contract[0], 'ContractViolationError')
    output.write('\tfrom %s import forall, exists, implies, %s\n' % \
                (MODULE, ex))
    loc = '.'.join([x.__name__ for x in path])
    for c in contract[2]:
        output.write('\tif not (')
        output.write(c[0])
        # jlr001: adding conidition statement to output message, easier debugging
        output.write('): raise %s("%s", %u, "%s")\n' % (ex, loc, c[1], c[0]))
    # ...ttw001

    # ttw016: return True for superclasses to use in preconditions
    output.write('\treturn True')
    # ...ttw016

    return _define(name, output.getvalue(), path[0])

rawDescription: How do I know which contract failed with Python's contract.py?

description: Know which contract failed with Python's contract.py


code:
class ForkingMixIn:

    """Mix-in class to handle each request in a new process."""

    timeout = 300
    active_children = None
    max_children = 40

rawDescription: Strange behaviour in Python SocketServer


code:
topush = {
    'cl1': {'ansible_host': ['172.17.0.200']},
    'cl3': {'ansible_host': ['172.17.0.202']}
}

def gen_host(data, group):
    ''' Takes a dictionary. It creates a INI file'''

    with open('host_test', 'w') as outfile:
        outfile.write("[{}]\n".format(group))

        for key, value in data.iteritems():
            outfile.write("{} ansible_host={}\n".format(key, value['ansible_host']))

if __name__ == "__main__":
    gen_host(topush, 'win_clones')

rawDescription: Python: write an INI file for Ansible

description: Python: write an INI file for Ansible


code:
class Link(models.Model):
    ...
    last_updated = models.DateTimeField(auto_now_add = True)
    ...

rawDescription: How do I write this insert statement in Django?

description: Write this insert statement in Django


code:
from django.db.models import Q

def search(request):
    if request.method == "GET":
      search_terms = request.GET['title']
      search_terms = search_terms.split(',')
      #get rid of duplicates
      search_terms = set(search_terms)
      queryargs = [Q(title__contains=i) for i in search_terms]
      jobs = Job.objects.filter(*queryargs)

rawDescription: Searching features implementation in django project


code:
example = [12, 3, 4]
print(example[0] + example[1]) #15 (12 + 3)
print(example[2] - example[1]) #1 (4 - 3)
print(sum(example)) # 19 (12 + 3 + 4)

rawDescription: Python: How can I use a specific integer from a list?


code:
import wx

class MainWindow(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.panel = wx.Panel(self)
        self.text = wx.TextCtrl(self.panel)
        self.text.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown)
        self.text.Bind(wx.EVT_KEY_UP, self.OnKeyUp)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.text, 1)

        self.panel.SetSizerAndFit(self.sizer)
        self.Show()

    def OnKeyDown(self, e):
        code = e.GetKeyCode()
        if code == wx.WXK_ESCAPE:
            print("Escape")
        if code == wx.WXK_UP:
            print("Up")
        if code == wx.WXK_DOWN:
            print("Down")
        e.Skip()

    def OnKeyUp(self, e):
        code = e.GetKeyCode()
        if code == wx.WXK_RETURN:
            print("Return")
        e.Skip()

app = wx.App(False)
win = MainWindow(None)
app.MainLoop()

rawDescription: wxPython: binding wx.EVT_CHAR_HOOK disables TextCtrl backspace

description: WxPython: binding wx.EVT_CHAR_HOOK disables TextCtrl backspace


code:
from scipy.stats import mannwhitneyu
a = np.arange(100)
b = np.arange(100)
np.random.shuffle(b)
np.corrcoef(a,b)
mannwhitneyu(a, b)
mannwhitneyu(a, a)

rawDescription: How to use Mann-Whitney U test in learning

description: Use Mann-Whitney U test in learning


code: b = models.CharField(max_length=7, default='0000000', editable=False)

rawDescription: Default value for field in Django model

description: Default value for field in Django model


code:
def parse(self, response):
    for sel in response.xpath('//table[@class]/tbody/tr'):
        item = SET()
        item['title'] = sel.xpath('td[1]/a[contains(@href,"ssoPageId")]/text()').extract()
        item['open'] = sel.xpath('td[3]/text()').extract()
        item['hi'] = sel.xpath('td[4]/text()').extract()
        item['lo'] = sel.xpath('td[5]/text()').extract()
        item['last'] = sel.xpath('td[6]/text()').extract()
        item['bid'] = sel.xpath('td[9]/text()').extract()
        item['ask'] = sel.xpath('td[10]/text()').extract()
        item['vol'] = sel.xpath('td[11]/text()').extract()
        urll = response.xpath('//table[@class]/tbody/tr/td[1]/a[contains(@href,"ssoPageId")]/@href').extract()
        urls = ["http://marketdata.set.or.th/mkt/" + i for i in urll]
        for url in urls:
            yield scrapy.Request(url,
                                 callback=self.parse_following_urls,
                                 meta={'item': item})

rawDescription: Scrape information from Scraped URL

description: Scrape information from Scraped URL


code:
import numpy as np

#write
bintest=open('binfile.in','ab')
a=np.array([[1.0,2.0],[3.0,2.0]])
a.tofile(bintest)
bintest.close()

#read
array=np.fromfile('binfile.in',dtype=np.float64)

rawDescription: How to make an equivalent to Fortran's 'access=stream' in python

description: Make an equivalent to Fortran's 'access=stream' in python


code: os.system("start /wait cmd /c {command}")

rawDescription: Python: Start new command prompt on Windows and wait for it finish/exit


code:
from Tkinter import*

root = Tk()

class GUI():
    def __init__(self, root, x, y):
        self.root=root
        self.create_button(x, y)

    def create_button(self, x, y):
        #Creates buttons
        self.button = Button(root)
        self.button.config(text="%s-%s" % (x, y))
        self.button.config(command=self.go_away)
        self.button.grid(column=x,row=y)

    def create_label(self, info, posit):
        #Creates labels
        self.label = Label(root)
        self.label.config(text=info)
        self.label.grid(column=posit[0],row=posit[1])

    def go_away(self):
        #Makes buttons disappear
        #self.button.grid_forget()
        self.button.destroy()

    def come_back(self):
        #Makes buttons reappear
        self.button.grid()

    def user_input(self,row,column):
        print("Row:", row)
        print("Column:", column)
        self.configure(row,column)
        print(self.button)

class Board():
    def __init__(self):
        self.buttons=[]
        self.create_board()
        Label(root, text="click on a button\nto destroy it",
              bg="lightblue"). grid(row=10, column=0,
              columnspan=3, sticky="nsew")

    def create_board(self):
        for x in range(3):
            for y in range(3):
                self.buttons.append(GUI(root, x, y))
##                cmd = lambda row=y, column=x: self.user_input(row,column)
##                self.create_button("   ", cmd, [x,y])

board = Board()
root.mainloop()

rawDescription: How to hide individual widgets created by a loop in python

description: Hide individual widgets created by a loop in python


code:
class SoftwarePackage:
    def __init__(self, name, description, order_of_installation, url):
        self.name = name
        self.description = description
        self.order_of_installation = order_of_installation
        self.url = "http://localhost:9090/api/software_package"

    def create(self):
        post_data = {"name": self.name, "description": self.description,
                     "order_of_installation": self.order_of_installation}
        post_data = json.dumps(post_data)
        req = urllib2.Request(self.url, post_data)

        req.add_header('Content-Type', 'application/json')
        return urllib2.urlopen(req, post_data)

rawDescription: how to call a class method in python

description: Call a class method in python


code:
from twisted.web import server, resource
from twisted.internet import reactor

class Simple(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        request.redirect("http://www.google.com")
        request.finish()
        return server.NOT_DONE_YET

site = server.Site(Simple())
reactor.listenTCP(8080, site)
reactor.run()

rawDescription: twisted location header redirect

description: Twisted location header redirect


code:
import datetime as DT
import time
d = ['09-2007', '10-2007', '03-2011', '05-2011']
[time.mktime(DT.datetime.strptime(dstr, '%m-%Y').timetuple())*1000 for dstr in d]

rawDescription: Convert date to json date string in python


code:
s = load_up_users_dictionary()

for word in text_to_check:
    if word not in s:
        new_words = s.suggest( word )
        replace_incorrect_word( word, new_words[0] )#Pick the first word from the returned list.

rawDescription: Autocorrect Spell Checker

description: Autocorrect Spell Checker


code:
choice_indices = [1, 2, 3, 4]
for idx in choice_indices:
  mask = df['choice-index'] == idx
  result_column = 'value-%d' % (idx)
  df.loc[mask, 'value'] = df.loc[mask, result_column]

rawDescription: Speeding up Pandas apply function

description: Speeding up Pandas apply function


code:
import re
re.sub(r'\b[a-z]', lambda m: m.group().upper(), 'home swe eeeet home')
re.sub(r'\b[a-z]', lambda m: m.group().upper(), 'heLLo OoO ooo ')

rawDescription: How to capitalize each word after a space leaving the rest of it as is and preserve the space in the end if it exists

description: Capitalize each word after a space leaving the rest of it as is and preserve the space in the end if it exists


code: from fruit_pkg import count_fruits

rawDescription: Python import for testing within same package


code:
lhs = roi[roi['zscore']>CUTOFF]
rhs = control[control['zscore']<CUTOFF]

combined = lhs.merge(rhs, on='gene', how='inner')

rawDescription: Pandas; Select rows in one data frame based on this data frame


code:
def get_names( file ):
    savenext = False
    with open("userdata.txt", "rt") as file:
        for line in file:
            if savenext == True:
                students= line
                savenext == False

            if "UserDone" in line:
                savenext = True

rawDescription: I need to create a list of users from a text file


code:
'''app.py

Usage:
  app.py -a ARG ... -b FILE ...
  app.py (-h | -v)

'''
from docopt import docopt
args = docopt(__doc__, version='1.0')
# now do something based on the value of args dict

rawDescription: In Python, is there a better way to deal with command line options when each option could have several arguments


code:
urlpatterns = patterns('',
    url(r'^', include('polls.urls', namespace="polls")),
    ...
)

rawDescription: Django urls.py only one app

description: Django urls.py only one app


code: conn.connect(wait=True, header = {'client-id': 'myhostname' })

rawDescription: stomp.py based durable client fills up subscribers list in ActiveMQ

description: Stomp.py based durable client fills up subscribers list in ActiveMQ


code:
import numpy as np
import pylab as plt

# Create random matrix, save it to a text file
N = 90
A = np.random.random((N,N))
np.fill_diagonal(A,.95)
np.savetxt("z.txt",A)

# Load the data
A = np.loadtxt("z.txt")

# Apply a mask so values below .9 don't show
A[A<.9] = None

# Scale the values from .9 to 1.0 using vmin,vmax
plt.imshow(A, interpolation='nearest', vmin=.9,vmax=1.0,cmap=plt.cm.jet)
plt.colorbar()
plt.show()

rawDescription: tweaking colours and scales of heatmap in R

description: Tweaking colours and scales of heatmap in R


code:
act = QtGui.QAction("Action", self)
act.triggered.connect(self.on_triggered)

act = QtGui.QAction("Action", self, triggered=self.on_triggered)

act = QtGui.QAction("Action", self)
act.pyqtConfigure(triggered=self.on_triggered)

rawDescription: Understanding a piece of python code

description: Understanding a piece of python code


code:
# Right
import hmac
# Note that hmac.new defaults to using MD5
hmac.new("password", "message").hexdigest() # 'f37438341e3d22aa11b4b2e838120dcf'

# Wrong
from hashlib import md5
md5("message"+"password").hexdigest() # 'd0647ee3be62a57c9475541c378b1fac'
md5("password"+"message").hexdigest() # 'c494404d2dd827b05e27bd1f30a763d2'

rawDescription: python hex hmac md5 of passwords not matching javascript

description: Python hex hmac md5 of passwords not matching javascript


rawDescription: How does one wrap numpy array types?

description: Wrap numpy array types


code:
textwidget = tk.Text(master)
textwidget.pack(side=tk.LEFT, fill=tk.BOTH)
for f in os.listdir('/tmp'):
    textwidget.window_create(tk.INSERT, window=tk.Label(textwidget, text=f))

rawDescription: How do I create a Tiling layout / Flow layout in TkInter?

description: Create a Tiling layout / Flow layout in TkInter


code:
import gzip

# your code as posted

zdir = { 'files':filestat, 'dirs':dirstat}
string_out = json.dumps(zdir, separators=(',',':'))
f = gzip.open( '/root/test/json'+pa+'gz', 'wb')
f.write(string_out)

rawDescription: Storing file information

description: Storing file information


code:
class CharacterLink(models.Model):
    character =  models.ForeignKey('NWODCharacter')
    class Meta:
        abstract = True

class SkillLink(models.Model):
    skill = models.ForeignKey('Skill', choices = SKILL_CHOICES)
    class Meta:
        abstract = True

class AttributeLink(models.Model):
    attribute = models.ForeignKey('Attribute', choices = ATTRIBUTE_CHOICES)
    class Meta:
        abstract = True

class CharacterSkillLink(CharacterLink, SkillLink):
    value = models.IntegerRangeField(min_value=1, max_value=5)
    speciality = models.CharField(max_length=200)

class CharacterAttributeLink(CharacterLink, AttributeLink):
    value = model.IntegerRangeField(min_value=1, max_value=5)

rawDescription: Is it possible/sensible to customize Django's auto-through tables to include other fields...through-factory?


code:
def overlaps1( a, b ):
        for i in range( 1, min( len(a), len(b) ) ):
                if a[-i:] == b[:i]:
                        print( a + b[i:] )

def overlaps2( a, b ):
        overlaps1(a,b)
        overlaps1(b,a)

overlaps2( 'bbb', 'bbab' )

rawDescription: How to find all overlaps of two strings in python

description: Find all overlaps of two strings in python


code:
ld = {} # basic dictionary
# now open & read file
with open('linked_id.txt') as fin:
    for ln in fin: # process each line in the file
        k, v = ln.split() # split each line eg. k = 'ID1', v = 'ID2'
        # make a dictionary entry - setdefault puts the k(ey) in and
        # in this case set the value to a list, append then adds to
        # the list by k(ey)
        ld.setdefault(k, []).append(v)

unq = [] # start an empty list
for k, v in ld.items(): # process the dictionary elements
    v.append(k)  # make the value list include the key
    ll = sorted(v)  # sort the new list
    if not ll in unq: # see if its in the unq (unique) list
        unq.append(ll) # if not add it

print(unq)  # show the unique sets

rawDescription: find all the linked IDs in a text file with each row has two IDs that are linked

description: Find all the linked IDs in a text file with each row has two IDs that are linked


code:
line = iterator.next()
next1 = iterator.next()

for next2 in iterator:
    #do stuff
    line = next1
    next1 = next2

rawDescription: how to get set of three next values from generator in a loop

description: Get set of three next values from generator in a loop


rawDescription: Move pivot_table values to rows

description: Move pivot_table values to rows


code:
import re
s =  "It was in 1990. Then it was in 1992. Then it was in 2000. Then it was in 2005.      Then it was in 2010."
re.search("\d{4}", s)
re.search("\d{4}", s).group()

rawDescription: How to limit the number of match by regexp

description: Limit the number of match by regexp


rawDescription: Lambda expression with lists as arguments


rawDescription: How to extract specific multiple values in JSON using python?

description: Extract specific multiple values in JSON using python


code:
from py2neo import Graph
graph = Graph()
targets = [1,4]
for target in targets:
    results = graph.cypher.execute("MATCH (n {id: %d})-[:foo]->(otherNode) RETURN n, otherNode" % target)
    # process results

rawDescription: How to get minimum subgraph for given vertices?

description: Get minimum subgraph for given vertices


code: pic_mat = np.array(imo.convert('L'))

rawDescription: python image size function in PIL

description: Python image size function in PIL


code:
bpy.ops.object.select_all(action='DESELECT')
bpy.ops.mesh.primitive_uv_sphere_add()
sphere = bpy.context.object

for i in range(1000):
    ob = sphere.copy()
    ob.data = sphere.data.copy()
    bpy.context.scene.objects.link(ob)
bpy.context.scene.update()

rawDescription: Blender performance issues with generating UV spheres


code:
from PySide import QtCore, QtGui

class Window(QtGui.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        grid = QtGui.QGridLayout()
        grid.addWidget(QtGui.QLabel('Label A', self), 0, 0)
        grid.addWidget(QtGui.QLabel('Label B', self), 0, 1)
        grid.addWidget(QtGui.QLabel('Label C', self), 1, 0)
        grid.addWidget(QtGui.QLabel('Label D', self), 1, 1)
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(QtGui.QRadioButton('Radio A', self))
        vbox.addWidget(QtGui.QRadioButton('Radio B', self))
        vbox.addWidget(QtGui.QRadioButton('Radio C', self))
        vbox.addWidget(QtGui.QPushButton('Button', self))
        widget = QtGui.QWidget(self)
        layout = QtGui.QGridLayout(widget)
        layout.addLayout(grid, 0, 0)
        layout.addLayout(vbox, 0, 1)
        layout.addWidget(
            QtGui.QSlider(QtCore.Qt.Horizontal, self), 1, 0, 1, 2)
        self.setCentralWidget(widget)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 100, 100)
    window.show()
    sys.exit(app.exec_())

rawDescription: Positioning Widgets inside a GUI Application (PySide)


code:
import bge

cont = bge.logic.getCurrentController()

kbd = cont.sensors["Keyboard"]

for key,status in kbd.events:
    if status == bge.logic.KX_INPUT_JUST_ACTIVATED:
        if key == bge.events.FKEY:
            cont.activate(cont.actuators['ToCube'])
        elif key == bge.events.GKEY:
            cont.activate(cont.actuators['ToCone'])
        elif key == bge.events.HKEY:
            cont.activate(cont.actuators['ToSphere'])

rawDescription: Blender object variables?

description: Blender object variables


code:
from pyspark.sql.functions import explode, avg, col

ratio = avg(
    # If status "S" then 1.0 else 0.0
    (col("status") == "S").cast("double")
 ).alias("ratio")

(df
    .withColumn("keyword", explode("keywords"))
    .groupBy("id", "type", "keyword")
    .agg(ratio))

rawDescription: PySpark: custom function in aggregation on grouped data


code: d = {k:[elem for elem in v if not elem.endswith(')')] for k,v in d.iteritems()}

rawDescription: How to iterate through dict values containing lists and remove items?

description: Iterate through dict values containing lists and remove items


rawDescription: Python: Check whether the list is in sequential or not | End of the list is defined


code:
from tkinter import *

class Application(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.master.title("Grid Manager")

        for r in range(6):
            self.master.rowconfigure(r, weight=1)
        for c in range(5):
            self.master.columnconfigure(c, weight=1)
            Button(master, text="Button {0}".format(c)).grid(row=6,column=c,sticky=E+W)

        Frame1 = Frame(master, bg="red")
        Frame1.grid(row = 0, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
        Frame2 = Frame(master, bg="blue")
        Frame2.grid(row = 3, column = 0, rowspan = 3, columnspan = 2, sticky = W+E+N+S)
        Frame3 = Frame(master, bg="green")
        Frame3.grid(row = 0, column = 2, rowspan = 6, columnspan = 3, sticky = W+E+N+S)

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

rawDescription: Python - Multiple frames with Grid manager


code:
from random import randint

def wordScramble(myString): # avoid name clashes with python modules
    stringArray = myString.split()
    for i, word in enumerate(stringArray):   # keep the index so we can update the list
        if len(word) >= 4:
            letter = randint(1,len(word)-2)
            point = letter
            while point == letter:
                point = randint(1, len(word)-2)
            stringArray[i] = switcher(word,letter,point)  # update the array
    return ' '.join(stringArray)   # return the result of the join

def switcher(word,letter,point):
    word = list(word)
    word[letter],word[point]=word[point],word[letter]
    return ''.join(word)  # return word back as a string

print(wordScramble("I can't wait to see how this turns itself out"))

rawDescription: Creating a word scrambler but it won't work, need help as a beginner


code:
def test(first): pass
test = d(test)

rawDescription: __decorated__ for python decorators

description: __decorated__ for python decorators


code:
def indexable_levels(args):
    #print 'args:',args
    levels = 0
    while True:
        if isinstance(args,str): break
        try:
            args = args[0]
            levels += 1
        except:
            break
    #print '   levels ->',levels
    return levels

# Create a factory object for the KML Google Extension namespace
_GX_ElementMakerSimple = objectify.ElementMaker(
    annotate=False,
    namespace=nsmap['gx'],
    nsmap={'gx': nsmap['gx']},
)

class _GX_ElementMaker (objectify.ElementMaker):
    'KML ElementMaker with overloads for custom text payloads like coordinates'
    def coord(self, *args):
        #print 'start coord: "%s"' % (str(args)), type(args), len(args)
        levels = indexable_levels(args)
        if levels == 1 and len(args) == 1:
            # This case is really redundant with the next
            assert isinstance(args[0],str)
            return _GX_ElementMakerSimple.coord(args[0])
        if levels == 1:
            return _GX_ElementMakerSimple.coord(' '.join([str(item) for item in args]))
        if levels == 2:
            # ((-121.583851, 37.386052),)
            assert(len(args)==1)
            return _GX_ElementMakerSimple.coord(' '.join([str(item) for item in args[0] ]))
        assert(False)

# Create a factory object for the KML Google Extension namespace
GX_ElementMaker = _GX_ElementMaker(
    annotate=False,
    namespace=nsmap['gx'],
    nsmap={'gx': nsmap['gx']},
)

rawDescription: checking and fixing values appended to a node with lxml.objectify in python

description: Checking and fixing values appended to a node with lxml.objectify in python


code:
# Not really faster, but it avoids your huge numbers issue
def changeFast(coinValueList, total, numCoins, coinDict):

    # Base Case: we've reached the money total we want
    if total == 0:
        return (numCoins, coinDict)

    bestCoins = -1
    bestDict = {}

    for i in range(len(coinValueList)):

        # You need to pass a copy of the dictionary to the
        # recursive calls. Otherwise each recursive call will
        # update the same dictionary!
        dictCopy = {}
        for coin in coinValueList:
            dictCopy[coin] = coinDict[coin]

        coin = coinValueList[i]

        if coin <= total:

            # Increment the corresponding coin slot in the dictionary
            dictCopy[coin] += 1
            (subCoins, subDict) = changeFast(coinValueList, total - coin, numCoins + 1, dictCopy)

            # Update our best results so far
            if bestCoins == -1 or subCoins < bestCoins:
                bestCoins = subCoins
                bestDict = subDict

    return (bestCoins, bestDict)

coins = [1, 3, 7, 12]

baseDict = {}
for coin in coins:
    baseDict[coin] = 0

print(changeFast(coins, 29, 0, baseDict))
# Returns (4, {1: 0, 3: 1, 7: 2, 12: 1}) as expected

rawDescription: Finding which coins make up the minimum of a total


code:
f = open('myfile.txt', 'w')
for x in range(255):
    ip = "10.1.1.%s\n" % str(x)
    f.write(ip)
f.close()

rawDescription: Outputting to a text file

description: Outputting to a text file


code:
db = pyodbc.connect('DSN=my_test_db;PWD=tiger')

print('-' * 20)
try:
    c = db.cursor()
    rs = c.execute("select * from v$version where banner like 'Oracle%'")
    for txt in c.fetchall():
        print('%s' % (txt[0]))
finally:
    db.close()

rawDescription: How do I connect to Oracle 10 from pyodbc?

description: Connect to Oracle 10 from pyodbc


code:
s = "Hello, how is it going ? I am tired actually, did not sleep   enough... That is bad for work, definitely"
s = parse(s)

#Create a list of all the tags you don't want
dont_want = ["UH", "PRP"]

sentence = parse(s).split(" ")

#Go through all the words and look for any occurence of the tag you don't want
#This is done through a nested list comprehension
[word for word in sentence if not any(tag in word for tag in dont_want)]

rawDescription: Format an entire text with pattern.en?

description: Format an entire text with pattern.en


code: [i[0] for i in taskscheduler.__dict__.items() if i[1] == 267008]

rawDescription: Retrieving class property/constant names from its value - Python


code:
def test_some_interaction(monkeypatch):
    monkeypatch.setattr("os.getcwd", lambda: "/")

rawDescription: How do I import the pytest monkeypatch plugin?

description: Import the pytest monkeypatch plugin


rawDescription: SparkSQL join on multiple column

description: SparkSQL join on multiple column


code: df2.join(pd.DataFrame({"x": s}))

rawDescription: Assign series to DataFrame with unequal indices


code:
import re
re.search('page=(\d+)', yourstring).group(1)

rawDescription: How to get character that comes after a particular substring, in python

description: Get character that comes after a particular substring, in python


code:
import os, threading

def safe_listdir(directory, timeout):
    contents = []
    t = threading.Thread(target=lambda: contents.extend(os.listdir(directory)))
    t.daemon = True  # don't delay program's exit
    t.start()
    t.join(timeout)
    if t.is_alive():
        return None
    return contents

rawDescription: Can os.listdir hang with network drives? What system call does it use?


rawDescription: How can one get the version of the currently-running Python interpreter from within a Python extension module?


rawDescription: Retrieving current Pyramid ini settings from a python script


code:
#!/usr/bin/python
from Tkinter import *
root = Tk()

descriptionFrame = Frame(root)

definitionFrame = LabelFrame(descriptionFrame, text="Definition")
definitionScroll = Scrollbar(definitionFrame)
definitionText = Text(definitionFrame, width=30, height=4, yscrollcommand=definitionScroll.set)
definitionScroll.config(command=definitionText.yview)

definitionText.delete("1.0", END)   # an example of how to delete all current text
definitionText.insert("1.0", "n/a") # an example of how to add new text to the text area

descriptionFrame.pack(fill=BOTH, expand=True)
definitionFrame.pack(fill=BOTH, expand=True)
definitionScroll.pack(side=RIGHT, fill=Y)
definitionText.pack(side=LEFT, fill=BOTH, expand=True)

root.mainloop()

rawDescription: Stop a Tkinter frame from resizing according to widget sizes


code:
with open('test.txt') as f: # with closes your files automatically
    data = f.read()
    f.seek(0) # reset file pointer
    data2 = f.readlines()

rawDescription: Setting multiple variables from opened file - Python


code:
#! /usr/bin/env python2
from SimpleHTTPServer import SimpleHTTPRequestHandler
import BaseHTTPServer

class CORSRequestHandler (SimpleHTTPRequestHandler):
    def end_headers (self):
        self.send_header('Access-Control-Allow-Origin', '*')
        SimpleHTTPRequestHandler.end_headers(self)

if __name__ == '__main__':
    BaseHTTPServer.test(CORSRequestHandler, BaseHTTPServer.HTTPServer)

rawDescription: Python - Enable access control on simple http server


code:
def longest(l):
    if(not isinstance(l, list)): return(0)
    return(max([len(l),] + [len(subl) for subl in l if isinstance(subl, list)] +
        [longest(subl) for subl in l]))

rawDescription: Finding the longest list in a list of lists in Python


code:
@property
def failureException(self):
    class MyFailureException(AssertionError):
        def __init__(self_, *args, **kwargs):
            self.b.save_screenshot('%s.png' % self.id())
            return super(MyFailureException, self_).__init__(*args, **kwargs)
    MyFailureException.__name__ = AssertionError.__name__
    return MyFailureException

rawDescription: How to execute code only on test failures with python unittest2?

description: Execute code only on test failures with python unittest2


code:
doc_id = db.test.insert({"foo": 1})
db.test.remove(doc_id)

rawDescription: How do I get the ID of an object after persisting it in PyMongo?

description: Get the ID of an object after persisting it in PyMongo


code:
import os

def absoluteFilePaths(directory):
   for dirpath,_,filenames in os.walk(directory):
       for f in filenames:
           yield os.path.abspath(os.path.join(dirpath, f))

rawDescription: Relative and Absolute paths of all files


code:
entry = filter(lambda x: x['Name']=='myhost1.mydomain.local', myjson['Members'])
# this will give you a sequence of zero or more elements

# if you want to return first element or None without raising exception, you can do something like:
return entry[0]['Tags'] if len(entry) else None

rawDescription: In Python, how can I get JSON value for a known key


code:
import sqlalchemy as sa
from unittest import TestCase
from mypackage.models.user import User

class TestUser(TestCase):
    def setUp(self):
        super(TestUser, self).setUp()
        sa.event.remove(User, "after_insert", do_something)
        sa.event.remove(User, "after_update", do_something)

    def tearDown(self):
        super(TestUser, self).tearDown()
        sa.event.listen(User, "after_insert", do_something)
        sa.event.listen(User, "after_update", do_something)

    @patch('my_package.user.do_something')
    def test_user(mock_do_something):
        user = User()
        assertSomething(user)

rawDescription: Python: How to mock SQLAlchemy event handlers (using mock.unittest)


code:
with open('text.txt') as text:
    with open('unique.txt', 'w') as output:
        seen = set()
        for line in text:
            line_hash = hash(line)
            if line_hash not in seen:
                output.write(line)
                seen.add(line_hash)

rawDescription: how to unique large text file content

description: Unique large text file content


code:
var = "C:\\Users\\Me\\level1\\level2\\level3\\level4\\level5\\level6\\level7\\level8\\test_one.txt"
base_path, filename = os.path.split(var)
# Sort the underscore out
new_filename = filename.replace('_', '')
# Go one level up from base_path
new_base_path = os.path.dirname(base_path)

output = os.path.join(new_base_path, new_filename)
print(output)

rawDescription: how parse a underscore from a path in python

description: How parse a underscore from a path in python


code:
def post(self, request, *args, **kwargs):
    body = request.body  # This is your string
    data = json.loads(body)
    service = data['Service']

rawDescription: Is this the correct format of POST body?

description: Is this the correct format of POST body


code: from dc_functions.dcfunc import function_name

rawDescription: Python - Calling a function from a class


code:
from PyQt5.QtWidgets import (QMessageBox,QApplication, QWidget, QToolTip, QPushButton,
                             QDesktopWidget, QMainWindow, QAction, qApp, QToolBar, QVBoxLayout,
                             QComboBox,QLabel,QLineEdit,QGridLayout,QMenuBar,QMenu,QStatusBar,
                             QTextEdit,QDialog,QFrame,QProgressBar
                             )
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtGui import QIcon,QFont,QPixmap,QPalette
from PyQt5.QtCore import QCoreApplication, Qt,QBasicTimer, QPoint

import sys

class cssden(QMainWindow):
    def __init__(self):
        super().__init__()

        self.mwidget = QMainWindow(self)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)

        #size
        self.setFixedSize(320, 450)
        self.center()

        #label
        self.lbl = QLabel(self)
        self.lbl.setText("test")
        self.lbl.setStyleSheet("background-color: rgb(0,0,0);"
                               "border: 1px solid red;"
                               "color: rgb(255,255,255);"
                               "font: bold italic 20pt 'Times New Roman';")
        self.lbl.setGeometry(5,5,60,40)

        self.oldPos = self.pos()

        self.show()

    #center
    def center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def mousePressEvent(self, event):
        self.oldPos = event.globalPos()

    def mouseMoveEvent(self, event):
        delta = QPoint (event.globalPos() - self.oldPos)
        #print(delta)
        self.move(self.x() + delta.x(), self.y() + delta.y())
        self.oldPos = event.globalPos()

app = QApplication(sys.argv)
app.setStyleSheet("QMainWindow{background-color: darkgray;border: 1px solid black}")

ex = cssden()
sys.exit(app.exec_())

rawDescription: PyQt5 draggable frameless window

description: PyQt5 draggable frameless window


code:
import sys
import os
import urllib.error
import urllib.request

def get_raw_webpage(url):
    """
        Download a web url as raw bytes
    """
    try:
        req = urllib.request.Request(url)
        response = urllib.request.urlopen(req)
        data = response.read()
        return data

    except urllib.error.HTTPError as e:
        print('HTTPError: ', e.code , file = sys.stderr)
        return None

    except urllib.error.URLError as e:
        print('URLError: ', e.args, file = sys.stderr)
        return None

    except ValueError as e:
        print('Invalid url.', e.args, file = sys.stderr)

    return None

def get_webpage(url):
    """
    Get webpage as raw bytes and then
    convert to readable form
    """
    data = get_raw_webpage(url)
    if data == None:
        return None

    return data.decode('utf-8')

rawDescription: Executing wget from python

description: Executing wget from python


code:
from cStringIO import StringIO
import pandas

s = StringIO()
with open('file.csv') as f:
    for line in f:
        if not line.startswith('TEST'):
            s.write(line)
s.seek(0) # "rewind" to the beginning of the StringIO object

pandas.read_csv(s) # with further parameters…

rawDescription: Is it possible to use read_csv to read only specific lines?


code:
english_set = set(E)
russian_set = set(R)
common_words = english_set.intersection(russian_set)

rawDescription: How to find all words that have the same appearence in two different languages?

description: Find all words that have the same appearence in two different languages


code:
def options(opt):
        opt.load('python')

def configure(conf):
    conf.load('python')
    conf.check_python_version((2,4,2))
    conf.check_python_headers()

def build(bld):

    bld.shlib(
        features = 'pyext',
        source = "mymodule.cpp",
        target = "myfoo",
        use = "PYTHON BOOST_PYTHON")

rawDescription: Waf: Specify library name for python extensions


code:
class point(object):
    memo = {}
    def __new__(cls, x, y):
        if (x, y) in cls.memo:         # if it already exists,
            return cls.memo[(x, y)]    # return the existing instance
        else:                          # otherwise,
            newPoint = object.__new__(cls) # create it,
            newPoint.x = x             # initialize it, as you would in __init__
            newPoint.y = y
            cls.memo[(x, y)] = newPoint # memoize it,
            return newPoint            # and return it!

rawDescription: How to create Classes in Python with highly constrained instances

description: Create Classes in Python with highly constrained instances


code:
def by_num_ele(start,step,n_elements):
    return numpy.arange(start,start+step*n_elements,step)

rawDescription: Is there a numpy function that allows you to specify start, step, and number?


code:
from collections import Counter
d = {}
#*1* Alternatively, could use : d = defaultdict(Counter)
with open(inputfile) as input_file:
    for line in input_file:
        for_who, items = line[:-1].split(':',1)
        d[for_who] = Counter(items.split(','))
        #Alternatively, if using defaultdict at *1*, d.update(items.split(','))
        #This allows "joe" to register multiple shopping lists which get summed into 1

#get totals by `sum`ming your Counters values:
totals = sum(d.values())

#Now add a 0-dict to each of the dictionaries just to make sure they have all the keys
zeros = dict((k,0) for k in totals)
for cntr in d.values():
    cntr.update(zeros)

key_order = list(totals.keys())  #list for py2k
with open(output_file,'w') as fout:
    fout.write('Order '+','.join(key_order)+'\n')
    fout.write('Totals,'+','.join(str(totals[k]) for k in key_order)+'\n')
    for person,dct in d.items():
        fout.write(person+','+','.join(str(dct[k]) for k in key_order)+'\n')

rawDescription: Comparing Two Dicts to Make a CSV for Inventory Management


code:
import ast
ast.literal_eval('1')
ast.literal_eval('1.0')
ast.literal_eval('1e10')

rawDescription: separating unspaced numbers from a string

description: Separating unspaced numbers from a string


code:
class Parser(object):

    def __init__(self, entry, model):
        self.entry = entry
        self.model = model

    def parse_text(self):
        # parsing self.entry.text
        ...
        some_object = self.model.objects.get(name=parsed_value)
        return some_object

rawDescription: Correct way to make python module smaller by delegating


code: df['Basic Stats'] = df['Basic Stats'].map(lambda x: x[9:13])

rawDescription: Split string in a column based on character position


code:
input = [('A1', 'B1', 'C1', 'Value'), (...)]

from collections import defaultdict

tree = defaultdict(lambda: defaultdict(lambda: defaultdict(list)))
#Alternatively you could use partial() rather than lambda:
#tree = defaultdict(partial(defaultdict, partial(defaultdict, list)))

for x, y, z, value in input:
    tree[x][y][z].append(value)

rawDescription: Python - translate a table to a hierarchical dictionary


code:
#models.py
class Asset(models.Model):
    name = models.CharField(max_length=100)
    asset_filename = models.CharField(max_length=4096)
    creation_date = models.DateTimeField(auto_now=True)

    def __unicode__(self):
        return self.name

#views.py
from urlparse import urljoin

def detail(request, asset_id):
    asset = get_object_or_404(Asset, pk=asset_id)
    asset_url = build_asset_url(request.get_host(), settings.ASSET_URL, asset.asset_filename)
    return render_to_response('html/detail.html', {'asset': asset, 'url': asset_url})

def build_asset_url(host, path, filename):
    """ Builds an absolute url to an asset located on the current server """
    url = "http://" % host
    url = urljoin(url, path)
    return urljoin(url, filename)

#settings.py
STATIC_URL = '/static/'
ASSET_URL = '/static/assets/assetrepository/'

rawDescription: Display relative url in iframe

description: Display relative url in iframe


code:
class Foo(tk.Frame):
    """Foo example"""

    def __init__(self, master=None):
        """Draw Foo GUI"""
        tk.Frame.__init__(self, master)
        self.grid()
        self.draw_window_bar()

    def draw_window_bar(self):
        """Draw bar TopLevel window"""
        self.window_bar = tk.Toplevel(self)
        # Some uber-pythonian code here...
        ask_yes_or_no = messagebox.askyesno('Brian?', 'Romani Ite Domum')
        if not ask_yes_or_no:
            self.window_bar.destroy()

rawDescription: How to close Toplevel window after the function it calls completes?

description: Close Toplevel window after the function it calls completes


rawDescription: Canot click button with Python with Selenium


code:
import pprint
x = [[[0]*3 for _ in range(3)] for _ in range(3)]
pprint.pprint(x)

rawDescription: 3 dimensional array definition in Python 2.7


code:
from wand.image import Image
from wand.color import Color

with Image(filename="http://i.stack.imgur.com/Mz9y0.jpg") as img:
    img.format = 'png'
    with Color('#FDFDFD') as white:
        twenty_percent = int(65535 * 0.2)  # Note: percent must be calculated from Quantum
        img.transparent_color(white, alpha=0.0, fuzz=twenty_percent)
    img.save(filename="/tmp/Mz9y0.png")

rawDescription: How to make the background of an image transparent with Wand?

description: Make the background of an image transparent with Wand


code:
data = [ {"key1": "value1", "key2": "value2", "key3": "value3"},
         {"key1": "value4", "key2": "value5", "key3": "value3"},
         {"key1": "value1", "key2": "value8", "key3": "value3"} ]
keylist = data[0].keys()
mydata = dict((k,', '.join(set(map(lambda d: d[k], data)))) for k in keylist)
mydata

rawDescription: Concatenating Unique Values from List of Dictionaries with sames Keys in Python


code:
result = []
for model in [Model1, Model2, Model3]:
    names = model.objects.filter(name__startswith='bla') \
                         .values_list('name', flat=True).distinct()
    result += names

rawDescription: Django - Select same column from many tables


code:
def has_good_deal(deals):
    return sorted(deals) != sorted(deals, key=lambda x: list(reversed(x)))

rawDescription: Algorithm for comparisons of elements in a two dimensional array


code:
for index_row, row in enumerate(stake_year.iterrows()):
    self.assertTrue(row[0] == counts[index_row][0])
    self.assertTrue(row[1][0] == counts[index_row][1])

rawDescription: list comprehension with concurrent loops python

description: List comprehension with concurrent loops python


code:
index = self.selectedIndexes()[0]
crawler = index.model().itemFromIndex(index)

rawDescription: Getting the currently selected item in QTreeView


code:
import wx

def render(dc):
    dc.Clear()
    region = wx.RegionFromPoints([(256, 64), (448, 448), (64, 448)])
    dc.SetClippingRegionAsRegion(region)
    dc.GradientFillLinear((0, 0, 512, 512), wx.RED, wx.BLACK, wx.NORTH)

def main():
    app = wx.PySimpleApp()
    bitmap = wx.EmptyBitmap(512, 512)
    render(wx.MemoryDC(bitmap))
    bitmap.SaveFile('output.png', wx.BITMAP_TYPE_PNG)

if __name__ == '__main__':
    main()

rawDescription: Using PIL to draw gradients with clipping masks?


code:
table = 'abcdefghijkl'
i = 0
while i < 4:
    print("| {} | {} | {} |".format(table[i], table[i+4], table[i+8]))
    i += 1

rawDescription: How to create a table without using methods or for-loops?

description: Create a table without using methods or for-loops


code:
class DailyProgress(db.Model):
    date = db.DateTimeProperty(auto_now_add=True)
    score = db.IntegerProperty()

rawDescription: How to save user's daily progress?

description: Save user's daily progress


code:
names = set(name.strip() for name in file2)
while f < 50:
    for line in file1:
        if line.strip() in names:
            f += 1

rawDescription: Simple nested for loop not working correctly


code:
res = []
for value in db.cursor.fetchall():
    pairs = []
    for index, column in enumerate(value):
        pairs.append((columns[index][0], column))
    d = dict(pairs)
    res.append(d)

rawDescription: Could you please explain this piece of code?


code:
d2 = pd.melt(df, id_vars="Country Name", var_name="Year", value_name="GDP")
d2 = d2.sort_values(["Country Name", "Year"]).reset_index(drop=True)
d2.head(10)

rawDescription: Stack columns in pandas dataframe to achieve record format


rawDescription: How to extract tuples from a pandas symmetric dataframe

description: Extract tuples from a pandas symmetric dataframe


code:
# global scope, the callback type
cback = ctypes.CFUNCTYPE(None,ctypes.POINTER(problem))

# decorate the callback
@cback
def change_struct_data(s):
    s.contents.val = 99

rawDescription: Increment Reference Counter for a CFUNCTYPE


code:
import subprocess, os
my_env = os.environ.copy()
my_env["PATH"] = "/usr/sbin:/sbin:" + my_env["PATH"]
subprocess.Popen(my_command, env=my_env)

rawDescription: Where does subprocess.Popen look for the argument process? (Python)


code:
import request, route, run

@route('/user-agent')
def user_agent():
    return request.environ.get('HTTP_USER_AGENT')
run()

rawDescription: Get $_SERVER['HTTP_USER_AGENT'] variable value in Bottle


code:
from datetime import datetime

def copyright_dates(start_year = datetime.now().year):
    return " - ".join(str(y) for y in sorted(set([start_year, datetime.now().year])))

rawDescription: Ruby to python one-liner conversion

description: Ruby to python one-liner conversion


code: allowed_domains = ["t13.cl"]

rawDescription: scraping simple page: scrapy doesn't return all links

description: Scraping simple page: scrapy doesn't return all links


code:
import sys
sys.path.append("/path/to/my/directory")

import hello_world

rawDescription: Import home-made python function in paraview


code:
with open(test_filename,"rt") as test:
    with open(predict_filename,"rt") as predict:
        for couple in zip(test,predict):
            do_something(couple)

rawDescription: yield from two generators at the same time, and make the result a tuple

description: Yield from two generators at the same time, and make the result a tuple


code:
confirm_links_html = 'Confirm Deny'
msg = EmailMessage('This is the title',  confirm_links, to=['youremail@gmail.com'])
msg.content_subtype = "html"

rawDescription: Changing a boolean through an email with Python/Django


code:
from collections import defaultdict

words_seen = defaultdict(list)

for word,filedate in get_words():
    words_seen[word].append(filedate)

rawDescription: String trend-analysis (suggestions for data structure)


code:
for sel in response.css('div.figuration'):
    ...

rawDescription: adding conditions when scraping

description: Adding conditions when scraping


code:
class MyForm(forms.Form):
    start_date = forms.DateField(input_formats=['%d/%m/%Y'])

rawDescription: how to change default dateformat AAAA-MM-DD to dd/mm/yyyy in Django?

description: Change default dateformat AAAA-MM-DD to dd/mm/yyyy in Django


code:
Solution
s2 = s1 / s1[0] - 1

rawDescription: Python Pandas How to make pct_change() calculate the change from a single number instead of previous numbers?


code:
for k,v in environment_add.iteritems():
    if k in environment:
        environment[k].update(v)
    else:
        environment[k] = v

rawDescription: Trying to grow a nested dictionary by adding more key:value pairs


code:
if filecmp.cmp('old_index.html', 'new_index.html'):
    # Do whatever you want if the files are the same
    print("Both the files are same")
else:
    # Do whatever you want if the files are NOT the same
    print("No, the files are NOT the same")

rawDescription: Python filecmp.cmp('old_index.html', 'new_index.html') in if event


code:
datetime_format = '%H:%M:%S.%f' # tweak depending on format of dates

df.index = pd.to_datetime(df.index, format=format_datetime)

rawDescription: Operating on index objects in Pandas

description: Operating on index objects in Pandas


code:
from django.conf import settings
from django.core.cache import cache
from django.db.models.signals import post_save
from django.http import HttpRequest
from django.utils.cache import _generate_cache_header_key

from someapp.models import BaseModelofThisClass

class SomeModel(BaseModelofThisClass):
    ...
    @property
    def cache_key(self):
        # Create a fake request object
        request = HttpRequest()
        # Set the request method
        request.method = "GET"
        # Set the request path to be this object's permalink.
        request.path = self.get_absolute_url()
        # Grab the key prefix (if it exists) from settings
        key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX
        # Generate this object's cache key using django's key generator
        key = _generate_cache_header_key(key_prefix, request)
        # This is a bit hacky but necessary as I don't know how to do it
        # properly otherwise. While generating a cache header key, django
        # uses the language of the HttpRequest() object as part of the
        # string. The fake request object, by default, uses
        # settings.LANGUAGE_CODE as it's language (in my case, 'en-us')
        # while the true request objects that are used in building views
        # use settings.LANGUAGES ('en'). Instead of replacing the segment
        # of the string after the fact it would be far better create a more
        # closely mirrored HttpRequest() object prior to passing it to
        # _generate_cache_header_key().
        key = key.replace(settings.LANGUAGE_CODE, settings.LANGUAGES[settings.DEFAULT_LANGUAGE][0])

        return key

    @receiver(post_save)
    def clear_cache_for_this_item(sender, instance, **kwargs):
        # If this is a sub-class of another model
        if sender not in BaseModelofThisClass.__subclasses__():
            return
        else:
            cache.delete(instance.cache_key)

rawDescription: Expiring a view-cache in Django 1.3.1

description: Expiring a view-cache in Django 1.3.1


code:
input = 1
for idx,i in enumerate(list_1):
    if input in i:
        return list_2[idx]

rawDescription: Cross Referencing Lists in Python

description: Cross Referencing Lists in Python


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

def f(z,t):
    return np.exp(-z)*np.sin(t-z)

z = np.linspace(0,5,3001)
t = np.arange(0,40000,4000)

for tval in t:
    plt.plot(z, f(z, tval))
plt.show()

rawDescription: How can I plot a mathematical expression of two variables in python?

description: Plot a mathematical expression of two variables in python


code:
to_exclude = {1, 2}
vector = ['a', 'b', 'c', 'd']
vector2 = [element for i, element in enumerate(vector) if i not in to_exclude]

rawDescription: Python Indexing with List of Indices to Exclude


code:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

mygreen = "#d2ffd2"
myred = "#dd0202"

style = ttk.Style()

style.theme_create( "yummy", parent="alt", settings={
        "TNotebook": {"configure": {"tabmargins": [2, 5, 2, 0] } },
        "TNotebook.Tab": {
            "configure": {"padding": [5, 1], "background": mygreen },
            "map":       {"background": [("selected", myred)],
                          "expand": [("selected", [1, 1, 1, 0])] } } } )

style.theme_use("yummy")

note = ttk.Notebook(root)
f1 = ttk.Frame(note, width=300, height=200)
note.add(f1, text = 'First')
f2 = ttk.Frame(note, width=300, height=200)
note.add(f2, text = 'Second')
note.pack(expand=1, fill='both', padx=5, pady=5)

tk.Button(root, text='yummy!').pack(fill='x')

root.mainloop()

rawDescription: Change color of "tab header" in ttk.Notebook


code:
F = []
F.extend(x)
F.extend(y)
F

rawDescription: Appending 2D lists

description: Appending 2D lists


code: df1.join(df2, how='outer')

rawDescription: Merging dataframes on indexes in PANDAS

description: Merging dataframes on indexes in PANDAS


code:
salt = linecache.getline(userin + '.userdat', 2).strip()
saltin = newin + salt
hashed_newin = (hashlib.sha256(saltin.encode()).hexdigest())
realin = linecache.getline('file.dat', 1).strip()
if hashed_newin == realin:
    return True

rawDescription: Hashed password authentication in Python not working


code:
import turtle
import time

def erasableWrite(tortoise, name, font, align, reuse=None):
    eraser = turtle.Turtle() if reuse is None else reuse
    eraser.hideturtle()
    eraser.up()
    eraser.setposition(tortoise.position())
    eraser.write(name, font=font, align=align)
    return eraser

t = turtle.Turtle()
t.hideturtle()
t.up()

t.goto(-100,100)
t.write("permanent", font=("Arial", 20, "normal"), align="center")

t.goto(100,100)
eraseble = erasableWrite(t, "erasable", font=("Arial", 20, "normal"), align="center")

time.sleep(1)

eraseble.clear()

t.goto(-100, -100)
erasable = erasableWrite(t, "erasable", font=("Arial", 20, "normal"), align="center", reuse=eraseble)

turtle.done()

rawDescription: turtle delete writing on Screen and Rewrite

description: Turtle delete writing on Screen and Rewrite


code:
import win32com.client

def get_contact(signin_uri, communicator):
   c = communicator.GetContact(signin_uri, communicator.MyServiceId)
   return c

comm = win32com.client.Dispatch('Communicator.UIAutomation')
contact = get_contact("jaya@contoso.com", comm)

rawDescription: writing python script on windows

description: Writing python script on windows


code:
_, idx, cnt = np.unique(a, return_index=True, return_counts=True)
idx[np.argmax(cnt)]

rawDescription: How would I write NumPy argmode()?

description: How would I write NumPy argmode()


rawDescription: Running scipy's oneway anova in a script


code:
from django.test.client import Client
client = Client()
resp = client.put('/employee/2/', data={'email': 'here@there.com'}, follow=True)
#... etc

rawDescription: Django REST browser interface

description: Django REST browser interface


code:
group = [0]*3
item   = [1,2,3]
group = [i + j for i,j in zip(group, item)]
group

rawDescription: How to increment values in a list in python without using the for loop?

description: Increment values in a list in python without using the for loop


code:
class MyProgressDialog(wx.Dialog):
    def __init__(self, parent, id, title, text=''):
        wx.Dialog.__init__(self, parent, id, title, size=(200,150), style=wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER)

        self.text = wx.StaticText(self, -1, text)
        self.gauge = wx.Gauge(self, -1)
        self.closebutton = wx.Button(self, wx.ID_CLOSE)
        self.closebutton.Bind(wx.EVT_BUTTON, self.OnClose)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.text, 0 , wx.EXPAND)
        sizer.Add(self.gauge, 0, wx.ALIGN_CENTER)
        sizer.Add(self.closebutton, 0, wx.ALIGN_CENTER)

        self.SetSizer(sizer)
        self.Show()

    def OnClose(self, event):
        self.Destroy()
        #can add stuff here to do in parent.

rawDescription: Is wxpython progressdialog cancel event possible?


code:
from suds.client import Client
url = "http://www.webservicex.net/country.asmx?WSDL"

client = Client(url)
port = client.wsdl.services[0].ports[0]
list_of_methods = [port.qname[1] + '/' + method for method in port.methods]
print(list_of_methods)

rawDescription: get the full path of web service's methods from wsdl file

description: Get the full path of web service's methods from wsdl file


code:
def f2c(t):
    """Convert degrees Fahrenheit to Celsius."""
    return (t - 32) * 5/9

temps = [(i, f2c(i)) for i in range(-10, 101, 10)]

rawDescription: Put elements in two-dimensional list using a loop - Python


rawDescription: How to remove duplicate dictionary based on selected keys from a list of dictionaries in Python?

description: Remove duplicate dictionary based on selected keys from a list of dictionaries in Python


code: btn_enter = Tkinter.Button(all_your_args, fg=your_desired_value)

rawDescription: How to change colour text from a tkinter.button

description: Change colour text from a tkinter.button


code: df = df.groupby(['Experiment', 'Step'], sort=False, as_index=False)['value'].aggregate(np.sum)

rawDescription: Using pandas.Dataframe.groupby without alphabetical ordering


code:
layout = Layout(
    xaxis=XAxis(
       range=[-150, 150],
       showgrid=True,
       zeroline=True,
       showline=True,
       gridcolor='#bdbdbd',
       gridwidth=2,
       zerolinecolor='#969696',
       zerolinewidth=4,
       linecolor='#636363',
       linewidth=6
    ),
    yaxis=YAxis(
        range=[-150,150],
        showgrid=True,
        zeroline=True,
        showline=True,
        gridcolor='#bdbdbd',
        gridwidth=2,
        zerolinecolor='#969696',
        zerolinewidth=4,
        linecolor='#636363',
        linewidth=6
   ),
   height=600,
   width=600,
)

rawDescription: Plotly, same scale for x and y axis

description: Plotly, same scale for x and y axis


code:
import difflib
difflib.SequenceMatcher(None, "never", "forever").get_matching_blocks()
difflib.SequenceMatcher(None, "address", "oddness").get_matching_blocks()

rawDescription: Python - how to find all intersections of two strings?


rawDescription: URL generator in python

description: URL generator in python


code:
df['index'] = df.index
df

rawDescription: How to write index of dataframe as a dataframe column

description: Write index of dataframe as a dataframe column


code:
import StringIO
from PIL import Image
im1 = Image.open(IMAGE_FILE)

# here, we create an empty string buffer
buffer = StringIO.String()
im1.save(buffer, "JPEG", quality=10)

# ... do something else ...

# write the buffer to a file to make sure it worked
with open("./photo-quality10.jpg", "w") as handle:
    handle.write(buffer.contents())

rawDescription: How to perform JPEG compression in Python without writing/reading

description: Perform JPEG compression in Python without writing/reading


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

FPS = 30  # frames per second
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
YELLOW = (255, 255, 0)
RED = (255, 0, 0)

class ProgressiveLine(object):
    def __init__(self, x1, y1, x2, y2, color=WHITE, width=1):
        self.x1, self.y1, self.x2, self.y2 = x1, y1, x2, y2
        self.color, self.width = color, width
        self.dx = self.x2-self.x1
        self.dy = self.y2-self.y1

    def draw(self, surface, percentage):
        percentage = min(abs(percentage), 1.0)
        xcur = self.x1 + self.dx*percentage
        ycur = self.y1 + self.dy*percentage
        pygame.draw.line(surface, self.color, (self.x1, self.y1), (xcur, ycur),
                         self.width)

def main():
    pygame.init()
    fpsclock = pygame.time.Clock()
    screen = pygame.display.set_mode((500,400), 0, 32)
    screen.fill(WHITE)

    prgrsline = ProgressiveLine(10, 390, 490, 10, RED, 3)

    percent_complete = 0.0
    while True:  # display update loop
        screen.fill(WHITE)

        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        if percent_complete < 1.0:
            percent_complete += 0.01
        prgrsline.draw(screen, percent_complete)

        pygame.display.update()
        fpsclock.tick(FPS)

main()

rawDescription: How to create a pop-up in pygame with transparent background and how to control loop as a line is been drawn?

description: Create a pop-up in pygame with transparent background and how to control loop as a line is been drawn


code:
from tkinter import *
root = Tk()

for relief in [RAISED, SUNKEN, FLAT, RIDGE, GROOVE, SOLID]:
    t = Toplevel(root, borderwidth=2, relief = relief)
    Label(t, text=relief, width=10).pack(side=LEFT)
root.mainloop()

rawDescription: Frame as a container (tkinter)

description: Frame as a container (tkinter)


code:
import subprocess
subprocess.call(['python', 'your_script.py'])

rawDescription: How to call a python file using python script

description: Call a python file using python script


code:
import ConfigParser

config = ConfigParser.RawConfigParser()
config.read('example.url')

try:
    url = config.get('InternetShortcut', 'URL')  # Classic URL Format
except ConfigParser.NoOptionError:
    url = config.get('DEFAULT', 'BASEURL')  # Extended URL Format

rawDescription: Extract URL from .url file

description: Extract URL from .url file


code: [reduce(lambda a, b: a*b, x)  for x in zip(*cd)]

rawDescription: fold a list of lists to produce a list

description: Fold a list of lists to produce a list


code:
for table in soup.find_all("table"):
    table.extract()

rawDescription: Remove tables from html files in python

description: Remove tables from html files in python


code:
str1="0Cell Phones: Smartphone,\x02\x05\x0e\x02\x05Mobile Phone - Best Buy13AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy4\x02\x05\x0e\x02\x05Cell Phones: Smartphone, Mobile Phone - Best Buy1\x02\x05\x0e\x02\x05AT&T Wireless: AT&T Phones & Cell Phone Plans - Best Buy"
"".join(x for x in str1 if 31 < ord(x) <127)

rawDescription: Remove special characters from the string


code:
yn = open("y_and_n.csv",'r')
y = open("y_only.csv",'w',newline='')

for i in yn:
    if i[0] == 'Y':
        y.write(i)

yn.close()
y.close()

rawDescription: Python write csv if condition is met

description: Python write csv if condition is met


code:
@classmethod
def get_non_deleted(cls, id):
    entity = cls.get_by_id(id)
    if entity and not entity.deleted:
        return entity

rawDescription: Query statement in get_by_id (ndb, GAE)

description: Query statement in get_by_id (ndb, GAE)


rawDescription: strip timestamp/syntax-sequence from python string

description: Strip timestamp/syntax-sequence from python string


code:
import socket
import struct
addr_long = int("0200A8C0",16)
hex(addr_long)
struct.pack("<L", addr_long)
socket.inet_ntoa(struct.pack("<L", addr_long))

rawDescription: Convert "little endian" hex string to IP address in Python


code:
def days(f, L):
    if f > L:
        x = list(range(0, 7))
        return x[f:] + x[:L+1]
    else:
        return list(range(f, L+1))

rawDescription: Get a range of days in Python

description: Get a range of days in Python


code:
def parse_site(self, response):
    global BASE_WEBSITE
    sel = Selector(response)
    sites = sel.xpath('//a') # xpath for the sites
    # To get the desc. of the <a> tag use sel.xpath('//a/text()').extract()
    # Get all the websites that would lead to clients.
    sites = [site for site in sites if "." in str(site.xpath('text()').extract())]
   # items = []
    for site in sites:
        item = DomainManagerItem()

        # Get the Description and trim it
        dName = str(site.xpath('text()').extract())[3:-2]

        # Get the Path and trim it
        newPath = "https://" +  BASE_WEBSITE +  (str(site.xpath("@href").extract())[3:-2])

        item['domainName'] = dName
        yield Request(url = newPath, callback = self.parse_client, meta = {'item':item})

def parse_client(self, response):
    sel = Selector(response)
    ite = response.meta['item']
    site = sel.xpath('//td')
    ite['totalUsers'] = str(site[8].xpath('text()').extract())[3:-2]

    return ite

rawDescription: Travel Path In Scrapy

description: Travel Path In Scrapy


code: 1. / (1 + exp(-decision_function(X)))

rawDescription: Calculate probability estimate P(y|x) per sample x in scikit for LinearSVC


rawDescription: Ignore python multiple return value

description: Ignore python multiple return value


code:
grepResults = subprocess.check_output([grepCmd], shell=true).split()
for i in range(1, len(grepResults), 9):
  pid = grepResults[i]
  killPidCmd = "kill -9 " + pid
  subprocess.call([killPidCmd], shell=true)

rawDescription: How to find Tomcat's PID and kill it in python?

description: Find Tomcat's PID and kill it in python


code:
import os
import tables

path = '/path/to/your/h5_files'
beta = tables.openFile(os.path.join(path, "test2.h5"), mode='w')

rawDescription: how do you create a pytable inside a folder using openFile?

description: Create a pytable inside a folder using openFile


code:
stream = yaml.dump(list_of_dicts, default_flow_style = False)
file.write(stream.replace('\n- ', '\n\n- '))

rawDescription: Formatting PyYAML dump() output

description: Formatting PyYAML dump() output


code:
def start_requests(self, filename, columnname):
    with open(filename) as file:
        headers = file.readline().strip().split(',')
        for line in file.readlines():
            zipcode = line.strip().split(',')[headers.index(columnname)]
            yield self.make_requests_from_url("http://www.example.com/zipcode/%05d/search.php" % zipcode)

rawDescription: List from CSV column in Python

description: List from CSV column in Python


code:
result_record_list[0].pic = None
result_record_list[0].put()

rawDescription: How to remove value from GAE NDB Property (type BlobKeyProperty)

description: Remove value from GAE NDB Property (type BlobKeyProperty)


code:
import os
def getpage(fname, pageindex, pagesize=100, ahead=20):
    """read page roughly by byte size"""
    size = os.path.getsize(fname)
    pagenum = size/pagesize
    f=open(fname,'r')
    pos=pageindex * pagesize
    #ahead some line
    pos -= ahead
    if pos <0:
        pos = 0
    f.seek(pos)
    f.readline()
    txt = f.read(pagesize)
    txt += f.readline()
    return txt

rawDescription: read part text from a large file  as a page  by python

description: Read part text from a large file  as a page  by python


code:
import tkinter as tk
from tkinter import ttk

root = tk.Tk()

# Base size
normal_width = 1920
normal_height = 1080

# Get screen size
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# Get percentage of screen size from Base size
percentage_width = screen_width / (normal_width / 100)
percentage_height = screen_height / (normal_height / 100)

# Make a scaling factor, this is bases on average percentage from
# width and height.
scale_factor = ((percentage_width + percentage_height) / 2) / 100

# Set the fontsize based on scale_factor,
# if the fontsize is less than minimum_size
# it is set to the minimum size
fontsize = int(14 * scale_factor)
minimum_size = 8
if fontsize < minimum_size:
    fontsize = minimum_size

# Create a style and configure for ttk.Button widget
default_style = ttk.Style()
default_style.configure('New.TButton', font=("Helvetica", fontsize))

frame = ttk.Frame(root)
button = ttk.Button(frame, text="Test", style='New.TButton')

frame.grid(column=0, row=0)
button.grid(column=0, row=0)

root.mainloop()

rawDescription: Tkinter Adaptive text and dimensions

description: Tkinter Adaptive text and dimensions


code:
def eraseItem(self,event):
    tuple_objects = self.workspace.find_closest(event.x, event.y, halo = 5)
    if len(tuple_objects) > 0 and tuple_objects[0] in self.dictID:
        objectToBeDeleted = tuple_objects[0]
        del self.dictID[objectToBeDeleted]
        self.workspace.delete(objectToBeDeleted)

rawDescription: Deleting lines on a Python tkinter canvas


code: df['arbitrarydata'] = df.groupby(('label', 'numbers')).transform(lambda x: np.random.rand())

rawDescription: How can I change the original DataFrame from a group?

description: Change the original DataFrame from a group


code:
from subprocess import Popen, PIPE

source = Popen(['source', 'arg1', 'arg2'], stdout=PIPE)
sink = Popen(['sink'], stdin=source.stdout)
source.stdout.close()
source.wait()
sink.wait()

rawDescription: Convert mp3 to wav on the fly using ffmpeg in Python


code:
from collections import defaultdict
hash = defaultdict(dict)
hash[1][2] = 1

rawDescription: Python dictionary very slow(2-D hash table)


rawDescription: how to import a submodule in Python (without `exec`)

description: Import a submodule in Python (without `exec`)


code:
class Friendship(models.Model):
  from_friend = models.ForeignKey(
    User, related_name='friend_set'
  )
  to_friend = models.ForeignKey(
    User, related_name='to_friend_set'
  )
  def __unicode__(self):
    return u'%s, %s' % (
      self.from_friend.username,
      self.to_friend.username
    )
  class Meta:
    unique_together = (('to_friend', 'from_friend'), )

rawDescription: How to write this "model" in Django?

description: Write this "model" in Django


code:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import datetime as dt

# Make a series of events 1 day apart
x = mpl.dates.drange(dt.datetime(2009,10,1),
                     dt.datetime(2010,1,15),
                     dt.timedelta(days=1))
# Vary the datetimes so that they occur at random times
# Remember, 1.0 is equivalent to 1 day in this case...
x += np.random.random(x.size)

# We can extract the time by using a modulo 1, and adding an arbitrary base date
times = x % 1 + int(x[0]) # (The int is so the y-axis starts at midnight...)

# I'm just plotting points here, but you could just as easily use a bar.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot_date(x, times, 'ro')
ax.yaxis_date()
fig.autofmt_xdate()

plt.show()

rawDescription: plot time of day vs date in matplotlib

description: Plot time of day vs date in matplotlib


code:
source = sys.stdin.read()
for ip in source.split(","):
    print(geolite2.lookup(ip))

rawDescription: python sys.stdin.read() unwanted split

description: Python sys.stdin.read() unwanted split


code:
counter = 0

while True:
    if counter % 120 == 0:
        humidity, temperature = Adafruit_DHT.read_retry(22, 4)
    moisture = ReadChannel(2)

    # then following lcd stuff, lcd.clear() and lcd message()...

    counter += 1
    sleep(1)

rawDescription: Add multipe time delays in python

description: Add multipe time delays in python


code:
def gen(lst, pat):
    size = len(pat)
    size_l = len(lst)
    for i in range(0, size_l, size):
        yield lst[i:i+size]

lst = [1, 2, 4, 1, 2, 4, 1, 2, 4]
pat = [1, 2, 4]
len(list(gen(lst, pat)))

rawDescription: Finding integer pattern from a list

description: Finding integer pattern from a list


rawDescription: How to save a ForeignKey without retrieving the foreign object instance?

description: Save a ForeignKey without retrieving the foreign object instance


code:
my_msg = "Hello world"
QtGui.QMessageBox.information(None, 'My Title', my_msg)

rawDescription: displaying message in PyQt4

description: Displaying message in PyQt4


code:
flattened = sorted((time,key,count) for day in data.values() for time,counters in day.items() for key,count in counters.items())
{time:{key:sum(datum[2] for datum in counters) for key,counters in itertools.groupby(group, lambda x:x[1])} for time,group in itertools.groupby(flattened, lambda x:x[0])}

{'15:20:00': {'outs': 30, 'ins': 15}, '15:00:00': {'outs': 15, 'ins': 17}, '15:10:00': {'outs': 15, 'ins': 36}}

rawDescription: Squash and sum values from 3-level nested dictionaries in one-liner (or two-liners)


code:
def __str__(self):
    related = PR_ComponentsData.objects.filter(id=self.id).last()
    return "{} ({})".format (related.comp_text, self.comp_nr)

rawDescription: Django with python3, results of sql query in selectbox


code:
from maya import cmds
import math

dags = ['obj']
attrs = ['sx', 'sy', 'sz']
tol = 0.001

for dag in dags:
    frames = [frame for frame in cmds.keyframe(dag, q=1)]
    for frame in frames:
        attrib_vals = [cmds.getAttr(dag+'.'+attr, time=frame) for attr in attrs]
        length = math.sqrt(sum(attr_val * attr_val for attr_val in attrib_vals))
        if length < tol:
            cmds.setKeyframe(dag, at=attrs, t=[frame], v=0)

rawDescription: Writing a MEL/Python script for changing scale values


code:
racenumber = 10

cursor = db.cursor()
cursor.execute("""CREATE TABLE `%s` (ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(50) DEFAULT NULL,
PRIZE_TOTAL VARCHAR(50) DEFAULT NULL, STRENGTH VARCHAR(50) DEFAULT NULL, URL VARCHAR(50) DEFAULT
NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1""" % (racenumber))

db.commit()
db.close()

rawDescription: Python mysql create and name new table using variable name