code:
try:
    import Tkinter as tk     ## Python 2.x
except ImportError:
    import tkinter as tk     ## Python 3.x

from functools import partial

opl = []
top = tk.Tk()

def move_it(num):
    for ctr in range(num, 5):
        opl[ctr].grid_forget()
        opl[ctr].grid(row=6, column=ctr)

for but_num in range(5):
    opl.append(tk.Button(top, width = 12 , text=str(but_num),
               command = partial(move_it, but_num)))
    opl[-1].grid(row=but_num, column=0, columnspan=2)

top.mainloop()

rawDescription: tkinter: press button to get its own grid

description: Tkinter: press button to get its own grid


code:
def main():
  self.progress_txt.AppendText("Processing")
  self.progress_txt.Update()
  #do something
  self.progress_txt.AppendText("Processing2")
  self.progress_txt.Update()
  #do something else
  self.progress_txt.AppendText("Finished")
  self.progress_txt.Update()

rawDescription: output statictext while processing python

description: Output statictext while processing python


code:
from django.db import connections
db_conn = connections['default']
try:
    c = db_conn.cursor()
except OperationalError:
    connected = False
else:
    connected = True

rawDescription: how can I check database connection to mysql in django

description: Check database connection to mysql in django


code:
import os

fileList = ["dir/dir2/dir3/dir3/file.txt",
    "dir/dir2/dir3/file.txt",
    "example/directory/path/file.txt"]

for file in fileList:
    dir = os.path.dirname(file)
    # create directory if it does not exist
    if not os.path.exists(dir):
        os.makedirs(dir)
    # Create blank file if it does not exist
    with open(file, "w"):
        pass

rawDescription: Create path and filename from string in Python


code: df[0].str.match('^as\.df$', case=False)

rawDescription: Pandas dataframe filter with matching

description: Pandas dataframe filter with matching


code: setattr(obj, attr_name, getattr(obj, attr_name) + 1)

rawDescription: Searching for a shorter way to increase an initially unknown attribute in Python


code: run("twistd -y run.tac", pty=False)

rawDescription: fabric don't start twisted application as a daemon

description: Fabric don't start twisted application as a daemon


code:
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search

client = Elasticsearch(host="localhost")

s = Search(using=client, index="my_index")

for hit in s.scan():
    print(hit.title)

rawDescription: How to obtain all the hits in elasticsearch for python?

description: Obtain all the hits in elasticsearch for python


code:
for k in dict:
    dict[k] = dict[k][0]

rawDescription: issue transforming Python dictionary of one-itemed list to dictionary of floats

description: Issue transforming Python dictionary of one-itemed list to dictionary of floats


code:
import matplotlib.backends.backend_tkagg as tkagg

# canvas is your canvas, and root is your parent (Frame, TopLevel, Tk instance etc.)
tkagg.NavigationToolbar2TkAgg(canvas, root)

rawDescription: matplotlib's zoom functionality inside a tkinter canvas

description: Matplotlib's zoom functionality inside a tkinter canvas


rawDescription: Getting the previous element in a list of lists


code:
import Image
import ImageFont, ImageDraw
image=Image.new("RGB",[320,320])
draw = ImageDraw.Draw(image)
a=u"ひらがな - Hiragana, 히라가나"
font=ImageFont.truetype("/Library/Fonts/Arial Unicode.ttf",14)
draw.text((50, 50), a, font=font)
image.save("a.png")

rawDescription: Drawing multilingual text using PIL

description: Drawing multilingual text using PIL


code:
import itertools
l=[['a','kl_hg', 'FOO'],['b', 'kl_c', 'po']]
if all( isinstance(x, basestring) for x in  itertools.chain.from_iterable(l) ):
    ...

rawDescription: How to check whether all elements in a list of lists are strings

description: Check whether all elements in a list of lists are strings


code:
for sheet in workbook.Sheets:
    print(sheet.name)
    for table in sheet.QueryTables:
        print("Found a query table on %s called %s" % (sheet.name, table.name))
        table.BackgroundQuery = False # i.e.: disable background query, and therefore cause Excel to 'wait' until it's done refreshing
        if table.Refresh() == True:     # This both refreshes the table, AND if the Refresh() method returns True (i.e.: refreshes successfully), tells you so.
            print("Query table %s refreshed!" % table.name)
        else:
            print("Query table %s FAILED to refresh." % table.name)
    for i in range(1,5):
        try:
            print("Found pivot table #%s called %s" % (i,sheet.PivotTables(i).Name))
            if sheet.PivotTables(i).RefreshTable()==True:
                print("Refreshed pivot table %s" % sheet.PivotTables(i).Name)
            else:
                print("FAILED to refresh pivot table %s" % sheet.PivotTables(i).Name)
        except:
            print("No pivot table #%s found on sheet %s" % (i,sheet.Name))
            break  # Break out of the for loop, since there's no point in continuing the search for pivots, I believe (but could be wrong about that!  Try creating two pivots, then deleting the first.  Does the second become PivotTables(1), or stay as 2?)

rawDescription: How do I make an Excel RefreshAll wait to close until finished?

description: Make an Excel RefreshAll wait to close until finished


code:
from itertools import groupby

edges = [(1, 2), (2, 3), (1, 3)]

adj = {k: [v[1] for v in g] for k, g in groupby(sorted(edges), lambda e: e[0])}
# adj: {1: [2, 3], 2: [3]}

rawDescription: Construct an Adjacency List from a List of edges?


code:
import fnmatch
fnmatch.fnmatch("fooabcdef", "*abcde?")
help(fnmatch.fnmatch)

rawDescription: String Simple Substitution

description: String Simple Substitution


code:
from jinja2 import Template
s = "{% for element in elements %}{{loop.index}} {% endfor %}"
Template(s).render(elements=["a", "b", "c", "d"])

rawDescription: How to output loop.counter in python jinja template?

description: Output loop.counter in python jinja template


code: next(c for c in type(self).mro() if hasattr(c, 'x'))

rawDescription: Getting current class in method call

description: Getting current class in method call


code: File = open (name + ".txt","r")#opens the Little file

rawDescription: How to use a varible to open a file

description: Use a varible to open a file


code:
from math import sin, cos, pi
import matplotlib.pyplot as plt

x,y = [cos((i*pi)/500) for i in range(1000)], [sin((i*pi)/500) for i in range(1000)]
plt.plot(x,y)
plt.show()

rawDescription: How to create a circle?

description: Create a circle


code:
from ttk import Progressbar
import Tkinter

class Example(Tkinter.Frame):
    def __init__(self, parent):
        Tkinter.Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        value_progress =50
        self.parent.title("Progressbar Thingymawhatsit")
        self.config(bg = '#F0F0F0')
        self.pack(fill = Tkinter.BOTH, expand = 1)
                #create canvas
        canvas = Tkinter.Canvas(self, relief = Tkinter.FLAT, background = "#D2D2D2",
                                            width = 400, height = 5)

        progressbar = Progressbar(canvas, orient=Tkinter.HORIZONTAL,
                                  length=400, mode="indeterminate",
                                  variable=value_progress,

                                  )
        # The first 2 create window argvs control where the progress bar is placed
        canvas.create_window(1, 1, anchor=Tkinter.NW, window=progressbar)
        canvas.grid()

def main():
    root = Tkinter.Tk()
    root.geometry('500x50+10+50')
    app = Example(root)
    app.mainloop()

if __name__ == '__main__':
    main()

rawDescription: TTK.Progressbar: How to change thickness of a horizontal bar


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

x = np.arange(0, 128)
y = (np.sin(.22*(x+10))>0).astype(np.float)

# filter
y2 = np.fft.fft(y)
f0 = np.fft.fftfreq(len(x))
y2[(f0<-.25) | (f0>.25)] = 0
y3 = abs(np.fft.ifft(y2))

plt.plot(x, y)
plt.plot(x, y3)
plt.xlim(-10, 140)
plt.ylim(-.1, 1.1)
plt.show()

rawDescription: Filtering signal: how to restrict filter that last point of output must equal the last point of input


code:
import requests
from bs4 import BeautifulSoup

res = requests.get('https://docs.python.org/2/library/functions.html')
abs_soup = BeautifulSoup(res.text, "html.parser")

print(abs_soup.find('dt', {'id': 'abs'}).find_next('dd').text)

rawDescription: Finding a specific string in a page with Beautifilsoup


code:
from bisect import bisect
...
periods = [0, 7, 30, 90, 180]
timeDiff = (today - dateLast).days
timePeriod = str(periods[bisect(periods[:-1], timeDiff)])

rawDescription: python best way to determine time ranges

description: Python best way to determine time ranges


rawDescription: How to use e.g. CO₂ as a label on Django

description: Use e.g. CO₂ as a label on Django


code:
latest = 0
latestfile = None

for fileattr in sftp.listdir_attr():
    if fileattr.filename.startswith('Temat') and fileattr.st_mtime > latest:
        latest = fileattr.st_mtime
        latestfile = fileattr.filename

if latestfile is not None:
    sftp.get(filename, filename)

rawDescription: How to downlad only the latest file from SFTP server with Paramiko?

description: Downlad only the latest file from SFTP server with Paramiko


code: BROKER_BACKEND = 'memory'

rawDescription: Unit testing with django-celery?

description: Unit testing with django-celery


code:
def check():
    text.tag_remove('found', '1.0', END)

    for word in list_of_words:
        idx = '1.0'
        while idx:
            idx = text.search(word, idx, nocase=1, stopindex=END)
            if idx:
                lastidx = '%s+%dc' % (idx, len(word))
                text.tag_add('found', idx, lastidx)
                idx = lastidx

    text.tag_config('found', foreground='red')

rawDescription: Searching for a list of words within a Tkinter text widgit in Python 2.7


rawDescription: conver a string of lists to a list of lists of lists

description: Conver a string of lists to a list of lists of lists


code:
class GolfClub:
    def __init__(self, name, size, distance):
        self.name = name
        self.size = size
        self.distance = distance

    def hits_further(self, other):
        if self.distance > other.distance:
            return "%s hits further" % self.name
        else:
            return "%s hits further" % other.name

club1 = GolfClub('Driver', 5, 200)
club2 = GolfClub('9Iron', 6, 300)
club1.hits_further(club2)

rawDescription: How to get the name of a variable

description: Get the name of a variable


code:
import binascii
binascii.unhexlify('00de34ef2ef4') # to raw binary
binascii.hexlify(_) # and back to hex
_.decode('ascii') # as str in Python 3

rawDescription: Convert from mac address to hex string and vice versa - both python 2 and 3


code:
import time
from ctypes import *
from ctypes.wintypes import *
import win32pdh

# with help from here http://coding.derkeiler.com/Archive/Python/comp.lang.python/2007-10/msg00717.html
# the following has been mashed together to get the info needed

def GetProcessID(name):
    object = "Process"
    items, instances = win32pdh.EnumObjectItems(None, None, object, win32pdh.PERF_DETAIL_WIZARD)
    val = None
    if name in instances :
        tenQuery = win32pdh.OpenQuery()
        tenarray = [ ]
        item = "ID Process"
        path = win32pdh.MakeCounterPath( ( None, object, name, None, 0, item ) )
        tenarray.append( win32pdh.AddCounter( tenQuery, path ) )
        win32pdh.CollectQueryData( tenQuery )
        time.sleep( 0.01 )
        win32pdh.CollectQueryData( tenQuery )
        for tencounter in tenarray:
            type, val = win32pdh.GetFormattedCounterValue( tencounter, win32pdh.PDH_FMT_LONG )
            win32pdh.RemoveCounter( tencounter )
        win32pdh.CloseQuery( tenQuery )
    return val

