code:
# ...
# ModuleFinder can't handle runtime changes to __path__, but win32com uses them
try:
    # py2exe 0.6.4 introduced a replacement modulefinder.
    # This means we have to add package paths there, not to the built-in
    # one.  If this new modulefinder gets integrated into Python, then
    # we might be able to revert this some day.
    # if this doesn't work, try import modulefinder
    try:
        import py2exe.mf as modulefinder
    except ImportError:
        import modulefinder
    import win32com, sys
    for p in win32com.__path__[1:]:
        modulefinder.AddPackagePath("win32com", p)
    for extra in ["win32com.shell"]: #,"win32com.mapi"
        __import__(extra)
        m = sys.modules[extra]
        for p in m.__path__[1:]:
            modulefinder.AddPackagePath(extra, p)
except ImportError:
    # no build path setup, no worries.
    pass

from distutils.core import setup
import py2exe
# The rest of the setup file.

rawDescription: Py2exe ImportError: No module named shell


code:
a="test                            result"
a.split()

rawDescription: Python: Split by 1 or more occurrences of a delimiter


code:
for line in textfile:
    list1 = ["0","0"]
    if patterns1 in line:
        newline = line
        dict1[newline] = list1
    if patterns2 in line:
        newline2 = line
        list1[0] = newline2
        dict1[newline] = list1
    if patterns3 in line:
        newline3 = line
        list1[1] = newline3
        dict1[newline] = list1

rawDescription: python2.7: check for string in a file and update a dict/list

description: Python2.7: check for string in a file and update a dict/list


code: txt = open("file.txt").read()

rawDescription: Doc, rtf and txt reader in python

description: Doc, rtf and txt reader in python


code:
from multiprocessing import Pool

objects=['obj1','obj2','obj3',...]

def function(obj):
    result_1=search_in_genome(obj)
    return(result)

if __name__ == "__main__":
    pool = Pool()
    result_final = pool.map(function, objects)

rawDescription: Multiprocessing using maximum CPU power in Python-3.x


code:
for field in Model._meta.fields:
    field.get_attname_column()

rawDescription: Django: how to read the db_column name of a model field


code:
def give_matrix(arr,i,j):
    res = []
    for ii in range(i-2,i+3):
        inner_res = []
        for jj in range(j-2,j+3):
            if (ii-2<0 or ii+3>n or jj-2<0 or jj+3>n): # manage borders
                inner_res.append('x')
            else:
                inner_res.append(arr[ii][jj])
        res.append(inner_res)
    return res

rawDescription: 5×5 dimensional matrix from m×n matrix

description: 5×5 dimensional matrix from m×n matrix


rawDescription: How to byteswap 32bit integers inside a string in python?

description: Byteswap 32bit integers inside a string in python


code:
from glob import glob
import fileinput
import os

with open('output.txt', 'w') as out:
    files = (os.path.join(p, f) for p, ds, fs in os.walk(os.curdir) for f in fs)
    for line in fileinput.input(files):
        if 'Subject:' in line:
            out.write(line)

rawDescription: extract lines from sub-folders using os.walk() module in Python?

description: Extract lines from sub-folders using os.walk() module in Python


code:
class Worker(QThread):
  def __init__(self, do_create_data=True, parent=None):
    super, etc
    self.do_create_data = create_data

  def run(self):
     if self.create_data:
         self.create_data()
     else:
         self.upload_data(), depends

rawDescription: Passing an argument when starting new QThread() in PyQt


code:
import numpy.lib.recfunctions as nlr
x = np.array(zip((1, 2), (3., 4.)), dtype=[('i', 'i4'), ('f', 'f4')])
y = np.array(zip(('a', 'b')), dtype=[('s', 'a10')])
x
y
z = nlr.merge_arrays([x, y], flatten=True)
z

rawDescription: How to hstack arrays of numpy records?

description: Hstack arrays of numpy records


code:
import random

numbers = {'x': 0, 'y': 0}

def randomnumbers():
    for x in range(100):
        n = random.randint(1, 8)

        if 1 <= n <= 5:
            numbers['x'] += 1
            print('%dx' % n)
            # E.g. 1x
        elif 6 <= n <= 8:
            numbers['y'] += 1
            print('%dy' % n)
            # E.g. 7y

randomnumbers()
print('x %d times' % numbers['x'])
# E.g. x 61 times
print('y %d times' % numbers['y'])
# E.g. y 39 times

rawDescription: In my python program how do I count the number of times a value has occurred


code:
import cv2

im = cv2.imread('c:/data/ph.jpg')
gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
contours,hierarchy = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
idx =0
for cnt in contours:
    idx += 1
    x,y,w,h = cv2.boundingRect(cnt)
    roi=im[y:y+h,x:x+w]
    cv2.imwrite(str(idx) + '.jpg', roi)
    #cv2.rectangle(im,(x,y),(x+w,y+h),(200,0,0),2)
cv2.imshow('img',im)
cv2.waitKey(0)

rawDescription: Extract all bounding boxes using OpenCV Python


code:
import gzip

content = b"Some content"
f = open("/tmp/f.gz", "wb")
gz = gzip.GzipFile(fileobj=f,mode="wb",filename="",mtime=0)
gz.write(content)
gz.close()
f.close()

rawDescription: setting the gzip timestamp from Python

description: Setting the gzip timestamp from Python


code:
len(BeautifulSoup(r.text, 'html').find('td', attrs={'class': 'eelantext'}).find_all('p'))
len(BeautifulSoup(r.text, 'lxml').find('td', attrs={'class': 'eelantext'}).find_all('p'))
len(BeautifulSoup(r.text, 'html5lib').find('td', attrs={'class': 'eelantext'}).find_all('p'))

rawDescription: Missing parts on Beautiful Soup results

description: Missing parts on Beautiful Soup results


code:
import sys
t = tuple(sys.argv[1:]) # since sys.argv[0] is the name of the script

rawDescription: Python: Create a tuple from a command line input


code:
headers = {
"User-Agent":
    "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
}
s = requests.session()
s.headers.update(headers)

for cookie in driver.get_cookies():
    c = {cookie['name']: cookie['value']}
    s.cookies.update(c)

rawDescription: Is it possible to "transfer" a session between selenium.webdriver and requests.session


code:
string = open('file_with_string.html', 'r').read()
doc = lxml.html.document_fromstring(string)

rawDescription: how to parse the file?

description: Parse the file


rawDescription: Conditionals for evaluating True and False in a python list comprehension?


code:
maxlevel = 5
currentlevel = [1]

for levels in range(maxlevel):
    nextlevel = [1]
    for index,item in enumerate(currentlevel[0:-1]):
        if (len(currentlevel) == 1):
            break

        nextlevel.append(item + currentlevel[index + 1])

    nextlevel.append(1)

    print(nextlevel)

    currentlevel = nextlevel

rawDescription: Python. Pascal's triangle

description: Python. Pascal's triangle


code:
from PyQt4 import QtGui, QtCore, uic
import sys

# Here you can add your ui path from desigener, no need to convert
RESOURCE_PATH             = package.__BASERESLOC__
baseUI                    = os.path.join(RESOURCE_PATH, "base_main.ui")
baseUIClass, baseUIWidget = uic.loadUiType(baseUI)

class BASEGUICLS(baseUIWidget, baseUIClass):
    def __init__(self,parent=None):
        super(BASEGUICLS, self).__init__(parent)
        self.setupUi(self)
        #after this you will have everything
        self.pushButton.setText("Foo")

def main():
    """
    Main function which init main GUI.
    """
    app = QtGui.QApplication(sys.argv)
    ex = BASEGUICLS(None)
    ex.show()
    sys.exit(app.exec_())

rawDescription: Converting pyqt ui files into py files

description: Converting pyqt ui files into py files


code:
"""
:rtype: (string, int, int)
"""

rawDescription: Documenting `tuple` return type in a function docstring for PyCharm type hinting


rawDescription: Pointers in python, v+=[] vs. v=v+[]

description: Pointers in python, v+=[] vs. v=v+[]


code:
from subprocess import Popen, PIPE, STDOUT
with open('debug.log', 'a') as log:
    log.write('Starting subprocess\n')
    log.flush()
    handle = Popen('winexe --system -U user%password //ip_client "cmd /C wmic os get osarchitecture"', shell=True, stdout=PIPE, stderr=STDOUT, stdin=PIPE)
    log.write('Outputting everything that the subprocess does...\n')
    log.flush()
    while handle.poll() is None:
        log.write('Output: ' + str(handle.stdout.read()) + '\n')
        log.flush()
    log.write('Command ended with code: ' + str(handle.poll()) + '\n')
    log.flush()
    handle.stdout.close()
    handle.stdin.close()

rawDescription: Winexe doesn't exit if launched from apache


code:
maximum = max(mydict, key=mydict.get)  # Just use 'min' instead of 'max' for minimum.
print(maximum, mydict[maximum])
# D 87

rawDescription: print highest value in dict with key

description: Print highest value in dict with key


code:
int(n ** 0.5 + 1) == 4
math.ceil(math.sqrt(n)) == 3

rawDescription: Math differences?

description: Math differences


code:
btoc = dict(zip(B, C))
A2 = np.array(map(btoc.get, A))
A2

rawDescription: Python: finding index of all elements of array in another including repeating arrays


code: total_avg = sum( map(len, strings) ) / len(strings)

rawDescription: Finding average length of strings in a list


rawDescription: How to calculate a percentage using grouped columns in Pandas python?

description: Calculate a percentage using grouped columns in Pandas python


code:
class RecipeContent(models.Model):
  ...
  def __unicode__(self):
    # You can access ForeignKey properties through the field name!
    return self.recipe.name

rawDescription: Can I use a ForeignKey in __unicode__ return?

description: Use a ForeignKey in __unicode__ return


code:
import maya.cmds as cmds

def refresher():
    # the function which does the closing/refreshing
    pass

cmds.scriptJob(e=["NewSceneOpened", refresher])
cmds.scriptJob(e=["SceneOpened", refresher])
cmds.scriptJob(e=["flushingScene", refresher])

rawDescription: Detecting Close Scene or Change Scene

description: Detecting Close Scene or Change Scene


code:
def getUniqueEntry(dictionary1, dictionary2, listOfKeys):
    assert sorted(dictionary1.keys()) == sorted(dictionary2.keys()), "Keys don't match"  #check that they have the same keys
    for key in dictionary1:
        if dictionary1[key] != dictionary2[key]:
            listOfKeys.append(key)

rawDescription: Comapring dictionary with list type values


code:
from surrogate import surrogate
from mock import patch

@surrogate('this.module.doesnt.exist')
@patch('this.module.doesnt.exist', whatever)
def test_something():
    from this.module.doesnt import exist
    do_something()

rawDescription: How do I mock the hierarchy of non-existing modules?

description: Mock the hierarchy of non-existing modules


code:
index=np.argmax(a)
max=a(index)

rawDescription: Numpy argmax. How to compute both max and argmax?


code:
"""A helper class for managing batch normalization state.

This class is designed to simplify adding batch normalization
(http://arxiv.org/pdf/1502.03167v3.pdf) to your model by
managing the state variables associated with it.

Important use note:  The function get_assigner() returns
an op that must be executed to save the updated state.
A suggested way to do this is to make execution of the
model optimizer force it, e.g., by:

  update_assignments = tf.group(bn1.get_assigner(),
                                bn2.get_assigner())
  with tf.control_dependencies([optimizer]):
    optimizer = tf.group(update_assignments)

"""

import tensorflow as tf

