code:
for value in d.itervalues():
    value.sort()

rawDescription: Sort values inside dictionary python

description: Sort values inside dictionary python


code:
# open with UTF-8 encoding (in case your system defaults to something else)
with open("TextOutput.txt", 'w', encoding='utf-8') as file:
    # Get the text and write it as a single block
    file.write(soup.get_text())

rawDescription: Why is the text formatting different in the Python 3 shell compared to text file produced?


rawDescription: Grid of clickable images in wxPython

description: Grid of clickable images in wxPython


code: sum(c.A for c in c_list)

rawDescription: Sum / Average an attribute of a list of objects in Python


code: s = SimpleXMLRPCServer.SimpleXMLRPCServer(("", 8000))

rawDescription: can SimpleXMLRPCServer listen on multiple addresses?

description: Can SimpleXMLRPCServer listen on multiple addresses


code:
import itertools
[list(xs) for xs in itertools.product([1,2,3], [1], [1,2,3,4])]

rawDescription: Python: generate a list containing lists from several lists


code:
import random
while 1:
    choices = ["a1", "a2","a3","b1","b2","b3","c1","c2","c3"]

    shuffle = []

    last = ""

    while choices:
        l = choices
        if last:
            l = [x for x in l if x[0] != last[0] and x[1] != last[1]]
        if not l:
            #no valid solution
            break
        newEl = random.choice(l)
        last = newEl
        shuffle.append(newEl)
        choices.remove(newEl)
    if not choices:
        print(shuffle)
        break

rawDescription: shuffling a list with restrictions in Python

description: Shuffling a list with restrictions in Python


code:
...
a = Label(root, text=time.strftime('%H:%M:%S'))
def update_time():
    a['text'] = time.strftime('%H:%M:%S')
    root.after(1000, update_time)
root.after(1000, update_time)
a.grid(row=3, column=1)
...

rawDescription: Digital clock display - multithreading required?


code:
class TicketBaseSerializer(serializers.ModelSerializer):

    my_new_name = serializers.PrimaryKeyRelatedField(
        source="cc",
        queryset=Person.objects.all(),
        many=True,
        required=False
        )

   # ... other code

rawDescription: Can you rename a PrimaryKeyRelatedField in django-rest-framework

description: Rename a PrimaryKeyRelatedField in django-rest-framework


rawDescription: Sort a list of objects by an attribute given a string of the name of the attribute


code:
lst = [['id', 'sub type', 'type'], ['1', 'apples', 'fruit'], ['15', 'orange', 'fruit'], ['3', 'corn', 'vegtable']]
[x[1] for x in lst]

rawDescription: Re-list a item from a nested list

description: Re-list a item from a nested list


code:
import pandas as pd
#read in the files using the IP address as the index column
df_1 = pd.read_csv('file1.csv', header= 0, index_col = 'IP')
df_2 = pd.read_csv('file2.csv', header= 0, index_col = 'IP')
#fill in the Nan
combined_df = df_1.combine_first(df_2)
combined_df.write_csv(path = '', sep = ',')

rawDescription: Merge csv's with some common columns and fill in Nans


code:
def test_read_file():
    file_contents = b"""Hello,World"""
    with NamedTemporaryFile() as fp:
        fp.write(file_contents)
        fp.flush()
        my_dict = read_file(fp.name)
    print(my_dict)
    assert my_dict == { "Hello" : "World" }

rawDescription: Why is my assertion failing when reading a NamedTemporaryFile?


rawDescription: Python regex: Finding input not matching a specific (variable-defined) length


rawDescription: Decoding time, presented in a weird format


code:
def example(a, b, c):
    return [k for k in locals().keys() if k not in globals()]

example(1, 2, 3)

rawDescription: Python locals() and globals() are the same?


code:
import web

class Echo:
    def GET(self):
        return """<html><form name="script-input-form" action="/" method="post">
Script: <input type="text" name="script-body">
<input type="submit" value="Submit">
</form><html>"""

    def POST(self):
        data = web.input()
        obj = compile(data['script-body'], '', 'exec')
        result = eval(obj, globals(), locals())
        web.seeother('/')

urls = (
  '/.*', Echo,
)
if __name__ == "__main__":
    app = web.application(urls, globals())
    app.run()
else:
    app = web.application(urls, globals()).wsgifunc()

rawDescription: How to connect a webpage with python to mod_wsgi?

description: Connect a webpage with python to mod_wsgi


code:
self.adln = Button(frame, text = "Add Line", command=self.adln)
self.adpt = Button(frame, text = "Add Point", command=self.adpt)
self.canvas.bind("<Button-1>", self.click)

#...
def adln(self):
    self.geometry = "Line"
def adpt(self):
    self.geometry = "Points"
#...

def click(self, event):
    if self.start is None:
        self.start = (event.x, event.y)
    else:
        self.draw_geometry()
        self.start = None
def draw_geometry(self):
    if self.geometry == "Points":
        p1 = Point(*self.start)
        p2 = Point(event.x, event.y)
        p1.draw(self.canvas)
        p2.draw(self.canvas)
    elif self.geometry == "Line":
        line = Line(event.x, event.y, *self.start)
        line.draw(self.canvas)

rawDescription: How to draw geometry in sub-frame by click on it and corresponding button with Tkinter

description: Draw geometry in sub-frame by click on it and corresponding button with Tkinter


code:
import numpy as np
import scipy.interpolate as interp
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

X = [1,1,1,1,2,2,2,2,3,3,3,3]
Y = [1,4,5,6,1,4,5,6,1,4,5,6]
Z = [2,6,3,6,2,7,4,6,2,4,2,3]

plotx,ploty, = np.meshgrid(np.linspace(np.min(X),np.max(X),10),\
                           np.linspace(np.min(Y),np.max(Y),10))
plotz = interp.griddata((X,Y),Z,(plotx,ploty),method='linear')

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(plotx,ploty,plotz,cstride=1,rstride=1,cmap='viridis')  # or 'hot'

rawDescription: Plotting three lists as a surface plot in python using mplot3d


code:
class Data():
  def __init__(self):
    self.vowels = ['a', 'e', 'u', 'i', 'o']

  def __len__(self): # if you want to use len() on your object
    return len(self.vowels) # refer to the list defined in constructor

rawDescription: How to acces a list from a Class constructor, for use in another class method, in python?

description: Acces a list from a Class constructor, for use in another class method, in python


code:
def removeItem(self,position):
    currentNode = ListNode
    previousNode = None
    count = 0

    while count != position:
        #quick check to make sure next node is not empty
        if currentNode.link == None:
            print("Position Invalid")
            return None

        previousNode = currentNode
        currentNode = currentNode.link
        count +=1

    #Node.Link should link to the next node in the sequence.
    previousNode.link = currentNode.link
    return currentNode

rawDescription: Removing a node in a Linked List using Links


code:
class  Fileupload(Resource):

    def get(self):
        pass

    def post(self, user_id):
        pass

    def delete(self, user_id, file_id):
        pass

rawDescription: Python, Flask - How to structure a restful web service method to manage uploaded files?


code:
ajax_safe_representation_of_key = entity.key.urlsafe()

# to retrieve that key
key = ndb.Key(urlsafe=ajax_safe_representation_of_key)
entity = key.get()

rawDescription: How to generate a front end ID for an element in order to retrieve it with an AJAX request?

description: Generate a front end ID for an element in order to retrieve it with an AJAX request


code:
import sys, fileinput

for count, line in enumerate(fileinput.input(filename, inplace=True)):
    if count == 69:  # Python counts from 0
        line = newvalue
    sys.stdout.write(line)

rawDescription: Simple, efficient way to writing to a specific line number in python


code: all_vars = locals().get('all_vars', [])

rawDescription: Python: how to test if potential variable names are in the namespace?


code:
import math

row = 0

IJ.run("Set Measurements...", "area centroid perimeter shape feret's area_fraction   redirect=None decimal=6")
IJ.run("Analyze Particles...")
rt = ResultsTable.getResultsTable()

imp = IJ.getImage()
ip = imp.getProcessor()

for roi in RoiManager.getInstance().getRoisAsArray():
  a = rt.getValue("Feret", row)
  b = rt.getValue("MinFeret", row)
  nu= 1
  L = 1
  p = 1
  sapf = (math.pi/4) * (1/(nu*L)) * math.pow(a, 3) * math.pow(b, 3) / (math.pow(a, 2) + math.pow(a, 2))*p
  rt.setValue("ROI no.", row, row + 1)
  rt.setValue("Sapflow", row, sapf)

  ip.setRoi(roi)
  stats = ImageStatistics.getStatistics(ip, Measurements.AREA, None)
  rt.setValue("Pixel count", row, stats.pixelCount)

  row = row + 1
rt.show("Results")

rawDescription: How to determine the amount of pixel of an given ROI?

description: Determine the amount of pixel of an given ROI


code:
class Main(QtGui.QMainWindow):
      def __init__(self):
          self.setAttribute(Qt.WA_TranslucentBackground)

rawDescription: Setting a transparent main window

description: Setting a transparent main window


rawDescription: decrease size of markers used in basemap and get fullscreen

description: Decrease size of markers used in basemap and get fullscreen


code: action = soup.find('form', id='form_product_page').get('action')

rawDescription: Getting form "action" from BeautifulSoup result


code:
arr = [s.shift(x).values[::-1][:3] for x in range(len(s))[::-1]]
arr
pd.Series(arr, index=s.index)

rawDescription: Creating a Pandas rolling-window series of arrays


code:
def PopularWordWalk (starting_dir, word_dict):
    print ("In", os.path.abspath(starting_dir))
    os.chdir(os.path.abspath(starting_dir))
    for (this_dir,dir_names,file_names) in os.walk('.'):
        for file_name in file_names:
            fpath = os.path.join(os.path.abspath(starting_dir), file_name)
            with open(fpath, 'r') as fileobj:
                text = fileobj.read()
            print(text)

rawDescription: Iterating files with os.walk, but cannot open and print text files


code:
app=TkinterApp()

def refreshApp():
    app.update()
    return True

gobject.idle_add(refreshApp)
loop = gobject.MainLoop()
loop.run()

rawDescription: tkinter integration with glib mainloop

description: Tkinter integration with glib mainloop


code:
# chunks is a list of filenames (you'll need to define generate_chunk_files)
chunks = generate_chunk_files('large_dataframe')
for chunk in chunks:
    # stores each chunk in your PiCloud bucket
    cloud.bucket.put(chunk)

def process_chunk(chunk):
    """Runs on PiCloud"""

    # saves chunk object locally
    cloud.bucket.get(chunk)
    f = open(chunk, 'r')
    # process the data however you want

# asynchronously runs process_chunk on the cloud for all chunks
job_ids = cloud.map(process_chunk, chunks)

rawDescription: What are the steps involved in running the same python script in parallel in amazon ec2 or picloud


rawDescription: Compare two different size matrices to make one large matrix - Speed Improvements?


code:
import pandas as pd
pd.get_dummies(listings['color'], 'color')

rawDescription: Loop that will create new Pandas.DataFrame column


code:
@asyncio.coroutine
def communicate():
    reader, writer = yield from asyncio.open_connection(HOST, PORT)
    writer.write(b'data')
    yield from writer.drain()
    answer = yield from reader.read()
    # process answer, maybe send new data back to server and wait for answer again
    writer.close()

rawDescription: How do I get my asyncio client to call a socket server and waiting for response

description: Get my asyncio client to call a socket server and waiting for response


code:
def storbinary(self, cmd, fp, blocksize=8192, callback=None):
    """Store a file in binary mode.  A new port is created for you.

    Args:
      cmd: A STOR command.
      fp: A file-like object with a read(num_bytes) method.
      blocksize: The maximum data size to read from fp and send over
                 the connection at once.  [default: 8192]
      callback: An optional single parameter callable that is called on
                on each block of data after it is sent.  [default: None]

    Returns:
      The response code.
    """
    self.voidcmd('TYPE I')
    conn = self.transfercmd(cmd)
    while 1:
        buf = fp.read(blocksize)
        if not buf: break
        conn.sendall(buf)
        if callback: callback(buf)
    conn.close()
    return self.voidresp()

rawDescription: Can I upload an object in memory to FTP using Python?

