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

N=1000
x = np.linspace(-.5,1.5,num=N)
xshift = x-0.5
Bz = 30*np.exp(-xshift**8/0.00125)*np.sin(xshift*2.*np.pi)
Np = 30*np.exp(-xshift**10/0.00125)+5
Vx = 200*np.exp(-xshift**10/0.00125)+400

fig = plt.figure()

#list of tuples of the form `(data, label)`
data_list = [(Bz,"B_z"),(Vx,"V_x"),(Np,"N_p")]

left = .15
height = .2
width = .7
bottom = .0
axes_ticks = []
axes = []
for i,(data,lab) in enumerate(data_list,1):
    ax = fig.add_subplot(len(data_list),1,i)
    bottom += height
    ax.set_position((left, bottom, width, height))

    ax.set_ylabel("$\mathrm{%s}$"%lab)
    axes_ticks.append(ax.get_xaxis().get_ticklocs())
    ax.get_xaxis().set_ticks([])
    ax.plot(x,data)
    axes.append(ax)
else:
    #Reset default tick labels here on ax
    axes[0].get_xaxis().set_ticks(axes_ticks[0])

plt.show()

rawDescription: Reset default axis tics on matplotlib subplot


code:
data = '''\
1000S 00RR: 20 values
1200S -10RR: 10 values
900S -20RR: 6 values
150S -05RR: 4 values
10000S 00RR: 2 values
'''.splitlines(keepends=True)

def keyfunc(line):
    return int(line[:line.index('S')])
test_int = keyfunc("1000S 00RR: 20 values")  # for testing only
print(type(test_int), test_int)
# <class 'int'> 1000

out = sorted(data, key=keyfunc)
for line in out: print(line, end='')

rawDescription: Sorting content of a text file in python 3.x


code:
def register(self, cls):
    if not hasattr(cls, 'name'):
        logger.warning('Cannot register VCS %s', cls.__name__)
        return
    if cls.name not in self._registry:
        self._registry[cls.name] = cls
        logger.debug('Registered VCS backend: %s', cls.name)

rawDescription: How to remove lines [DEBUG] pip.vcs: Registered VCS backend: *** from log file

description: Remove lines [DEBUG] pip.vcs: Registered VCS backend: *** from log file


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

# =================== deltaV-vs-trust

times = np.array([1.0,  60.0, 3600.0, 86400.0, 604800,  2592000, 31556926, 315569260,  3155692600])
timeText = ['sec','min','hour', 'day',   'week',  'month', 'year',   '10years',  '100years']

dists= np.array([1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 6371e+3, 42164e+3,
                384400e+3, 1e+9, 1e+10, 5.790918E+010, 1.082089E+011, 1.495979E+011,
                2.279366E+011, 7.784120E+011, 1.426725E+012, 2.870972E+012,
                4.498253E+012, 1.40621998e+13, 2.99195741e+14, 7.47989354e+15,
                4.13425091e+16])

distText = ['10m','100m', '1km','10km', '100km', '1000km', 'LEO',
            'GEO', 'Moon', r'10$^6$km',r'10$^7$km', 'Mercury', 'Venus', 'Earth',
            'Mars', 'Jupiter', 'Satrun', 'Uranus', 'Neptune', 'Heliopause',
            'Oorth', 'Outer Oorth', 'Alpha Centauri']

vMin, vMax = 1e+0, 1e+8
aMin, aMax = 1e-4, 1e+2

As = np.linspace(aMin, aMax, 2)

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

for dist, text in zip(dists, distText):
    # compute the line
    v = np.sqrt(2*dist * As)
    ax.plot(v, As, 'b-', alpha=0.5)

    # sort out where the label should be
    txt_y = aMin
    txt_x = v[0]
    # clip to the edges
    if (txt_x < vMin):
        txt_x = vMin
        txt_y = vMin**2 / (2*dist)

    ax.text(txt_x, txt_y, text,
            rotation=60, color='b', rotation_mode='anchor',
            horizontalalignment='left',
            verticalalignment='bottom')

for time, txt in zip(times, timeText):
    # compute the line
    x = As * time
    ax.plot(x, As, 'r-', alpha=0.5)

    # sort out where the label should be
    txt_x = x[-1]
    txt_y = aMax
    # clip to the edges
    if(txt_x > vMax):
        txt_x = vMax
        txt_y = vMax / time

    ax.text(txt_x, txt_y, txt,
            rotation=40, color='r',
            horizontalalignment='right', rotation_mode='anchor',
            verticalalignment='baseline')

ax.set_ylabel(r"acceleration [m/s$^2$]")
ax.set_xlabel(r"delta-v [m/s]")
ax.set_yscale('log')
ax.set_xscale('log')
ax.grid()
ax.set_ylim(aMin, aMax)
ax.set_xlim(vMin, vMax)

rawDescription: Matplotlib tilted text on log scale?

description: Matplotlib tilted text on log scale


code:
N_SUBBITS = 4
N_SUBLISTS = 3
([0] + [1]*(N_SUBBITS-1)) * N_SUBLISTS

rawDescription: Compact generation of a single list with multiple list multiplication operators


code:
def callback(event=None):
    ...

rawDescription: Bind method in Tkinter passes an argument when it shouldn't


code:
alphabetL = 'abcdefghijklmnopqrstuvwxyz'
alphabetC = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
number = '0123456789'
space = ' '
Ll = len(alphabetL)
Lc = len(alphabetC)
Ln = len(number)
Lall = Ll + Lc + Ln
msgall = alphabetL + alphabetC + number + space
Question1 = input("Hello, please insert the message you want encrypted: ")
key1 = int(input("Please insert the key you want used [Keep between 1 and 26]: "))

cipher2 = ''

def ceaser_cipher(Question1,key1):
    cipher = ''
    for A in Question1:
        if A in alphabetL:
            cipher += alphabetL[(alphabetL.index(A)+key1)%Ll]
        elif A in alphabetC:
            cipher += alphabetC[(alphabetC.index(A)+key1)%Lc]
        elif A in number:
            cipher += number[(number.index(A)+key1)%Ln]
        elif A in space:
            cipher += space
        else:
            print ("Error, please use abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")

    return cipher

cipher=ceaser_cipher(Question1,key1)
print (cipher)
Question2 = input("Would you like to decrypt the message? [Y/N]: ")
if Question2 == "Y":
    cipher2=ceaser_cipher(cipher,-key1)
    print (cipher2)

rawDescription: Decryption not working in Caesar cipher in Python


code: client.get("/get-user-settings/param1=%i&param2=%j" % (i, j), name="Get User Settings")

rawDescription: Isit possible to union the similar GET requests in WEB output data in locust.io?


code:
import pkgutil
plugin_names = [
    name for (loader, name, ispkg) in pkgutil.iter_modules()
    if name.startswith('mypackage-')]

rawDescription: Packages as plugins in Python

description: Packages as plugins in Python


code:
class UserForm(forms.ModelForm):
    class Meta:
        model = User

class UserProfileForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        # magic
        self.user = kwargs['instance'].user
        user_kwargs = kwargs.copy()
        user_kwargs['instance'] = self.user
        self.user_form = UserForm(*args, **user_kwargs)
        # magic end

        super(UserProfileForm, self).__init__(*args, **kwargs)

        self.fields.update(self.user_form.fields)
        self.initial.update(self.user_form.initial)

    def save(self, *args, **kwargs):
        self.user_form.save(*args, **kwargs)
        return super(ProfileForm, self).save(*args, **kwargs)

    class Meta:
        model = UserProfile

rawDescription: Save user form and profile in one Django CBV


code:
def f(map,n=0):
        dictionary=beforeF(map) #function before i made
        for key in dictionary.keys():
            fullName = map + '\\' + key
            if path.isdir(fullName):
                print(n*'\t'+key+':')

                f(fullName, n+1)
            else:
                print(n*'\t'+key + ' (' + str(dictionary[key])+ ')')

rawDescription: How to dict folders?

description: Dict folders


code:
connection = engine.connect()
result = connection.execute("""SELECT DISTINCT Distributor FROM Product""")
result_list = result.fetchall()
result_list[0][0]
connection.close()

rawDescription: Python: Print only one value of an SQL query result set


rawDescription: Bitshift Encrypt and Decrypt with Circular shift in Python


code:
def write_to_txt(header,data):
    with open('test.txt','a+') as f:
        f.write("|{}|\n".format('|'.join(str(field)
                          for field in header))) # write header
        f.write("|{}|\n".format('|'.join(str(field)
                          for field in data)))

rawDescription: How to output vertical bar format in textfile

description: Output vertical bar format in textfile


code:
import subprocess

try:
    child = subprocess.Popen(blah)
    child.wait()

except KeyboardInterrupt:
    child.terminate()

rawDescription: kill subprocess when python process is killed?

description: Kill subprocess when python process is killed


code:
from django.contrib import admin

class MovieGenreInline(admin.TabularInline):
    model = MovieGenre

class MovieAdmin(admin.ModelAdmin):
    inlines = [
        MovieGenreInline,
    ]

rawDescription: Admin site add 2 related models at the same time


code:
def bench_lxml_xpath_direct(root): # Very slow but very fast if text() is removed.
  name_list = root.xpath("book/author/name/text()")
  print ("Size of list = " + str(len(name_list)))

def bench_lxml_xpath_loop(root): # Fast
  name_list = root.xpath("book/author/name")
  result = []
  for n in name_list:
    result.append(n.text)

  print ("Size of list = " + str(len(name_list)))

def bench_lxml_getiterator(tree): # Very fast
  result = []
  for name in tree.getiterator("name"):
    result.append(name.text)
  print ("Size of list = " + str(len(result)))

def bench_lxml_findall(tree):  # Superfast
  result = []
  for name in tree.findall("//name"):
    result.append(name.text)
  print ("Size of list = " + str(len(result)))

rawDescription: Fast python XML validator with XPath support


code:
import os
from subprocess import Popen, PIPE
import time

PIPE_PATH = "/tmp/my_pipe"

if not os.path.exists(PIPE_PATH):
    os.mkfifo(PIPE_PATH)

Popen(['xterm', '-e', 'tail', '-f', PIPE_PATH])

for _ in range(5):
    with open(PIPE_PATH, "w") as p:
        p.write("Hello world!\n")
        time.sleep(1)

rawDescription: Using Python's Subprocess to Display Output in New Xterm Window


code: self.assertEqual(a == b, condition)

rawDescription: assertEqual or assertNotEqual depending on condition

description: AssertEqual or assertNotEqual depending on condition


code:
m = 10**4; c = 4
f=lambda n,m,c:( 2**(n - 2)*n*(n - 1)*binomial(m, n)*factorial(m - S(3)/2)*
factorial(m - n)/(binomial(2*m, n)*factorial(m - n/2)*factorial(m - n/2
- S(1)/2))-c)
mpmath.findroot(lambda x:f(x, m, c),(300,450),solver='bisect')

rawDescription: Sympy can graph the function but cannot find the obvious root


code:
def home(request):
    if request.method == 'POST':
        data = request.POST['variable']

rawDescription: get data from HTML without using django form template

description: Get data from HTML without using django form template


code: result = y if x else z

rawDescription: One line Boolean check in Python

description: One line Boolean check in Python


code: 'iterator' if obj is iter(obj) else 'iterable'

rawDescription: How to tell the difference between an iterator and an iterable?

description: Tell the difference between an iterator and an iterable


rawDescription: Pandas dataframe - identify rows with value over threshold in any column


code:
with open("Scores.txt","r") as f:
    lists = [line.rstrip().split() for line in f.readlines()]
    lists.sort()
    print(lists)

# Output
[['Amber', '0'], ['Blue', '2'], ['Cyan', '1']]

rawDescription: Python Sorting a list with 2 pieces of data alphabetically


code:
for cluster in A:
    if cluster not in B:
        return False
return True

rawDescription: Pythonic way to check if two list of list of arrays are equal