processIDs = GetProcessID('OUTLOOK') # Remember this is case sensitive
PQI = 0x400
#open a handle on to the process so that we can query it
OpenProcessHandle = windll.kernel32.OpenProcess(PQI, 0, processIDs)
# OK so now we have opened the process now we want to query it
GR_GDIOBJECTS, GR_USEROBJECTS = 0, 1
print(windll.user32.GetGuiResources(OpenProcessHandle, GR_GDIOBJECTS))
print(windll.user32.GetGuiResources(OpenProcessHandle, GR_USEROBJECTS))
#so we have what we want we now close the process handle
windll.kernel32.CloseHandle(OpenProcessHandle)

rawDescription: How do I gather performance metrics for GDI and user Objects using python

description: Gather performance metrics for GDI and user Objects using python


code:
L = [1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1]
import itertools
import operator
[[i for i,value in it] for key,it in itertools.groupby(enumerate(L), key=operator.itemgetter(1)) if key != 0]

rawDescription: Extract separate non-zero blocks from array


code:
class ItemMaster(models.Model):
    ...

    @classmethod
    def update_imdb_rank(self):
        with transaction.atomic():
            cursor = connection.cursor()
            cursor.execute("UPDATE main_itemmaster i JOIN mturk_imdbentry m USING (imdb_url) SET i.imdb_rank=m.imdb_rank")

rawDescription: Commit manually in django

description: Commit manually in django


code:
# some data..

x = np.array([[np.linspace(0,100,200)],[np.linspace(0,100,200)]])
y1 = np.linspace(0,100,200)
y2 = [2*i + 2 for i in y1]
y = np.array([y1,y2])
z = np.array([y2 - y1,y2 - y1]) # distance value

# Method

x=x.ravel()              #Flat input into 1d vector
x=(x[x!=np.isnan])   #eliminate any NaN
y=y.ravel()
y=(y[y!=np.isnan])
z=z.ravel()
z=(z[z!=np.isnan])

znew = griddata((x, y), z, (x[None,:], y[:,None]), method='linear') # grid the data and interpolate z so z will be equivalent at all equal x coords.

levels = np.linspace(z.min(), z.max(), 100)
plt.ylabel('Y', size=15)
plt.xlabel('X', size=15)
cmap = plt.cm.Blues
cs = plt.contourf(x , y, znew, levels=levels, cmap=cmap) # colour according to z
cbar = plt.colorbar(cs)
cbar.set_label('distance', rotation=90, fontsize=15)
cbar.set_ticks([50,100])

plt.show()

rawDescription: Gradient in color between plot lines in python based on distance between them


code:
def max_subarray(A):
    max_ending_here = max_so_far = 0
    for x in A:
        max_ending_here = max(0, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)

    if max_so_far > 0:
        return max_so_far
    else:
        return max(A)

rawDescription: Python Maximum sum of a range in an array


rawDescription: Displaying binomials and matrices using asciimath with mathjax


rawDescription: SocketServer continue execution after serve_forever


code:
listA = [a for a in listA if a not in listC]
listB = [a for a in listB if a not in listC]

rawDescription: Remove items from two lists if they meet a criteria


code:
p = subprocess.Popen('pwd', stdout = subprocess.PIPE)
p.communicate() # returns (stdout, None)

rawDescription: How to let the output being printed on the interactive shell with subprocess

description: Let the output being printed on the interactive shell with subprocess


code:
import atexit

def cleanup_directories():
    directories = ["C:\\projects\\project_alpha\\tmp",]
    for path in directories:
        if os.path.exists(path) and os.path.isdir(path):
            shutil.rmtree(path)

atexit.register(cleanup_directories)

rawDescription: shutil.rmtree(...) does not work in my script

description: Shutil.rmtree(...) does not work in my script


code:
def get_mem(servername, q):
    res = os.popen('ssh %s "grep MemFree /proc/meminfo | sed \'s/[^0-9]//g\'"' % servername)
    q.put(res.read().strip())

# ...

import threading, queue
q = queue.Queue()
threading.Thread(target=get_mem, args=("server01", q)).start()
result = q.get()

rawDescription: Threading in python: retrieve return value when using target=


code:
values = {'what': 'surreal', 'punctuation': 'is'}
template=" Hello, {what} world {punctuation} One of Python least-used functions is "
t = template.format(**values)
print(t)
# Hello, surreal world is One of Python least-used functions is

rawDescription: How to substitute values in a MAP to string template in Python

description: Substitute values in a MAP to string template in Python


code:
# transactional session
Session = sessionmaker(transactional=True)
sess = Session()

rawDescription: Trouble with copying dictionaries and using deepcopy on an SQLAlchemy ORM object


code:
import random
import string

lower = string.ascii_lowercase # letters a-z

s = 'zyxwvutsr'

l = ['abc', 'def']

# This loop will continue while the string s does not
# contain all of the substrings in l
while not all(i in s for i in l):
    s += random.choice(lower)

rawDescription: string list members in sample string in Python

description: String list members in sample string in Python


code:
with open("file.txt") as f:
    allLines = f.readlines()
    for lineNumber in range(len(allLines)):
        if "word" in allLines[lineNumber]:
            print("Match in line {0}".format(lineNumber))

rawDescription: python,find Specified word in large text file and return that lines?

description: Python,find Specified word in large text file and return that lines


code:
import shlex
shlex.split('Some whitespace "separated string"')

rawDescription: Convert a string to a whitespace separated list w/quoted elements


code:
def clearDate(self):
    self.MyInput.findChild(QtGui.QLineEdit).setText('')

rawDescription: Correct use of the .clear() method on QDateTimeEdit


code:
def match_ends(words):
    count = 0
    for item in words:
        if len(item) >= 2 and item[0] == item[-1]:
            count += 1
    return count

def front_x(words):
    x_list = []
    other_list = []
    for item in words:
        if item[0].lower() == "x":
            x_list.append(item)
        else:
            other_list.append(item)
    x_list.sort()
    other_list.sort()
    return x_list + other_list

rawDescription: Google's python class

description: Google's python class


code:
# before redirect
request.session['users_list'] = users_list

# in sent view
users_list = request.session.get('users_list', None)

rawDescription: Can any one explain how can i pass arg or kwargs from redirect to another view?


code:
if abc == 'abc':
    subprocess.check_output('bash file.sh', shell=True)

rawDescription: Execute File from python

description: Execute File from python


code:
from tqdm import tqdm
import requests

url = "http://example.com/bigfile.bin"
# Streaming, so we can iterate over the response.
response = requests.get(url, stream=True)

with open('output.bin', 'wb') as f:
    for data in tqdm(response.iter_content()):
        f.write(data)

rawDescription: Progress Bar while download file over http with Requests


code:
import random
rand_data = map(random.uniform, data[:-1], data[1:])

rawDescription: Generating a random number between two values from an array in Python


rawDescription: Find minimum Dic key and it's value from List


code:
def create(self, validated_data):

    if 'recipients' in validated_data:
        recipients_data = validated_data.pop('recipients')
    else:
        recipients_data = []

    for recipient_data in recipients_data:
        created_my_model = MyModel.objects.create(recipient=User.objects.get(id=recipient_data['id']),
                                                  text=validated_data['text'])

    return something # here you need to decide what to return

rawDescription: Create many objects. Django REST framework


code:
class MyModel(peewee.Model):

  def __str__(self):
    r = {}
    for k in self._data.keys():
      try:
         r[k] = str(getattr(self, k))
      except:
         r[k] = json.dumps(getattr(self, k))
    return str(r)

class User(MyModel):
    email = CharField()
    status = CharField(default="enabled")
    firstname = CharField()
    lastname = CharField()
    class Meta:
        database = db

rawDescription: Peewee model to JSON

description: Peewee model to JSON


code:
rs = c.execute("SELECT * FROM Categories")
cols = [d[0] for d in rs.description]
print(cols)
for rs in c.fetchall():
    print(rs)

rawDescription: How to use pyodbc to get results from all odbc compliant databases?

description: Use pyodbc to get results from all odbc compliant databases


code:
class Map:
    def __init__(self):
        self.robots = []

    def add_robot(self, robot):
        self.robots.add(robot)

    def is_occupied(self, x, y):
        for r in self.robots:
            if r.xpos == x and r.ypos == y:
                return True
        return False

rawDescription: What is the most effecient way to keep track of collisions


code:
name = "John"
idd = 11
person = Person(name, idd)
new_key = person.put()
auto_assigned_id = new_key.id()

rawDescription: Retrieve a numeric ID from a Model instance just created


code:
insert_sql = 'INSERT INTO admin_details(username, password)  VALUES("{0}","{1}")'.format(*tup)
cur.execute(insert_sql)
conn.commit()

rawDescription: Programming Error in python, How do I parse values of a tuple in a table with SQL query?


rawDescription: How to remove the first few characters of a string?

description: Remove the first few characters of a string


code:
def getnumber(strs):
    num = int(strs)
    return -1 if num < 0 else num

rawDescription: python: how do I do simple variable declaration?

description: Python: how do I do simple variable declaration


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

import json

s = 'Żółte słonie'
print(type(s))
print(repr(s))
sd = json.dumps(s)
print(repr(sd))
s2 = json.loads(sd)
print(type(s2))
print(repr(s2))

f = open('out.txt', 'w')
try:
    f.write(s2)
except UnicodeEncodeError:
    print('UnicodeEncodeError, encoding data...')
    f.write(s2.encode('UTF8'))
    print('data encoded and saved')
f.close()

rawDescription: Unicode encoding for Polish characters in Python


code:
("http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q='%s'"
 % sys.argv[1])

rawDescription: passing arguments into a python script from cmd line or a bash script

description: Passing arguments into a python script from cmd line or a bash script


code:
class Foo(object):
    def __init__(self):
       self.count = 0
    def callme(self):
       self.count += 1
       return self

a = Foo()
reduce(lambda x,y:x.callme(),range(7),a)
a.count

rawDescription: Compressing "n"-time object member call

description: Compressing "n"-time object member call


rawDescription: Trying to understand recursion in Python


code:
if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

rawDescription: Chrome native messaging doesn't accept messages of certain sizes (Windows)


code:
for s in mystrings:
    open_window_for_string(s)

rawDescription: Opening different windows in wxPython using strings from a list


code:
import Tkinter
tclsh = Tkinter.Tcl()
tclsh.eval("""
    proc unknown args {puts "Hello World!"}
    }"!dlroW olleH" stup{ sgra nwonknu corp
""")

rawDescription: Know any creative ways to interface Python with Tcl?


code: ioff()

rawDescription: How to disable screen update in matplotlib

description: Disable screen update in matplotlib


code:
Dict = {}
def getDetail():
    subdict = {}
    first_name = input("Enter first name")
    if first_name.lower() != 'quit':
        last_name = input("Enter last name")
        nick_name = input("Enter nickname")
        address = input("Enter address")
        number = input("Enter phone number")
        subdict['nick'] = nick_name
        subdict['firstname'] = first_name
        subdict['lastname'] = last_name
        subdict['address'] = address
        subdict['number'] = number
        dict[nick_name] = subdict

rawDescription: Append sub dictionary to main dictionary


code:
def list(self, *args, **kwargs):
    prefix = kwargs.get('prefix', args[0] if args else '')

rawDescription: Getting names of values passed as *args and **kwargs


code:
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import gaussian_kde
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
density = gaussian_kde(data)
xs = np.linspace(0,8,200)
density.covariance_factor = lambda : .25
density._compute_covariance()
plt.plot(xs,density(xs))
plt.show()

rawDescription: How to create a density plot in matplotlib?

description: Create a density plot in matplotlib


code: np.frompyfunc(f, 2, 1).outer(xs, ys)

rawDescription: Get matrix of all combinations of function evaluations


rawDescription: How do I use regex to match a specific word that contains at least one uppercase letter but not all in lowercase?

description: Use regex to match a specific word that contains at least one uppercase letter but not all in lowercase


code:
os.getcwd()
os.getcwd().split(os.sep)

rawDescription: Python: Output list of folders in given path


