code:
class Finalizable:
    def __del__(self): pass
a = Finalizable()
b = Finalizable()
a.x = b
b.x = a
del a
del b
import gc
gc.collect()
gc.garbage

rawDescription: how to create uncollectable garbage in python?

description: Create uncollectable garbage in python


code:
new_date = dt.datetime.strptime(row[0], "%Y.%m.%d")
new_time = dt.datetime.strptime(row[1], "%H:%M").time()

dt.datetime.combine(new_date, new_time)

rawDescription: Addition of two dates on python 3

description: Addition of two dates on python 3


code:
def get_context_data(self, **kwargs):
    # Call the base implementation first to get a context
    context = super(PublisherDetail, self).get_context_data(**kwargs)
    # Add in a QuerySet of all the books
    context['book_list'] = Book.objects.all()
    form = myForm(request.POST or None)
    return context

rawDescription: How to get the value of a HTML form text field into a Django view?

description: Get the value of a HTML form text field into a Django view


rawDescription: Django URL not resolving

description: Django URL not resolving


code:
while True:
    i = temp.rindex('.')
    if not i:
        break
    ...

rawDescription: An idiomatic Python version of Ruby code with a while loop that tests a statement?


code:
class BlankLinesHelpFormatter (argparse.HelpFormatter):
    def _split_lines(self, text, width):
        return super()._split_lines(text, width) + ['']

rawDescription: Python argparse: Insert blank line between help entries


code:
# Generator; fetch specific rows from log file
def parse_log(filename):
    reg = re.prepare( '...')

    with open(filename,'r') as f:
       for row in f:
           match = reg.match(row)
           if match:
               yield match.group(1)

for i in parse_log('web.log'):
    pass # Do whatever you need with matched row

rawDescription: Examining large log files in python

description: Examining large log files in python


code:
mydict = {}
temp = "Probabilità"
mydict["key"] = temp
json_data = json.dumps(mydict, encoding="utf-8", ensure_ascii=False)

rawDescription: Encoding a JSON file

description: Encoding a JSON file


code:
from collections import Counter

anagram_class_counts = Counter()

for substring in get_all_substrings(x):
    anagram_class_counts[frozenset(Counter(substring).viewitems())] += 1

anagram_pair_count = sum(x*(x-1)/2 for x in anagram_class_counts.viewvalues())

rawDescription: Can this python code be more efficient?

description: Can this python code be more efficient


code:
import os
with open('/home/david/Desktop/datafile.txt', 'w') as F:
    for d in os.walk('/'):
        F.write(str(d) + '\n')

rawDescription: Iterating over os.walk in linux

description: Iterating over os.walk in linux


code:
data = [1,2,3,5,11,12,13,15,22,25,27,30]

# divide it into blocks like [[a .. a+10], [b .. b+10], ...]
result = []
block  = None
for d in data:
    if block:
        if d <= hi:
            # belongs to current block
            block.append(d)
        else:
            # start a new block
            result.append(block)  # finish previous block
            block = [d]           # start new block
            lo, hi = d, d + 10    # reset endpoints for new block
    else:
        # special handling for first value encountered
        block = [d]
        lo, hi = d, d + 10
# cleanup
if block:
    result.append(block)

# result = [[1, 2, 3, 5, 11], [12, 13, 15, 22], [25, 27, 30]]