class ConvolutionalBatchNormalizer(object):
  """Helper class that groups the normalization logic and variables.

  Use:
      ewma = tf.train.ExponentialMovingAverage(decay=0.99)
      bn = ConvolutionalBatchNormalizer(depth, 0.001, ewma, True)
      update_assignments = bn.get_assigner()
      x = bn.normalize(y, train=training?)
      (the output x will be batch-normalized).
  """

  def __init__(self, depth, epsilon, ewma_trainer, scale_after_norm):
    self.mean = tf.Variable(tf.constant(0.0, shape=[depth]),
                            trainable=False)
    self.variance = tf.Variable(tf.constant(1.0, shape=[depth]),
                                trainable=False)
    self.beta = tf.Variable(tf.constant(0.0, shape=[depth]))
    self.gamma = tf.Variable(tf.constant(1.0, shape=[depth]))
    self.ewma_trainer = ewma_trainer
    self.epsilon = epsilon
    self.scale_after_norm = scale_after_norm

  def get_assigner(self):
    """Returns an EWMA apply op that must be invoked after optimization."""
    return self.ewma_trainer.apply([self.mean, self.variance])

  def normalize(self, x, train=True):
    """Returns a batch-normalized version of x."""
    if train:
      mean, variance = tf.nn.moments(x, [0, 1, 2])
      assign_mean = self.mean.assign(mean)
      assign_variance = self.variance.assign(variance)
      with tf.control_dependencies([assign_mean, assign_variance]):
        return tf.nn.batch_norm_with_global_normalization(
            x, mean, variance, self.beta, self.gamma,
            self.epsilon, self.scale_after_norm)
    else:
      mean = self.ewma_trainer.average(self.mean)
      variance = self.ewma_trainer.average(self.variance)
      local_beta = tf.identity(self.beta)
      local_gamma = tf.identity(self.gamma)
      return tf.nn.batch_norm_with_global_normalization(
          x, mean, variance, local_beta, local_gamma,
          self.epsilon, self.scale_after_norm)

rawDescription: How could I use Batch Normalization in TensorFlow?


code:
class Moment(db.Model):
    user = db.IntegerProperty()
    index = db.IntegerProperty()
    date = db.DateTimeProperty()
    qx = db.FloatProperty()
    qy = db.FloatProperty()
    qz = db.FloatProperty()
    qw = db.FloatProperty()
    latitude = db.FloatProperty()
    longitude = db.FloatProperty()
    image = db.BlobProperty()

class UploadHandler(webapp2.RequestHandler):
    def post(self):
        obj = biplist.readPlistFromString(self.request.body)
        Moment(user = obj['user'],
               index = obj['index'],
               date = obj['date'],
               qx = obj['qx'],
               qy = obj['qy'],
               qz = obj['qz'],
               qw = obj['qw'],
               latitude = obj['latitude'],
               longitude = obj['longitude'],
               image = obj['image']).put()

rawDescription: GAE Python TypeError on datastore filter query


code:
from flask import session

color = 'blue'
session['usr_fav_color'] = color

rawDescription: Client-side variables in Flask?

description: Client-side variables in Flask


code:
def getCoordinates(filename):
    '''
    Pass in a filename.
    Return a parsed dictionary in the form of:

    {
        city:  [lat, lon]
    }
    '''

    fin = open(filename,"r")
    cities = {}

    for line in fin:

        # this is going to split on the comma, and
        # only once, so you get the city, and the rest
        # of the line
        city, extra =  line.split(',', 1)

        # we could do a regex, but again, I dont think
        # you know what a regex is and you seem to already
        # understand split. so lets just stick with that

        # this splits on the '[' and we take the right side
        part = extra.split('[')[1]

        # now take the remaining string and split off the left
        # of the ']'
        part = part.split(']')[0]

        # we end up with something like: '4660, 12051'
        # so split that string on the comma into a list
        latLon = part.split(',')

        # associate the city, with the latlon in the dictionary
        cities[city] = latLong

    return cities

rawDescription: How do I read from a file consists of city names and coordinates/Populations and create functions to get the coordinates and population?

description: Read from a file consists of city names and coordinates/Populations and create functions to get the coordinates and population


code:
import csv
with open('../path/to/file.csv', 'w') as f:
    csv_writer = csv.writer(f)
    csv_writer.writerows(your_row_data)

rawDescription: Reading and Writing data in CSV files in Python


code:
from eventlet import *
patcher.monkey_patch(all=True)

import os, sys, time
from boto.s3.connection import S3Connection
from boto.s3.bucket import Bucket

import logging

logging.basicConfig(filename="s3_download.log", level=logging.INFO)

def download_file(key_name):
    # Its imp to download the key from a new connection
    conn = S3Connection("KEY", "SECRET")
    bucket = Bucket(connection=conn, name="BUCKET")
    key = bucket.get_key(key_name)

    try:
        res = key.get_contents_to_filename(key.name)
    except:
        logging.info(key.name+":"+"FAILED")

if __name__ == "__main__":
    conn = S3Connection("KEY", "SECRET")
    bucket = Bucket(connection=conn, name="BUCKET")

    logging.info("Fetching bucket list")
    bucket_list = bucket.list(prefix="PREFIX")

    logging.info("Creating a pool")
    pool = GreenPool(size=20)

    logging.info("Saving files in bucket...")
    for key in bucket.list():
        pool.spawn_n(download_file, key.key)
    pool.waitall()

rawDescription: Fastest way to download 3 million objects from a S3 bucket


code:
def afunc():
    foo.set('A')
    tempchoice.set('afuncaction')
    global myfunc
    myfunc = afuncaction # save a reference to this function

...

if messagebox.askyesno:
    myfunc()

rawDescription: Using a variable to call a function in Python 3 and tkinter


code:
import pymysql

# URL DATA
input = []  ## LIST OF LISTS
for id in IDlist:
     url='www.example.com/'+str(id)
     values=requests.get(url) ##some parse omitted
     input.append([values[1],values[2],id])

# DATABASE UPDATE
connection = pymysql.connect(
            host='localhost', db='test_db',
            user='root', passwd='***')
mycursor = connection.cursor()

for items in input:
     sql="""UPDATE mytable
         SET COL1=%s, COL2=%s
         WHERE ID=%s"""
     mycursor.execute(sql, tuple(items))
     connection.commit()

mycursor.close()  ## here all loops done
connection.close()  ## close db connection

rawDescription: Update data to Mysql in a while loop with Python: Only partial data was saved


code:
import hashlib
import struct

cha1 = struct.pack('16B', *[int(c, 16) for c in (challenge[i:i+2]
    for i in xrange(0, len(challenge), 2))])

word = hashlib.md5('\0%s%s' % (word, cha1)).hexdigest()

rawDescription: from php to django for pack('H32',$challenge) and md5("\0" . $word . $challenge)

description: From php to django for pack('H32',$challenge) and md5("\0" . $word . $challenge)


code:
def graph(numX, xWidth, scaleY, radius=2):
    minY = 0
    offsetX = -200
    for xVal in range(numX):

        x = offsetX + (xVal*xWidth)
        rand = random.random()
        y = minY + int(rand*scaleY)
        turtle.penup()
        turtle.goto(x,y)
        turtle.pendown()
        turle.circle(radius)

graph(20, 20, 100, 5)

turtle.mainloop()

rawDescription: I'm trying to run this graph with turtle and turtle is not even coming up


rawDescription: How to look up two directories in Python?

description: Look up two directories in Python


code:
data = np.zeros((2,2))
data
from pandas import DataFrame
df  = DataFrame(data, index = ['first', 'second'], columns=['c1','c2'])
df
i = df.index
c = df.columns
df  = DataFrame(np.random.rand(2,2), index = i, columns=c)
df

rawDescription: Keep pandas structure with numpy/scikit functions


code:
class childclass(parentclass):
    def somefunction(self):
        with patch('somemodule.parentclass', childclass):
            super(childclass, self).somefunction()

rawDescription: Instantiate children class from parent without changing parent code


code:
bool(1)
bool(34)
bool(0)

rawDescription: How does an int evaluate as a boolean statement?


code:
class ShoppingList(Base):
    thing1_id = Column(Integer, primary_key=True)
    thing2_id = Column(Integer, primary_key=True)

rawDescription: A django like unique together in turbogears/sqlalchemy


code: self._thread = Thread(target=self.run)

rawDescription: Python thread dont start

description: Python thread dont start


rawDescription: Pandas: Using Unix epoch timestamp as Datetime index


code:
xlabels = [1, 2, 3, 4]
[xlabels[i] if i % 2 != 0 else '' for i in range(len(xlabels))]

rawDescription: python list comprehension by step of 2

description: Python list comprehension by step of 2


rawDescription: Pairwise cdist in scipy instead of zip

description: Pairwise cdist in scipy instead of zip


code:
from django.db.models import IntegerField, Sum, Case, When

workers = Worker.objects.annotate(
              num_jobs=Sum(
                  Case(
                      When(job__is_completed=True, then=1),
                      default=0,
                      output_field=IntegerField()
                  )
               )
           )

rawDescription: Django exclude from annotation count

description: Django exclude from annotation count


code:
class DateTimeFieldTz(models.DateTimeField):

    def from_db_value(self, value, expression, connection, context):
        if value is None:
            return None
        else:
            return django.utils.timezone.localtime(value)

rawDescription: How to get local datetime from django model DateTimeField?

description: Get local datetime from django model DateTimeField


code:
cur.execute('select * from Updates')

# extract column names
column_names = [d[0] for d in cur.description]

for row in cur:
  # build dict
  info = dict(zip(column_names, row))

  # dump it to a json string
  reply = json.dumps(info)

rawDescription: How to read data out of a SQLite database, into a dictionary before encoding it in JSON?

description: Read data out of a SQLite database, into a dictionary before encoding it in JSON


code:
allkeys = ...  # might be known; or obtained from available dicts by union;
               # 'xKey' can be removed at this stage to simplify the list
               # comprehension that follows
sortedKeys = sorted(allKeys)
list_of_values = [[d.get(k) for k in sortedKeys if k in d]
                                                   for d in list_of_dicts]

rawDescription: Order of values when extracting Python dict to list


rawDescription: get image from hexa string

description: Get image from hexa string


code:
loc_Con = hxs.select('/tr/td[2]/span/span/span') #for country
loc_Reg = hxs.select('/tr/td[2]/span/span') #for region
loc_Loc = hxs.select('//tr[3]/td[2]/span/span') #for local
items = []
for titles in titles:
   item = somethingItem()
   temp1 = loc_Con.select('text()').extract()
   temp2 = loc_Reg.select('text()').extract()
   temp3 = loc_Loc.select('text()').extract()
   temp1 = temp1[0] if temp1 else ""
   temp2 = temp2[0] if temp2 else ""
   temp3 = temp3[0] if temp3 else ""
   item["code"] = "{0}-{1}-{2}".format(temp1,
                                       temp2,
                                       temp3)

rawDescription: temporary variable in scrapy

description: Temporary variable in scrapy


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

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

x = 0.7 * np.outer(np.cos(u), np.sin(v))
y = 0.4 * np.outer(np.sin(u), np.sin(v))
z = 0.1 * np.outer(np.ones(np.size(u)), np.cos(v))
ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')
ax.set_xlim([-0.5, 0.5])
ax.set_ylim([-0.5, 0.5])
ax.set_zlim([-0.5, 0.5])

plt.show()

rawDescription: Same range for axes x y z

description: Same range for axes x y z


code:
from collections import OrderedDict

D = OrderedDict()

with open("fin.txt") as fin:
    for line in fin:
        if line.isspace():   # Guard against empty lines
            continue
        molecule, sep, activity = line.partition(" ")
        activity = float(activity)
        if molecule in D:
            if activity > D[molecule]:
                D[molecule] = activity
                D.move_to_end(molecule)
        else:
            d[molecule] = activity

rawDescription: removing multiple entries with duplicate values from a list while preserving order

description: Removing multiple entries with duplicate values from a list while preserving order


code: [Text(i) for i in range(0, 5)]

rawDescription: How can I define any number of variables without first setting the number?

description: Define any number of variables without first setting the number


code:
import string
import random

def generate_similar(string):
    # Generates similar name by substituting vowels
    similar_word = []
    for char in string:
        if char.lower() in 'aeiou':
           similar_word.append(random.choice(string.letters).lowercase())
        else:
            similar_word.append(char)
    return ''.join(similar_word)

rawDescription: Generate similar domain names with Python