code:
from dulwich import index, repo
#get repository object of current directory
repo = repo.Repo('.')
indexfile = repo.index_path()
#we want to checkout HEAD
tree = repo["HEAD"].tree

index.build_index_from_tree(repo.path, indexfile, repo.object_store, tree)

rawDescription: Programmatically `git checkout .` with dulwich


rawDescription: Change type of a model field in Odoo preserving old records


code: added.sort(key=lambda x: os.stat(os.path.join(path_to_watch, x)).st_mtime)

rawDescription: Sorting files by date

description: Sorting files by date


code:
from datetime import datetime
datetime.fromtimestamp(1339119900000/1e3).strftime('%Y-%m-%d %H:%M')
datetime.fromtimestamp(1339120800000/1e3).strftime('%Y-%m-%d %H:%M')

rawDescription: datetime.date.fromtimestamp: ignores hour and minute

description: Datetime.date.fromtimestamp: ignores hour and minute


code:
d = {'Drogba': ['Le Mans', 'Chelsea', 'Galatasaray'], 'Beckham': ['Manchester United', 'Real Madrid', 'Los Angeles Galaxy']}
g = nx.Graph(d)
g.nodes()
g.edges("Beckham")
g.neighbors("Drogba")

rawDescription: NetworkX: Adding edges to a graph from a dictionary with lists as values


code:
arr
arr[np.argsort(arr[:,1])]

rawDescription: Python: sorting an array with NaNs

description: Python: sorting an array with NaNs


code:
from Tkinter import *
from random import *

################################################################################
# Application ##################################################################
################################################################################

class Application(Tk):
    def __init__(self):
        Tk.__init__(self); self.resizable(0, 0)
        self.geometry('{}x{}'.format(640, 480))

        self.button = Button(text = 'Check', command = self.checknum)
        self.button.place_configure(x = 170, y = 260, width = 300)

        self.value = IntVar(); self.number = Entry(textvariable = self.value)
        self.number.place_configure(x = 170, y = 220, width = 300)

        self.store = randint(1, 100)
        self.state, self.tries = 1, 0

        self.label_1 = Label(text = 'Tries: {}'.format(self.tries))
        self.label_1.place_configure(x = 10, y = 10) # place label

        self.label_2 = Label(text = 'Messages: ')
        self.label_2.place_configure(x = 10, y = 40)

        self.mainloop()

    def checknum(self):
        if self.state:
            if self.value.get() > self.store:
                self.tries += 1
                self.label_1.configure(text = 'Tries: {}'.format(self.tries))
                self.label_2.configure(text = 'Messages: {}'.format('Lower'))

            if self.value.get() < self.store:
                self.tries += 1
                self.label_1.configure(text = 'Tries: {}'.format(self.tries))
                self.label_2.configure(text = 'Messages: {}'.format('Higher'))

            if self.value.get() == self.store:
                self.tries += 1; self.state = 0
                self.label_1.configure(text = 'Tries: {}'.format(self.tries))
                self.label_2.configure(text = 'Messages: {}'.format('You won'))

################################################################################
# Run ##########################################################################
################################################################################

app = Application()

################################################################################
################################################################################
################################################################################

rawDescription: Python3.x Using easyGUI with magic number game


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

rawDescription: How can we plot solids of revolution in python 3 (with matplotlib)?


code:
np.ma.hstack((x, y))
np.ma.max(np.ma.hstack((x, y)))

rawDescription: Numpy: Stacking masked Arrays and calculating min/max


code:
from django.contrib.auth.decorators import login_required
from django.contrib.comments.models import Comment
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.contrib import comments

@login_required
def delete_own_comment(request, message_id):
    comment = get_object_or_404(comments.get_model(), pk=message_id,
            site__pk=settings.SITE_ID)
    if comment.user == request.user:
        comment.is_removed = True
        comment.save()

rawDescription: Allowing users to delete their own comments in Django


rawDescription: urllib: get utf-8 encoded site source code

description: Urllib: get utf-8 encoded site source code


code: len(info["comments"])

rawDescription: Extracting data from dictionary in python


code:
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import numpy as np
np.random.seed(2016)

N = 10**3
x_values = (np.random.random(size=N))*15
y_values = np.random.random(size=N)
plt.hist2d(x_values, y_values, bins=50, normed=True, vmin=0, vmax=1)
plt.colorbar(norm=mcolors.NoNorm)
plt.show()

rawDescription: doubts about setting range of colorbar in the hist2d plot - matplotlib

description: Doubts about setting range of colorbar in the hist2d plot - matplotlib


code:
from subprocess import Popen, PIPE, STDOUT
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE,
    stderr=STDOUT)

output = event.communicate()

rawDescription: Run BASH built-in commands in Python?

description: Run BASH built-in commands in Python


code: process = subprocess.Popen(['foo', '-b', 'bar'])

rawDescription: Can subprocess.call be invoked without waiting for process to finish?


rawDescription: Python - Defining an integer variable over multiple lines


code:
def keyfunc(item):
    key, value = item
    if isinstance(key, str):
        return 1
    else:
        return len(key)

max(d.items(), key=keyfunc)[0]

rawDescription: Need help to find with dictionary objects in python


code:
import csv
import collections
with open('in.csv', newline='') as f, open('out.csv', newline='') as result:
    next(f) # skip the input header row
    vals = collections.defaultdict(list) # start a default dict of {item:[],...}
    for row in csv.reader(f): # iterate through input CSV
        # find or create the key e.g. "2.1 53.2", and
        # append the id to its list of values
        vals['{} {}'.format(*row[:2])].append(row[2])
    # create a header row by adding ['id'] to a list of "valx" strings
    # by finding the maximum list by length, finding its length,
    # iterating over a range of that number,
    # and creating the necessary "valx" strings
    csv.writer(result, dialect='excel').writerow(['id'] + ['val{}'.format(num) for num in range(len(max(vals.values(), key=len)))])
    for k,v in sorted(vals.items()): # iterate over the items in the sorted dictionary
        # create an appropriate list by adding the key and the values, and write it
        csv.writer(result, dialect='excel').writerow([k] + list(v))

rawDescription: Python - CSV transpose cells with the same value / remove duplicates but keep values


code:
if len(path) > 255:
    path, ext = os.path.split(path)
    path = path[:252-len(ext)] + '...' + ext

description: File Upload:Trim-last-few-Characters-Save Extension


code:
import itertools
itertools.chain.from_iterable(itertools.repeat([1, 2, 3], 5))

rawDescription: Is there an elegant way to cycle through a list N times via iteration (like itertools.cycle but limit the cycles)?


code:
from pandas.io.data import DataReader
from pandas import Panel, DataFrame
symbols = ['AAPL', 'GLD', 'SPX', 'MCD']
data = dict((symbol, DataReader(symbol, "yahoo", pause=1)) for symbol in symbols)
panel = Panel(data).swapaxes('items', 'minor')
closing = panel['Close'].dropna()
closing.head()

rawDescription: python pandas organizing multidimensional data into an object

description: Python pandas organizing multidimensional data into an object


rawDescription: Why is my Python script not writing the last few lines into my file?


code:
class InvFileTransferSpeed(Widget):
  'Widget for showing the transfer speed (useful for file transfers).'

  format = '%6.2f %ss/%s'
  prefixes = ' kMGTPEZY'
  __slots__ = ('unit', 'format')

  def __init__(self, unit='loop'):
    self.unit = unit

  def update(self, pbar):
    'Updates the widget with the current SI prefixed speed.'

    if pbar.seconds_elapsed < 2e-10 or pbar.currval < 2e-10: # =~ 0
      scaled = power = 0
    else:
      speed = pbar.seconds_elapsed / pbar.currval
      power = int(math.log(speed, 1000))
      scaled = speed / 1000.**power

    return self.format % (scaled, self.prefixes[power], self.unit)

rawDescription: python-progressbar library - inverse FileTransferSpeed

description: Python-progressbar library - inverse FileTransferSpeed


code: from django_extensions.db.fields.json import JSONField

rawDescription: Convert Django models to normal objects

description: Convert Django models to normal objects


code:
import pandas as pd
data = [('a', 'b', 'c'), ('d', 'e', 'f')]
df = pd.DataFrame(data)
df.to_csv('test.csv', index=False, header=False)

rawDescription: How to write list of lists to CSV file Python?

description: Write list of lists to CSV file Python


rawDescription: Convert a large string into a list of floats when an item contains brackets


code:
import xml.etree.ElementTree as ET
tree = ET.parse(filePath)
data = float(tree.find('InfoType/SpecificInfo')[0].text)

rawDescription: Is parsing XML really this ugly in python?


rawDescription: How to set the timeout on HTTPConnection under python 2.4

description: Set the timeout on HTTPConnection under python 2.4


rawDescription: Adding the values of a dictionry to another dictionary


code:
try: import Image         # Python 2.x
except ImportError:
    from PIL import Image # Python 3.x

rawDescription: getting the color of pixels on the screen in Python3.x

description: Getting the color of pixels on the screen in Python3.x


code:
from itertools import zip_longest
a_dict = {"a":1,"b":3,"c":4}
b_dict = {"d":44,"e":23}
for a_pair,b_pair in zip_longest(a_dict.items(),b_dict.items()):
    if a_pair:
        print(a_pair[0],a_pair[1])
    if b_pair:
        print(b_pair[0],b_pair[1]);

rawDescription: iterating over dictionaries for getting all elements using single loop

description: Iterating over dictionaries for getting all elements using single loop


code:
Builder.load_string('''
<RotatedImage>:
    canvas.before:
        PushMatrix
        Rotate:
            angle: root.angle
            axis: 0, 0, 1
            origin: root.center
    canvas.after:
        PopMatrix
''')

class RotatedImage(Image):
    angle = NumericProperty()

rawDescription: Kivy how to rotate a picture

description: Kivy how to rotate a picture


code:
while True:
    rlist, wlist, xlist = select.select([client, proc.stdout], [], [])

rawDescription: Python subprocess: streaming in and out

description: Python subprocess: streaming in and out


code:
import itertools

for combination in itertools.combinations(iterable, k):
    print(combination)

rawDescription: k-combinations in Python 3.x

description: K-combinations in Python 3.x


code:
from bottle import Jinja2Template

@hook('before_request')
def before_request():
    Jinja2Template.defaults['myglobal'] = 'My global'

rawDescription: Bottle py and Jinja2 global variable

description: Bottle py and Jinja2 global variable


code:
import collections # requires Python 2.7 -- see note below if you're using an earlier version
def merge_dict(d1, d2):
    """
    Modifies d1 in-place to contain values from d2.  If any value
    in d1 is a dictionary (or dict-like), *and* the corresponding
    value in d2 is also a dictionary, then merge them in-place.
    """
    for k,v2 in d2.items():
        v1 = d1.get(k) # returns None if v1 has no value for this key
        if ( isinstance(v1, collections.Mapping) and
             isinstance(v2, collections.Mapping) ):
            merge_dict(v1, v2)
        else:
            d1[k] = v2

rawDescription: Python, merge multi-level dictionaries

description: Python, merge multi-level dictionaries


code:
import networkx as nx
import matplotlib.pyplot as plt
from random import random
g = nx.random_graphs.erdos_renyi_graph(10,0.5)
colors = [(random(), random(), random()) for _i in range(10)]
nx.draw_circular(g, node_color=colors)
plt.show()

rawDescription: networkx: change node color in draw_circular

description: Networkx: change node color in draw_circular


rawDescription: Run shell script in python

description: Run shell script in python


code: response.content = response.content.replace("BAD", "GOOD")

rawDescription: Django Middleware - How to edit the HTML of a Django Response object?


code:
img = request.files['imugen']
filename = secure_filename(img.filename)
img.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

rawDescription: Uploaded image is broken after writing to file