code:
import sys, random
from PyQt5 import QtGui, QtCore, QtWidgets

class ViewDelegate(QtWidgets.QStyledItemDelegate):
    def __init__(self):
        QtWidgets.QStyledItemDelegate.__init__(self)
        self.padding = 2
        self.AlignmentFlag =  QtCore.Qt.AlignRight

    def paint(self, painter, option, index):
        x = option.rect.x()
        y = option.rect.y()
        width = option.rect.width()
        height = option.rect.height()
        iconList = index.data(256)                      # get the icons associated with the item
        text = index.data()                             # get the items text

        for a, i in enumerate(iconList):
            m = max([i.width(), i.height()])
            f = (height- 2*self.padding)/m                  # scalingfactor
            i = i.scaled(int(i.width()*f),int(i.height()*f))                    # scale all pixmaps to the same size depending on lineheight
            painter.drawPixmap(QtCore.QPoint(x,y+self.padding),i)
            x += height

        painter.drawText(QtCore.QRect(x + self.padding,y + self.padding, width - x - 2*self.padding, height - 2*self.padding),self.AlignmentFlag, text)

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.setGeometry(200,100,200,220)
        self.icons = []
        for i in ('arrow_double.svg', 'asc.png', 'desc.png', 'checked.png'):
            icon = QtGui.QPixmap(i)
            self.icons.append(icon)

        self.listWidget = QtWidgets.QListView(self)
        self.delegate = ViewDelegate()
        self.listWidget.setGeometry(20,20,160,180)
        self.listWidget.setItemDelegate(self.delegate)
        self.model = QtGui.QStandardItemModel(self.listWidget)

        itemsTexts = ['abcde','fghij','klmno','pqrst','uvwxy','zABCD']

        for r, i in enumerate(itemsTexts):
            item = QtGui.QStandardItem(i)
            self.model.setItem(r,0, item)
            self.model.setData(self.model.index(r,0), self.iconList(), 256) # save the items icons in userRole

        self.listWidget.setModel(self.model)

    def iconList(self):                             # creates a random iconList
        r = random.randint(1,len(self.icons))                   # Anzahl icons in the list
        iconList = []
        for i in range(0,r):
            n = random.randint(0,len(self.icons)-1)
            icon = self.icons[n]
            iconList.append(icon)
        return iconList

app = QtWidgets.QApplication(sys.argv)
widget = MyWidget()
widget.show()
sys.exit(app.exec_())

rawDescription: Complicated model item in PyQt

description: Complicated model item in PyQt


code:
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings

process = CrawlerProcess(get_project_settings())

process.crawl('testspider1', domain='domain1.com')
process.crawl('testspider2', domain='domain2.com')
process.crawl('testspider3', domain='domain3.com')
process.start()

rawDescription: Automate crawling of mutiple spiders in same scrapy project with cron or some other scheduler


code:
pieces = []
item = self.tree.GetSelection()

while self.tree.GetItemParent(item):
  piece = self.tree.GetItemText(item)
  pieces.insert(0, piece)
  item = self.tree.GetItemParent(item)

rawDescription: Get Path to Item on a TreeCtrl

description: Get Path to Item on a TreeCtrl


code:
from sympy import poly
p = poly('15*x-22*x**3+14*x**40')
p.terms()

rawDescription: How to read the power of a polynomial term?

description: Read the power of a polynomial term


rawDescription: Python - Tables within tables

description: Python - Tables within tables


code:
import subprocess

...

# Call make to clean
if env.GetOption('clean'):
    subprocess.call(['make', 'clean'])

rawDescription: Performing custom actions on `scons -c`

description: Performing custom actions on `scons -c`


rawDescription: Python "here, . . . where" construction

description: Python "here, . . . where" construction


code:
if laser.y == past_edge_of_window:
    self.game.itemlist.remove(laser)
    self.label.destroy()

rawDescription: Clearing Python Objects with no References from Memory


code:
from django.db.models import Count
User.objects.filter(device__is_enabled=1).annotate(
    device_count=Count('device')).filter(device_count=2)

User.objects.exclude(device__is_enabled=0)

rawDescription: Django aggregate function problem (Count = -number-)


code:
from django.forms import forms
forms.__file__

rawDescription: Django: Checking source code of automatically generated functions


code:
import csv
# assuming file is named 'csvfile.csv' in the current directory
with open('csvfile.csv', newline='') as csvfile:
    # read the csv file and specify the delimiter
    csvreader = csv.reader(csvfile, delimiter="|")
    #skip the header row
    next(csvreader)
    # for every data row in the file, add 5 to the number in the
    # first column and print the result
    for row in csvreader:
        value_of_a = row[0]
        print(float(value_of_a) + 5)

rawDescription: How I can read variables from csv in python


code: data.groupby(level=[0, 1]).sum()

rawDescription: Summing over a multiindex level in a pandas series


code:
df = pd.DataFrame.from_items([("A\tbar", [1, 2, 3]), ("B\tfoo" , [4, 5, 6])],orient='index', columns=['one', 'two', 'three'])
df['col_a'] = df.index
lista = [item.split('\t')[0] for item in df['col_a']]
listb = [item.split('\t')[1] for item in df['col_a']]
df['col_a'] = lista
df['col_b'] = listb
cols = df.columns.tolist()
cols = cols[-2:] + cols[:-2]
df = df[cols]
df.to_csv('filename', index=False)

rawDescription: Writing DataFrame to CSV with add header name for row names in Pandas


code:
@init
def initialize (project):

    # File is installed relative to sys.prefix
    project.install_file("Lib/site-packages/foo/conf","foo/conf/settings.ini")

rawDescription: Pybuilder - Non-python files are not packaged


code:
aDict = {'key1': 'value1', 'key2': 'value2'}
aList = [{k:v} for k, v in aDict.items()]
aList

rawDescription: list of dictionaries from single dictionary

description: List of dictionaries from single dictionary


code:
result = None
with pyodbc.connect('DRIVER={SQL Server};SERVER=mydb;DATABASE=solarwinds;Trusted_Connection=True', timeout=1) as cnxn:
    cursor = cnxn.cursor()
    result = cursor.execute(query).fetchall()

rawDescription: How to set a DB connection timeout for a python/pyodbc/unixODBC/MS ODBC Driver 11 for SQL Server/Linux stack?

description: Set a DB connection timeout for a python/pyodbc/unixODBC/MS ODBC Driver 11 for SQL Server/Linux stack


code:
from numpy.random import randn
import numpy as np
import pandas as pd

index = pd.date_range(start="18:10",periods=20,freq='min')
df = pd.DataFrame(randn(20,3),columns=list('abc'),index=index)
calindex = pd.date_range("18:12:30",periods=4,freq='5min')
caldata = pd.Series([10,20,30,40],index = calindex)

# if you use numpy 1.7
real_time = df.index.values
cali_time = caldata.index.values

# if you use numpy 1.6
real_time = np.array(df.index.values.view("i8") / 1000, dtype="datetime64[us]")
cali_time = np.array(caldata.index.values.view("i8") / 1000, dtype="datetime64[us]")

right_index = cali_time.searchsorted(real_time, side="left")
left_index = np.clip(right_index - 1, 0, len(caldata)-1)
right_index = np.clip(right_index, 0, len(caldata)-1)
left_time = cali_time[left_index]
right_time = cali_time[right_index]
left_diff = np.abs(left_time - real_time)
right_diff = np.abs(right_time - real_time)
caldata2 = caldata[np.where(left_diff < right_diff, left_time, right_time)]
df["offset"] = caldata2.values

rawDescription: Distribute data of one time series onto another


code:
import struct
header = struct.pack('!II', packetNo, totalPackets)

rawDescription: How to split data into equal size packets having variable header size..

description: Split data into equal size packets having variable header size..


code: list_of_tuples = [tup for tup in list_of_tuples if tup[1] is not None]

rawDescription: Iteration possibly skipping an element

description: Iteration possibly skipping an element


code:
def delete_selected(modeladmin, request, queryset):
    queryset.delete()

class SomeAdmin(admin.ModelAdmin):
    actions = (delete_selected,)

rawDescription: How to skip delete confirmation page in Django admin for specify model?

description: Skip delete confirmation page in Django admin for specify model


code:
def rotateY(self, amount):
    '''Rotates a vertex on the Y axis around the origin by a given amount (in radians)'''
    temp_x = self.x
    self.x = self.x * math.cos(amount) + self.z * math.sin(amount)
    self.z = temp_x * (-math.sin(amount)) + self.z * math.cos(amount)

rawDescription: 3D rotations in python (slowly decreasing radius)


code:
import win32com.client

autoit = win32com.client.Dispatch("AutoItX3.Control")

autoit.AnyAutoitMethod()

rawDescription: How to call an AutoIt script in Python

description: Call an AutoIt script in Python


code:
import cv2
import numpy as np

img = cv2.imread('dave.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

edges = cv2.Canny(gray,100,200,apertureSize = 3)
cv2.imshow('edges',edges)
cv2.waitKey(0)

minLineLength = 30
maxLineGap = 10
lines = cv2.HoughLinesP(edges,1,np.pi/180,15,minLineLength,maxLineGap)
for x in range(0, len(lines)):
    for x1,y1,x2,y2 in lines[x]:
        cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2)

cv2.imshow('hough',img)
cv2.waitKey(0)

rawDescription: Hough lines in OpenCV/Python

description: Hough lines in OpenCV/Python


code:
def ssl(sock, keyfile=None, certfile=None):
    # we do an internal import here because the ssl
    # module imports the socket module
    import ssl as _realssl
    warnings.warn("socket.ssl() is deprecated.  Use ssl.wrap_socket() instead.",
                  DeprecationWarning, stacklevel=2)
    return _realssl.sslwrap_simple(sock, keyfile, certfile)

rawDescription: PYTHON SSL - The difference between two ways to set up a ssl connection


code:
with open("conf.cfg") as f:
    dict_ = {key: value
             for key, value in (line.strip().split(" ")[:2]
                                for line in f)}

rawDescription: Load options dictionary using generator expression


rawDescription: Django accessing ForeignKey model objects


code:
from django.db import connections
import sqlite3

# Create a Django database connection for our test database
connections.databases['test'] = {'NAME': ":memory:", 'ENGINE': "sqlite3"}

# We assume that the database under the source_wrapper hasn't been created
source_wrapper = connections.all()[0]
target_wrapper = connections.all()[1]

# Create the tables for the source database
source_wrapper.creation.create_test_db()

# Dump the database into a single text query
query = "".join(line for line in source_wrapper.connection.iterdump())

# Generate an in-memory sqlite connection
connection = sqlite3.connect(":memory:")
target_wrapper.connection = connection
target_wrapper.connection.executescript(query)

rawDescription: How can I copy an in-memory SQLite database to another in-memory SQLite database in Python?

description: Copy an in-memory SQLite database to another in-memory SQLite database in Python


code:
class DerivedData(object):
    def __init__(self):
        self.qty1 = 0.0
        self.qty2 = 0.0
        self.combo = 0.0
        self.max = 0.0
        self.peak = Peak(time_point=0.0, qty1=0.0, qty2=0.0)

    def accumulate(self, data):
        self.qty1 += data.qty1
        self.qty2 += data.qty2
        self.combo = self.qty1 + self.qty2
        if self.combo > self.max:
            self.max = self.combo
            self.peak = Peak(time_point=data.time_point,
                             qty1=self.qty1,
                             qty2=self.qty2)

sys = DerivedData()
clusters = defaultdict(DerivedData)
nodes = defaultdict(DerivedData)

dataset.sort(key=operator.attrgetter('time_point'))

for t in dataset:
    sys.accumulate(t)
    clusters[t.cluster].accumulate(t)
    nodes[t.node].accumulate(t)

rawDescription: Python: Improving long cumulative sum

description: Python: Improving long cumulative sum


rawDescription: How to extract slug from URL with regular expression in Python?

description: Extract slug from URL with regular expression in Python