code:
import os
import re

REGEX = re.compile("Slide([0-9]+).png")

for filename in os.listdir('.'):
    match_ = re.match(REGEX, filename)
    if match_:
        slide_n = int(match_.group(1)) + 121
        os.rename(filename, "Slide{}.png".format(slide_n))

rawDescription: Rename files that are already sorted (Python 3.3)


code:
from Tkinter import *
import tkFileDialog

class View(Listbox):
    def __init__(self, master):
        Listbox.__init__(self, master)      #makes view class listbox

class Controller(object):
    def __init__(self, master):
        """ Main interface:
        master - the top level window
        """
        self._master = master

        frame1 = Frame(self._master)
        frame1.pack(side=TOP, fill=BOTH, padx=5,expand=True)

        self._Listbox=View(frame1)
        self._Listbox.pack(side = TOP,fill=BOTH, expand = True,pady=20)

        menubar = Menu(self._master)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command = self.file_open)
        menubar.add_cascade(label='File',menu=filemenu)
        self._master.config(menu=menubar)

    def file_open(self):
        filename = tkFileDialog.askopenfilename()

        #insert each line in the file into the listbox
        with open(filename,'r') as f:
            for line in f:
                self._Listbox.insert(END,line)

if __name__ == "__main__":
    root=Tk()
    c=Controller(root)
    root.mainloop()

rawDescription: Python - GUI - Tkinter listboxes

description: Python - GUI - Tkinter listboxes


code:
class createdbentry(forms.ModelForm):

    choices = ( (1,'Yes'),
                (0,'No'),
              )

    class Meta:
        model = Mymodelname

    def __init__(self, *args, **kwargs):
        super(createdbentry, self).__init__(*args, **kwargs)

        BinaryFieldsList = ['FirstFieldName', 'SecondFieldName', 'ThirdFieldName']
        for field in BinaryFieldsList:
            self.fields[field].widget = forms.RadioSelect(choices=choices)

rawDescription: Django / Python, Using Radio Button for boolean field in Modelform?


code:
class User(db.Model):
    def readonly(self):
        return ReadOnlyUser(self.name, self.id);

rawDescription: Exposing a "dumbed-down", read-only instance of a Model in GAE


code:
import sys
sys.stdout.write('something')
bytes_written = sys.stdout.write('something')

rawDescription: In python, why does sys.stdout.write() behave differently between running it inside command line and running it inside a script


code:
import random
import unittest
import mock

def choice(states):
    states = list(states)
    rnd = random.random()
    for state, p in states:
        rnd -= p
        if rnd <= 0:
            return state

class Tests(unittest.TestCase):
    @mock.patch('random.random')
    def test_first_state_fires(self, random_call):
        random_call.return_value = 1
        self.assertEquals(choice([(1, 1)]), 1)

    @mock.patch('random.random')
    def test_returns_none(self, random_call):
        random_call.return_value = 2
        self.assertIsNone(choice([(1, 1)]))

rawDescription: Python injecting random number into tests


code:
import pdb
pdb.set_trace()

rawDescription: Can I put a breakpoint in a running Python program that drops to the interactive terminal?

description: Put a breakpoint in a running Python program that drops to the interactive terminal


code:
c = numpy.r_[0, A.cumsum()][indices]
sums = c[:,1] - c[:,0]

rawDescription: Numpy sum of values in subarrays between pairs of indices


code:
import uuid
from django.db import models

def make_uuid():
   """Return UUID4 string."""
   return str(uuid4())

class UUIDModel(models.Model):

   uuid = models.CharField(
      editable=False, max_length=36, db_index=True,
      unique=True, default=make_uuid
   )

   class Meta:
      abstract = True

class RealModel(UUIDModel):

   name = models.CharField(max_length=36)

   def do_something(self):
      pass

rawDescription: Best way to create a more complex model autofield in django?

description: Create a more complex model autofield in django


code:
intervals = int((last_date - first_date).total_seconds()) // (60*30)
no_date = [first_date + datetime.timedelta(seconds=i*60*30)
           for i in range(0, intervals)
           if first_date + datetime.timedelta(seconds=i*60*30) not in fixed_days]

rawDescription: Python: Getting the missing datetime intervals


code:
import os
os.system("THEANO_FLAGS='device=gpu0' python myscript.py")
os.system("THEANO_FLAGS='device=gpu1' python myscript.py")

rawDescription: Select GPU during execution in Theano

description: Select GPU during execution in Theano


code:
import Tkinter as tk
...
entry1 = tk.Entry(...)
entry1.focus_set()

rawDescription: Python tkinter entrybox cursor

description: Python tkinter entrybox cursor


code:
from pyramid.events import NewRequest
from pyramid.events import subscriber

@subscriber(NewRequest)
def setAcceptedLanguagesLocale(event):
    if not event.request.accept_language:
        return
    accepted = event.request.accept_language
    event.request._LOCALE_ = accepted.best_match(('en', 'fr', 'de'), 'en')

rawDescription: Determine the user language in Pyramid

description: Determine the user language in Pyramid


code:
class TestApp(App):
    def msg_in(self, btn):
        msg = Message()
        msg.size_hint = [None, None]
        self.msg_layout.add_widget(msg)
        self.sv1_main.scroll_to(msg)
    # ...

rawDescription: How to automatically scroll down in a Kivy ScrollView?

description: Automatically scroll down in a Kivy ScrollView


rawDescription: How to specify the multicast SEND interface in Python?

description: Specify the multicast SEND interface in Python


rawDescription: Create column from non null values in other column in Pandas


code:
class MyModel(ndb.Model):
    title = ndb.StringProperty()

    def _post_put_hook(self, future):
        fields = [search.TextField(name='title', value=self.title)]
        doc    = search.Document(doc_id=self.key.id(), fields=fields)
        search.Index('index-name').put(doc)
        ...

rawDescription: How frequently should I rebuild my App Engine search index (full text search)?


code:
#!/usr/bin/env python
import random
import io

list1 = [line.strip() for line in io.open('data.txt', 'r', encoding="utf-8-sig")]

rndword = random.choice(list1)
brokenword = list(rndword)
print(brokenword)

rawDescription: Editing large Python file consumes systems resources


code:
import re
import json
for line in logs:
    for t in re.finditer(r"\{.*\}", line):
        try:
            json.loads(t.group())
        except ValueError:
            pass

rawDescription: how to read JSON object from raw text file using python

description: Read JSON object from raw text file using python


code:
with open('/path/to/file', 'w') as outFile:
  outFile.write("new contents\n")

rawDescription: python overwrite and append to text file

description: Python overwrite and append to text file


code:
class Vector:

    def __init__(self, entries):

        self.elements = []
        for e in entries:
            self.elements.append(self.process(e))

    def __str__(self):

        buff = ''
        for e in self.elements:
            buff += str(e)
        return buff

rawDescription: How can I use the value of a variable in the name of another without using a dictionary in python?

description: Use the value of a variable in the name of another without using a dictionary in python


code:
# Import smtplib for the actual sending function
import smtplib

# Here are the email package modules we'll need
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '

# Create the container (outer) email message.
msg = MIMEMultipart()
msg['Subject'] = 'Our family reunion'
# me == the sender's email address
# family = the list of all recipients' email addresses
msg['From'] = me
msg['To'] = COMMASPACE.join(family)
msg.preamble = 'Our family reunion'

# Assume we know that the image files are all in PNG format
for file in pngfiles:
    # Open the files in binary mode.  Let the MIMEImage class automatically
    # guess the specific image type.
    fp = open(file, 'rb')
    img = MIMEImage(fp.read())
    fp.close()
    msg.attach(img)

# Send the email via our own SMTP server.
s = smtplib.SMTP('localhost')
s.sendmail(me, family, msg.as_string())
s.quit()

rawDescription: python - send email along with attachment

description: Python - send email along with attachment


code:
class CarSerializer(serializers.ModelSerializer):
    photo_url = serializers.SerializerMethodField()

    class Meta:
        model = Car
        fields = ('id','name','price', 'photo_url')

    def get_photo_url(self, car):
        request = self.context.get('request')
        photo_url = car.photo.url
        return request.build_absolute_uri(photo_url)

rawDescription: Django serialize imagefield to get full url


code: ('/.*\.json', JSONHandler)

rawDescription: Invoking Specific Handler according to Exension


code:
fruit = [df.columns[row.astype(bool)].tolist() for row in df.values]
pprint.pprint(fruit)

rawDescription: Convert pandas dataframe to a list

description: Convert pandas dataframe to a list


code: hex(ord("B"))

rawDescription: Python character to keyboard hex

description: Python character to keyboard hex


code:
strs="# Nmap done at Tue Nov 27 10:09:18 2012 -- 512 IP addresses (17 hosts up) scanned in 143.58 seconds"
re.findall("(\d+)\s+IP address",strs)
re.findall("(\d+)\s+hosts up",strs)

rawDescription: Extract specific values out of string in Python


rawDescription: Regex replacing a string while saving parts of it


code:
class Named(object):
    """Named object mix-in. Not useable directly."""
    def __setattr__(self, name, value):
        if hasattr(self, name):
            raise AttributeError(
                "%r object attribute %r is read-only" %
                (self.__class__.__name__, name))
        else:
            raise AttributeError(
                "Cannot add attribute %r to %r object" %
                (name, self.__class__.__name__))

    def __new__(cls, name, *args):
        self = super(Named, cls).__new__(cls, *args)
        super(Named, self).__setattr__('_name', name)
        return self

    def __str__(self):  # override string conversion to be name
        return self._name

    __repr__ = __str__

class NamedInt(Named, int):
    """NamedInt class. Constructor will return a NamedLong if value is big."""
    def __new__(cls, name, *args):
        value = int(*args) # will raise an exception on invalid arguments
        if isinstance(value, int):
            return super(NamedInt, cls).__new__(cls, name, value)
        elif isinstance(value, long):
            return NamedLong(name, value)

class NamedLong(Named, long):
    """Nothing to see here."""
    pass

rawDescription: Avoid having two different numeric subclasses?


code:
custom_text = "foo bar"

# addText(picture, xpos, ypos, text)
# add text "foo bar" to custom_picture, starting at (15, 50)
addText(custom_picture, 15, 50, custom_text)

# add text "kung-foo bar" to custom_picture2, starting at (40, 20)
addText(custom_picture2, 40, 20, "kung-" + custom_text)

new_custom_text = "kung-" + custom_text
# add text "kung-foo bar" to new_custom_picture, starting at (10, 30)
addText(new_custom_picture, 10, 30, new_custom_text)

rawDescription: How do I add a variable's value to a picture in JES/ Jython?

description: Add a variable's value to a picture in JES/ Jython


code: datetime.datetime(2004, 12, 3)

rawDescription: Pythonic way to make datetime object

description: Pythonic way to make datetime object


code:
profile = form.save(commit=False)
profile.user = request.user
profile.save()

rawDescription: Set user field in a form object created using ModelForm


code:
XList=[2,3,4,5,5,6]
YList=['A','A','A','B','A','A']
idx = []
for i in range(len(XList)-1):
   if XList[i]==XList[i+1]: idx.append(i)
   else:
      if len(idx)>=1:
        idx.append(i)
        YList[idx[0]:idx[-1]+1] = sorted(YList[idx[0]:idx[-1]+1])
        idx=[]

YList
df = pd.DataFrame({'X':XList,
                   'Y':YList})
df

rawDescription: Reorder pandas DataFrame with specific rules


code:
for i, item in enumerate(lst):
    if item == 1:
      list[i] = 0

rawDescription: Some questions about python list element and list comprehensions


code:
l = ["one", "two", 3]
all(isinstance(item, str) for item in l)
l = ["one", "two", '3']
all(isinstance(item, str) for item in l)

rawDescription: How to check if all items in list are string

description: Check if all items in list are string


code:
from matplotlib.lines import Line2D
from matplotlib import pyplot