code:
import re
li = [int(d) for d in re.findall(r'iter_(\d+)\.caffemodel', ''.join(files))]

rawDescription: Extract int between two different strings in python


code: int(filter(str.isdigit, str1))

rawDescription: Extract Number from String - Python

description: Extract Number from String - Python


code:
import re

old = open("combined.glm").read()

space = re.compile("object line_space {.*?}",re.DOTALL + re.MULTILINE)
conf = re.compile("object line_conf {.*?}",re.DOTALL + re.MULTILINE)
ug = re.compile("object line_ug {.*?}",re.DOTALL + re.MULTILINE)
nod = re.compile("object nod_l {.*?}",re.DOTALL + re.MULTILINE)

all_space = space.findall(old)
all_conf = conf.findall(old)
all_ug = ug.findall(old)
all_nod = nod.findall(old)

with open("combined_order.glm","w") as f:
    for thing in all_space:
        f.write(thing + "\n\n")
    for thing in all_conf:
        f.write(thing + "\n\n")
    for thing in all_nod:
        f.write(thing + "\n\n")
    for thing in all_ug:
        f.write(thing + "\n\n")

rawDescription: trouble in rearranging the data in a text file using python

description: Trouble in rearranging the data in a text file using python


code:
d = {'Data': {0: 'information1', 1: 'information2', 2: 'information3'}}
inner = d['Data']

rawDescription: Splitting nested dictionary

description: Splitting nested dictionary


code:
def print_dict_stuff(name, d, key):
    print("Dictionary {} has value {} under key {}".format(name, d[key], key))

rawDescription: How do I print out a dict's name not {key:values}?

description: Print out a dict's name not {key:values}


code:
def nearbin(bin):
    ...

def main(args):
    parser = argparse.ArgumentParser(...)
    ...
    args = parser.parse_args(args)

    nearbin(args.bin)

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))

rawDescription: Python: using either command line or import


code:
##
# Parses an XML document from a string constant.  Same as {@link #XML}.
#
# @def fromstring(text)
# @param source A string containing XML data.
# @return An Element instance.
# @defreturn Element

fromstring = XML

rawDescription: What is the difference between Python's ElementTree.XML() and ElementTree.fromstring?


code:
visual_style["layout"] = layout
visual_style["bbox"] = (300, 300)
visual_style["margin"] = 10
plot(g, **visual_style)

rawDescription: How can one set the size of an igraph plot?


code:
data = client_sock.recv(1024)
with open('textfile.txt', 'a') as f:
    for ch in data:
        f.write('{}\n'.format(ord(ch)))

rawDescription: How can I read a byte array from a socket in Python

description: Read a byte array from a socket in Python


code:
import os
import sqlite3
try:
    import cPickle as pickle
except:
    import pickle

class MyObj(object):
    def __init__(self, arg):
        self.arg = arg
    def __str__(self):
        return 'MyObj(%r)' % self.arg

def adapter_func(obj):
    """Convert from in-memory to storage representation.
    """
    print('adapter_func(%s)\n' % obj)
    return pickle.dumps(obj)

def converter_func(data):
    """Convert from storage to in-memory representation.
    """
    print('converter_func(%r)\n' % data)
    return pickle.loads(data)

# Register the functions for manipulating the type.
sqlite3.register_adapter(MyObj, adapter_func)
sqlite3.register_converter("MyObj", converter_func)

def stuff():
    db_filename = 'todo.db'

    db_is_new = not os.path.exists(db_filename)

    conn = sqlite3.connect(db_filename)

    if db_is_new:
        print('need to create schema')
    else:
        print('database exists, assume schema does to')

    conn.close()

    db_filename = 'todo.db'

    # Create some objects to save.  Use a list of tuples so
    # the sequence can be passed directly to executemany().
    to_save = [ (MyObj('this is a value to save'),),
                (MyObj(42),),
                ]

    with sqlite3.connect(db_filename,
                         detect_types=sqlite3.PARSE_DECLTYPES) as conn:
        # Create a table with column of type "MyObj"
        conn.execute("""
        create table if not exists obj (
            id    integer primary key autoincrement not null,
            data  MyObj
        )
        """)
        cursor = conn.cursor()

        # Insert the objects into the database
        cursor.executemany("insert into obj (data) values (?)", to_save)

        # Query the database for the objects just saved
        cursor.execute("select id, data from obj")
        for obj_id, obj in cursor.fetchall():
            print('Retrieved', obj_id, obj, type(obj))
            print()

if __name__ == "__main__":
    stuff()

rawDescription: python sqlite3 code works in global space but thows error when I place it in a function

description: Python sqlite3 code works in global space but thows error when I place it in a function


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

class Base(models.Model):
    content_type = models.ForeignKey(ContentType,editable=False,null=True)

    def save(self):
        if(not self.content_type):
            self.content_type = ContentType.objects.get_for_model(self.__class__)
        self.save_base()

    def as_leaf_class(self):
        content_type = self.content_type
        model = content_type.model_class()
        if(model == Base):
            return self
        return model.objects.get(id=self.id)

rawDescription: How do I find the "concrete class" of a django model baseclass

description: Find the "concrete class" of a django model baseclass


code:
types,end_server_ip,end_server_alias = [],[],[]
with(open('in.txt', "r")) as f:
    types = [line.rstrip().split(",") for line in f] # Put List syntax to do list compreehension
    k = 0
    while k < len(types):
        print(types[k])
        if types[k][0] is not None: # acess types as index for row, and index for column
            if type(types[k][0]) == type('string'):
                print('Its a String!!!')
            print(1)
            end_server_ip.append(types[k][0])
        if types[k][1] is not None:
            print(2)
            if type(types[k][1]) == type('string'):
                print('Its a String!!!')
            end_server_alias.append(types[k][1])
        k += 1
f.close()

rawDescription: Reading from file,appending to lists

description: Reading from file,appending to lists


code:
import functools
def retry_until(desired_return_value, retries=0):
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            ...

rawDescription: Python: Return the name of a function within a function within a function


code:
current_poke = None
for item in pokemonList:
    if not current_poke:
        current_poke = (item, [])
    elif item:
        current_poke[1].append(item)
    else:
        name, types = current_poke
        pokeDict[name] = types
        current_poke = None

rawDescription: Converting a list into a multi-valued dict


code:
from os.path import dirname,realpath
sys.path.append(dirname(dirname(realpath(__file__))))

rawDescription: using os.path is quite verbose is there a more concise way to manipulate paths

description: Using os.path is quite verbose is there a more concise way to manipulate paths


code:
def reject_outliers(data, m=2):
    return data[abs(data - np.mean(data)) < m * np.std(data)]

rawDescription: Is there a numpy builtin to reject outliers from a list


code:
#!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "djangoToolkit.settings")
    sys.path.append("..\\LibraryProject\\src")
    from django.core.management import execute_from_command_line

    execute_from_command_line(sys.argv)

rawDescription: Manage.py cannot find package from other eclipse project


rawDescription: Converting DataFrame column data into array


code:
from datetime import datetime
import sys
import cx_Oracle
import csv

connection = cx_Oracle.connect('user','password', 'ORPM2')
cursor = connection.cursor()
SQL="SELECT * FROM EXPORT01"
cursor.execute(SQL)
filename = r"C:\Projects\SQL_Export\Export01.csv"

with open(filename, "wb") as fout:
    writer = csv.writer(fout)
    writer.writerow([i[0] for i in cursor.description ]) # heading row

    for row in cursor.fetchall():
        cols = list(row)
        cols[0] = cols[0].strftime("%d/%m/%Y")
        writer.writerow(cols)

cursor.close()
connection.close()

rawDescription: Exporting CSV via Python with headers & date formatting


code: admin = Blueprint('admin', __name__, static_folder='static', static_url_path='/static/admin')

rawDescription: Flask blueprint static directory does not work?


code:
ax2 = ax.twiny()

# Ensure that the x limits are the same
ax2.set_xlim(ax.get_xlim())

# Set the labels to be the values we want and rotated
ax2.set_xticklabels(other, rotation=90)

# Place the xticks on ax2 at the bar centers
ax2.set_xticks(x)

rawDescription: Align xticks on top of axes with bars in matplotlib


code:
kanjiCodes=['0x9C00', '0x9D70','0x9D6B', '0xFA2D']

print([chr(int(code_point, 16)) for code_point in kanjiCodes])
# ['鰀', '鵰', '鵫', '鶴']

rawDescription: How to convert from a unicode code point to an actual unicode string in python?

description: Convert from a unicode code point to an actual unicode string in python


code:
def __gt__(self, other):
    """Greater than ordering."""
    if not isinstance(other, Key):
      return NotImplemented
    return self.__tuple() > other.__tuple()

def __tuple(self):
    """Helper to return an orderable tuple."""
    return (self.app(), self.namespace(), self.pairs())

rawDescription: AppEngine/Python NDB key order

description: AppEngine/Python NDB key order


code:
m = np.random.rand(5,3)
b = m.tobytes()
mb = np.frombuffer(b).reshape(m.shape)

rawDescription: How to write a numpy array to a byte memorystream?

description: Write a numpy array to a byte memorystream


code:
import urllib
import json
import sys
import itertools

def hits(astr):
    for start in itertools.count():
        query = urllib.urlencode({'q':astr, 'rsz': 8, 'start': start*8})
        url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s'%(query)
        search_results = urllib.urlopen(url)
        results = json.loads(search_results.read())
        data = results['responseData']
        if data:
            hits = data['results']
            for h in hits:
                yield h['url']
        else:
            raise StopIteration

def showmore(astr,num):
    for i,h in enumerate(itertools.islice(hits(astr),num)):
        print('{i}: {h}'.format(i=i,h=h))

if __name__=='__main__':
    showmore(sys.argv[1],50)

rawDescription: how to increase the number of pages comes in google search?

description: Increase the number of pages comes in google search


code:
import pandas as pd
import numpy as np

df = pd.DataFrame({'trader' : ['a','a','a','a','a','a','a'],'stock' : ['a','a','a','a','a','a','b'], 'day' :[0,1,2,4,5,10,1],'delta':[10,-10,15,-10,-5,5,6], 'cumq' : [10,0,15,5,0,6,11] ,'tag': [1,1,2,2,2,0,0]})

def proc_trader(_df):
    if _df.shape[0] == 1:
        _df['tag'] = _df['delta'] == 0
        return _df

    _df['tag'] = np.nan
    # make every ending of a roundtrip with its index
    _df['tag'][df.cumq == 0] = range(1, (df.cumq == 0).sum() + 1)
    # backfill the roundtrip index until previous roundtrip;
    # then fill the rest with 0s (roundtrip incomplete for most recent trades)
    _df['tag'] = _df['tag'].fillna(method = 'bfill').fillna(0)
    return _df

df = df.groupby(['trader', 'stock']).apply(proc_trader)

rawDescription: how to identify specific sequences (round-trips) in a pandas dataset?

description: Identify specific sequences (round-trips) in a pandas dataset


rawDescription: converting byte to str python2.7

description: Converting byte to str python2.7


code:
import matplotlib.pyplot as plt
import matplotlib.tri as tri
from mpl_toolkits.mplot3d import Axes3D
import random

def f( x, y):
    if x + y < 1: return 0
    else: return 1

x = [0, 1, 1, 0]
y = [0, 0, 1, 1]
tris = [[0, 1, 3], [1, 2,3]]
z = [0] * 4

triv = tri.Triangulation(x, y, tris)

fig = plt.figure()
ax = fig.add_subplot( 111, projection='3d')
trip = ax.plot_trisurf( triv, z )
trip.set_facecolor('white')

xs = [random.random() for _ in range( 100)]
ys = [random.random() for _ in range( 100)]
zs = [f(xs[i], ys[i]) for i in range( 100)]

ax.scatter( xs, ys, zs)
plt.show()

rawDescription: Matplotlib -- mplot3d: triplot projected on z=0 axis in 3d plot?