description: Upload an object in memory to FTP using Python


code:
#!/usr/bin/env python
import os
from subprocess import Popen, PIPE

working_dir = b"/home/MTS/Dropbox/dir/In_Files"
for filename in os.listdir(working_dir):
    print("Performing calculations on {filename!r}...".format(**vars()))
    p = Popen(["run_command.command", "-f", "a"], cwd=working_dir, stdin=PIPE)
    p.communicate(input=b"\n".join([b"1", filename, b"4"]))
    if p.returncode != 0: # non-zero exit status may indicate failure
        raise Error

rawDescription: Getting Python to emulate user inputs in an interactive Perl script


code:
def scroll_wheel_up(num_times):
    for i in xrange(1, num_times):
        time.sleep(.005)
        multiplier = 1 - (float(i) / num_times)
        speed = 4 * multiplier
        event = CGEventCreateScrollWheelEvent(None, 0, 1, speed)
        CGEventPost(kCGHIDEventTap, event)

rawDescription: Smooth Scrolling with Quartz.CoreGraphics in Python


code:
import math
import winsound
import time

labels = ['a','a#','b','c','c#','d','d#','e','f','f#','g','g#']
# name is the complete name of a note (label + octave). the parameter
# n is the number of half-tone from A4 (e.g. D#1 is -42, A3 is -12, A5 is 12)
name   = lambda n: labels[n%len(labels)] + str(int((n+(9+4*12))/12))
# the frequency of a note. the parameter n is the number of half-tones
# from a4, which has a frequency of 440Hz, and is our reference note.
freq   = lambda n: int(440*(math.pow(2,1/12)**n))

# a dictionnary associating note frequencies to note names
notes  = {name(n): freq(n) for n in range(-42,60)}

# the period expressed in second, computed from a tempo in bpm
period = lambda tempo: 1/(tempo/60)

# play each note in sequence through the PC speaker at the given tempo
def play(song, tempo):
    for note in song.lower().split():
        if note in notes.keys():
            winsound.Beep(notes[note], int(period(tempo)*1000))
        else:
            time.sleep(period(tempo))

# "au clair de la lune"!! 'r' is a rest
play( 'c4 c4 C4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '
      'c4 C4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r '
      'd4 d4 d4 d4 A3 r a3 r d4 c4 B3 a3 g3 r r r '
      'c4 c4 c4 d4 e4 r d4 r c4 e4 d4 d4 c4 r r r ', 180 )

rawDescription: How can i create a melody? Is there any sound-module?

description: Create a melody? Is there any sound-module


code:
from eve.io.media import MediaStorage

class AmazonS3MediaStorage(MediaStorage):
    """ Your actual implementation """
    pass

app = Eve(media=AmazonS3MediaStorage)

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

rawDescription: how to upload image through python-eve to some external storage server e.g. S3?

description: Upload image through python-eve to some external storage server e.g. S3


code:
myNewDict = {v: k for k, v in myDict.iteritems()}
myNewList = [myNewDict[x] for x in myList]

rawDescription: Convert elements in a list using a dictionary key


code:
class _Context:
    foo = 'bar'
render(request, 'example.html', vars(_Context))

rawDescription: Something better than locals() or dict(foo=foo) for exporting context to template engines


code:
with open("file_1.idx", "r") as file_1, open("file_2.rtf", "w") as file_2:
    for line in file_1:
        if "abc" in line:
            file_2.write(line)

rawDescription: Python iterate and write to second file

description: Python iterate and write to second file


code:
def __getattr__(self, attr):
    if attr in self.__dict__:
        return self.__dict__[attr]

    # Proxy virConnect API calls
    libvirtconn = self.__dict__.get("_libvirtconn")
    return getattr(libvirtconn, attr)

rawDescription: Where is this python method defined?

description: Where is this python method defined


rawDescription: Computing number of new IDs seen each day in Pandas


code:
def nest (flow, root_rep_id_list, deep = 0):
    msglist = []
    nested_comments = []
    deep += 1

    for rep_id in root_rep_id_list:
        if rep_id in flow:
            msglist.append(flow[rep_id])

    for msg in msglist:
        nested_comments.append(Nestedobject (msg, nest(flow, msg.replies, deep) if msg.replies else None, deep))
        logging.error(msg.replies)
    return nested_comments

rawDescription: Nested comments in gae/python

description: Nested comments in gae/python


code: df  = pd.DataFrame({'value' : [0,0,0,0,0,0,0,0,0,0]}, index=pd.date_range(pd.datetime(2014,3,30), freq='B', periods=10))

rawDescription: Dataframe creation with weekdays or adding week days


code:
def insert(self,t):
    '''inserts a new element into the tree'''
    if self.root is None:
        self.root = Node(t)
    else:
        self._do_insert(self.root,t)

def _do_insert(self,parent,t):
    if t > parent.key:
        if parent.left is None:
            parent.left = Node(t)
        else:
            self._do_insert(parent.left,t)
    elif t < parent.key:
        if parent.right is None:
            parent.right = Node(t)
        else:
            self._do_insert(parent.right,t)
    else:
        # raise a KeyError or something appropriate?
        pass

rawDescription: Binary Search Tree in python not working


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

# Fake Data
x = range(1,101)
y = 5 * np.log(x) + np.random.rand(len(x))

# Fit
coefficients = np.polyfit(np.log(x),y,1) # Use log(x) as the input to polyfit.
fit = np.poly1d(coefficients)

plt.plot(x,y,"o",label="data")
plt.plot(x,fit(np.log(x)),"--", label="fit")
plt.legend()
plt.show()

rawDescription: How plot ployfit n log n with python?

description: How plot ployfit n log n with python


code: ln -s -T /opt/appname/main.py /usr/bin/appname.py

rawDescription: Structuring a Python App (eventually for deb packaging)


code:
import collections
codes = collections.defaultdict(list)
for line in open('code_postaux_v201410.csv'):
    if not line[:1].isdigit():
        continue
    row = line.strip().split(';')
    codes[row[2]]+= [row[1].strip()]

def test_failures(regexp):
    r = re.compile(regexp)
    return [code for code in codes if not r.match(code)]

len(test_failures(r'^((0[1-9]{1})|([1-8]{1}[0-9]{1})|9[0-5]{1})[0-9]{3}$'))
# 283 !

# not ideal, because it does not guarantee the input to be an existing one
len(test_failures(r'^0[1-9]|[1-8][0-9]|9[0-8]|2A|2B[0-9]{3}$'))
# but at least no miss!

rawDescription: Python regex for integers combination from 01000 to 95999


code:
import random

length = random.randrange(5, 16)

randstr = ''.join(random.choice(letters) for _ in range(length))

rawDescription: Constructing a random string

description: Constructing a random string


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-

import MySQLdb

mystring = "Bientôt l'été"

myinsert = [ { "name" : mystring.encode("utf-8").strip()[:65535], "id" : 1 } ]

con = None
con = MySQLdb.connect('localhost', 'abc', 'def', 'ghi');
cur = con.cursor()

cur.execute("set names utf8;")     # <--- add this line,

sql = "INSERT INTO 'MyTable' ( 'my_id', 'my_name' ) VALUES ( %(id)s, %(name)s ) ; "
cur.executemany( sql, myinsert )
con.commit()
if con: con.close()

rawDescription: How to correctly insert utf-8 characters into a MySQL table using python

description: Correctly insert utf-8 characters into a MySQL table using python


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

dataset = [{'A':19, 'B':39, 'C':61, 'D':70},
           {'A':34, 'B':68, 'C':32, 'D':38},
           {'A':35, 'B':45, 'C':66, 'D':50},
           {'A':23, 'B':23, 'C':21, 'D':16},
           {'A':35, 'B':45, 'C':66, 'D':50}]
data_orders = [['A', 'B', 'C', 'D'],
               ['B', 'A', 'C', 'D'],
               ['A', 'B', 'D', 'C'],
               ['B', 'A', 'C', 'D'],
               ['A', 'B', 'C', 'D']]
colors = ["r","g","b","y"]
names = sorted(dataset[0].keys())
values = np.array([[data[name] for name in order] for data,order in zip(dataset, data_orders)])
lefts = np.insert(np.cumsum(values, axis=1),0,0, axis=1)[:, :-1]
orders = np.array(data_orders)
bottoms = np.arange(len(data_orders))

for name, color in zip(names, colors):
    idx = np.where(orders == name)
    value = values[idx]
    left = lefts[idx]
    plt.bar(left=left, height=0.8, width=value, bottom=bottoms,
            color=color, orientation="horizontal", label=name)
plt.yticks(bottoms+0.4, ["data %d" % (t+1) for t in bottoms])
plt.legend(loc="best", bbox_to_anchor=(1.0, 1.00))
plt.subplots_adjust(right=0.85)
plt.show()

rawDescription: Stacked bar chart with differently ordered colors using matplotlib


code:
key="Key1"
value = "Value1"
'{!r:<10}:{!r:>10}'.format(key, value)

rawDescription: python - formatting a string with key value pair separate by ':'

description: Python - formatting a string with key value pair separate by ':'


code:
from collections import defaultdict
from operator import itemgetter

sums = defaultdict(int)
for key, value in gona:
    sums[key] += value

new_gona = sorted(sums.iteritems(), key=itemgetter(0))

rawDescription: Adding up values in a 2D array in Python


code:
def callback():
    n = int(e.get())
    result = factorial(n)
    t.insert("1.0", str(result))

rawDescription: Python GUI - Print into text box instead of Shell Py 3.3


code:
def grab_main_color(self, rect, max_colors=256):
    """returns a tuple with the RGB value of the most present color in the given rect"""
    img=ImageGrab.grab(rect)
    colors = img.getcolors(max_colors)
    max_occurence, most_present = 0, 0
    try:
        for c in colors:
            if c[0] > max_occurence:
                (max_occurence, most_present) = c
        return most_present
    except TypeError:
        raise Exception("Too many colors in the given rect")

rawDescription: Simulate mouse click/Detect color under cursor in Python


code:
import subprocess
cmd = ['psql', '-d', 'test', '-U', 'postgres', '-f', 'test_points.pgsql']
subprocess.Popen(cmd)  # will run in the background if the output is not used in the rest of the script

rawDescription: How can I start a query in PostgreSQL, then detach the initiating program (e.g. python) so it can be closed, leaving the query to run for days

description: Start a query in PostgreSQL, then detach the initiating program (e.g. python) so it can be closed, leaving the query to run for days


code:
import random, threading, webbrowser

port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)

threading.Timer(1.25, lambda: webbrowser.open(url) ).start()

app.run(port=port, debug=False)

rawDescription: Python - Flask - open a webpage in default browser


code:
import gdata.spreadsheets.client
import gdata.spreadsheets.data
import gdata.gauth

# create the OAuth2 token
token = gdata.gauth.OAuth2Token(client_id='CLIENTID',
                                client_secret='CLIENTSECRET',
                                scope='https://spreadsheets.google.com/feeds/',
                                user_agent='blah.blah',
                                access_token='ACCESSTOKEN',
                                refresh_token='REFRESHTOKEN')

# create the spreadsheet client and authenticate
spr_client = gdata.spreadsheets.client.SpreadsheetsClient()
token.authorize(spr_client)

#create a ListEntry. the first item of the list corresponds to the first 'header' row
entry = gdata.spreadsheets.data.ListEntry()
entry.set_value('ham', 'gary')
entry.set_value('crab', 'sack')

# add the ListEntry you just made
spr_client.add_list_entry(entry, 'SPREADSHEETID', 'od6')

rawDescription: insert row python gdata.spreadsheets.client

description: Insert row python gdata.spreadsheets.client


code:
def replace_unicode(s):
    # helper function which returns the unicode char for a re match object
    def unirepl(m):
        return unichr(int(m.group(1), 16))

    return re.sub(r"<U([0-9a-fA-F]{4})>", unirepl, s)

rawDescription: pythonic way to replace numbers in a string with their unicode character

description: Pythonic way to replace numbers in a string with their unicode character


code:
x = 'ranganath'
[ x[i:i+2] for i in xrange(0,len(x),2) ]

rawDescription: Suggestions to split a string into substring