f=pyplot.figure()
a=f.add_subplot(111)
a.plot([3,1,4,1,5,9,2], color='k') # so you have some content
a.add_line(Line2D([0.5, 0.5], [0, 1], transform=a.transAxes,
                  linewidth=2, color='b'))
pyplot.show()

rawDescription: How to draw an axis in the middle of the figure using Matplotlib

description: Draw an axis in the middle of the figure using Matplotlib


code:
from functools import reduce
reduce(getattr, "X.Y.Z".split('.'), doc)

rawDescription: Python Chain getattr as a string

description: Python Chain getattr as a string


code:
from numpy import *
import matplotlib.pylab as pl

def gibbs_sampler(alpha,delta,gamma,y,t):
    #initialize beta
    beta=1

    num_iter=100

    beta_draws=[]
    lambda_draws=[]

    for i in range(num_iter):
        #sample lambda given other lambdas and beta
        lambdas=lambda_update(alpha,beta,y,t)

        #record sample
        lambda_draws.append(lambdas)

        #sample beta given lambda samples
        beta=beta_update(alpha,gamma,delta,lambdas,y)

        #record sample
        beta_draws.append(beta)

    pl.plot(beta_draws)
    pl.show()

def lambda_update(alpha,beta,y,t):

    new_alpha=[(x+alpha) for x in y]
    new_beta=[1.0/(a+beta) for a in t]#Changed here

    #sample from this distribution 10 times
    samples=random.gamma(new_alpha,new_beta)
    return samples

def beta_update(alpha,gamma,delta,lambdas,y):
    #get sample
    sample=random.gamma(len(y)*alpha+gamma,
                        1.0 / (delta+sum(lambdas)))#Changed here
    return sample

def main():

    y=[5,1,5,14,3,19,1,1,4,22]
    t=[94,16,63,126,5,31,1,1,2,10]

    alpha=1.8
    gamma=0.01
    delta=1

    gibbs_sampler(alpha,delta,gamma,y,t)

if __name__ == '__main__':
    main()

rawDescription: Python Gibbs Sampler not working

description: Python Gibbs Sampler not working


code:
Dict1['var1'] = {'value':20, 'result':None}
Dict1['var2'] = {'value':30, 'result':None}
Dict2['var1'] = {'value':23, 'result':None}
Dict2['var2'] = {'value':26, 'result':None}

if Dict1['var1']['value']  < Dict2['var1']['value']:
    Dict2['var1']['result'] = True

rawDescription: How can store multidimension array in django python


code:
from __future__ import print_function

with open(radFile) as rad:
    counter = 0
    zonefile = open(r'd:\zones\{}.rad'.format(counter),'w')
    for line in rad:
        if not line.startswith("#"):
            if zonefile.closed:
                counter += 1
                zonefile = open(r'd:\zones\{}.rad'.format(counter),'w')
            print(line, file=zonefile)
        else:
            zonefile.close()
    zonefile.close()

rawDescription: How to capture non commented lines of code from a text file?

description: Capture non commented lines of code from a text file


code:
import tkinter as tk

root = tk.Tk()
textfield = tk.Text(root)
textfield.pack()
textfield.focus()
root.mainloop()

rawDescription: default entry field in tkinter with python

description: Default entry field in tkinter with python


code:
import pygame
from itertools import cycle

pygame.init()
screen = pygame.display.set_mode((300, 300))
s_r = screen.get_rect()

timer = pygame.time.Clock()

movement = "straight"

x = 0
player = pygame.Rect((x, 100, 50, 50))

while True:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise

    if movement == 'straight':
      x += 10
      player = pygame.Rect((x, 100, 50, 50))

    if x >= 300:
      x = 0

    screen.fill(pygame.color.Color('Black'))
    pygame.draw.rect(screen, pygame.color.Color('Grey'), player)

    pygame.display.flip()
    timer.tick(25)

rawDescription: Making image move straight with pygame

description: Making image move straight with pygame


code:
def __init__(self):
    ...
    self.items = {'1':['a','b','c'],'2':['d','e','f'],'3':['g','h','i']}
    self.Combobox_1.activated[str].connect(self.on_combo_activated)
    ...

...

def on_combo_activated(self, text):
    self.Combobox_2.clear()
    self.Combobox_2.addItems(self.items[text])

rawDescription: PyQT4 Combobox changes the list of another combobox


code:
filedata = file.read()  # Cache once

year = re.search(r'Popularity\sin\s\d{4}', filedata)  # Search in cache
print(year)

#find
1	Michael	Ashley
rank_names = re.search(r'\d*	\w*	\w*	', filedata)  # Search cache again
print(rank_names)

rawDescription: Python 3 re.findall closing file?

description: Python 3 re.findall closing file


code:
a, b, c, d = 1, 2, 3, 4.44
my_tup = (a, b, c, d)
my_tup = tuple([float("{0:.1f}".format(n)) for n in my_tup])

rawDescription: Format list of tuples to 1 decimal

description: Format list of tuples to 1 decimal


code:
def issorted(numlist):
    for i in range(1, len(numlist)):
        if numlist[i] < numlist[i-1]:
            #you want to return False and exit the function.
            #return is the best option here.
            return False
    #if the for loop succeeds, you want to return True by default
    return True

rawDescription: Writing the return function

description: Writing the return function


code:
class Data(db.Model):
    data_id = db.Column(db.Integer, primary_key=True)
    data_date = db.Column(db.Date)
    details_main = db.Column(db.String(50))

    details = relationship(
        Details,
        primaryjoin=remote(Details.details_main) == foreign(details_main))
    details_desc = association_proxy('details', 'details_desc')

rawDescription: SQLAlchemy: @property mapping?

description: SQLAlchemy: @property mapping


code: f = open (locfile, "rb")

rawDescription: File size differences after copying a file to a server vía FTP


code:
frozenset([1,9])
frozenset([9,1])
hash(frozenset([1,9]))
hash(frozenset([9,1]))
frozenset([1,9]) == frozenset([9,1])

rawDescription: Python - hash() and dict

description: Python - hash() and dict


code:
class DocumentCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Document
        fields = ('id', 'owner', 'created_time', 'update_time', 'expiry_time',
                  'description', 'size', 'type', 'status')
        read_only_fields = ('id', 'owner', 'created_time', 'update_time')

rawDescription: Django Rest Framework not returning all fields after creation


code:
import Tkinter as tk

root = tk.Tk()
deli = 100           # milliseconds of delay per character
svar = tk.StringVar()
labl = tk.Label(root, textvariable=svar, height=10 )

def shif():
    shif.msg = shif.msg[1:] + shif.msg[0]
    svar.set(shif.msg)
    root.after(deli, shif)

shif.msg = ' Is this an alert, or what? '
shif()
labl.pack()
root.mainloop()

rawDescription: News Scrolling Text in Python

description: News Scrolling Text in Python


code:
z = dict(x=x, y=y)
pd.concat(z)

rawDescription: Create a DataFrame from a dictionary of DataFrames


code:
def inStr():
    n = -1
    while n<2:
        try:
            n = int(input('Enter a positive integer greater than 2: '))
        except:
            pass
    print(positive(n)) # prints None

def positive(n, step=0):
    if n < 2:
        # print(step) #it prints correct answer
        return step   #but why it returns None?
    return positive(n//2, step+1)

inStr()

rawDescription: Receiving return None value

description: Receiving return None value


code:
s = "Hello  Bye          Test"
s
s.split()

rawDescription: How to extract data from .txt file that is separated by varying space size?

description: Extract data from .txt file that is separated by varying space size


code:
def run_script(file_path):
  process = subprocess.Popen(['myscript', -M, file_path], stdout=subprocess.PIPE)
  output,err = process.communicate()
  return process.returncode

@mock.patch('subprocess.Popen')
def test_run_script(self, mock_subproc_popen):
  process_mock = mock.Mock()
  attrs = {'communicate.return_value': ('ouput', 'error')}
  process_mock.configure_mock(**attrs)
  mock_subproc_popen.return_value = process_mock
  am.account_manager("path") # this calls run_script somewhere, is that right?
  self.assertTrue(mock_subproc_popen.called)

rawDescription: Mocking a subprocess call in Python

description: Mocking a subprocess call in Python


code:
def diff(prev,lat):
    p=prev
    l=lat

    prevDiff = []
    latDiff = []

    for d1 in p[:]:
        flag = False
        for d2 in l:
            if len(set(d1.items()) ^ set(d2.items())) == 0:
                p.remove(d1)
                l.remove(d2)
                flag = True
                break
        if not flag:
            prevDiff.append(d1)
            p.remove(d1)

    prevDiff = prevDiff + p
    latDiff = latDiff + l

    resJSONdata=[]
    if len(prevDiff) != 0:
        resJSONdata.append({'prevCount':len(prevDiff)})
        resJSONdata.append({'prev':prevDiff})
    if len(latDiff) != 0:
        resJSONdata.append({'latestCount':len(latDiff)})
        resJSONdata.append({'latest':latDiff})

#     return json.dumps(resJSONdata,indent = 4,sort_keys=True)
    return resJSONdata

rawDescription: Multilevel JSON diff in python

description: Multilevel JSON diff in python


code:
with open('honeyd.txt', 'r') as infile:
    for index, line in enumerate(infile, 1):
        with open('test.rule{}'.format(index), 'w') as outfile:
             outfile.write('alert {} {} -> {} {}\n'.format(*line.split()))

rawDescription: python for save each list into some output file

description: Python for save each list into some output file


rawDescription: Convert string in Image and blit in Pyglet


code:
k = "a"
all(l[i][k] <= l[i+1][k] for i in range(len(l) - 1))

rawDescription: How to check if a list of dictionaries is sorted?

description: Check if a list of dictionaries is sorted


code:
def check_shopping_list(shopping_list):
    if shopping_list:  # No need to check len(), just that it has contents
        for item in shopping_list:
            pass
    else:
        raise EmptyShoppingList("You should really add SPAM to your list")

def validate_input(input):
    if not input:  # catches empty inputs
        raise MissingInput("Please try again")
    else:
        print("Validated!")

def read_file(file_name):
    if os.path.exists(file_name):  # returns True/False, but we don't have to explicitly state that
        with open(file_name) as doc:
            pass
    else:
        print("That file doesn't exist, do you want to create it?")

rawDescription: Python explicit condition checking compared to implicit


code:
def out_match(st):
    return st if re.search(r'(?<!cxdef\.)trimheader', st) else None

out_match('=trimheaderspace')
out_match('cxdef.trimheaderspace()')

rawDescription: regex : match string with invert pattern preceeding the other pattern

description: Regex : match string with invert pattern preceeding the other pattern


rawDescription: How to print to console in color?

description: Print to console in color


code:
## merged dataframe
df_merged = pd.merge(m2, m1, how='inner', left_on='type', right_on='type')

## create function to check that date fails between start and end date
f = lambda x : x if x['date'] >  x['startdate'] and x['date'] < x['enddate'] else     None

## apply function to dataframe
df_merged=df_merged.apply(f, axis=1)

## drop na values
df_merged.dropna()

rawDescription: how to assign a value to a variable based on its relationship with another data frame in Python

description: Assign a value to a variable based on its relationship with another data frame in Python


code:
def findString(inputStr, targetStr):
    if convertToStringSoup(targetStr).find(convertToStringSoup(inputStr)) != -1:
            return True
    return False

def convertToStringSoup(testStr):
    testStr = testStr.lower()
    testStr = testStr.replace(" ", "")
    testStr = testStr.replace("(", "")
    testStr = testStr.replace(")", "")
    return testStr

findString("hello", "hello")
findString("hello", "hello1")
findString("hello", "hell!o1")
findString("hello", "hell( o)1")

rawDescription: A more powerful method than Python's find? A regex issue?


code:
API_STATUS = {1: 'some status', 2: 'some other status message'}
import pprint
pprint.pprint(API_STATUS, width=1)

rawDescription: Output/Print a "readable" dictionary

description: Output/Print a "readable" dictionary


code:
nums = [3,51,34]
reduce(lambda x, y: [y] if not x else x + [y + x[-1]], nums, None)
# [3, 54, 88]

rawDescription: how can i do math operation on list elements in python?

description: Do math operation on list elements in python


code:
def traverse(dic, path=None):
    if not path:
        path = []
    for i in dic:
        local_path = path[:].append(i)
        if i['type'] == 'folder':
            for j in traverse(i['children'], local_path):
                yield j, local_path
        elif i['type'] == 'url':
            yield i, local_path

rawDescription: Traverse a nested dictionary and get the path in Python?


code:
req = urllib2.Request(url)
req.headers['Range'] = 'bytes=%s-%s' % (start, end)
f = urllib2.urlopen(req)

rawDescription: Download A Single File Using Multiple Threads


rawDescription: Python dict to DataFrame Pandas

description: Python dict to DataFrame Pandas


code:
import matplotlib.pyplot as plt
import h5py

f = h5py.File("rhOverM_Asymptotic_GeometricUnits.h5", "r")
data = f['Extrapolated_N2.dir/Y_l2_m-1.dat']
plt.plot(data[:, 0], data[:, 1], label='column1')
plt.plot(data[:, 0], data[:, 2], label='column2')
plt.legend()
plt.show()

rawDescription: Gravitational Waveform Plot From h5 File


rawDescription: String formatting with Unicode

description: String formatting with Unicode


code:
import asyncio

def wakeup():
    # Call again
    loop.call_later(0.1, wakeup)

print('Event loop starting')
loop = asyncio.SelectorEventLoop()
# Register periodic callback
loop.call_later(0.1, wakeup)
asyncio.set_event_loop(loop)
loop.run_forever()
print('Event loop ended')

rawDescription: Why can't I catch SIGINT when asyncio event loop is running?


code:
...
cv2.imshow('window name', img)
cv2.waitKey()

rawDescription: Window OpenCV in python in terminal

description: Window OpenCV in python in terminal


code:
for i in clslist:
    if i.str1 == A and i.str2 == B:
        i.strlist.append(whatever)

rawDescription: add to a list in tuple with search in python

description: Add to a list in tuple with search in python


code:
import numpy as np
from scipy.linalg import solve

A = np.random.random((3, 3))
b = np.random.random(3)

x = solve(A, b)
x

np.dot(A, x) - b

rawDescription: Matrix multiplication, solve Ax = b solve for x


code:
for key in dct:
    key(*dct[key])

rawDescription: python evaluate functions with parameters given by a dictionary

description: Python evaluate functions with parameters given by a dictionary


code:
from itertools import starmap
from collections import deque

exhaust_iterable = deque(maxlen=0).extend

exhaust_iterable(starmap(function, dictionary.items()))

rawDescription: Apply a function on a dict's items

description: Apply a function on a dict's items


code:
#UNTESTED
@app.route('/')
def list_posts():
    entries = db_session.query(Entry).order_by(desc(Entry.id)).limit(5)
    resp = make_response(render_template('list.html', entries=entries))
    resp.cache_control.max_age = 300
    return resp

rawDescription: How can I add cache control in Flask when I'm rendering a template?

description: Add cache control in Flask when I'm rendering a template


code:
import module

old_divide = module._divide

def new_divide(var):
    if var == 0:
        var = 1e-131
    return old_divide(var)

module._divide = new_divide

rawDescription: How to handle slightly changing a method from an installed module?

description: Handle slightly changing a method from an installed module


code:
import cv2
import numpy as np
re_img1 = cv2.imread('re_img1.png')
b, g, r = cv2.split(re_img1)

ttl = re_img1.size / 3 #divide by 3 to get the number of image PIXELS

"""b, g, and r are actually numpy.ndarray types,
so you need to use the appropriate method to sum
all array elements"""
B = float(np.sum(b)) / ttl #convert to float, as B, G, and R will otherwise be int
G = float(np.sum(g)) / ttl
R = float(np.sum(r)) / ttl
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)

