code:
import nibabel as nib
import numpy as np

data = np.arange(4*4*3).reshape(4,4,3)

new_image = nib.Nifti1Image(data, affine=np.eye(4))

rawDescription: Creating a nifti file from a numpy array


code:
class CommentForm(forms.Form):
    name = forms.CharField(
                widget=forms.TextInput(attrs={'class':'special'}))
    url = forms.URLField()
    comment = forms.CharField(
               widget=forms.TextInput(attrs={'size':'40'}))

rawDescription: Disable autocomplete on textfield in Django?


code:
class Bunch(object):
    def __init__(self, **kwds):
        self.__dict__.update(kwds)

rawDescription: Namedtuple like class

description: Namedtuple like class


code:
from gi.repository import Gtk

class AnotherWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="GCT")
        self.connect("destroy", lambda x: Gtk.main_quit())

        self.add(Gtk.Label("This is another window"))
        self.show_all()

class Main(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="GCT")
        self.connect("destroy", lambda x: Gtk.main_quit())

        self.box = Gtk.Box()
        self.set_default_size(300, 300)
        self.set_position(Gtk.WindowPosition.CENTER)
        self.table = Gtk.Table(6, 5)

        self.button = Gtk.Button("sub-window")
        self.button.connect("clicked", self.open_window)
        self.table.attach(self.button, 0, 2, 0, 1)

        self.box.add(self.table)
        self.add(self.box)
        self.show_all()

    def open_window(self, win):
        subw = AnotherWindow()

def main():
    m = Main()
    Gtk.main()
    return 0

if __name__ == '__main__':
    main()

rawDescription: Creating a sub-window with PyGTK

description: Creating a sub-window with PyGTK


code:
# Build mask
mask = np.zeros(image_array.shape, dtype=np.uint8)
cv2.circle(mask, max_loc, circle_radius, (255, 255, 255), -1, 8, 0)

# Apply mask (using bitwise & operator)
result_array = image_array & mask

# Crop/center result (assuming max_loc is of the form (x, y))
result_array = result_array[max_loc[1] - circle_radius:max_loc[1] + circle_radius,
                            max_loc[0] - circle_radius:max_loc[0] + circle_radius, :]

rawDescription: Point detection and circle area selection


code:
def mergesort(lst):
    '''Recursively divides list in halves to be sorted'''
    if len(lst) == 1:
        return lst, 0
    middle = len(lst)/2
    left = mergesort(lst[:middle])[0]  # Ignore intermediate splits
    right = mergesort(lst[middle:])[0]  # Ignore intermediate splits
    sortedlist, splits = merge(left, right)
    return sortedlist, splits

rawDescription: Merge sort to count split inversions in Python


code:
from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def my_view(request):
    return HttpResponse('Hello world')

rawDescription: httplib - CSRF token

description: Httplib - CSRF token


code:
for n in range(15):
    if n == 100:
        print(n)
        break

rawDescription: Opposite of Python for ... else

description: Opposite of Python for ... else


rawDescription: Python JSON: NameError: name 'false' is not defined


code:
import pandas as pd

a_interp = pd.DataFrame(a).interpolate(method='linear', axis=0).values
plt.contourf(xa, ya, a_interp, 100)
plt.show()

rawDescription: Interpolate NaN values in pyplot without using scipy.interpolate.griddata


code:
PySys_SetPath(".");
mymod = PyImport_ImportModule("your_DLL_name or Py_module_name");

rawDescription: Loading c dll in python

description: Loading c dll in python


code:
from json import loads, dumps
from collections import OrderedDict

def to_dict(input_ordered_dict):
    return loads(dumps(input_ordered_dict))

rawDescription: how to convert a nested OrderedDict to dict?

description: Convert a nested OrderedDict to dict


code:
d = {"answer": 42}
"the answer is %(answer)d" % d

rawDescription: what do %(xyz)s representation mean in python

description: What do %(xyz)s representation mean in python


code:
from itertools import permutations
import random
dic = {k:random.randint(1, 1000) for k in permutations('abcde', 3)}

list(partial_match(('a', 'b', None), dic))
list(partial_match(('a', None, 'b'), dic))
[dic[('a', 'b', x)] for x in 'cde']
[dic[('a', x, 'b')] for x in 'cde']

rawDescription: partial match dictionary key(of tuples) in python

description: Partial match dictionary key(of tuples) in python


code: os.waitpid(pid, 0)

rawDescription: Python + SSH Password auth (no external libraries or public/private keys)?


code:
import sys

if sys.version_info[0] < 3:
    infile = open(filename, 'rb')
else:
    infile = open(filename, 'r', newline='', encoding='utf8')

with infile as csvfile:
    ...

rawDescription: Python 2 and 3 csv reader

description: Python 2 and 3 csv reader


rawDescription: Unable to get xpath for screen scraping

description: Unable to get xpath for screen scraping


code:
class Base(object):
    def __init__(self, args):
        # perform some initialization
        pass
    def calculate(self):
        # do stuff
        pass
    @classmethod
    def precalculated(cls, args):
        # construct first
        newBase = cls(args)
        # now call method "calculate"
        newBase.calculate()
        return newBase

class Derived(Base):
    def __init__(self, args, additional_attr):
        super(Derived, self).__init__(args)
        # do some work and create new instance attributes
        self.additional_attr = additional_attr
    @classmethod
    def precalculated(cls, args, additional_attr): # also if you want
        newDerived = cls(args, additional_attr)
        newDerived.calculate()
        return newDerived

newBase = Base('foo')
precalculatedBase = Base.precalculated('foo')
newDerived = Derived('foo', 'bar')
precalculatedDerived = Derived.precalculated('foo', 'bar')

rawDescription: python: calling super().__init__ too early in the __init__ method?

description: Python: calling super().__init__ too early in the __init__ method


code:
f = open('some.log', 'r')
while True:
    line = ''
    while len(line) == 0 or line[-1] != '\n':
        tail = f.readline()
        if tail == '':
            time.sleep(0.1)          # avoid busy waiting
            # f.seek(0, io.SEEK_CUR) # appears to be unneccessary
            continue
        line += tail
    process(line)

rawDescription: Python parsing log file to extract events in real time


code:
import subprocess
addr = '10.20.30.40'
subprocess.call([ 'ssh', addr ])

rawDescription: Python script to create SSH connection

description: Python script to create SSH connection


code:
def gcd(a, b):
   while b != 0:
        c = a % b
        a, b = b, c  # tuple assignment FTW!
        if b == 0:
            break
   return a

while True:
    m = int(input("First number (0 to stop): "))
    if m == 0:
        break
    n = int(input("Second number: "))
    print("The greatest common divisor of {0} and {1} is {2}".format(n, m, abs(gcd(m, n))))

rawDescription: How to break out of a while loop in Python 3.3

description: Break out of a while loop in Python 3.3


code:
from Tkinter import *
def roll(): pass
def links(): pass
def create(): pass
root=Tk()
root.title("CIME")

rows = 0
def create_detail_frame():
    global rows
    step = LabelFrame(root,text="Enter Details:")
    step.grid(row=rows, columnspan=7, sticky='W',padx=5, pady=5, ipadx=5, ipady=5)
    Label(step,text="Competitors",font = "Arial 8 bold italic").grid(row=0,sticky='E', padx=5, pady=2)
    Label(step,text="Keywords",font = "Arial 8 bold italic").grid(row=1,sticky='E', padx=5, pady=2)
    Label(step,text="Project Name",font = "Arial 8 bold italic").grid(row=2,sticky='E', padx=5, pady=2)
    e1 = Entry(step)
    e2 = Entry(step)
    e3 = Entry(step)
    e1.grid(row=0,column=1,columnspan=7, sticky="WE", pady=3,padx=5)
    e2.grid(row=1,column=1,columnspan=7, sticky="WE", pady=3,padx=5)
    e3.grid(row=2,column=1,columnspan=7, sticky="WE", pady=3,padx=5)
    Button(step,text ="Search Words",width=10,font = "Arial 8 bold    italic",activebackground="red",command=roll).grid(row=3,column=0,sticky=W,pady=4,padx=5)
    Button(step,text="Google Search",width=10,font = "Arial 8 bold italic",command=links).grid(row=3,column=2,sticky=W,pady=4,padx=5)
    Button(step,text="Extraxt Text",width=10,font = "Arial 8 bold italic",command = create).grid(row=3,column=4,sticky=W,pady=4,padx=5)
    rows += 1

    # Reposition text, scroll
    #scr.grid_forget()
    #tex.grid_forget()
    #scr.grid(row=rows, padx=1, column=7, rowspan=15, columnspan=1, sticky=NS)
    #tex.grid(row=rows,column=1)

    # Reposition text, scroll
    scr.grid(row=rows)
    tex.grid(row=rows)

tex = Text(master=root)
scr=Scrollbar(root,orient =VERTICAL,command=tex.yview)
scr.grid(row=1, padx=1, column=7, rowspan=15, columnspan=1, sticky=NS)
tex.grid(row=1,column=1)
tex.config(yscrollcommand=scr.set,font=('Arial', 8, 'bold', 'italic'))

Button(root, text='Add detail frame', command=create_detail_frame).grid(row=0, column=7)
create_detail_frame()

mainloop()

rawDescription: Tkinter adding label frames

description: Tkinter adding label frames


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

signal = 1.2*np.sin(np.linspace(0, 30, 2000))
pos_signal = signal.copy()
neg_signal = signal.copy()

pos_signal[pos_signal <= 0] = np.nan
neg_signal[neg_signal > 0] = np.nan

#plotting
plt.style.use('fivethirtyeight')
plt.plot(pos_signal, color='r')
plt.plot(neg_signal, color='b')
plt.savefig('pos_neg.png', dpi=200)
plt.show()

rawDescription: Pyplot - change color of line if data is less than zero?


code:
import readline
import subprocess
import rlcompleter

def display_matches(substitutions, matches, longest_match_length):
    m = '\n'.join(matches) + '\n'
    proc = subprocess.Popen('column | less', shell=True, stdin=subprocess.PIPE)
    # python2:
    proc.communicate(m)
    # python3:
    # proc.communicate(m.encode('utf-8'))

readline.set_completion_display_matches_hook(display_matches)
readline.parse_and_bind('tab: complete')

rawDescription: Python Tab Completion Pager

description: Python Tab Completion Pager


code:
class Server(object):
    pass

for k, v in services:
    setattr(Server, k, v)

rawDescription: How to instantiate class in python dynamically?

description: Instantiate class in python dynamically


code:
class TestY(TestCase):

    def test_model_relation(self):
        x = X.objects.create(name="test1")
        y = Y(event=X.objects.create(name="test2"))
        y.full_clean()  # `event` correctly set. This should pass
        y.save()
        self.assertEqual(Y.objects.filter(event__name="test2").count(), 1)

    def test_model_relation__event_missing(self):
        x = X.objects.create(name="test1")
        y = Y()  # Y without `event` set
        with self.assertRaises(ValidationError):
            y.full_clean()
            y.save()
        self.assertEqual(Y.objects.filter(event__name="test2").count(), 0)

rawDescription: Unit Test foreign key constraints in Django models


rawDescription: Unicode HTML Conversion to ASCII in Python


rawDescription: pandas: bypassing numerical index

description: Pandas: bypassing numerical index


code:
from types import MethodType
from pandas import DataFrame, MultiIndex

def _gencmd(df, pandas_as='pd'):
    """
    With this addition to DataFrame's methods, you can use:
        df.command()
    to get the command required to regenerate the dataframe df.
    """
    if pandas_as:
        pandas_as += '.'
    index_cmd = df.index.__class__.__name__
    if type(df.index)==MultiIndex:
        index_cmd += '.from_tuples({0}, names={1})'.format([i for i in df.index], df.index.names)
    else:
        index_cmd += "({0}, name='{1}')".format([i for i in df.index], df.index.name)
    return 'DataFrame({0}, index={1}{2}, columns={3})'.format([[xx for xx in x] for x in df.values],
                                                                pandas_as,
                                                                index_cmd,
                                                                [c for c in df.columns])