code:
from math import isnan
testList = [float('nan'), float('nan'), 5.5, 5.0, 5.0, 5.5, 6.0, 6.5]
next(x for x in testList if not isnan(x))

rawDescription: return first non NaN value in python list

description: Return first non NaN value in python list


rawDescription: how to declare variable type, C style in python

description: Declare variable type, C style in python


code:
import numpy as np
aa = np.random.random((5, 5))

m = np.mean(aa)
d = 0.8 - m  # value to add
bb = aa + d

if d > 0:  # Modify values  != 1
    ii = aa + d > 1
    d2 = np.sum(bb[ii] - 1)
    bb[ii] = 1
    bb[~ii] = bb[~ii] + d2/np.sum(~ii)
elif d < 0:  # Modify values  != 0
    ii = aa + d < 0
    d2 = np.sum(bb[ii])
    bb[ii] = 1
    bb[~ii] = bb[~ii] + d2/np.sum(~ii)

print("The mean of bb is %f" % np.mean(bb))

rawDescription: Change cell values in numpy 2D array to match a number


rawDescription: Python - Get list of every permutation of a list of a set number of characters


code:
Counter('string string')
Counter('string string'.split())

rawDescription: getting the mid frequency words from a list and getting their synonyms by web scraping Indo Wordnet in python

description: Getting the mid frequency words from a list and getting their synonyms by web scraping Indo Wordnet in python


code:
for i in range(1,4):

    h = open('header{0}.txt'.format(i),'r')
    d = open('data{0}.txt'.format(i),'r')
    a = open('asc{0}.txt'.format(i),'a')

    hdata = h.readlines()
    ddata = d.readlines()
    a.writelines(hdata+ddata)
    a.close()

rawDescription: How to combine header files with data files with python?

description: Combine header files with data files with python


code:
with open('datafile') as fin:
    lines = list(fin)
    lines.sort(key=lambda line: line.split()[1])

with open('outfile','w') as fout:
    fout.writelines(lines)

rawDescription: Processing files in memory

description: Processing files in memory


code:
L = [' 1 2 ', '3 4 ']
[tuple(int(y) for y in x.split()) for x in L]

rawDescription: Converting a list of strings, into a list of tuples containing integers


code:
try:
    ar = ar.flatten()
except AttributeError:
    if not return_inverse and not return_index:
        return np.sort(list(set(ar)))
    else:
        ar = np.asanyarray(ar).flatten()

rawDescription: Numpy.unique behavior (flattening insconsistencies?)


code:
response=self.app.post('/test_function',
                       data=json.dumps(dict(foo='bar')),
                       content_type = 'application/json')

rawDescription: How to send requests with JSONs in unit tests

description: Send requests with JSONs in unit tests


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

fig, ax = plt.subplots()
pd.DataFrame(np.random.randn(100, 2)).cumsum().plot(ax=ax)

rawDescription: How do you make plotting two pandas Series in the same ipython notebook cell use different colors automatically?

description: Make plotting two pandas Series in the same ipython notebook cell use different colors automatically


rawDescription: python pandas OLS.predict, what is the correct signature?

description: Python pandas OLS.predict, what is the correct signature


code:
from itertools import groupby

def overlaps(a, b):
    result = True
    # Supposing a[2] is the start, a[3] the end.
    # If end before start, they are not overlapping
    if a[3] < b[2] or b[3] < a[2]:
        result = False

    return result

def test_overlapping(hits):
    overlapping = 'None'
    overlapping_count = 0
    for i in range(len(hits)-1):
        if overlaps(hits[i], hits[i+1]):
            overlapping_count += 1

    if overlapping_count == 0:
        overlapping = 'None'
    elif overlapping_count == len(hits) -1:
        overlapping = 'All'
    else:
        overlapping = 'Some'

    return overlapping

fh = open('file.txt')

file_all = open('result_all.txt', 'w')
file_some = open('result_some.txt', 'w')
file_none = open('result_none.txt', 'w')

line = fh.readline() # quit header

for qid, grp in groupby(fh, lambda l: l.split()[0]):
    hits = []
    for line in grp:
        hsp = line.split()
        hsp[2], hsp[3] = int(hsp[2]), int(hsp[3])
        hits.append(hsp)
    if len(hits) > 1:
        hits.sort(key=lambda x: x[2])
        overlapping = test_overlapping(hits)
        out_file = file_none
        if overlapping == 'All':
            out_file = file_all
        elif overlapping == 'Some':
            out_file = file_some

        for h in hits:
            out_file.write('\t'.join([str(v) for v in h]))
            out_file.write('\n')

file_all.close()
file_some.close()
file_none.close()

rawDescription: Finding overlapping and non overlapping regions


code:
import numpy as np

m = 15
n = 18
fecundity = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 1, 2, 1, 1, 1])
Bunnies = np.array([0]*m)
Rabbits = np.array([1]+[0]*(m-1))

for month in range(0, 18):
    # every month I shift the list of 1 since they're getting older
    Rabbits = np.roll(Rabbits, 1)
    # I set the newborns as 0
    Rabbits[0] = 0
    # I calculate the newborns
    Bunnies = Rabbits * fecundity
    # and then I assign them to the rabbits 0 month old
    Rabbits[0] = sum(Bunnies)

# the sum of Rabbits is the number of final pairs of Rabbits after n months
Total_Rabbits = sum(Rabbits)
# 26 Rabbits

rawDescription: Fibonacci mortal rabbits with variable fecundity


code:
import csv
reader = csv.reader(open('myfile.csv', 'rb'), dialect='excel-tab')
fieldnames = ['Name','Class']
writer = csv.DictWriter(open('myfile.csv', 'rb'), fieldnames, restval='', extrasaction='ignore', dialect='excel-tab')

for row in reader:
    newrow = {}
    for field in row:
        key = field.split(' ', 1)[0]
        newrow[key] = field
    writer.writerow(newrow)

rawDescription: Parsing a tab-separated file with missing fields


code:
def line(n):
    for i in range(n):
        print(i+1, end='')
    print()

rawDescription: How to make a number triangle

description: Make a number triangle


code:
def function():
    if condition1:
        reaction1()
    elif condition2:
        reaction2()
    else:
        deafult_reaction()

rawDescription: How would I put an if statement inside a function?


rawDescription: Regular Expression to Match All Enclosed '' (2 Single Quotes)


code:
title_data = Title.objects \
    .filter(language=language) \
    .filter(page__menuorder__menu__name=kwargs['menu']) \
    .order_by('page__menuorder__priority')

rawDescription: Django prefetching nested tables

description: Django prefetching nested tables


code:
def hasRunFromUnitTest():
    return 'unittest' in sys.modules

rawDescription: How can I detect if my python script/code was ran from a python unittest?

description: Detect if my python script/code was ran from a python unittest


code:
from django.contrib.admin.filterspecs import RelatedFilterSpec, FilterSpec
from models import Gallery

class GalleryFilterSpec(RelatedFilterSpec):
    def __init__(self, f, request, params, model, model_admin):
        self.lookup_kwarg = f.name
        self._lookup_model = f.rel.to
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)
        self.user = request.user
        self.lookup_choices = [(g.pk, g.name) for g in Gallery.objects.all()]

    def has_output(self):
        return len(self.lookup_choices) > 1

    def title(self):
        return self._lookup_model._meta.verbose_name

FilterSpec.filter_specs.insert(0,
        (lambda f: f.rel.to == Gallery, GalleryFilterSpec))

rawDescription: Django admin, filter objects by ManyToMany reference


code:
import numpy as np
np.random.seed(1)
N = 10
b1 = np.random.rand(N)
b2 = np.random.rand(N)
X = np.column_stack([b1, b2])
X -= X.mean(axis=0)
fact = N - 1
by_hand = np.dot(X.T, X.conj()) / fact
print(by_hand)
# [[ 0.04735338  0.01242557]
#  [ 0.01242557  0.07669083]]

using_cov = np.cov(b1, b2)

assert np.allclose(by_hand, using_cov)

rawDescription: Python: Covariance matrix by hand

description: Python: Covariance matrix by hand


code: reader.fieldnames = "email", "name", "id",  "phone"

rawDescription: Replace fieldnames when using DictReader


code:
if os.listdir(os.path.join(DIR2, dirName)):
    print("Not empty!")

rawDescription: IF statement : Shell to python

description: IF statement : Shell to python


code:
from kivy.app import App
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.lang import Builder

Builder.load_string("""

<Test>:
    size_hint: .5, .5
    pos_hint: {'center_x': .5, 'center_y': .5}
    do_default_tab: False

    TabbedPanelItem:
        text: 'first tab'
        Label:
            text: 'First tab content area'
    TabbedPanelItem:
        id: tab2
        text: 'tab2'
        BoxLayout:
            Label:
                text: 'Second tab content area'
            TextInput:
                text: 'Button that does nothing'
                focus: root.current_tab == tab2   # <--- this is it! also can be changed to "== self.parent.parent"
""")

class Test(TabbedPanel):
    pass

class TabbedPanelApp(App):
    def build(self):
        t = Test()
        return t

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

rawDescription: Kivy TabbedPanel Autofocus

description: Kivy TabbedPanel Autofocus


code: object.__setattr__(self, name, value)

rawDescription: __setattr__ only when attribute does not exist


code:
import numpy as np
np.random.seed(1977)
import matplotlib.pyplot as plt

# Generate data...
x_obs = np.linspace(-2, 2, 20)
true_model = [0.2, -0.1, 4, 2, 1, 0]

noise = np.random.normal(0, 5, x_obs.shape)
y_obs = np.polyval(true_model, x_obs) + noise

# Fit to a 5-th order polynomial
fit_model = np.polyfit(x_obs, y_obs, 5)

x = np.linspace(-3, 3, 100)
y_true = np.polyval(true_model, x)
y_pred = np.polyval(fit_model, x)

# Made up confidence intervals (I'm too lazy to do the math...)
high_bound = y_pred + 3 * (0.5 * x**4 + 3)
low_bound = y_pred - 3 * (0.5 * x**4 + 3)

# Plot the results...
fig, ax = plt.subplots()
ax.fill_between(x, high_bound, low_bound, color='gray', alpha=0.5)
ax.plot(x_obs, y_obs, 'ko', label='Observed Values')
ax.plot(x, y_pred, 'k--', label='Predicted Model')
ax.plot(x, y_true, 'r-', label='True Model')
ax.legend(loc='upper left')
plt.show()

rawDescription: Plotting a probability density

description: Plotting a probability density


rawDescription: xlwt - Print Range Settings

description: Xlwt - Print Range Settings


code:
import multiprocessing
from functools import partial
filename = "file1.txt"
pat = "afow"
N = 1000

""" This is the naive string search algorithm"""

def search(pat, txt):
    patLen = len(pat)
    txtLen = len(txt)
    offsets = []

    # A loop to slide pattern[] one by one
    # Range generates numbers up to but not including that number
    for i in range ((txtLen - patLen) + 1):

    # Can not use a for loop here
    # For loops in C with && statements must be
    # converted to while statements in python
        counter = 0
        while(counter < patLen) and pat[counter] == txt[counter + i]:
           counter += 1
           if counter >= patLen:
               offsets.append(i)
        return str(offsets).strip('[]')

if __name__ == "__main__":
     tasks = []
     pool_outputs = []
     pool = multiprocessing.Pool(processes=5)
     lines = []
     with open(filename, 'r') as infile:
         for line in infile:
             lines.append(line.rstrip())
     tasks = lines
     func = partial(search, pat)
     if len(lines) > N:
        pool_output = pool.map(func, lines )
        pool_outputs.append(pool_output)
     elif len(lines) > 0:
        pool_output = pool.map(func, lines )
        pool_outputs.append(pool_output)
     pool.close()
     pool.join()
     print('Pool:', pool_outputs)

rawDescription: Better examples of Parallel processing in Python


code:
def get_table_data(self):
    return [self.object]

rawDescription: django: django-tables2 DetailView CBV won't display single object

description: Django: django-tables2 DetailView CBV won't display single object


code:
merged_file['ratio'] = [fuzz.ratio(a, b)
                        for a, b in zip(merged_file.iloc[:,7], merged_file.iloc[:,33])]

rawDescription: pandas and fuzzywuzzy match percentage not turning correct