rawDescription: splitting an RGB image to R,G,B channels - python

description: Splitting an RGB image to R,G,B channels - python


code:
import glob
def get_actual_filename(name):
    name = "%s[%s]" % (name[:-1], name[-1])
    return glob.glob(name)[0]

rawDescription: In Python, how can I get the correctly-cased path for a file?


code:
s
grouped = s.groupby(level=0)
grouped.first()
grouped.last()

rawDescription: python pandas remove duplicates in series

description: Python pandas remove duplicates in series


rawDescription: Find actual location of installed python app. (not the symlink)


rawDescription: Python attribute of combination of two objects


code:
from django.core.paginator import Paginator

# in the view:
p = Paginator(objects, 2)
page = p.page(current_page)
for o in page.object_list:
    # do processing
    pass

rawDescription: Only process subset of a queryset in Django (and return original queryset)


code:
import numpy as np
from scipy.spatial import distance

A = np.array([[1,23,2,5,6,2,2,6,2],[12,4,5,5],[1,2,4],[1],[2],[2]], dtype=object )
B = np.array([[1,23,2,5,6,2,2,6,2],[12,4,5,5],[1,2,4],[1],[2],[2]], dtype=object )

Aflat = np.hstack( A )
Bflat = np.hstack( B )

dist = distance.cosine( Aflat, Bflat )

rawDescription: Python: Cosine Similarity m * n matrices


rawDescription: Python hex decoding shows wrong result for special charters


code:
for sub_list in my_list:
    for dx in (0, -1):
        while sub_list and sub_list[dx] == 0:
            sub_list.pop(dx)

rawDescription: Remove leading and trailing zeros from multidimensional list in Python


code:
import sys, random
from PyQt4 import QtGui, QtCore

# Robot Widget
class RobotLink(QtGui.QWidget):
    def __init__(self, parent, x, y, width, height, fill):
        super(RobotLink, self).__init__(parent)
        self._fill     = fill
        self._rotation = 0
        self.setGeometry(x, y, width, height)

    def paintEvent(self, e):
        painter = QtGui.QPainter()
        painter.begin(self)
        self.drawLink(painter)
        painter.end()

    def drawLink(self, painter):
        painter.setPen(QtGui.QColor(0, 0, 0))
        painter.setBrush(self._fill)
        painter.drawEllipse(0, 0, self.width(), self.height())

# Window
class Window(QtGui.QWidget):
    # Default Constructor, sets up the window GUI
    def __init__(self):
        super(Window, self).__init__()
        self.initUI()

    def initUI(self):
        self._link1 = RobotLink(self, 10, 10, 100, 50, QtCore.Qt.DiagCrossPattern)
        self._link2 = RobotLink(self, 100, 100, 50, 100, QtCore.Qt.Dense5Pattern)
        self._link3 = RobotLink(self, 150, 150, 50, 50, QtCore.Qt.Dense2Pattern)

        self.setGeometry(300, 300, 800, 600)
        self.setWindowTitle("CSCE 452 - PaintBot")

    def paintEvent(self, e):
        super(Window, self).paintEvent(e)
        painter = QtGui.QPainter()
        painter.begin(self)
        self.drawBoundingBoxes(painter)
        painter.end()

    # Draws the boxes that define the robots workspace and
    # the control panel
    def drawBoundingBoxes(self, painter):
        color = QtGui.QColor(0, 0, 0)
        color.setNamedColor("#cccccc")
        painter.setPen(color)

        # Draw the robot workspace
        painter.setBrush(QtGui.QColor(255, 255, 255))
        painter.drawRect(10, 10, 500, 578)

        # Draw the control panel workspace
        painter.setBrush(QtGui.QColor(150, 150, 150))
        painter.drawRect(520, 10, 270, 578)

        # Draws the slider 'base'
        painter.setPen(QtGui.QColor(0, 0, 0))
        painter.drawLine(100, 570, 400, 570)

    def changeValue(self, value):
        self.wid.emit(QtCore.SIGNAL("updateRobot(int)"), value)
        self.wid.repaint()

# Setup the Window, and the Robot
app = QtGui.QApplication(sys.argv)
win = Window()
win.show()
app.exec_()

rawDescription: PyQT - Positioning and Displaying a Custom Widget


rawDescription: Add new "plugin" to Flask app in runtime


code: foo = sys.stdin.read(1024)