code:
module.exports = {

  context: __dirname,

  entry: {
    'baseapplication/movies_list/static/movies_list/index':  '../movies_list/interfaces/index',
    'baseapplication/series_list/static/series_list/index':  '../series_list/interfaces/index',
   },

  output: {
    path: './',
    filename: "[name].js",
  },

}

rawDescription: React - Django webpack config with dynamic 'output'


code:
def function(self,RECORD):
    TEMP_LIST_RECORDS=[]
    #Depends the number of X, we got 10, 100,1000,10000 LOOPS
    LOOPS=int(math.pow(10,X_RANGE))
    DIGITS="%0"+str(X_RANGE)+"d"

    #Then we create the records and we add to the MYSQL data query
    for x in range (0,LOOPS):

        RECORD = GET_NEW_RECORD()  # THIS IS THE CHANGE.

        END_OF_NUMBER=DIGITS%x
        RECORD.DN=DN_NUMBER+str(END_OF_NUMBER)
        RECORD.GN=GN_NUMBER+str(END_OF_NUMBER)

        TEMP_LIST_RECORDS.append(RECORD)

    return TEMP_LIST_RECORDS

rawDescription: Appending modified object to list in for loop -- only last modification is stored


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

N = 1e5
lum = 10**10.5 * np.random.normal(loc=1, scale=1, size=1e5)
lum = np.log10(lum)
dist = np.random.normal(loc=5, scale=5, size=1e5)

f, (ax1, ax2) = plt.subplots(1,2, sharex=False, sharey=True,figsize=(20,8))
# Not bothered with the locators
#ax1.xaxis.set_minor_locator(minor_locator3)
#ax1.yaxis.set_minor_locator(minor_locator4)
ax1.tick_params('both', length=10, width=2, which='major')
ax1.tick_params('both', length=5, width=2, which='minor')
ax1.set_xlabel(r'$\log\mathcal{L} ~[\odot]$',fontsize=30)
ax1.set_ylabel(r'Number of galaxies',fontsize=30)
ax1.set_yscale('log')
ax1.set_xlim(6,13.5)
bins = np.linspace(6,13,141)
ax1.hist(lum,bins,histtype='step')
# Subselect the luminosities
mask = (lum >= 10) & (lum <= 11)
# Overplot colored bar histogram
ax1.hist(lum[mask],bins,histtype='bar', color='red', lw=0)

#ax2.xaxis.set_minor_locator(minor_locator5)
#ax2.yaxis.set_minor_locator(minor_locator6)
ax2.tick_params('both', length=10, width=2, which='major')
ax2.tick_params('both', length=5, width=2, which='minor')
ax2.set_xlabel(r'$r_e ~{\rm [Kpc]}$',fontsize=30)
ax2.set_yscale('log')
bins = np.linspace(0,25,251)
ax2.hist(dist,bins,histtype='step')

plt.subplots_adjust(wspace=0.005, left=0.15, right=0.9, top=0.95, bottom=0.05)
plt.savefig('R50_hist.png',bbox_inches='tight')

rawDescription: partially shade the histogram in python

description: Partially shade the histogram in python


code:
df = pd.DataFrame({"col":[1, 33, 555, 7777]})
df["new_col"] = ["%07d" % x for x in df.col]
df

rawDescription: Pandas command unintentionally shifting data between rows


code:
# Ellipsoid
u = np.linspace(0, 2.*np.pi, 100)
v = np.linspace(0, np.pi, 100)
x = 60 * np.outer(np.cos(u), np.sin(v))
y = 20 * np.outer(np.sin(u), np.sin(v))
z = 10 * np.outer(np.ones(np.size(u)), np.cos(v))

rawDescription: Matplotlib parametric surface plot unexpected results, why?


code:
import dateutil.parser
data = ['3-Mar-15', '1-Apr-14', '27-Aug-14', '18-Jan-13']

[dateutil.parser.parse(x).isocalendar()[1] for x in data]

Out[117]: [10, 14, 35, 3]

rawDescription: Get the week index of each date?

description: Get the week index of each date


code: from django.contrib.auth.hashers import make_password

rawDescription: How can I convert plaintext password to django passwords when importing users?

description: Convert plaintext password to django passwords when importing users


code:
import numpy as np
from scipy.interpolate import griddata

# random data to interpolate
x = np.array([0, 10, 13, 17, 20, 50, 55, 60.0])
y = np.array([10, 20, 40, 80, 90, 95, 100, 120.0])
zg = np.random.randn(8, 8)

#select one of the following two line, it depends on the order in z
#xg, yg = np.broadcast_arrays(x[:, None], y[None, :])
xg, yg = np.broadcast_arrays(x[None, :], y[:, None])

yg2, xg2 = np.mgrid[y.min()-10:y.max()+10:100j, x.min()-10:x.max()+10:100j]

zg2 = griddata((xg.ravel(), yg.ravel()), zg.ravel(), (xg2.ravel(), yg2.ravel()), method="nearest")
zg2.shape = yg2.shape

import pylab as pl

pl.pcolormesh(xg2, yg2, zg2)
pl.scatter(xg.ravel(), yg.ravel(), c=zg.ravel())

rawDescription: Scipy Griddata Output Dimensions

description: Scipy Griddata Output Dimensions


code:
import requests

url = 'http://my-public-bucket.s3.amazonaws.com/'
files = {
    'key': ('', 'test/test.jpg'),
    'file': open('test.jpg', 'rb'),
}

r = requests.post(url, files=files)

rawDescription: Upload images and metadata to public Amazon S3 bucket with Python requests


code: csv_type21 = Button(csvfiles, text = "Browse ...", command = lambda obj = var21, tid = 21: find_csvfile(obj, tid))

rawDescription: Tkinter button remains sunken when pressed


rawDescription: tuple in redis / python: can store, not retrieve

description: Tuple in redis / python: can store, not retrieve


code:
import somemodule
somemodule.aFunction = aFunction

rawDescription: Is it good practice to pass a Python module as an argument


code:
def counter(func):
    def wrapper(*args, **kwargs):
        wrapper.count += 1
        return func(*args, **kwargs)       # <- this line is important!!
    wrapper.count = 0
    return wrapper

rawDescription: Python wrapper preventing function call?

description: Python wrapper preventing function call


code:
distance_x = x-self.location[0]
distance_y = y-self.location[1]
if abs(distance_x) < abs(distance_y):
    ratio = distance_x/abs(distance_y)
    speed_x = ratio * speed

rawDescription: moving a rectangle to a specific point

description: Moving a rectangle to a specific point


code:
vals = "key=val key2=val2"
dict(s.split("=") for s in vals.split())

rawDescription: convert dsn string in python to kwargs

description: Convert dsn string in python to kwargs


code:
import string

s = '@x arg-xa, arg. xb, arg xc @y arg-ya, arg. yb, arg yc @z arg-za, arg. zb, arg zc'

result = []

for part in s.split('@')[1:]:  # `[1:]` skips the first (empty) element
    command, _, arguments = part.partition(' ')

    result.append({
        'command': command,
        'args': map(string.strip, arguments.split(', '))
    })

rawDescription: Python Regex Named Groups

description: Python Regex Named Groups


code:
import re

def make_tree(data):
    items = re.findall(r"\(|\)|\w+", data)

    def req(index):
        result = []
        item = items[index]
        while item != ")":
            if item == "(":
                subtree, index = req(index + 1)
                result.append(subtree)
            else:
                result.append(item)
            index += 1
            item = items[index]
        return result, index

    return req(1)[0]

string = "(TOP (S (NP (PRP I))..." # omitted for readability
tree = make_tree(string)

print(tree)
# Output: ['TOP', ['S', ['NP', ['PRP', 'I']]...

rawDescription: Split "Nested" String By Parentheses into Nested List


code: obj = type('obj', (object,), {'propertyName' : 'propertyValue'})

rawDescription: How to create inline objects with properties in Python?

description: Create inline objects with properties in Python


rawDescription: how to make triangle using python 2.7

description: Make triangle using python 2.7


code:
from chardet import detect

with open('your_file.txt', 'rb') as ef:
    detect(ef.read())

rawDescription: Read file with Python without knowing encoding


code:
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import run_wsgi_app

class QueueItem(db.Model):
  created = db.DateTimeProperty(required=True, auto_now_add=True)
  data = db.BlobProperty(required=True)

  @staticmethod
  def push(data):
    """Add a new queue item."""
    return QueueItem(data=data).put()

  @staticmethod
  def pop():
    """Pop the oldest item off the queue."""
    def _tx_pop(candidate_key):
      # Try and grab the candidate key for ourselves. This will fail if
      # another task beat us to it.
      task = QueueItem.get(candidate_key)
      if task:
        task.delete()
      return task
    # Grab some tasks and try getting them until we find one that hasn't been
    # taken by someone else ahead of us
    while True:
      candidate_keys = QueueItem.all(keys_only=True).order('created').fetch(10)
      if not candidate_keys:
        # No tasks in queue
        return None
      for candidate_key in candidate_keys:
        task = db.run_in_transaction(_tx_pop, candidate_key)
        if task:
          return task

class QueueHandler(webapp.RequestHandler):
  def get(self):
    """Pop a request off the queue and return it."""
    self.response.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    task = QueueItem.pop()
    if not task:
      self.error(404)
    else:
      self.response.out.write(task.data)

  def post(self):
    """Add a request to the queue."""
    QueueItem.push(self.request.body)

rawDescription: What is the simplest way to implement a remote FIFO queue as a Python GAE application?


code:
f = open("C:/file.txt", "r")  #name of file open in read mode

lines = f.readlines()   #split file into lines

print(lines[1])  #print line 2 from file

rawDescription: Reading and Writing from files in python


rawDescription: Regex - How can I match a phrase to the end of a line?


code:
while True:
    try:
        choice = int(input("what would you like to do ? "))
    except ValueError:
        print ("Invalid choice.Valid choises are between 1-4.")
        continue
    if choice<1 or 4<choice:
        print ("Invalid choice.Valid choises are between 1-4.")
        continue
    else:
        print ("some codes will work on here..")

rawDescription: Python- Do not want letters or numbers outside of range input


code:
for line in input_file:
    if 'WB_LI' in line and year in line:
        #printing lines that matches user input
        percentage = int(line[58:61])
        total += percentage
        count_instance+=1
        if percentage > max_value:
            max_value = percentage
            max_line = line
        if percentage < min_value:
            min_value = percentage
            min_line = line

rawDescription: How to find the first instance of a min and max value in a file using python?

description: Find the first instance of a min and max value in a file using python


rawDescription: alternative for python pivot_table for frequency table of two variables

description: Alternative for python pivot_table for frequency table of two variables


code:
class TestModel(models.Model):
    enb_id = models.IntegerField(null=True, verbose_name=" eNB ID", blank=True)

    class Meta:
        verbose_name = " test model"

rawDescription: How to stop auto-capitalization of verbose_name in django

description: Stop auto-capitalization of verbose_name in django


rawDescription: How to use eval inside exec in Python 2

description: Use eval inside exec in Python 2


rawDescription: Dictionary generation and data appending in Python


code:
class CustomStreamListener(tweepy.StreamListener):

  def check_ukcoords(self, status):
      if status.coordinates is not None:
          lat = status.coordinates['coordinates'][1]
          lng = status.coordinates['coordinates'][0]
          return 49.7 < lat < 58.8 and -6.1 < lng < 1.7

  def check_uscoords(self, status):
      if status.coordinates is not None:
          lat = status.coordinates['coordinates'][1]
          lng = status.coordinates['coordinates'][0]
          return 25.1 < lat < 49.1 and -125 < lng < -60.5

rawDescription: Using Tweepy to sort tweets by location

description: Using Tweepy to sort tweets by location