description: Pandas and fuzzywuzzy match percentage not turning correct


code:
import itertools
list(itertools.compress(s_list, b_list))

rawDescription: Get elements from one list based on another boolean list


code:
import sqlalchemy.types
from sqlalchemy import Column
from sqlalchemy.ext.declarative import ( declarative_base,
                                         _declarative_constructor )

from camelot.admin.entity_admin import EntityAdmin
from camelot.model import metadata
import camelot.types

from elixir import session

class Entity( object ):

    def __init__( self, **kwargs ):
        _declarative_constructor( self, **kwargs )
        session.add( self )

Entity = declarative_base( cls = Entity,
                           metadata = metadata,
                           constructor = None )

class Movie( Entity ):

    __tablename__ = 'movie'

    id = Column( sqlalchemy.types.Integer, primary_key = True )
    name = Column( sqlalchemy.types.Unicode(50), nullable = False )
    cover = Column( camelot.types.Image(), nullable = True )

    class Admin( EntityAdmin ):
        list_display = ['name']
        form_display = ['name', 'cover']

rawDescription: Is Python Camelot tied to Elixir?

description: Is Python Camelot tied to Elixir


code:
df = df.convert_objects(convert_numeric=True)
df[:2]
df.dtypes

rawDescription: Column type inference for heterogeneous vector of ints and floats [pandas]


code:
import wx

class MyFrame(wx.Frame):
  def __init__(self, title, *args, **kwargs):
    super(MyFrame, self).__init__(None, title=title, *args, **kwargs)
    panel  = wx.Panel(self)
    button = wx.Button(panel, label="Button")
    tooltip = wx.ToolTip("Try to click this button")
    button.SetToolTip(tooltip)

class MyApp(wx.App):
  def OnInit(self):
    self.frame = MyFrame("Example")
    self.frame.Show()
    return True

MyApp(False).MainLoop()

rawDescription: wxPython showing help upon mouse focus

description: WxPython showing help upon mouse focus


rawDescription: Find indices of elements equal to zero from numpy array


code:
d = {"response": {"body": {"contact": {"email": "mr@abc.com", "mobile_number": "0123456789"}, "personal": {"last_name": "Muster", "gender": "m", "first_name": "Max", "dob": "1985-12-23", "family_status": "single", "title": "Dr."}, "customer": {"verified": "true", "customer_id": "1234567"}}, "token": "dsfgf", "version": "1.1"}}
df = pd.io.json.json_normalize(d)
df.columns = df.columns.map(lambda x: x.split(".")[-1])
df

rawDescription: Nested Json to pandas DataFrame with specific format


code:
# condition ? trueValue : falseValue
trueValue if condition else falseValue

rawDescription: Conditional operator in Mako using Pylons


code:
for v in a.values():
    del v[2]   # or v[n] in general

rawDescription: Python - delete multiple list elements in dictionary


rawDescription: How to add an empty column to a dataframe?

description: Add an empty column to a dataframe


code:
from Tkinter import *

master = Tk()

person = ["P1","P2","P3"]
result = {}

for i in person:
    result[i] = Variable()
    Checkbutton(master, text=i, variable=result[i]).pack()

master.mainloop()

rawDescription: Python TKinter: Each item in a Python list becomes the title of a Tkinter checkbutton


rawDescription: How do I parse a text file in dictionary form and put it into a dictionary in python?

description: Parse a text file in dictionary form and put it into a dictionary in python


code:
myGrid = gridlib.Grid(panel)
sizer.Add(myGrid, 1, wx.EXPAND|wx.ALL)

rawDescription: how to make wxpython grid automatic fit-to-window

description: Make wxpython grid automatic fit-to-window


code:
import os
from xml.etree import ElementTree
file_name = "example.xml"
full_file = os.path.abspath(os.path.join("xml", file_name))
dom = ElementTree.parse(full_file)
Fruit = dom.findall("Fruit")

for f in Fruit:
    Explanation = f.find("Explanation").text
    Types = f.findall("Type")
    for t in Types:
        Type = t.text
        print ("{0}, {1}".format(Type, Explanation))

rawDescription: Get data from XML file Python

description: Get data from XML file Python


code:
def stringsInDic(Rack, dictionary):
    func = functools.partial(test, Rack)
    return filter(func, dictionary)

rawDescription: Filter( ) function takes function with two inputs


code:
import psutil
all_processes = [p.as_dict() for p in psutil.process_iter()]

rawDescription: Querying the Status of a Service on mac using python


code:
import Tkinter as tk

class CustomDialog(tk.Toplevel):
    def __init__(self, parent, prompt):
        tk.Toplevel.__init__(self, parent)

        self.var = tk.StringVar()

        self.label = tk.Label(self, text=prompt)
        self.entry = tk.Entry(self, textvariable=self.var)
        self.ok_button = tk.Button(self, text="OK", command=self.on_ok)

        self.label.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x")
        self.ok_button.pack(side="right")

        self.entry.bind("<Return>", self.on_ok)

    def on_ok(self, event=None):
        self.destroy()

    def show(self):
        self.wm_deiconify()
        self.entry.focus_force()
        self.wait_window()
        return self.var.get()

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.button = tk.Button(self, text="Get Input", command=self.on_button)
        self.label = tk.Label(self, text="", width=20)
        self.button.pack(padx=8, pady=8)
        self.label.pack(side="bottom", fill="both", expand=True)

    def on_button(self):
        string = CustomDialog(self, "Enter something:").show()
        self.label.configure(text="You entered:\n" + string)

if __name__ == "__main__":
    root = tk.Tk()
    root.wm_geometry("400x200")
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: How do I return a result from a dialog?

description: Return a result from a dialog


code:
def isPointerType(t):
    if issubclass(t, _ctypes._Pointer): return True
    return False

def getValueOf(obj):
    if isPointerType(obj.__class__):
        return cast(obj, c_void_p).value
    else:
        return obj.value

def static_cast(obj, t):
    newObj = t()
    if isPointerType(t):
        cast(pointer(obj), POINTER(c_void_p)).contents.value = getValueOf(obj)
    else:
        newObj.value = getValueOf(obj)
    return newObj

rawDescription: ctypes cast c_uint64 to c_char_p

description: Ctypes cast c_uint64 to c_char_p


code: [(i,i) for i  in xrange(1,6)]

rawDescription: Fastest way to create range of tuples in Python


code:
class HistoricalData(object):

    def __init__(self):
        self.dataPoints = {}

rawDescription: Instantiating class retains references

description: Instantiating class retains references


code:
import textwrap
string = 'A string with words'
textwrap.wrap(string,15)

rawDescription: Splitting a string using space delimiters and a maximum length


code:
import matplotlib.pyplot as plt
from scipy.ndimage.interpolation import rotate
import scipy.misc
lena = scipy.misc.lena()
rotated_lena = rotate(lena, 30, reshape=True)
f, (ax0,ax1) = plt.subplots(1,2)
ax0.imshow(lena, cmap='gray')
ax1.imshow(rotated_lena, cmap='gray')
plt.show()  # shows a normal version of Lena and a version that is rotated by 30° CCW, uncropped

rawDescription: rotate image without cropping it, with skimage

description: Rotate image without cropping it, with skimage


code:
class Region(tuple):
    pass

region = Region(( "buffer", "region" ))
region.cmd = ( "kill", "mark" )

rawDescription: Python, extend/add field to tuple

description: Python, extend/add field to tuple


code:
import pandas as pd
df = pd.DataFrame({"pear": [1,2,3], "apple": [2,3,4], "orange": [3,4,5]})

len(df.columns)
3

rawDescription: Python pandas dataframe: retrieve number of columns


code:
for index, item in enumerate(L):
  if a in item or b in item:
    r.append(index)

rawDescription: Python - Searching index of lists in list containing one element


code:
# assuming you have values each on separate line
values = []
for line in open('path-to-the-file'):
    values.append(line)
    # might want to implement stripping newlines and such in here
    # by using line.strip() or .rstrip()

# or perhaps more than one value in a line, with some separator
values = []
for line in open('path-to-the-file'):
    # e.g. ':' as a separator
    separator = ':'
    line = line.split(separator)
    for value in line:
        values.append(value)

# or all in one line with separators
values = open('path-to-the-file').read().split(separator)
# might want to use .strip() on this one too, before split method

rawDescription: Importing a text file to create a list in Python 3.x?


code:
root = Tk()

label1 = Label(root, text = "Dive number")
E1 = Entry(root, bd = 5)

label2 = Label(root, text = "Time in")
E2 = Entry(root, bd = 5)

label3 = Label(root, text = "Time out")
E3 = Entry(root, bd = 5)

label4 = Label(root, text = ("Max depth"))#--------------NEW--------------
E4 = Entry(root, bd = 5)

def getinfo():
    print (E1.get())
    print (E2.get())
    print (E3.get())
    print (E4.get())

submit = Button(root, text = "submit", command = getinfo)
label1.pack()
E1.pack()
label2.pack()
E2.pack()
label3.pack()
E3.pack()
label4.pack()
E4.pack()
submit.pack(side =BOTTOM)
root.mainloop()

rawDescription: Use 4 input boxes rather than 3 in tkinter?


code:
import shutil
from subprocess import Popen, PIPE
from threading import Thread

def copy_and_close(source, destination):
    with source, destination:
        shutil.copyfileobj(source, destination)

agx_cmd = ("tibrvlisten -service {agxService} -network {agxNetwork} "
           "-daemon {domain}".format(**vars())).split()
agx_process = Popen(agx_cmd, stdout=PIPE, bufsize=1)
agx_file = open(self.AGX_logFileName, 'wb')
agx_file.write(agx_process.stdout.readline()) # block until a line is read
Thread(target=copy_and_close, args=[agx_process.stdout, agx_file]).start()
# do other things here..
rc = agx_process.wait()

rawDescription: How should I have one process blocked until another process writes a line to a file?


rawDescription: Python float to string: how to get '0.03' but '-.03'


code:
def append_it(filename):
    return "{0}_{2}.{1}".format(*filename.rsplit('.', 1) + [generate_id()])

rawDescription: How to add an id to filename before extension?

description: Add an id to filename before extension


code:
import ntpath, posixpath

assert ntpath.join("a", "b") == r"a\b"
assert posixpath.join("a", "b") == "a/b"

rawDescription: concatenate paths for linux and windows at the same time

description: Concatenate paths for linux and windows at the same time


code:
import matplotlib.pyplot as plt

# Using this layout to make the grouping clear
data = [('apples', [0.1, 0.25]),
        ('oranges', [0.6, 0.35]),
        ('pears', [0.1, 0.18]),
        ('bananas', [0.7, 0.98]),
        ('peaches', [0.6, 0.48])]

# Reorganize our data a bit
names = [item[0] for item in data]
predicted = [item[1][0] for item in data]
observed = [item[1][1] for item in data]

# It might make more sense to use a bar chart in this case.
# You could also use `ax.scatter` to plot the data instead of `ax.plot`
fig, ax = plt.subplots()
ax.plot(predicted, color='lightblue', marker='o', linestyle='none',
        markersize=12, label='Predicted')
ax.plot(observed, color='red', marker='s', linestyle='none',
        markersize=12, label='Observed')

ax.margins(0.05)
ax.set(xticks=range(len(names)), xticklabels=names, ylabel='Meaningless')
ax.legend(loc='best', numpoints=1)
ax.grid(axis='x')

plt.show()

rawDescription: Plotting ordinal data with a marker in matplotlib


code:
from Tkinter import *
from Tkinter import Tk

root = Tk()
usernameVal = StringVar()
class myclass():

    def __init__(self):
        self.main()

    def submitForm(self,*args):
        try:
            print("submitForm pressed")

            print('name is %s' % self.usernameVal.get()) #mira como hace el print!
            self.usernameVal.set("")

            #usernameVal.clear(1.0, END)  ??

        except ValueError:
            pass

    def main(self):

    #container view
        mainframe = Frame(root) #  mainframe contained by root!, init

        mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) #  add subview mainframe
        mainframe.columnconfigure(0, weight=1)
        mainframe.rowconfigure(0, weight=1)

    #UI widgets
        createLbl = Label(mainframe, text='Create login & Password')
        createLbl.grid(column=2 , row=1, sticky=(W,E))

    # user name
        nameLbl = Label(mainframe, text='User Name')
        nameLbl.grid(column=1 , row=2, sticky=(W,E))

        self.usernameVal = StringVar()
        usernameTf = Entry(mainframe, textvariable = self.usernameVal)
        usernameTf.grid(column=2 , row=2, sticky=(W,E))

        button = Button(mainframe, text='Create User', command=self.submitForm)
        button.grid(column=3 , row=2, sticky=(W,E))

    #my loop
        root.mainloop()