# find midpoint for each block
mid_points = [(block[0] + block[-1]) // 2 for block in result]

# mid_points = [6, 17, 27]

rawDescription: how to calculate the average of an array by range 10?

description: Calculate the average of an array by range 10


code:
import locale
locale.setlocale(locale.LC_NUMERIC, 'en_US')
locale.format("%d", 1234567, grouping=True)

rawDescription: Thousands Separator in Python

description: Thousands Separator in Python


rawDescription: Comparing equality between sum and constant


code:
self.txtLog.tag_config("success", foreground="blue", font="Arial 10 italic")
log = open(logFile, 'r')
while 1:
    line = log.readline()
    if len(line) == 0:
        break
    else:
        tags = ("success",) if line.startswith("SUCCESS") else None
        self.txtLog.insert(Tkinter.END, line+os.linesep, tags)
log.close()

rawDescription: Tkinter dynamically changing text colour of recurring strings in a textbox


code:
def join(a, *p):
    """Join two or more pathname components, inserting '/' as needed.
    If any component is an absolute path, all previous path components
    will be discarded."""
    path = a
    for b in p:
        if b.startswith('/'):
            path = b
        elif path == '' or path.endswith('/'):
            path +=  b
        else:
            path += '/' + b
    return path

rawDescription: Is it always ok to os.path.join fake paths that don't exist?


code: userSubset = set([user for user in users for record in user.records if dt < record.datetime < dt + timedelta(days=7)])

rawDescription: Date filter in list-comphresion with class variable


code:
with open("image.bin", "rb") as b_f:
    OverScan = 0
    sizeY = 480
    reg = OverScan + 10
    binary_data = b_f.read(2*192*(1+sizeY)*reg)

rawDescription: How to open a binary file as raw string in python?

description: Open a binary file as raw string in python


code:
my_list = ['abc','def','ghi','jkl','def']
'def' in my_list[:-1]
my_list2 = ['abc','ghi','jkl','def']
'def' in my_list2[:-1]

rawDescription: Boolean. Is string in list and not last position ? Python


code:
import datetime as DT
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

start = [DT.datetime(2000,1,1)+DT.timedelta(days=i) for i in (2,0,3)]
end = [s+DT.timedelta(days=i) for s,i in zip(start, [15,7,10])]
start = mdates.date2num(start)
end = mdates.date2num(end)
yval = [1,2,3]
width = end-start

fig, ax = plt.subplots()
ax.barh(bottom=yval, width=width, left=start, height=0.3)
xfmt = mdates.DateFormatter('%Y-%m-%d')
ax.xaxis.set_major_formatter(xfmt)
# autorotate the dates
fig.autofmt_xdate()
plt.show()

rawDescription: Floating Bar Chart

description: Floating Bar Chart


code:
from django.shortcuts import redirect

urlpatterns = patterns('',
    url(r'^$', views.main, name='main'),
    url(r'^login/$', views.login, name='login'),
    url(r'^app/$',views.app, name='app'),
    url(r'^.*$', redirect('/')), # <------------
)

rawDescription: How to redirect to main page is no pattern is satisfied in django?

description: Redirect to main page is no pattern is satisfied in django


code:
clib = ctypes.cdll.LoadLibrary('some.so')
c_foo = clib.c_foo
c_foo.restype = ctypes.py_object

rawDescription: Python reference count and ctypes

description: Python reference count and ctypes


rawDescription: Python ggplot is not plotting dataframe

description: Python ggplot is not plotting dataframe


code:
from PIL import Image
from numpy import eye
arr = (eye(200)*255).astype('uint8') # sample array
im = Image.fromarray(arr) # monochromatic image
imrgb = Image.merge('RGB', (im,im,im)) # color image
imrgb.show()

rawDescription: PIL: using fromarray() with binary data and writing coloured text


code:
#python 3
#from tkinter import *
#from tkinter import ttk

#python 2
from Tkinter import *
import ttk

import time
import subprocess
import paramiko

import threading

# keep track of widgets for event handlers
widget_track = {}

# event handler creates connect thread
def connect_evt():
    t = threading.Thread(target=connect)
    t.daemon = True
    t.start()
    widget_track['connect'].config(text="Connected", state="disabled", command=None)

def connect():
  time.sleep(5)   # todo: temporary for test
  return
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect('192.168.1.2', username='pi', password='raspberry')
  stdin, stdout, stderr = ssh.exec_command('cd')
  stdin, stdout, stderr = ssh.exec_command('roscore &')
  time.sleep(20)
  stdin, stdout, stderr = ssh.exec_command('\n')
  stdin, stdout, stderr = ssh.exec_command('cd scripts')
  stdin, stdout, stderr = ssh.exec_command('python /home/pi/scripts/listener2.py')
  return

# event handler creates run thread
def run_evt():
    t = threading.Thread(target=run)
    t.daemon = True
    t.start()
    widget_track['run'].config(text="Running", state="disabled", command=None)

def run():
  time.sleep(5)     # todo: temporary for test
  return
  stdin, stdout, stderr = ssh.exec_command('python ES96_Vivaldi/talker2.py')

root = Tk()

mainframe = ttk.Frame(root, padding="3 3 12 12")
mainframe.grid(column=0, row=0, sticky=(N, W, E, S))
mainframe.columnconfigure(0, weight=1)
mainframe.rowconfigure(0, weight=1)

# connect button starts connect background thread
btn = ttk.Button(mainframe, text="Connect", command=connect_evt)
btn.grid(column=1, row=3, sticky=S)
widget_track['connect'] = btn

# run button start run background thread
btn = ttk.Button(mainframe, text="Run", command=run_evt)
btn.grid(column=3, row=3, sticky=S)
widget_track['run'] = btn

ttk.Label(mainframe, text="Click 'Connect' to establish link.").grid(column=1, row=1, sticky=W)
ttk.Label(mainframe, text="Click 'Run' to control using the arrow keys").grid(column=1, row=2, sticky=W)

for child in mainframe.winfo_children(): child.grid_configure(padx=5, pady=5)

root.mainloop()

rawDescription: How to run two non-terminating scripts in parallel in a GUI?

description: Run two non-terminating scripts in parallel in a GUI


code:
for dataset in alias:
    current = dataset[0]
    print(current.text)

rawDescription: Parsing XML in Python with Loop

description: Parsing XML in Python with Loop


code:
import numpy as np
a = np.random.random(10)  # set up a random array to play with
a
b = np.array([0,5,6,9])  # indices we *don't want*
mask = np.ones(a.shape,dtype=bool)
mask[b] = False          # Converted to a mask array of indices we *do want*
mask
np.arange(a.shape[0])[mask]  #This gets you the indices that aren't in your original
a[mask]  #This gets you the elements not in your original.

rawDescription: Return elements not referenced by array of indices in Python


code:
def myMain(key):
    def ExecP1():
        pass
    def ExecP2():
        pass
    def ExecP3():
        pass
    def ExecPn():
        pass
    locals()['Exec' + key]()

rawDescription: Python: Using a dictionary to select function to execute


rawDescription: Using boolean masks in Pandas

description: Using boolean masks in Pandas


code:
class App(Tkinter.Tk):
    def __init__(self):
        Tkinter.Tk.__init__(self)
        self.entry = Tkinter.Entry()
        self.listbox = Tkinter.Listbox()
        self.entry.pack(side="top", fill="x")
        self.listbox.pack(side="top", fill="both", expand=True)
        for i in range(100):
            self.listbox.insert("end", "item %s" % i)

        self.entry.bind("<Down>", self.OnEntryDown)
        self.entry.bind("<Up>", self.OnEntryDown)

    def OnEntryDown(self, event):
        self.listbox.yview_scroll(1,"units")

    def OnEntryUP(self, event):
        self.listbox.yview_scroll(-1,"units")

rawDescription: How to scroll an inactive Tkinter ListBox?

description: Scroll an inactive Tkinter ListBox


code:
import cv2
import numpy as np

im = cv2.imread('../media/basketball.jpg')

# convert to HSV space
im_hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
# take only the orange, highly saturated, and bright parts
im_hsv = cv2.inRange(im_hsv, (7,180,180), (11,255,255))

# To show the detected orange parts:
im_orange = im.copy()
im_orange[im_hsv==0] = 0
# cv2.imshow('im_orange',im_orange)

# Perform opening to remove smaller elements
element = np.ones((5,5)).astype(np.uint8)
im_hsv = cv2.erode(im_hsv, element)
im_hsv = cv2.dilate(im_hsv, element)

points = np.dstack(np.where(im_hsv>0)).astype(np.float32)
# fit a bounding circle to the orange points
center, radius = cv2.minEnclosingCircle(points)
# draw this circle
cv2.circle(im, (int(center[1]), int(center[0])), int(radius), (255,0,0), thickness=3)

out = np.vstack([im_orange,im])
cv2.imwrite('out.png',out)

rawDescription: How can i pythonically us opencv to find a a basketball in an image?

description: Pythonically us opencv to find a a basketball in an image


code:
my_doc = col.find_one({'_id': my_str})
if my_doc is not None:
    # Document exist, modify it
    my_doc['hours'].append({"14": "yet another thing"})
    col.update({'_id': my_str}, my_doc)
else:
    # Insert the new document with all the new attributes
    col.insert({'_id': my_str, 'hours': [{"14": "yet another thing"}]})

rawDescription: MongoDB - add doc to list of docs (if unique)


code:
import operator,functools
a = map(functools.partial(map, functools.partial(operator.or_, b)), a)

rawDescription: Python: using map() without lambdas on a multidimensional array/list


code:
from Tkinter import *
main = Tk() #New Tk window
variable = 0

def function():
    global variable
    variable = 1
    newThing()

def newThing():
   global variable
   if variable==1:
       Checkbutton(main, text="test").pack()
   variable = 0

Button(main, text="Change", command=function).pack()
main.mainloop()

rawDescription: Python 2.7 Tkinter redraw widget inside if


code:
from win32com.client import DispatchEx
xl = DispatchEx("Excel.Application")
xl.Visible = 1
xl.Workbooks.Open("somefile.xls")
xl.Save("somefile.xls")

rawDescription: Opening Excel in wxpython

description: Opening Excel in wxpython


code:
from IPython.display import display, Javascript

def markdown_below():
    display(Javascript("""
    IPython.notebook.insert_cell_below('markdown')
    """));

markdown_below()

rawDescription: How to make new cells in ipython notebook markdown by default?

description: Make new cells in ipython notebook markdown by default


code:
from ilogue.fexpect import expect, expecting, run

prompts = []
prompts += expect('What is your name?','John')
prompts += expect('Are you at stackoverflow?','Yes')

with expecting(prompts):
    run('my_command')

rawDescription: How to answer to prompts automatically with python fabric?

description: Answer to prompts automatically with python fabric


code:
def frob(n=None):
    if n is None:
            n = int(raw_input("Please enter a value:"))
    return n**2 + n
frob(23)
frob()

rawDescription: Check if required variable has been passed


code:
import multiprocessing
queue = multiprocessing.Queue()
queue._reader.fileno()
queue._writer.fileno()

rawDescription: Python Multiprocessing Queue file discriptor


code:
urlpatterns = [
    url(r'^(?P<content_type_name>comics|articles|videos)$', views.content_type, name='content_type'),
]

rawDescription: How to set up a Django URL regex that accepts only 3 specific words?

description: Set up a Django URL regex that accepts only 3 specific words


code:
def Appviewer_SAVE(self):
    target = open("saved", "a")
    target.write("%s\t" % App_InfoTrans0())
    target.write("%s\t" % App_InfoTrans1())
    target.write("%s\n" % App_InfoTransfer_Gender) #\n doesn't make a difference here
    target.close()

rawDescription: Python files - Write to new line each time opened


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

from PyQt4 import QtGui, QtCore

class MyDialog(QtGui.QWidget):
    def __init__(self, modelSource, parent=None):
        super(MyDialog, self).__init__(parent)

        self.tableView = QtGui.QTableView(self)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.setModel(modelSource)

        self.listView = QtGui.QListView(self)
        self.listView.setModel(modelSource)
        self.listView.setModelColumn(0)

        self.comboBox = QtGui.QComboBox(self)
        self.comboBox.setModel(modelSource)
        self.comboBox.setModelColumn(1)

        self.layoutGrid = QtGui.QGridLayout(self)
        self.layoutGrid.addWidget(self.comboBox, 0, 0, 1, 2)
        self.layoutGrid.addWidget(self.listView, 1, 0, 1, 1)
        self.layoutGrid.addWidget(self.tableView, 1, 1, 1, 1)

class MyWindow(QtGui.QWidget):
    _dialogs = []
    def __init__(self, parent=None):
        super(MyWindow, self).__init__(parent)

        self.modelSource = QtGui.QStandardItemModel(self)

        for rowNumber in range(3):
            items = []
            for columnNumber in range(3):
                item = QtGui.QStandardItem()
                item.setText("row: {0} column {1}".format(rowNumber, columnNumber))

                items.append(item)

            self.modelSource.appendRow(items)

        self.labelDialogs = QtGui.QLabel(self)
        self.labelDialogs.setText("Select a number of dialogs to create:")

        self.spinBoxDialogs = QtGui.QSpinBox(self)
        self.spinBoxDialogs.setValue(3)

        self.pushButtonShow = QtGui.QPushButton(self)
        self.pushButtonShow.setText("Show Dialogs!")
        self.pushButtonShow.clicked.connect(self.on_pushButtonShow_clicked)

        self.pushButtonClose = QtGui.QPushButton(self)
        self.pushButtonClose.setText("Close Dialogs")
        self.pushButtonClose.clicked.connect(self.on_pushButtonClose_clicked)

        self.layoutHorizontal = QtGui.QHBoxLayout(self)
        self.layoutHorizontal.addWidget(self.labelDialogs)
        self.layoutHorizontal.addWidget(self.spinBoxDialogs)
        self.layoutHorizontal.addWidget(self.pushButtonShow)
        self.layoutHorizontal.addWidget(self.pushButtonClose)

    @QtCore.pyqtSlot()
    def on_pushButtonShow_clicked(self):
        self._dialogs = []
        dialogsNumber = self.spinBoxDialogs.value()

        for dialogNumber in range(dialogsNumber):
            dialog = MyDialog(self.modelSource)
            dialog.show()
            dialog.move(100, 100)

            self._dialogs.append(dialog)

    @QtCore.pyqtSlot()
    def on_pushButtonClose_clicked(self):
        for dialog in self._dialogs:
            dialog.close()

        self._dialogs = []

if __name__ == "__main__":
    import sys

    app = QtGui.QApplication(sys.argv)
    app.setApplicationName('MyWindow')

    main = MyWindow()
    main.show()

    sys.exit(app.exec_())

rawDescription: update multiple views on multiple dialogs connected to a single data model

description: Update multiple views on multiple dialogs connected to a single data model


code:
f = nx.Graph()
fedges = filter(lambda x: g.degree()[x[0]] > 0 and g.degree()[x[1]] > 0, g.edges())
f.add_edges_from(fedges)

rawDescription: python networkx remove nodes and edges with some condition

description: Python networkx remove nodes and edges with some condition


code:
with open(fname, "r") as fo:
    content_as_string = fo.read()
    match = re.search('Num_row_labels=(\d+)', content_as_string)
    # do want you want to the matchings

rawDescription: Python: read the content of a text file and look for a match/condition


code: filter(lambda x:x[0]>0, zip(a,b))

rawDescription: Neat way to conditionally select elements from two lists?


code:
from Tkinter import *  # from tkinter import *

lst = ['a', 'b', 'c', 'd']

root = Tk()
t = Text(root)
for x in lst:
    t.insert(END, x + '\n')
t.pack()
root.mainloop()

rawDescription: Printing a list to a Tkinter Text widget


code:
user = UniversityDetails.objects.get(email=email)
send_mail("Your PW", user.password, "admin@example.com", [email])

rawDescription: Forgotten password implementation in Django


code:
vals = numpy.zeros((a.shape[0], a.shape[1]))
indexOfMax = numpy.argmax(a,2)
for i in range(a.shape[0]):
  for j in range(a.shape[1]):
    vals[i,j] = b[i,j, indexOfMax[i,j]]

rawDescription: How can I convert matlab code into python code?

description: Convert matlab code into python code


code:
def upload_document(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            new_document = form.save()
            form.save_m2m()
            return HttpResponseRedirect("/thanks/")

    else:
        form = DocumentForm()

    return render_to_response('upload_page.html', {'form':form}, context_instance=RequestContext(request))

rawDescription: When and how is a many-to-many relationship created when saving a model?


rawDescription: Function to normalise string file paths

description: Function to normalise string file paths


code:
a = 'd\x04'
a
print(a)
repr(a)
print(repr(a))

rawDescription: Print string "like" the interactive interpreter?


code:
def GetFile(self, method):
    if  method not in {'url','attachment'}:
        raise ValueError

rawDescription: Python method parameter restricted class


code:
def run_script(self, script_name):
    """ Run a script on the remote array and return the stdout
    """
    try:
        chan = self._ssh.get_transport().open_session()
        # five minute timeout on the channel communication
        chan.settimeout(5*60.0)
        common_functions_file = os.path.join(SCRIPT_DIR, 'zfs_common_functions.js')
        common_functions = open(common_functions_file).read().splitlines()
        # add common_functions to the top of the script
        script_contents = common_functions + open(script_name).read().splitlines()
        chan.exec_command('script')
        if chan.send_ready():
            chan.sendall("\n".join(script_contents))
            chan.send("\n.\n")

        results = StringIO()
        error = StringIO()
        bufsize = 1024
        while not chan.exit_status_ready():
            if chan.recv_ready():
                data = chan.recv(bufsize)
                while data:
                    results.write(data)
                    data = chan.recv(bufsize)

            if chan.recv_stderr_ready():
                error_buf = chan.recv_stderr(bufsize)
                while error_buf:
                    error.write(error_buf)
                    error_buf = chan.recv_stderr(bufsize)

        exit_status = chan.recv_exit_status()
        if exit_status == 0:
            return results.getvalue()
        else:
            raise ZfsScriptError(results.getvalue())

    except socket.timeout:
        logger.warn("%s: Timeout running %s" %(self.hostname, script_name))
        return None

    except paramiko.SSHException as e:
        logger.warn(
            "Couldn't execute script on array %s: %s" % (self.hostname, e))
        raise

    except AttributeError as e:
        logger.exception(e)
        raise

    except Exception:
        raise

    finally:
        results.close()
        error.close()
        chan.close()

rawDescription: Implement timeout for paramiko with an interactive element


code:
import csv
from collections import defaultdict

db = defaultdict(list)
with open('csvfile.csv') as f:
     csvreader = csv.reader(f)
     for row in csvreader:
         db[row[0]].append((row[1], row[4], row[5], row[6]))

return db

rawDescription: Creating a database from a .csv file

description: Creating a database from a .csv file


code:
class FooAdmin(admin.ModelAdmin):
    list_display = ('get_url',)

    def get_url(self, obj):
        return "<img src='{url}' />".format(url=obj.url)
    get_url.allow_tags = True

rawDescription: Change list_display in django

description: Change list_display in django


rawDescription: using .read() from a specific part of file

description: Using .read() from a specific part of file


code:
msk = df1.apply(lambda col: df[1] != col).any(axis=1)
msk.index = df1.index  # iloc doesn't support masking
df1.loc[msk]

rawDescription: Delete duplicate values in a row within a Pandas DataFrame (Python)


code:
from subprocess import Popen, PIPE

DEBUG = True
if DEBUG:
    def log(msg, data):
        print(msg)
        print(repr(data))
else:
    def log(msg, data):
        pass

def setFromFile(fname):
    with open(fname) as inf:
        return set(ln.strip() for ln in inf)

def setFromString(s):
    return set(ln.strip() for ln in s.split("\n"))

def main():
    # get list of installed packages
    p = Popen(['dpkg', '--get-selections'], stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
    installed_packages = setFromString(stdout)

    # get list of expected packages
    known_packages = setFromFile('/home/john/packages.txt')

    # calculate the difference
    unknown_packages = installed_packages - known_packages
    unknown_packages_string = "\n".join(unknown_packages)

    log("Installed packages:", installed_packages)
    log("Known packages:", known_packages)
    log("Unknown packages:", unknown_packages)

if __name__=="__main__":
    main()

rawDescription: Creating a set from a variable instead of a file


code:
class ExampleDelegate(QtGui.QStyledItemDelegate):
    def createEditor(self, parent, option, index):
        line_edit = QtGui.QLineEdit(parent)
        line_edit.setMaxLength(3)
        return line_edit

class Example(QtGui.QDialog):
    def __init__(self,):
        super(Example, self).__init__()
        self.build_ui()

    def build_ui(self):
        self.table_model = QtGui.QStandardItemModel(4, 2)
        self.delegate = ExampleDelegate()
        self.table_view = QtGui.QTableView()
        self.table_view.setItemDelegateForColumn(0, self.delegate)
        self.table_view.setModel(self.table_model)

        self.layout.addWidget(self.table_view)
        self.layout = QtGui.QGridLayout()
        self.setLayout(self.layout)

rawDescription: How to put a QLineEdit into QTableView cell PyQt4?

description: Put a QLineEdit into QTableView cell PyQt4


code:
class PersonCreateSerializer(serializers.ModelSerializer):
    # Explicit declaration sets the field to be `read_only=False`
    id = serializers.UUIDField()

    class Meta:
        model = Person
        fields = ('id', 'username', 'email', 'password')

rawDescription: Create UUID on client and save primary key with Django REST Framework and using a POST


code:
with open(MyFile,'r') as f:
    searching = True
    for num, line in enumerate(f):
        if searching and 'Results' in line:
            ResultLine=num
            searching = False
    lastline = num

rawDescription: Python read text file and keep it open

description: Python read text file and keep it open


code:
#turn csv files into a list of lists
with open('train.csv') as csvfile:
     reader = csv.reader(csvfile, delimiter=',')
     csv_data = list(reader)

#count the amount of patients with heart problems
count = 0
for row in csv_data:
    try:
        if (row and int(row[13]) > 0):
            count += 1
    except IndexError:
        print("could not find the heart diseases status for the row" + str(row))

print("the amount of patients with heart disease is " + str(count))

rawDescription: CSV how to split and find number of 0's in column


rawDescription: How would I get everything before a : in a string Python


code:
from django.db.models.signals import pre_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(post_save, sender=ValidateResult)
def my_handler(sender, **kwargs):
    ...

rawDescription: Auto Update Django Model based on other model fields


code:
import itertools

def perm(n, seq):
    for p in itertools.product(seq, repeat=n):
        file.write("".join(p))
        file.write("\n")

perm(4, "0123")

rawDescription: Python itertools permutations how to include repeating characters


code:
data = [1,2,3,4,5,6]

out = open("output.txt", "w")

for i in data:
    out.write(str(i) + "\n")

out.close()

rawDescription: Python: Turning arrays into text files

description: Python: Turning arrays into text files


code:
values = KeyedTuple(*zip(*(
                    (row[i], k) for i, k in enumerate(row.keys())
                    if not k in ("year", "month")
                    )))

# or, just simple tuple:
values = tuple(row[i] for i, k in enumerate(row.keys())
               if not k in ("year", "month"))

rawDescription: Better way to get certain fields from a SQLAlchemy KeyedTuple


code:
array = [1, 2, 3, 4, 2, -2, -3, 8, 3, 0]
array = map(lambda x: x if x < 3 else 2, array)
array

rawDescription: Replacing elements in an array in Python


rawDescription: Create a slice using a tuple

description: Create a slice using a tuple


code:
form = MyForm(data=request.POST)
if form.is_valid():   # checks of the form and its fields validate
    form.save()
# else you can do something else, show the validation errors for example

rawDescription: How to work with ModelForm and ModelFormSet

description: Work with ModelForm and ModelFormSet


code:
# configuration
from kivy.config import Config
Config.set('graphics', 'width',  800)
Config.set('graphics', 'height', 600)

# other imports
from kivy.app import App
from kivy.uix.widget import Widget
...

rawDescription: Force Window Size Kivy

description: Force Window Size Kivy


rawDescription: Calculate STD manually using Groupby Pandas DataFrame


code:
df = pd.DataFrame(random_integers(0,100,(3,3)),columns=list('ABC'),index=list('abc'))

differ = reshape([sum(df[col2]-df[col]) for col2 in df for col in df], (3,3))
differ = pd.DataFrame(differ, columns=list('ABC'),index=list('ABC'))

differ

rawDescription: More elegant computation of zscore of column differences in Pandas


code:
import cv2
cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        cv2.imwrite("image.png", frame)
        break

cv2.destroyWindow("preview")

rawDescription: Launching webcam and capturing an image using python


code:
import numpy as np
A = np.matrix([[1,2,3,33],[4,5,6,66],[7,8,9,99]])

np.argmax(A)  # 11, which is position of 99

np.argmax(A[:,:])  # 11, which is position of 99

np.argmax(A[:1])  # 3, which is position of 33

np.argmax(A[:,2])  # 2, which is position of 3
np.argmax(A[1:,2])  # 1, which is position of 2

rawDescription: Understanding argmax

description: Understanding argmax


code:
import os
import numpy as np
import pandas as pd

def get_df_in_chunks(file_names, **kwargs):
    """Read all files in chunks."""
    # Set default chunk size if not specified.
    kwargs['chunksize'] = kwargs.get('chunksize', 100000)
    for file_name in file_names:
        df = pd.read_csv(file_name, **kwargs)
        yield from iter(df)

my_path = '.'
file_names = [my_path + "\\" + file for file in os.listdir(my_path) if file.endswith(".csv")]
print('file_names: {}'.format(file_names))

# Read all files to determine the global min and max values.
min_x = +np.inf
max_x = -np.inf
min_y = +np.inf
max_y = -np.inf
for chunk in get_df_in_chunks(file_names, header=None, dtype=np.float32,
                              usecols=["x","y"], names=["x","y"]):
    print('  - chunk: {}'.format(chunk.shape))
    min_x = min(min_x, chunk["x"].min())
    max_x = max(max_x, chunk["x"].max())
    min_y = min(min_y, chunk["y"].min())
    max_y = max(max_y, chunk["y"].max())
print("x min/max:", min_x, max_x)
print("y min/max:", min_y, max_y)

# Calculate tile extents.
tile_size = 1.5
tile_limits = [min_x - (min_x%tile_size),
               max_x - (max_x%tile_size) + tile_size,
               min_y - (min_y%tile_size),
               max_y - (max_y%tile_size) + tile_size]
print("tile_size:", tile_size)
print("tile_limits:", tile_limits)

if not os.path.exists(my_path + "\\tiles"):
    os.mkdir(my_path + "\\tiles")

tile_files = []
try:
    # Open all tile files.
    for i in range(int(round(tile_limits[1]-tile_limits[0])/tile_size)):
        for j in range(int(round(tile_limits[3]-tile_limits[2])/tile_size)):
            tile_extent = [tile_limits[0] + i*tile_size,
                           tile_limits[0] + i*tile_size + tile_size,
                           tile_limits[2] + j*tile_size,
                           tile_limits[2] + j*tile_size + tile_size]
            f = open(my_path + "\\tiles\\{},{}.csv".format(i,j), 'w')
            tile_files.append((f, tile_extent))

    for chunk in get_df_in_chunks(file_names, header=None, dtype=np.float32,
                                  usecols=["x","y","z"], names=["x","y","z"]):
        # For each tile, write all relevant rows into the corresponding tile file.
        for f, tile_extent in tile_files:
            # Option 1: boolean condition.
            frame = chunk[(chunk["x"] >= tile_extent[0]) &
                          (chunk["x"] <  tile_extent[1]) &
                          (chunk["y"] >= tile_extent[2]) &
                          (chunk["y"] <  tile_extent[3])]
            # Option 2: query using numexpr. Could be faster, but wasn't in my test.
            #frame = chunk.query('x >= {} & x < {} & y >= {} & y < {}'.format(*tile_extent))

            ##print('file: {} tile_extent: {} frame: shape={}'.format(f.name, tile_extent, frame.shape))
            frame.to_csv(f, header=None, index=False)
finally:
    # Close all tile files.
    for f, _ in tile_files:
        f.close()

rawDescription: Effectively order XYZ coordinates from many huge CSV files into small tiles


code:
import string, random
from hashlib import sha512

def get_random_string(size):
    chars = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(chars) for _ in range(size))

def draegg_view(request):
    size = 40
    if request.method == 'POST':
        text = get_random_string(size)
        hash = sha512(text).hexdigest()
        form = genSysForm(initial={'Key':text, 'Hash': hash })
    else:
        form = genSysForm()
    return render_to_response('synopticup/monodra.html', {'form': form}, context_instance=RequestContext(request))

rawDescription: Convert simultaneously to a SHA512 hash

description: Convert simultaneously to a SHA512 hash


code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

museum_dictionary = { "louvre": "Paris", "prado": "Madrid"}

driver = webdriver.Firefox()

def YahooImager(searchterm):
    page = "https://images.search.yahoo.com"

    landing = driver.get(page)

    WebDriverWait(driver, 4)

    assert "Yahoo Image Search" in driver.title

    searchbox = driver.find_element_by_name("p") # Find the query box

    city = museum_dictionary[searchterm]

    searchbox.send_keys("{} {}".format(searchterm, city) + Keys.RETURN)

    WebDriverWait(driver, 4)

    try:
        driver.find_element_by_xpath('//*[@id="resitem-0"]/a').click()
    except NoSuchElementException:
        assert 0, '//*[@id="resitem-0"]/a'
        driver.close()

    WebDriverWait(driver, 4)

    try:
        driver.find_element_by_link_text("View Image").click()
    except NoSuchElementException:
        assert 0, "View Image"
        driver.close()

    WebDriverWait(driver, 4)

    # driver.close()

    return driver.current_url

image_url = YahooImager("prado")

print(repr(image_url))

rawDescription: Retrieving url from google image search for first entry, using python and selenium


code: new_list = [[element or '0.00' for element in sublist] for sublist in big_list]

rawDescription: replace empty elements in list of list

description: Replace empty elements in list of list


code:
Relation1 = dev_engine.execute(sqlquery1)
relation1_items = [r for r in Relation1]
# ...
# now you can iterate over relation1_items as much as you want

rawDescription: Iterating over table multiple times Python SQLAlchemy


code:
DetailedWorkData = [["Detailed Work Information",""],
                    ["Procedure: XXXXX", "Planned by: XXXXXX"]]
b = Table(DetailedWorkData, colWidths=[285,285])
b.hAlign = "LEFT"
b.setStyle(TableStyle([
                       ('BACKGROUND',(0,0),(-1,0),HexColor("#C0C0C0")),
                       ('GRID',(0,1),(-1,-1),0.01*inch,(0,0,0,)),
                       ('FONT', (0,0), (-1,0), 'Helvetica-Bold')]))
Story.append(b)

rawDescription: Python ReportLab -- Table too wide for page


code:
joes_images = ImageItem.objects.filter(user__username='joe')  # your code
upload_dates = set([(i.year, i.month, i.day) for i in joes_images])  # set of upload_date
joes_images_separated = dict([(d, []) for d in upload_dates])
for d in upload_dates:
    for i in joes_images:
        if (i.year, i.month, i.day) == d:
            joes_images_separated[d].append(i)

rawDescription: Django/Python: How to group queryset results by date?


code:
from collections import defaultdict
from itertools import chain
from banyan import SortedDict, OverlappingIntervalsUpdator

def closed_regions(rects):

    # Sweep Line Algorithm to set up adjacency sets:
    neighbors = defaultdict(set)
    status = SortedDict(updator=OverlappingIntervalsUpdator)
    events = sorted(chain.from_iterable(
            ((r.left, False, r), (r.right, True, r)) for r in set(rects)))
    for _, is_right, rect in events:
        for interval in status.overlap(rect.vertical):
            neighbors[rect].update(status[interval])
        if is_right:
            status.get(rect.vertical, set()).discard(rect)
        else:
            status.setdefault(rect.vertical, set()).add(rect)

    # Connected Components Algorithm for graphs:
    seen = set()
    def component(node, neighbors=neighbors, seen=seen, see=seen.add):
        todo = set([node])
        next_todo = todo.pop
        while todo:
            node = next_todo()
            see(node)
            todo |= neighbors[node] - seen
            yield node
    for node in neighbors:
        if node not in seen:
            yield component(node)

rawDescription: How to find rectangle intersection in python?

description: Find rectangle intersection in python


code:
import numpy as np

contours, hierarchy = cv2.findContours(bw_img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = np.vstack(contours).squeeze()

rawDescription: Convert contour to 2d point list in opencv


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

x = np.arange(start=0, stop=5, step=0.1)

n_data = len(x)
n_rnd = 1000

m = np.random.normal(loc=1, scale=0.3, size=n_rnd)
b = np.random.normal(loc=5, scale=0.3, size=n_rnd)

y = m * x[:, np.newaxis] + b

for val in y.transpose():
    plt.plot(x, val, alpha=0.05)

# Or without the iteration:
# plt.plot(x, y, alpha=0.05)

plt.show()

rawDescription: How to efficiently generate a straight line with random slope and intercept in Python?

description: Efficiently generate a straight line with random slope and intercept in Python


code:
def myfunction(current):
    current += 1
    myvalue = 'Test Value'
    print(current)
    return current, myvalue

current = 1
while ( current < 10 ):
    current, myvalue = myfunction(current)
    print(myvalue)

rawDescription: Python access variable in while loop

description: Python access variable in while loop


rawDescription: Sorting Pandas Dataframe by order of another index


code:
import ctypes
def winSetClipboard(text):
    GMEM_DDESHARE = 0x2000
    ctypes.windll.user32.OpenClipboard(0)
    ctypes.windll.user32.EmptyClipboard()
    try:
        # works on Python 2 (bytes() only takes one argument)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text))+1)
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        hCd = ctypes.windll.kernel32.GlobalAlloc(GMEM_DDESHARE, len(bytes(text, 'ascii'))+1)
    pchData = ctypes.windll.kernel32.GlobalLock(hCd)
    try:
        # works on Python 2 (bytes() only takes one argument)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text))
    except TypeError:
        # works on Python 3 (bytes() requires an encoding)
        ctypes.cdll.msvcrt.strcpy(ctypes.c_char_p(pchData), bytes(text, 'ascii'))
    ctypes.windll.kernel32.GlobalUnlock(hCd)
    ctypes.windll.user32.SetClipboardData(1,hCd)
    ctypes.windll.user32.CloseClipboard()

rawDescription: Python script importing results to ctrl-c memory


code:
x=6

for words in foo:
  if "bar" in words:
    x = -x;

rawDescription: Convert an integer to its negative

description: Convert an integer to its negative


code:
0 and 'string'
1 and 'string'
'string' or 10
'' or 10

rawDescription: What does Python return when we return with logical operator?


code:
import time, sys

for i in [1,2,3,4,5]:
    sys.stdout.write(str(i))
    sys.stdout.flush() #flush the buffer because python buffers stdout
    time.sleep(5)
    sys.stdout.write("\b") #literally "write backspace".
    sys.stdout.flush()

rawDescription: Stdout and flush? It's appending and not flushing


code:
# -*- coding: UTF-8 -*-

from bs4 import BeautifulSoup as B_S
import pymysql as db
import time

def mod_content():

    conn = db.connect( host='192.xxx.x.xxx', port=3306, user='USER', passwd='PASSWORD', db='GRW', charset='utf8' ) ## declare charset
    c = conn.cursor()
    sql = "SELECT city_id,nid,html_content,notes FROM content_city WHERE nid = 13 AND city_id = 182 ORDER BY city_id"
    c.execute( sql )

    for rec in c.fetchall():
        contents = rec[2]

        temp = B_S( contents)
        soup = temp.body

        allDivs = soup.find_all( 'div', { 'class':'picright' } )
        for div in allDivs:
            print( str( div )[ :80 ] )
            '''
            do clean up stuff
            '''

        # now, output the data. I end up with utf-8 string with ascii diacritics
        contents = soup.encode( 'ascii' )
        content_2str = contents.decode( 'utf-8' )
        content_2str = content_2str.replace( "'", "'" ) ## single quotes replaced
        content_2str = ' '.join( content_2str.split() ) ## removes extra spaces and line breaks - now compacted

        ## I can now print it to file or update MySQL
        if updateSQL == 'yes':

            sql = "UPDATE content_city SET html_content = '" + content_2str + \
            "',notes = '" + notes_2str + "' WHERE city_id = " + str( recID ) + \
            " AND nid = " + str( nid ) + ""

            c.execute( sql )
            conn.commit()

        if printToFile == 'yes':

            file2 = tempRoot + NIDs[ key ]+'_MOD.html'
            mod = open( file2, 'a',4 )

            mod.write( '\n' + str( nid ) + '\n' + str( recID ) + '\n' + \
                       content_2str + '\n' + notes_2str + '\n\n' )
            time.sleep(1)
            mod.close()

    print( 'mod_content Complete' )

mod_content()

rawDescription: Converting inconsistant encoding to utf-8 Python 3.4 BS 4.3


code:
import json
d = {'firstKey': True, 'secondKey': False}
json.dumps(d)
s = json.dumps(d)
json.loads(s) == d

rawDescription: Loading JSON object with special values as a string


code:
tags = nltk.pos_tag(tokens)
dt_tags = [t for t in tags if t[1] == "DT"]
dt_tags

rawDescription: Filter Specific Part of Speech NLTK

description: Filter Specific Part of Speech NLTK


code:
from passlib.hash import sha256_crypt
hashed = sha256_crypt.encrypt(password)

rawDescription: Password submission in Python

description: Password submission in Python


code: turtle.write('Hello, Robert', font=("Arial", 8, "normal"))

rawDescription: How to make the font size of turtle.write function larger

description: Make the font size of turtle.write function larger


code:
myDict = {
    'p1': {1: [1, 2, 3], 2: [4, 5, 6]},
    'p2': {3: [7, 8, 9], 4: [0, 1, 2]}
}

from collections import Mapping

def go_go_gadget_go(mapping):
    for k, v in mapping.items():
        if isinstance(v, Mapping):
            for ok in go_go_gadget_go(v):
                yield [k] + ok
        else:
            yield [k] + [v]

for protocol, n, counts in go_go_gadget_go(myDict):
    print(protocol, n, counts)

# p2 3 [7, 8, 9]
# p2 4 [0, 1, 2]
# p1 1 [1, 2, 3]
# p1 2 [4, 5, 6]

rawDescription: Access Nested Levels of a dict Without Nested Looping


code:
import datetime as dt

d = dt.datetime.strptime("25-01-1973", "%d-%m-%Y")

# Convert datetime object to date object.
d = d.date()

print(d.isoformat())
# 1973-01-25

rawDescription: Converting string to date object without time info


code:
def cutter(seq):
    n = len(seq)
    if n <= 20:
        # here the recursion stops, do your stuff with the sequence
        return
    a = cutter(seq[:n/2])
    b = cutter(seq[n/2:])
    # combine the answer from both subsequences
    return

rawDescription: Splitting a range of numbers up recursively with Python


code:
class MyModel(models.Model):
    field_1 = models.CharField(max_length=80)
    field_2 = models.Charfield(max_length=80)

    def save(self, *args, **kwargs):
        #Here you can have all kinds of validations you would need

        self.field_2 = self.field_1 + "extra info"
        super(MyModel, self).save(*args, **kwargs)

rawDescription: Using own field to define others in Django Models


code:
df
df.groupby('Name').agg({'Mins': np.sum, 'Goals': np.sum, 'Ass': np.sum, 'Value': lambda x: x.iloc[-1]})

rawDescription: Dataframes - Sum some columns, get the last value from others


code:
class Base(object):
    ...
    def fun(self):
        raise NotImplementedError

rawDescription: How to properly decorate a function to be overridden in python?

description: Properly decorate a function to be overridden in python


code:
df = pd.DataFrame({'accredited': ['10/10/2011', 'is not accredited']})
df
df['accredited'] = df['accredited'].str.replace(r'(?i).*not.*', 'not accredited')
df

rawDescription: Replace string values in a dataframe based on regex match


code:
import requests
s = requests.session()

def get_csrf_tokens():
    url = "https://www.linkedin.com/"
    req = s.get(url).text

    csrf_token = req.split('name="csrfToken" value=')[1].split('" id="')[0]
    login_csrf_token = req.split('name="loginCsrfParam" value="')[1].split('" id="')[0]

    return csrf_token, login_csrf_token

def login(username, password):
    url = "https://www.linkedin.com/uas/login-submit"
    csrfToken, loginCsrfParam = get_csrf_tokens()

    data = {
        'session_key': username,
        'session_password': password,
        'csrfToken': csrfToken,
        'loginCsrfParam': loginCsrfParams
    }

    req = s.post(url, data=data)

login('username', 'password')

rawDescription: why isn't Requests not signing into a website correctly?

description: Why isn't Requests not signing into a website correctly


code:
def getCountofproducts(list):
    #list - category ids

    where = '"{0}"."{1}" = "CORE_RELATIONSHIP"."CHILD_ID"'.format(Product._meta.db_table, Product._meta.pk.column)
    table = '"{0}"'.format(clsObj._meta.db_table)

    return Category.objects.filter(p2c__parent_id__in=list, p2c__type="rel", p2c__child_id__isnull=False)\
                                    .values('p2c__parent').annotate(childCount=Count('p2c__parent'))\
                                    .extra(tables=[table], where=[where.upper()])

rawDescription: Django + Oracle count

description: Django + Oracle count


code:
from mycelerytasks import send_email

...

deferred_result = send_email.apply_async(*args, **kwargs)

rawDescription: Python/Django AMQP?

description: Python/Django AMQP


code:
def matching_sublists(dict1, dict2):
    result = dict()
    for k in dict1:
        assert(k in dict2)
        result[k] = 0
        A = [set(l) for l in dict1[k]]
        B = [set(l) for l in dict2[k]]
        for sublistA in A:
            result[k] += sum([1 for sublistB in B if not sublistA.isdisjoint(sublistB) ])
    return result

if __name__=='__main__':
    dict1={"key1":[[1,2],[6,7]],"key2":[[1,2,3,4,5,6,7,8,9]]}
    dict2={"key1":[[0,1,2,3],[5,6,7,8],[11,13,15]],"key2":[[7,8,9,10,11],[16,17,18]]}
    print(matching_sublists(dict1, dict2))

rawDescription: Matching values in variable length lists containing sublists in python


code:
t1 = datetime.datetime.now()
t1.strftime("%U")

rawDescription: How can I find week numbers with weeks starting on Sunday in Python?

description: Find week numbers with weeks starting on Sunday in Python


code:
import matplotlib.pyplot as plt
import networkx as nx
graph = {
    '1': ['2', '3', '4'],
    '2': ['5','11','12','13','14','15'],
    '3' : ['6','7','66','77'],
    '5': ['6', '8','66','77'],
    '4': ['7','66','77'],
    '7': ['9', '10']
    }

MG = nx.DiGraph(graph)

plt.figure(figsize=(8,8))
pos=nx.graphviz_layout(MG,prog="twopi",root='1')

nodes = MG.nodes()
degree = MG.degree()
color = [degree[n] for n in nodes]
size = [2000 / (degree[n]+1.0) for n in nodes]

nx.draw(MG, pos, nodelist=nodes, node_color=color, node_size=size,
        with_labels=True, cmap=plt.cm.Blues, arrows=False)
plt.show()

rawDescription: Python networks change color of nodes when using draw_network_nodes()


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

a = np.array([
    [1293605162197, 0, 0],
    [1293605477994, 63, 0],
    [1293605478057, 0, 0],
    [1293605478072, 2735, 1249],
    [1293606162213, 0, 0],
    [1293606162229, 0, 0]])

d = a[:,0]
y1 = a[:,1]
y2 = a[:,2]

# convert epoch to matplotlib float format
s = d/1000
ms = d-1000*s  # not needed?
dts = map(datetime.datetime.fromtimestamp, s)
fds = dates.date2num(dts) # converted

# matplotlib date format object
hfmt = dates.DateFormatter('%m/%d %H:%M')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.vlines(fds, y2, y1)

ax.xaxis.set_major_locator(dates.MinuteLocator())
ax.xaxis.set_major_formatter(hfmt)
ax.set_ylim(bottom = 0)
plt.xticks(rotation='vertical')
plt.subplots_adjust(bottom=.3)
plt.show()

rawDescription: Creating graph with date and time in axis labels with matplotlib


code:
from django.forms import ModelForm, ChoiceField
class MyModelForm(ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        geoiplocator_instance = GeoIpLocator()
        city_country_dictionary=geoiplocator_instance.get_country_city_dictionary()
        users_country_name = city_country_dictionary['country_name']
        users_city = city_country_dictionary['city']

        # not exactly sure what you wanted to do with this choice field.
        # make the country the only option? Pull a list of related countries?
        # add it and make it the default selected?
        self.fields['country'] = ChoiceField(choices = [(users_country_name, users_country_name),])
        self.fields['city'].initial = users_city

rawDescription: Dynamically populating values in djangoform


code:
from igraph import Graph
from random import randint
g = Graph.GRG(100, 0.2)        # generate a geometric random graph
g.es["capacity"] = [randint(0, 1000) for i in xrange(g.ecount())]
cut = g.maxflow(0, 99, "capacity")

rawDescription: s-t cut algorithm in Python

description: S-t cut algorithm in Python


rawDescription: Extracting aws region from s3 event data in python (lambda)


code:
import scipy
import scipy.stats
#now you can use
scipy.stats.poisson
#if you want it more accessible you could do what you did above
from scipy.stats import poisson
#then call poisson directly
poisson

rawDescription: No module named scipy.stats - Why despite scipy being installed


code:
def test_foo():
    new_account = account()

rawDescription: How can I manually trigger re-execution of a shared py.test fixture?

description: Manually trigger re-execution of a shared py.test fixture


code:
displays = (wx.Display(i) for i in range(wx.Display.GetCount()))
sizes = [display.GetGeometry().GetSize() for display in displays]

rawDescription: How to find the screen size of two monitors using wx.displaySize()

description: Find the screen size of two monitors using wx.displaySize()


code:
class whatever:
    animals = AnimalObject()
    fruits = FruitObject()

class AnimalObject:
    animals = ['cows','moose']
    properties = [9,26]

class FruitObject:
    land = ['strawberries', 'other berries']
    space = ['apples', 'cherries']

rawDescription: How to simplify creating huge data structures in Python

description: Simplify creating huge data structures in Python


rawDescription: Get the __file__ of the function one level up in the stack


code: count_vect = CountVectorizer(tokenizer=lambda text: tokenizer(text, **args), stop_words='english', strip_accents='ascii', min_df=0, max_df=1., vocabulary=None)

rawDescription: PYTHON: How to pass tokenizer with keyword arguments to scikit's CountVectorizer?


code: six_or_none(4) is None

rawDescription: Python doctests: test for None

description: Python doctests: test for None


code:
import urllib2

url_response = urllib2.urlopen('http://myip:myport/?CreateOrder=Create+New+Order')

rawDescription: Python execute HTTP commands

description: Python execute HTTP commands


rawDescription: How to use (new style) string formatting in matplotlib figure text

description: Use (new style) string formatting in matplotlib figure text


code:
list_file = open("header.txt")
search_words = [word.strip() for word in list_file]
list_file.close()

matches = []

master_file = open("master_file.txt")

store = False
for line in master_file:
    if not store and line.strip() and any(line.strip() in s for s in search_words):
        store = True
    if not line.strip():
        print(line)
        store = False

    if store:
           matches.append(line)

rawDescription: Searching large text file with python

description: Searching large text file with python


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

def CustomQuerySet(QuerySet):
    @commit_on_success
    def update(self, **kwargs):
        for instance in self:
            pre_save.send(sender=instance.__class__, instance=instance, raw=False,
                          using=self.db, update_fields=kwargs.keys())
        # use self instead of self.all() if you want to reload all data
        # from the db for the post_save signal
        result = super(CustomQuerySet, self.all()).update(**kwargs)
        for instance in self:
            post_save.send(sender=instance.__class__, instance=instance, created=False,
                           raw=False, using=self.db, update_fields=kwargs.keys())
        return result

    update.alters_data = True

rawDescription: Django "emulate" database trigger behavior on bulk insert/update/delete


code:
for y in range(-10,1,2):
    self.bottomframe.update()
    self.bottomframe.place(in_=self.statusframe, relx=1,  y=y**2, anchor="se", relwidth=1, bordermode="outside")

rawDescription: In Python 3 (tkinter) is it possible to animate a frame?


code:
from collections import defaultdict

class trie:
    __slots__ = ('children', 'freq', 'name', 'top5')

    def __init__(self):
        self.children = defaultdict(trie)
        self.freq = 0
        self.name = None
        self.top5 = []

    def __getitem__(self, suffix):
        node = self
        for letter in suffix:
            node = node.children[letter]
        return node

    def computetop5(self):
        candidates = []
        for letter, child in self.children.items():
            child.computetop5()
            candidates.extend(child.top5)
        if self.name is not None:
            candidates.append((self.freq, self.name))
        candidates.sort(reverse=True)
        self.top5 = candidates[:5]

    def insert(self, freq, name):
        node = self[name]
        node.freq += freq
        node.name = name

root = trie()
with open('letter_s.txt') as f:
    for line in f:
        freq, name = line.split(None, 1)
        root.insert(int(freq.strip()), name.strip())
root.computetop5()
print(root['St'].top5)

rawDescription: Autocomplete Style Prefix Lookup

description: Autocomplete Style Prefix Lookup


code:
from behave.__main__ import main as behave_main
behave_main("path/to/tutorial")

rawDescription: Run python behave from python instead of command line


code:
from string import maketrans

complement_tt = maketrans('01', '10')

s = '001001'
s = s.translate(complement_tt)  # It's now '110110'

rawDescription: complement/negate a boolean string in python

description: Complement/negate a boolean string in python


code:
import requests
import BeautifulSoup as bs

URL = "page to get"
pg = requests.get(URL).content
pg = bs.BeautifulSoup(pg)

scripts = bs.findAll('script')

for sc in scripts:
    try:
        print("External code at {}".format(sc['src']))
    except KeyError:
        print("Inline code:")
        print(sc.getText())

rawDescription: How to export javascript from html using python

description: Export javascript from html using python


code:
ri = [0,2]
a[np.ix_(ri, ci)]
s=a[np.ix_(ri, ci)]
np.may_share_memory(a, s)

rawDescription: How to create a sub-matrix in numpy

description: Create a sub-matrix in numpy


rawDescription: Pandas: convert items to dict where orderID is the dict key


code:
def getRelativeFrameGeometry(widget):
    g = widget.geometry()
    fg = widget.frameGeometry()
    return fg.translated(-g.left(),-g.top())

def screenCaptureWidget(widget, filename, fileformat='png'):
    rfg = getRelativeFrameGeometry(widget)
    pixmap =  QtGui.QPixmap.grabWindow(widget.winId(),
                                       rfg.left(), rfg.top(),
                                       rfg.width(), rfg.height())
    pixmap.save(filename, fileformat)

rawDescription: how to take a screenshot of a PySide widget that is a window, and include the titlebar and border

description: Take a screenshot of a PySide widget that is a window, and include the titlebar and border


code:
import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.button1 = tk.Button(self.frame, text = 'New Window', width = 25, command = self.new_window)
        self.button1.pack()
        self.frame.pack()
    def new_window(self):
        self.newWindow = tk.Toplevel(self.master)
        self.app = Demo2(self.newWindow)

class Demo2:
    def __init__(self, master):
        self.master = master
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.quitButton.pack()
        self.frame.pack()
    def close_windows(self):
        self.master.destroy()

def main():
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Tkinter example code for multiple windows, why won't buttons load correctly?


code:
date_string = '{0} {1}'.format(fl['journey']['Day'][row] - 1,
                               fl['journey']['BeginTime'][row])

dateobj = datetime.datetime.strptime(date_string, '%w %H:%M:%S')

rawDescription: Add day of week to a time in Python strptime


code:
foo \
.bar \
.baz

(foo
.bar
.baz)

rawDescription: Nicer way of method chaining in Python?

description: Nicer way of method chaining in Python


code:
import sys
import types
import unittest

from nose.config import Config, all_config_files
from nose.core import run
from nose.loader import TestLoader
from nose.suite import ContextSuite
from nose.plugins.manager import PluginManager

from myapp import find_test_objects

def load_tests(config, obj):
    """Load tests from an object

    Requires an already configured nose.config.Config object.

    Returns a nose.suite.ContextSuite so that nose can actually give
    formatted output.
    """

    loader = TestLoader()
    kinds = [
        (unittest.TestCase, loader.loadTestsFromTestCase),
        (types.ModuleType, loader.loadTestsFromModule),
        (object, loader.loadTestsFromTestClass),
    ]
    tests = None
    for kind, load in kinds.items():
        if isinstance(obj, kind) or issubclass(obj, kind):
            log.debug("found tests for %s as %s", obj, kind)
            tests = load(obj)
            break

    suite = ContextSuite(tests=tests, context=obj, config=config)

def main():
    "Actually configure the nose config object and run the tests"
    config = Config(files=all_config_files(), plugins=PluginManager())
    config.configure(argv=sys.argv)

    tests = []
    for group in find_test_objects():
        tests.append(load_tests(config, group))

    run(suite=tests)

rawDescription: Good way to collect programmatically generated test suites in nose or pytest


rawDescription: How to declare array of zeros in python (or an array of a certain size)

description: Declare array of zeros in python (or an array of a certain size)


code: mat - scipy.sparse.dia_matrix((mat.diagonal()[scipy.newaxis, :], [0]), shape=(one_dim, one_dim))

rawDescription: Remove/set the non-zero diagonal elements of a sparse matrix in scipy


rawDescription: Does python support decorator in runtime?


code:
# define the normal (yellow) grid
tcks = np.arange(0,90,10)

fig, ax = plt.subplots(figsize=(8,8))

# plot the sample data
ax.imshow(z, cmap=plt.cm.Greys_r, interpolation='none', vmin=0.4, vmax=1.5, extent=[0,z.shape[0],0,z.shape[1]])

ax.set_xticks(tcks)
ax.set_xticks(tcks+5, minor=True)

ax.set_yticks(tcks)
ax.set_yticks(tcks+5, minor=True)

ax.xaxis.grid(True,'minor', linestyle='--', lw=1., color='y')
ax.yaxis.grid(True,'minor', linestyle='--', lw=1., color='y')

ax.xaxis.grid(True,'major', linestyle='-', lw=1., color='r')
ax.yaxis.grid(True,'major', linestyle='-', lw=1., color='r')

ax.set_xlim(0,80)
ax.set_ylim(0,80)

rawDescription: Plotting two different sized grids. Smaller grid centred on the centre of the bigger


code:
def main():
    infile = open("abbreviations.txt", "r")
    d = {}
    w = []
    for line in infile:
        temp = line.split(":")
        d[temp[0]]=temp[1].rstrip()
        # For easy punctuation marks manage add these rules
        d[temp[0]+"?"] = temp[1].rstrip()+"?"
        d[temp[0]+"!"] = temp[1].rstrip()+"!"
        d[temp[0]+","] = temp[1].rstrip()+","
        d[temp[0]+"."] = temp[1].rstrip()+"."
        w.append(temp[0])
    infile.close()
    im = input("Please input the instant message:   ")
    im = im.split() # Split with space as separator
    res = "" # String to store the result
    for i in im: #Iterate over words
        if i in d: # If the word is in our dic
            res += d[i] # Add the substitution to result
        else: # If no substitution needed
            res += i  # Add original word
        res += " " # Add a space after each word

    res = res.strip() # Delete extra spaces at the end
    print(im)
    print(res)

main()

rawDescription: PYTHON: Translation - Instant message abbreviation --> text?


code:
renderers = iconview.get_cells()
iconview.clear()
for r in renderers:
    if not isinstance(r, Gtk.TextRenderer):
        iconview.pack_start(r)
    else:
        iconview.pack_start(my_custom_renderer)

rawDescription: How do I create a Gtk Iconview with a custom CellRendererText

description: Create a Gtk Iconview with a custom CellRendererText


code:
wordcount = {}
with open('/Users/user/Desktop/Text.txt', 'r', encoding='utf-8') as f:
    for line in f:
        for word in line.split():
            line = line.lower()
            word = word.strip(string.punctuation + string.digits)
            if word:
                if word in wordcount:
                    wordcount[word] += line.count(word)
                else:
                    wordcount[word] = line.count(word)
    return wordcount

rawDescription: Read words from file into dictionary

description: Read words from file into dictionary


code:
def sizes(s):
    s['size_kb'] = locale.format("%.1f", s['size'] / 1024.0, grouping=True) + ' KB'
    s['size_mb'] = locale.format("%.1f", s['size'] / 1024.0 ** 2, grouping=True) + ' MB'
    s['size_gb'] = locale.format("%.1f", s['size'] / 1024.0 ** 3, grouping=True) + ' GB'
    return s

df_test = df_test.append(rows_list)
df_test = df_test.apply(sizes, axis=1)

rawDescription: Return multiple columns from apply pandas


code:
# Other imports here
from werkzeug.utils import safe_join

# ... snip Flask setup ...

@app.route("/reports/<path:report_name>")
def report_viewer(report_name):
    if report_name is None:
        abort(404)

    BASE_PATH = "/your/base/path/to/reports"

    fp = safe_join(BASE_PATH, report_name)
    with open(fp, "r") as fo:
        file_contents = fo.read()

    return file_contents

rawDescription: Set iframe src response from Flask

description: Set iframe src response from Flask


code:
#!/usr/bin/python
from gi.repository import Gtk, GLib, GObject
from gi.repository import AppIndicator3 as appindicator
import os
import signal

class Gui():
    def __init__(self):
        self.window = Gtk.Window(title="Signal example")
        self.window.set_size_request(250,150)
        self.window.connect("delete-event", Gtk.main_quit)
        self.window.show_all()

    def cleanup(self):
        print("... Cleaning up variables, etc.")

    def quit(self, widget):
        print("... Exiting main gtk loop")
        Gtk.main_quit()

def InitSignal(gui):
    def signal_action(signal):
        if signal is 1:
            print("Caught signal SIGHUP(1)")
        elif signal is 2:
            print("Caught signal SIGINT(2)")
        elif signal is 15:
            print("Caught signal SIGTERM(15)")
        gui.cleanup()
        gui.quit(None)

    def idle_handler(*args):
        print("Python signal handler activated.")
        GLib.idle_add(signal_action, priority=GLib.PRIORITY_HIGH)

    def handler(*args):
        print("GLib signal handler activated.")
        signal_action(args[0])

    def install_glib_handler(sig):
        unix_signal_add = None

        if hasattr(GLib, "unix_signal_add"):
            unix_signal_add = GLib.unix_signal_add
        elif hasattr(GLib, "unix_signal_add_full"):
            unix_signal_add = GLib.unix_signal_add_full

        if unix_signal_add:
            print("Register GLib signal handler: %r" % sig)
            unix_signal_add(GLib.PRIORITY_HIGH, sig, handler, sig)
        else:
            print("Can't install GLib signal handler, too old gi.")

    SIGS = [getattr(signal, s, None) for s in "SIGINT SIGTERM SIGHUP".split()]
    for sig in filter(None, SIGS):
        print("Register Python signal handler: %r" % sig)
        signal.signal(sig, idle_handler)
        GLib.idle_add(install_glib_handler, sig, priority=GLib.PRIORITY_HIGH)

if __name__ == "__main__":
    gui = Gui()
    InitSignal(gui)
    Gtk.main()

rawDescription: Python GTK signal handler not working

description: Python GTK signal handler not working


code: arrays = [np.array(map(int, line.split())) for line in open('scienceVertices.txt')]

rawDescription: Reading non-uniform data from file into array with NumPy


code:
non = lambda s: s if s<0 else None
mom = lambda s: max(0,s)

ox, oy = 100, 20

shift_lena = numpy.zeros_like(lena)
shift_lena[mom(oy):non(oy), mom(ox):non(ox)] = lena[mom(-oy):non(-oy), mom(-ox):non(-ox)]

rawDescription: Shifting an image in numpy

description: Shifting an image in numpy


code:
gen = (float(line.partition(' ')[0]) for line in open(fname))
min(enumerate(gen), key=lambda x: abs(x[1] - a))

rawDescription: In Python, how do I search a flat file for the closest match to a particular numeric value?


code:
import os

def selection():
    strings = []
    strings.append("VEGETABLES FOR THE WEEK:\n")
    for veg in veg_selection:
        strings.append(veg.upper())
    strings.append("\n")
    strings.append("FRUITS FOR THE WEEK:\n")
    for fruit in fruit_selection:
        strings.append(fruit.upper())
    return os.linesep.join(strings)

s = selection()  # s now contains output string, and nothing is printed
print(s)  # print whole string at once

rawDescription: Assigning function print output to string variable


code:
rr,tt = zip(*[(i*10, i*12) for i in xrange(4)])
rr
tt

rawDescription: Possible to return two lists from a list comprehension?


code: dirfiles = [f for f in z.namelist() if f.startswith(pathprefix)]

rawDescription: How to list a folder's files using the zipfile module in Python

description: List a folder's files using the zipfile module in Python


code:
lowest_path_cost = float('Inf')
# pretend that these were calculated using some worthwhile algorithm
path_costs = [1, 100, 2000000000000, 50]
for path in path_costs:
  if path < lowest_path_cost:
    lowest_path_cost = path
lowest_path_cost

rawDescription: What is the point of float('Inf') in Python?


rawDescription: Adding numpy matrices together

description: Adding numpy matrices together


code:
img = gtk.Image()
img.set_from_file(filename)
new = gtk.ImageMenuItem(gtk.STOCK_NEW, 'New')
new.set_image(img)

rawDescription: How can a custom icon be used in an image menu item?


code:
import urllib2
import shutil

urls = []
for i in range(10):
    urls.append(str('https://www.example.org/users/' + i))

def getUrl(urls):
    for url in urls:
        # Only a file_name based on url string
        file_name = url.replace('https://', '').replace('.', '_').replace('/', '_')
        response = urllib2.urlopen(url)
        with open(file_name, 'wb') as out_file:
            shutil.copyfileobj(response, out_file)

getUrl(urls)

rawDescription: How to collect a continuous set of webpages using python?

description: Collect a continuous set of webpages using python


rawDescription: python Loop through a list and look for uniques

description: Python Loop through a list and look for uniques


code:
import pandas as pd

import numpy as np

a = np.array([[1, 1, 1, 1, 1, 0, 1, 0, 0, 2, 1],
              [2, 1, 0, 0, 0, 1, 2, 1, 1, 2, 2]])

df = pd.DataFrame(a, dtype=np.float64)

df.replace(0, method='pad', axis=1)

rawDescription: Is there some elegant way to manipulate my ndarray


code:
import itertools
import csv

d = {"key1": [1, 2, 3], "key2": [4, 5, 6], "key3": [7, 8, 9, 11]}
with open("test.csv", "wb") as outfile:
    writer = csv.writer(outfile)
    writer.writerow(d.keys())
    writer.writerows(itertools.izip_longest(*d.values()))

rawDescription: write a dictionary of different-length lists to a csv file

description: Write a dictionary of different-length lists to a csv file


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

screen = curses.initscr()
curses.noecho()
curses.mousemask(curses.ALL_MOUSE_EVENTS)

screen.keypad(1)

char = ""

try:
    while True:
        char = screen.getch()

        screen.addstr( str(char) + " ")
        if char == curses.KEY_MOUSE:
            screen.addstr (" |" + str(curses.getmouse()) + "| ")

finally:
    screen.keypad(0)
    curses.endwin()

    curses.echo()

rawDescription: A slider for curses based UI

description: A slider for curses based UI


code:
count = 0

def intro(start):
    if start == "yes" or start == "y":
        print("Lets begin.")
    else:
        print("Thanks for checking it out! Bye Bye!")

def question1():

    global count
    count += 1
    return count

def question2():

    global count
    count += 1
    return count

def main():

    print("Hello There! Welcome to an all new Trivial Pursuit!")
    print("You have twenty multiple choice questions and twenty true and false.")
    print ("Each question is one point. Your score will be presented at the end. ")
    print("Would you like to begin? Press y or yes")

    start = input()
    intro(start)

    question1()
    question2()

    print("You got", count, "right!")

main()

rawDescription: I would like to total the amount of correct answers and display it at the end getting error local variable referenced


code: urllib.urlencode(q, doseq=1)

rawDescription: Urlecoding a string back from a dictionary


code:
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor

from imdbyear.items import MovieItem

class IMDBSpider(CrawlSpider):
    name = 'imdb'
    rules = (
        # extract links at the bottom of the page. note that there are 'Prev' and 'Next'
        # links, so a bit of additional filtering is needed
        Rule(LinkExtractor(restrict_xpaths=('//*[@id="right"]/span/a')),
            process_links=lambda links: filter(lambda l: 'Next' in l.text, links),
            callback='parse_page',
            follow=True),
    )

    def __init__(self, start=None, end=None, *args, **kwargs):
      super(IMDBSpider, self).__init__(*args, **kwargs)
      self.start_year = int(start) if start else 1874
      self.end_year = int(end) if end else 2016

    # generate start_urls dynamically
    def start_requests(self):
        for year in range(self.start_year, self.end_year+1):
            yield scrapy.Request('http://www.imdb.com/search/title?year=%d,%d&title_type=feature&sort=moviemeter,asc' % (year, year))

    def parse_page(self, response):
        for sel in response.xpath("//*[@class='results']/tr/td[3]"):
            item = MovieItem()
            item['Title'] = sel.xpath('a/text()').extract()[0]
            # note -- you had 'MianPageUrl' as your scrapy field name. I would recommend fixing this typo
            # (you will need to change it in items.py as well)
            item['MainPageUrl']= "http://imdb.com"+sel.xpath('a/@href').extract()[0]
            request = scrapy.Request(item['MainPageUrl'], callback=self.parseMovieDetails)
            request.meta['item'] = item
            yield request
    # make sure that the dynamically generated start_urls are parsed as well
    parse_start_url = parse_page

    # do your magic
    def parseMovieDetails(self, response):
        pass

rawDescription: IMDB scrapy get all movie data

description: IMDB scrapy get all movie data


code:
import dis
def func():
 for i in iterable:
  for j in [1,2,3]:
   print(i+j)

dis.dis(func)

rawDescription: Is a constant list used in a loop constructed/deleted with each pass?


code:
target_dict = defaultdict(list)
for i, key in enumerate(keys):
    target_dict[k].append(values[i])

rawDescription: How to go from a values_list to a dictionary of lists

description: Go from a values_list to a dictionary of lists


rawDescription: How do I apply unknown arguments to a function in Python 3.x?

description: Apply unknown arguments to a function in Python 3.x


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

# simulate data
# =============================
np.random.seed(1234)
df = pd.DataFrame({'px_last': 100 + np.random.randn(1000).cumsum()}, index=pd.date_range('2010-01-01', periods=1000, freq='B'))
df['50dma'] = pd.rolling_mean(df['px_last'], window=50)
df['200dma'] = pd.rolling_mean(df['px_last'], window=200)
df['label'] = np.where(df['50dma'] > df['200dma'], 1, -1)

# plot
# =============================
df = df.dropna(axis=0, how='any')

fig, ax = plt.subplots()

def plot_func(group):
    global ax
    color = 'r' if (group['label'] < 0).all() else 'g'
    lw = 2.0
    ax.plot(group.index, group.px_last, c=color, linewidth=lw)

df.groupby((df['label'].shift() * df['label'] < 0).cumsum()).apply(plot_func)

# add ma lines
ax.plot(df.index, df['50dma'], 'k--', label='MA-50')
ax.plot(df.index, df['200dma'], 'b--', label='MA-200')
ax.legend(loc='best')

rawDescription: Plot Multicolored line based on conditional in python


code:
from django.utils.html import strip_tags

template_values = {
     'company_id': company.id
}
template_file = os.path.join(os.path.dirname(__file__), 'templates/email.html')
html = template.render(template_file, template_values)

plain_text = strip_tags(html)

rawDescription: How to remove all html tags from django template?

description: Remove all html tags from django template


rawDescription: Getting SciPy quantiles to match Stata xtile function


code:
import itertools

def getString(length=4, characters='abcdefghijklmnopqrstuvwxyz0123456789._-'):
    for s in itertools.product(characters, repeat=length):
        yield ''.join(s)

for s in getString():
    print(s)

aaaa
aaab
aaac
aaad
aaae
aaaf
...

rawDescription: Making string series in Python

description: Making string series in Python


code:
import curses

def check_press(scr):
    c = None
    x = 0
    while c != 120: # exit on x
        c = scr.getch()
        if c == 122: # count on 'z'
            x += 1
            scr.addstr(0, 0, "%5d" % x)
            scr.refresh()

if __name__ == '__main__':
    curses.wrapper(check_press)

rawDescription: How can I build a counter in python?

description: Build a counter in python


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

# Generate some random data.
N=300
a = np.random.random_integers(low=0, high=20, size=N)

# Use bincount and nonzero to generate your data in the correct format.
b = np.bincount(a)
ind = np.nonzero(b)[0]

width=0.8

fig, ax = plt.subplots()

ax.bar(ind-width/2., b)

plt.show()

rawDescription: Creating a barchart from histogram, python matplotlib


code:
def deep(o):
    for k, v in o.iteritems():
        if k.lower() == 'key_i_look_for':
            return v
        if not isinstance(v, list):
            v = [v]
        for i in v:
            if isinstance(i, dict):
                result = deep(i)
                if result is not None:
                    return result

rawDescription: Break in for dictionary loop

description: Break in for dictionary loop


rawDescription: python: how should I write very long lines of code?

description: Python: how should I write very long lines of code


code:
total = 0
count = 0

with open("data.csv") as source:
    rdr = csv.reader(source, delimiter=',')
    next(rdr, None) #skip the header
    for row in rdr:
        try:
            if isinstance(float(row[4]),float):
                total+= float(row[4])
                count += 1
        except ValueError:
            pass

ave = round(total / count,2)
print(ave)

rawDescription: How to extract only the a specific column of a CSV file in python

description: Extract only the a specific column of a CSV file in python


code:
def page_query(query_string):

  transaction_id = create_query_transaction(0, BLINKS_PAGE_SIZE, query_string)
  return transaction_id

def next_page(transaction_id):

    transaction = BlinkQueryTransaction.query.get(transaction_id)

    query = eval(transaction.sql)
    query = query.slice(transaction.latest_offset, transaction.page_size)

    transaction.latest_offset = transaction.latest_offset + transaction.page_size
    db.session.commit()

    return query

def create_query_transaction(latest_offset, page_size, query):

    bqt = BlinkQueryTransaction(latest_offset=latest_offset, page_size=page_size, sql=query)
    bqt = save_to_db(bqt)

    return bqt.id

rawDescription: Saving and restoring queries in flask-SQLAlchemy


code:
import logging

logging.debug('Debug Message')

if some_error:
   logging.error('Error Message')

rawDescription: How do I use Logging in the Django Debug Toolbar?

description: Use Logging in the Django Debug Toolbar


code: subprocess.check_call("/home/R/daemon_excel.py arg1 arg3 arg2 &", shell=True)

rawDescription: Python-Linux: run script in background from script


code:
for row_index in range(0, old_sheet.nrows):
    column_con = old_sheet.cell(row_index, 0).value

    # First split into a list and convert to sequence
    column_con = tuple(column_con.split(', '))

    aaa = dict.fromkeys(column_con).keys()

    # Since aaa is a list of keys, you also need to join them in a string
    aaa = ', '.join(aaa)
    new_sheet.write(row_index, 0, aaa)

rawDescription: Using Python to remove duplicated contents in cells in Excel


code:
import matplotlib.pylab as plt
from numpy.random import rand

data = rand(100,100)
mycm = plt.cm.Reds

fig = plt.figure()
ax4 = plt.subplot2grid((3, 4), (1, 3), colspan=1, rowspan=1)

heatmap = ax4.pcolor(data, cmap=mycm, edgecolors = 'none', picker=True)

box = ax4.get_position()
ax4.set_position([box.x0*1.05, box.y0, box.width, box.height])

# create color bar
axColor = plt.axes([box.x0*1.05 + box.width * 1.05, box.y0, 0.01, box.height])
plt.colorbar(heatmap, cax = axColor, orientation="vertical")
plt.show()

rawDescription: Python matplotlib - how to move colorbar without resizing the heatmap?


code:
from proj.tasks import add
res = add.chunks(zip(range(100), range(100)), 10)()
res.get()

rawDescription: RabbitMQ: What Does Celery Offer That Pika Doesn't?


code:
import sys
sys.path.append("/home/me/myproj/gitmodules")
import mygitsubmodule

rawDescription: How to import python file from git submodule

description: Import python file from git submodule


code:
import types
a = types.SimpleNamespace()
a.attr1 = 123
a.attr2 = '123'
a.attr3 = [1,2,3]
a.attr1
a.attr2
a.attr3

rawDescription: Can you add attributes to an object dynamically?

description: Add attributes to an object dynamically


code: return '\n'.join([' '.join([str(x),str(y)]) for x,y in sorted_dict])

rawDescription: I need to sort a dictionary by order of value and RETURN it


code:
ks = set(random.sample(d, 2))
dict((k, list(ks & set(d[k]))) for k in ks)

rawDescription: pythonic way to filter a dictionary of arrays

description: Pythonic way to filter a dictionary of arrays


code:
# http://www.cs.utexas.edu/users/EWD/ewd07xx/EWD792.PDF

n = 15
bases = [2, 3, 5]

nums = [1] * n
candidates_indexes = [0 for _ in bases]
candidates = [base for base in bases]

for i in range(1, n):
    nextn = min(candidates)
    nums[i] = nextn

    for index, val in enumerate(candidates):
        if val == nextn:
            candidates_indexes[index] += 1
            candidates[index] = bases[index] * nums[candidates_indexes[index]]

print(nums)

rawDescription: how to generate numbers given their prime factors, but with unknow exponents?

description: Generate numbers given their prime factors, but with unknow exponents


code:
fileA = open("file1.txt",'r')
fileB = open("file2.txt",'r')
output = open("results.txt",'w')

dictA = dict()
for line1 in fileA:
    listA = line1.split('\t')
    dictA[listA[1]] = listA

dictB = dict()
for line1 in fileB:
    listB = line1.split('\t')
    dictB[listB[1]] = listB

for key in set(dictA).intersection(dictB):
    output.write(dictA[key][1] + '\t' + dictA[key][2] + '\t' + dictA[key][3] + '\t' + dictA[key][4] + '\n')

rawDescription: Finding common IDs in different .txt files and appending additional corrisponding lines


rawDescription: Pandas Fill NaN with Column Values

description: Pandas Fill NaN with Column Values


code:
from tkinter import *

x = 10
y = 10
a = 100
b = 100

def change_coord(event):
    global coord
    if event.keysym == 'Up':
        coord[1] -=1
        coord[3] -=1
    if event.keysym == 'Down':
        coord[1] +=1
        coord[3] +=1
    if event.keysym == 'Right':
        coord[0] +=1
        coord[2] +=1
    if event.keysym == 'Left':
        coord[0] -=1
        coord[2] -=1
    canvas1.coords(arc, *coord)

window = Tk()
window.geometry("500x500")

canvas1=Canvas(window, height = 400, width = 400)
canvas1.grid(row=0, column=0, sticky=W)
coord = [x, y, a, b]
arc = canvas1.create_arc(*coord, start=0, extent=150, fill="blue")

window.bind_all('<Up>', change_coord)
window.bind_all('<Down>', change_coord)
window.bind_all('<Left>', change_coord)
window.bind_all('<Right>', change_coord)
window.mainloop()

rawDescription: How can I return a value into the main program when calling a function with a keyboard event in TKinter?

description: Return a value into the main program when calling a function with a keyboard event in TKinter


code:
# y is here the class target with color values, e.g. ['r', 'g',..., 'r']
plt.scatter(X_reduced[:,0], X_reduced[:,1], c=y, picker=True)

rawDescription: Problems relating additional Information to Scatterplot points


code: myrandom = random.Random(myseed)

rawDescription: Set random seed temporarily, like "new Random()"


code:
from Tkinter import *
import time

class App():
    def __init__(self):
        self.window = Tk()
        self.root = Frame(self.window, height=200,width=200)
        self.root.pack()
        self.root.pack_propagate(0)
        self.window.title('Timer')
        self.label = Label(text="")
        self.label.pack()
        self.sec = 11
        self.timerupdate()
        self.root.mainloop()
    def timerupdate(self):
        if self.sec!=0:
            self.sec-=1
            self.label.configure(text=self.sec)
            self.root.after(1000, self.timerupdate)
        if self.sec == 0:
          self.sec = 11

app=App()
app.mainloop()

rawDescription: How to reset the timer using tkinter

description: Reset the timer using tkinter


code:
import HTMLParser
encoded_text = 'subi.bhaskaran@in.ibm.com'
decoded_text = HTMLParser.HTMLParser().unescape(encoded_text)

rawDescription: Decoding encoded email id in python

description: Decoding encoded email id in python


code:
cols = pd.Series(df.columns.tolist()).apply(pd.Series).sum(axis=1)
cols

rawDescription: collapse a pandas MultiIndex

description: Collapse a pandas MultiIndex


code:
from collections import namedtuple

Result = namedtuple('Result', 'foo bar spam ham eggs')

def sort_of_long_function_name(arg1, arg2, arg3, arg4):
    return Result(foo_result, bar_result, spam_result, ham_result, eggs_result)

result = sort_of_long_function_name(param1, param2, param3, param4, param5)
do_something_with(result.foo)
do_something_else_with(result.bar)
# etc.

rawDescription: What is the correct way to format long lines of code in python?


code:
while lft and rgt:  #NEITHER HALF IS EMPTY
    if lft[-1] >=rgt[-1]:   #lft HAS GREATEST LAST VALUE
        # if the last of lft is greater than the last of rgt (which is sorted),
        # then it is also greater than everything before the last element of rgt,
        # so it generates as many inversions as the remaining elements in rgt
        inversions += len(rgt)
        res.append(lft.pop())   #APPEND IT
    else:   #rgt HAS GREATEST LAST VALUE
        res.append(rgt.pop())   #APPEND IT

rawDescription: Python mergesort: counting inversions without multiple function calls


code:
def function(number):
    global accumulator
    accumulator = number

rawDescription: Defined function in python gets rid of variable after finish


code:
with open('text.txt', 'w') as out:
   for key, value in sorted(dict1.items()):
       print(key,':',value, file=out)

rawDescription: Python - When Outputting Dictionary to External Text File Only First Key Is Being Outputted


code:
start_list = []
end_list = []
started = False

with open(filename) as myFile:
    for num, line in enumerate(myFile, 1):
        if not started and start_needle in line:
            start_list.append(num)
            started = True
        if started and line.endswith(end_needle):
            end_list.append(num)
            started = False

rawDescription: find next immediate line with string (after finding a first string)

description: Find next immediate line with string (after finding a first string)


code:
Mat1 = np.matrix(np.random.rand(3,3))
Mat1
Mat2 = np.diag(np.negative(np.squeeze(np.asarray(np.sum(Mat1,axis=1)))))
Mat2
np.diag(-Mat1.A.sum(1))

rawDescription: python negative sum of rows on matrix diagonal efficiently

description: Python negative sum of rows on matrix diagonal efficiently


code:
pnt = Point(5, 23)
[coord for coord in pnt]
pnt.coords

rawDescription: How to find lat long values from the POINT

description: Find lat long values from the POINT


code:
def explode(sep,x):
    if isinstance(x,(str,unicode)): return x.split(sep)
    elif isinstance(x,list): return [explode(sep,each) for each in x]
    elif isinstance(x,dict):return {key:explode(sep,x[key]) for key in x}
    else: raise ValueError("function doesn't support",type(x))

l = [["hello,world"],["i need help, python"]]
l = explode(",",l)

rawDescription: split a string with commas inside of a list python

description: Split a string with commas inside of a list python


code:
from django.core.urlresolvers import reverse

from rest_framework.test import APITestCase, APIClient

class TestReadings(APITestCase):

    def setUp(self):
        self.client = APIClient()

    def test_put(self):

        url = reverse('readings', kwargs={}) # 'readings' here is the named url
        request = self.client.post(url, data={})

rawDescription: PUT request made with Python requests module has no data


rawDescription: Splliting the string data in pandas dataframe


code:
import os
clear = lambda: os.system('cls')
clear()

rawDescription: How to clear python interpreter console?

description: Clear python interpreter console


code:
import matplotlib.pyplot as plt
from numpy.random import random
from numpy import var

H = random(size=(120,80))
Hvar = var(H, axis=1)
fig, axs = plt.subplots(figsize=(3,3), ncols=2, sharey=True, sharex=False)
plt.sca(axs[0])
plt.imshow(H) #heatmap into current axis
axs[0].set_ylim(0,120)
axs[1].scatter(Hvar, range(len(Hvar)))
plt.show()

rawDescription: Matplotlib: How does one plot a 1D array of x values with y-axis corresponding to a heatmap?


rawDescription: Tracing back foreign-keys

description: Tracing back foreign-keys


rawDescription: Dictionary with 2 keys and 1 value to pandas Dataframe


code:
class TestForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super(TestForm, self).__init__(auto_id=True, *args, **kwargs)

rawDescription: django: Changing auto_id of ModelForm based form class

description: Django: Changing auto_id of ModelForm based form class


code:
countMap = {}
for v in a.itervalues():
    countMap[v] = countMap.get(v,0) + 1
uni = [ k for k, v in a.iteritems() if countMap[v] == 1]

rawDescription: Python: finding keys with unique values in a dictionary?


code:
fragment = """<head><meta http-equiv="refresh" content="5;url=http://google.com"/></head>"""
soup = BeautifulSoup(fragment)
element = soup.find('meta', attrs={'http-equiv': 'refresh'})
element
refresh_content = element['content']
refresh_content
url = refresh_content.partition('=')[2]
url

rawDescription: How to use beautifulsoup to get redirect html?

description: Use beautifulsoup to get redirect html


code:
...
from Crypto.Cipher import PKCS1_v1_5
private_rsa_key = open('rsa_1024_priv.pem', 'r').read()
rsa_key = RSA.importKey(private_rsa_key)
cipher = PKCS1_v1_5.new(rsa_key)
decrypted = cipher.decrypt(encrypted, "ERROR")

rawDescription: JSEncrypt to PyCrypto RSA encryption not possible


code:
d = clf.decision_function(x)[0]
probs = np.exp(d) / np.sum(np.exp(d))

rawDescription: Scikit-learn Ridge classifier: extracting class probabilities


code:
import hashlib
...
@application.route("/rupload/<filename>", methods=['POST', 'PUT'])
def rupload(filename):
    # Sanity checks and setup skipped.

    filename = secure_filename(filename)
    fileFullPath = os.path.join(UPLOAD_FOLDER, filename)
    file_hash = hashlib.sha256()
    with open(fileFullPath, 'wb+') as f:
        input = request.get_data()
        f.write(input)
        file_hash.update(input)
        ...
    fileDigest = file_hash.hexdigest()

rawDescription: ReSTfully upload file in Flask without multipart/form-data


code:
def solve_sparse(A, b):
  num_iters = 0

  def callback(xk):
    num_iters += 1

  # call the solver on your data
  return scipy.sparse.linalg.cg(A, b, callback=callback)[0]

rawDescription: Retrieving number of iterations that ran for sparse linear solver in SciPy


code:
class Listbox(tk.Listbox):
    def autowidth(self,maxwidth):
        f = font.Font(font=self.cget("font"))
        pixels = 0
        for item in self.get(0, "end"):
            pixels = max(pixels, f.measure(item))
        # bump listbox size until all entries fit
        pixels = pixels + 10
        width = int(self.cget("width"))
        for w in range(0, maxwidth+1, 5):
            if self.winfo_reqwidth() >= pixels:
                break
            self.config(width=width+w)

master = tk.Tk()
listbox = Listbox(master, selectmode=tk.SINGLE)

keys = serverDict.keys()
for key in sorted(keys):
    listbox.insert(tk.END, key)

button = tk.Button(master, text="Execute", command=execute)
listbox.autowidth(250)
listbox.pack()
button.pack()
tk.mainloop()

rawDescription: How to fit Tkinter listbox to contents

description: Fit Tkinter listbox to contents


code:
from django.shortcuts import render
from django.http import HttpResponse
from TasksManager.models import Supervisor, Developer
# View for create_developer
def page(request):
    error = False
    # If form has posted
    if request.POST:
        if 'name' in request.POST:
            name = request.POST.get('name', '')
        else:
            error=True
        if 'login' in request.POST:
            login = request.POST.get('login', '')
        else:
            error=True
        if 'password' in request.POST:
            password = request.POST.get('password', '')
        else:
            error=True
        if 'supervisor' in request.POST:
            supervisor_id = request.POST.get('supervisor', '')
        else:
            error=True
        if not error:
            supervisor = Supervisor.objects.get(id = supervisor_id)
            new_dev = Developer(name=name, login=login, password=password,supervisor=supervisor)
            new_dev.save()
            return HttpResponse("Developer added")
        else:
            return HttpResponse("An error as occured")
    else:
        supervisors_list =  Supervisor.objects.all()
        return render(request, 'en/public/create_developer.html', {'supervisors_list' : supervisors_list})

rawDescription: objects.all() query not working

description: Objects.all() query not working


rawDescription: Pandas divide one row by another and output to another row in the same dataframe


rawDescription: Sending and receiving bytes from a microcontroller


rawDescription: Evaluate environment variables into a string


code:
relx, rely = ev.pos[x] - mx, ev.pos[y] - my
number = rely//boxsize*numboxsx + relx//boxsize

rawDescription: How to calculate the number of box according to their position?

description: Calculate the number of box according to their position


code:
basename = os.path.basename(file)
if ext in (".txt", ".htm", ".html"):
    ftp.storlines("STOR " + basename, open(file))
else:
    ftp.storbinary("STOR " + basename, open(file, "rb"), 1024)

rawDescription: Trying to upload with ftplib, can connect just fine, but I'm messing something up at some point.


rawDescription: Django Annotate Conditional

description: Django Annotate Conditional


code:
def set_hash(entity, name, value):
  if value:
    setattr(entity, name, hashlib.sha512(value + salt).hexdigest())

set_hash(person, "last_name", last_name)
set_hash(person, "first_name", first_name)

rawDescription: How to access GAE datastore property with variable usage instead of actual name?

description: Access GAE datastore property with variable usage instead of actual name


rawDescription: Combine multiple Booleans and Check if any are true in python


code:
tree = etree.parse("./test.xml")
num_elems = tree.xpath("count(//Product)")    # note: returns a float

rawDescription: Efficiently counting elements in a very large XML doc using lxml


rawDescription: Typecasting before division (or any other mathematical operator) of columns in dataframes


code:
import gevent
from gevent.pywsgi import WSGIServer
from gevent.lock import Semaphore
from geventwebsocket.handler import WebSocketHandler
from datetime import datetime

def process(ws,data,sem):
    print('{} got data "{}"'.format(datetime.now().strftime('%H:%M:%S'), data))
    gevent.sleep(5)
    with sem:
        ws.send(data)

def app(environ, start_response):
    ws = environ['wsgi.websocket']
    sem = Semaphore()
    while True:
        data = ws.receive()
        gevent.spawn(process,ws,data,sem)

server = WSGIServer(("", 10004), app,handler_class=WebSocketHandler)
server.serve_forever()

rawDescription: why is gevent-websocket synchronous?

description: Why is gevent-websocket synchronous


code:
import numpy as np
from collections import Counter
a = np.array([1, 2, 1, 3, 3, 3, 0])
[item for item, count in Counter(a).iteritems() if count > 1]

rawDescription: Determining duplicate values in an array


code: category_map = {c.name: c for c in Category.objects.all()}

rawDescription: Django Model Into Dictionary Comprehension


code:
import cv2
import numpy as np

c = cv2.VideoCapture('test.avi')
_,f = c.read()

avg1 = np.float32(f)
avg2 = np.float32(f)

# loop over images and estimate background
for x in range(0,4):
    _,f = c.read()

    cv2.accumulateWeighted(f,avg1,1)
    cv2.accumulateWeighted(f,avg2,0.01)

    res1 = cv2.convertScaleAbs(avg1)
    res2 = cv2.convertScaleAbs(avg2)

    cv2.imshow('img',f)
    cv2.imshow('avg1',res1)
    cv2.imshow('avg2',res2)
    k = cv2.waitKey(0) & 0xff
    if k == 5:
        break

rawDescription: Python opencv background subtraction

description: Python opencv background subtraction


code:
from django.db.models import Manager
is_many_to_many = isinstance(qty.name, Manager)

rawDescription: Django: how to get model field is ManyToManyField or not


code:
class Pet(db.Model):
    name = db.StringProperty(required=True, default="(unnamed)")

rawDescription: Default Values for Models in Google App Engine


code:
def make_testcase(filename, myfunc, docstring):
    def test_something(self):
        data = loadmat(filename)
        result = myfunc(data)
        self.assertTrue(result > 0)

    clsdict = {'test_something': test_something,
               '__doc__': docstring}
    return type('ATest', (unittest.TestCase,), clsdict)

MyTest = makeTestCase('some_filename', my_func, 'This is a docstring')

rawDescription: How do I programmatically set the docstring?

description: Programmatically set the docstring


code:
def A(S,K):
    result = 0
    if S <= K:
        result = K
    elif K < S < 2*K:
        result = 2*K-S
    return result

rawDescription: Basic Python Functions (Mathematics involved)


code:
import shutil
shutil.copy('fruitsoriginal.txt', 'fruits.txt')

rawDescription: Copy .txt file onto a separate .txt file - python


code:
import os.path as op

op.abspath(op.join(__file__, op.pardir, op.pardir, op.pardir))

rawDescription: Python idiom to get same result as calling os.path.dirname multiple times?


code:
doc = QtGui.QTextDocument()
doc.setHtml(label.text())
text = doc.toPlainText()

rawDescription: Get Plain text from a QLabel with Rich text


code:
CSV = 'UC013. MANTER ITEM DE NOTA FISCAL / NOTA DE SERVI\xc3\x87O / RECIBO'
DOC = 'UC013. MANTER ITEM DE NOTA FISCAL / NOTA DE SERVI\xc7O / RECIBO'
CSV = CSV.decode('utf-8')
DOC = DOC.decode('latin1')
print(CSV == DOC)    # True

rawDescription: Python \xYZ characters in console

description: Python \xYZ characters in console


code:
import mad

mf = mad.MadFile("foo.mp3")
track_length_in_milliseconds = mf.total_time()

rawDescription: time length of an mp3 file

description: Time length of an mp3 file


code:
f = file('output.txt','w')
g = file('err.txt','w')

p = subprocess.Popen(cmd, shell=True, stdout=f, stderr=g)

f.close()
g.close()

rawDescription: How to get the stdout and stderr for subprocess.call?

description: Get the stdout and stderr for subprocess.call


code:
with open('list.txt') as f:
    lines = f.readlines()
line_list = lines[-3:]

rawDescription: Python how to read last three lines of a .txt file, and put those items into a list?


code:
def runbg(cmd, sockname="dtach"):
    return run('dtach -n `mktemp -u /tmp/%s.XXXX` %s'  % (sockname,cmd))

rawDescription: start a background process with nohup using fabric

description: Start a background process with nohup using fabric