code:
syncoutput,sync_error = p.communicate()
print(syncoutput)

rawDescription: Output of proc.communicate() does not format newlines in django python


code:
class ValidEntryManager(models.Manager):
    def get_query_set(self):
        today = datetime.today()
        start_date = datetime(today.year, today.month, today.day)
        end_date = datetime(today.year, today.month, today.day+1)
        return super(ValidEntryManager, self).get_query_set().filter(timestamp__gte=start_date, timestamp__lte=end_date)

rawDescription: Django manager return all entries for today - DateTimeField


code:
from itertools import izip

def relabel(labels):
    seen = {}
    for l in labels:
        if l not in seen:
            seen[l] = len(seen)
        yield seen[l]

def compare_labels(l1,l2):
    if len(l1) != len(l2):
        return False

    l1 = relabel(l1)
    l2 = relabel(l2)
    return all(x==y for x,y in izip(l1,l2))

rawDescription: Efficiently comparing lists of arbitrarily-assigned labels


code:
def __init__(self, useOffset=True, useMathText=None, useLocale=None):
    # useOffset allows plotting small data ranges with large offsets: for
    # example: [1+1e-9,1+2e-9,1+3e-9] useMathText will render the offset
    # and scientific notation in mathtext

    self.set_useOffset(useOffset)

rawDescription: matplotlib remove axis label offset by default

description: Matplotlib remove axis label offset by default


code:
def multi_filter(predicates, iterable):
    bins = [[] for _ in predicates]
    for item in iterable:
        for predicate, bin in zip(predicates, bins):
            if predicate(item):
                bin.append(item)

    return bins

rawDescription: multiple self-contained filters applied during a single iteration

description: Multiple self-contained filters applied during a single iteration


code:
import numpy
import matplotlib.pyplot as plt

x = numpy.random.randn(1000)

values, bins, _ = plt.hist(x, normed=True)
area = sum(numpy.diff(bins)*values)

rawDescription: How to get the area under a histogram in python

description: Get the area under a histogram in python


code:
def list_avg(str_list):
    int_list = [float(i.strip('[]')) for i in str_list.split(',')]
    return sum(int_list) / len(int_list)

rawDescription: converting a '[1,2,3,4]' to a float or int in python

description: Converting a '[1,2,3,4]' to a float or int in python


code:
tree = ET.parse('file.xml')
root = tree.getroot()
parent_map = dict((c, p) for p in tree.getiterator() for c in p)

# list so that we don't mess up the order of iteration when removing items.
iterator = list(root.getiterator('Target'))

for item in iterator:
    old = item.find('ID')
    text = old.text
    if '12345' in text:
        parent_map[item].remove(item)
        continue

tree.write('out.xml')

rawDescription: Removing parent element and all subelements from XML


code:
class Move:
  TYPES = ['rock', 'paper', 'scissors']
  BEATS = {
    'rock': ['scissors'],
    'paper': ['rock'],
    'scissors': ['paper']
  }

  def __init__(self, type):
    if type not in self.TYPES:
      raise Exception("Invalid move type")
    self.type = type

  def __str__(self):
    return self.type

  def __cmp__(self, other):
    if other.type in self.BEATS[self.type]:
      return 1
    elif self.type in self.BEATS[other.type]:
      return -1
    else:
      return 0

rawDescription: How can I make this code Pythonic

description: Make this code Pythonic


code: re.findall('Catalina 320', string.split('These boats')[0])

rawDescription: How can I control results returned by Python's re.findall() on an html string?

description: Control results returned by Python's re.findall() on an html string


rawDescription: What's the difference between [[False] * 26] * 26] and [[False] * 26 for _ in range(0, 26)]?


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

WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500

pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))

BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)

def display_text_animation(string):
    text = ''
    for i in range(len(string)):
        DISPLAYSURF.fill(WHITE)
        text += string[i]
        text_surface = font.render(text, True, BLACK)
        text_rect = text_surface.get_rect()
        text_rect.center = (WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
        DISPLAYSURF.blit(text_surface, text_rect)
        pygame.display.update()
        pygame.time.wait(100)

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

display_text_animation('Hello World!')
main()

rawDescription: Making text appear one character at a time [PyGame]


code:
from scrapy.http import Request
from scrapy.spider import BaseSpider
from scrapy.selector import XmlXPathSelector
from scrapy.item import Item, Field
import csv

class Road(Item):
    RoadNum = Field()
    RoadName = Field()
    PostNum = Field()

def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
    csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
    for row in csv_reader:
        yield [unicode(cell, 'utf-8') for cell in row]

class Geospider(BaseSpider):
    name = 'Geospider'
    allowed_domains = ["http://kortforsyningen.kms.dk/"]
    start_urls = []

    def start_requests(self):
        reader = unicode_csv_reader(open('AddressesAndZipcodes.csv'))
        for row in reader:
            address, zip_code = row[:2]
            url = 'http://kortforsyningen.kms.dk/service?ServiceName=geoV&soegemetode=0&vejnavn=%s&kommunepost=%s&format=XML&max_hits=10&login=xxx&password=xxx' % (address, zip_code)

            yield Request(url=url, meta={'zip_code': zip_code})

    def parse(self, response):
        xxs = XmlXPathSelector(response)
        sites = xxs.select('//dokument/forekomst')

        item = Road()
        item['RoadNum'] = sites.select("vejkode/text()").extract()
        item['RoadName'] = sites.select("vejnavn/text()").extract()
        item['PostNum'] = response.meta['zip_code']

        yield item

rawDescription: Making web scraper yield more information


rawDescription: How to run python script with Laravel's command fire method?

description: Run python script with Laravel's command fire method


code:
import os
import signal
import subprocess
import sys

p = subprocess.Popen(['ping', 'google.com'], stdout=subprocess.PIPE)
while True:
    line = p.stdout.readline()

    sys.stdout.write(line)
    sys.stdout.flush()
    if '10' in line:
        break

p.kill()

rawDescription: Catching Terminal Output in Python

description: Catching Terminal Output in Python


code:
import wx
frame = wx.Frame(None)

rawDescription: purpose of wx.App when just showing a frame is enough

description: Purpose of wx.App when just showing a frame is enough


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

# choose your colormap
cmap = plt.cm.jet

# get a Nx4 array of RGBA corresponding to zs
# cmap expects values between 0 and 1
z_list = np.array(z_list) # if z_list is type `list`
colors = cmap(z_list / z_list.max())

# set the alpha values according to i_list
# must satisfy 0 <= i <= 1
i_list = np.array(i_list)
colors[:,-1] = i_list / i_list.max()

# then plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x_list, y_list, z_list, c=colors)
plt.show()

rawDescription: How can I control the color and opacity of each point in a python scatter plot?

description: Control the color and opacity of each point in a python scatter plot


code:
connect_string = 'dbname=test host=localhost port=5493 user=postgres password=postgres'
connection = psycopg2.connect(connect_string)
cursor = connection.cursor()
f = open(fn, 'rt')
try:
    reader = csv.reader(f)
    cols = []
    for row in reader:
        if not cols:
            cols = row
            psycopg_marks  = ','.join(['%s' for s in cols])
            insert_statement = "INSERT INTO xyz (%s) VALUES (%s)" % (','.join(cols), psycopg_marks)
            print(insert_statement)
        else:
            print(row)
            cursor.execute(insert_statement, row)
finally:
    f.close()

...

rawDescription: Dynamically handling data columns in csv for import to Postgresql


rawDescription: Fetch latest related objects in django

description: Fetch latest related objects in django


code:
funcDict = {
    'EXT': (lambda x: os.path.splitext(x)[1])
}

rawDescription: Python - Inline get one member of tuple from delegate


code:
import math
math.cos(90)
old_cos = math.cos
def new_cos(degrees):
    return old_cos(math.radians(degrees))
math.cos = new_cos
math.cos(90)

rawDescription: Python how to override a method defined in a module of a third party library


rawDescription: python : how to convert string literal to raw string literal?

description: Python : how to convert string literal to raw string literal


code:
import matplotlib.pyplot as plt
fig1 = plt.figure()
chrt = 0
for i, group in df.groupby('Country'):
    chrt += 1
    ax = fig1.add_subplot(2,2, chrt)
    group.plot(x='Month', y='Value (USD)',title=str(i), ax=ax)

rawDescription: Add a subplot within a figure using a for loop and python/matplotlib


code:
class Team:
  def __init__(self):
    self.name = None
    self.logo = None
    self.members = 0

rawDescription: How to define a class in Python

description: Define a class in Python


rawDescription: Combining lists of tuples based on a common tuple element


code:
from django.core.files.uploadedfile import InMemoryUploadedFile
from cStringIO import StringIO
buf = StringIO(data)  # `data` is your stream of bytes
buf.seek(0, 2)  # Seek to the end of the stream, so we can get its length with `buf.tell()`
file = InMemoryUploadedFile(buf, "image", "some_filename.png", None, buf.tell(), None)
photo.image.save(file.name, file)  # `photo` is an instance of `MyModel`
photo.image

rawDescription: a StringIO like class, that extends django.core.files.File

description: A StringIO like class, that extends django.core.files.File


code: color_frame[np.where(((b_ch < b-offset) | (b_ch > b+offset)) & ((g_ch < g-offset) | (g_ch > g+offset)) & ((r_ch < r-offset) | (r_ch > r+offset)))] = 0

rawDescription: Masking Objects with certain RGB values in Images


code:
x = keypoint.pt[0]
y = keypoint.pt[1]
size = keypoint.size
dir_in_degrees = keypoint.angle
laplacian = round(keypoint.class_id)
hessian = keypoint.response

rawDescription: OpenCV 2.4, Python - Retrieving the laplacian from a SURF keypoint


code:
rx_buf = [ser.read(16384)] # Try reading a large chunk of data, blocking for timeout secs.
while True: # Loop to read remaining data, to end of receive buffer.
    pending = ser.inWaiting()
    if pending:
         rx_buf.append(ser.read(pending)) # Append read chunks to the list.
    else:
         break

rx_data = ''.join(rx_buf) # Join the chunks, to get a string of serial data.

rawDescription: Losing data in received serial string

description: Losing data in received serial string


rawDescription: Filter Queryset by field in OnetoOne model


code:
D2 = dict((x['id'], x['val']) for x in D)
L2 = [D2[x] for x in L]

rawDescription: python: iterate through list and replace elements with corresponding dictionary values

description: Python: iterate through list and replace elements with corresponding dictionary values


code:
index = {}
with open('/tmp/file_index', 'r') as f:
    for line in f.readlines():
        index[line.split(',')[1].strip()] = line.split(',')[0]

if CurrentString in index.keys():
    CurrentString = index[CurrentString]

rawDescription: Replace string with designated number from file


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')

X = np.random.rand(100)*10+5
Y = np.random.rand(100)*5+2.5
Z = np.random.rand(100)*50+25

scat = ax.scatter(X, Y, Z)

# Create cubic bounding box to simulate equal aspect ratio
max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max()
Xb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][0].flatten() + 0.5*(X.max()+X.min())
Yb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][1].flatten() + 0.5*(Y.max()+Y.min())
Zb = 0.5*max_range*np.mgrid[-1:2:2,-1:2:2,-1:2:2][2].flatten() + 0.5*(Z.max()+Z.min())
# Comment or uncomment following both lines to test the fake bounding box:
for xb, yb, zb in zip(Xb, Yb, Zb):
   ax.plot([xb], [yb], [zb], 'w')

plt.grid()
plt.show()

rawDescription: matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y-

description: Matplotlib (equal unit length): with 'equal' aspect ratio z-axis is not equal to x- and y-


rawDescription: Transmit JSON data to Django website

description: Transmit JSON data to Django website


code:
import ast
my_src_str = '"""hello"""'
ast.literal_eval(my_src_str)

rawDescription: How to interpret python source string as a real string?

description: Interpret python source string as a real string