rawDescription: How to create the PYTHON version of this PHP script. ( reads from php://stdin )

description: Create the PYTHON version of this PHP script. ( reads from php://stdin )


rawDescription: How to update a matplotlib figure from loop?

description: Update a matplotlib figure from loop


code:
class C(object):
   def __init__(self):
       self.index = 0
       self.iterable = range(10)
   def __iter__(self):
       return self
   def min(self):
     try:
         return self.iterable[self.index]
     except IndxError:
         raise Exception('The index is out of range')
c=C()

c.min()
c.iterable=[5,1,4,8]
c.min()

rawDescription: Python min override

description: Python min override


code: a = radiobutton.isChecked()

rawDescription: from pyqt4 designer gui how to get radio button value using python

description: From pyqt4 designer gui how to get radio button value using python


code:
#list1=[5,5,5,5,5]
list1=[1,2,3,1,3]
#list1=[1,2,3,4,5]
list2=[]

for num in list1:
    if list1.count(num) > 1:
        list2.append(num)

print(list2)

rawDescription: List reset in a "for" loop

description: List reset in a "for" loop


code:
import turtle

turtle.colormode(255)

for i in range(0,255,15):
    turtle.pencolor(i,i,i)
    turtle.write("Hello")
    turtle.delay(100)

rawDescription: Fading Text in Python Turtle

description: Fading Text in Python Turtle


code:
class FrozenClass(object):
    __isfrozen = False
    def __setattr__(self, key, value):
        if self.__isfrozen and not hasattr(self, key):
            raise TypeError( "%r is a frozen class" % self )
        object.__setattr__(self, key, value)

    def _freeze(self):
        self.__isfrozen = True

class Test(FrozenClass):
    def __init__(self):
        self.x = 42#
        self.y = 2**3

        self._freeze() # no new attributes after this point.

a,b = Test(), Test()
a.x = 10
b.z = 10 # fails

rawDescription: Prevent creating new attributes outside __init__


code:
class Time(object):
    @classmethod
    def from_seconds(cls, seconds):
         _hours, _minutes, _seconds = ...
         return cls(_hours, _minutes, _seconds)

rawDescription: Should I, and how to, add methods to int in python?


code:
user = 'heinz'
import re
regex = re.compile('%s-\d*'%user)
regex.match('heinz-1')
regex.match('heinz-11')
regex.match('heinz-12345')
regex.match('foo-12345')

rawDescription: Using variables in Python regular expression


rawDescription: Call external program from python and get its output


code:
def foo(x):
    y = None
    def bar():
        return x
    return bar

bar = foo('spam')
foo.__code__.co_cellvars
bar.__code__.co_freevars
dir(bar.func_closure[0])
bar.func_closure[0].cell_contents

rawDescription: How can I determine what namespaces are visible to a Python stack frame?

description: Determine what namespaces are visible to a Python stack frame


code:
lst = [1,2,3]
newlst = [dict(number=n) for n in lst]
newlst

rawDescription: Python dictionary manipulation

description: Python dictionary manipulation


code:
df = pandas.DataFrame(numpy.random.randint(1,3, (10,5)), columns=['a','b','c','d','e'])
df

rawDescription: Pandas: Shift down values by one row within a group


code:
from collections import defaultdict

# Create dict that automatically assigns empty dict to a key that doesn't exist
dd = lambda: defaultdict(dd)
filesdict = dd()

for line in fileslist:
    path = line.split('/')
    if path[-1] != '':
        d = filesdict

        # Iterate to location where file is to be added without mutating path
        for i in range(len(path) - 1):
            # If d[path[i]] doesn't exist empty dict is automatically created here
            d = d[path[i]]
        d[path[-1]] = 'file'

rawDescription: Best practice to recursively update a nested dictionary?


code:
df = s.reset_index(name='col1')
df
df.to_json(orient='records')

rawDescription: Pandas TimeSeries into MongoDB

description: Pandas TimeSeries into MongoDB


code:
import pandas as pd

df = pd.DataFrame([['Apple',pd.to_datetime('1/1/2005'),10,10,'Orange'],['Apple', pd.to_datetime('12/1/2005'),1, 1 ,'Orange']])
df.columns = ['Identity','Date', 'value1' , 'value2','Random']

full_df = pd.DataFrame()
full_df['Date'] = [pd.to_datetime(str(x)+'/1/2005') for x in range(1,13)]
full_df['Identity'] = 'Apple'

result =  full_df.merge(df,how='left').fillna(0)
result

rawDescription: Conditionally insert rows into pandas DataFrame


code:
some = 100

def callback1(res1):
    param2 = res1 + some
    func2(param2, callback2)
def callback2(res2):
    ...

param1 = 1
func1(param1, callback1)

rawDescription: How can I create chain of callbacks in python?

description: Create chain of callbacks in python


code:
D1, D2 = A.shape
A[:, 0] = A[:, D2-1]
A.resize((D1, D2-1), refcheck=False)
A.shape
# => would be (5, 4) if the shape was initially (5, 5) for example

rawDescription: Efficient way to drop a column from a Numpy array?


code:
from redis import StrictRedis
r = StrictRedis()
pipe = r.pipeline()
pipe.set('KEY1', 1)
pipe.set('KEY2', 2)
pipe.set('KEY3', 3)
pipe.command_stack
[(('SET', 'KEY1', 1), {}), (('SET', 'KEY2', 2), {}), (('SET', 'KEY3', 3), {})]

rawDescription: redis.py: How to flush all the queries in a pipeline

description: Redis.py: How to flush all the queries in a pipeline


code: FORCE_SCRIPT_NAME = '/forum'

rawDescription: How to change DjangoBB idea of a base url?

description: Change DjangoBB idea of a base url


code:
#!/usr/bin/env python
from PIL import ImageChops # $ pip install pillow
from pyscreenshot import grab # $ pip install pyscreenshot

im = grab()
while True: # http://effbot.org/zone/pil-comparing-images.htm
    diff = ImageChops.difference(grab(), im)
    bbox = diff.getbbox()
    if bbox is not None: # exact comparison
        break

print("bounding box of non-zero difference: %s" % (bbox,))
# superimpose the inverted image and the difference
ImageChops.screen(ImageChops.invert(im.crop(bbox)), diff.crop(bbox)).show()
input("Press Enter to exit")

rawDescription: Python : How to detect any changes in the screen


code:
matrix = [
    [0,0,1],
    [1,0,1],
    [0,1,0],
]
{i: [j for j, x in enumerate(row) if x] for i, row in enumerate(matrix)}

rawDescription: Form a edge list from a matrix-python

description: Form a edge list from a matrix-python


code: a[tuple(sorted(dct.items()))] = b

rawDescription: How to use a dictionary as key for a dictionary in Python

description: Use a dictionary as key for a dictionary in Python


code:
import re

# Using re.split with grouping parens so the separators get returned in the split results
chunk = re.split(r'(<Turn.*?>|\?)', original_text)

# The "<Turn...>" and "?" separators are at the odd indexes. These are the
# places that '<question>' and '</question>' need to be inserted.
for i in range(1, len(chunk), 2):
    if chunk[i] == '?':
        chunk[i-2] += '<question>'
        chunk[i] += '</question>'

new_text = ''.join(chunk)

print(new_text)

rawDescription: Python find and replace questions in xml files


code:
class MyClass(object):
    def __init__(self):
        self.trigger = False
        self._my_property = 0

    def set_my_property(self, value):
        if self.trigger:
            raise Exception("WHOOPS!")
        self._my_property = value
        # TODO: mark my_property so that if it gets set again, an assert
        # is triggered
        self.trigger = True

    def get_my_property(self):
        return self._my_property

    my_property = property(get_my_property, set_my_property, None)

c = MyClass()
c.set_my_property(4)

# any of these lines would cause an assertion
c.set_my_property(8)
c.my_property = 123

rawDescription: Python assert on property set

description: Python assert on property set


code:
import numpy as np
image = np.arange(16).reshape(4, 4)
ylin = np.array([0, 3, 2, 2])
xsam = np.array([2, 3, 0, 1])
newarr = image[ylin, xsam]
newarr

rawDescription: Numpy Indexing with Arrays

description: Numpy Indexing with Arrays


code: Run > Configure

rawDescription: joblib.Parallel runing through spyder hanging on Windows

description: Joblib.Parallel runing through spyder hanging on Windows


code:
import os
os.system('<command line instruction>')

rawDescription: Linux command line instructions from python


rawDescription: Adding values to binary string

description: Adding values to binary string


code:
from decimal import Decimal
x = Decimal('1.' + '0' * 200)
x

rawDescription: Python, infinite floats?

description: Python, infinite floats


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

values = np.array([684, 434, ... , 1186])
times = np.arange(0,len(values))
time_labels = ['00:00', '01:00', ..., '23:00']

plt.plot(times, values, 'o-')
plt.xticks(times, time_labels)
plt.show()

rawDescription: plotting changes over time in python/matplotlib

description: Plotting changes over time in python/matplotlib


code:
import requests
r = requests.get(
    "https://data.lacity.org/resource/9w5z-rg2h.json?$where=within_circle(lat_lon, 34.053714, -118.242653, 1000)",
    headers={"X-App-Token":"[YOUR APP TOKEN]"}
)
r.json()[0] # {u'permit_status': u'Permit Finaled', u'inspection_result': u'Partial Inspection', u'lat_lon': {u'latitude': u'34.04866', u'needs_recoding': False, u'longitude': u'-118.23787'}, u'address': u'100 S ALAMEDA ST', u'inspection': u'Excavation/Setback/Form/Re-Bar', u'inspection_date': u'2013-08-27T00:00:00', u'permit': u'13016-30000-09747'}

rawDescription: Socrata SODA and Python

description: Socrata SODA and Python


code:
# calculate the position once and but the rect at that position
playText_rect = playText.get_rect(topleft=(rightBorder / 2 - playText.get_width() / 2 - 200, bottomBorder / 2 - playText.get_height() / 2 + 120))
settingsText_rect = settingsText.get_rect(topleft=(rightBorder / 2 - settingsText.get_width() / 2 + 200, bottomBorder / 2 - settingsText.get_height() / 2 + 120))

...

# use the rect as position argument for blit
setDisplay.blit(settingsText, settingsText_rect)

...

setDisplay.blit(playText, playText_rect)

rawDescription: (Pygame) Problems with Mouseover Detection


code:
from sys import exit

try: input = raw_input          # To make it work both in Python 2 and 3
except NameError: pass

def bank_vault():
    print("This room is full of money up to 5 million dollars. How much do you take?")

    how_much = int(input("> ")) # Why not eliminate choice variable here?

    if how_much == 0:
        dead("You are robbing a bank and took nothing... The cops shot you in the face.")
    elif how_much < 5000000:    # Changed to else condition
        print("Nice take, now you have to escape!")
    else:                       # Added a check
        dead("There isn't that much!")

def escape_route():
    print("There are cops blocking the front door.")
    print("There are cops blocking the back door.")
    print("There is no way to get out of there.")
    print("You see a small opening on the ceiling.")
    print("Type ceiling to go through it.")
    print("Or type stay to try your luck.")
    escaped_cops = False

    while not escaped_cops:
        choice = input("> ")

        if choice == "stay":
            dead("Your bank robbing friends left your stupid ass and the cops shot you in the face. Idiot move dipshit.")
        elif choice == "ceiling":
            print("You escaped! Now wash that money and don't go to prison.")
            escaped_cops = True

def dead(why):
    print(why)
    exit(0)

bank_vault()
escape_route()

rawDescription: How do I move to different parts of code in this game/story

description: Move to different parts of code in this game/story


code:
with open('/tmp/home_dir.txt', 'w') as  text_file_1:
    for item in os.listdir('/home'):
        text_file_1.write('%s\n' % item)

rawDescription: How to write list output to a text file in Python

description: Write list output to a text file in Python


code:
header = ['country name', 'average urban population ratio', 'average life expectancy', 'sum of total population in all years', 'sum of urban population in all years']

final_list = []

for key, value in sorted(stats_dict.iteritems()):
    if value[5] != 0:
        final_list.append([key, value[4], value[5], value[0], value[1]])

with open('output.csv', 'wb') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(header)
    writer.writerows(final_list) # note .writerows

# f.close() - not needed, the with statement closes the file for you

rawDescription: Writing output csv file python

description: Writing output csv file python


code:
from itertools import groupby

# Some itertools magic to split the list into groups with [-1,-1,-1] as the delimiter.
pointLists = [list(group) for k, group in groupby(points, lambda x: x == [-1,-1,-1]) if not k]
color = (255,255,255)
for pointList in pointLists:
    # Only use the x and y components of the points.
    drawPoints = [[l[0], l[1]] for l in pointList]
    # Assume 'screen' is your display surface.
    pygame.draw.lines(screen, color, False, drawPoints)

rawDescription: draw lines from a set of coordinates pygame

description: Draw lines from a set of coordinates pygame


code:
import csv
import random

input_path = r"path\to\input"
output_path = r"path\to\output"

with open(input_path, "rb") as file:
    rows = list(csv.reader(file, delimiter=","))

random.shuffle(rows)

with open(output_path, "wb") as file:
    csv.writer(file, delimiter=",").writerows(rows)

rawDescription: How do I shuffle in Python for a column (years) with keeping the corrosponding column values?

description: Shuffle in Python for a column (years) with keeping the corrosponding column values


code:
import urllib

def save(self):
    location = "%s, %s, %s, %s" % (self.address, self.city, self.state, self.zip)

    if not self.latitude or not self.longitude:
        latlng = self.geocode(location)
        latlng = latlng.split(',')
        self.latitude = latlng[0]
        self.longitude = latlng[1]

    super(Marker, self).save()

def geocode(self, location):
    output = "csv"
    location = urllib.quote_plus(location)
    request = "http://maps.google.com/maps/geo?q=%s&output=%s&key=%s" % (location, output, settings.GOOGLE_API_KEY)
    data = urllib.urlopen(request).read()
    dlist = data.split(',')
    if dlist[0] == '200':
        return "%s,%s" % (dlist[2], dlist[3])
    else:
        return ','

rawDescription: Geocoding an address on form submission?

description: Geocoding an address on form submission


code:
import inspect
class X(object):
    pass

inspect.isclass(X)
x = X()
isinstance(x, X)
y = 25
isinstance(y, X)

rawDescription: How to check whether a variable is a class or not?

description: Check whether a variable is a class or not


code:
def getsuperclass(cls):
    try:
        nextclass = cls.__mro__[1]
    except IndexError:
        raise TypeError("No superclass")
    return nextclass

@singledispatch
def hello(value):
    return ['default']

@hello.register(Base)
def hello_base(value):
    return hello.dispatch(getsuperclass(Base))(value) + ['base']

@hello.register(Derived)
def hello_derived(value):
    return hello.dispatch(getsuperclass(Derived))(value) + ['derived']

print(hello(Derived()))

rawDescription: Equivalent to super() for functools.singledispatch


code:
def strictly_increasing(L):
    return all(x<y for x, y in zip(L, L[1:]))

def strictly_decreasing(L):
    return all(x>y for x, y in zip(L, L[1:]))

def non_increasing(L):
    return all(x>=y for x, y in zip(L, L[1:]))

def non_decreasing(L):
    return all(x<=y for x, y in zip(L, L[1:]))

rawDescription: Python - How to check list monotonicity

description: Python - How to check list monotonicity


code:
a = A( 1, 2, lambda x,y: x + y)
b = A( 1, 2, lambda x,y: x * y)

rawDescription: How to assign an operation like sum or substitute, etc., to a variable

description: Assign an operation like sum or substitute, etc., to a variable


code:
top="."
import os
for root, dirs, files in os.walk(top):
    for name in files:
        # do something with each file as 'name' (a)
        pass
    for name in dirs:
        # do something with each subdir as 'name' (b)
        pass
    # do something with root (dir path so far)
    # break at any point if necessary

rawDescription: How Could Python iterate the directoriy and detect the new files?


code:
import timeit

def for_list(data):
    for d in data:
        bunk = d ** d

def while_list(data):
    while data:
        d = data.pop(0)
        bunk = d ** d

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print(timeit.timeit('data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for_list(data)', 'from __main__ import for_list'))
# 0.959696054459

print(timeit.timeit('data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; while_list(data)', 'from __main__ import while_list'))
# 2.40107011795

rawDescription: Python: Why is popping off a queue faster than for-in block?


code:
from IPython.lib.pretty import pprint

pprint(your_big_ugly_data_structure)

rawDescription: Copy IPython's pretty printing of results


code:
import datetime
RefTime = datetime.datetime(1900,1,1,0,0,0)
OneHour = datetime.timedelta(0,3600)

date = []

for i in range(100):
    #python loop starts at 0, so add 1 to your magic number below
    MyTime = 97847 + 1 + i
    t0 = RefTime + OneHour * MyTime
    date.append(t0.strftime("%Y%m%d%H"))

#now 'date' is a list with 100 strings like "1911030200", etc.

rawDescription: Date format conversion in python

description: Date format conversion in python


rawDescription: Convert unicode to unicode escape syntax


code:
def Shoot(self):
    laser = self.Canvas.create_rectangle(...)
    self.lasers.append(laser)

def do_animation(self):
    # make a copy of the list of lasers to iterate
    # over, so we can remove items from the original
    # list when they go off screen
    lasers = self.lasers[:]
    for laser in lasers:
        # get current coordinates of this laser
        (x0,y0,x1,y1) = self.canvas.bbox(laser)

        if x1 < self.canvas.winfo_height():
            # if it is not off screen, move it up
            self.canvas.move(laser, 0, -10)
        else:
            # if it IS off screen, delete it
            self.canvas.delete(laser)
            self.lasers.remove(laser)

    self.after(30, self.do_animation)

rawDescription: How to use multiprocessing or threading with tkinter

description: Use multiprocessing or threading with tkinter


rawDescription: How do I add to odd index values in python?

description: Add to odd index values in python


code:
import re
from operator import itemgetter
import pprint

# Pretty printer (for nice output)
pp = pprint.PrettyPrinter(indent=4)

# Test data
arr = [
['193T','4234234234'],['30T','54353456346'],['203K','4234234234'],['19E','4234234234']
]

for x in arr:
    # Regex search of string
    m = re.search("(?i)(\d+)([a-z])", x[0])
    if m:
        number = int(m.group(1))
        character = m.group(2)
        x.pop(0)
        x.insert(0, character)
        x.insert(0, number)

# Sort the results
result = sorted(sorted(arr, key=itemgetter(0)), key=itemgetter(1))

pp.pprint(result)

rawDescription: Python - Using regex to seperate alphanumeric list into integer and string


code: date = ' '.join(list_of_line[0:3])

rawDescription: Python getting the date from a file

description: Python getting the date from a file


code:
tags = ['model', 'modelyear', 'makestring', 'vehicleid']
vehicle = {}
for tag in tags:
    vehicle[tag] = '{}'.format(soup.find('ns:' + tag).text)

rawDescription: Using BeautifulSoup to Parse XML to a Dictionary


code: {{ itemsByPosition.A2.attribute }}

rawDescription: accessing objects stored in dictionary as values using django templatetag outputs only its string representation; not original object

description: Accessing objects stored in dictionary as values using django templatetag outputs only its string representation; not original object


code:
class ProjectType(object):
    build_cmd = ""
    markers = []

    @classmethod
    def make_project(cls, path):
        prj_types = (PythonProject, AutoconfProject, MakefileOnly, ProjectType)
        for p in prj_types:
            markers = p.markers
            if any(path.isfile(path.join(path, x)) for x in markers):
                return p()

class PythonProject(ProjectType):
    build_cmd = "python setup.py develop --user"
    markers = ['setup.py']

class AutoconfProject(ProjectType):
    #TODO: there should be also a way to configure it
    build_cmd = "./configure && make -j3"
    markers = ['configure.in', 'configure.ac', 'makefile.am']

class MakefileOnly(ProjectType):
    build_cmd = "make"
    markers = ['Makefile']

rawDescription: Factory method in python

description: Factory method in python


code:
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
from wx.glcanvas import GLCanvas
import wx

#===================================================================================================
class myGLCanvas(GLCanvas):
    def __init__(self, *args, **kwargs):
        GLCanvas.__init__(self, *args, **kwargs)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_SIZE, self.OnResize)
        self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown)
        self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.Bind(wx.EVT_RIGHT_UP, self.OnRightUp)
        self.Bind(wx.EVT_MOTION, self.OnMouse)

        self.init = False
        self.width, self.height = self.GetSize()

        self.alpha = 0
        self.beta = 0
        self.distance = 5.0

        self.oldX = 0
        self.oldY = 0
        self.leftDown = False
        self.rightDown = False

        self.axes = False

    #-----------------------------------------------------------------------------------------------
    def Axes(self, allow):
        self.axes = allow

    #-----------------------------------------------------------------------------------------------
    def OnDraw(self):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, (0.5, 0.5, 1.0, 1.0))
        glutSolidSphere(0.5, 20, 20)

        if self.axes:
            self.ShowAxes()

        self.SwapBuffers()

    #-----------------------------------------------------------------------------------------------
    def ChangeView(self):
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glTranslate(0.0, 0.0, -self.distance)
        glRotate(-90, 0.0, 1.0, 0.0)
        glRotate(-90, 1.0, 0.0, 0.0)

        glRotate(self.alpha, 0.0, 0.0, 1.0)
        glRotate(self.beta, 0.0, 1.0, 0.0)

        self.OnDraw()

    #-----------------------------------------------------------------------------------------------
    def Resize(self):
        ratio = float(self.width) / self.height;

        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        glViewport(0, 0, self.width, self.height)
        gluPerspective(45, ratio, 1, 1000)

        self.ChangeView()

    #-----------------------------------------------------------------------------------------------
    def OnPaint(self, event):
        wx.PaintDC(self)
        self.SetCurrent()
        if not self.init:
            self.InitGL()
            self.init = True
        self.OnDraw()

    #-----------------------------------------------------------------------------------------------
    def OnLeftDown(self, event):
        self.oldX, self.oldY = event.GetPosition()
        self.leftDown = True

    def OnRightDown(self, event):
        self.oldX, self.oldY = event.GetPosition()
        self.rightDown = True

    def OnLeftUp(self, event):
        self.leftDown = False

    def OnRightUp(self, event):
        self.rightDown = False

    def OnMouse(self, event):
        if self.leftDown or self.rightDown:
            X, Y = event.GetPosition()
            if self.rightDown:
                self.distance += (Y - self.oldY) * 0.05

            if self.leftDown:
                self.alpha += (X - self.oldX) * 0.5
                self.beta += (Y - self.oldY) * 0.5

            self.ChangeView()
            self.oldX, self.oldY = X, Y

    #-----------------------------------------------------------------------------------------------
    def OnResize(self, e):
        self.width, self.height = e.GetSize()
        self.Resize()

    #-----------------------------------------------------------------------------------------------
    def ShowAxes(self):
        glDisable(GL_LIGHTING)

        glColor3f(1.0, 1.0, 0.0)
        glRasterPos3f(1.2, 0.0, 0.0)
        glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ord('x'))
        glRasterPos3f(0.0, 1.2, 0.0)
        glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ord('y'))
        glRasterPos3f(0.0, 0.0, 1.2)
        glutBitmapCharacter(GLUT_BITMAP_9_BY_15, ord('z'))

        glColor3f(1.0, 0.0, 0.0)
        glBegin(GL_QUADS)
        glVertex3f(0, 0, 0)
        glVertex3f(1, 0, 0)
        glVertex3f(1, 1, 0)
        glVertex3f(0, 1, 0)
        glEnd()
        glColor3f(0.0, 1.0, 0.0)
        glBegin(GL_QUADS)
        glVertex3f(0, 0, 0)
        glVertex3f(0, 0, 1)
        glVertex3f(0, 1, 1)
        glVertex3f(0, 1, 0)
        glEnd()
        glColor3f(0.0, 0.0, 1.0)
        glBegin(GL_QUADS)
        glVertex3f(0, 0, 0)
        glVertex3f(1, 0, 0)
        glVertex3f(1, 0, 1)
        glVertex3f(0, 0, 1)
        glEnd()

        glEnable(GL_LIGHTING)

    #-----------------------------------------------------------------------------------------------
    def InitGL(self):
        glLightfv(GL_LIGHT0, GL_DIFFUSE,  (0.8, 0.8, 0.8, 1.0))
        glLightfv(GL_LIGHT0, GL_AMBIENT,  (0.2, 0.2, 0.2, 1.0))
        glLightfv(GL_LIGHT0, GL_POSITION, (1.0, 1.0, 1.0, 0.0))
        glEnable(GL_LIGHT0)