DataFrame.command = MethodType(_gencmd, None, DataFrame)

rawDescription: Given a pandas dataframe, is there an easy way to print out a command to generate it?


rawDescription: Applying Conditional Exclusions to Pandas DataFrame using Counts


code:
class Example2(Item):

    def __init__(self, base):
         self.base = base
         self.base.get_item(Example1()).do_something()

         # or if don't want to store base, and just call its method once:
         base.get_item(Example1()).do_something()

if __name__ == '__main__':

    base = Base()
    base.add_item(Example1())
    base.add_item(Example2(), base)

rawDescription: Python oop question

description: Python oop question


code:
import struct
struct.unpack('!f', '41973333'.decode('hex'))[0]
struct.unpack('!f', '41995C29'.decode('hex'))[0]
struct.unpack('!f', '470FC614'.decode('hex'))[0]

rawDescription: Convert hex to float

description: Convert hex to float


code:
df.index = df['value']
df.reindex(np.arange(df.value.min(), df.value.max() + 1)).fillna(0)

rawDescription: How can I fill in a missing values in range with Pandas?

description: Fill in a missing values in range with Pandas


code:
df
df.groupby("col2")
df.groupby("col2").median()
df.groupby("col2").median().reset_index()

rawDescription: Python - Pandas - DataFrame reduce rows

description: Python - Pandas - DataFrame reduce rows


code:
import pylab as pl

fig= pl.figure( figsize=(5,5) )
ax  = fig.add_subplot(111)

ax.scatter(df.index, df.Amount, s=20, c=df.ID)

rawDescription: Matplotlib Plot time series with colored points Pandas (Python)


code:
#for getting
total = 0
shard_keys = []
for i in range(20): #20 shards
    key_name = shard + str(i)
    shard_keys.append(db.Key.from_path('Counter', key_name))
counters = db.get(shard_keys)
for counter in counters:
    if counter:
        total += counter.count

#for incrementing a shard
import random
key_name = 'shard' + str(int(random.random()*20)) #choose a random shard
counter = Counter.get_by_key_name(key_name) #try to retrieve from datastore
if not counter:
    counter = Counter(key_name=key_name) #shard doesn't exist, create one
counter.count += 1
db.put(counter)

rawDescription: App Engine Shard Counters and High Replication Datastore


code: cluster = DBSCAN(eps=1.0, min_samples=1,metric=lambda X, Y: distance.normalized_euclidean(X, Y, SD=stdv))

rawDescription: How to implement callable distance metric in scikit-learn?

description: Implement callable distance metric in scikit-learn


code:
def get_all_children(tree, item=""):
    children = tree.get_children(item)
    for child in children:
        children += get_all_children(tree, child)
    return children

rawDescription: How to get the item count in tkinter treeview?

description: Get the item count in tkinter treeview


rawDescription: How do I replace a closed event loop?

description: Replace a closed event loop


rawDescription: How to add up different numbers in a list?

description: Add up different numbers in a list


code:
dict(itertools.izip_longest(l, x))
# {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}

rawDescription: Creating a dictionary from two iterables and consuming both of them


code:
import numpy as np
from numpy import array

A = array([[2, 1, 9],
           [1, 1, 5],
           [7, 4, 1]])
Ind = np.argsort(A)

B = array([[ 3,  6,  9],
           [ 1,  5,  3],
           [13,  7,  2]])

# an array of the same shape as A and B with row numbers for each element
rownums = np.tile(np.arange(3), (3, 1)).T

new_B = np.take(B, rownums * 3 + Ind)
print(new_B)
# [[ 6  3  9]
#  [ 1  5  3]
#  [ 2  7 13]]

rawDescription: Sort array by other array sort indexing in Python


code:
m = np.arange(2*3*5).reshape((2,3,5))
axis, start, end = 2, 1, 3
target = m[:, :, 1:3]
target
slc = [slice(None)] * len(m.shape)
slc[axis] = slice(start, end)
np.allclose(m[slc], target)

rawDescription: Slicing a numpy array along a dynamically specified axis


code:
def customresize(array, new_size):
    return (array._type_*new_size).from_address(addressof(array))

rawDescription: unknown array length in python ctypes

description: Unknown array length in python ctypes


code: start_point = max(i - words, 0)

rawDescription: Is there an easy way to write this in Python?


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

# Make some random data to represent your r, g, b bands.
ny, nx = 2, 3
r, g, b = [np.random.random(ny*nx).reshape((ny, nx)) for _ in range(3)]

c = np.dstack([r,g,b])

plt.imshow(c, interpolation='nearest')
plt.show()

rawDescription: How to assign RGB color values to grid mesh with matplotlib

description: Assign RGB color values to grid mesh with matplotlib


code:
from shapely.geometry import Polygon, Point, LinearRing

poly = Polygon([(0, 0), (2,8), (14, 10), (6,1)])
point = Point(12,4)

pol_ext = LinearRing(poly.exterior.coords)
d = pol_ext.project(point)
p = pol_ext.interpolate(d)
closest_point_coords = list(p.coords)[0]

rawDescription: Find Coordinate of Closest Point on Polygon Shapely


code:
with open('fname', 'w') as file:
    file.writelines('\t'.join(i) + '\n' for i in nested_list)

rawDescription: Python - Nested List to Tab Delimited File?


code:
# reading from file:
with open('cities.txt') as f:
    lines = f.readlines()

# pre-processing
indices = {line.split()[0]: i for i, line in enumerate(lines)}
distances = [line.split()[1:] for line in lines]

#user input:
start = input("Please enter starting point: ")
end = input("Now please enter ending point: ")

# evaluation:
distance = distances[indices[start]][indices[end]]

# output:
print("Distance between {start} and {end} is {distance} km.".format(**locals()))

rawDescription: Python 3: Getting information from list in list


code:
from google.appengine.ext import ndb
import webapp2
import json

class User(ndb.Model):
  company_              = ndb.KeyProperty(repeated=True)

  @property
  def company(self):
    return {} if not self.company_ else self.company_

  @company.setter
  def company(self, value):
    if value:
      # self.company_ = self.company_.expand(value) if self.company_ else [value]
      # Lists mutate when expanded. Code above was returning None
      self.company_ = self.company_ + [value] if self.company_ else [value]
    else:
      self.company_ = []
    self.put()

class Company(ndb.Model):
  administrator         = ndb.KeyProperty(kind=User, repeated=True)
  manager               = ndb.KeyProperty(kind=User, repeated=True)

class BaseHandler(webapp2.RequestHandler):
  def jwrite(self, **kw):
    return self.response.out.write( json.dumps(kw) )

class require(BaseHandler):
  @staticmethod
  def login(handler):
    def check_requirements(self, *a, **kw):
      if not self.auth.get_user_by_session():
        self.redirect('/', abort=True)
      else:
        return handler(self, *a, **kw)
    return check_requirements

class role(BaseHandler):
  @staticmethod
  def administrator(handler):
    def check_requirements(self, *a, **kw):
      # I didn't care much about optimizing queries
      # since this isn't frequent operation.
      # For more frequent calls, I'd consider projections.
      companies = ndb.get_multi( *a )
      # Next lines checks if current user is administrator
      # for all companies passed to the function
      if not self.user.key in reduce(lambda x, y: x if x != y else y, map(lambda c: c.administrator, companies)):
        return self.jwrite( error = 'Permission denied. Administrator required.' )
      else:
        return handler(self, *a, **kw)
    return check_requirements

  @staticmethod
  def manager(handler):
    def check_requirements(self, *a, **kw):
      companies = ndb.get_multi( *a )
      # Next lines checks if current user is manager
      # or administrator (since admin has higher privileges)
      # for all companies passed to the function
      if not self.user.key in reduce(lambda x, y: x if x != y else y, map(lambda c: c.manager + c.administrator, companies)):
        return self.jwrite( error = 'Permission denied. Manager or Administrator required.' )
      else:
        return handler(self, *a, **kw)
    return check_requirements

class ApiHandler(BaseHandler):
  @require.login
  def post(self, model, action, key=''):
    method = '_post_%s' % model
    try:
      getattr(self, method)(action, key)
    except Exception as error:
      return self.jwrite( error = error)

  def _post_company(self, action, key):

    if action == 'create':
      data = dict(self.request.POST)
      """ Company.create( data ) method:
          Populates Company instance with POST data.
          Assigns first user that created the company
            both administrator and manager roles.
      """
      key_ = Company.create( data )
      if key_:
        self.user.company = key_
      return

    elif action == 'delete':

      @role.administrator
      def delete_all_user_companies(self, *a):
        ndb.delete_multi( *a )
        self.user.company = None
        return

      delete_all_user_companies( self, self.user.company )

    elif action == 'update':

      @role.manager
      def update_company(self, *a ):
        data = dict(self.request.POST)
        """ Company.update( key, data ) method:
            Populates Company instance with POST data
        """
        key_ = Company.update( key, data )
        if key_:
          return

      update_company(self, ndb.Key(Company, key))

rawDescription: ndb models, decorators, nested functions

description: Ndb models, decorators, nested functions


code:
data = """     Week product  quantity        Month
0  201301    coke       1.5           1
1  201302   fanta       1.7           2
2  201304    coke       3.6           5
3  201306  sprite       2.4          10
4  201308   pepsi       2.9          12
"""

import pandas as pd
import io

df = pd.read_csv(io.BytesIO(data), delim_whitespace=True)
df["Month"] = df.Month.map("{:02}".format)

rawDescription: python pandas add leading zero to make all months 2 digits

description: Python pandas add leading zero to make all months 2 digits


code:
class ToFile:
    def __init__(self):
        self.filename = "object_{0}.txt".format(id(self))

    def to_f(self):
        with open(self.filename, 'w') as f:
            f.write(str(self))

class Person(ToFile):
    def __init__(self, name):
        super().__init__()
        self.name = name

    def __str__(self):
        return self.name

rawDescription: How to best implement this Ruby code in Python

description: Best implement this Ruby code in Python


code:
import win32gui,win32process
def get_window_pid(title):
    hwnd = win32gui.FindWindow(None, title)
    threadid,pid = win32process.GetWindowThreadProcessId(hwnd)
    return pid

rawDescription: How do I get a PID from a window title in windows OS using Python?

description: Get a PID from a window title in windows OS using Python


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.list = QtGui.QTreeWidget(self)
        self.list.setRootIsDecorated(False)
        self.list.setUniformRowHeights(True)
        self.list.setAllColumnsShowFocus(True)
        self.list.setItemsExpandable(False)
        self.list.header().hide()
        self.list.setColumnCount(2)
        for label, color in (
            ('v=x**2', 'red'),
            ('v=x/2', 'blue'),
            ('v=2*x', 'green'),
            ('v=3*2', 'orange'),
            ('v=5-x', 'purple'),
            ):
            item = QtGui.QTreeWidgetItem([label, '------------'])
            item.setForeground(1, QtGui.QColor(color))
            self.list.addTopLevelItem(item)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.list)

if __name__ == '__main__':

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

rawDescription: Generate PyQt Legend

description: Generate PyQt Legend


code:
from tkinter import *