code:
from PyQt5.QtWidgets import QOpenGLWidget
from PyQt5.QtCore import QBasicTimer

class OpenGLWidget(QOpenGLWidget):
    def __init__(self):
        self._timer = QBasicTimer()          # creating timer
        self._timer.start(1000 / 60, self)   # setting up timer ticks to 60 fps

    def paintGL(self):
        pass                                 # some painting code here

    def timerEvent(self, QTimerEvent):
        self.update()                        # refreshing the widget

rawDescription: PyQt5 QOpenGLWidget idle issue

description: PyQt5 QOpenGLWidget idle issue


rawDescription: Iterating through a list of lists and comparing current and last elements


code:
def get_image_size(fname):
    '''Determine the image type of fhandle and return its size.
    from draco'''
    with open(fname, 'rb') as fhandle:
        head = fhandle.read(24)
        if len(head) != 24:
            return
        if imghdr.what(fname) == 'png':
            check = struct.unpack('>i', head[4:8])[0]
            if check != 0x0d0a1a0a:
                return
            width, height = struct.unpack('>ii', head[16:24])
        elif imghdr.what(fname) == 'gif':
            width, height = struct.unpack('<HH', head[6:10])
        elif imghdr.what(fname) == 'jpeg':
            try:
                fhandle.seek(0) # Read 0xff next
                size = 2
                ftype = 0
                while not 0xc0 <= ftype <= 0xcf:
                    fhandle.seek(size, 1)
                    byte = fhandle.read(1)
                    while ord(byte) == 0xff:
                        byte = fhandle.read(1)
                    ftype = ord(byte)
                    size = struct.unpack('>H', fhandle.read(2))[0] - 2
                # We are at a SOFn block
                fhandle.seek(1, 1)  # Skip `precision' byte.
                height, width = struct.unpack('>HH', fhandle.read(4))
            except Exception: #IGNORE:W0703
                return
        else:
            return
        return str(width) + "x" + str(height)

rawDescription: How to obtain a jpeg resolution in python 3, without any alien libraries?

description: Obtain a jpeg resolution in python 3, without any alien libraries


code:
import tornado.web
import tornado.httpserver

class TestParamsHandler(tornado.web.RequestHandler):
    def get(self, param1, param2, param3):
        param2 = param2 if param2 else 'default2'
        param3 = param3 if param3 else 'default3'
        self.write(
            {
                'param1': param1,
                'param2': param2,
                'param3': param3
            }
        )

# My initial answer is above, but I think the following is better.
class TestParamsHandler2(tornado.web.RequestHandler):
    def get(self, **params):
        self.write(params)