if __name__ == "__main__":
    myclass()

rawDescription: python clear textField "Entry"

description: Python clear textField "Entry"


code:
datum = 0
end = len(lists)
while datum < end:
    # do stuff

    # don't forget to increment datum
    datum += 1

rawDescription: Updating Index Value in For Loop

description: Updating Index Value in For Loop


code:
import signal, os

def handler(signum, frame):
    print('Signal handler called with signal', _)

# Set the alarm to fire every second
signal.signal(signal.SIGALRM, handler)
signal.alarm(1)

# ... Do stuff - the alarm will keep firing ...

# Done: clear alarm
signal.alarm(0)

rawDescription: How do I change a variable periodically while keeping the rest of my programming running at normal speed?

description: Change a variable periodically while keeping the rest of my programming running at normal speed


rawDescription: Pandas Python: why does np.round() 3.601626 to 2 dp returns 3.6?


code:
meanTrialTypeRt = [Rt[trialTypeData == trialType].mean()
                   for trialType in xrange(4)]

rawDescription: Numpy arrays instead of python lists - using nditer to create a 2d array from two 1d arrays


code:
array=[BoundName1, BoundName2, BoundName3]
ReprioritizeBoundaries(["NAME:NewOrder"] + array)

rawDescription: Passing an Array to Function with "..."

description: Passing an Array to Function with "..."


code:
x = np.array([1, 0, 1, 1, 0, 0])
np.where(x)[0] # returns a tuple hence the [0], see help(np.where)
# array([0, 2, 3])
x.nonzero()[0] # in this case, the same as above.

rawDescription: Python numpy index set from Boolean array


code:
import shelve
a = shelve.open("output")
a['lin_clf'] = lin_clf
a.close()

rawDescription: Using scikit SVM generated model in another code


code:
res = rs.get(url, headers={'referer': 'https://www.ris.gov.tw/id_card/'})
with open('check.jpg', 'wb') as jpeg_file:
    jpeg_file.write(res.content)

rawDescription: Python crawler verification picture

description: Python crawler verification picture


code: associate(instance_id=None, network_interface_id=None, private_ip_address=None, allow_reassociation=False, dry_run=False)

rawDescription: Boto Ec2 and elastic IP's

description: Boto Ec2 and elastic IP's


code:
user = User.objects.get(username='user123')
friendships = Friendship.objects.filter(Q(receiver=user) | Q(sender=user))

usernames = []

for friendship in friendships:
    if friendship.receiver == user:
        usernames.append(friendship.receiver.username)
    else:
        usernames.append(friendship.sender.username)

rawDescription: Django: Query to get User.usernames via foreign key


code:
def __init__(self, id, list1=None):
    if list1 is None:
        self.list1 = []

rawDescription: Why default parameter doesn't work for Python object distinguish


code:
def mapindex(self):
    """Function called to update a row in the tableview and database"""
    i, ok = QtGui.QInputDialog.getInteger(self,
            "Update Row", "Row:", 1, 1, 100, 1)
    row = "%d" % i
    row = int(row) - 1
    if ok:
        self.ui.Submit.hide()
        self.ui.updateButton.show()
        self.mapper.setCurrentIndex(row)

def updaterow(self):
    """Function to update data from line edits to the database"""
    text1 = self.ui.lineEditUser.text()
    text2 = self.ui.lineEditEmail.text()
    row = self.mapper.currentIndex() #being the missing link
    self.model.setData(self.model.index(row, 0), str(text1).upper())
    self.model.setData(self.model.index(row, 1), str(text2))
    self.model.submitAll()
    self.ui.lineEditUser.clear()
    self.ui.lineEditEmail.clear()
    self.ui.Submit.show()
    self.ui.updateButton.hide()

rawDescription: pyqt Using QDataWidgetMapper to update row in database

description: Pyqt Using QDataWidgetMapper to update row in database


code:
import operator

playerinfo = [('ansonca01', 4, 1871, 1, 'RC1'),
              ('forceda01', 44, 1871, 1, 'WS3'),
              ('mathebo01', 68, 1871, 1, 'FW1')]

idmatch = [('ansonca01', 'Anson', 'Cap', '05/06/1871'),
           ('aaroh101', 'Aaron', 'Hank', '04/13/1954'),
           ('aarot101', 'Aaron', 'Tommie', '04/10/1962')]

id = operator.itemgetter(0)  # To get id field.

idinfo = {id(rec): rec[1:] for rec in idmatch}  # Dict for fast look-ups.

merged = [info + idinfo[id(info)] for info in playerinfo if id(info) in idinfo]

print(merged) # -> [('ansonca01', 4, 1871, 1, 'RC1', 'Anson', 'Cap', '05/06/1871')]

rawDescription: How to merge two tuples in a list if the first tuple elements match in python?

description: Merge two tuples in a list if the first tuple elements match in python


rawDescription: Merging 1D and 2D lists in python

description: Merging 1D and 2D lists in python


code:
from fabric.api import local
my_branch = local('git rev-parse --abbrev-ref HEAD', capture=True)

rawDescription: Using Fabric to deploy current git branch to heroku


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

data = np.random.rand(10,10)*0.6+0.4 # data ranging from 0.4 to 1

xAxisScale = np.linspace(0.0, 80, len(data[0,:]))
yAxisScale = np.linspace(0.0, 80, len(data[0,:]))

fig = plt.figure(figsize = (16, 9), dpi = 100)
ax = fig.add_subplot(111 )
image = ax.contourf(xAxisScale, yAxisScale, data,levels=np.arange(0,1.01,0.01),vmin = 0.0,vmax=1.0)
colorbar = fig.colorbar(image, ticks = [0.0, 0.5, 1.0])

plt.show()

rawDescription: pyplot depicted range of colorbar

description: Pyplot depicted range of colorbar


code:
def a():
    globals()['something'] = 'bob'

rawDescription: Declare global variables in Python

description: Declare global variables in Python


code:
def quadratic_roots(a, b, c):

  if type(a) != float and type(a) != int:
      print('All values must be a int or float. Bitch')
      return None
  if type(b) != float and type(b) != int:
      print('All values must be a int or float. Bitch')
      return None
  if type(c) != float and type(c) != int:
      print('All values must be a int or float. Bitch')
      return None

  a = float(a)
  b = float(b)
  c = float(c)
  if a == 0 and (b == 0 or c == 0):
    return []
  if a == 0:
      root = (-c) / b
      list_root = [root]
      return list_root

  discriminant = (b ** 2) -  4  * a * c
  root1 = ((-b) - ((discriminant)**.5))/(2*a)
  root2 = ((-b) + ((discriminant)**.5))/(2*a)
  if root1 > root2:
      list_roots = [root2, root1]
  elif root2 > root1:
      list_roots = [root1, root2]
  else: # roots are equal
      list_roots = [root1]
  return list_roots

rawDescription: quadratic formula function python

description: Quadratic formula function python


code:
dates = matplotlib.dates.date2num(list_of_datetimes)
plot_date(dates, values)

rawDescription: plotting time in python with matplotlib

description: Plotting time in python with matplotlib


code:
def chooseOneServer():
    dara = websvc()
    i=0
    servers = []
    for item in dara:
        for key,value in item.items() :
            if key == '1':
                servers.append(('i',value))
                i += 1
    return servers

rawDescription: Showing the last item of a list in a ChoiceField


code:
class Post(models.Model):
    title = models.CharField(max_length=500)
    text = models.TextField()
    creation_date = models.DateTimeField(auto_now_add=True)
    edited_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(User)

    def __unicode__(self):
        return "%s at %s by %s" % (self.title, self.creation_date, self.author.first_name)

class Edit(models.Model):
    creation_date = models.DateTimeField(auto_now_add=True)
    editor = models.ForeignKey(User)
    post = models.ForeignKey(Post)

    def __unicode__(self):
        return "%s edited by %s" % (self.post.title, self.editor.first_name)

rawDescription: How to allow user to edit post with Django?

description: Allow user to edit post with Django


code:
mydict = {}
for each_line in ClassName_csvfile:
     rollnum = get_roll_num()
     classname = get_class_name()
     mydict[rollnum]=classname

for each_line in Student_csv_file:
     rollnum = get_roll_num()
     mark = get_mark()
     grade = get_grade()
     Classname = ''
     if mydict.has_key(rollnum):
        Classname = mydict[rollnum]
     writetofile(rollnum, mark, grade, Classname)

rawDescription: Merging records from two '.CSV' files in python


code:
fixed_df1 = pd.read_csv('sample1.txt', sep=';', encoding='latin1')
fixed_df2 = pd.read_csv('sample2.txt', sep=';', encoding='latin1')
fixed_df = pd.concat([fixed_df1, fixed_df2])

rawDescription: iPython:Using Pandas, How do I combine multiple text files to find reacurring usernames?

description: IPython:Using Pandas, How do I combine multiple text files to find reacurring usernames


code:
import numpy as np
import scipy.optimize

A = \
np.array([[ 1,  2,  3,  4,  5],
          [ 2,  1,  3,  4,  5],
          [-1,  2,  3,  0,  0],
          [ 0,  0,  0,  0,  0],
          [ 0,  0,  0,  0,  0]])

B = \
np.array([[0],
          [2],
          [3],
          [0],
          [0]])

def objfun(x):
    H = 0.1*np.ones([5,5])
    f = np.dot(np.transpose(x),np.dot(H,x))
    return f

def constr1(x):
    """ The constraint is satisfied when return value >=0 """
    sol = A*x
    if np.allclose(sol, B):
        return 0.01
    else:
        # Return the negative distance between the expected solution
        # and the actual solution for a somehow meaningful value
        return -np.linalg.norm(B-sol)

scipy.optimize.fmin_cobyla(objfun, [0.0, 0.0, 0.0, 0.0,0.0], [constr1])
#np.linalg.solve(A, b)

rawDescription: Using Scipy minimize (scipy.optimize.minimize) with a large equality constraint matrix


code:
flag = fcntl.fcntl(MyStream.fileno(), fcntl.F_GETFL)
fcntl.fcntl(MyStream.fileno(), fcntl.F_SETFL, flag & ~os.O_NONBLOCK)

rawDescription: Make a stream read() blocking

description: Make a stream read() blocking


code:
r.table('cube7').filter(
  lambda row: r.and_(r.args(r.expr(skObj).map(
    lambda x: row['sk'].contains(
      lambda y: (y['sid'] == x['sid']) & (y['et'] >= x['et'])
    )
  )))
)

rawDescription: How to apply Greater than equal in python lambda expression in Rethinkdb

description: Apply Greater than equal in python lambda expression in Rethinkdb


code:
text_edit = QPlainTextEdit()
...
text=open('file.txt').read()
text_edit.setPlainText(text)

rawDescription: PyQT Reading a text file

description: PyQT Reading a text file


code:
from pprint import pformat