class newtonGUI(Frame):
    def __init__(self, master):
        #Set up frame
        Frame.__init__(self, master)
        self.master.title("Newton's Squareroot")
        self.grid(column = 0, row = 0)

        #Label and field for number input
        self._inputLabel = Label(self, text = "Input a positive number")
        self._inputLabel.grid(row = 0, column = 0)
        self._inputVar = DoubleVar()
        self._inputVar.set(1.0)
        self._inputEntry = Entry(self, textvariable = self._inputVar)
        self._inputEntry.grid(row = 0, column = 1)

        #Display the common square root
        self._estimateLabel = Label(self, text = "Square root estimate")
        self._estimateLabel.grid(row = 1, column = 0)
        self._estimateVar = DoubleVar()
        self._estimateVar.set(1.0)
        self._estimateEntry = Label(self, textvariable = self._estimateVar)
        self._estimateEntry.grid(row = 1, column = 1)

        #Button that computes the input
        self._estimateButton = Button(self, text = "Estimate", command = self._newtonSquare)
        self._estimateButton.grid(row = 4, column = 0)

        #Button that resets text boxes
        self._resetButton = Button(self, text = "Reset", command = self._reset)
        self._resetButton.grid(row = 4, column = 1)

    def _newtonSquare(self):
        val = self._inputVar.get()
        est = self._estimateVar.get()
        if val <= 0.0:
            self._estimateVar.set(0.0)
        else:
            self._estimateVar.set((est + val / est) / 2)

    def _reset(self):
        self._inputVar.set(1.0)
        self._estimateVar.set(1.0)

def main():
    root = Tk()
    newtonGUI(root)
    root.mainloop()
main()

rawDescription: Newton's square formula using tkinter/using a button for computations multiple times


test: test

rawDescription: Format of valid json

description: Format of valid json


rawDescription: How do I convert a string of hexadecimal values to a list of integers?

description: Convert a string of hexadecimal values to a list of integers


code:
with mock.patch('your_module.Database_read') as dbread_mock:
    # prepare the dbread_mock
    dbread_mock.return_value = 10
    # execute a test call
    retval = some_function(3, 'some range')
    # check the result
    dbread_mock.assert_called_with('some range')

rawDescription: Python: know function is called from a unittest?


code:
import os, subprocess, sys

if len(sys.argv) != 3:
    print('Must have 2 arguments!')
    print('Correct usage is "python answer.py input_dir output_dir" ')
    exit()

input_dir = sys.argv[1]
output_dir = sys.argv[2]
input_file_extension = '.txt'
cmd = 'currentframe'

# iterate over the contents of the directory
for f in os.listdir(input_dir):
    # index of last period in string
    fi = f.rfind('.')
    # separate filename from extension
    file_name = f[:fi]
    file_ext = f[fi:]
    # create args
    input_str = '%s.%s.ifd' % (os.path.join(input_dir, file_name), cmd)
    output_str =  '%s.%s.png' % (os.path.join(output_dir + file_name), cmd)
    cli_args = ['mantra', '-f', input_str, output_str]
    #call function
    if subprocess.call(cli_args, shell=True):
        print('An error has occurred with command "%s"' % ' '.join(cli_args))

rawDescription: Need a script to iterate over files and execute a command


code: ax = svv[['Flow2 L/s','GWT','DOC mg/L', 'Hgtot ng/L', 'MeHg ng/L']].dropna().plot(subplots=True, figsize=(20, 20))

rawDescription: Access subplot axes returned by pandas.DataFrame.plot()


code:
def _b2motion(x, y):
    lb.scan_dragto(x, (-y/3)) #here
    _select(y)
    return 'break'

rawDescription: Python Tkinter: Listbox drag selection

description: Python Tkinter: Listbox drag selection


rawDescription: All possible combinations of a list of a list


code:
from sympy import simplify
from sympy.abc import x,y
vers1 = (x+y)**2
vers2 = x**2 + 2*x*y + y**2
simplify(vers1-vers2) == 0
simplify(vers1+vers2) == 0

rawDescription: Sympy - Comparing expressions

description: Sympy - Comparing expressions


code:
# MappedClass from Ming is not JSON serializable and we do not have utilities like json_util (for BSON) to convert
# MappedClass object to JSON. Below encoder is created for this requirement.
# Usage: MappedClassJSONEncoder().encode(data)
class MappedClassJSONEncoder(JSONEncoder):
    """
    Returns a MappedClass object JSON representation.
    """

    def _get_document_properties(self, klass):
        """
        Returns the declared properties of the MappedClass's child class which represents Mongo Document
        Includes only the user declared properties such as tenantId, _id etc
        :param klass:
        :return:
        """
        return [k for k in dir(klass) if k not in dir(MappedClass)]

    def _get_attr_json_value(self, attr):
        if isinstance(attr, bson.objectid.ObjectId):
            return str(attr)
        elif isinstance(attr, datetime.datetime):
            return attr.isoformat()
        elif isinstance(attr, dict):
            dict_data = {}
            for member in attr:
                dict_data.update({member: self._get_attr_json_value(attr[member])})
            return dict_data
        else:
            return attr

    def default(self, o):
        mapped_class_attributes = self._get_document_properties(type(o))
        attributes_data = {}
        for attr_name in mapped_class_attributes:
            attr = o.__getattribute__(attr_name)
            attributes_data.update({attr_name: self._get_attr_json_value(attr)})
        return attributes_data

rawDescription: Ming ODM MappedClass json conversion

description: Ming ODM MappedClass json conversion


code: np.column_stack((a, b1, b2))

rawDescription: Augmenting a matrix in Python using numpy


rawDescription: Python, url from request

description: Python, url from request


code:
union
union.args

rawDescription: sympy set: iterate over intervals

description: Sympy set: iterate over intervals


code:
def __str__(self):
    result = "["
    node = self.head
    if node != None:
        result += str(node.data)
        node = node.next
        while node:
            result += ", " + str(node.data)
            node = node.next
    result += "]"
    return result

rawDescription: Python Unordered Listwith nodes: __str__ method


code:
class ExampleOAuth2Client:
    def __init__(self, client_id, client_secret):
        self.access_token = None

        self.service = OAuth2Service(
            name="foo",
            client_id=client_id,
            client_secret=client_secret,
            access_token_url="http://api.example.com/oauth/access_token",
            authorize_url="http://api.example.com/oauth/access_token",
            base_url="http://api.example.com/",
        )

        self.get_access_token()

    def get_access_token(self):
        data = {'code': 'bar',
                'grant_type': 'client_credentials',
                'redirect_uri': 'http://example.com/'}

        session = self.service.get_auth_session(data=data, decoder=json.loads)

        self.access_token = session.access_token

rawDescription: How can I get an oauth2 access_token using Python

description: Get an oauth2 access_token using Python


code:
commands = {'start': start, 'stop': stop, 'status': status}

parser = argparse.ArgumentParser('My command line app')
parser.add_argument('command', choices=commands.keys())
parser.add_argument('hosts', nargs='*', default=[])
args = parser.parse_args()

commands[args.command](*args.hosts)

rawDescription: How can I get an argument name from argparse?

description: Get an argument name from argparse


code:
from django.utils.safestring import mark_safe

CHOICES = (('a', 'Option 1'), ('b', mark_safe('Option 2 link')))

rawDescription: How to include a link in CheckboxSelectMultiple label

description: Include a link in CheckboxSelectMultiple label


code:
def clean_name(self):
    cleaned_data = self.cleaned_data

    name = cleaned_data.get('name', '')
    if MyModel.objects.filter(name__iexact=name).exists():
        raise forms.ValidationError(_(u"This already exists."))
    return name

rawDescription: Weird values for form.cleaned_data = {'name': {...}}


code:
from django.shortcuts import redirect
import re

class AllauthOverrideMiddleware():
    """
    A middleware to implement a custom user flow
    """
    def __init__(self):
        # allauth urls
        self.url_social = re.compile("^/accounts/.*$")

    def process_request(self, request):

        # WE CAN ONLY POST TO ALLAUTH URLS
        if request.method == "GET" and\
           self.url_social.match(request.path):
            return redirect("/")

rawDescription: Changing django-allauth render_authentication_error behavior


code:
class ToySale(EmbeddedDocument):
    end_time = FloatField()
    percentage = IntField()
    uid = IntField()

    @property
    def super_price(self):
        toy = Toy.objects(sale__uid=self.uid)  # get Document by EmbeddedDocument
        return toy.price - (self.percentage * toy.price / 100)

rawDescription: MongoDB, MongoEngine: How to get Document by its EmbeddedDocument?


code:
import multiprocessing
import time

def merge(d2):
    time.sleep(1) # some time consuming stuffs
    for key in d2.keys():
        if key in d1:
            d1[key] += d2[key]
        else:
            d1[key] = d2[key]

def init(d):
    global d1
    d1 = d

if __name__ == '__main__':

    d1 = multiprocessing.Manager().dict()
    pool = multiprocessing.Pool(initializer=init, initargs=(d1, ))

    l = [{ x % 5 : x } for x in range(10)]

    for item in l:
        pool.apply_async(merge, (item,))

    pool.close()
    pool.join()

    print(l)
    print(d1)

rawDescription: python multiprocessing lock issue

description: Python multiprocessing lock issue


code:
from urllib.request import urlretrieve

for link in link_list:
    urlretrieve(link)

rawDescription: How to Download PDFs from Scraped Links [Python]?


code:
def _get_bottoms(absolute_heights):
    bottoms = np.zeros((2,6))
    diff = absolute_heights[0, :] - absolute_heights[1, :]
    i = np.sign(diff) == np.sign(absolute_heights[0, :])
    bottoms[0, i] = absolute_heights[1, i]
    bottoms[1, ~i] = absolute_heights[0, ~i]
    return bottoms

rawDescription: Define the bottom of each bar in a stacked bar graph


rawDescription: Examples for string find in Python

description: Examples for string find in Python


code:
import bisect
bisect.bisect_left([100,300,500,800,1000], p)

rawDescription: Python: Mapping from intervals to values


code:
#draw stuff onto QPixmap named pix
byteArray = QByteArray()
buffer = QBuffer(byteArray)
buffer.open(QIODevice.WriteOnly)
pix.save(buffer, 'PNG')
stringIO = StringIO(byteArray)
stringIO.seek(0)
tfile = tempfile.NamedTemporaryFile(suffix=".png", mode="wb", delete=False)
tfile.write(stringIO.buf)
tfile.close()
imagebox = mpl.offsetbox.OffsetImage(mpl._png.read_png(tfile.name),zoom=zlvl)
ab = mpl.offsetbox.AnnotationBbox(imagebox, [w/2,0],frameon=False)
ab.set_figure(self.canvas.figure)
ab.draggable()
self.subplot.axes.add_artist(ab)
os.remove(tfile.name)

rawDescription: Custom Artist In Matplotlib Legend

description: Custom Artist In Matplotlib Legend


code:
import pandas as pd

df1 = pd.read_csv("path to file 1")
df2 = pd.read_csv("path to file 2")

result = merge(df1, df2, on='First column', sort=True)
result.to_csv("path to result file")

rawDescription: Handling and printing data in CSV files

description: Handling and printing data in CSV files


rawDescription: Converting Indices of Series to Columns

description: Converting Indices of Series to Columns


code:
def select(x1, y1, w, h):
    x, y = position

    minX, maxX = sorted([x1, x1 + w])
    minY, maxY = sorted([y1, y1 + h])

    if minX <= x <= maxX and minY <= y <= maxY:
        selected = True
    else:
        selected = False

rawDescription: Checking if a point is inside negative box


rawDescription: Dividing a string into a list of smaller strings of certain length


code:
line = None
for line in proc.stdout:
    pass
# now line is either the last line or None.
if line is not None:
    process(line)

rawDescription: Waiting for last line from subprocess

description: Waiting for last line from subprocess


code:
import lxml.html
s = '''<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-GB" lang="en"></html>'''
root = lxml.html.fromstring(s)
root.get('xml:lang')

rawDescription: How can I get Page Language (xml:lang="") using lxml library?

description: Get Page Language (xml:lang="") using lxml library