code:
class Simplemovingaverage():
    def __init__(self, navg, items):
        self.navg = navg
        self.items = items

    def calculate(self):
        av = []
        for i in range(len(self.items)):
            if i+1 < self.navg:
                av.append(0)
            else:
                av.append(sum(self.items[i+1-self.navg:i+1])/self.navg)
        return av

rawDescription: Python simple moving average class based


code:
@event.listens_for(Command, 'before_insert', propagate = True)
def serialize_before_insert(mapper, connection, target):
    print("serialize_before_insert")
    target._bin_array = target.toBinArray()

rawDescription: SQLAlchemy-serialize values into column of table


code:
import subprocess

output = subprocess.check_output(['sudo', 'dpkg', '-l'])

rawDescription: How to save the data coming from "sudo dpkg -l" in Ubuntu terminal by using python

description: Save the data coming from "sudo dpkg -l" in Ubuntu terminal by using python


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

dates       = [20020514, 20020515, 20020516, 20020517, 20020520]
highs       = [1135, 1158, 1152, 1158, 1163]
lows        = [1257, 1253, 1259, 1264, 1252]
upperLimits = [1125.0, 1125.0, 1093.75, 1125.0, 1125.0]
lowerLimits = [1250.0, 1250.0, 1156.25, 1250.0, 1250.0]

zaxisvalues0= [0, 0, 0, 0, 0]
zaxisvalues1= [1, 1, 1, 1, 1]
zaxisvalues2= [2, 2, 2, 2, 2]

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

ax.plot(dates, zaxisvalues1, lowerLimits, color = 'b')
ax.plot(dates, zaxisvalues2, upperLimits, color = 'r')

for i,j,k,h in zip(dates,zaxisvalues0,lows,highs):
    ax.plot([i,i],[j,j],[k,h],color = 'g')

ax.scatter(dates, zaxisvalues0, highs, color = 'g', marker = "o")
ax.scatter(dates, zaxisvalues0, lows, color = 'y', marker = "^")

matplotlib.pyplot.show()

rawDescription: Connecting two points in a 3D scatter plot in Python and matplotlib


code:
def parseRoster(self, response):
    play_original = response.meta['play']
    players1 = []
    int = 0
    for players in response.xpath("//td[@class='sortcell']"):

        play = play_original.copy()

        play['name'] = players.xpath("a/text()").extract()[0]
        play['position'] = players.xpath("following-sibling::td[1]").extract()[0]
        play['age'] = players.xpath("following-sibling::td[2]").extract()[0]
        play['height'] = players.xpath("following-sibling::td[3]").extract()[0]
        play['weight'] = players.xpath("following-sibling::td[4]").extract()[0]
        play['college'] = players.xpath("following-sibling::td[5]").extract()[0]
        play['salary'] = players.xpath("following-sibling::td[6]").extract()[0]
        print(play)
        players1.append(play)
    print(players1)
    return players1

rawDescription: Issue with my Scrapy callback function

description: Issue with my Scrapy callback function


code:
import signal
import sys

def exit_func(signal, frame):
    '''Exit function to be called when the user presses ctrl+c.
    Replace this with whatever you want to do to break out of the loop.
    '''
    print("Exiting")
    sys.exit(0) # remove this if you do not want to exit here

# register your exit function to handle the ctrl+c signal
signal.signal(signal.SIGINT, exit_func)

#loop forever
while True:
    ...

rawDescription: Simplest method to call a function from keypress in python(3)


code:
with open("filename.txt") as f:
    lines = [line.strip("\n") for line in f]

rawDescription: What happens if I read a file without closing it afterwards?


code:
import numpy as np
arr = np.array(tableData)
np.insert(arr, (2, 4), None, axis=1)

rawDescription: Pythonic Way of Inserting Columns at Arbitrary Positions


code:
import datetime
from google.appengine.ext import db

q = db.Query(DateTest)

# This month
month = datetime.datetime.today().replace(day=1, hour=0, minute=0, second=0, microsecond=0)

q.filter('dateAdded >= ', month)
results = q.fetch(10)

rawDescription: How to get the records from the current month in App Engine (Python) Datastore?

description: Get the records from the current month in App Engine (Python) Datastore


code:
import ftplib
ftp = ftplib.FTP("ladsweb.nascom.nasa.gov")
ftp.login()
ftp.cwd("allData/5/MOD11A1/2012/193/")
filenames = []
ftp.retrlines('NLST', filenames.append)
print(filenames)

rawDescription: Where is the file name list stored?

description: Where is the file name list stored


code:
while values[index] is not None:
    index = (index+1)% len(values)

rawDescription: Looping around a list in python

description: Looping around a list in python


code:
import threading
t = threading.Thread(name='non-daemon', target=non_daemon)

t.start() # This will not block
t.join() #  This is blocking

rawDescription: What is the pythonic way of doing nothing?


code:
import itertools

for _ in itertools.repeat(None, N):
    do_something()

rawDescription: pythonic way to do something N times without an index variable?

description: Pythonic way to do something N times without an index variable


code: dict(zip(keys, values))

rawDescription: How to create a dictionary from a couple of tuples of the same size?

description: Create a dictionary from a couple of tuples of the same size


code:
numOfResults = sel.get_xpath_count(xpath)
l = []
for i in range(1,numOfResults+1):
   l.append(sel.get_text(xpath='(%s)[%d]'%(xpath, i)))

rawDescription: Indexing over the results returned by selenium


code:
from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(10,20)
p.x
p.y
p.x = 100

rawDescription: Should I implement classes with constant interface in Python?


code:
def flow_rate_to_size(rate):
    if rate <= 0.2:
        size = 15
    elif 0.2 < rate <= 1:
        size = 22
    elif 1 < rate <= 1.9:
        size = 32
    else:
        size = 45
    return size

flow_rates = [0.1, 0.3, 1, 2, 0.4, 1.5]
pipe_sizes = [flow_rate_to_size(rate) for rate in flow_rates]
print(pipe_sizes)

rawDescription: Logical operators with lists

description: Logical operators with lists


code:
grid.shape
indices
grid[:,19,16,8]
grid[(slice(None),) + indices]

rawDescription: How to mix numpy slices to list of indices?

description: Mix numpy slices to list of indices


rawDescription: "io.open" is improperly opening UTF-16 files


code:
import types

class E(object):
    def __get__(self,obj,cls):

        def returned(*args):
            print(obj.__dict__)
        return types.MethodType(returned, obj, cls)

rawDescription: Implementing bound method using descriptor


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

plt.plot([10, 20, 30], [1, 3, 2])
axes = plt.gca()
axes.get_xaxis().set_major_locator(ticker.MultipleLocator(1))
axes.get_xaxis().set_major_formatter(ticker.FormatStrFormatter("%x"))
plt.show()

rawDescription: Hexadecimal X-axis in matplotlib?

description: Hexadecimal X-axis in matplotlib


code:
def reverse_words(string): # don't name your own object str
    return ' '.join([word[::-1] for word in
                     string.split(' ')])

rawDescription: Reverse words in string - same order - including whitespace


code:
img = plt.imread('latest_0013679_caz.tiff')
plt.imshow(img[:, :, 0], cmap=plt.cm.coolwarm)

rawDescription: How to display tiff file in color?

description: Display tiff file in color


code:
from binascii import crc32
with open(filename, "rb") as f:
    data = f.read()
crc32(data)

rawDescription: How do I convert a binary image into an in-memory data structure in python?

description: Convert a binary image into an in-memory data structure in python


code:
req_handler.send_response(200, 'OK')
req_handler.wfile.write(C.output()) # you may need to .encode() the C.output()
req_handler.end_headers()
#write body...

rawDescription: Sending "Set-Cookie" in a Python HTTP server


code: [k for k in my_dict if k[0] == dog]

rawDescription: Do I need to pass in all values of a tuple to index a dictionary?


code:
class MyLabel(QtGui.QWidget):
    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        painter.setPen(QtCore.Qt.black)
        painter.translate(20, 100)
        painter.rotate(-90)
        painter.drawText(0, 0, "hellos")
        painter.end()

rawDescription: PyQT: Rotate a QLabel so that it's positioned diagonally instead of horizontally


code:
zip(cv.get_feature_names(),
    np.asarray(X.sum(axis=0)).ravel())

rawDescription: List the words in a vocabulary according to occurrence in a text corpus , Scikit-Learn


code:
def myFunc(aList):
    for i in range(0,len(aList)):
        aList[i] = 0
    return aList

wholeList = range(0,10)
wholeList[3:6] = myFunc(wholeList[3:6])

rawDescription: Slicing a list without copying

description: Slicing a list without copying


code:
class0=np.zeros((3,4))
class1=np.ones((2,4))
class2=np.ones((5,4))*2
class3=np.ones((2,4))*3
class_list=[class0,class1,class2,class3]
lenlist=[x.shape[0] for x in class_list]
m = np.concatenate(class_list, axis=0)
m
lenlist
class_ends=np.cumsum(lenlist)
class_ends
Y=np.repeat(range(len(lenlist)),lenlist)
Y

rawDescription: Efficient way to concatenate Numpy arrrays and extract indexes


code: [row[0] for row in nested_list[1:]]

rawDescription: taking a value from double list and making it a menu

description: Taking a value from double list and making it a menu


code:
import A

class ClearStaticMiddleware(object):
  def process_response(self, request, response):
    A.x = {}
    return response

rawDescription: Class static attribute value shared between requests


rawDescription: Python - Coding a formula weaving between + and -


code:
class FlaskApp(Flask):

    def __init__(self, *args, **kwargs):
        super(FlaskApp, self).__init__(*args, **kwargs)
        self.complex_object = create_my_object()

app = FlaskApp(__name__)

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

rawDescription: Initialize objects on different threads for flask server


code:
class Simple(object):
    def make(self, arg):
        return arg * 2
s = Simple()
def times_eight(self, arg):
    return arg * 8
s.make = times_eight.__get__(s, Simple)
s.make(10)
type(s.make)

rawDescription: monkey-patching python an instance method

description: Monkey-patching python an instance method


code:
while playing == 1:
   for _ in range(10):
       if GPIO.input(9) == 0:
           GPIO.output(18, GPIO.LOW)
           print("Well done!!")
           break
       time.sleep(0.1)
   else:
       print("Wrong!")
       lives = lives - 1

rawDescription: Python if statement delay

description: Python if statement delay


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

fig, ax = plt.subplots()

ax.scatter(*np.random.random((2, 5)), s=200, marker=r'$\circlearrowleft$')
ax.scatter(*np.random.random((2, 5)), s=200, marker=r'$\circlearrowright$')

plt.show()

rawDescription: Matplotlib specific marker (rotation symbol)


code:
## dbutil.py
class DBConnection(object):
    def __init__(self, cfg_name):
        self.cfg_name = cfg_name
        self.cfg = self.load_config(self.cfg_name)
        self.pool = txpostgres.ConnectionPool(None, min=5, **self.cfg)

    @staticmethod
    def load_config(name):
        with open('config.json') as json_file:
            cfg = json.load(json_file)
        return cfg.get(name)

    @defer.inlineCallbacks
    def get_pool(self):
        try:
            yield self.pool.start()
        except txpostgres.AlreadyConnected:
            pass
        defer.returnValue(self.pool)

@defer.inlineCallbacks
def db_factory(cfg_name):
    db = DBConnection(cfg_name)
    db.pool = yield db.get_pool()
    defer.returnValue(db)

## basehandler.py
def __init__(self, name=None, db=None):
    resource.Resource.__init__(self)
    self.name = name
    self.db = db
    self.pool = self.db.pool

@defer.inlineCallbacks
def runQuery(self, *args, **kwargs):
    res = yield self.pool.runQuery(*args, **kwargs)
    defer.returnValue(res)

## server.py
@defer.inlineCallbacks
def init_site(db):
    db = yield db_factory(db)
    root = RootURLHandler(db)
    reactor.listenTCP(SERVER_PORT, site)