def application(environ, start_response):
    # show the environment:
    output = ['
']
    output.append(pformat(environ))
    output.append('
')

    #create a simple form:
    output.append('<form method="post">')
    output.append('<input type="text" name="test">')
    output.append('<input type="submit">')
    output.append('</form>')

    if environ['REQUEST_METHOD'] == 'POST':
        # show form data as received by POST:
        output.append('
FORM DATA
')
        output.append(pformat(environ['wsgi.input'].read()))

    # send results
    output_len = sum(len(line) for line in output)
    start_response('200 OK', [('Content-type', 'text/html'),
                              ('Content-Length', str(output_len))])
    return output

rawDescription: Python POST data using mod_wsgi

description: Python POST data using mod_wsgi


code:
from struct import Struct

unpacker = Struct("b")
unpacker.unpack("z")[0]

rawDescription: Is there a better way than int( byte_buffer.encode('hex'), 16 )


rawDescription: Including external binaries in python package


code:
import boto
s3 = boto.connect_s3('access', 'secret')
b = s3.get_bucket('destination_bucket')
mp = b.initiate_multipart_upload('tmp/large-copy-test.mp4')
mp.copy_part_from_key('source_bucket', 'path/to/source/key', 1, 0, 999999999)
mp.copy_part_from_key('source_bucket', 'path/to/source/key', 2, 1000000000, 1999999999)
mp.copy_part_from_key('source_bucket', 'path/to/source/key', 3, 2000000000, 2999999999)
mp.copy_part_from_key('source_bucket', 'path/to/source/key', 4, 3000000000, 3999999999)
mp.copy_part_from_key('source_bucket', 'path/to/source/key', 5, 4000000000, 4999999999)
mp.copy_part_from_key('source_bucket', 'path/to/source/key', 6, 5000000000, 5500345712)
mp.complete_upload()

rawDescription: How can I copy files bigger than 5 GB in Amazon S3?

description: Copy files bigger than 5 GB in Amazon S3


rawDescription: Python: Converting a dictionary to JSON and back appends "u" to each entry


code:
for poop in o_cap:
    t = t.replace(poop,'')
for poop in e_cap:
    t = alvin.replace(poop,'')

rawDescription: Python str.find() overriding Element.find(), how to circumvent?


code:
import Tkinter as tk

class App(object):
    def __init__(self, master):
        self.master = master
        self.initialize()

    def lock_func(self):
        def step():
            while True:
                print("blah")
                self.nextstep_id = self.master.after(1, nextstep)
                yield
        nextstep = step().next
        self.nextstep_id = self.master.after(1, nextstep)

    def stop(self):
        self.master.after_cancel(self.nextstep_id)
        print("stopped")

    def initialize(self):
        self.nextstep_id = 0
        self.process_button = tk.Button(self.master, text="Process",
                                        command=self.lock_func)
        self.stop_button = tk.Button(self.master, text="Stop",
                                     command=self.stop)
        self.process_button.pack()
        self.stop_button.pack(expand='yes', fill='x')

root = tk.Tk()
app = App(root)
root.mainloop()

rawDescription: Interacting with Tkinter window during a long process


code:
import matplotlib.pyplot as plt

#change these 2 variables to suit your needs
nPass = 5857
nFail = 1362

plt.rcParams.update({'font.size': 22}) #adjust font size; not really needed

plt.pie([nPass, nFail],
        colors=["green","red"],
        labels=["Pass", "Fail"],
        autopct='%1.1f%%',
        startangle=90)

plt.axis('equal') #ensure pie is round
plt.show()

rawDescription: How to create pie chart using python ?

description: Create pie chart using python


code:
startYear = 1986
endYear = 2014

empty_list = range(startYear, endYear+1)

rawDescription: Extracting each year from an item in a list in the format [yyyy,yyyy]


code:
def get_hours():
    result = dbconn.query("select * from hours where date < (select max(date) from last_export) order by date DESC")

    if result:
        return result
    else:
        return False

rawDescription: How to check if sql query result is empty in web.py/python

description: Check if sql query result is empty in web.py/python


code:
class Question(db.Model):
    class __amf__:
        static = ('answers',)

    questionText = db.StringProperty(multiline=False)

class Answer(db.Model):
    answertText = db.StringProperty(multiline=False)
    question = db.ReferenceProperty(Question, collection_name='answers')

rawDescription: GAE datastore eager loading in python api


code:
import numpy as np

y_data = [
     [[a,0],[b,1],[c,None],[d,6],[e,7]],
     [[a,5],[b,2],[c,1],[d,None],[e,1]],
     [[a,3],[b,None],[c,4],[d,9],[e,None]],
     ]

x_data = [0, 1, 2, 3, 4]

for i in range(5):
    xv = []
    yv = []
    for j, v in enumerate(row[i][1] for row in y_data):
        if v is not None:
            xv.append(j)
            yv.append(v)
    ax.plot(xv, yv, label=y_data[0][i][0])

rawDescription: Plot missing points for complicated 3D list of points - Python


code:
def get_hours():
    days_of_theweek = ["Monday", "Tuesday", "Wednesday", "Thursday",
                       "Friday", "Saturday", "Sunday"]
    hours = {}

    for the_day in days_of_theweek:
        prompt = "  Enter the shift hours for {}: ".format(the_day)
        hours[the_day] = int(raw_input(prompt))
        os.system('cls')
    return hours

rawDescription: Returning a dictionary from a loop

description: Returning a dictionary from a loop


code:
from tkinter import *

def chooseColor(event):
    global color #set color to global so it updates in other function
    color = colorchooser.askcolor()

def paint(event):
    #create a line while in this event. use color[1] to get the second element in the color tuple
    canvas.create_line(event.x,event.y,event.x+1,event.y+1, fill=color[1])

tk = Tk()

canvas = Canvas(tk, width=500, height=500)
canvas.pack()

color = tkColorChooser.askcolor() #get initial color, as a tuple

canvas.bind_all("<Button-3>", chooseColor)
canvas.bind_all("<B1-Motion>", paint)

tk.mainloop()

rawDescription: How can I Change My pen tools color?

description: Change My pen tools color


code:
import matplotlib.pylab as plt
import numpy as np
import scipy.integrate as integrate

##Parameters
kp = .5 #proportional gain
ki = .1 #integral gain
vr = 25 #desired velocity in m/s
Tm = 190 #Max Torque in Nm
wm = 420 #engine speed
B = 0.4 #Beta
an = 12 #at gear 4
p = 1.3 #air density
Cd = 0.32 #Drag coefficient
Cr = .01 #Coefficient of rolling friction
A = 2.4 #frontal area

##Variables
m = 18000.0 #weight
v0 = 20. #starting velocity
t = np.linspace(61, 500, 5000) #time
theta = np.radians(4) #Theta

def torque(v):
    return Tm * (1 - B*(an*v/wm - 1)**2)

def vderivs(status, t):
    v, int_err = status

    err = vr - v
    control = kp * err + ki * int_err

    v1 = an * control * torque(v)
    v2 = m*Cr*np.sign(v)
    v3 = 0.5*p*Cd*A*v**2
    v4 = m*np.sin(theta)
    vtot = v1-v2-v3-v4*(t>=200)
    return vtot/m, err

def velocity(desired, theta, time):
    return integrate.odeint(vderivs, [desired, 0], time)[:, 0]

t0l = [i for i in range(61)]
vf=[v0 for i in range(61)]+[v for v in velocity(v0,theta,t)]
tf=t0l+[time for time in t]

plt.plot(tf, vf, 'k-', label=('V(0) = '+str(v0)))

v0=35.
vf=[v0 for i in range(61)]+[v for v in velocity(v0,theta,t)]
plt.plot(tf, vf, 'b-', label=('V(0) = '+str(v0)))

v0=vr
vf=[v0 for i in range(61)]+[v for v in velocity(v0,theta,t)]
plt.plot(tf, vf, 'g-', label=('V(0) = Vr'))

plt.axhline(y=vr, xmin=0, xmax=1000, color='r', label='Desired Velocity')
plt.legend(loc = "upper right")
plt.axis([0,500,18,36])
plt.show()

rawDescription: Integral control system does not behave properly


code:
crumbs = list(soup.find('div',{"id":"breadcrumbs"}).find_all('a'))
for ind, crumb in enumerate(crumbs):
    if ind < len(crumbs) - 1:
        ending = {'end': ', '}
    else:
        ending = {}
    print(crumb.text, **ending)

rawDescription: combining links into one one output in beautifulsoup

description: Combining links into one one output in beautifulsoup


code:
def cycling(p, start, done):
    while not done[e]:
        done[e] = True
        e = p[e]
        yield e

def toCycle(p):
    done = [False]*len(p)
    cycles = [tuple(cycling(p, 0, done))]
    while not all(done):
        start = done.index(False)
        cycles.append(tuple(cycling(p, start, done)))
    return cycles

rawDescription: efficiently converting a bijection to cycle notation

description: Efficiently converting a bijection to cycle notation


code:
import shutil
import subprocess

proc = subprocess.Popen([...], stdin=subprocess.PIPE)

my_input = get_filelike_object('from a place not given in the question')

shutil.copyfileobj(my_input, proc.stdin)

rawDescription: Is there a simple way in Python to create a file which can be written to in one thread and read in a different one?


code:
from importlib import import_module
import_module(str("." + market), 'market')

rawDescription: Trying to import class from a module in the same package by a string


rawDescription: sed regex to Python re

description: Sed regex to Python re


code:
import numpy as np
from scipy.integrate import odeint

def integrate_cons(x, t, l):
   # unless you use np.matrix which I never do, you have to use np.dot
   xdot = -np.dot(l,x)
   return xdot;

t = np.linspace(0, 10, 101)
# just a random matrix
l = np.random.rand(3,3)
# initial conditions
x0 = np.array([1,1,1])
#laplacian is a 3x3 matrix
#initial_condition is a vector
solution = odeint(integrate_cons, x0, t, args=(l,))
print(solution)

rawDescription: Python ODEINT problems with args

description: Python ODEINT problems with args


code:
import scipy.optimize as optimize
import numpy as np

def func(x):
    return np.cos(x)**2 + 6 - x

# 0<=cos(x)**2<=1, so the root has to be between x=6 and x=7
print(optimize.bisect(func, 6, 7))
# 6.77609231632

rawDescription: Solving equation using bisection method

description: Solving equation using bisection method


code:
from operator import itemgetter
list_ = [{'x':1,'y':2},{'x':1,'y':1},{'x':3,'y':3}]
sorted(list_,key=itemgetter('x','y'))

rawDescription: How to sort the coordinate list?

description: Sort the coordinate list


code:
import wx

class MyMCD(wx.Dialog):
    def __init__(self, parent, message, caption, choices=[]):
        wx.Dialog.__init__(self, parent, -1)
        self.SetTitle(caption)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.message = wx.StaticText(self, -1, message)
        self.clb = wx.CheckListBox(self, -1, choices = choices)
        self.chbox = wx.CheckBox(self, -1, 'Select all')
        self.btns = self.CreateSeparatedButtonSizer(wx.OK | wx.CANCEL)
        self.Bind(wx.EVT_CHECKBOX, self.EvtChBox, self.chbox)

        sizer.Add(self.message, 0, wx.ALL | wx.EXPAND, 5)
        sizer.Add(self.clb, 1, wx.ALL | wx.EXPAND, 5)
        sizer.Add(self.chbox, 0, wx.ALL | wx.EXPAND, 5)
        sizer.Add(self.btns, 0, wx.ALL | wx.EXPAND, 5)
        self.SetSizer(sizer)
#        self.Fit()

    def GetSelections(self):
        return self.clb.GetChecked()

    def EvtChBox(self, event):
        state = self.chbox.IsChecked()
        for i in range(self.clb.GetCount()):
            self.clb.Check(i, state)

if __name__ == '__main__':
    l = ['AND', 'OR', 'XOR', 'NOT']
    app = wx.PySimpleApp()
    dlg = MyMCD(None, 'Choose as many as you wish', 'MCD Title', choices = l)
    if dlg.ShowModal() == wx.ID_OK:
        result = dlg.GetSelections()
        wx.MessageBox(str(result) + ' were chosen')
    dlg.Destroy()

rawDescription: Creating a custom dialog that allows me to select all files at once or a single file individually


code:
from django.shortcuts import get_object_or_404

# get Room instance by id or raise 404 page if not found
room = get_object_or_404(Room,pk = id)
# add squawk to many-to-many relation
room.squawks.add(squawk_object)

rawDescription: Inserting manytomany field into db

description: Inserting manytomany field into db


code:
def Action1(self, intToPrint=None, **kwargs):
    print("Print 1: %d - %s"%(self.someVar,intToPrint))

def Action2(self, firstNum=None, firstString=None, **kwargs):
    print("Print 2: %d - %d %s"%(self.someVar,firstNum, firstString))
...
action1Group.set_defaults(func=MyClass.Action1)
...
args.func(mc, **vars(args))

rawDescription: How should you use argparse to choose which action to perform and pass arguments to it?


rawDescription: mod-pbxproj, how to add custom framework to XCode Project file

description: Mod-pbxproj, how to add custom framework to XCode Project file


code:
#convert base 10 to any base between 2 and 16
def convBase(n, base):
    charSeq = '0123456789ABCDEF'
    if n < base:
        return charSeq[n]
    else:
        return convBase(n//base, base) + charSeq[n%base]

#print convBase(10,16)

rawDescription: Function that returns a string of digits that represent the base b representation of n in python


code:
tag_number = int(instrumentform.cleaned_data['tag'])
for query_result in Class1.objects.filter(tag = tag_number).values_list('example1', 'exmaple2'):
    example5, example6 = query_result

rawDescription: Django - Reference data from another model using a foreign key


code:
import matplotlib.pyplot as plt

fig, (ax1,ax2) = plt.subplots(1,2)

ax1.xaxis.tick_top()
ax2.xaxis.tick_top()

ax1.set_title('Title1')
ax2.set_title('Title2',y=1.05)

fig.savefig('title.png')

rawDescription: matplotlib x axis on top interference with the title

description: Matplotlib x axis on top interference with the title


code: [sum(a) for a in zip(*array)]

rawDescription: Merging/adding lists in Python

description: Merging/adding lists in Python


code:
import random
random.sample(range(100), 5)

rawDescription: Take n items at random from a list

description: Take n items at random from a list


rawDescription: How to represent a data structure like this in python pandas?

description: Represent a data structure like this in python pandas


rawDescription: why do python strings not have __iter__ function?

description: Why do python strings not have __iter__ function


code:
checkTime = time.time() - 60*30

# use any() as a fast way to run a loop
# The .__delitem__() method always returns `None`, so this runs the whole loop
lst = [k for k in self.keys() if self[k].lastAccess > checkTime]
any(self.__delitem__(k) for k in lst)

rawDescription: is this the right way to delete object inside dict

description: Is this the right way to delete object inside dict


rawDescription: Checking number of elements in Python's `Counter`


code:
import inspect
h = lambda x : int(x,base=2)
inspect.getargspec(h)

rawDescription: functools.partial vs normal Python function

description: Functools.partial vs normal Python function


code:
s = os.statvfs('/')
(s.f_bavail * s.f_frsize) / 1024
os.system('df -k /')

rawDescription: Find free disk space in python on OS/X

description: Find free disk space in python on OS/X


code:
import lxml.etree as ET

content = '''\
<root xmlns="SVGNS">
<glyph unicode="©" horiz-adv-x="1792" d="M834 ... -40t-121 -18z " />
<glyph unicode="C" horiz-adv-x="1509" d="M1766 338q-49 ... 83.5v-215z" />
</root>'''
font = ET.fromstring(content)
font
font.xpath('//n:glyph', namespaces={'n':'SVGNS'})[0].attrib

rawDescription: Python lxml, unicode matching in SVG attribute


rawDescription: Regular expression: match start or whitespace


code:
months = cdiff.DATE.map(lambda x: x.month)
pivot_table(cdiff, values='COUNT', rows=[months, 'LOCATION'],
            aggfunc=np.sum)

rawDescription: Pandas pivot_table on date

description: Pandas pivot_table on date


code:
import math
def f_of_x(op):
    return eval("lambda x:" + op, math.__dict__)

rawDescription: Using Lambdas to build executable functions from string expressions


code:
from collections import Counter

inp = input("Enter letters") # input() if using python 3

l = len(inp.strip()) # get length of input string ,inp.strip() removes any whitespace, just use len(inp) if you want to include

c = Counter(inp)

for char in c:
    c[char] = c[char] * 100 / l  # don't need to cast as float for python 3
print (c)
Counter({'C': 30.0, 'G': 30.0, 'A': 20.0, 'T': 20.0})

rawDescription: Python Storing & Printing Data from a text file


rawDescription: Interpolate values row-wise for 2D Numpy array


code:
app1 = Flask(__name__)
app1.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/database1.db'
db1 = SQLAlchemy(app1)

class Lcn(db1.Model):
    __tablename__ = 'lcn'

app2 = Flask(__name__)
app2.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/database2.db'
db2 = SQLAlchemy(app2)

class LcnRemote(db2.Model):
    __tablename__ = 'lcn'

rawDescription: Using same name of tables with different binds in Flask


code: qualifies = all(course in courses_taken for course in courses_required)

rawDescription: How should I loop through a Python 2.6 dict and efficiently check another dict to see if the same key exists?


code:
import Tkinter as tk
import sys, random

class Shuffle(object):
    def __init__(self,master=None):
        self.master=master
        self.text=tk.Label(master, text="Type in something:")
        self.box=tk.Entry(master)
        self.buttn = tk.Button(master, text="Done", width=10, command=self.calc)
        self.globvar = tk.StringVar()
        self.globvar.set(0)
        self.result = tk.Label(self.master, textvariable=self.globvar)
    def hide(self):
        self.text.pack_forget()
        self.box.pack_forget()
        self.buttn.pack_forget()
        self.result.pack_forget()
    def show(self):
        self.text.pack(padx=2, pady=2)
        self.box.focus_set()
        self.box.pack(side=tk.TOP, padx=3, pady=3)
        self.buttn.pack(side=tk.TOP, padx=3, pady=3)
        self.result.pack(side=tk.TOP, padx=3, pady=3)
    def calc(self):
        word = self.box.get()
        while len(word) != 0:
            i = random.randrange(0, len(word))
            self.globvar.set(word[i])
            word = word[0:i] + word[i+1:]

class MainApp(object):
    def __init__(self,master=None):
        self.master=master
        app=self.app=tk.Tk()
        app.title("Mkee's Tools")
        app.geometry('500x500')
        menubar=tk.Menu(app)
        self.shuffle=Shuffle(master)
        self.current=self.shuffle
        program_menu=tk.Menu(menubar)
        program_menu.add_command(label='Shuffle',command=self.show_shuffle)
        menubar.add_cascade(label='Programs', menu=program_menu)
        app.config(menu=menubar)
    def show_shuffle(self):
        self.current.hide()
        self.current=self.shuffle
        self.shuffle.show()
    def show_buttons(self):
        self.current.hide()
        self.current=self.buttons
        self.buttons.show()

def main():
    m=MainApp()
    m.app.mainloop()

if __name__=='__main__':
    main()

rawDescription: Python 2.7.2 global variables + tkinter

description: Python 2.7.2 global variables + tkinter


code:
dict1 = {'bookA': 1, 'bookB': 2, 'bookC': 3}
dict2 = {'bookC': 2, 'bookD': 4, 'bookE': 5}
dict2.update(dict1)
print(dict2)

rawDescription: Why am I getting "None" after merging two dictionaries


code:
from spidermonkey import Runtime
rt = Runtime()
cx = rt.new_context()
result = cx.eval_script(whatyoupostedabove)

rawDescription: How to evaluate javascript code in Python

description: Evaluate javascript code in Python


code:
def classify(rgb_tuple):
    # eg. rgb_tuple = (2,44,300)

    # add as many colors as appropriate here, but for
    # the stated use case you just want to see if your
    # pixel is 'more red' or 'more green'
    colors = {"red": (255, 0, 0),
              "green" : (0,255,0),
              }

    manhattan = lambda x,y : abs(x[0] - y[0]) + abs(x[1] - y[1]) + abs(x[2] - y[2])
    distances = {k: manhattan(v, rgb_tuple) for k, v in colors.items()}
    color = min(distances, key=distances.get)
    return color

rawDescription: Classifying RGB values in python

description: Classifying RGB values in python


code:
from lxml import etree
raw = '''<root><foo/></root>'''
root = etree.fromstring(raw)
root.text = 'bar'
etree.tostring(root)

rawDescription: How to create a Text Node with lxml?

description: Create a Text Node with lxml


code:
class Main(mainFrame):
    def __init__(self):
        mainFrame.__init__(self, None) # using super().__init__(self, None) fails
    def about_click( self, event ):
        print("AboutDialog")

def main():
    app = wx.PySimpleApp(0)
    frame = Main()
    app.SetTopWindow(frame)
    frame.Show()
    app.MainLoop()

if __name__ == '__main__':
    main()

rawDescription: UI class inheritance, super() not working correctly


code: list_of_dicts = [{key: value for (key, value) in zip(header, line.strip().split('; '))} for line in open('abcd.txt') if not line.strip().startswith('#')]

rawDescription: Loading .txt file as a dict, but exclude commented rows


code:
from django.views.generic import CreateView

class UploadFileView(CreateView):
    form_class = FileUploadForm
    template_name = 'project/file_upload.html'
    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(UploadFileView, self).form_valid(form)

rawDescription: Working with Django's FormView

description: Working with Django's FormView


code: clean_pps = {k: sum(filter(None, v.values())) for k, v in list_of_pps.items()}

rawDescription: Python dictionary: sum up numerical and remove 'None' values from nested dictionary and assign results to keys of first level


code:
import urllib2
# create a password manager
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()

# Add the username and password.
# If we knew the realm, we could use it instead of None.
top_level_url = "http://example.com/foo/"
password_mgr.add_password(None, top_level_url, username, password)

handler = urllib2.HTTPBasicAuthHandler(password_mgr)

# create "opener" (OpenerDirector instance)
opener = urllib2.build_opener(handler)

# use the opener to fetch a URL
opener.open(a_url)

# Install the opener.
# Now all calls to urllib2.urlopen use our opener.
urllib2.install_opener(opener)

rawDescription: Python And 401 reponse

description: Python And 401 reponse


code:
import math

def getDistance(lat1,lon1,lat2,lon2):
    # This uses the haversine formula, which remains a good numberical computation,
    # even at small distances, unlike the Shperical Law of Cosines.
    # This method has ~0.3% error built in.
    R = 6371 # Radius of Earth in km

    dLat = math.radians(float(lat2) - float(lat1))
    dLon = math.radians(float(lon2) - float(lon1))
    lat1 = math.radians(float(lat1))
    lat2 = math.radians(float(lat2))

    a = math.sin(dLat/2) * math.sin(dLat/2) + \
        math.cos(lat1) * math.cos(lat2) * math.sin(dLon/2) * math.sin(dLon/2)

    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))

    d = R * c * 0.621371 # Converting km to miles with "* 0.621371"

    return d

rawDescription: Calculating distance travelled from gps track points using python


code:
import numpy as np

class PandasModel(QtCore.QAbstractTableModel):
    """
    Class to populate a table view with a pandas dataframe
    """
    def __init__(self, data, parent=None):
        QtCore.QAbstractTableModel.__init__(self, parent)
        self._data = np.array(data.values)
        self._cols = data.columns
        self.r, self.c = np.shape(self._data)

    def rowCount(self, parent=None):
        return self.r

    def columnCount(self, parent=None):
        return self.c

    def data(self, index, role=QtCore.Qt.DisplayRole):
        if index.isValid():
            if role == QtCore.Qt.DisplayRole:
                return self._data[index.row(),index.column()]
        return None

    def headerData(self, p_int, orientation, role):
        if role == QtCore.Qt.DisplayRole:
            if orientation == QtCore.Qt.Horizontal:
                return self._cols[p_int]
            elif orientation == QtCore.Qt.Vertical:
                return p_int
        return None

rawDescription: PyQt QTableView prohibitibily slow when scrolling with large data sets


code:
from django.shortcuts import render

def home(request):
    htmlf = urllib.urlopen("https://docs.djangoproject.com/en/dev/topics/http/urls")
    htmlt = htmlf.read()
    regex = '<title>(.+?)</title> '
    patt = re.compile(regex)
    price = re.findall(patt,htmlt)
    return render(request, "home.html", {'hello': price} )

rawDescription: Send data to a HTML page using block content


code:
a
b
a[b]

rawDescription: Numpy: get values from array where indices are in another array


code:
import datetime
timestamp = datetime.datetime(2013, 6, 4, 6, 18, 1).time()

rawDescription: How to define start and end times in python

description: Define start and end times in python


code:
import numpy as np

no_rows = 5
no_columns = 4

a = np.zeros((no_rows, no_columns), dtype = np.float)

with open('myfile') as f:
    for i, line in enumerate(f):
        a[i,:] = cool_function_that_returns_formatted_data(line)

rawDescription: Efficient way to process CSV file into a numpy array


rawDescription: Regular expression to match number(s) and arithmetic operators


rawDescription: Execute a function from a function object


code:
def append_unfailed(res):
    unfailed = set(store_front_list)
    for r in res:
        store_front_id, failcnt = s.split('\t')
        unfailed.discard(store_front_id)
    for store_front_id in unfailed:
        res.append('%s\t0' % store_front_id)

rawDescription: defining a value for a list in python

description: Defining a value for a list in python


code:
#relese reference to l b and s
del l
del b
del s
#now the WaveBuffer and Source should be destroyed, so we could:
pyopenal.quit()

rawDescription: What is the correct way to clean up when using PyOpenAL?


code:
list.selection_set( items[ 0 ] )
list.focus_set()
list.focus( items[ 0 ] ) # this fixes a problem.

rawDescription: How to set focus for Tkinter widget?

description: Set focus for Tkinter widget


code:
fout=open("out.csv","a")
for k in [0.9, 0.8, 0.75, 0.6, 0.5, 0.4, 0.2, 0.1]:# n
    for j in [0.,5.,10.,30.,70.,80.,100.]: # R
        f = open(printname("minTm",0.0,"n",k,"R",j), 'r+')
        lines = f.readlines()
        for i in range(0, len(lines)):
            line = lines[i]
            fout.write(line)
fout.close()

rawDescription: merging csv files with python goes wrong

description: Merging csv files with python goes wrong


code:
from selenium.webdriver.firefox import webdriver

WIKI_PAGE = 'How_I_Met_Your_Mother'

driver = webdriver.WebDriver()
driver.get('https://en.wikipedia.org/wiki')

script = 'history.pushState({}, "", "%s")' % WIKI_PAGE
driver.execute_script(script)

driver.get('https://en.wikipedia.org/wiki')

rawDescription: Save and load browser history for selenium


code:
import sys
sys.path.append('path_to_package/')

from module import some_function

rawDescription: Import module ignoring __init__.py

description: Import module ignoring __init__.py


code: line = line.replace(line, "<test> " + line.rstrip('\n') + "</test>\n")

rawDescription: Editing text in a document

description: Editing text in a document


rawDescription: Finding the last values before a specific value in numpy/pandas


code:
import mmap

SEARCH_TEXT = b'* SMTP *'
SKIP_LINES = 2
KEEP_LINES = 2

with open('log.txt', 'rb') as f:
    log = mmap.mmap(f.fileno(), 0, prot=mmap.PROT_READ)
    n = log.rfind(SEARCH_TEXT)
    if n == -1:
        print('{!r} not found'.format(SEARCH_TEXT))
    else:
        log.seek(n)
        for i in range(SKIP_LINES):
            _ = log.readline()

        print(''.join(log.readline().decode() for _ in range(KEEP_LINES)))

rawDescription: Python: iterate through lines after reverse reading a text file


code:
import nltk
j = 'you can get it cheaper than $20.99. shop at amazon.com. hurry before prices go up.'
nltk.sent_tokenize(j)

rawDescription: How do I split string on delimiters but exclude other strings

description: Split string on delimiters but exclude other strings


code:
options = ChromeOptions()
options.add_argument("--start-maximized")
driver = ChromeDriver(options)

rawDescription: How to Maximize window in chrome using webDriver (python)


code:
with open('file.out', 'w') as output:
    for n in xrange(100000000):
        s = "{0:08d}".format(n)
        output.write(s[:2] + '-' + s[2:] + '\n')

rawDescription: Print all possible combinations, given a specific number format


code:
def censor(text, word):
    text = text.split(" ")
    asterisks=[]
    text_with_asterisks=[]

    for item in text:
        if item not in word:
            text_with_asterisks.append(item)
        else:
            asterisks=[]
            for letter in word:
                asterisks.append("*")

            text_with_asterisks.append(''.join(asterisks)) #here's the culprit
    return (" ".join(text_with_asterisks))

rawDescription: Python,join() function, adding space between words


code:
source = """
class test:
    class inner_class:
        pass
    pass

class test2:
    pass
"""

import ast
p = ast.parse(source)
classes = [node.name for node in ast.walk(p) if isinstance(node, ast.ClassDef)]
# ['test', 'test2', 'inner_class']

rawDescription: How to find the list of all the class name in a file in python?

description: Find the list of all the class name in a file in python


code:
# Python 2/3 compatibility snippet:
try:
    from collections import MutableSequence
except ImportError:
    from collections.abc import MutableSequence

class WList(MutableSequence):
    def __init__(self, *args, **kw):
        self.data = list(*args, **kw)

    def __getitem__(self, index):
        return self.data[index]

    def __setitem__(self, index, value):
        if len(value) != 2:
            raise TypeError ("You have to pass a value and a weight")
        self.data[index] = value

    def __delitem__(self, index):
        del self.data[index]

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

    def insert(self, index, value):
        if len(value) !=2:
            raise TypeError ("You have to pass a value and a weight")
        self.data.insert(index, value)

    def set_weight(self, index, weight):
        self.data[index] = (self.data[index][0], weight)

    def __repr__(self):
        return "Wlist(%r)" % self.data

rawDescription: Python, extend a list object to include weights for each element


rawDescription: Python struct appears inaccurate

description: Python struct appears inaccurate


code:
import arff, numpy as np
dataset = arff.load(open('mydataset.arff', 'rb'))
data = np.array(dataset['data'])

rawDescription: .arff files with scikit-learn?

description: .arff files with scikit-learn


code:
class Foo:
    def __init__(self):
        return 42

foo = Foo()

rawDescription: How to return a value from __init__ in Python?

description: Return a value from __init__ in Python


code:
with open('test.txt') as f:
    lines = f.readlines()
f.close()

f= open('test.txt', 'w')#open file for write
for line in lines:
    if line.split('\t')[0] == "querykey":
        line = line + ',newkey'

    f.write('\n'.join(lines))
f.close()

rawDescription: Writing to the end of specific line in python


code:
import numpy as np
mask = np.array([False, False, False, True, True, False, False])
data = np.array([1, 2, 3, 4, 5, 6, 7])
data[mask]

rawDescription: Array as index in Python

description: Array as index in Python


code:
whens = [When(some_value__in=l, then=Value('list #{}'.format(i)))\
            for i, l in enumerate(my_list)]

MyModel.objects.filter(...).annotate(label=Case(*whens, output_field=CharField()))

rawDescription: Django ORM - Dynamically add When to Case


code:
from OpenGL.GL.ARB.draw_elements_base_vertex import *
glDrawElementsBaseVertex

rawDescription: Calling OpenGL Extensions from Python

description: Calling OpenGL Extensions from Python


code:
from urllib2 import urlopen
from urlparse import urlparse
req = urlopen('http://capitalfm.com/?foo=bar')
req.geturl()
url = urlparse(req.geturl())
url.query

rawDescription: How to get the (current url + query string) using python code with urllib2?

description: Get the (current url + query string) using python code with urllib2


code: re.sub(r'@(\w+)', lambda m: d[m.group(1)], s)

rawDescription: Use '\g<index> or r'\index' as dict key when use re.sub?


code:
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib2.urlopen(req)

rawDescription: setting referral url in python urllib.urlretrieve

description: Setting referral url in python urllib.urlretrieve


code:
tri = np.zeros((67, 67))
tri[np.triu_indices(67, 1)] = dm

rawDescription: Numpy: convert an array to a triangular matrix


code: ax.set_xticklabels(['true true true...', 'true true false...', ...], rotation=45)

rawDescription: python pyplot x axis comments

description: Python pyplot x axis comments


code:
import shelve
import gdbm

def gdbm_shelve(filename, flag="c"):
    return shelve.Shelf(gdbm.open(filename, flag))

db = gdbm_shelve("dbfile")

rawDescription: Shelve: choice of database

description: Shelve: choice of database


code:
image = self.request.POST["qqfile"]
imgObj = cStringIO.StringIO(image.file.read())

# Connect to S3...
# create s3 Key
key = bucket.new_key("%s" % uuid.uuid4());

# guess mimetype for headers
file_mime_type = mimetypes.guess_type(image.filename)
if file_mime_type[0]:
   file_headers = {"Content-Type": "%s" % file_mime_type[0]}
else:
   file_headers = None

key.set_contents_from_string(imgObj.getvalue(), headers=file_headers)

key_str = key.key

#return JSON response with key and append to s3 url on front end.

rawDescription: Webapp2 request application/octet-stream file upload


code:
import re
str='<a  href="test/?n=451484"   >'
re.findall(r'test/\?n=(\d+)', str)

rawDescription: How to search for question mark and / with regular expression ? python

description: Search for question mark and / with regular expression ? python


code:
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class RankItem(models.Model):
    rank = models.IntegerField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    def __unicode__(self):
        return self.rank

rawDescription: django model help involving m2m and foreignkey

description: Django model help involving m2m and foreignkey


code:
import urllib.request, urllib.error

data ="""
<?xml version="1.0" ?>
<AccessRequest xml:lang="en-US">
    <AccessLicenseNumber>XXXXX</AccessLicenseNumber>
    <UserId>XXXX</UserId>
    <Password>XXXXX</Password>
</AccessRequest>
<?xml version="1.0" ?>
<RatingServiceSelectionRequest xml:lang="en-US">
    <Request>
        <TransactionReference>
            <CustomerContext>Bare Bones Rate Request</CustomerContext>
            <XpciVersion>1.0</XpciVersion>
        </TransactionReference>
        <RequestAction>Rate</RequestAction>
        <RequestOption>Rate</RequestOption>
    </Request>
    <PickupType>
        01
    </PickupType>
    <Shipment>
        <Shipper>
            <Address>
                <PostalCode>44111</PostalCode>
        <StateProvinceCode>OH</StateProvinceCode>
                <CountryCode>US</CountryCode>
            </Address>
        </Shipper>
        <ShipTo>
            <Address>
                <PostalCode>74403</PostalCode>
        <StateProvinceCode>OK</StateProvinceCode>
                <CountryCode>US</CountryCode>
            <ResidentialAddressIndicator/>
            </Address>
        </ShipTo>
        <ShipFrom>
            <Address>
                <PostalCode>44023</PostalCode>
        <StateProvinceCode>OH</StateProvinceCode>
                <City>Chagrin Falls</City>
                <CountryCode>US</CountryCode>
            </Address>
        </ShipFrom>
        <Service>
            03
        </Service>
        <Package>
            <PackagingType>
                02
            </PackagingType>
            <Dimensions>
                <UnitOfMeasurement>
                IN
                </UnitOfMeasurement>
                <Length>8.0</Length>
                <Width>8.0</Width>
                <Height>8.0</Height>
            </Dimensions>
            <PackageWeight>
                <UnitOfMeasurement>
                LBS
                </UnitOfMeasurement>
                <Weight>12.0</Weight>
            </PackageWeight>
        </Package>
    </Shipment>
</RatingServiceSelectionRequest>
"""

try:
    httpresq = urllib.request.Request(url="https://wwwcie.ups.com/ups.app/xml/Rate", data=data.encode('utf_8'), headers={'Content-Type': 'application/x-www-form-urlencoded'})
    response = urllib.request.urlopen(httpresq)
    return_values = response.read()
    print(return_values)
except urllib.error.URLError as e:
    error = "urllib.error.URLError exception was raised: %s" % e
    print(error)

rawDescription: Does anyone have an example on how to use the ups xml api for rating package shipments?


code:
class WrapODE(object):
    def __init__(self):
        self.y_0 = 0.
        self.L_x = []
        self.timestep = 0
        self.times = np.arange(0., 1., 0.1)

    def run(self):
        self.L_y = odeint(
            self.dy,
            self.y_0, self.times,
            args=(self,))

    @staticmethod
    def dy(y, t, self):
        """"
        Discretized application of dudt

        Watch out! Because this is a staticmethod, as required by odeint, self
        is the third argument
        """
        x = np.random.rand(3,1)
        if t >= self.times[self.timestep]:
            self.timestep += 1
            self.L_x.append(x)
        else:
            self.L_x[-1] = x
        return y + x.sum()

rawDescription: NumPy odeint output extra variables

description: NumPy odeint output extra variables


rawDescription: Python: Creation of array with fill values according to column/row