code:
class klasse(object):

    #  name = [] if this was the case, the name would be a class variable,
    #  and all instances would share it

    def __init__(self, value):
        self.name = [] #  but now it is a separate for each instance
        self.add_name(value)

    def add_name(self, value):
        self.name.append(str(value))

rawDescription: Multiple instances of a class containing a list in python


code:
import pygame
import sys

def load_image(name):
    image = pygame.image.load(name)
    return image

class TestSprite(pygame.sprite.Sprite):
    def __init__(self):
        super(TestSprite, self).__init__()
        self.images = []
        self.images.append(load_image('image1.png'))
        self.images.append(load_image('image2.png'))
        # assuming both images are 64x64 pixels

        self.index = 0
        self.image = self.images[self.index]
        self.rect = pygame.Rect(5, 5, 64, 64)

    def update(self):
        '''This method iterates through the elements inside self.images and
        displays the next one each tick. For a slower animation, you may want to
        consider using a timer of some sort so it updates slower.'''
        self.index += 1
        if self.index >= len(self.images):
            self.index = 0
        self.image = self.images[self.index]

def main():
    pygame.init()
    screen = pygame.display.set_mode((250, 250))

    my_sprite = TestSprite()
    my_group = pygame.sprite.Group(my_sprite)

    while True:
        event = pygame.event.poll()
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit(0)

        # Calling the 'my_group.update' function calls the 'update' function of all
        # its member sprites. Calling the 'my_group.draw' function uses the 'image'
        # and 'rect' attributes of its member sprites to draw the sprite.
        my_group.update()
        my_group.draw(screen)
        pygame.display.flip()

if __name__ == '__main__':
    main()

rawDescription: Animated sprite from few images

description: Animated sprite from few images


code: strings = dict((x, x) for x in L)

rawDescription: Create string(s) from list(s) items

description: Create string(s) from list(s) items


code:
for name in duV.dtype.names:
    globals()[name.lower()] = duV.field(name)

rawDescription: automatically resolve numpy recarray

description: Automatically resolve numpy recarray


code: print('$'+str(total))

rawDescription: How to remove space in function with python

description: Remove space in function with python


code:
import win32ui, win32con as w

def MoveToBack(window_name):
    flags = w.SWP_NOSIZE | w.SWP_NOMOVE | w.SWP_NOACTIVATE | w.SWP_SHOWWINDOW | w.SWP_ASYNCWINDOWPOS
    hwnd = win32ui.FindWindow(None, window_name)
    hwnd.SetWindowPos(w.HWND_BOTTOM, (0,0,0,0), flags)

rawDescription: Making windows appear on Bottom

description: Making windows appear on Bottom


code:
# Get an array of numbers
numbers = map(float, '1,2,3,4'.split(','))

# Now get the sum
total = sum(numbers)

rawDescription: Removing all commas from list in Python

description: Removing all commas from list in Python


code:
from collections import Counter
import sys
from random import randint

# Python 2/3 compatibility
if sys.hexversion >= 0x3000000:
    inp = input
    rng = range
else:
    inp = raw_input
    rng = xrange

def get_int(prompt):
    while True:
        try:
            return int(inp(prompt))
        except ValueError:
            pass

def main():
    sides = get_int("How many sides does your die have? ")
    times = get_int("How many times do you want to roll? ")
    results = Counter(randint(1, sides) for roll in rng(times))

if __name__=="__main__":
    main()

rawDescription: Unlimited sides to dice in simulator

description: Unlimited sides to dice in simulator


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

plt.figure(figsize = (4,4))
gs1 = gridspec.GridSpec(4, 4)
gs1.update(wspace=0.025, hspace=0.05) # set the spacing between axes.

for i in range(16):
   # i = i + 1 # grid spec indexes from 0
    ax1 = plt.subplot(gs1[i])
    plt.axis('on')
    ax1.set_xticklabels([])
    ax1.set_yticklabels([])
    ax1.set_aspect('equal')
    plt.subp

plt.show()

rawDescription: How to remove gaps between subplots in matplotlib?

description: Remove gaps between subplots in matplotlib


code:
import os
f=open('existingfile.txt', 'wb+')

f.write('somebytes')
f.close()
os.rename('currentPath\existingfile.txt', 'NewPath\existingfile.txt')

#reopen file - Repeat

rawDescription: How to keep writing in a moved file with the same file object?

description: Keep writing in a moved file with the same file object


code:
def solve(terms_list, stack, current_s, desired_s):
    if len(terms_list) == 0:
        if current_s == desired_s:
            print(stack)
        return

    for w in [0, 1, -1]: # ignore term (0), add it (1), subtract it (-1)
        stack.append(w)
        solve(terms_list[1:], stack, current_s + w * terms_list[0], desired_s)
        stack.pop()

rawDescription: Algorithm for subset-sum with subtraction


code:
LISTBOX.insert(END, line)
LISTBOX.itemconfigure(END, background="blue")

rawDescription: How to set the color of items in a listbox

description: Set the color of items in a listbox


code: data = data[0]

rawDescription: How to delete a list parameters but not the contents?

description: Delete a list parameters but not the contents


rawDescription: python convert a binary string to a structure sutiable for bitwise operators

description: Python convert a binary string to a structure sutiable for bitwise operators


code:
lu = LibraryUser(library_membership_number= '...', user_id = user)
lu.save()

rawDescription: Creating a new instance of a Custom User Model in Django


code:
import datetime
import os

DIRECTORY = '.'

for filename in os.listdir(DIRECTORY):

    # Skip non-xls file
    if not filename.lower().endswith('.xls'):
        continue

    path = os.path.join(DIRECTORY, filename)
    mtime = os.path.getmtime(path)  # modification time
    prefix = datetime.datetime.fromtimestamp(mtime).strftime('%Y%m%d')
    newpath = os.path.join(DIRECTORY, prefix + '_' + filename)

    # rename it
    os.rename(path, newpath)

rawDescription: file rename, python batch-processing

description: File rename, python batch-processing


code:
import multiprocessing.dummy
import threading

def generate():
    for i in range(20):
        print('generating {}'.format(i))
        yield i

def consume(i):
    print('thread {} consuming {}'.format(threading.current_thread().ident, i))

pool = multiprocessing.dummy.Pool(4)

list(pool.imap(consume, generate()))

rawDescription: Multithreaded functionality with dynamic data input


rawDescription: Drop row in pandas dataframe if any value in the row equals zero


code:
'''
This is a multiline
comment.
'''

rawDescription: Commenting multiple lines in an ipython cell


code:
from pymongo import Connection
connection = Connection()
db = connection['test-database']
collection = db['test-collection']

rawDescription: How do I create a new database in MongoDB using PyMongo?

description: Create a new database in MongoDB using PyMongo


code:
thresh = 0.9
accepted_probabilities_idx = probabilities.max(axis=1) > thresh
accepted_labels_predicted = labels_predicted[accepted_probabilities_idx]
accepted_new_data = pandas.DataFrame(new_data, index=accepted_probabilities_idx)

rawDescription: Setting a threshold in classifier output in Python


code:
pos1 = np.array([[0,0,0],[2,2,2]])
pos2 = np.array([[1,1,1],[3,3,3]])

for point_pairs in zip(pos1, pos2):
    xs, ys, zs = zip(*point_pairs)
    ax.plot(xs, ys, zs)

rawDescription: Plotting multiple 3D lines: data transformation


code: from_date = today.replace(day=day)

rawDescription: What is better way to create datetime object where just date needs to change?


code:
def findLine(line, fileName):
    file = open(fileName, 'rb').readlines() #open File and create list of each line
    i = file[line-1] #get the line you need, note that python lists start at 0
    i = i.replace('\r', '').replace('\n', '') #strip out all the unnecessary stuff
    del file
    return i

def findLineSmall(line, fileName):
    return open(fileName, 'rb').readlines()[line-1].replace('\r', '').replace('\n', '') #Everything compressed to one line

data = []
data.append(findLineSmall(6, 'data'))

rawDescription: Append a unique line from a text to a list in Python


code:
import csv
import operator

idgetter = operator.itemgetter(2)
with open('path/to/file') as infile:
    infile.readline()
    ids = [idgetter(row) for row in csv.reader(infile)]

rawDescription: How to read in a certain csv file column (up and down) Python

description: Read in a certain csv file column (up and down) Python


code:
a=input('Enter the list of tuples')
b=[]
for i in range(len(a)):
    b.append(sum(a[i]))

rawDescription: In Python, Given a list of tuple, generate a list whose elements are sum of elements of contained tuples


code:
for item in eda_workflow['steps']:
    item['constaints'] = constraints

rawDescription: Python: modify information on list item

description: Python: modify information on list item


code:
import os
yourfile = os.listdir("/home/user/Desktop/directory_which_only_contains_this_one_file")[0]

rawDescription: Getting a filename and save it in a variable in Python


code:
#!/usr/bin/env python

from datetime import datetime

with open("stuff.txt", "r") as f:
    for line in f:
        # Remove initial or ending whitespace (like line endings)
        line = line.strip()

        # Split the timestamp and value
        raw_timestamp, value = line.split(",")

        # Make the timestamp an actual datetime object
        timestamp = datetime.strptime(raw_timestamp, "%Y%m%d")

        # Print the timestamp separated by -'s. Replace - with / or whatever.
        print("%s,%s" % (timestamp.strftime("%Y-%m-%d"), value))

rawDescription: How to reformat a timestamp in Python

description: Reformat a timestamp in Python


code:
x_vals = []
y_vals = []

for i in range(0,len(lines)):
    line=lines[i]
    values=line.split("     ")

    x_vals.append(float(values[0]))
    y_vals.append(float(values[1]))

plt.plot(x_vals, y_vals,'ro-')

rawDescription: linestyle feature for plotting in python with matplotlib.pyplot

description: Linestyle feature for plotting in python with matplotlib.pyplot


rawDescription: Python Pandas Dataframe filter and replace


rawDescription: How to stop turtles at certain coordinates?

description: Stop turtles at certain coordinates


code:
import pandas as pd
import statsmodels.api as sm

data = sm.datasets.macrodata.load_pandas().data

def rolling_coint(x, y):
    yy = y[:len(x)]
    # returns only the p-value
    return sm.tsa.coint(x, yy)[1]

historical_coint = pd.expanding_apply(data.realgdp, rolling_coint,
                                      min_periods=36,
                                      args=(data.realdpi,))

rawDescription: Plotting Historical Cointegration Values between two pairs


code:
new_list.append([linewords[0],
                        linewords[1],
                        linewords[3],
                        ",".join(sorted(linewords[4].split(",")))])

rawDescription: Sorting a list element alphabetically

description: Sorting a list element alphabetically


code:
from matplotlib.mlab import psd, csd

def tfe(x, y, *args, **kwargs):
   """estimate transfer function from x to y, see csd for calling convention"""
   return csd(y, x, *args, **kwargs) / psd(x, *args, **kwargs)

rawDescription: Python version of Matlab Signal Toolbox's tfestimate()?


code:
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.naive_bayes import MultinomialNB

corpus = ['this document is about cheese',
          'this is about snakes',
          'another one about cheese',
          'and another one about snakes']
label = ['cheese', 'snakes', 'cheese', 'snakes']

clf = make_pipeline(CountVectorizer(), MultinomialNB())
clf.fit(corpus, label)
predicted = clf.predict(['one about cheese'])
print(predicted)
# ['cheese']

rawDescription: How to create a matrix for input string in SciKitLearn module of Python?

description: Create a matrix for input string in SciKitLearn module of Python


code:
import pyglet
from pyglet.gl import *

window = pyglet.window.Window()
image = pyglet.resource.image('pic.jpg')
mask = pyglet.resource.image('mask.jpg')
createdtex=False;
imagetex = 0