application = tornado.web.Application([
    (r"/test1/(?P<param1>[^\/]+)/?(?P<param2>[^\/]+)?/?(?P<param3>[^\/]+)?", TestParamsHandler),
    (r"/test2/(?P<param1>[^\/]+)/?(?P<param2>[^\/]+)?/?(?P<param3>[^\/]+)?", TestParamsHandler2)
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8080)
tornado.ioloop.IOLoop.instance().start()

rawDescription: How can I implement multiple URL parameters in a Tornado route?

description: Implement multiple URL parameters in a Tornado route


code:
from ladon.ladonizer import ladonize
from ladon.types.ladontype import LadonType

class OrderLookUpResponse(LadonType):
    RSOID = str
    ItemNum = str
    Quant = str

@ladonize(str,rtype=[OrderLookUpResponse])
def LookupOrder(self,OrderID):
    results=[]
    cursor.execute("SELECT ALIAS,QTY,RSO_ID FROM RSK_DETAIL WHERE RSO_ID IN(SELECT RSO_ID FROM RSK_ORDER WHERE ACCT_CODE = 'SCRUBBED')")
    rows=cursor.fetchall()
    for row in rows:
        RSOID = row.RSO_ID
        ALIAS=row.ALIAS
        Qty=row.QTY
        result = OrderLookUpResponse()
        result.RSOID=RSOID
        result.ItemNum=ALIAS
        result.Quant=Qty
        results.append(result)
    return results

rawDescription: Ladon only returning once for a for loop


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

# read in the file and separate it into two lists
a = pd.read_csv('Sorted_Bike_Uses.csv', header=0)
b = a['Bike ID']
c = a['Number of Uses']

# create the graph
plt.plot(c)

# label the x and y axes
plt.xlabel('Bicycles', weight='bold', size='large')
plt.ylabel('Number of Rides', weight='bold', size='large')

# format the x and y ticks
plt.xticks(range(len(c)), b, rotation=50, horizontalalignment='right', weight='bold', size='large')
plt.yticks(weight='bold', size='large')

# give it a title
plt.title("Top Ten Bicycles (by # of uses)", weight='bold')

# displays the graph
plt.show()

rawDescription: pyplot x-axis being sorted

description: Pyplot x-axis being sorted


code:
import json
...
l = soup.p.get_text()  # find p tag and extract text from it
result = json.loads(l) # convert text into python list

rawDescription: How to extract the specific contents from the html doc I grasp

description: Extract the specific contents from the html doc I grasp


code:
import scrapy
from tutorial.items import TutorialItem

class ChillumSpider(scrapy.Spider):
    name = "chillum"
    allowed_domains = ["flipkart.com"]
    start_urls = ["http://www.flipkart.com/search?q=brown+jacket&as=offas-show=off&otracker=start"]

    def parse(self, response):
        titles = response.xpath('//a[@class="fk-display-block"]/text()').extract()
        for title in titles:
            item = TutorialItem()
            item['title'] = title
            yield item

rawDescription: Scrape result export prooblem

description: Scrape result export prooblem


code:
columns = [col[0] for col in cursor.description]
rows = [dict(zip(columns, row)) for row in cursor.fetchall()]

rawDescription: MySQL fetchall() - how to get data inside a dict rather than inside a tuple


code:
import random
import matplotlib.pyplot as plt

labels = [chr(j) for j in range(97, 115)]

fake_data1 = [random.random() for l in labels]
fake_data2 = [random.random() for l in labels]
y_data = range(len(labels))

figure()
ax = gca()

ax.grid(True)
ax.scatter(fake_data1, y_data, color='r')
ax.scatter(fake_data2, y_data, color='b')

ax.set_yticks(range(len(labels)))
ax.set_yticklabels(labels)
ax.invert_xaxis()
plt.draw()

rawDescription: How to produce plot with text as ytick labels

description: Produce plot with text as ytick labels


code:
# Change
open(file_in, 'r')
open(file_out, 'w')
# to
input_file = open(file_in, 'r')
output_file = open(file_out, 'w')

for ln in input_file:
    # do your processing
    if res:
        lemme = res.group(3)
        output_file.write(str(lemme) + "\n")

rawDescription: Python: how to transform a string which carries the filename into a readable filename?


code:
A = np.ones((50000000,))
B = A[:,np.newaxis]
B.flags

rawDescription: Referencing a numpy arrray without creating an expensive copy


rawDescription: Parsing adjacent items in Scrapy

description: Parsing adjacent items in Scrapy


code:
def doctype(soup):
    items = [item for item in soup.contents if isinstance(item, bs4.Doctype)]
    return items[0] if items else None

rawDescription: Get document DOCTYPE with BeautifulSoup

description: Get document DOCTYPE with BeautifulSoup


code:
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

app = QApplication(sys.argv)
web = QWebView()
web.settings().setAttribute(QWebSettings.PluginsEnabled, True)
web.show()
web.load(QUrl('file:///C:/test/test.pdf')) # Change path to actual file.
sys.exit(app.exec_())

rawDescription: Is it possible to get QWebKit to display pdf files?


code:
s=0
L=[int(c) for c in input()]
for x in range(8):
    a=L[x]*(2**(7-x))
    # This is the same as "s=s+a"
    s+=a
print(s)

rawDescription: Python: Ask to user a list var

description: Python: Ask to user a list var


code:
x = 'Hello, WORLD, McGisty, you are my HERO THAT I am.'
m = ' '.join(e.capitalize() if e.isupper() else e for e in x.split())
m

rawDescription: in string, capitalize allcaps words and leave the rest alone

description: In string, capitalize allcaps words and leave the rest alone


code:
class Room (MapSite):
    def __init__ (self, room_no):
        self._room_no = room_no
        self._map_site = None

    def get_side (self, direction):
        return ...

    def set_side(self, direction, map_site):
        ...

    # No need to define enter since it is inherited

rawDescription: How does one implement in python the equivalent of a C++ class member that returns a pointer to another class?

description: Implement in python the equivalent of a C++ class member that returns a pointer to another class


code:
from string import ascii_letters
from string import digits
from base64 import b16decode
from base64 import b16encode

ALPHANUMERIC_SET = set(ascii_letters + digits)

def utf8_string_to_hex_string(s):
    return ''.join(chr(i) for i in b16encode(s.encode('utf-8')))

def hex_string_to_utf8_string(s):
    return b16decode(bytes(list((ord(i) for i in s)))).decode('utf-8')

def underscore_encode(chars_in):
    chars_out = list()
    for char in chars_in:
        if char not in ALPHANUMERIC_SET:
            chars_out.append('_{}_'.format(utf8_string_to_hex_string(char)))
        else:
            chars_out.append(char)
    return ''.join(chars_out)

def underscore_decode(chars_in):
    chars_out = list()
    decoding = False
    for char in chars_in:
        if char == '_':
            if not decoding:
                hex_chars = list()
                decoding = True
            elif decoding:
                decoding = False
                chars_out.append(hex_string_to_utf8_string(hex_chars))
        else:
            if not decoding:
                chars_out.append(char)
            elif decoding:
                hex_chars.append(char)
    return ''.join(chars_out)

rawDescription: How to encode UTF-8 strings with only "A-Z","a-z","0-9", and "_" in Python

description: Encode UTF-8 strings with only "A-Z","a-z","0-9", and "_" in Python


code:
try:
    input = raw_input
except NameError:
    pass

# now input() does the job on either 2.x or 3.x

rawDescription: Python, removing required quotes from input()


code:
c.execute("""INSERT INTO Website (website_name, enabled) VALUES (%s, 0)""", (store_name))
my_last_id = c.lastrowid  # cursor.lastrowid

rawDescription: python mysqldb INSERT is inserting arbitrary values in AUTO_INCREMENT primary column

description: Python mysqldb INSERT is inserting arbitrary values in AUTO_INCREMENT primary column


code:
class GetInputTest(unittest.TestCase):

  @patch('builtins.input', side_effect=["yes", "1"])
  def test_output(self,m):
      saved_stdout = sys.stdout
      try:
          out = io.StringIO()
          sys.stdout = out
          main()
          output = out.getvalue().strip()
          # Make sure TEST appears at the end, in addition to the original list of items.
          self.assertEqual(output, "1.Scallywag\n2.Crew\n3.Pirate\nTEST")

      finally:
          sys.stdout = saved_stdout

rawDescription: Python unit test for nested if statement


code:
import pandas as pd

# Reset indexes for unpivoting. If you need the original DataFrames
# as is later on, don't pass inplace=True and store the return value as
# the new index free frame.
df1.reset_index(level=0, inplace=True)
df2.reset_index(level=0, inplace=True)

# unpivot dataframes
df1_melt = pd.melt(df1, id_vars=['SKU'], var_name='USER', value_name='ACTUAL')
df2_melt = pd.melt(df2, id_vars=['SKU'], var_name='USER', value_name='PREDICTED')

# merge dataframes on SKU, USER
df_merged = df1_melt.merge(df2_melt, on=['SKU', 'USER'])

for row in df_merged.itertuples(index=False):
    sku, user, actual, predicted = row
    print('{user} SKU {sku}: ACTUAL = {actual}, PREDICTED = {predicted}'.format(
        user=user, sku=sku, actual=actual, predicted=predicted
    ))

rawDescription: Extract values from 2 seprate dataframes with same index and column names


code:
import urllib.request

url_target = urllib.request.urlopen("http://stackoverflow.com")
tmp_copy_string = url_target.read().decode("utf8").split('\n')    #split string on newline

for line in tmp_copy_string:
        print(line)

rawDescription: Python 3 web page to lines

description: Python 3 web page to lines


rawDescription: Calculate percent change on a Pandas DataFrame


code:
pos_postfixes = ['k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
neg_postfixes = ['m', 'µ', 'n', 'p', 'f', 'a', 'z', 'y']

num_postfix = n[-1]
if num_postfix in pos_postfixes:
    num = float(n[:-1])
    num*=10**((pos_postfixes.index(num_postfix)+1)*3)
elif num_postfix in neg_postfixes:
    num = float(n[:-1])
    num*=10**(-(neg_postfixes.index(num_postfix)+1)*3)
else:
    num = float(n)
print(num)

rawDescription: Convert string with engineer prefix to float


rawDescription: wxPython, Threads, and PostEvent between modules

description: WxPython, Threads, and PostEvent between modules


code:
itertools.chain.from_iterable(
  ("new1", "new2") if item == "old" else (item, ) for item in values)

rawDescription: pythonic way of replacing one item with two or more in a list

description: Pythonic way of replacing one item with two or more in a list


code:
# services.py
# this is a module, doesn't keep any state within,
# it may read and write to the DB, do some processing etc but doesn't remember things
def get_scores(student_id):
    return Score.objects.filter(student=student_id)

# views.py
# receives HTTP requests
def view_scores(request, student_id):
    scores = services.get_scores(student_id)
    # e.g. use the scores queryset in a template return HTML page

rawDescription: Pythonic Django object reuse

description: Pythonic Django object reuse


code:
class MyModelChoiceField(ModelChoiceField):
    def label_from_instance(self, obj):
        return "My Object #%i" % obj.id

rawDescription: Labels for Django select form field

description: Labels for Django select form field


code: os.environ['HOMEDRIVE'] = 'D:'

rawDescription: Python - Override environment variables homedrive and homepath


code:
def generate(x):
    for digits in itertools.count(1):
        for i in itertools.product(range(1, 10), repeat=digits):
            if reduce(operator.mul, i) == x:
                yield i
    if (math.pow(2, digits) > x):
        break

rawDescription: How to build a dynamically growing nested list comprehension?

description: Build a dynamically growing nested list comprehension


code: 'This is a ' + type(somevariable).__name__

rawDescription: Python type as a string

description: Python type as a string


rawDescription: regular expression get number from string

description: Regular expression get number from string


code:
for i in qs:
    obj = myEmails(text=i.text)
    obj.save()

rawDescription: Creating new table while iterating through a queryset in django


rawDescription: how to make a 2-digit string from an integer using regex in python

description: Make a 2-digit string from an integer using regex in python


code:
import bisect
import itertools

teams = ['W', 'X', 'Y', 'Z']
goals = [4, 5, 1, 9]

# Create the max goal of each team
goal_ranges = itertools.accumulate(goals)

# Create sorted tuples of goals and teams (comes sorted because of accumulate)
ordered_teams = list(zip(goal_ranges, teams))

def get_team(goal_number):
    # Get the leftmost occurence of the goal number, and extract the team from the tuple
    return ordered_teams[bisect.bisect_left(ordered_teams, (goal_number,))][1]

rawDescription: tuples and list arrangements in python

description: Tuples and list arrangements in python


code:
from joblib import Parallel, delayed

if __name__ == "__main__":
    result = Parallel(n_jobs=-1)(delayed(simu)(c) for c in clusterSizes)
    # process result

rawDescription: Parallel.For in Python

description: Parallel.For in Python


code:
#!/usr/bin/python

from ansible.runner.lookup_plugins.file import LookupModule as FilePlugin
from ansible import utils

class ActionModule(object):

    def __init__(self, runner):
        self.runner = runner

    def run(self, conn, tmp_path, module_name, module_args, inject, complex_args=None, **kwargs):

        options = {}
        options.update(utils.parse_kv(module_args))

        file_plugin = FilePlugin()
        files_content = file_plugin.run(terms=options.get('myarg'), inject=inject)
        options['myarg'] = files_content[0]

        return self.runner._execute_module(conn=conn, tmp="/tmp", module_name="mymod", args=utils.serialize_args(options), inject=inject)

rawDescription: Custom ansible module in python - How to resolve relative role file paths?


code:
import csv
cot=csv.writer(open('file.csv','wb'))

tmp=[['','Project 1','Project 2','Project 3'],
     ['Student1','','2','1'],
     ['Student2','1','2','3'],
     ['Student3','1','3','2']]
for t in tmp:
    cot.writerow(t)

rawDescription: Using Python to get a CSV output for the following example


code:
# To read all data at once
with open("/path/to/file.txt") as file_handle:
    file_contents = file_handle.read()

# To read one line at a time
with open("/path/to/file.txt") as file_handle:
    for line in file_handle:
        line = line.strip()
        # Do more stuff with line

rawDescription: Plotting in Python

description: Plotting in Python


code:
import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    prompt = 'prompt: '
    intro = "Simple command processor example."

rawDescription: Simulating CLI Shell with python

description: Simulating CLI Shell with python


code: print(choice(foo));

rawDescription: How do I randomly select from a list in Python?

description: Randomly select from a list in Python


code: QObject.connect(app, SIGNAL("focusChanged(QWidget *, QWidget *)"), changedFocusSlot)

rawDescription: How to realize wx.EVT_KILL_FOCUS and wx.lib.intctrl.IntCtrl in PySide?

description: Realize wx.EVT_KILL_FOCUS and wx.lib.intctrl.IntCtrl in PySide


code:
def range(start, stop=None):
    if stop is None: # only one arg, treat stop as start ...
        stop = start
        start = 0
    ...

rawDescription: Order of default and non-default arguments


code:
import re
re.match('img', 'test.img')
re.search('img', 'test.img')

rawDescription: Regular Expression in Python can't parse string contains dot


code:
df = pd.DataFrame([1, 2, 3], index=[dt.datetime(2013, 1, 1), dt.datetime(2013, 1, 3), dt.datetime(2013, 1, 5)])
df
start = df.index.searchsorted(dt.datetime(2013, 1, 2))
end = df.index.searchsorted(dt.datetime(2013, 1, 4))
df.ix[start:end]

rawDescription: python pandas dataframe slicing by date conditions

description: Python pandas dataframe slicing by date conditions


code:
import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

rval, frame = vc.read()

while True:

  if frame is not None:
     cv2.imshow("preview", frame)
  rval, frame = vc.read()

  if cv2.waitKey(1) & 0xFF == ord('q'):
     break

rawDescription: OpenCV wont' capture from MacBook Pro iSight


code:
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    # ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rawDescription: Django direct link to file

description: Django direct link to file


rawDescription: assigning two variables to one list slice

description: Assigning two variables to one list slice


code:
size = min(image.Size)

originX = image.Size[0] / 2 - size / 2
originY = image.Size[1] / 2 - size / 2

cropBox = (originX, originY, originX + size, originY + size)

rawDescription: What's a more elegant rephrasing of this cropping algorithm? (in Python)


rawDescription: Importing a 3-D list variable from a text file in Python


code:
from itertools import combinations
import numpy as np

candy = [ ["snickers", 150.5], ["mars", 130.3], ["choc", 10.0]]

n = len(candy)
ww = np.array([c[1] for c in candy]) # extract weights of candys
idx = np.arange(n) # list of indexes

iidx,sums = [],[]
# generate all possible sums with index list
for k in range(n):
    for ii in combinations(idx, k+1):
        ii = list(ii) # convert tupel to list, so it can be used as a list of indeces
        sums.append(np.sum(ww[ii]))
        iidx.append(ii)
sums = np.asarray(sums)
ll = np.where(np.abs(sums-160.5)<1e-9)  # filter out values which match 160.5

# print results
for le in ll:
    print([candy[e] for e in iidx[le]])

rawDescription: Should this be solved using a subset sum algorithm


rawDescription: What is the Python (numpy or scipy or Pandas) equivalent for R's adjboxStats function?


code:
sum = 0.
n = 0
correct_ans = np.argmax(test_y, axis=1)
returned_ans = self.predictor(test_x)
for c, r in zip(correct_ans, returned_ans):
    if c == r:
        sum += 1
    n += 1
avg = sum / n

rawDescription: Numpy mean 'inplace'

description: Numpy mean 'inplace'


code: subset = subset.iloc[subset.index.get_level_values(2) != 'blo']

rawDescription: Pandas dataframe with MultiIndex: exclude level values


code:
from functools import reduce # Valid in Python 2.6+, required in Python 3
import operator

reduce(operator.mul, (3, 4, 5), 1)

rawDescription: What's the Python function like sum() but for multiplication? prod()?


code:
def slice_tuple(slice_):
    return slice_.start, slice_.stop, slice_.step

rawDescription: Get index values from slice objects in python


code:
countries = [
    {'name': 'Australia', 'population': 21, 'tz': 'UTC +10', 'visits': 1},
    {'name': 'Germany', 'population': 81, 'tz': 'UTC +1', 'visits': 2},
    {'name': 'Mexico', 'population': 107, 'tz': 'UTC -6', 'visits': 0},
]

template = """
<select>
<option{% if record.visits = 0%} selected {% endif %}>0
<option{% if record.visits = 1%} selected {% endif %}>1
<option{% if record.visits = 2%} selected {% endif %}>2
</select>
"""

class CountryTable(tables.Table):
    name = tables.Column()
    population = tables.Column()
    tz = tables.Column(verbose_name='time zone')
    visits = tables.TemplateColumn(template)

rawDescription: Customize column for django-tables as drop down list


code:
import time
import tweepy

auth = tweepy.OAuthHandler(..., ...)
auth.set_access_token(..., ...)

api = tweepy.API(auth)

ids = []
for page in tweepy.Cursor(api.followers_ids, screen_name="McDonalds").pages():
    ids.extend(page)
    time.sleep(60)

screen_names = [user.screen_name for user in api.lookup_users(user_ids=ids)]

rawDescription: Get all friends of a given user on twitter with tweepy


code:
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

server_url = "http://%s:%s/wd/hub" % (test_host, test_port)
dc = DesiredCapabilities.HTMLUNIT
wd = webdriver.Remote(server_url, dc)
wd.get('http://www.google.com')

rawDescription: How do I use the HTMLUnit driver with Selenium from Python?

description: Use the HTMLUnit driver with Selenium from Python


code:
for x in PLAYER:
    if x in DECK:
        DECK.remove(x)

rawDescription: How can i select random items from a set of two lists and then remove that set of items from another list built out of all the possibilities

description: Select random items from a set of two lists and then remove that set of items from another list built out of all the possibilities


code:
while True:   # to loop the question
    answer = input("Do you like burgers? ").lower()
    if answer == "y" or answer == "n":
        break

rawDescription: Python: very basic help on a while loop

description: Python: very basic help on a while loop


rawDescription: How can I store testing data for python nosetests?

description: Store testing data for python nosetests


code:
import itertools
def findsubsets(S,m):
    return set(itertools.combinations(S, m))

rawDescription: How can I find all the subsets of a set, with exactly n elements?

description: Find all the subsets of a set, with exactly n elements


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

fig,ax = plt.subplots()

# Lets say your files are called data-00.txt, data-01.txt etc.
for i in range(66):
    data=np.genfromtxt('data-{:02d}.txt'.format(i))
    ax.plot(data)

fig.savefig('my_fig.png')

rawDescription: Plot multiple data using for loop, pyplot and genfromtxt


code:
# you could do the group_changes somewhat faster if you care a lot
group_changes = np.concatenate(([0], np.where(groups[:-1] != groups[1:])[0] + 1))
Vprods = np.multiply.reduceat(values, group_changes)

rawDescription: Product of array elements by group in numpy (Python)


code:
def encrypted(text):
    scores = defaultdict(lambda: 0)
    for letter in text: scores[letter] += 1
    largest = max(scores.values())
    average = len(text) / 256.0
    return largest < average + 5 * sqrt(average)

rawDescription: Python: Is there a good way to check if text is encrypted?


code:
class MyClass:
    def __init__(self):
        self._private1 = "Whatever1"

    @property
    def private1(self):
        return self._private1

    @private1.setter
    def private1(self, value):
        self._private1 = value

rawDescription: Accessing private variables when there's a getter/setter for them


code:
import re
formula = "P = V*I*cos(2*pi*f)"
variables = re.findall('[a-zA-Z]+' , formula)
special = ['cos', 'pi']
variables = [v for v in variables if v not in special]

rawDescription: Identifying variables in equation

description: Identifying variables in equation


code:
pcount = 0
for c in function_str:
    if c == '(': pcount += 1
    if c == ')': pcount -= 1
    if (c == 'a' or c == 'o') and pcount == 0:
        return c # Root found

rawDescription: Given a binary boolean formula, how to find primary/root operator?


code:
from flask import request
...

imgfile = request.files['file-id']
imgname = imgfile.filename

rawDescription: Python, Flask - How to Use DHTML uploader to load a file


code: new = [[x, y, val] for (x, y), val in zip(points, vals)]

rawDescription: Adding an entry to a python tuple

description: Adding an entry to a python tuple


code:
f = Foobar.objects.get(id=1)
foo = 'somefield'
bar = 'somevalue'
setattr(f, foo, bar) # f.foo=bar
f.save()

rawDescription: Update model instance with dynamic field names


code:
import shlex

str1 = "./program.sh %lf %lf" % (x0, x1)
sim_flux230 = subprocess.check_output(shlex.split(str1))

rawDescription: Python subprocess: using a string variable as command


code:
import os

version_matching = {}

for path, subdirs, files in os.walk('test'):

    print("Entering " + path)

    for filename in files:
        parts = filename.split('_')

        file_name = parts[0]

        try:
            version = int(parts[1])
        except (IndexError, ValueError):
            # In case some files don't follow the pattern
            print("Skipping " + path + '/' + filename)
            continue

        if file_name not in version_matching:

            # First time we see this file, save the informations

            version_matching[file_name] = {"version": version,
"path": path + '/' + filename}

        elif version_matching[file_name]["version"] > version:

            # We have already seen the file,
            # but the one we are handling has a lower version number,
            # we delete it

            print("Removing " + path + '/' + filename)
            os.remove(path + '/' + filename)

        else:

            # We have already seen the file,
            # but this version is more recent,
            # we delete the saved one

            print("Removing " + version_matching[file_name]["path"])
            os.remove(version_matching[file_name]["path"])

            # And we update the saved infos

            version_matching[file_name]["version"] = version
            version_matching[file_name]["path"] = path + '/' + filename

rawDescription: Python Comparing and deleting files

description: Python Comparing and deleting files


code:
def __init__(self):
    super(ProvaLayout, self).__init__()
    self.cols = 2
    self.Labell = Label(text="-------------")
    self.add_widget(self.Labell)
    self.btn = Button(text="caio")
    self.add_widget(self.btn)
    def callback(instance): # single argument without self (it's a local function inside a method)
        self.Labell.text="caio"  # changing text property of existing self.Label instead of creating a new object
    self.btn.bind(on_press = callback) # you should use on_press, not on_pressed

rawDescription: Kivy fails to change label text

description: Kivy fails to change label text


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

x = np.arange(500) + 100
y = 50 * np.cos(x / 10.0) + 100

fig, ax = plt.subplots()

ax.imshow(plt.imread('floor_plan.gif'), origin='lower')
ax.autoscale(False)
ax.plot(x, y)

plt.show()

rawDescription: Insert a Picture as the Background of a Figure?


code:
from gi.repository import Gtk

class MainWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title='GMouse 600')
        self.overlay = Gtk.Overlay()
        self.add(self.overlay)
        self.background = Gtk.Image.new_from_file('./images/g600-thumb-buttons.jpg')
        self.overlay.add(self.background)
        self.grid = Gtk.Grid()
        self.button = Gtk.Button(label='Test')
        self.grid.add(self.button)
        self.overlay.add_overlay(self.grid)

window = MainWindow()
window.connect('delete-event', Gtk.main_quit)
window.show_all()
Gtk.main()

rawDescription: Gtk3 Image full window image from file (python3)


code:
import glob, os

programxoutput = glob.glob('ProgramX*')[0]
os.rename(programxoutput, 'input.output')

rawDescription: Grabbing output FILE from Python Popen process?


rawDescription: page range for printing algorithm

description: Page range for printing algorithm


code:
geopoint = {'latitude':41.123,'longitude':71.091}
print('{latitude} {longitude}'.format(**geopoint))

rawDescription: How do I format a string using a dictionary in python-3.x?

description: Format a string using a dictionary in python-3.x


code:
class ABRoot:

     def index(self):
         funds = database.FundList()
         template = lookup.get_template("index.html")
         return template.render(fund_list=funds)

if __name__ == '__main__':

     dispatcher = cherrypy.dispatch.RoutesDispatcher()
     dispatcher.explicit = False
     dispatcher.connect('test', '/', ABRoot().index)

     conf = {
    '/' : {
        'request.dispatch' : dispatcher,
        'tools.staticdir.root' : "C:/Path/To/Application",
        'log.screen' : True
    },
    '/css' : {
        'tools.staticdir.debug' : True,
        'tools.staticdir.on' : True,
        'tools.staticdir.dir' : "css"
    },
    '/js' : {
        'tools.staticdir.debug' : True,
        'tools.staticdir.on' : True,
        'tools.staticdir.dir' : "js"
    }
     }

     #conf = {'/' : {'request.dispatch' : dispatcher}}

     cherrypy.tree.mount(None, "/", config=conf)
     cherrypy.quickstart(None, config=conf)

rawDescription: Using CherryPy with Routes dispatching

description: Using CherryPy with Routes dispatching


rawDescription: Delete certain values from a dictionary?

description: Delete certain values from a dictionary


code:
import bpy

scene = bpy.context.scene

# Create new lamp datablock
lamp_data = bpy.data.lamps.new(name="New Lamp", type='POINT')

# Create new object with our lamp datablock
lamp_object = bpy.data.objects.new(name="New Lamp", object_data=lamp_data)

# Link lamp object to the scene so it'll appear in this scene
scene.objects.link(lamp_object)

# Place lamp to a specified location
lamp_object.location = (5.0, 5.0, 5.0)

# And finally select it make active
lamp_object.select = True
scene.objects.active = lamp_object

rawDescription: Can you add a light source in blender using python

description: Add a light source in blender using python


rawDescription: How to remove all cells in a pyqt4 tablewidget?

description: Remove all cells in a pyqt4 tablewidget


code:
def makePlayFair(key, alpha):

    letters = []
    for letter in key + alpha:
        if letter not in letters:
            letters.append(letter)

    box = []
    for line_number in range(5):
        box.append( letters[line_number * 5: (line_number+1) * 5])

rawDescription: My python method isn't working correctly, skipping items in a list (playfair cipher)


code:
from pprint import pprint

def dsum(*args):
    return {
        k1: {
            k: sum(d.get(k1, dict()).get(k, 0) for d in args)
            for k in set.union(*(set(d.get(k1, dict())) for d in args))
        }
        for k1 in set.union(*(set(d) for d in args))
    }

A = {"Green":{"Small": 5, "Medium": 10, "Large": 15}, "Yellow": {"Small": 7, "Medium": 14, "Large": 21}}

B = {"Green":{"Small": 1, "Medium": 2, "Large": 3}, "Yellow": {"Small": 3, "Medium": 6, "Large": 9}}

C = {"Green":{"Small": 6, "Medium": 12, "Large": 18}, "Yellow": {"Small": 10, "Medium": 20, "Large": 30}}

testC = dsum(A, B)
assert C == testC
pprint(testC)

rawDescription: How can I add the values of the same keys in different dictionaries in python?

description: Add the values of the same keys in different dictionaries in python


code:
from BeautifulSoup import BeautifulSoup
import xlwt

text = '''

Tesco - United Kingdom
CO
Unknown
BULATS

Tesco - United Kingdom
CO
Unknown
BULATS

'''

wb = xlwt.Workbook()
ws = wb.add_sheet('a test sheet')

soup = BeautifulSoup(text)
table = soup.find('table')
rows = table.findAll('tr')
x = 0
for tr in rows:
    cols = tr.findAll('td', attrs={'class' : 'normaltext'})
    if not cols:
        # when we hit an empty row, we should not print anything to the workbook
        continue
    y = 0
    for td in cols:
        texte_bu = td.text
        texte_bu = texte_bu.encode('utf-8')
        texte_bu = texte_bu.strip()
        ws.write(x, y, td.text)
        print(x, y, td.text)
        y = y + 1
    # update the row pointer AFTER a row has been printed
    # this avoids the blank row at the top of your table
    x = x + 1

wb.save('example.xls')

rawDescription: BeautifulSoup - Blank line in the output 'cause a strange useless


code:
dics = [x[i:i+5] for i in range(0,len(x),5)]
dics
[{i.keys()[0]:i.values()[0] for i in j} for j in dics]

rawDescription: grouping similar values together

description: Grouping similar values together


code:
from django.utils import unittest
from django.test.client import RequestFactory

class SimpleTest(unittest.TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()

    def test_details(self):
        # Create an instance of a GET request.
        request = self.factory.get('/customer/details')

        # Test my_view() as if it were deployed at /customer/details
        response = my_view(request)
        self.assertEqual(response.status_code, 200)

rawDescription: how to get request object in django unit testing?

description: Get request object in django unit testing


code:
from functools import wraps
from flask import current_app, request, session, redirect, render_template
from flask_login import current_user
from werkzeug.datastructures import MultiDict

def login_required_save_post(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if current_app.login_manager._login_disabled or current_user.is_authenticated:
            # auth disabled or already logged in
            return f(*args, **kwargs)

        # store data before handling login
        session['form_data'] = request.form.to_dict(flat=False)
        session['form_path'] = request.path
        return current_app.login_manager.unauthorized()

    return decorated

@app.route('/article/<int:id>', methods=['GET', 'POST'])
@login_required_save_post
def article_detail(id):
    article = Article.query.get_or_404(id)

    if session.pop('form_path', None) == request.path:
        # create form with stored data
        form = CommentForm(MultiDict(session.pop('form_data')))
    else:
        # create form normally
        form = CommentForm()

    # can't validate_on_submit, since this might be on a redirect
    # so just validate no matter what
    if form.validate():
        # add comment to article
        return redirect(request.path)

    return render_template('article_detail.html', article=article)

rawDescription: Store post data for use after authenticating with Flask-Login


code:
import sys
import time

sys.stdout.write('name=')
last_lenght = 0
with open('names.txt') as names:
    for name in names:
        sys.stdout.write('\b' * last_lenght)    # go back
        sys.stdout.write(' ' * last_lenght)     # clear last name
        sys.stdout.write('\b' * last_lenght)    # reposition
        sys.stdout.write(name.strip())
        sys.stdout.flush()
        last_lenght = len(name.strip())
        time.sleep(0.5)

rawDescription: printing dynamically string in one line in python

description: Printing dynamically string in one line in python


code: result = "".join([el for el in sequence_lines2 if not len(el) % 60])

rawDescription: Joining Elements in a List according to length - Python


code:
import json

with open("mel1.json") as fo:
    data1 = json.load(fo)

with open("mel2.json") as fo:
    data2 = json.load(fo)

data1.update(data2)

with open("melout.json", "w") as fo:
    json.dump(data1, fo)

rawDescription: How to merge two JSON file with pandas

description: Merge two JSON file with pandas


code:
ax = df[['price','cost']].plot(kind = 'bar',stacked = True,color = ['grey','navy'])
ax.get_children()[3]
ax.get_children()[3].get_width()
ax.get_children()[3].get_bbox()
plt.plot(df.index+0.5, df['net'],color = 'orange',linewidth=2.0)

rawDescription: How to add a line on a pandas bar plot in matplotlib?

description: Add a line on a pandas bar plot in matplotlib


code:
from itertools import izip
from numpy.random import randint

g = Graph()
g.add_vertex(100)
# insert some random links
for s,t in izip(randint(0, 100, 100), randint(0, 100, 100)):
    g.add_edge(g.vertex(s), g.vertex(t))

vprop_double = g.new_vertex_property("double")            # Double-precision floating point
vprop_double[g.vertex(10)] = 3.1416

vprop_vint = g.new_vertex_property("vector<int>")         # Vector of ints
vprop_vint[g.vertex(40)] = [1, 3, 42, 54]

eprop_dict = g.new_edge_property("object")                # Arbitrary python object.
eprop_dict[g.edges().next()] = {"foo": "bar", "gnu": 42}  # In this case, a dict.

gprop_bool = g.new_edge_property("bool")                  # Boolean
gprop_bool[g] = True

rawDescription: Adding edge weights and scaling drawn edge lengths in graph_tool


code:
import os, sys
PROJECT_ROOT = os.path.join(os.path.realpath(os.path.dirname(__file__)), os.pardir)
sys.path.append(PROJECT_ROOT)

# Now you can import from the django_project package
from django_project.django_app1.utils import bar1
from django_project.django_app2 import bar2

rawDescription: Python - How to PYTHONPATH with a complex directory structure?


code:
df = DataFrame({'column': ['A', 'B', 'C', 'P', 'Z']})
df['column'].replace('P', 'Z')

rawDescription: Python is there a fill specific cell value function for pandas?


code:
import subprocess
p1 = Popen(["fping", '-C10', '-B1', '-p500','-r1', '-s', '172.29.172.106'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
output,error = p1.communicate()

rawDescription: Python subprocess Popen stdout to variable only


code:
li = [["user1", 100], ["user2", 234], ["user3", 131]]

import operator

sorted(li, key=operator.itemgetter(1))   # Ascending order
sorted(li, key=operator.itemgetter(1), reverse=True)  # Reverse Sort

rawDescription: python: sort a list of lists by an item in the sublist

description: Python: sort a list of lists by an item in the sublist


code:
def find_acronym():

    found = False

    # if search term in database returns acronym and expansion
    for abbr, text in acronyms.items():
        if abbr == search_analyte.get():
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
            found = True
        elif str(search_analyte.get()) in text:
            expansion.insert(0.0,'{0:>6}: {1: <10}\n'.format(abbr, text))
            found = True

    # if search term not in database
    if not found:
        expansion.insert(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is  not in the database.','Add,if appropriate'))

rawDescription: logic in if statement flow in Python

description: Logic in if statement flow in Python


code:
"""
This module contains methods and classes
"""

class class_:
    """
    This class is well... a class
    """
    def method(self, in_):
        """
        This method takes one argument: in_ and returns it
        """
        return in_

rawDescription: Add help to python module

description: Add help to python module


code:
one = open("sample-r1.txt",'r')
two = open("sample-r2.txt",'r')
k=[]
h=[]
for line in one:
    tmp=line.rstrip().split('\t')
    if len(tmp)>1:
        k.append ( tmp )
for record in two:
    tmp=record.rstrip().split('\t')
    if len(tmp)>1:
        h.append ( tmp )
i=0
j=0
newList=[]
while i < len(k) and j < len(h):
    if k[i][1] <= h[j][1]:
        newList.append(k[i])
        i+=1
    else:
        newList.append(h[j])
        j+=1
while i < len(k):
    newList.append(k[i])
    i+=1
while j < len(h):
    newList.append(h[j])
    j+=1
for row in newList:
    print("\t".join(row))

rawDescription: merge and sort two sorted text file

description: Merge and sort two sorted text file


code:
try:
    # filter data
    fdata = []
    fdata1 = PropertyValue()
    fdata1.Name = "UseTaggedPDF"
    fdata1.Value = True
    fdata.append(fdata1)

    fdata.append(fdata1)

    args = []
    arg1 = PropertyValue()
    arg1.Name = "FilterName"
    arg1.Value = "writer_pdf_Export"
    arg2 = PropertyValue()
    arg2.Name = "FilterData"
    arg2.Value = uno.Any("[]com.sun.star.beans.PropertyValue", tuple(fdata) )
    args.append(arg1)
    args.append(arg2)

    document.storeToURL(outputUrl, tuple(args))
finally:
    document.close(True)

rawDescription: Python-UNO bridge: change PDF export options


code:
def sortList(sortMe):
    tmp = []
    for i in xrange(len(sortMe)):
        tmp.append(sortMe[i])
        tmp.append(sortMe[len(sortMe)-(i+1)])
    return tmp[:len(sortMe)]

print(sortList(['a','b','c','d','e','f']))

rawDescription: List reorder and Encoding

description: List reorder and Encoding


code: df2[df1 != df2].dropna(how='all')

rawDescription: Remove empty row from DataFrame in pandas


rawDescription: Re to replace & with name entity

description: Re to replace & with name entity


code:
src = {"a": 1, "aBar": 2, "b": 3, "bBar": 4}
d = {key: src[key] for item in 'ab' for key in (item, item+'Bar')}

rawDescription: Is there a Pythonic way to iterate over an "expanded" source list?


code:
from matplotlib.ticker import MaxNLocator
plt.gca().yaxis.set_major_locator(MaxNLocator(3))

rawDescription: Changing the count of numbers of the y-axis (Python, matplotlib.pyplot)


code:
self.pixels_array = array('B')

def extract_pixels_from_image(self):
    pixels = self.image.pixels
    for y in range(self.height):
        for x in range(self.width):

            i = (x + (self.height - 1 - y) * self.width) * 4

            r = int(max(0, min(255, 255 * pixels[i])))
            g = int(max(0, min(255, 255 * pixels[i + 1])))
            b = int(max(0, min(255, 255 * pixels[i + 2])))
            a = int(max(0, min(255, 255 * pixels[i + 3])))

            self.pixels_array.extend([r, g, b, a])

rawDescription: Why is array filling slow in python

description: Why is array filling slow in python


code:
server = HTTPServer(application)
server.listen(8888)
tornado.ioloop.IOLoop.instance().start()

#somewhere in your code
server.stop()

rawDescription: Stopping a tornado application

description: Stopping a tornado application


code:
foo = Bar()
(foo.setSomething(something1)
     .setStatus('vertical')
     .setAttributes(attributes))

rawDescription: Python3.2 vertical chaining

description: Python3.2 vertical chaining


code:
def apply_until( fun, vals ):
    for val in vals:
        if fun(val):
            break

rawDescription: Is there a "map until" or "map while" construct in python?


code:
#read the contents of the file
text = open("yourfile").read()
#get the underlying TextBuffer object of the TextView and set its text
textbox.get_buffer().set_text(text)

rawDescription: How do I read from a text file into a text box?

description: Read from a text file into a text box


code:
with open('data.json', 'w') as outfile:
    outfile.write(out)

rawDescription: Json print output in python different from write output because of escaped characters


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
tab = [[1.0000, 3.14159], [1, 2], [2, 1]]
tab2 = [['%.2f' % j for j in i] for i in tab]

ytable = plt.table(cellText=tab2, colLabels=['Col A','Col B'],
                    colWidths=[.5]*2, loc='center')
ytable.set_fontsize(34)
ytable.scale(1, 4)
plt.show()

rawDescription: Matplotlib Row heights table property

description: Matplotlib Row heights table property


code:
x
y
indices = np.logical_not(np.logical_or(np.isnan(x), np.isnan(y)))
x = x[indices]
y = y[indices]
x
y

rawDescription: Delete nan AND corresponding elements in two same-length array


code: getbinary(ftp, "subbdy.zip", open(r'C:\Path\to\subbdy.zip', 'wb'))

rawDescription: How to Retrieve a Zip Folder from FTP in Python


code:
from bs4 import BeautifulSoup
import json

soup = BeautifulSoup(driver.page_source)
dict_from_json = json.loads(soup.find("body").text)

rawDescription: how to grab from JSON in selenium python

description: Grab from JSON in selenium python


rawDescription: Join grouped elements of list into one list with single-element in Python


code:
def find_match (my_hexplode_chains):

    x =  0
    len_chain = len(my_hexplode_chains)
    while x <= len_chain:
        y = x + 1
        for tile_id_x, tile_x in my_hexplode_chains[x].items():
            for tile_id_y, tile_y in my_hexplode_chains[y].items():
                if tile_id_y in tile_x["neighbours"]:
                    my_hexplode_chains[x].update(my_hexplode_chains[y])
                    del my_hexplode_chains[y]
                    return True
        x += 1
    return False

rawDescription: Creating a list of dictionaries where each dictionary contains another dictionary as values


code:
line2 = new_file.next() # now pointing at line 3
if line2[0] == "P":
    for _ in xrange(4):
        new_file.next() # skip lines 3, 4, 5, 6
else:
    new_file.next() # skip line 3 only

rawDescription: move through lines after using readline() python

description: Move through lines after using readline() python


code: '\n'.join(elem[0] for elem in queryresult)

rawDescription: python convert tuple to string

description: Python convert tuple to string


code:
class GameClass:
    def __init__( self, fc, pc ):
        self.Field = fc
        self.Player = pc

class PlayerClass:
    def __init__( self, fc ):
        self.fc = fc

    def DoMagicHere( self ):
        # use self.fc
        pass

fc=FieldClass()
pc=PlayerClass(fc)
gc=GameClass(fc, pc)

rawDescription: Python OOP - Class relationships

description: Python OOP - Class relationships


code:
import numpy as np
p = np.array([ 1,2,3,4,5,6,7,8,9,10,11,12])
p_reshape = p.reshape(4,3)
p_reshape
np.unravel_index(5, p_reshape.shape)

rawDescription: How to return the position (Index) of an element after reshaping from 1D to 2D numpy array?

description: Return the position (Index) of an element after reshaping from 1D to 2D numpy array


code:
import sys
from PyQt4 import QtGui, QtCore

class Dialog(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)

        layout = QtGui.QVBoxLayout()
        self.setLayout(layout)

        self.b1 = QtGui.QPushButton('flash splash')
        self.b1.clicked.connect(self.flashSplash)

        layout.addWidget(self.b1)

    def flashSplash(self):
        # Be sure to keep a reference to the SplashScreen
        # otherwise it'll be garbage collected
        # That's why there is 'self.' in front of the name
        self.splash = QtGui.QSplashScreen(QtGui.QPixmap('/path/to/image.jpg'))

        # SplashScreen will be in the center of the screen by default.
        # You can move it to a certain place if you want.
        # self.splash.move(10,10)

        self.splash.show()

        # Close the SplashScreen after 2 secs (2000 ms)
        QtCore.QTimer.singleShot(2000, self.splash.close)

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

    main = Dialog()
    main.show()

    sys.exit(app.exec_())

rawDescription: Briefly flash a picture

description: Briefly flash a picture


code: ws.sort(key=lambda datum: (datum['date'], datum['type'], datum['location']))

rawDescription: Python: how to sort array of dicts by two fields?


code:
import wx

########################################################################
class SubPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, number):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour("red")

        label = "Sub panel-%s" % number
        lbl = wx.StaticText(self, label=label)

        sizer = wx.BoxSizer()
        sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(sizer)

########################################################################
class ColorPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, number, color, sub_panels):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(color)

        label = "Panel-%s" % number
        lbl = wx.StaticText(self, label=label)

        v_sizer = wx.BoxSizer(wx.VERTICAL)
        for i in range(sub_panels):
            p = SubPanel(self, i+1)
            v_sizer.Add(p, 0, wx.ALL|wx.EXPAND|wx.CENTER, 10)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(v_sizer, 0, wx.ALL, 5)
        sizer.Add(lbl, 0, wx.ALL|wx.CENTER, 5)
        self.SetSizer(sizer)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        hsizer = wx.BoxSizer(wx.HORIZONTAL)
        v_sizer = wx.BoxSizer(wx.VERTICAL)

        colors = [("green", 3),
                  ("yellow", 2),
                  ("light blue", 2),
                  ("purple", 2)]
        count = 1
        for color, subpanel in colors:
            panel = ColorPanel(self, count, color, subpanel)
            hsizer.Add(panel, 1, wx.EXPAND)
            count += 1

        orange_panel = ColorPanel(self, count, "orange", 0)
        v_sizer.Add(hsizer, 1, wx.EXPAND)
        v_sizer.Add(orange_panel, 1, wx.EXPAND)

        self.SetSizer(v_sizer)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Panels!", size=(600,400))
        panel = MainPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: Arranging the panels automatically in wxPython


code:
treeview.freeze_child_notify()
treeview.set_model(None)

# Add rows to the model
# ...

treeview.set_model(model)
treeview.thaw_child_notify()

rawDescription: Speed up image loading in a gtk.IconView


code:
class MyInfoForm(forms.Form):
    firstname = forms.CharField(label=u' First name :', max_length=30)
    def __init__(self, *args,**kwargs):
        self.flag= kwargs.pop('flag', None)
        super(MyInfoForm, self).__init__(*args, **kwargs)
        if self.flag:
            # XXX IMPORTANT :
            # you want to access self.fields['fieldname']
            # NOT self.fieldname
            self.fields["firstname"].label = "Yadda"

rawDescription: Python Class variable initialization access variables out side init


code:
od = OrderedDict((('a', 'first'), ('b', 'second')))
od
items = od.items()  # list(od.items()) in Python3
items.reverse()
OrderedDict(items)

rawDescription: Order of keys in Python dictionary

description: Order of keys in Python dictionary


rawDescription: Geneate a random integer or to predefined int


rawDescription: Find an Exact Tuple Match in a List of Tuples and Return Its Index


code:
entr = [list(int(x) for x in input().split())
        for i in range(int(input()))]
N = len(entr)

rawDescription: Multiline user input with list comprehension in Python 3


code:
l = [1, 2, 3, 4]
sum([i*j for i,j in list(itertools.combinations(l, 2))])

rawDescription: Sum of product of combinations in a list


code:
a = [20, 10, 9, 8, 8, 7, 6, 2, 1]

def func(a, lim):
    out = []
    temp = []
    for i in a:
        if i > lim:
            out.append([i])
        else:
            temp.append(i)
            if sum(temp) > lim:
                out.append(temp)
                temp = []
    return out

print(func(a, 15))
# [[20], [10, 9], [8, 8], [7, 6, 2, 1]]

rawDescription: Python - summing and grouping through a list


rawDescription: How to execute a nested loop with dataframes for regression analysis

description: Execute a nested loop with dataframes for regression analysis


code:
thestring = """['name', 'quest', 'favorite color']"""
theobject = ast.literal_eval(thestring)

rawDescription: Decoding json in jython using only default libraries


code:
import os, sys, arcpy

InFolder = sys.argv[1] # make this a hard set path if you like

arcpy.env.workspace = InFolder
CapitalKeywordsToRemove = ["_AREAS","_LINES"]# MUST BE CAPITALS

DS_List = arcpy.ListFeatureClasses("*.shp","ALL") # Get a list of the feature classes (shapefiles)
for ThisDS in DS_List:
    NewName = ThisDS # set the new name to the old name

    # replace key words, searching is case sensitive but I'm trying not to change the case
    # of the name so the new name is put together from the original name with searching in
    # upper case, use as many key words as you like

    for CapKeyWord in CapitalKeywordsToRemove:
        if CapKeyWord in NewName.upper():
            # remove the instance of CapKeyWord without changing the case
            NewName = NewName[0:NewName.upper().find(CapKeyWord)] + NewName[NewName.upper().find(CapKeyWord) + len(CapKeyWord):]

    if NewName != ThisDS:
        if not arcpy.Exists(NewName):
            arcpy.AddMessage("Renaming " + ThisDS + " to " + NewName)
            arcpy.Rename_management(ThisDS , NewName)
        else:
            arcpy.AddWarning("Cannot rename, " + NewName + " already exists")
    else:
        arcpy.AddMessage("Retaining " + ThisDS)

rawDescription: How to get rid of suffixes from several shapefiles in a folder

description: Get rid of suffixes from several shapefiles in a folder


rawDescription: Python Scrapy XPathSelector

description: Python Scrapy XPathSelector


code:
item_num = int(input("Please enter the number of items on your grocery  list.\n"))
item_list = [str(input("What is the item #" + str(count + 1) + " on your list?\n")) for count in range(item_num)]
item_price = [int(input("Enter the price of the item \n")) for i in range(item_num)]
item_quan = [int(input("What is the quantity of item #" + str(count + 1) + " that you bought?\n")) for count in range(item_num)]
subtotal = sum(int(quan * price) for quan, price in zip(item_quan, item_price))
print ("The subtotal is...")
print (subtotal)
tax = 0.07 * subtotal
total = subtotal + tax
print ("The grand total is...")
print (total)

rawDescription: Python Grocery Program - How to get each item multiplied by its quantity separately?


code:
from django.conf import settings

class OriginalModel(Model):
    ...
    def save(self, *args, **kwargs):
        if not settings.TESTING:
            # Do some file system interaction, but not during testing.
            pass
        # Now save instance as per normal.
        return super(originalModel, self).save(*args, **kwargs)

rawDescription: Django - call original and overriden save method


code:
import pylab as plt
x = plt.linspace(0,2,100)
y = plt.linspace(0,10,100)

z = [[plt.sinc(i) for i in x] for j in y]

CS = plt.contourf(x, y, z, 20, # \[-1, -0.1, 0, 0.1\],
                        cmap=plt.cm.rainbow)
plt.colorbar(CS)
plt.plot(x,2+plt.sin(y), "--k")

rawDescription: python matplotlib: how to use fill_between with a colormap to fill the background of a 2d plot?

description: Python matplotlib: how to use fill_between with a colormap to fill the background of a 2d plot


code:
class User(models.Model):
    username = models.CharField(max_length=100) #Id is automatically generated by Django
    password = models.CharField(max_length=100)

    def __unicode__(self):
        return self.username

class File(models.Model):
    users = models.ManyToManyField(User, through='UserFile')
    file_name = models.CharField(max_length=100)
    type = models.CharField(max_length=10)

class UserFile(models.Model):
    user = models.ForeignKey(User)
    file = models.ForeignKey(File)
    # Should probably use CharField if you know the length
    session_id = models.TextField()

rawDescription: Foreign key not shown with Many to Many Relationship in Django?


code:
def duplicateDel():
    f1 = csv.reader(open('file1.csv', 'rb'))
    writer = csv.writer(open("file2.csv", "wb"))
    x = set()
    for row in f1:
        if row[3] not in x:
            writer.writerow(row)
            x.add( row[3] )

duplicateDel()

rawDescription: Why does this python function not work if I wrap it in a def() call?


code:
for k,v in d.iteritems():
    if k.startswith('ev'):
        result = v
        break
else:
    raise KeyError()  # or set to default value

rawDescription: Finding a key in a dictionary without knowing its full name


code:
def filter_history(old, new, name, repoPath):
    command = """'
        an="$GIT_AUTHOR_NAME"
        am="$GIT_AUTHOR_EMAIL"
        cn="$GIT_COMMITTER_NAME"
        cm="$GIT_COMMITTER_EMAIL"

        if [[ "$GIT_COMMITTER_EMAIL" == |old|* ]]
        then
            cn="|name|"
            cm="|new|"
        fi
        if [[ "$GIT_AUTHOR_EMAIL" == |old|* ]]
        then
            an="|name|"
            am="|new|"
        fi

        export GIT_AUTHOR_NAME="$an"
        export GIT_AUTHOR_EMAIL="$am"
        export GIT_COMMITTER_NAME="$cn"
        export GIT_COMMITTER_EMAIL="$cm"
    '
    """

#Do string replace
    command = command.replace("|old|", old)
    command = command.replace("|new|", new)
    command = command.replace("|name|", name)

    subprocess.Popen(['git filter-branch --env-filter', command],cwd=os.path.dirname(repoPath), shell=True)

rawDescription: Using git filter-branch with Python subprocess module


code:
button = getattr(self, 'flipButton')
button.setEnabled(True)

rawDescription: Python variable variables without eval?

description: Python variable variables without eval


code: packages = ['.']

rawDescription: How to add a Python file to the installed targets with Cython and distutils?

description: Add a Python file to the installed targets with Cython and distutils


code:
import base64

## To encrypt:
base64.b64encode("XYZ")
## you got 'WFla'

## To decrypt:
base64.b64decode("WFla")
# you got 'XYZ'

rawDescription: How to encrypt password in Python pysftp?

description: Encrypt password in Python pysftp


code: list(set(temp1) - set(temp2))

rawDescription: Get difference between two lists

description: Get difference between two lists


code:
from sklearn.neighbors.regression import KNeighborsRegressor, check_array, _get_weights

class MedianKNNRegressor(KNeighborsRegressor):
    def predict(self, X):
        X = check_array(X, accept_sparse='csr')

        neigh_dist, neigh_ind = self.kneighbors(X)

        weights = _get_weights(neigh_dist, self.weights)

        _y = self._y
        if _y.ndim == 1:
            _y = _y.reshape((-1, 1))

        ######## Begin modification
        if weights is None:
            y_pred = np.median(_y[neigh_ind], axis=1)
        else:
            # y_pred = weighted_median(_y[neigh_ind], weights, axis=1)
            raise NotImplementedError("weighted median")
        ######### End modification

        if self._y.ndim == 1:
            y_pred = y_pred.ravel()

        return y_pred

X = np.random.rand(100, 1)
y = 20 * X.ravel() + np.random.rand(100)
clf = MedianKNNRegressor().fit(X, y)
print(clf.predict(X[:5]))
# [  2.38172861  13.3871126    9.6737255    2.77561858  17.07392584]

rawDescription: Predict with sklearn-KNN using median (instead of mean)


code:
cmd = 'ping 192.168.1.1'
output = subprocess.check_output(cmd.split())

rawDescription: loading another program that takes in a textfile in a program subprocess

description: Loading another program that takes in a textfile in a program subprocess


code:
orig = [1,2,3,4,5]
sampled_vec = [3,1,3]
indices = [orig.index(i) for i in sampled_vec]
indices

rawDescription: Finding indices of elements in vector

description: Finding indices of elements in vector


code:
revdict = dict([(mydict[key],key) for key in mydict])
revdict['myValue']

rawDescription: Getting the key for a value

description: Getting the key for a value


rawDescription: Setting value of numpy array based on multiple criteria


code:
a = {'device': {'version': '1.2.3'}}
b = {'device': {'name': 'testdevice'}}
c = {'other':  {'cost': '1000'}}
to_merge = [a,b,c]
d = {}
for m in to_merge:
    for k,v in m.items():
        d.setdefault(k, {}).update(v)

d

rawDescription: How to merge two python dictionaries with elements on the same level?

description: Merge two python dictionaries with elements on the same level


code:
from PIL import Image
import numpy
import matplotlib.pyplot as plt
import glob

imageFolderPath = '/home/B/Pictures/'
imagePath = glob.glob(imageFolderPath+'/*.JPG')

im_array = numpy.array( [numpy.array(Image.open(imagePath[i]).convert('L'), 'f') for i in range(len(imagePath))] )

rawDescription: Array of images in python

description: Array of images in python


code:
class KeyList(models.Model):
    key_one = models.ForeignKey(KeyOne)
    key_two = models.ForeignKey(KeyTwo)
    key_three = models.ForeignKey(KeyThree)
    list = models.CharField()
    class Meta:
        unique_together = (("key_one", "key_two", "key_three"),)

rawDescription: Django unique combination of foreign keys