#        glShadeModel(GL_SMOOTH)
        glEnable(GL_LIGHTING)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClearDepth(1.0)

        self.Resize()

#===================================================================================================
class ToolPanel(wx.Panel):
    def __init__(self, parent, canvas, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        self.canvas = canvas

        self.button1 = wx.Button(self, label="TEXT 1")
        self.button2 = wx.Button(self, label="TEXT 2")
        self.check1 = wx.CheckBox(self, label="Show Axes")
        self.Bind(wx.EVT_CHECKBOX, self.Check1)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.button1, flag=wx.BOTTOM, border=5)
        self.sizer.Add(self.button2, flag=wx.BOTTOM, border=5)
        self.sizer.Add(self.check1)

        self.border = wx.BoxSizer()
        self.border.Add(self.sizer, flag=wx.ALL | wx.EXPAND, border=5)

        self.SetSizerAndFit(self.border)

    #-----------------------------------------------------------------------------------------------
    def Check1(self, e):
        self.canvas.Axes(e.Checked())
        self.canvas.OnDraw()

#===================================================================================================
class MainWin(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, title='OpenGL', *args, **kwargs)

        self.canvas = myGLCanvas(self, size=(640, 480))
        self.panel = ToolPanel(self, canvas=self.canvas)

        self.sizer = wx.BoxSizer()
        self.sizer.Add(self.canvas, 1, wx.EXPAND)
        self.sizer.Add(self.panel, 0, wx.EXPAND)
        self.SetSizerAndFit(self.sizer)

        self.Show()

#===================================================================================================
app = wx.App(False)
main_win = MainWin(None)
app.MainLoop()

rawDescription: adding wxGLCanvas to wxPanel problem

description: Adding wxGLCanvas to wxPanel problem


code:
def comparison_factory(compare_to):
   def compare_func(x):
      res = x < compare_to
      print("is {} less than {}? {}".format(x, compare_to, res))
      return res
   return compare_func

funcs = [ comparison_factory(n) for n in range(1,5) ]

for f in funcs:
   f(3)

rawDescription: Workaround overwriting local variable in for loop?


code: df = pd.read_csv("filename", parse_dates = ["datetime1","datetime2"])

rawDescription: datetime conversion and manipulation in python

description: Datetime conversion and manipulation in python


code:
import sys
from tkinter import *

root = Tk()

def number():
    x = 420
    while x < 8400: # Limit for example
        x +=420
        textbox.insert(END, str(x^70)+'\n')
        print(textbox.get(1.0, END)) # Print current contents

button_1 = Button(root, text="Start...", command=number) #Changed bind to command, bind is not really needed with a button
button_1.pack()

textbox = Text(root)
textbox.pack()

root.mainloop()

rawDescription: Trying to print the output from my function inside my GUI window


code: foobar = FooBar(some_field=None)

rawDescription: Django force null field

description: Django force null field


code:
import numpy as np
prediction = np.array([1,1,1,0,0,1])
actual     = np.array([1,0,1,0,1,0])
np.sum(prediction == actual, dtype=float) / len(prediction)
np.mean(prediction == actual)