@window.event
def on_draw():
    window.clear()
    global createdtex
    texfrmbuf =(GLuint*1)()
    global imagetex
    if createdtex!=True:
        imagetex = image.get_texture()
        glEnable(GL_BLEND)
        glBlendFunc(GL_ZERO, GL_SRC_COLOR)
        glGenFramebuffersEXT(1,texfrmbuf)
        glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT,texfrmbuf[0])
        glFramebufferTexture2DEXT(GL_DRAW_FRAMEBUFFER_EXT,GL_COLOR_ATTACHMENT0_EXT, imagetex.target,imagetex.id,0)
        mask.blit(0,0)
        glFlush()
        glDisable(GL_BLEND)
        glDeleteFramebuffersEXT(1,texfrmbuf)
        glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT,0)
        createdtex=True

    imagetex.blit(0,0)

pyglet.app.run()

rawDescription: pyglet: blit a texture with specified alpha mask

description: Pyglet: blit a texture with specified alpha mask


code:
bb= set(b)
nl = [elem for elem in a if elem not in bb]

rawDescription: do list subtraction in python

description: Do list subtraction in python


code:
class Test:
   def __repr__(self):
       return 'asd'

rawDescription: How to apply __str__ function when printing a list of objects in python

description: Apply __str__ function when printing a list of objects in python