def main(db):
    log.startLogging(LogFile('server.log', '.', maxRotatedFiles=5))
    init_site(db)
    reactor.run()

rawDescription: Sharing a txpostgres connection pool

description: Sharing a txpostgres connection pool


code:
from subprocess import Popen, PIPE, STDOUT
soxCall = '/usr/local/bin/sox ' + infileName + \
                 ' ' + outfileName + ' rate 8k'
p = Popen(soxCall, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)

rawDescription: Downsample wav RIFF file using python

description: Downsample wav RIFF file using python


code:
import numpy.distutils.system_info as sysinfo
sysinfo.get_info('atlas')

rawDescription: How to check blas/lapack linkage in numpy/scipy?

description: Check blas/lapack linkage in numpy/scipy


code:
class Iterator(object):
    def __iter__(self):
        return self

    def __next__(self):
        # Python 3
        return 'a value'

    next = __next__  # Python 2

rawDescription: How to make an object both a Python2 and Python3 iterator?

description: Make an object both a Python2 and Python3 iterator


code:
plt.scatter(X,f)
x = np.linspace(0, 1, 1000)
plt.plot(x,qdbeta0+qdbeta1*x+qdbeta2*x**2)

rawDescription: Trying to plot a quadratic regression, getting multiple lines


code:
hb = ax.hexbin(test1["X"], test1["Y"], C=test1.Size, **plot_format)

# you might need to force a draw event here, otherwise `hb.get_colors()` can return
# incorrect values
ax.figure.canvas.draw()

counts = hb.get_array()         # get the counts (n,)
colors = hb.get_facecolors()    # get the facecolors of the patches (n, 4)
colors[:, 3] = counts > 0       # set the alpha channel to 0 where counts <= 0
hb.set_facecolors(colors)       # update the facecolors of the patches

rawDescription: Matplotlib hexbin: How to avoid displaying bins where np.mean is zero


code:
from __future__ import print_function
f = lambda x: print(x)
f("HI")

rawDescription: Why doesn't print work in a lambda?

description: Why doesn't print work in a lambda


code:
from django.db import models
from django.contrib.auth.models import AbstractUser

class CustomUser(AbstractUser):
    type_choices = (
        ('SU', 'Super User'),
        ('A', 'User Type A'),
        ('B', 'User Type B'),
        ('C', 'User Type C'),
    )
    user_type = models.CharField(max_length=2,
                                 choices=type_choices,
                                 default='C')

class UserDetails(model.Model):
    type = models.OneToOneField('CustomUser')
    extra_info = models.CharField(max_length=200)

rawDescription: Django 1.8, Multiple Custom User Types

description: Django 1.8, Multiple Custom User Types


code:
logfile=open('/home/prasanna/Downloads/processed_file','r')
cleanfile=open('/home/prasanna/Downloads/cleaned_file','a')
with logfile:
    for line in logfile:
         line_words=line.split()
         url=line_words[6].split('.')
         if "gif?" not in line and ".png?" not in line and ".js?" not in line:
              cleanfile.write(line)
cleanfile.close()
logfile.close()

rawDescription: To find a pattern in python in a url

description: To find a pattern in python in a url


code:
from wsgiref.simple_server import make_server
from pyramid.config import Configurator
from pyramid.response import Response

def hello_world(request):
    return Response('Hello')

class LanguagePredicate():

    def __init__(self, val, config):
        self.val = val

    def text(self):
        return 'lang = %s' % (self.val,)

    phash = text

    def __call__(self, context, request):
        return request.GET.get('lang') == self.val

def hello_world_fr(request):
    return Response('bonjour')

def main():
    config = Configurator()

    config.add_route_predicate('lang', LanguagePredicate)

    config.add_route('hello_fr', '/', lang='fr')
    config.add_route('hello', '/')

    config.add_view(hello_world_fr, route_name='hello_fr')
    config.add_view(hello_world, route_name='hello')

    app = config.make_wsgi_app()
    return app

if __name__ == '__main__':
    app = main()
    server = make_server('0.0.0.0', 6547, app)
    print ('Starting up server on http://localhost:6547')
    server.serve_forever()

rawDescription: Custom route predicates in Pyramid

description: Custom route predicates in Pyramid


rawDescription: Colormap is being ignored for matplotlib contourf plot with custom levels


rawDescription: A more pythonic way to build a class based on a string (how not to use eval)


code:
import sys,csv
csv.writer(sys.stdout).writerow(['one", f"', 'two', 'three'])
csv.reader(['"one"", f""",two,three']).next()

rawDescription: python csv help

description: Python csv help


code:
#!/usr/bin/python
import os.path

def lvl_down(path):
    return os.path.split(path)[0]

def lvl_up(path, up_dir):
    return os.path.join(path, updir)

print(lvl_down('a/b/c'))   # prints a/b
print(lvl_up('a/b/c','d')) # prints a/b/c/d

rawDescription: Python - change given directory one level above or below


code:
foo = eval('lambda x, y: x +y ')
foo(1, 2)

rawDescription: How can I create a callable function from a textarea in Flask?

description: Create a callable function from a textarea in Flask


code:
def main():
  t1_stop= threading.Event()
  t1 = threading.Thread(target=thread1, args=(1, t1_stop))

  t2_stop = threading.Event()
  t2 = threading.Thread(target=thread2,  args=(2, t2_stop))

  time.sleep(duration)
  #stop the thread2
  t2_stop.set()

def thread1(arg1, stop_event):
  while(not stop_event.is_set()):
      #similar to time.sleep()
      stop_event.wait(time)
      pass

def thread2(arg1, stop_event):
  while(not stop_event.is_set()):
      stop_event.wait(time)
      pass

rawDescription: Stopping a thread after a certain amount of time


code:
import re
a = ['rhubarb','plain custard','jam','vanilla custard','pie','cheesecake']
[i for i, s in enumerate(a, start=1) if re.search('custard', s)]

rawDescription: Python index a list where a regex matches


code:
d = {'FOO': "('BAR','BAA'),('CAR','CAA')", 'FOOO': "('BAAR','BAAA'),('CAAR','CAAA')"}
d2 = {k: zip(*ast.literal_eval(v))[0] for k,v in d.iteritems()}
# d2 is now {'FOO': ('BAR', 'CAR'), 'FOOO': ('BAAR', 'CAAR')}

rawDescription: Filtering items within Python dictionary values containing strings of tuples


rawDescription: Generating your own colormap in SciPy

description: Generating your own colormap in SciPy


code:
from periodic import element
hydrogen = element('hydrogen')
hydrogen.mass

rawDescription: Is there any chemical database written for python?


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

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: Plotting 3D scatter with python?

description: Plotting 3D scatter with python


code:
while start + 1< len(search):
    start = search.find(needle, start +1)

    if start == -1:
        break

    results.append(start )

return results

rawDescription: findString program python

description: FindString program python


code:
for i in xrange(len(mat)):
 print(mat[i:] + mat[:i])

rawDescription: Change elements order in a matrix (python)


code:
class Pair(object):

    def __init__(self, key, value):
        self.key = key
        self.value = value

    def __iter__(self):
        return (v.key for v in self.value)

    # alternative iter function, that allows more complicated logic
    def __iter__(self):
        for v in self.value:
             yield v.key

p = Pair("parent", [Pair("child0", "value0"), Pair("child1", "value1")])

assert list(p) == ["child0", "child1"]

rawDescription: Implementing __next__ in a custom class

description: Implementing __next__ in a custom class


code:
import curses
import time

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)

i = 0

while True:
    i += 1

    event = screen.getch()
    screen.clear()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.addstr("The User Pressed UP", curses.A_REVERSE)
        screen.refresh()
        time.sleep(2)

    elif event == curses.KEY_DOWN:
        screen.addstr("The User Pressed DOWN", curses.A_BLINK)
        screen.refresh()
        time.sleep(2)

    else:
        screen.addstr("Loop {0}".format(i))

curses.endwin()

rawDescription: Key event printing in a terminal using `curses`


rawDescription: How to Replace a single, unknown, index in a 2d list in python


code:
import xml.etree.ElementTree as ElementTree

def main():
    with open('data.xml') as f:
        et = ElementTree.parse(f)
        for article in et.findall('article'):
            xml_string = ElementTree.tostring(article)
            # Now you can write xml_string to a new file
            # Take care to name the files sequentially

if __name__ == '__main__':
    main()

rawDescription: Extract each xml node in separate txt file


code:
import datetime
import json

def datetime_handler(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()
    raise TypeError("Unknown type")

json.dumps(data, default=datetime_handler)

rawDescription: datetime.datetime is not JSON serializable

description: Datetime.datetime is not JSON serializable


code:
# coding: utf-8
import os
import sys
import weakref

from txredis.client import RedisClient

from twisted.web import server, resource
from twisted.internet import reactor, protocol, defer
from twisted.python import log

from utils import cors, redis_conf_from_url

log.startLogging(sys.stdout)

PORT = int(os.environ.get('PORT', 9000))
REDIS_CONF = redis_conf_from_url(os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379'))
REDIS_SUB_CHANNEL = 'votes'

class RedisBroadcaster(RedisClient):
    def subscribe(self, *channels):
        self._send('SUBSCRIBE', *channels)

    def handleCompleteMultiBulkData(self, reply):
        if reply[0] == u"message":
            message = reply[1:][1]
            self.sse_connector.broadcast(message)
        else:
            super(RedisClient, self).handleCompleteMultiBulkData(reply)

@defer.inlineCallbacks
def redis_sub():
    clientCreator = protocol.ClientCreator(reactor, RedisBroadcaster, password=REDIS_CONF.get('password'))
    redis = yield clientCreator.connectTCP(REDIS_CONF['host'], REDIS_CONF['port'])
    redis.subscribe(REDIS_SUB_CHANNEL)

class Subscribe(resource.Resource):
    isLeaf = True
    sse_conns = weakref.WeakSet()

    @cors
    def render_GET(self, request):
        request.setHeader('Content-Type', 'text/event-stream; charset=utf-8')
        request.write("")
        self.sse_conns.add(request)
        return server.NOT_DONE_YET

    def broadcast(self, event):
        for conn in self.sse_conns:
            event_line = "data: {}\r\n".format(event)
            conn.write(event_line + '\r\n')

if __name__ == "__main__":
    sub = Subscribe()
    reactor.listenTCP(PORT, server.Site(sub))

    RedisBroadcaster.sse_connector = sub
    reactor.callLater(0, redis_sub)

    reactor.run()

rawDescription: Twisted SSE server subscribed to Redis via pubsub


code:
form = driver.find_element_by_id("home-login")

# login
user_fieldelement = form.find_element_by_id(user_fieldID)
user_fieldelement.send_keys(puca_username)

# password
passwd_fieldelement = form.find_element_by_id(passwd_fieldID)
user_fieldelement.send_keys(puca_password)

rawDescription: Selenium webdriver - element can be found but is not visible?


code: im = numpy.reshape(c, (32,32,3), order='F')

rawDescription: How to view an RGB image with pylab

description: View an RGB image with pylab


code:
s = u'word1 \ufeffword2'
s = s.replace(u'\ufeff', '')
s

rawDescription: How to remove this special character?

description: Remove this special character


code:
out = [e for e in list_input for i in list_lines if e.startswith(i)]
output.writelines(out)

rawDescription: Python remove file lines without matches from another file


code:
filenames = os.listdir('.')
text = '\n'.join(filenames)
console.settext(text)

rawDescription: Make a string output as a list

description: Make a string output as a list


code: [re.search(r'data_(.+?)_48P', i).group(1) for i in files if re.search(r'data_.+?_48P', i)]

rawDescription: Extract substring from list of file names in Python or R


code:
from boto.s3.connection import S3Connection

conn = S3Connection('your-access-key','your-secret-key')
bucket = conn.get_bucket('bucket')
for key in bucket.list():
    try:
        res = key.get_contents_to_filename(key.name)
    except:
        logging.info(key.name+":"+"FAILED")

rawDescription: Downloading the files from s3 recursively using boto python.


code:
from yattag import Doc, indent

doc, tag, text = Doc().tagtext()

with tag("p"):
    text("My paragraph.")

print(indent(doc.getvalue())) # will indent the tags but not the text directly contained between <tag> and </tag>

print(indent(doc.getvalue(), indent_text = True)) # will also indent the text directly contained between <tag> and </tag>

rawDescription: How to make yattag source better formatted?

description: Make yattag source better formatted


code:
import itertools
ranges=np.linspace(0,n,n*10+1)  # alternatively 'range(100)' or so to test
combinations=itertools.combinations(ranges,2)
save=[]

for c in combinations:
    if c[1] - c[0] > 0.5:
        save.append(c)

rawDescription: faster way of finding combinations?

description: Faster way of finding combinations


code: any(s in word for s in {'a', 'b', 'c'})

rawDescription: Multiple if conditions comparing to one

description: Multiple if conditions comparing to one


code:
input = r'a\ue00f\ue010\ue011\ue012\ue013\a'
elems = input.split('\\')
''.join((elems[0], elems[-1]))

rawDescription: Remove characters between backslashes in string in Python


code:
class MyFrame1 (wx.Frame):
    def __init__(self):
        super(MyFrame1, self).__init__()

        fluid_sizer = wx.BoxSizer(wx.HORIZONTAL)
        fluid_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)
        #                             ^--- proportion = 1

        self.fixed_panel = wx.Panel(self, wx.ID_ANY, wx.DefaultPosition, wx.Size(-1,-1), wx.TAB_TRAVERSAL)
        self.fixed_panel.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_HIGHLIGHT))
        fixed_sizer = wx.BoxSizer(wx.VERTICAL)
        fixed_sizer.SetMinSize(wx.Size(150,-1))
        self.m_button1 = wx.Button(self.fixed_panel, wx.ID_ANY, u"MyButton", wx.DefaultPosition, wx.DefaultSize, 0)
        fixed_sizer.Add(self.m_button1, 0, wx.ALL, 5)
        self.fixed_panel.SetSizer(fixed_sizer)
        self.fixed_panel.Layout()
        fixed_sizer.Fit(self.fixed_panel)

        fluid_sizer.Add(self.fixed_panel, 0, wx.EXPAND |wx.ALL, 5)
        #                                 ^--- proportion = 0

        fluid_sizer.AddSpacer((0, 0), 1, wx.EXPAND, 5)
        #                             ^--- proportion = 1

        self.SetSizer(fluid_sizer)
        self.Layout()