rawDescription: Evaluate prediction with a binary vector in python


code:
strs="Name.1001.ext"
strs.replace(".","_",1) # now only 1 occurrence of the

rawDescription: find and replace a character in my file names with a python re

description: Find and replace a character in my file names with a python re


code:
import string

def find_cap(sentence):
    s = []
    for word in sentence.split():

        # strip() removes each character from the front and back of the string
        word = word.strip(string.punctuation)

        if word.startswith(word.capitalize()):
            s.append(word)
    return s

rawDescription: Creating a function that returns all capitalized words in a sentence (commas excluded)


code:
from matplotlib.pyplot import *
import numpy as np

def highlight():
    m = np.random.randn(10,10)
    highlight = m < 0

    # RGBA overlay matrix
    overlay = np.zeros((10,10,4))

    # we set the red channel to 1
    overlay[...,0] = 1.

    # and we set the alpha to our boolean matrix 'highlight' so that it is
    # transparent except for highlighted pixels
    overlay[...,3] = highlight

    fig,ax = subplots(1,1,num='Press "h" to highlight pixels < 0')

    im = ax.imshow(m,interpolation='nearest',cmap=cm.gray)
    colorbar(im)
    ax.hold(True)
    h = ax.imshow(overlay,interpolation='nearest',visible=False)

    def toggle_highlight(event):
        # if the user pressed h, toggle the visibility of the overlay
        if event.key == 'h':
            h.set_visible(not h.get_visible())
            fig.canvas.draw()

    # connect key events to the 'toggle_highlight' callback
    fig.canvas.mpl_connect('key_release_event',toggle_highlight)

rawDescription: Highlight certain points on a matplotlib matrix


code:
stop = False
def handler(number, frame):
    global stop
    stop = True
signal.signal(signal.SIGUSR1, handler)
for file in files:  # or whatever your main loop looks like
    # Process one file
    if stop:
        break

rawDescription: how can I stop python script without killing it?

description: Stop python script without killing it


code:
def updateCentroid(self, label):
    cluster = self.clusters[label]
    n = len(cluster.points)
    cluster.centroid.x = ((n-1)*cluster.centroid.x + cluster.points[n-1].x)/n
    cluster.centroid.y = ((n-1)*cluster.centroid.y + cluster.points[n-1].y)/n

rawDescription: Optimizing mean in python

description: Optimizing mean in python


code:
f = open(filename,'rt')
a = [[int(token) for token in line.split()] for line in f.readlines()[::2]]

rawDescription: Splitting Text File Into Columns and Rows in Python


code:
class StrippedCharField(CharField):
     """Newforms CharField that strips trailing and leading spaces."""
     def clean(self, value):
         if value is not None:
             value = value.strip()
         return super(StrippedCharField, self).clean(value)

rawDescription: Strip spaces from Django form

description: Strip spaces from Django form


code:
import os

process = os.popen('gcc -E myHeader.h')
preprocessed = process.read()
process.close()

rawDescription: reading a os.popen(command) into a string

description: Reading a os.popen(command) into a string


code:
def new(a, N):
    mask = (a > 0) & (a < N)
    elements = a[mask]
    indices = np.arange(a.size)[mask]

    sorting_idx = np.argsort(elements, kind='mergesort')
    ind_sorted = indices[sorting_idx]

    x = np.searchsorted(elements, range(N), side='right', sorter=sorting_idx)

    return [ind_sorted[x[i]:x[i+1]] for i in range(N-1)]

rawDescription: Filling a list faster

description: Filling a list faster


code:
def g(x):
  g.r = 4
g
g(3)
g.r

rawDescription: Python: getting a reference to a function from inside itself


code:
# urls.py
from django.conf.urls import patterns, include
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    (r'^admin/', include(admin.site.urls)),
)

rawDescription: Why is admin.py never loaded?

description: Why is admin.py never loaded


code:
import paho.mqtt.client as mqtt
import json
import datetime as dt

TIMELIMIT = dt.timedelta(minutes=5)

testlist = {}       ## <<-- changed this to a dict()

def on_message(client, userdata, msg):
    payloadjson = json.loads(msg.payload.decode('utf-8'))
    line = payloadjson["value"].split(',')
    epc =  line[1]

    # this converts the time stamp string to something python can
    # use in date / time calculations
    when = dt.datetime.strptime(payloadjson['datetime'], '%Y-%m-%d %H:%M:%S')

    if epc not in testlist or when - testlist[epc] > TIMELIMIT:
        testlist[epc] = when

        for epc, when in teslist.items():
            print (epc, when)

rawDescription: How to append a list selectively?

description: Append a list selectively


code:
def parse(self, response):
    items = []
    item = gdpItem()
    driver = self.driver
    driver.get(response.url)
    driver.find_element_by_partial_link_text('Select all').click()
    driver.find_element_by_xpath('//option[contains(text(),"GDP (Million N.T.$,at Current Prices)")]').click()
    driver.find_element_by_xpath('//option[contains(text(),"Data")]').click()
    driver.find_element_by_xpath('//input[@type="SUBMIT"]').click()

    hxs = HtmlXPathSelector(text=self.driver.page_source)
    data = hxs.xpath("//table[@class='pxtable']//tbody//tr")

    for datum in data:
        item ["date"] = datum.xpath('td[1]/text()').extract()
        item ["data"] = datum.xpath('td[2]/text()').extract()

        yield item

rawDescription: Scrapy CSV export reside in 1 cell

description: Scrapy CSV export reside in 1 cell


code: p = subprocess.Popen(["./namecoind", "name_new", "d/" + domainname])

rawDescription: Subprocess.Popen: How to pass arguments without whitespace


rawDescription: I have a list of tuples, how can I take out a specific element?


code:
from BeautifulSoup import BeautifulSoup
import csv

import urllib2

url="http://www.conakat.com/states/ohio/cities/defiance/road_maps/"

page=urllib2.urlopen(url)

soup = BeautifulSoup(page.read())

f = csv.writer(open("Defiance Steets1.csv", "w"), lineterminator ="\n")
f.writerow(["Street", "Zipcode"]) # Write column headers as the first line

#print soup.
links = soup.findAll('a')

for link in links:
    #i = link.find_next_sibling('i')
    i = link.findNextSibling('i')
    if getattr(i, 'name', None):
        a, i = link.string, i.string[1:-1]
        print [a,i]
        f.writerow([a, i])

rawDescription: Python BeautifulSoup Empty Rows in CSV File


code:
a = [1, 2, 3, 4, 5]
b = [1, 2, 4]

print(all(i in a for i in b)) # Checks if all items are in the list
print(any(i in a for i in b)) # Checks if any item is in the list

rawDescription: Simplest way to check if multiple items are (or are not) in a list?


code:
def fw_material_qual(throat_thickness, runs):
    results = {}
    if throat_thickness <= 3:
        results['mat_thickness_qual'] = (0.7 * throat_thickness,
                                         1.5 * throat_thickness)
        if runs == 's':
            results['throat_thickness_qual'] = (
                0.75 * throat_thickness, 1.5 * throat_thickness)
        else:
            results['throat_thickness_qual'] = 'no restriction'

rawDescription: Calculating values based on the results of other values


code:
l = range(2, 101)
sorted(set(l).difference(a for i in l for a in l if a!=i and a%i == 0))

rawDescription: Python- Sieve of Eratosthenes- Compact Python


code: import pdb; pdb.set_trace()

rawDescription: Debbuging models.py code

description: Debbuging models.py code


code: args = ['-w', 'test_dir/testsetA/', '--collect-only']

rawDescription: Nose collect tests in a directory

description: Nose collect tests in a directory


code:
class myClass(object):
    def __init__(self,foo,bar):
        self.foo = foo
        self.bar = bar
    def __repr__(self):
        return 'myClass({0.foo},{0.bar})'.format(self)

item = myClass(1,2)
item
myDict = {}
myDict[item] = 10
myDict

rawDescription: Readable names for python objects as dictionary keys


code:
sawDelim = False
idx = 1
with open("hugefile") as fin, open("hugefile_out") as fout:
    for line in fin:
        if delimiter in line:
            sawDelim = True

        if sawDelim:
            fout.write(line)
            idx += 1

        # now that we've printed out 4 lines, reset and keep looking
        # (or could also bail if you want to only find one set)
        if (idx > 4):
            idx = 1
            sawDelim = False

rawDescription: Python 2.7. write following 4 lines out from a huge file


code:
def transform_date(date_string, tzinfo):
    fmt = '%Y-%m-%d'
    date = datetime.strptime(date_string, fmt).replace(tzinfo=tzinfo)
    return date

rawDescription: Insert a tzinfo into datetime

description: Insert a tzinfo into datetime


code:
import numpy as np
import networkx as nx
import pylab as plt

A = np.array([[0,0,1,0],[1,0,0,0],[1,0,0,1],[1,0,0,0]])
G = nx.DiGraph(A)

pos = [[0,0], [0,1], [1,0], [1,1]]
nx.draw(G,pos)
plt.show()

rawDescription: Python converting ndarrays into graph

description: Python converting ndarrays into graph


code:
import locale

# if you're on Windows in the US most likely
# the following is returned: ('en_US', 'cp1252')
deflang, defencoding = locale.getdefaultlocale()

# now that you have encoded your data (from Unicode)
# you may commit it to the database
write_this_to_db = u'Libert\u00e9'.encode(defencoding)
# -> 'Libert\xe9'

rawDescription: Using Unicode values in an access table and to concatenate label expression


code:
class MyModel(django.db.Model):
    MyTextField = django.db.TextField(db_column="mytextfield", primary_key=True)

    class Meta:
        db_table = "my_table"

rawDescription: Django without additional tables?

description: Django without additional tables


code:
import pandas as pd
idx = pd.date_range('2013-01-01', pd.datetime.today(), freq='H')
s = pd.Series(np.random.random_sample(idx.size) * 1000, index=idx)
s.describe() # print some statistics
s.index
s.resample('D', how='median').plot()

rawDescription: Python plot median value

description: Python plot median value


code:
widgets = ['Test: ', Percentage(), ' ', Bar(marker=RotatingMarker()), ' ', ETA(), ' ', FileTransferSpeed()]
pbar = ProgressBar(widgets=widgets)

def dlProgress(count, blockSize, totalSize):
    if pbar.maxval is None:
        pbar.maxval = totalSize
        pbar.start()

    pbar.update(min(count*blockSize, totalSize))

urllib.urlretrieve(url, fileName, reporthook=dlProgress)
pbar.finish()

rawDescription: How to make a download with progress bar in Python?

description: Make a download with progress bar in Python


rawDescription: Python Google App Engine - Get location

description: Python Google App Engine - Get location


code:
@pyqtSlot(QAction)
def on_menuAbout_triggered(self, action):
    """
    Show about page
    """
    about_box = QMessageBox(self)
    about_box.about(self, 'About', 'This is a GUI...\n\nwww.google.com')
#        about_box.setText('This is a GUI')
#        about_box.exec()

rawDescription: new pop up window (Qt4 / PyQt4, Python3)

description: New pop up window (Qt4 / PyQt4, Python3)


code:
from bisect import bisect_left

def select_type(typeselec,
                breakpoints=[4, 20, 30, 36, 40, 50],
                types='0BAFGKM'):
    return types[bisect_left(breakpoints, typeselec)]

for i in range(59):
    print(i, select_type(i))

rawDescription: "Fuzzy" hashtables in Python to replace elif chains?


code:
with open('testdata.txt', 'r') as input:
  for index, line in enumerate(input):
      with open('filename{}.txt'.format(index), 'w') as output:
          output.write(line)

rawDescription: Write output of for loop to multiple files


code:
column_names = ['Name', 'Surname', 'Age', 'DOB']
sheet = CSheet(panel)
for index, name in enumerate(column_names):
    sheet.SetColLabelValue(index, name)
sizer.Add(sheet)

rawDescription: wx.lib.sheet column and row names

description: Wx.lib.sheet column and row names