code:
"""
Get all the authorized hosts for a iSCSI.

Important manual pages:
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Hardware
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Virtual_Guest
http://sldn.softlayer.com/reference/datatypes/SoftLayer_Network_Storage
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Storage
http://sldn.softlayer.com/reference/services/SoftLayer_Network_Storage/getObject

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
import SoftLayer

USERNAME = 'set me'
API_KEY = 'set me'

iscsiId = 6548079

# Declares the API client
client = SoftLayer.Client(username=USERNAME, api_key=API_KEY)
networkStorageService = client['SoftLayer_Network_Storage']

objectMask = "mask[id,username,allowedVirtualGuests[fullyQualifiedDomainName,allowedHost[name,credential[username,password]]],allowedHardware[fullyQualifiedDomainName,allowedHost[name,credential[username,password]]]]"

try:
    response = networkStorageService.getObject(id=iscsiId, mask=objectMask)
    print(response)
except SoftLayer.SoftLayerAPIError as e:
    # If there was an error returned from the SoftLayer API then bomb out with the
    # error message.
    print("Unable to retrieve the network storage. faultCode=%s, faultString=%s" % (e.faultCode, e.faultString))

rawDescription: How get the softlayer storage credendials?


code:
import os
import package_name

package_dir = os.path.dirname(package_name.__file__)
theme_dir = os.path.join(package_dir, 'themes')

rawDescription: Paths from a module/imported package

description: Paths from a module/imported package


rawDescription: Python/Flask: Identify Referring Domain

description: Python/Flask: Identify Referring Domain


code:
from kivy.graphics import *
#^^^^^^ all imports you need for that to work + App()/runTouchApp()

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class Root(Widget):
    def __init__(self, **kw):
        super(Root, self).__init__()
        with self.canvas:
            Color(1,0,0,0.5)
            Rectangle(pos=self.pos, size=Window.size)

        bx=BoxLayout(width=Window.width)
        but1=Button(text="mask it!")
        but1.bind(on_release=self.mask)
        but2=Button(text="clear it!")
        but2.bind(on_release=self.clear)

        bx.add_widget(but1)
        bx.add_widget(but2)
        self.add_widget(bx)
        #after few hundred lines of code you'll hate to type even ".add_"
        #binding on_release and other is a way more shorter
        #learn kv, have less troubles :)

    def mask(self, *args):
        with self.canvas:
            #you have to "push" the stencil instructions
            #imagine StencilPush and StencilPop as { and }
            StencilPush()

            #set mask
            Rectangle(pos=[self.pos[0],self.pos[1]+200], size=[100,100])

            #use mask
            StencilUse()

            #draw something and mask will be placed on it
            #Color(1,1,1) for full color, otherwise it tints image
            Color(0,1,0)
            Rectangle(source='<your picture>',\
            pos=[0,0], size=[Window.width-200,Window.height-200])

            #disable Stencil or mask will take effect on everything
            #until StencilPop()
            StencilPop()

            #here it doesn't take effect
            Color(0,1,1)
            Rectangle(pos=[self.pos[0]+200,self.pos[1]+200],\
            size=[Window.width-200,Window.height-200])

            #However here, when StencilPop() and StencilUse()
            #are again, mask is still in the memory
            StencilPush()
            StencilUse()

            #mask is applied... and draws nothing
            #because it's not in the mask's area
            Color(1,1,0)
            Rectangle(pos=[self.pos[0]+200,self.pos[1]+200],\
            size=[Window.width-200,Window.height-200])

            #I think UnUse() is optional
            StencilUnUse()

            #and of course Pop() it
            StencilPop()

    def clear(self, *args):
        self.canvas.clear()
        self.__init__()

class My(App):
    def build(self):
        return Root()

My().run()

rawDescription: How do i mask an image in kivy using python?

description: Mask an image in kivy using python


code:
handle = open('/tmp/file.txt', 'w')
handle.write('foo')
handle.tell()

rawDescription: How to confirm that a file object is empty? [Python]

description: Confirm that a file object is empty? [Python]


rawDescription: Read a hidden value in a div using Selenium Python binding


code:
mylist = []
for i in range(million):
    mylist.append(something)
mytup = tuple(mylist)

rawDescription: Python : Variable size problems with Pyscripter


code:
A = numpy.array(range(10)).reshape(5, 2)
B = numpy.array(range(5))
B
A * B
B = B.reshape(5, 1)
B
A * B

rawDescription: How to multiply a numpy tuple array by scalar array

description: Multiply a numpy tuple array by scalar array


code:
class MyThreads(threading.Thread):
    def __init__(self):
        self.server = None;
        threading.Thread.__init__(self);
    def run(self):
        if self.server == None:
            address = ('localhost', 40000);
            self.server = SocketServer.TCPServer(address, EchoRequestHandler);

        self.server.serve_forever()

rawDescription: Simple TCP Server in python

description: Simple TCP Server in python


code:
import wx

TIMER_ID = 100

class Frame(wx.Frame):
    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, size=(350,200))
        self.timer = None
        self.Bind(wx.EVT_LEFT_DCLICK, self.OnDoubleClick)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)

    def OnDoubleClick(self, event):
        self.timer.Stop()
        print("double click")

    def OnSingleClick(self, event):
        print("single click")
        self.timer.Stop()

    def OnLeftDown(self, event):
        self.timer = wx.Timer(self, TIMER_ID)
        self.timer.Start(200) # 0.2 seconds delay
        wx.EVT_TIMER(self, TIMER_ID, self.OnSingleClick)

app = wx.App(redirect=True)
top = Frame("Hello World")
top.Show()
app.MainLoop()

rawDescription: How to distinguish the double click and single click of mouse in wxpython

description: Distinguish the double click and single click of mouse in wxpython


code:
def getConnectionPool():
    config = {
                "user":"user",
                "password":"password",
                "host":"localhost",
                "port":"12345",
                "database":"database"
              }
    pool = mysql.connector.pooling.MySQLConnectionPool(pool_name="MyPool", pool_size=10, **config)
    return pool

def getAllObjects():
    pool = getConnectionPool()
    newObject = NewObject(pool)

class NewObject(object):
    def __init__(self, pool):
        self.conn = pool.get_connection()
        # cursor, etc.

rawDescription: Can a MySQL connector be shared between objects?


code:
import Tkinter
root = Tkinter.Tk()
root.tk.eval('source {foo.tcl}')
root.tk.eval('foo_bar')

rawDescription: how to use TCL packages/code in python pytest program

description: Use TCL packages/code in python pytest program


code:
import sys
import pygame
from pygame.locals import *
pygame.init()

size = width, height = 720, 480
speed = [2, 2]
black = (0,0,0)
blue = (0,0,255)
green = (0,255,0)
red = (255,0,0)

screen = pygame.display.set_mode(size)

pygame.display.set_caption("BETA::00.0.1")

clock = pygame.time.Clock()

def text_objects(text, font):
    textSurface = font.render(text, True, black)
    return textSurface, textSurface.get_rect()

def game_intro():

  screen.fill(blue)

  largeText = pygame.font.Font('freesansbold.ttf',115)
  TextSurf, TextRect = text_objects("BETA", largeText)
  TextRect.center = ((width/2),(height/2))
  screen.blit(TextSurf, TextRect)

  pygame.draw.rect(screen, green,(150,450,100,50))
  pygame.draw.rect(screen, red,(550,450,100,50))

  pygame.display.flip()
  pygame.display.update()
  clock.tick(15)

  intro = True

  while intro:
     for event in pygame.event.get():
         print(event)
         if event.type == pygame.QUIT:
             pygame.quit()
             quit()

game_intro()

rawDescription: Pygame window displays blank black screen


code: aspect = (max(x) - min(x)) / (max(y) - min(y))

rawDescription: matplotlib: get axis ratio of plot

description: Matplotlib: get axis ratio of plot


code:
def run_me(self):
    config_vars= self.get_properties('services','package_install','package_info')
    convig_vars_2 = self.get_properties('network','proxy_server','proxy_user')

rawDescription: Using dictionary comprehension with ConfigParser


code: dic2 = {k: min(v) for k, v in dic.items()}

rawDescription: Remove the duplicates from the values list of a key in a dictionary?


code:
from abaqusConstants import *
from viewerModules import *
import os

# User variables ------------------
elementSetName='fix'
outPutFileName='tmp.txt'
# ---------------------------------

currView=session.viewports[session.currentViewportName]
cOdbD=currView.odbDisplay
odb = session.odbs[cOdbD.name]
odbRootA=odb.rootAssembly

directory=os.path.split(odb.path)[0]

with open(os.path.join(directory,outPutFileName),"w") as f:

    f.write("%s\n" % ('  Part Instance  Element ID        Type  Attached nodes'))
    f.write("%s\n" % ('--------------------------------------------------------------------------------'))

    for element in odbRootA.elementSets[elementSetName.upper()].elements[0]:

        f.write("%s" % ('    ' + element.instanceName + '         ' + str(element.label) + '        ' + element.type))

        nodeNum=0
        for node in element.connectivity:
            nodeNum+=1
            if nodeNum>4:
                f.write("\n%s\n" % (''))
                nodeNum=-4

            f.write("%s" % ('        ' + str(node)))
        f.write("\n")
        f.write("\n")

rawDescription: How to print the connectivity in abaqus python matrix using writeFieldReport

description: Print the connectivity in abaqus python matrix using writeFieldReport


code:
import itertools

tasks_combinations = [[1, 2, 3], [2, 3, 4]]
people_tasks = [[1, 3], [2, 3], [3, 4]]

people_tasks_product = map(set, (itertools.product(*people_tasks)))

for tasks_combination in tasks_combinations:
    if set(tasks_combination) in people_tasks_product:
        print('Task combination {} is covered.'.format(tasks_combination))
    else:
        print('Task combination {} is NOT covered.'.format(tasks_combination))

rawDescription: Check whether all possible combinations from a list appear in an attribute of objects in another list


code:
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.datas,
          name=os.path.join('..\\path\\to\\output', 'AppName.exe'),
          icon='C:\\abs\\path\\to\\icon\\icon.ico',
          debug=False,
          strip=False,
          upx=False,
          console=False )

rawDescription: wxpython icon for task bar

description: Wxpython icon for task bar


code:
from gi.repository import WebKit
from gi.repository import Gtk, Gdk

def get_source(webobj, frame):
  doc = web.get_dom_document()
  element = doc.get_elements_by_name("q")
  child = element.item(0)
  child.set_value("test")
  SubBtn = doc.get_elements_by_name("btnG")
  btn = SubBtn.item(0)
  btn.click()

win = Gtk.Window()

web = WebKit.WebView()
web.open("http://google.com")
web.connect("load-finished", get_source)
win.add(web)
win.connect('destroy', lambda w: Gtk.main_quit())
win.show_all()
Gtk.main()

rawDescription: How to auto fill input field with pygtk+ WebKit

description: Auto fill input field with pygtk+ WebKit


code:
from operator import or_
or_mask = reduce(or_,mask_list)

rawDescription: logical or on list of pandas masks

description: Logical or on list of pandas masks


rawDescription: dropping rows from dataframe based on a "not in" condtion

description: Dropping rows from dataframe based on a "not in" condtion


code:
def joinit(iterable, delimiter):
    it = iter(iterable)
    yield next(it)
    for x in it:
        yield delimiter
        yield x

rawDescription: python: most elegant way to intersperse a list with an element

description: Python: most elegant way to intersperse a list with an element


code: string_list = ['string1', 'string2', 'string3', 'string4']

rawDescription: Best way to initialize a static list in a Python module

description: Initialize a static list in a Python module


code:
from functools import partial

options = { 0: func0,
            1: func1,
            2: partial(func2, foo1),
            3: partial(func3, foo2),
          }

options[choice]()

rawDescription: Passing no arguments while calling function through dict


code:
auth = base64.b64encode("%s:%s" % (username, password))
headers['Proxy-Authorization'] = ["Basic " + auth.strip()]
endpoint = endpoints.TCP4ClientEndpoint(reactor, host, port, timeout=yourTimeout)
agent = client.ProxyAgent(endpoint, reactor=reactor, pool=pool)

rawDescription: How to set timeout for ProxyAgent?

description: Set timeout for ProxyAgent


rawDescription: What is right way to build database with deep dependencies in Django?


code:
df2 = df.asn.str.split(',').apply(pd.Series)
df2.index = df.set_index(['Name', 'count']).index
df2.stack().reset_index(['Name', 'count'])

rawDescription: Pandas: how to convert a cell with multiple values to multiple rows?


code:
app = wx.PySimpleApp()

f = Frame(None, -1, "Some Title For This Frame")
f.Show()

app.MainLoop()

# Down here more code can follow.

rawDescription: Does not come out from MainLoop()

description: Does not come out from MainLoop()


code:
from kivy.properties import StringProperty
class AnswerScreen(Screen):
    bkgd = StringProperty("")
...

rawDescription: Kivy dynamic background loading not functioning


code:
@register.simple_tag(takes_context=True)
def foo(context):
    request = context['request']
    request.META
    ...

rawDescription: How to access request.META in a template custom tag in django?

description: Access request.META in a template custom tag in django


code:
def set_values():
    cycle_num = input("Cycle Amount: ")
    probability = input("Probability: ")
    return cycle_num, probability

def display_values(cycle_num, probability):
    print("Cycle Amount: ", cycle_num)
    print("Probability: ", probability)

def main_menu():
  cycle_num=0
  probability=0

  while True:
    user_choice = input("Choose option 1, 2 or 3")
    if user_choice == "1":
        cycle_num, probability=set_values()
    elif user_choice == "2":
        display_values(cycle_num, probability)
    else:
      break

if __name__ == '__main__':
  main_menu()

rawDescription: How to use variables set in one function in another

description: Use variables set in one function in another


code:
import win32com.client
js = win32com.client.Dispatch('MSScriptControl.ScriptControl')
js.Language = 'JavaScript'
js.AddCode('function add(a, b) {return a+b;}')
js.Run('add', 1, 2)

rawDescription: Programmatically detect system-proxy settings on Windows XP with Python


rawDescription: Cleanest way to filter a Pandas dataframe?


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

# Add subplots using gridspec instead of plt.subplots()
gs = gridspec.GridSpec(1,2, height_ratios=[1,1])
f = plt.figure()
ax1 = plt.subplot(gs[0])
ax2 = plt.subplot(gs[1])

im = np.random.random((100,100))
ax1.imshow(im)
ax1.set_xlim(0, im.shape[1])
ax1.set_ylim(0, im.shape[0])
x = np.arange(100)
ax2.plot(x, x**2)

rawDescription: Matplotlib: Same height for subfigures

description: Matplotlib: Same height for subfigures


code:
if __name__ == "__main__":
    print('Ah, what a hard day of threading...')

rawDescription: Python - multiple copies of output when using multiprocessing


code: zip(*a)

rawDescription: Pass each element of a list to a function that takes multiple arguments in Python?


rawDescription: Parsing String according to Dates in Python


code:
import pandas as pd
from IPython.core import display as ICD

df = pd.DataFrame(
    {'area': [5, 42, 20, 20, 43, 78, 89, 30, 46, 78],
     'cost': [52300, 52000, 25000, 61600, 43000, 23400, 52300, 62000, 62000, 73000],
     'grade': [1, 3, 2, 1, 2, 2, 2, 4, 1, 2], 'size': [1045, 957, 1099, 1400, 1592, 1006, 987, 849, 973, 1005],
     'team': ['man utd', 'chelsea', 'arsenal', 'man utd', 'man utd', 'arsenal', 'man utd', 'chelsea', 'arsenal', 'arsenal']})

result =  df.groupby(['team', 'grade']).agg({'cost':'mean', 'area':'mean', 'size':'sum'}).rename(columns={'cost':'mean_cost', 'area':'mean_area'})

dfs = {team:grp.drop('team', axis=1)
       for team, grp in result.reset_index().groupby('team')}

for team, grp in dfs.items():
    print(team)
    ICD.display(grp)

rawDescription: Pandas: How to reference and print multiple dataframes as HTML tables


code:
import musicplayer, sys, os, fnmatch, random, pprint, Tkinter

class Song:
        def __init__(self, fn):
                self.url = fn
                self.f = open(fn)
        # `__eq__` is used for the peek stream management
        def __eq__(self, other):
                return self.url == other.url
        # this is used by the player as the data interface
        def readPacket(self, bufSize):
                return self.f.read(bufSize)
        def seekRaw(self, offset, whence):
                r = self.f.seek(offset, whence)
                return self.f.tell()

files = []
def getFiles(path):
        for f in sorted(os.listdir(path), key=lambda k: random.random()):
                f = os.path.join(path, f)
                if os.path.isdir(f): getFiles(f) # recurse
                if len(files) > 1000: break # break if we have enough
                if fnmatch.fnmatch(f, '*.mp3'): files.append(f)
getFiles(os.path.expanduser("~/Music"))
random.shuffle(files) # shuffle some more

i = 0

def songs():
        global i, files
        while True:
                yield Song(files[i])
                i += 1
                if i >= len(files): i = 0

def peekSongs(n):
        nexti = i + 1
        if nexti >= len(files): nexti = 0
        return map(Song, (files[nexti:] + files[:nexti])[:n])

# Create our Music Player.
player = musicplayer.createPlayer()
player.outSamplerate = 96000 # support high quality :)
player.queue = songs()
player.peekQueue = peekSongs

# Setup a simple GUI.
window = Tkinter.Tk()
window.title("Music Player")
songLabel = Tkinter.StringVar()

def onSongChange(**kwargs): songLabel.set(pprint.pformat(player.curSongMetadata))
def cmdPlayPause(*args): player.playing = not player.playing
def cmdNext(*args): player.nextSong()

Tkinter.Label(window, textvariable=songLabel).pack()
Tkinter.Button(window, text="Play/Pause", command=cmdPlayPause).pack()
Tkinter.Button(window, text="Next", command=cmdNext).pack()

player.onSongChange = onSongChange
player.playing = True # start playing
window.mainloop()

rawDescription: Mp3 player with GUI on Python

description: Mp3 player with GUI on Python


code:
s = "   xyz"
len(s) - len(s.lstrip())

rawDescription: Returning the lowest index for the first non whitespace character in a string in Python


code:
def load_some_script():
    pyfd = open("some_python_script.py", "r")
    src = pyfd.read()
    pyfd.close()

    exec(src, globals())  # execute the code in the global scope

load_some_script()
some_function('foo', 'bare')  # should now be available at module level.

rawDescription: Python call function directory from local() using exec


code: Popen('command1 | command2 | command3',shell=True)

rawDescription: invoking pipe command with Popen in Python

description: Invoking pipe command with Popen in Python


rawDescription: How to count values in a certain range in a Numpy array?

description: Count values in a certain range in a Numpy array


code:
def resizeInto(surface, rect):
    surSize = list(surface.get_size())
    rectSize = rect.size
    for i in (0, 1):
        if surSize[i] > rectSize[i]:
            surSize[1 - i] = 1. * surSize[1 - i] / surSize[i] * rectSize[i]
            surSize[i] = rectSize[i]

    if surSize != surface.get_size():
        rounded = [int(round(s)) for s in surSize]
        surface = pygame.transform.smoothscale(surface, rounded)
    return surface

rawDescription: Pygame (basics)

description: Pygame (basics)


code:
try:
    from mercurial import demandimport; demandimport.enable()
except ImportError:
    import sys
    sys.stderr.write("abort: couldn't find mercurial libraries in [%s]\n" %
                     ' '.join(sys.path))
    sys.stderr.write("(check your install and PYTHONPATH)\n")
    sys.exit(-1)

rawDescription: Fast-Responding Command Line Scripts

description: Fast-Responding Command Line Scripts


code: data = data[(data['RotSpeed'] <= ROTOR_SPEED) & (data['HorWindV'] <= WIND_SPEED)]

rawDescription: How can be used multiple filter in the numpy array?


code:
with open("setPhrases.txt") as out_file:
    writer = csv.writer(out_file)
    for row in file_rows:
        spamwriter.writerow(row[0],row[1])

rawDescription: How can I add to the tally of a chosen phrase?

description: Add to the tally of a chosen phrase


code:
print('some notification at the beginning')

while true:
    guestNames = input("Please enter the name of your " + guestNumber[number] + " guest: ").capitalize()

    if guestNames == 'Done':
        # Jump out of the loop if user says done
        break
    else:
        # Assume user input 'name age location', replace all space with commas
        guestList.append(guestNames.replace(' ', ','))
        number += 1

guestList.sort()

# the with keyword will close the guestFile at the end
with open("guestList.csv","w") as guestFile:
    guestFile.write('your headers\n')
    for entries in guestList:
        guestFile.write('%s\n' % entries)

rawDescription: Python: Writing lists to .csv file

description: Python: Writing lists to .csv file


code:
[re.search('product\/([0-9]{5,6})_productdescription', s).group(1)
 if re.search('product\/([0-9]{5,6})_productdescription', s)
 else ''
 for s in urls]

rawDescription: Regular expression for URLs in Python

description: Regular expression for URLs in Python


code:
A1, A2, B1, B2, C1, C2 = range(6)

def isAdjacent (actual, classifierOutput):
    return actual - 2 < classifierOutput < actual + 2

rawDescription: Efficiently check for adjacent accuracy (group membership?)


code:
# Make sure App Engine SDK is available
import sys
sys.path.append('/usr/local/google_appengine')
from google.appengine.api.files import records
from google.appengine.datastore import entity_pb
from google.appengine.api import datastore

raw = open('path_to_datastore_export_file', 'r')
reader = records.RecordsReader(raw)
for record in reader:
  entity_proto = entity_pb.EntityProto(contents=record)
  entity = datastore.Entity.FromPb(entity_proto)
  #Entity is available as a dictionary!

rawDescription: How can one load an AppEngine cloud storage backup to a local development server?


code:
img = images.Image(blob_key=image.blob)
img.rotate(270)
t = img.execute_transforms(output_encoding=images.PNG)
filename = '/' + UploadHandler.get_gs_bucket_for_images() + 'blobstore_demo.png'
mimetype = 'image/png'
with gcs.open(filename,'w', content_type=mimetype) as f:
    f.write(t)

blobstore_filename = '/gs' + filename

rawDescription: How to set the content type of an image before storing it to blobstore?

description: Set the content type of an image before storing it to blobstore


code:
import numpy as np
A = np.ones(10,5,3)
B = np.ones(10,5)
Result = A/B[:,:,np.newaxis]

rawDescription: Divide an array of arrays by an array of scalars


code: db.GqlQuery("SELECT * FROM User WHERE email >= :1 AND email <= :2", searchData, unicode(searchData) + u"\ufffd")

rawDescription: How can I make my App Engine Datastore user search faster?

description: Make my App Engine Datastore user search faster


code: arg1 = None if arg1 not in ["first", "second", "third"] else arg1

rawDescription: Pythonic way to allow data, present in list else None


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

# Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.

# First create the x and y coordinates of the points.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)

angles = np.linspace(0, 2*math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi/n_angles

x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()

# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)

# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = np.where(xmid*xmid + ymid*ymid < min_radius*min_radius, 1, 0)
triang.set_mask(mask)

# Plot the triangulation.
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(triang, 'bo-')
plt.title('triplot of Delaunay triangulation')

plt.show()

rawDescription: Triangulation of a polygon using matplotlib


code:
def min_and_max(iterable):
    iterator = iter(iterable)

    # Assumes at least two items in iterator
    minim, maxim = sorted((next(iterator), next(iterator)))

    for item in iterator:
        if item < minim:
            minim = item
        elif item > maxim:
            maxim = item

    return (minim, maxim)

with open('gmm_data.txt', 'r') as f:
    values = (float(value_str) for line in f for value_str in line.split())
    minim, maxim = min_and_max(values)

print(maxim)
print(minim)

rawDescription: How can I find the highest value in a .txt file?

description: Find the highest value in a .txt file


code:
import webbrowser
import argparse

parser = argparse.ArgumentParser(description='Accept URL parameters on the command line.')
parser.add_argument('UserID', metavar='UID', type=str, nargs=1,
                   help='The User ID')
parser.add_argument('UserName', metavar='UName', type=str, nargs=1,
                    help = 'The User Name')

args = parser.parse_args()
url = 'http://stackoverflow.com/users/%s/%s' % (args.UserID[0], args.UserName[0])
print(url)
webbrowser.open(url)

rawDescription: Using command line arguments to launch url in system web browser


code:
with open('lyrics.conf') as f:
    data = file.read()
verses = data.split('/')
def build_blender_object(verse):
  # Put meaningful code here
  pass
blender_objects = [build_blender_object(v) for v in verses]

rawDescription: Distributing list items to variables in python


rawDescription: Slicing a list in Python without generating a copy


code:
while len(primeList) < 100000:
    rootN = sqrt(num)
    for i in primeList:
        if i <= rootN:
            if num % i == 0:
                break
        else:
            primeList.append(num)
            break
    else:
        primeList.append(num)
    num += 2

rawDescription: Python sqrt() doubles runtime?

description: Python sqrt() doubles runtime


code:
numbers = ['0','1','2']
[''.join(p) for n in range(1,4) for p in product(numbers, repeat=n)]

rawDescription: Merging the results of itertools.product?


code:
import email, email.header
m = email.message_from_string("Subject: math340-05 =?UTF-8?B?4oCTIEF1ZmdhYmUgNS4x?=")
raw_header = email.header.decode_header(m["Subject"])
header = email.header.make_header(raw_header)
print(str(header))
# or for py2: print(unicode(header))

description: Parse “math340-05 =?UTF-8?B?4oCTIEF1ZmdhYmUgNS4x?=”


code: ' '.join((' ' if pred else '').join(seq) for pred, seq in itertools.groupby("C S E majors in U S".split(), lambda x: len(x) > 1))

rawDescription: Concatenate certain letters in a string

description: Concatenate certain letters in a string


code:
# Declare a mutable object so that it can be pass via reference
user_input = [None]

# spawn a new thread to wait for input
def get_user_input(user_input_ref):
    user_input_ref[0] = raw_input("Give me some Information: ")

mythread = threading.Thread(target=get_user_input, args=(user_input,))
mythread.daemon = True
mythread.start()

for increment in range(1, 10):
    time.sleep(1)
    if user_input[0] is not None:
        break

rawDescription: waiting for user input in separate thread

description: Waiting for user input in separate thread


code:
new=list()
words_to_delete = set(words_to_delete)
email_process_list = email_process_list[::-1]
while len(email_process_list) > 0:
    email = email_process_list.pop()
    email_clean=[word for word in email if word not in words_to_delete]
    new.append(email_clean)

rawDescription: Python : need performance to retrieve a string in a big list


code:
import unicodedata
def shave_marks(txt):
    """This method removes all diacritic marks from the given string"""
    norm_txt = unicodedata.normalize('NFD', txt)
    shaved = ''.join(c for c in norm_txt if not unicodedata.combining(c))
    return unicodedata.normalize('NFC', shaved)

rawDescription: Remove diacritics from string for search function


code: re.search(r"Car.*?Car", string1)

rawDescription: Python Regular Expression to match multiple occurrences of word


code:
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')

rawDescription: Open explorer on a file

description: Open explorer on a file


code:
import threading
my_thread = threading.Thread(target=your_function, args=(), kwargs={})  # This can go inside a loop, providing different args each time.
my_thread.start()

rawDescription: Simultaneously call functions with different parametrs in Python


code:
def my_view(request):
    context = {}
    context['items'] = Item.objects.all()
    context['anothervalue'] = context['items'][2].name
    return render_to_response('template.html', context)

rawDescription: Getting local dictionary for function scope only in Python


code:
def foo3(items,totalIndices):
    N = len(items)
    cols=[]
    cnts=[]
    for item in items:
        indices = getIndices(item)
        cols += indices
        cnts.append(len(indices))
    rows = np.arange(N).repeat(cnts) # main change
    data = np.ones(rows.shape, dtype=bool)
    mat = sparse.coo_matrix((data,(rows,cols)),shape=(N,totalIndices))
    mat = mat.tocsr()
    return mat

rawDescription: Numpy efficient construction of sparse coo_matrix or faster list extension


rawDescription: web.py downloading images

description: Web.py downloading images


code:
whitelist = ['prop1', 'prop2', ...]

def update_entity(key, **changed_values):
  ent = key.get()
  for name, value in changed_values.items():
    if name in whitelist:
      setattr(ent, name, value)  # Or ent._properties[name]._set_value(ent, value)
  ent.put()

rawDescription: Partly update App Engine entity

description: Partly update App Engine entity


rawDescription: Execute complex bash script within Python


code:
class Article(Base):
    @hybrid_property
    def published(self):
        return self.is_published == True

    @hybrid_property
    def recent(self):
        # this relies on the date arithmetic of the target backend
        return datetime.now() - self.created_at >= datetime.timedelta(days=7)

articles = query(Article).filter(Article.published, Article.recent).all()

rawDescription: SQLAlchemy equivalent of named scopes in ActiveRecord


code:
from urllib2 import urlopen, Request
from string import ascii_uppercase, digits
from random import choice

# Open your data file
with open("C:\datafile.xml", "r") as data_file:
    data_file_string = data_file.read()

# The URL
url = 'https://api.mozenda.com/rest?WebServiceKey=[CANNOT-PROVIDE]&Service=Mozenda10&Operation=Collection.AddItem&CollectionID=1037'

# The boundary delimits where the file to be uploaded starts and where it ends.
boundary = "".join(choice(ascii_uppercase + digits)
                   for x in range(20))
body_list = []
body_list.append("--" + boundary)
body_list.append("Content-Disposition: form-data;"
                 " name='file'; filename=''")
body_list.append("Content-Type: application/octet-stream")
body_list.append("")
body_list.append(data_file_string)
body_list.append("--{0}--".format(boundary))
body_list.append("")
body="\r\n".join(body_list).encode("utf8")

content_type = ("multipart/form-data; boundary="
                "{0}").format(boundary)
headers = {"Content-Type": content_type,
           "Content-Length": str(len(body))} # Tells how big the content is

request = Request(url, body, headers)

result = urlopen(url=request).read()

rawDescription: Mozenda Bulk Insertion with Python Script


code:
#First add a dummy column
result_GB_daily_average['count'] = 1

#Then calculate a cumulative sum and divide it by 7
result_GB_daily_average['Week'] = result_GB_daily_average['count'].cumsum() / 7.0

#Then Round the weeks
result_GB_daily_average['Week']=result_GB_daily_average['Week'].round()

#Then do the group by and calculate average
result_GB_week_average = result_GB_daily_average.groupby('Week')['NREL','AVERT'].mean()

rawDescription: Group Daily Data by Week for Python Dataframe


code: psum(*x + [y])

rawDescription: Unpack positional arguments from data structure in Python


code:
def traverse(tree):

    for index, subtree in enumerate(tree):
        if type(subtree) == nltk.tree.Tree:
            traverse(subtree)
        elif type(subtree) == tuple:
            newVal = (subtree[0], subtree[1].lower())
            subtree = newVal
            tree[index] = subtree

rawDescription: Change the value of the POS tag in NLTK Tree leaf


code:
with open("file.txt") as fileobj:
    sets = [set(line.split()) for line in fileobj]
    for first_index in range(len(sets) - 2, -1, -1):
        for second_index in range(len(sets) - 1, first_index, -1):
            union = sets[first_index] | sets[second_index]
            intersection = sets[first_index] & sets[second_index]
            if len(intersection) / float(len(union)) > 0.25:
                del sets[second_index]
with open("output.txt", "w") as fileobj:
    for set_ in sets:
        # order of the set is undefined, so we need to sort each set
        output = " ".join(sorted(set_, key=lambda x: int(x[1:])))
        fileobj.write("{0}\n".format(output))

rawDescription: How to filter overlap rows in a big file in python

description: Filter overlap rows in a big file in python


code:
def call_this():
    self.wpCpuUsage.display(cpu_percent(interval=1))

self.my_timer = QtCore.QTimer()
self.my_timer.timeout.connect(call_this)
self.my_timer.start(1000) #1 second interval

rawDescription: How to have a PyQT program keep refreshing one widget, always providing an up-to-date value?

description: Have a PyQT program keep refreshing one widget, always providing an up-to-date value


code:
import matplotlib.pylab as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

x = [0, 10,20,50,100]
y=[1,2,3,10,100]

plt.plot(x, y)
plt.xscale('log')
plt.grid()

ax = plt.gca()
ax.set_xticks(x[1:]) # note that with a log axis, you can't have x = 0 so that value isn't plotted.
ax.xaxis.set_major_formatter(ScalarFormatter())

plt.show()

rawDescription: pyplot: plotting x-axis in log scale spacing but not labeling it in exponential form

description: Pyplot: plotting x-axis in log scale spacing but not labeling it in exponential form


code:
# myunittest.py
from unittest import TestProgram

class MyTestProgram(TestProgram):
    USAGE = """\