rawDescription: wxpython: how would I configure a box sizer so that it has a center column that moves on resize, but doesn't change dimensions(pic explanation inside)

description: Wxpython: how would I configure a box sizer so that it has a center column that moves on resize, but doesn't change dimensions(pic explanation inside)


code:
values = ["this", "is", "your", "array"]
result = " ".join(values)

rawDescription: Print space after each word

description: Print space after each word


rawDescription: python : use optparse on given list rather than on system command line arguments

description: Python : use optparse on given list rather than on system command line arguments


code:
import math
t = range(8001)
wave = map(lambda x: math.sin(2 * math.pi * 440 * x), t)

rawDescription: How to play a vector in Python?

description: Play a vector in Python


code:
class AlgoMixin(object):
  # Does not end in "Test"; not a subclass of unittest.TestCase.
  # You may prefer "AbstractBase" or something else.

  def test_empty(self):
    result = self.function(make_empty_graph())
    self.assertTrue(result)

class TestF(AlgoMixin, unittest.TestCase):
  function = staticmethod(f)
  # Doesn't need to be in setup, nor be an instance attribute.
  # But doesn't take either self or class parameter, so use staticmethod.

  def test_random(self):
    pass  # Specific test for algorithm 'f'.

rawDescription: How to factorise python test cases with nosetests

description: Factorise python test cases with nosetests


code: highestscore = max(firstscore, secondscore, thirdscore)

rawDescription: Python: finding which variable has the highest value and assign that value to a new variable


code:
import BaseHTTPServer, SimpleHTTPServer
import ssl
import socket
import select
import threading

FRONTEND_PORT = 4443
BACKEND_PORT_SSL = 44431
BACKEND_PORT_HTTP = 44432
HOST = 'localhost'

httpd_ssl = BaseHTTPServer.HTTPServer((HOST, BACKEND_PORT_SSL), SimpleHTTPServer.SimpleHTTPRequestHandler)
httpd_ssl.socket = ssl.wrap_socket (httpd_ssl.socket, certfile='key.pem', server_side=True)

httpd_direct = BaseHTTPServer.HTTPServer((HOST, BACKEND_PORT_HTTP), SimpleHTTPServer.SimpleHTTPRequestHandler)

def serve_forever(http_server):
    http_server.serve_forever()

def categorize(sock, addr):
    data = sock.recv(1)
    if data == '\x16':
        port = BACKEND_PORT_SSL
    else:
        port = BACKEND_PORT_HTTP
    other_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    other_sock.connect((HOST, port))
    other_sock.send(data)
    inp = [sock, other_sock]
    select_timeout = 1.0
    try:
        while 1:
            r,w,x = select.select(inp,[],[],select_timeout)
            if not r:
                continue
            for s in r:
                o_s = inp[1] if inp[0]==s else inp[0]
                buf = s.recv(4096)
                if not buf:
                    raise socket.error
                o_s.send(buf)
    except socket.error:
        pass
    finally:
        for s in inp:
            s.close()

threading.Thread(target=serve_forever, args=(httpd_ssl,)).start()
threading.Thread(target=serve_forever, args=(httpd_direct,)).start()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, FRONTEND_PORT))
sock.listen(10)

while True:
    conn, addr = sock.accept()
    threading.Thread(target=categorize, args=(conn, addr)).start()

rawDescription: Python Magic (smart, dual-mode) SSL Socket?


code:
simple_variable = initial_value

def ViewName(request):
    global simple_variable
    simple_variable = value
    ...

def AnotherViewName(request):
    global simple_variable

rawDescription: django how to use a variable globally

description: Django how to use a variable globally


code:
[x*x for x in range(5)]
sum(_) # instead of having to type sum([0,1,4,9,16]) by hand

rawDescription: python interpreter with ellipsis _ function?

description: Python interpreter with ellipsis _ function


code:
regex = r'^0{0,4}%s ?$' % building_no
address = Address.objects.filter(building__iregex=regex)\

rawDescription: Django Queryset: Cast VARCHAR field in SQL before filtering


rawDescription: ctypes pointer to a c_int vs array of c_ints

description: Ctypes pointer to a c_int vs array of c_ints


code:
def product_Image(self):
    """Method to return store image for admin panel"""

    images = ''
    for image_path in self.image_paths:
        images += '<img src="/images/%s" height="150" width="150"/>' % image_path
    return images
product_Image.allow_tags = True

rawDescription: how to show multiple images in Django admin panel

description: Show multiple images in Django admin panel


code:
id_1d = np.arange(9)

# getting the indices of the multi-dimensional array
idx,idy,idz = np.unravel_index(id_1d,(3,3,3))

(idx,idy,idz)
(array([0, 0, 0, 0, 0, 0, 0, 0, 0]),
 array([0, 0, 0, 1, 1, 1, 2, 2, 2]),
 array([0, 1, 2, 0, 1, 2, 0, 1, 2]))

# getting the 1d indecis
np.ravel_multi_index((idx,idy,idz),(3,3,3))
array([0, 1, 2, 3, 4, 5, 6, 7, 8])

rawDescription: efficient algorithm for 1d to 3d index correspondence in numpy

description: Efficient algorithm for 1d to 3d index correspondence in numpy


code:
import easygui
import inspect
import functools

funcs = [f for f in easygui.__dict__.values() if callable(f)]
for func in funcs:
    sig = inspect.signature(func)
    if 'title' in sig.parameters:
        newf = functools.partial(func, title='mytitle')
        setattr(easygui, func.__name__, newf)

rawDescription: Automatically replace the default value for each function in module


code:
if xbmc.getInfoLabel('Network.MacAddress') != None:
    mac_address = xbmc.getInfoLabel('Network.MacAddress')
else:
    mac_address = None

rawDescription: how to get mac address in android with python

description: Get mac address in android with python


code:
def locked_iter(it):
    it = iter(it)
    lock = threading.Lock()
    while 1:
        try:
            with lock:
                value = it.next()
        except StopIteration:
            return
        yield value

rawDescription: How to wrap a Python iterator to make it thread safe?

description: Wrap a Python iterator to make it thread safe


code:
from collections import Counter  # or defaultdict

col_counts = Counter()           # or defaultdict(int)

last_value = object()            # won't show up in table
for row in access_table:
    col_counts[row[field]] += 1
    if row[field] != last_value:
        print(col_counts[last_value])
        last_value = row[field]
    ...
    other_processing()
    ...

rawDescription: How do I loop through the rows in a column and count them using Python?

description: Loop through the rows in a column and count them using Python


code:
class Zone(Entity):
    __mapper_args__ = {'polymorphic_identity': 'zones'}
    __tablename__ = "zones"
    id          = Column(Integer, ForeignKey('entities.id'), primary_key=True)
    @property
    def transits(self):
        return self.transits_from_here + self.transits_to_here

class Transit(Base):
    __tablename__ = "transits"
    id          = Column(Integer, primary_key=True)
    start = Column(Integer, ForeignKey('zones.id'))
    end = Column(Integer, ForeignKey('zones.id'))

    s_zone = relationship(Zone, primaryjoin=(start==Zone.id), backref="transits_from_here")
    e_zone = relationship(Zone, primaryjoin=(end==Zone.id), backref="transits_to_here")

rawDescription: Combining relationships

description: Combining relationships


code:
x = np.array([0,0,0,0,0,1,1,2,2,2,1,1,0,0])
n = x.sum()
rows = np.arange(n)
positions = np.nonzero(x)[0]
cols = np.repeat(positions, x[positions])
result = np.zeros((n, len(x)), dtype=int)
result[rows, cols] = 1
result

rawDescription: Dissolve numpy array into binary array

description: Dissolve numpy array into binary array


code: return char in x

rawDescription: More concise way of checking if a character is equal to a set of given characters in Python?


code:
from itertools import chain
try:
    first_row = next(results)
    for row in chain((first_row,), results):
        pass # do something
except StopIteration as e:
    pass # 0 results

rawDescription: How can I check if SQLite cursor result from a SELECT statement is empty?

description: Check if SQLite cursor result from a SELECT statement is empty


code:
import string as str_module

alphabet = "abcdefghijklmnopqrstuvwxyz0123456789"
key = None
with open("cryptkey", "r") as f:
    key = f.read(36)

tocryptvar = None
with open("tocrypt.txt", "r") as f:
    tocryptvar = f.read().lower()

trans_table = str_module.maketrans(alphabet, key)

tocryptvar = tocryptvar.translate(trans_table)

rawDescription: Replacing parts of a string simultaneously


code:
class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__()
        comboStyle="QComboBox {background-color: #7A7A7A; border: 1px solid black;}"
        self.setStyleSheet(comboStyle)
        for each in ['Item_1','Item_2','Item_3','Item_4','Item_5']:
            item=QtGui.QTreeWidgetItem([each])
            self.addTopLevelItem(item)
            combo1=QtGui.QComboBox()
            combo2=QtGui.QComboBox()
            self.setItemWidget(item, 1, combo1)
            self.setItemWidget(item, 2, combo2)
        self.setColumnCount(5)
        self.resize(360,240)
        self.show()

rawDescription: How to share single StyleSheet among multiple item-widgets?

description: Share single StyleSheet among multiple item-widgets