Usage: %(progName)s [options] [test] [...]

Options:
  -h, --help       Show this message
  -v, --verbose    Verbose output
  -q, --quiet      Minimal output

Examples:
  %(progName)s                               - run default set of tests
  %(progName)s MyTestSuite                   - run suite 'MyTestSuite'
  %(progName)s MyTestCase.testSomething      - run MyTestCase.testSomething
  %(progName)s MyTestCase                    - run all 'test*' test methods
                                               in MyTestCase
    """
    # additional changes here...

main = MyTestProgram

if __name__ == "__main__":
    main(module=None)

rawDescription: How can I customize python unitest.py --help?

description: Customize python unitest.py --help


code:
from matplotlib import pyplot
import pylab
from mpl_toolkits.mplot3d import Axes3D
import random

fig = pylab.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = range(0,100)
sequence_containing_y_vals = range(0,100)
sequence_containing_z_vals = range(0,100)

random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)

ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

rawDescription: How to make a 3D scatter plot in Python?

description: Make a 3D scatter plot in Python


code:
from unittest.mock import patch, MagicMock

...

def test_call_do_something(self):
    m = MagicMock()
    with patch.dict("sys.modules", something_else=m):
        input_mock = MagicMock()
        my_func(input_mock)
        m.do_something.assert_called_with(input_mock)

rawDescription: Mocking a module imported inside of a function


code:
from io import StringIO
import pandas as pd

players=StringIO(u"""Year-Week-Name
2014-1-Dan
2014-1-James
2014-2-Dan
2014-2-James""")

df_players = pd.DataFrame.from_csv(players, sep="-", parse_dates=False)
df_players = df_players.reset_index()

injuries=StringIO(u"""Year-Week-Name
2014-1-Dan
2014-1-James
2014-2-Dan""")

df_injuries = pd.DataFrame.from_csv(injuries, sep="-", parse_dates=False)
df_injuries = df_injuries.reset_index()

player_names = df_players.Name.unique().tolist()

#Create new dataframe with all names as columns
df3 = df_players[['Year','Week','Name']]#.drop_duplicates()

for name in player_names:
    df3[name] = 0

# Set injury status from injuries dataframe
for i,r in df_injuries.iterrows():
        df3.loc[(df3['Year'] == r.Year) & (df3['Week'] == r.Week),r.Name] = 1

df3

rawDescription: Create a data frame by comparing 2 data frames in Python


code:
class MyClass(object):
    """
    .. rubric:: Class variables

    :cvar foo: foo documentation
    :cvar bar: bar documentation

    .. rubric:: Instance variables

    :ivar baz: baz documentation

    """

    pass

rawDescription: Sectioning / grouping attributes inside a class


code:
import numpy as np
data = np.array([[5,2], [4,1], [3,6]])
col = 0
data[np.argsort(data[:,col])]

rawDescription: Sorting a python array/recarray by column


code:
def joint_sorted(*sequences):
    """Sorts two or more presorted sequences. The priority is in
decreasing order for the case of unambiguous elem order.

>>> joint_sorted([1,3,4,5,6], [1,2,4,6,7], [6, 10, 11], [12, 11, 17])
[1, 3, 2, 4, 5, 6, 7, 10, 12, 11, 17]
>>> joint_sorted('adgth', 'dbgjhk')
'adbgtjhk'"""
    def for_two(first_seq, second_seq):
        first_set, second_set = set(first_seq), set(second_seq)
        if (len(first_seq) != len(first_set)
            or len(second_seq) != len(second_set)):
            raise TypeError("The sequences must contain "
                "unique elems only!")
        common_elems = first_set & second_set
        before, buf = {}, []
        for i, e in iter(enumerate(second_seq)):
            if e in common_elems:
                before[e], buf = buf, []
            else:
                buf.append(e)
        result = []
        for e in first_seq:
            if e in before:
                result.extend(before[e])
            result.append(e)
        result.extend(buf)
        if isinstance(first_seq, str):
            return ''.join(result)
        return first_seq.__class__(result)
    first_seq = sequences[0]
    for i in range(1, len(sequences)):
        first_seq = for_two(first_seq, sequences[i])
    return first_seq

rawDescription: Merged sorting with gaps

description: Merged sorting with gaps


code:
def testChatChars(string):
   return re.match(r'[\x20-\x5A\x5C\x5E-\x7E]+$', string) is not None

rawDescription: Re.match always returning None in python


code:
x_indexes, _ = numpy.ogrid[:len(I), :0]
numpy.vectorize(f)(A, I, B[x_indexes, I])

rawDescription: Multidimensional indexing and mapping

description: Multidimensional indexing and mapping


code: re.subn(rgx, new_string, content, flags=re.DOTALL)

rawDescription: python regex matches but won't sub immediately afterward

description: Python regex matches but won't sub immediately afterward


code:
import os

def contained_dirs(dir):
    return filter(os.path.isdir,
                  [os.path.join(dir, f) for f in os.listdir(dir)])

rawDescription: Python "Walk" directory, max depth

description: Python "Walk" directory, max depth


code:
import os
os.system('"C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe" /command:your_command your_args /path:your_path')

rawDescription: TortoiseSVN GUI from python

description: TortoiseSVN GUI from python


code:
from pylab import *
import math
import numpy as np

def little_pie(breakdown,location,size):
    breakdown = [0] + list(np.cumsum(breakdown)* 1.0 / sum(breakdown))
    for i in xrange(len(breakdown)-1):
        x = [0] + np.cos(np.linspace(2 * math.pi * breakdown[i], 2 * math.pi *
                          breakdown[i+1], 20)).tolist()
        y = [0] + np.sin(np.linspace(2 * math.pi * breakdown[i], 2 * math.pi *
                          breakdown[i+1], 20)).tolist()
        xy = zip(x,y)
        scatter( location[0], location[1], marker=(xy,0), s=size, facecolor=
               ['gold','yellow', 'orange', 'red','purple','indigo','violet'][i%7])

figure(1, figsize=(6,6))

little_pie([10,3,7],(1,1),600)
little_pie([10,27,4,8,4,5,6,17,33],(-1,1),800)

fracs = [10, 8, 7, 10]
explode=(0, 0, 0.1, 0)
pie(fracs, explode=explode, autopct='%1.1f%%')
show()

rawDescription: Matplotlib: Draw pie chart with wedge breakdown into barchart


code: dosomething = wrap(dosomething)

rawDescription: How Python script executes?

description: How Python script executes


code:
import win32com.client
excel = win32com.client.Dispatch('Excel.Application')
excel.Visible = False # I want to keep it this way

path = "C:\\Users\\username\\Documents\\DDA"
wb_new = excel.Workbooks.Open(path + '\\new_file.xlsx')

# wb_new is a file with three tabs, with one value in cell A1 each...
# ...if you want to recreate it.

active_sheets = wb_new.Sheets.Count
for i in range(0, active_sheets):
    ws = wb_new.Worksheets(i + 1)
    ws.Columns.WrapText = False
    ws.Columns.AutoFit()
    ws.Activate() # answer starts here
    excel.ActiveWindow.Zoom = 80
    excel.ActiveWindow.DisplayGridlines = False

rawDescription: Load existing Excel file, change the zoom level for all sheets, and remove gridlines


code:
import mock

def test_do_sth():
    with mock.patch('function1.apply_async') as function1_mock:
        do_sth()
        assert function1_mock.called

rawDescription: How to unit test code that runs celery tasks?

description: Unit test code that runs celery tasks


code:
import glob
import re

pattern = re.compile(r'something(.*?)ending')
for file in glob.glob('.mydir/something**ending.csv'):
    xx = pattern.search(file).group(1)

rawDescription: Matching a string in a filename

description: Matching a string in a filename


rawDescription: Opening a child dialog window from a main window with Pyside


code: [d['jim'] for d in l]

rawDescription: Shortcut to print only 1 item from list of dictionaries


code:
import string #fixed typo was using
rot13 = string.maketrans(
    "ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
    "NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World!", rot13)
# 'Uryyb Jbeyq!'

rawDescription: Short rot13 function

description: Short rot13 function


code:
from itertools import product
test = {'a': [1, 2], 'b': ['x', 'y', 'z']}
[dict(zip(test.keys(), part)) for part in product(*test.values())]

rawDescription: How to transform a dictionary of strings to lists to a list of dictionaries?

description: Transform a dictionary of strings to lists to a list of dictionaries


code:
def update_project_filter(request):
    ...
    selected_project_id = project_form.cleaned_data["Project_Name"].id
    request.session['selected_project_id'] = selected_project_id
    ...

def update_project(request):
    ...
    selected_project_id = request.session.get('selected_project_id')
    ...

rawDescription: How to pass data between django views

description: Pass data between django views


code:
sql = ("CREATE INDEX index_my_table2 ON my_table (value);")
cursor.execute(sql)

rawDescription: sqlite3 index table in python

description: Sqlite3 index table in python


code:
arr = np.array(img)
g = arr[:,:,1]
bs = arr[:,:,2]*sensitivity
cond = g>bs
arr[:,:,1] = cond*bs + (~cond)*g
out = Image.fromarray(arr)

rawDescription: Faster method for adjusting PIL pixel values


code:
numpy.array([range(i) for i in range(50)])*.25 #these lists are of different length
numpy.array([range(50) for i in range(50)])*.25 #these lists are of the same length

rawDescription: python_list to array error

description: Python_list to array error


code:
import time
import os
import glob
from ZODB import DB
from ZODB.FileStorage import FileStorage
import transaction
from zc.blist import BList

print('STARTING')

random = open('/dev/urandom', 'rb')

def test_list(my_list, loops = 1000, element_size = 100):
    print('testing list')
    start = time.time()
    for loop in xrange(loops):
        my_list.append(random.read(element_size))
    print('appending %s elements took %.4f seconds' % (loops, time.time() - start))

    start = time.time()
    length = len(my_list)
    print('length calculated in %.4f seconds' % (time.time() - start,))

    start = time.time()
    for loop in xrange(loops):
        my_list.insert(length / 2, random.read(element_size))
    print('inserting %s elements took %.4f seconds' % (loops, time.time() - start))

    start = time.time()
    for loop in xrange(loops):
        my_list[loop] = my_list[loop][1:] + my_list[loop][0]
    print('modifying %s elements took %.4f seconds' % (loops, time.time() - start))

    start = time.time()
    for loop in xrange(loops):
        del my_list[0]
    print('removing %s elements took %.4f seconds' % (loops, time.time() - start))

    start = time.time()
    transaction.commit()
    print('committing all above took %.4f seconds' % (time.time() - start,))

    del my_list[:loops]
    transaction.commit()

    start = time.time()
    pack()
    print('packing after removing %s elements took %.4f seconds' % (loops, time.time() - start))

for filename in glob.glob('database.db*'):
    try:
        os.unlink(filename)
    except OSError:
        pass

db = DB(FileStorage('database.db'),
        cache_size = 2000)

def pack():
    db.pack()

root = db.open().root()

root['my_list'] = BList()

print('inserting initial data to blist')

for loop in xrange(10):
    root['my_list'].extend(random.read(100) for x in xrange(100000))
    transaction.commit()

transaction.commit()

test_list(root['my_list'])

rawDescription: maintaining a large list in python

description: Maintaining a large list in python


code:
import csv
with open('sample.csv', 'r') as f:
    rows=csv.DictReader(f, fieldnames=None,restkey=None,restval=None,dialect='excel',delimiter=",")
    filtered_rows=[]
    previous_flag=False
    for item in rows:
        if item['Hex'] not in ['81','80'] and not (previous_flag and  item['Hex'] == '0'):
            filtered_rows.append(item)
        previous_flag = item['Hex'] == '81'
    for i in filtered_rows :
        print (i['Hex'])

rawDescription: Filter csv rows with multiple conditions


code:
import operator

...

search_fields = {'contact_name', 'company', 'position', 'country'}

conditions = []
for name in search_fields:
    value = self.request.GET.get(name, None)
    if value:
        conditions.append(Q(**{name + "__in": value.split(',')}))

qs = qs.filter(reduce(operator.and_, conditions))

rawDescription: How to mix AND and OR operators in Django query?

description: Mix AND and OR operators in Django query


code:
ls(DNS)
ls(DNSQR)
ls(DNSRR)

rawDescription: python/scapy DNS sniffer and parser

description: Python/scapy DNS sniffer and parser


code: result = format(int(strvalue, 16) + 37, 'x')

rawDescription: How to add string representation of hex?

description: Add string representation of hex


code:
import json

...

(headers, js) = response.split("\r\n\r\n")
data = json.loads(js)
token = data["authentication-token"]
secret = data["authentication-secret"]

rawDescription: How to extract JSON data from a response containing a header and body?

description: Extract JSON data from a response containing a header and body