code:
import time
def current_time_as_float():
    lt = time.localtime()
    return ((lt.tm_sec / 60.) + lt.tm_min / 60.) + lt.tm_hour

rawDescription: Python reading local time from system (Ubuntu) and getting in a float format


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

options = {'linewidth':2,
           'color':'red',
           'linestyle':'dashed'}

x = np.linspace(0,10,100)
y = x**2

fig, ax = plt.subplots()

ax.plot(x,y, **options)

plt.show()

rawDescription: Defining plot options once and call them for several subplots


rawDescription: How to use group by pandas to fetch a column corresponding to a max column?

description: Use group by pandas to fetch a column corresponding to a max column


rawDescription: Print full ascii art

description: Print full ascii art


code:
import subprocess
FileName = "/Users/fis/Desktop/installation_guide.txt"
subprocess.call(['open', FileName])

rawDescription: How to open a file on mac osx in python

description: Open a file on mac osx in python


rawDescription: django Getting unwatched items

description: Django Getting unwatched items


code:
False and some_function()
True or some_function()

rawDescription: Why doesn't the operator module have a function for logical or?


code:
import xlwt
import datetime

workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sheet1')

date_format = xlwt.XFStyle()
date_format.num_format_str = 'dd/mm/yyyy'

worksheet.write(0, 0, datetime.datetime.now(), date_format)

workbook.save('date_format.xls')

rawDescription: Writing xlwt dates with Excel 'date' format


rawDescription: Rounding Pandas Timestamp to minutes

description: Rounding Pandas Timestamp to minutes


code:
profile = user.profile
profile.age = 34
profile.save()

rawDescription: How do you update an attribute in a user profile in Django with a command?

description: Update an attribute in a user profile in Django with a command


code:
sentence = input("Input your sentence: ")
findCount = 0
lines = 0
fLines = open('keywords1.txt').readlines()
for line in fLines:
    lines += 1
    if line in sentence:
       findCount += 1
if lines == findCount:
   print("hello there")

rawDescription: How to search for multiple keywords in a textfile in Python

description: Search for multiple keywords in a textfile in Python


code:
import sys
sys.argv = raw_input('Enter command line arguments: ').split()

#Rest of the program here

rawDescription: Passing command Line argument to Python script within Eclipse(Pydev)


code:
import csv, datetime, os
from lxml import etree

def makeFacet(event, newheaders, ev, facetname, catname, count, nhposstart, nhposend):
    facets = etree.SubElement(event, "facets", name=facetname)
    categories = etree.SubElement(facets, "categories", name=catname)
    instance = etree.SubElement(categories, "instance")
    instance.set("instance-tag", count)

    for i in range(nhposstart, nhposend):
        property = etree.SubElement(instance, "property")
        property.set("name", newheaders[i])
        property.set("value", ev[i].strip())

# read the csv
fh = "SO.csv"
rh = open(fh, "rU")

try:
    rlist = list(csv.reader(rh))
except csv.Error as e:
    sys.exit("file %s, line %d: %s" % (filename, reader.line_num, e))
finally:
    rh.close()

# generate the xml

# newheaders is a mapping of the csv column names, because they don't correspondent w/ the XML
newheaders = ["REPORT_ID","NEXT_REPORT_ID","initial-event-date","number","title","summary-docket-num", "description-story"]

root = etree.Element("co_ehs")

object = etree.SubElement(root, "object")

object.set("id", "3") # Not sure about this one
object.set("object-type", "ehs-report")

for c, ev in enumerate(rlist[1:]):
    event  = etree.SubElement(object, "event")
    event.set("event-tag", "%s"%c)
    makeFacet(event, newheaders, ev, "header", "processing", "%s"%c, 0, 4)
    makeFacet(event, newheaders, ev, "informational", "short-title", "%s"%c, 4, 5)
    makeFacet(event, newheaders, ev, "header", "file_num", "%s"%c, 5, 6)
    makeFacet(event, newheaders, ev, "informational", "short_narrative", "%s"%c, 6, 7)

print(etree.tostring(root, xml_declaration=True, encoding="UTF-8", pretty_print=True))

rawDescription: How to turn python list comprehensions into xml

description: Turn python list comprehensions into xml


code:
import re

myRegex = re.compile(r"\*\*(.+?)\*\*")
string = "some **text** and some **more**"

output = myRegex.sub(r"\1", string)

rawDescription: Markdown emphasis - re substitution

description: Markdown emphasis - re substitution


code:
def ack5(m, n):
    if m == 0: return n + 1
    if m == 1: return n + 2
    if m == 2: return 2*n + 3
    if m == 3: return 8*(2**n - 1) + 5
    if n == 0: return ack5(m-1, 1)
    return ack5(m-1, ack5(m, n-1))

rawDescription: Best style for maintaining long equation


code:
# Wrapped in a custom context manager for better readability
@contextlib.contextmanager
def get_session():
    with contextlib.closing(Session()) as session:
        yield session

with get_session() as session:
    session.add(...)

rawDescription: try-finally with SqlAlchemy: is this a good habit?

description: Try-finally with SqlAlchemy: is this a good habit


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

def update_thread(sender, **kwargs):
    instance = kwargs['instance']
    created = kwargs['created']
    raw = kwargs['raw']
    if created and not raw:
        instance.thread.last_message_time = instance.datetime
        instance.thread.save()

post_save.connect(update_thread, sender=NewMessage)

rawDescription: Django: How to update the field of another model during object creation


code:
a_max = a.max(axis=0)
...
out = log(sum(exp(a - a_max), axis=0))

rawDescription: Does scipy logsumexp() deal with the underflow challenge?


code:
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

X, Y = np.mgrid[-1:1:20j, -1:1:20j]
Z = (X+Y) * np.exp(-6.0*(X*X+Y*Y)) + np.random.rand(X.shape[0])

xnew, ynew = np.mgrid[-1:1:80j, -1:1:80j]
tck = interpolate.bisplrep(X, Y, Z, s=0)
znew = interpolate.bisplev(xnew[:,0], ynew[0,:], tck)

fig = plt.figure(figsize=(12,12))
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, cmap='summer', rstride=1, cstride=1, alpha=None)
plt.show()

fig = plt.figure(figsize=(12,12))
ax = fig.gca(projection='3d')
ax.plot_surface(xnew, ynew, znew, cmap='summer', rstride=1, cstride=1, alpha=None, antialiased=True)
plt.show()

rawDescription: Smooth surface Plot with Pyplot

description: Smooth surface Plot with Pyplot


code:
from collections import Counter

tokens = ["today", "good", "computer", "people", "good"]
single_tokens = [k for k, v in Counter(tokens).iteritems() if v == 1 ]
# single_tokens == ['today', 'computer', 'people']

rawDescription: Filter items that only occurs once in a very large list


code:
def remove_duplicates(documents):
    unique_documents = []
    seen = set()
    for document in documents:
        if (document['user'], document['text']) in seen:
            continue
        unique_documents.append(document)
        seen.add((document['user'], document['text']))

    return unique_documents

rawDescription: How to remove duplicate dictionaries based on 2 keys?

description: Remove duplicate dictionaries based on 2 keys


code:
import serial
import threading
import Queue
import Tkinter as tk

class SerialThread(threading.Thread):
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self.queue = queue
    def run(self):
        s = serial.Serial('COM10',9600)
        while True:
            if s.inWaiting():
                text = s.readline(s.inWaiting())
                self.queue.put(text)

class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.geometry("1360x750")
        frameLabel = tk.Frame(self, padx=40, pady =40)
        self.text = tk.Text(frameLabel, wrap='word', font='TimesNewRoman 37',
                            bg=self.cget('bg'), relief='flat')
        frameLabel.pack()
        self.text.pack()
        self.queue = Queue.Queue()
        thread = SerialThread(self.queue)
        thread.start()
        self.process_serial()

    def process_serial(self):
        while self.queue.qsize():
            try:
                self.text.delete(1.0, 'end')
                self.text.insert('end', self.queue.get())
            except Queue.Empty:
                pass
        self.after(100, self.process_serial)

app = App()
app.mainloop()

rawDescription: python code for serial data to print on window.

description: Python code for serial data to print on window.


rawDescription: How to find a string between to special characters in python?

description: Find a string between to special characters in python


code:
import pyx
pyx.unit.set(defaultunit="cm")
c=pyx.canvas.canvas()
c.fill(pyx.path.circle(1,2,0.25))
c.writePDFfile('filename')

rawDescription: Python tool(s) to make drawings using dimensionful units


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

df = pd.DataFrame(
    [(1, 2), (1, 3), (1, 4), (2, 1), (2, 2)], columns=['col1', 'col2'])
df.hist(bins=4, by=df['col1'])
plt.savefig('/tmp/out.png')

rawDescription: in python pandas, how to save a 'grid chart'?

description: In python pandas, how to save a 'grid chart'


code:
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')

patches, texts, autotexts = plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')

otherInfo = [3, 5, 3, 4]

for text, info in zip(autotexts, otherInfo):
    text.set_text(u"%s ± %.1f" % (text.get_text(), info)) #you can play here with the format to get the label that you want

rawDescription: Matplotlib Pie Chart Mathtext Label/Autopct


code:
import subprocess

args = ['-u', 'wjimenez5271', '-p']
subprocess.call('mysql', args)
print('done')

rawDescription: How to wrap mysql in a python script

description: Wrap mysql in a python script


rawDescription: How to parse the string into list of tuples

description: Parse the string into list of tuples


code:
import Tkinter as tk
import threading
import random
import time
from Queue import Queue, Empty

root = tk.Tk()
time_label = tk.Label(root, text='<unknown> seconds')
volt_label = tk.Label(root, text='<unknown> volts')
time_label.pack()
volt_label.pack()

def DAQ(q):
    while True:
        q.put((time.time(), random.randrange(100)))
        time.sleep(2)

def update_data(queue, root):
    try:
        timestamp, volts = queue.get_nowait()
    except Empty:
        pass
    else:
        time_label.config(text='{:.1f} seconds'.format(timestamp))
        volt_label.config(text='{:.4f} volts'.format(volts))
    root.after(100, update_data, queue, root)

data_queue = Queue()
t = threading.Thread(target=DAQ, args=(data_queue,))
t.daemon = True
t.start()
update_data(data_queue, root)
root.mainloop()

rawDescription: Data Acquistion using Python

description: Data Acquistion using Python


code: re.findall('a.*?c', 'abcbc')

rawDescription: How can I make re.findall('a.*c', 'abcbc') match abc instead of abcbc

description: Make re.findall('a.*c', 'abcbc') match abc instead of abcbc


code:
from cStringIO import StringIO
import numpy as np

x = np.ones(10)

f = StringIO()
np.savez_compressed(f, x=x)
f.seek(0)
out = f.read()

print(out)

rawDescription: Serialize numpy arrays into an npz string?


code:
s = """bla bla bla infor-
mation bla bla bla"""
s.replace('-\n','')

rawDescription: Merge hyphenated word in python

description: Merge hyphenated word in python


code:
class Game(object):
    def __init__(self):
        self.count = 4
        self.current_player = 0

    def next_turn(self):
        self.current_player += 1
        self.current_player %= self.count

rawDescription: How to determinate whose turn is? Card game (tkinter)

description: Determinate whose turn is? Card game (tkinter)


code: pd.merge(df1, df2, on=['id', 'name']).set_index(['id', 'name']).sum(axis=1)

rawDescription: Pandas DataFrame merge suming column

description: Pandas DataFrame merge suming column


code:
myDict = {'x' : 1, 'y' : 2}
myList = [1,2,3]
post = {'uname' : 'jon', 'node' : myDict, 'access-levels' : myList}
json.dumps(post)

rawDescription: Send Multiple Node Json Post in Python

description: Send Multiple Node Json Post in Python


code:
def make_dtype(n_float_cols):
    spec = dict(
        names=['name'] + ['f{:03d}'.format(i) for i in range(n_float_cols)],
        formats=['|S12'] + ['<f8'] * n_float_cols,
    )
    return np.dtype(spec)

dt = make_dtype(51)

rawDescription: Correct dtype definition

description: Correct dtype definition


code:
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import time

class WorkerThread(QThread):
    updateSignal = pyqtSignal(int)

    def run(self):
        count = 0
        while True:
            time.sleep(0.1)
            self.updateSignal.emit(count)
            count += 1

class ProgressBar(QProgressBar):
    def __init__(self, parent=None):
        super(ProgressBar, self).__init__(parent)
        self.worker = WorkerThread()
        self.worker.updateSignal.connect(self.updateProgress) # here should bind to a general slot

    def startWorker(self):
        self.worker.start()

    def updateProgress(self, progress):
        self.setValue(progress)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    p = ProgressBar()
    p.startWorker()
    p.show()
    app.exec_()

rawDescription: PyQt4 unable to call function of main Gui class from QThread class


code:
def f(t, *a):
    return sum(exp(x * t) for x in a)

rawDescription: Creating recursively a function gaining variables each iteration in Python


code: div_odd = lambda n: (n//2, n//2 + 1)

rawDescription: Python divide odd number to closest integers


code:
#!/usr/bin/env python

from app import test_settings
from django.core.management import call_command
import django
import os
import sys

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.test_settings')
django.setup()

# We only suppose 'unit' and 'integration' tests
test_type = sys.argv[1] if len(sys.argv) == 2 else 'unit'
for app_name in test_settings.CUSTOM_APPS:
    try:
        module = '{}.tests.{}'.format(app_name, test_type)
        __import__(module)
        print('Module \'{}\' exists. Running {} tests...'
              .format(module, test_type))
        call_command('test', module, verbosity=2, failfast=True, pattern='*.py')
    except ImportError:
        print('Module \'{}\' doesn\'t exist. Checking next...'.format(module))

rawDescription: How can I discover tests in specific locations using folder wildcards?

description: Discover tests in specific locations using folder wildcards


code:
cookie_string = "; ".join([str(x)+"="+str(y) for x,y in cookies.items()])
headers = {
        "Accept-Language" : "en-US,en;q=0.8,pt;q=0.6",
        "Connection" : "keep-alive",
        "Cookies": cookie_string
}
requests.get(url, headers=headers)

rawDescription: Convert cookies as dict to cookies as string for HTTP request


code:
from collections import Counter
def predominant_sign(data):
    signs = Counter(k['sign'] for k in data if k.get('sign'))
    for sign, count in signs.most_common():
        print(sign, count)

rawDescription: Count occurrences of each key in python dictionary


code:
def removeT(b):
    s1 = ""
    while True:
        s2 = raw_input("Enter a word/sentence you want to process: ")
        if s2 == "quit": return s1
        s2 = s2.replace("T", "")
        if b:
            s2 = s2.replace("t", "")
        s1 += s2

rawDescription: How To Take Specific Letters Off A String


code:
d = [{'year':   2012, 'x':        8154   , 'y': 13496},
     {'year':   2013, 'x':        8585   , 'y': 11421},
     {'year':   2014, 'x':        10376  , 'y': 10890},
     {'year':   2015, 'x':        11720  , 'y': 10714},]

df_so = pd.DataFrame(d)

fig, ax = plt.subplots()
ax.plot('year', 'x', data=df_so)

ax.plot('year', 'y', data=df_so)

ax.xaxis.get_major_formatter().set_useOffset(False)
ax.xaxis.get_major_locator().set_params(integer=True)

rawDescription: Matplotlib: How to fix unexpected x tick behaviour


code:
class Group(db.Model):
    ...
    people = db.relationship(Person, lambda: groups_people, lazy='dynamic',
        backref=db.backref('groups', lazy='dynamic'))
    ...

rawDescription: Why can't I run a query against my has many relationship in SQLAlchemy?


code:
plt.quiverkey(QV1, 1.2, 0.515, 2, 'arrow 1', coordinates='data')
plt.quiverkey(QV2, 1.2, 0.520, 2, 'arrow 2', coordinates='data')
plt.quiverkey(QV3, 1.2, 0.525, 2, 'arrow 3', coordinates='data')

rawDescription: python/matplotlib - How to put the legend of arrow

description: Python/matplotlib - How to put the legend of arrow


code:
class Animal:
    def __init__(self, name):    # Constructor of the class
        self.name = name
    def talk(self):              # Abstract method, defined by convention only
        raise NotImplementedError("Subclass must implement abstract method")

class Cat(Animal):
    def talk(self):
        return 'Meow!'

class Dog(Animal):
    def talk(self):
        return 'Woof! Woof!'

animals = [Cat('Missy'),
           Dog('Lassie')]

for animal in animals:
    print(animal.name + ': ' + animal.talk())

# prints the following:
# Missy: Meow!
# Lassie: Woof! Woof!

rawDescription: python polymorphism concepts example

description: Python polymorphism concepts example


code:
from django.middleware.cache import UpdateCacheMiddleware
from django.utils.cache import learn_cache_key
from django.http import HttpRequest
from network.views import StatusView

request = HttpRequest()
request.META['SERVER_NAME'] = '1.0.0.127.in-addr.arpa' # important
request.META['SERVER_PORT'] = '8000'                   # important
request._cache_update_cache = True
response = StatusView(request=request).get(request)
cacher = UpdateCacheMiddleware()
cacher.process_response(request, response).render()

rawDescription: How can I render and cache a view programatically in Django?

description: Render and cache a view programatically in Django


code:
with open('test.csv', 'w') as a_file:
    for result in C:
        result = ' '.join(result)
        a_file.write(result + '\n')

rawDescription: How do I remove the commas, quotes, and parentheses from an exported python list?

description: Remove the commas, quotes, and parentheses from an exported python list


code:
for (key, value) in self.data:
    setattr(self, key, value)

rawDescription: Way to take a JSON object from a REST call and populate a Class


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

mean1 = 0
variance1 = 1
sigma1 = math.sqrt(variance1)
x = np.linspace(-3,3.5,100, endpoint=True)
y1 = mlab.normpdf(x,mean1,sigma1)
fig, ax = plt.subplots()
ax.plot(x,y1)

mean2 = 0.4
variance2 = 2
sigma2 = math.sqrt(variance2)
y = np.linspace(-4,3.5,100, endpoint=False)
y2 = mlab.normpdf(y,mean2,sigma2)
ax.plot(x,y2)

ax.fill_between(x[:30], y1[:30], color='blue')
ax.fill_between(x[:30], y2[:30], color='green')
ax.fill_between(x[-30:], y1[-30:], y2[-30:], color='red', alpha=0.5)
ax.set_yticks([])
ax.set_xticks([])
plt.savefig('fill_norms.png')
plt.show()

rawDescription: Reproduce two distributions as provided on a single plot using Python


code:
import socket
# ...
host_id = socket.gethostname()
# or alternately
host_id = socket.gethostname().split('.')[0]

rawDescription: Grinder - Accessing the Host ID

description: Grinder - Accessing the Host ID


code:
user_dict['salt'] = uuid.uuid4().hex
print_stderr(user_dict['salt'])
import hashlib
m = hashlib.sha512()
m.update(user_dict['pwd'])
m.update(user_dict['salt'])
user_dict['pwd'] = m.hexdigest()
print_stderr(user_dict['pwd'])

rawDescription: Python on Dotcloud Crashes on certain functions


code:
class C(object):
    _use_obj = 'attr1 attr2'.split()

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

    def __getattribute__(self, name):
        # setup, make it easier to get attributes we need
        get = super(C, self).__getattribute__
        use_obj = get('_use_obj')
        obj = get('obj')

        if name in use_obj:
            # rule 1, attribute is specifically listed
            return getattr(obj, name)
        try:
            # rule 2, try attribute on self
            return get(name)
        except AttributeError:
            # rule 3, fall back to self.obj
            return getattr(obj, name)

rawDescription: Python dispatching attribute access to embeded object


code:
from django.shortcuts import render

def view_1(request):
    return render(request, 'same_template.html', {})
def view_2(request):
    return render(request, 'same_teamplate.html', {})

rawDescription: django portlets

description: Django portlets


code:
from xml.dom import minidom

xmldoc = minidom.parse(path_to_file)
restrictions=[]
topic_nodes = xmldoc.getElementsByTagName('topic')
for topic_node in topic_nodes:
  restrictions_nodes = topic_node.getElementsByTagName('restrictions')
  if not restrictions_nodes:
      restrictions.append(0)
      continue

  result = []
  for restrictions_node in restrictions_nodes:
      restriction_nodes = restrictions_node.getElementsByTagName('restriction')
      for restriction_node in restriction_nodes:
          result.append(restriction_node.attributes['id'].value)

  restrictions.append(result)

print(restrictions)

rawDescription: Iterate through attribute values with minidom


code:
for i, v in kwargs.items():
    print ("    ", i, ": ", v)

rawDescription: Using kwargs in while loops - Python 3

description: Using kwargs in while loops - Python 3


code: queryString = 'SELECT * FROM tableA WHERE sec_code in '+tuple(scoreDF.index)

rawDescription: pandas' read_sql with a list of values for WHERE condition

description: Pandas' read_sql with a list of values for WHERE condition


code:
import os

# this function splits the attribute=value into two lists
# the first list are all the attributes
# the second list are all the values
def getAttributesAndValues(line):
    attributes = []
    values = []

    # first we split the input over the &
    AtributeValues = line.split('&')
    for attrVal in AtributeValues:
        # we split the attribute=value over the '=' sign
        # the left part goes to split[0], the value goes to split[1]
        split = attrVal.split('=')
        attributes.append(split[0])
        values.append(split[1])

    # return the attributes list and values list
    return attributes,values

# test the function using the line beneath so you understand how it works
# line = "Attribute1=Value&Attribute2=Value&Attribute3=Vale&AttibuteN=Value"
# print getAttributesAndValues(line)

# this function writes a single file to an output file
def writeToCsv(inFile='', wfile="outFile.csv", delim=","):
    f_in = open(inFile, 'r')    # only reading the file
    f_out = open(wfile, 'ab+')  # file is opened for reading and appending

    # read the whole file line by line
    lines = f_in.readlines()

    # loop throug evert line in the file and write its values
    for line in lines:
        # let's check if the file is empty and write the headers then
        first_char = f_out.read(1)
        header, values = getAttributesAndValues(line)

        # we write the header only if the file is empty
        if not first_char:
            for attribute in header:
                f_out.write(attribute+delim)
            f_out.write("\n")

        # we write the values
        for value in values:
            f_out.write(value+delim)
        f_out.write("\n")

# Read all the files in the path (without dir pointer)
allInputFiles = os.listdir('input/')
allInputFiles = allInputFiles[1:]

# loop through all the files and write values to the csv file
for singleFile in allInputFiles:
    writeToCsv('input/'+singleFile)

rawDescription: Using Python to Merge Single Line .dat Files into one .csv file


code:
from skimage import img_as_uint
# ...
io.imsave("./testout/" + img_name, img_as_uint(binary))

rawDescription: scikit-image saves binary image as completely black image

description: Scikit-image saves binary image as completely black image


code:
dc = ["hello", "world", "foo"]
lines = ["This is", "an example of hello", "line in the world of strings", "Testing"]
[word for word in dc if any(word in line for line in lines)]

rawDescription: How to find an element in a list which is part of another element in another list in Python

description: Find an element in a list which is part of another element in another list in Python


code:
import matplotlib.pyplot as plt

# ... your other code here

fig, ax = plt.subplots(ncols=1, nrows=1) # These arguments can be omitted for one
                                         # plot, I just include them for clarity
ax.plot(e_vals, 'g^')
ax.set_ylabel('Eigenvalues')

ax.grid(b=True, which='major', color='b', linestyle='-')

plt.show()

rawDescription: Gridlines not showing up

description: Gridlines not showing up


code:
d = datetime.datetime.today().replace(microsecond=0)
d

rawDescription: simple way to drop milliseconds from python datetime.datetime object

description: Simple way to drop milliseconds from python datetime.datetime object


rawDescription: python pandas: reverse df column order

description: Python pandas: reverse df column order


code: np.fmax(a, 1e-15, a)

rawDescription: replacing values in a whole array

description: Replacing values in a whole array


code:
class SoftwareVersionAdmin(ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        # Proper kwargs are form, fields, exclude, formfield_callback
        if obj: # obj is not None, so this is a change page
            kwargs['exclude'] = ['foo', 'bar',]
        else: # obj is None, so this is an add page
            kwargs['fields'] = ['foo',]
        return super(SoftwareVersionAdmin, self).get_form(request, obj, **kwargs)

rawDescription: different fields for add and change pages in admin

description: Different fields for add and change pages in admin


code:
lim_dict = dict()
for ax in fig.axes:
    lim_dict[ax] = (ax.get_xlim(), ax.get_ylim())

def ax_changed(ax):
    old_xlim, old_ylim = lim_dict[ax]
    return np.all(old_xlim == ax.get_xlim()) and np.all(old_ylim == ax.get_ylim())

changed_axes = [ax for ax in figs.axes if ax_changed(ax)]
not_changed_axes = [ax for ax in figs.axes if not ax_changed(ax)]

rawDescription: matplotlib navigation toolbar pan & zoom

description: Matplotlib navigation toolbar pan & zoom


code:
import scipy.sparse as sps
shape = (1000, 2000)
rows, cols = 1000, 2000
sps_acc = sps.coo_matrix((rows, cols)) # empty matrix
for j in xrange(100): # add 100 sets of 100 1's
    r = np.random.randint(rows, size=100)
    c = np.random.randint(cols, size=100)
    d = np.ones((100,))
    sps_acc = sps_acc + sps.coo_matrix((d, (r, c)), shape=(rows, cols))

sps_acc

rawDescription: Building and updating a sparse matrix in python using scipy


rawDescription: How to make a parent thread wait either specified amount of time or until the child thread finishes?

description: Make a parent thread wait either specified amount of time or until the child thread finishes


code:
constructor = config['class'] # or '()' for a custom object being configured
kwargs = dict([(k, config[k]) for k in config if valid_ident(k)])
obj = constructor(**kwargs)

rawDescription: List of dictConfig configuration options for Python logging handlers?


code:
def update_after(m):
    """ calls self.update_everything() after method m """
    def decorated(self, *args, **kwargs):
        r = m(self, *args, **kwargs)
        self.update_everything()
        return r
    return decorated

def MyClass(object):
    def __init__(self):
        pass

    def update_everything(self):
        '''update everything'''
        pass

    @update_after
    def f1(self):
        #do stuff
        return result

    @update_after
    def f2(self):
        #do stuff
        return result

    @update_after
    def f3(self):
        #do stuff
        return result

rawDescription: Specify action to be performed at the end of many functions


code:
import PyPDF2
pdfFileObj = open('my_file.pdf',rb)     #'rb' for read binary mode
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pdfReader.numPages
pageObj = pdfReader.getPage(9)          #'9' is the page number
pageObj.extractText()

rawDescription: Best tool for text extraction from PDF in Python 3.4


rawDescription: Use index in pandas to plot data

description: Use index in pandas to plot data


code:
def checkCache(cachedText):
    cache = open( "cache" )
    for line in cache:
        if cachedText + ":" in line:
            break
    else:
        requestDefinition(cachedText)
    cache.close()

rawDescription: Search a file for a string, and execute a function if string not found; in python


code:
D2R = ctypes.cdll.LoadLibrary("d2r.so")
D2R_GetSingleResult = D2R.D2R_GetSingleResult
D2R_GetSingleResult.argtypes = (ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int, ctypes.POINTER(ctypes.c_float), ctypes.c_int, ctypes.c_void_p, ctypes.c_void_p)
D2R_GetSingleResult.restype = ctypes.c_int
...
fResult = ctypes.c_float()
lRetVal = D2R_GetSingleResult("Folder", "Folder\\Proj1", 2001001, fResult, 1, None, None)

rawDescription: Call a function in a DLL and use an array as argument


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

from PyQt4 import QtCore, QtGui

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

        self.label = QtGui.QLabel(self)
        self.label.setText("Click Me")

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.label)

    def mousePressEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            self.label.setText("Left Mouse Click!")

        elif event.buttons() == QtCore.Qt.RightButton:
            self.label.setText("Right Mouse Click!")

        return super(myWindow, self).mousePressEvent(event)

if __name__ == "__main__":
    import sys

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

    main = myWindow()
    main.resize(150, 150)
    main.show()

    sys.exit(app.exec_())

rawDescription: Can PyQt QWebPage linkClicked signal detect which mouse button was used


code:
q = 'MV0346FDG-PFHTGE-CFSGD-22205-C0'
q[:q.rfind('-')]
'MV0346FDG-PFHTGE-CFSGD-22205'

rawDescription: Python: Parse a line and exclude last token


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

def regularise_array(arr, val=-1):
    """ Takes irregular array and returns regularised masked array

    This first pads the irregular awway *arr* with values *val* to make
    it of rectangular. It then applies a mask so that the padded values
    are not displayed by pcolormesh. For this reason val should not
    be in *arr* as you will loose these points.
    """

    lengths = [len(d) for d in data]
    max_length = max(lengths)
    reg_array = np.zeros(shape=(arr.size, max_length))

    for i in np.arange(arr.size):
        reg_array[i] = np.append(arr[i], np.zeros(max_length-lengths[i])+val)

    reg_array = np.ma.masked_array(reg_array, reg_array == val)

    return reg_array

data = np.array([[1,2,3], [1,2], [1,2,3,4,5,6,7], [1,2,3,4]])

reg_data = regularise_array(data, val=-1)

plt.pcolormesh(reg_data)
plt.jet()
plt.colorbar()
plt.show()

rawDescription: python matplotlib imshow with difference lenghts in data-array

description: Python matplotlib imshow with difference lenghts in data-array


code:
import collections

keyed = collections.defaultdict(list) # (a,b): [1,2,3]

for k1,k2,val in data:
    keyed[(k1,k2)].append(val)

[list(keys) + vals for keys,vals in sorted(keyed.items())]

rawDescription: Python list in list reformatting

description: Python list in list reformatting


code:
data = html.parse('http://httpbin.org/redirect/2')
data.docinfo.URL

rawDescription: How to get current url of a parsed HTML page in Python with lxml?

description: Get current url of a parsed HTML page in Python with lxml


code:
import numpy as np
from scipy.stats import multivariate_normal

x, y = np.mgrid[-1.0:1.0:30j, -1.0:1.0:30j]
# Need an (N, 2) array of (x, y) pairs.
xy = np.column_stack([x.flat, y.flat])

mu = np.array([0.0, 0.0])

sigma = np.array([.025, .025])
covariance = np.diag(sigma**2)

z = multivariate_normal.pdf(xy, mean=mu, cov=covariance)

# Reshape back to a (30, 30) grid.
z = z.reshape(x.shape)

rawDescription: Generating 3D Gaussian distribution in Python


code: end_timestamp = start_timestamp + 5 * 60 * 60

rawDescription: Adding hours to unix time stamp in python


code:
test = ["this", "the"],["example", "test"],["is not", "isnt"],[" working", "correct"]
# The * before test unpacks the tuple into separate arguments
result2 = list(itertools.product(*test))
print(result2)
[('this', 'example', 'is not', ' working'), ('this', 'example', 'is not', 'correct'), ('this', 'example', 'isnt', ' working'), ('this', 'example', 'isnt', 'correct'), ('this', 'test', 'is not', ' working'), ('this', 'test', 'is not', 'correct'), ('this', 'test', 'isnt', ' working'), ('this', 'test', 'isnt', 'correct'), ('the', 'example', 'is not', ' working'), ('the', 'example', 'is not', 'correct'), ('the', 'example', 'isnt', ' working'), ('the', 'example', 'isnt', 'correct'), ('the', 'test', 'is not', ' working'), ('the', 'test', 'is not', 'correct'), ('the', 'test', 'isnt', ' working'), ('the', 'test', 'isnt', 'correct')]

rawDescription: Product of tuple

description: Product of tuple


rawDescription: Array with names possible?

description: Array with names possible


code: c, *d = b

rawDescription: parse a list into variable and sublist - pythonic way

description: Parse a list into variable and sublist - pythonic way


code:
#!/usr/bin/env python3.3

amt = int(input("What is your starting balance: $"))
while(True):
    i = int(input("What is your withdrawal amount: $"))
    if(i == 0):
        break
    else:
        amt -= i

print("Your account balance is:"+str(amt))

rawDescription: Loop until specific input

description: Loop until specific input


code:
seq = fib() | take_while(lambda x: x < 1000000) \
            | where(lambda x: x % 2) \
            | select(lambda x: x * x) \
            | sum()

rawDescription: method chaining in python

description: Method chaining in python


code:
data = []
for f in frames:
    # do your calculation
    # line = [1, 2, 3, 4]
    data += line
data = np.array(data).reshape((-1,4))

rawDescription: Stack arrays in sequence

description: Stack arrays in sequence


code:
from sympy import lambdify
g_func = lambdify( (x), g )

rawDescription: What is the best way to convert a SymPy matrix to a numpy array/matrix


code:
a = open("foo","rb")
data = a.read()
a.close()

x = np.fromstring(data[4:-4], dtype='float64')

rawDescription: Want to check this script I wrote to read a Fortran binary file


code:
from bs4 import BeautifulSoup
import itertools
soup = BeautifulSoup(html_doc)

# wrap all h1 and next siblings into sections
h1s = soup.find_all('h1')
for el in h1s:
    els = [i for i in itertools.takewhile(
              lambda x: x.name not in [el.name, 'script'],
              el.next_siblings)]
    section = soup.new_tag('section')
    el.wrap(section)
    for tag in els:
        section.append(tag)

print(soup.prettify())

rawDescription: Wrap multiple tags with BeautifulSoup

description: Wrap multiple tags with BeautifulSoup


code:
for res in re.finditer('(?P<str>asd)(?P<dig>\d*)', text):
   print (res.group('dig'),res.group('str'))

[(res.group('dig'),res.group('str')) for res in re.finditer('(?P<str>asd)(?P<dig>\d*)', text)]

rawDescription: Change order of elements found by re.findall


rawDescription: Iterating using two variables

description: Iterating using two variables


code:
import kivy
kivy.require('1.8.0')

from kivy.app import App
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.button import Button
from kivy.uix.button import Label
from kivy.uix.button import ButtonBehavior
from kivy.lang import Builder
from kivy.graphics import Triangle
from kivy.graphics import Color

Builder.load_string("""

<TwoColorsButton>:
    size_hint: None,None
    size: 250,250
    font_size: '26dp'
    canvas.before:
        Color:
            rgba:0.5,0,0,1
        Triangle:
            points: [0,0, 0,root.size[1], root.size[0],0]
        Color:
            rgba:0,0,0.5,1
        Triangle:
            points: [0,root.size[1],root.size[0],root.size[1],root.size[0],0]
    text:'click me'
    on_press:print "I've been pressed"
""")

class TwoColorsButton(ButtonBehavior,Label):
    pass

class TwoColorsApp(App):
    def build(self):
        my_button = TwoColorsButton()
        return my_button

if __name__ == '__main__':
    TwoColorsApp().run()

rawDescription: How do I make a two tone "Button" in Kivy?

description: Make a two tone "Button" in Kivy


code:
import json

jsons = []
jsons.append("""{
"meta":  {
"code": 200
},
"data":  [
 {
  "username": "rawhawk_sk",
  "profile_picture": "https://scontent.cdninstagram.com/t51.2885-19/s150x150/12724928_109384759877664_1105313598_a.jpg",
  "id": "670907103",
  "full_name": "shwan mcswan"
}
]
}
""")

jsons.append("""{
"meta":  {
"code": 200
},
"data":  []
} """)

output_list = []

for txt in jsons:
    beta = json.loads(txt)
    if beta.get('data'):
        for item in beta['data']:
            output_list.append(item['id'])
    else:
        output_list.append('ACC deleted')

print(output_list)

rawDescription: Checking whether a JSON dictionary is empty or not and storing in a list


code:
x = [p[0] for p in points]
y = [p[1] for p in points]
centroid = (sum(x) / len(points), sum(y) / len(points))

rawDescription: How to get center of set of points using Python

description: Get center of set of points using Python


code:
import subprocess

def pdftotext(pdf, page=None):
    """Retrieve all text from a PDF file.

    Arguments:
        pdf Path of the file to read.
        page: Number of the page to read. If None, read all the pages.

    Returns:
        A list of lines of text.
    """
    if page is None:
        args = ['pdftotext', '-layout', '-q', pdf, '-']
    else:
        args = ['pdftotext', '-f', str(page), '-l', str(page), '-layout',
                '-q', pdf, '-']
    try:
        txt = subprocess.check_output(args, universal_newlines=True)
        lines = txt.splitlines()
    except subprocess.CalledProcessError:
        lines = []
    return lines

rawDescription: How to extract text from pdf line by line in python 2.7

description: Extract text from pdf line by line in python 2.7


code:
# Save a dictionary into a pickle file.
import pickle
favorite_color = { "lion": "yellow", "kitty": "red" }
pickle.dump( favorite_color, open( "save.p", "wb" ) )

# Load the dictionary back from the pickle file.
import pickle

favorite_color = pickle.load( open( "save.p", "rb" ) )
# favorite_color is now { "lion": "yellow", "kitty": "red" }`

rawDescription: Python: Storing List Objects Externally

description: Python: Storing List Objects Externally


code:
import re
rexp = r'(?:\b)([A-Z]{3})(?:$|[^A-Z])'
re.search(rexp, 'USA').groups()
re.search(rexp, 'NSFW') is None
re.search(rexp, 'aUSA') is None
re.search(rexp, 'NSF,').groups()

rawDescription: Python Three Letter Acronyms

description: Python Three Letter Acronyms


code:
from Tkinter import *

class ScrollableCanvas(Canvas):
    def __init__(self, master, *args, **options):
        self.frame = Frame(master)
        Canvas.__init__(self, self.frame, *args, **options)
        self.xscrollbar = Scrollbar(self.frame, command=self.xview, orient=HORIZONTAL)
        self.yscrollbar = Scrollbar(self.frame, command=self.yview)
        self.config(xscrollcommand=self.xscrollbar.set, yscrollcommand=self.yscrollbar.set)
    def create_line(self, *args, **options):
        Canvas.create_line(self, args, **options)
        self._resize(*args)
    def _resize(self, *args):
        maxwidth = max(args[0], args[2], int(self['width']))
        maxheight = max(args[1], args[3], int(self['height']))
        self.config(scrollregion=(0, 0, maxwidth, maxheight))
    def grid(self, *args, **options):
        self.frame.grid(*args, **options)
        Canvas.grid(self, row=0, column=0)
        self.xscrollbar.grid(row=1, column=0, sticky=E+W)
        self.yscrollbar.grid(row=0, column=1, sticky=N+S)

rawDescription: How to expand a Canvas when I place an object on it?

description: Expand a Canvas when I place an object on it


code:
from distutils.command.build import build
from distutils.core import setup

class MyBuild(build):
    def run(self):
        build_path = self.build_lib
        # Populate files to 'build_path'

setup(
    # ...
    cmdclass=dict(build=MyBuild)
)

rawDescription: Distutils ignores build/lib on Ubuntu

description: Distutils ignores build/lib on Ubuntu


code:
import random
import multiprocessing
import functools

class my_decorator(object):
    def __init__(self, target):
        self.target = target
        try:
            functools.update_wrapper(self, target)
        except:
            pass

    def __call__(self, candidates, args):
        f = []
        for candidate in candidates:
            f.append(self.target([candidate], args)[0])
        return f

def old_my_func(candidates, args):
    f = []
    for c in candidates:
        f.append(sum(c))
    return f

my_func = my_decorator(old_my_func)

if __name__ == '__main__':
    candidates = [[random.randint(0, 9) for _ in range(5)] for _ in range(10)]
    pool = multiprocessing.Pool(processes=4)
    results = [pool.apply_async(my_func, ([c], {})) for c in candidates]
    pool.close()
    f = [r.get()[0] for r in results]
    print(f)

rawDescription: Python decorator with multiprocessing fails


code:
import base64

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

# Creating the csv formatted string
csv_line_length = len(max(mylist,key=len))
csv_string = ''
for row in mylist:
    temp_row = ['"' + col + '"' for col in row]
    while len(temp_row) < csv_line_length:
      temp_row.append([])
    csv_string += ','.join(temp_row) + '\n'
# Encoding the string to base64
encoded = base64.b64encode(csv_string.encode('utf-8'))

rawDescription: Python - generate csv file in memory and then encode its data into base64?


code:
def is_interface_up(interface):
    addr = netifaces.ifaddresses(interface)
    return netifaces.AF_INET in addr

rawDescription: Python: check whether a network interface is up


code:
def __repr__(self):
    assert self._initialized, "Thread.__init__() was not called"
    status = "initial"
    if self._started.is_set():
        status = "started"
    self.is_alive() # easy way to get ._is_stopped set when appropriate
    if self._is_stopped:
        status = "stopped"
    if self._daemonic:
        status += " daemon"
    if self._ident is not None:
        status += " %s" % self._ident
    return "<%s(%s, %s)>" % (self.__class__.__name__, self._name, status)

rawDescription: Python which thread starts first?

description: Python which thread starts first


code:
def SendData(self):

    TargetSystems = self.targetSystem.text().split(',')
    Msg2Send = self.lineedit.text()

    for TargetSystem in TargetSystems:

        self.Clientsocket.connectToHost(TargetSystem, PORT)
        self.Clientsocket.waitForConnected(-1)  # This is required data to be writing
        self.request = QtCore.QByteArray()
        stream = QtCore.QDataStream(self.request, QtCore.QIODevice.WriteOnly)
        stream.setVersion(QtCore.QDataStream.Qt_4_2)
        stream.writeUInt32(0)
        stream.writeQString(Msg2Send)
        stream.device().seek(0)
        stream.writeUInt32(self.request.size() - SIZEOF_UINT32)
        self.Clientsocket.write(self.request)
        self.nextBlockSize = 0
        self.request = None
        self.Clientsocket.disconnectFromHost() # .close() is not closing the socket connection, so i changed it this

rawDescription: TCP Messaging with QtNetwork in python using PyQt


code:
f = open('/path/to/your/test.pdf')
ms = gdata.data.MediaSource(file_handle=f, content_type='application/pdf', content_length=os.path.getsize(f.name))
folder = "https://docs.google.com/feeds/default/private/full" # folder in google docs.
entry = client.Upload(ms, f.name, folder_or_uri= folder + '?ocr=true') # ?ocr=true is the kicker

rawDescription: Python: what's the gdata method for uploading an image with enabled OCR?


code: sorted(str,key=lambda x: int(x[0]))

rawDescription: writing the key function inside the sorted function

description: Writing the key function inside the sorted function


code:
import cv2
import numpy as np

# Load two images of same size
img1 = cv2.imread('img1.jpg')
img2 = cv2.imread('img2.jpg')

both = np.hstack((img1,img2))

rawDescription: How do I concatenate two matrices in Python OpenCV?

description: Concatenate two matrices in Python OpenCV


code:
with open(wave_cat,'r') as catID:
    ct = 0
    for i, cat_line in enumerate(catID):
        if not len(cat_line.strip()) == 0:
            line    = cat_line.split()
            #replen = re.sub('length:','length0:','length:')
            if line[0] == '#' and line[1] == 'event':
                num = long(line[2])
            elif line[0] == 'length:':
                ct += 1
                if ct == 2:
                    Length = float(line[2])
                    ct = 0

rawDescription: How to recover only the second instance of a string in a text file?

description: Recover only the second instance of a string in a text file


code:
import random, time

def permuted(items, pieces = 2):
    sublists = [[] for i in range(pieces)]
    for x in items:
        sublists[random.randint(0,pieces-1)].append(x)
    permutedList = []
    for i in range(pieces):
        time.sleep(0.01)
        random.seed()
        random.shuffle(sublists[i])
        permutedList.extend(sublists[i])
    return permutedList

rawDescription: How to randomly shuffle a list that has more permutations than the PRNG's period?

description: Randomly shuffle a list that has more permutations than the PRNG's period


code:
import pandas as pd
import matplotlib.pyplot as plt
index={'A','B','C','D','E'}
d={'typ':[1,2,2,2,1],'value':[10,25,15,17,13]}
df=pd.DataFrame(d,index=index)

# define the colors for each type
colors = {1:'blue', 2:'red'}

# plot the bars
plt.bar(range(len(df)), df['value'], align='center',
        color=[colors[t] for t in df['typ']])

rawDescription: bar plot with different colors in python

description: Bar plot with different colors in python


rawDescription: Having trouble with pygame.translation.rotation


rawDescription: Fill in a numpy array without creating list


code:
import ast
from pyspark.mllib.linalg import SparseVector

def parse_sparse(s):
    return SparseVector(*ast.literal_eval(s.strip()))

parse_sparse("(1, [], [])")
## SparseVector(1, {})

parse_sparse("(5, [1, 3], [0.4, -0.1])")
## SparseVector(5, {1: 0.4, 3: -0.1})

rawDescription: Parsing all zero sparse vectors with pyspark SparseVectors


code:
def index(filename, word_lst):

    dic = {}
    line_count = 0

    for word in word_lst:
        dic[word] = []   # <---

    with open(filename) as infile:
        for line in infile:
            line_count += 1
            for word in word_lst:
                if word in line:
                    dic[word].append(line_count)  # <----

    print(dic)

rawDescription: Creating a Dictionary with Line Numbers of Keywords


code:
import pipes
from pexpect import run # $ pip install pexpect

args = ["./solve.m", Mrefnorm, Mvert, Mcomp, Mangle]
command = " ".join(map(pipes.quote, args))
output, status = run(command, withexitstatus=True)

rawDescription: Redirecting Output from Mathematica Script to PIPE Instead of stdout Using subprocess.Popen Yields Null String


code:
from configobj import ConfigObj
config = ConfigObj(filename)

value = config['entry']
config['entry'] = newvalue
config.write()

rawDescription: How to save a configuration file / python file IO

description: Save a configuration file / python file IO


rawDescription: Python_How to parse data and make it into new file


code:
def tail(f, n, offset=None):
    """Reads a n lines from f with an offset of offset lines.  The return
    value is a tuple in the form ``(lines, has_more)`` where `has_more` is
    an indicator that is `True` if there are more lines in the file.
    """
    avg_line_length = 74
    to_read = n + (offset or 0)

    while 1:
        try:
            f.seek(-(avg_line_length * to_read), 2)
        except IOError:
            # woops.  apparently file is smaller than what we want
            # to step back, go to the beginning instead
            f.seek(0)
        pos = f.tell()
        lines = f.read().splitlines()
        if len(lines) >= to_read or pos == 0:
            return lines[-to_read:offset and -offset or None], \
                   len(lines) > to_read or pos > 0
        avg_line_length *= 1.3

rawDescription: Get last n lines of a file with Python, similar to tail


rawDescription: calculate total of string column

description: Calculate total of string column


code:
def update_tags_with_value(tags, many_to_many_class, champ):
    if tags:
        many_to_many_class.objects.filter(
            personne=self.instance,
            date_v_fin=None
        ).update(date_v_fin=django_datetime.now())
        for idx_tag_with_value in tags:
            args = {
                'personne': self.instance,
                champ: TagWithValue.objects.get(
                    pk=idx_tag_with_value
                )}
            pl = many_to_many_class.objects.create(**args)
            pl.save()

update_tags_with_value(self.cleaned_data.get('known_languages'),
                       PersonneLangue, 'langue')
update_tags_with_value(self.cleaned_data.get('types_permis'),
                       PersonneTypePermis, 'type_permis')
update_tags_with_value(self.cleaned_data.get('diplomes'),
                       PersonneDiplome, 'diplome')
update_tags_with_value(self.cleaned_data.get('centres_dinteret'),
                       PersonneCentreDInteret, 'centre_dinteret')
update_tags_with_value(self.cleaned_data.get('hobbies'),
                       PersonneHobby, 'hobby')

rawDescription: Is there a way to pass a named argument?

description: Is there a way to pass a named argument


rawDescription: Attach last column of DataFrame to another DataFrame


code:
import clr
clr.AddReference("Microsoft.Office.Interop.Excel")
import Microsoft.Office.Interop.Excel as Excel
excel = Excel.ApplicationClass()

wb = excel.Workbooks.Open('testFile.xlsx')
ws = wb.Worksheets['Sheet1']

address = ws.Cells(row, col).Hyperlinks.Item(1).Address

rawDescription: Extracting Hyperlinks From Excel (.xlsx) with Python


code:
def file_head_display(limit = 5):
    file = str(input('Enter the name of the file: '))
    f_open = open (file, 'r')

    line_counter = 0
    for line in f_open:                  # for each line in the text file
        if line_counter < limit:         # if current line is < 5
            print(line, end="")          # then print the line
            line_counter += 1
        else:                            # else, stop looping
            break

file_head_display()

rawDescription: Program prints individual lines and not whole file


rawDescription: cant remove .text. using a regular expression

description: Cant remove .text. using a regular expression


rawDescription: python - list operations

description: Python - list operations


code:
class Foo(object):
  bar = []          # defines a class variable on Foo (shared by all instances)
a = Foo()
b = Foo()
a.bar.append(1)     # appends the value 1 to the previously empty list Foo.bar
b.bar               # returns the value of the class variable Foo.bar
a.bar = 1           # binds 1 to the instance variable a.bar, masking the access
a.bar               # you previously had to the class variable through a.bar
b.bar               # b doesn't have an instance variable 'bar' so this still
a.bar = []          # bind a's instance variable to to an empty list
a.bar
b.bar               # b doesn't have an instance variable 'bar' so this still
del a.bar           # unbinds a's instance variable unmasking the class variable
a.bar               # so a.bar now returns the list with 1 in it.

rawDescription: Python and object/class attrs - what's going on?


rawDescription: Adding custom Field to django queryset containing source record


code:
import tensorflow as tf
from toposort import toposort
sess=tf.InteractiveSession()
matrix1=tf.constant([[3.,3.]])
matrix2=tf.constant([[2.],[2.]])
sum=tf.add(matrix1,matrix2)
product=tf.matmul(matrix1,matrix2)
final=tf.mul(sum,product)
g=sess.graph
deps={}
for op in g.get_operations():
    # op node
    op_inputs=set()
    op_inputs.update([t.name for t in op.inputs])
    deps[op.name]=op_inputs
    # tensor output node
    for t in op.outputs:
        deps[t.name]={op.name}
deps
{u'Add': {u'Const:0', u'Const_1:0'},
 u'Add:0': {u'Add'},
 u'Const': set(),
 u'Const:0': {u'Const'},
 u'Const_1': set(),
 u'Const_1:0': {u'Const_1'},
 u'MatMul': {u'Const:0', u'Const_1:0'},
 u'MatMul:0': {u'MatMul'},
 u'Mul': {u'Add:0', u'MatMul:0'},
 u'Mul:0': {u'Mul'}}
list(toposort(deps))
[{u'Const', u'Const_1'},
 {u'Const:0', u'Const_1:0'},
 {u'Add', u'MatMul'},
 {u'Add:0', u'MatMul:0'},
 {u'Mul'},
 {u'Mul:0'}]

rawDescription: TensorFlow - get execution ordering of fetches


code:
import re

def slugify(s):
    return re.sub(r'\W+', '-', s.lower().replace('_', '-'))

def get_slug_to_class_items(policy_class):
    yield (slugify(policy_class.__name__), policy_class)
    for subclass in policy_class.__subclasses__():
        for slug, subclass in get_slug_to_class_items(subclass):
            yield (slug, subclass)

slug_to_class = dict(get_slug_to_class_items(Policy_Base))
# print repr(slug_to_class)

rawDescription: Python: inspecting module to pick out classes of certain type?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(unicodestring_containing_the_entire_htlm_doc)
table = soup.find('table', {'class': 'details'})
th = table.find('th', text='Issued on:')
th
td = th.findNext('td')
td
td.text

rawDescription: Extracting table contents from html with python and BeautifulSoup


code:
import traceback
def _is_setup():
    for tb in reversed(traceback.extract_stack()):
        if (tb[2] == "_run_setup"):
            return True
    return False

def _is_teardown():
    for tb in reversed(traceback.extract_stack()):
        if (tb[2] == "_run_teardown"):
            return True
    return False

rawDescription: Robot Framework : How to know whether a test library function is being executed from setup/test/teardown


code:
def freqs(attDice, defDice, rolls):
    m = min(attDice, defDice)
    freq = [0]*(m+1)
    for i in range(rolls):
        ar = random.randrange(6**attDice)
        dr = random.randrange(6**defDice)
        ad = [(ar / 6**j) % 6 for j in range(attDice)]
        ad.sort(reverse=True)
        dd = [(dr / 6**j) % 6 for j in range(defDice)]
        dd.sort(reverse=True)
        aws = sum(j > k for j, k in zip(ad, dd))
        freq[aws] += 1
    return freq

rawDescription: Speed up Risk wargame dice rolling simulation


code:
s = 'This is the                                     Sample text I need to get       all this               but only with single spaces'
' '.join(s.split())
#'This is the Sample text I need to get all this but only with single spaces'

rawDescription: How to remove all the white space from string in Python

description: Remove all the white space from string in Python


code:
class BlogPostResource(ModelResource):

    comments = fields.ToManyField("resources.CommentResource",
        attribute=lambda bundle: bundle.obj.comments.all().order_by("published"))

rawDescription: Is it possible to sort elements in a ToManyField attribute using TastyPie?


code:
sel = Selector(response)
data = sel.xpath('//div[@class="class"]').extract()
if not data:
    # increment failure stats here
    return
# else fill the item

rawDescription: How to count empty responses in Scrapy ?

description: Count empty responses in Scrapy


code:
def records(textfile):
    record_lines = []
    for line in textfile:
        if line != '\n':
            record_lines.append(line)
        else:
            yield ''.join(record_lines)
            record_lines = []
    yield ''.join(record_lines)

for record in records(the_file):
    process(record)

rawDescription: python record separtor file iteration

description: Python record separtor file iteration


code: button.props.image = gtk.image_new_from_icon_name('emblem-favorite', gtk.ICON_SIZE_BUTTON)

rawDescription: How to set icon from theme in PyGTK

description: Set icon from theme in PyGTK


code: date_hierarchy = 'created'

rawDescription: Django 1.5+ Admin Date Range Filter

description: Django 1.5+ Admin Date Range Filter


code: prices = map(float, prices)

rawDescription: How to make every object in a list a float

description: Make every object in a list a float


code:
class Foo(object):
    pass

class Bar(object):
    pass

Foo.other = Bar
Bar.other = Foo

rawDescription: Python circular references

description: Python circular references


code:
result = sorted((trans for trans in my_list if trans.type in types),
                key=lambda x: x.code)

rawDescription: Sorting A List Comprehension In One Statement


code:
r = list()
S = "free tree"
S = "".join(S.split())
s = list()
for i in range(0,len(S)) :
    s.append(S[i])
while len(s) > 0 :
    c1 = s.pop(0)
    c2 = 'X'
    if len(s) > 0 :
        if s[0]!=c1 :
            c2 = s.pop(0)
    else :
        c2 = ''
    r.append("{0}{1}".format(c1,c2))
result = " ".join(r)
print(result)

rawDescription: Getting rid of duplicate blocks in a string


code:
for crew in root.xpath('.//crew[descendant::role[contains(text(), "Primary")]]'):
    crew.getparent().remove(crew)

rawDescription: remove tag and contents based on child tag value - python lxml

description: Remove tag and contents based on child tag value - python lxml


rawDescription: Counting consecutive events on pandas dataframe by their index


code:
#!/usr/bin/env python

import json
import os

FILE = "defs.json"

# load file (if exists...)
if not os.path.exists(FILE):
    defs = {}
else:
    with open(FILE) as defs_file:
        try:
            defs = json.load(defs_file)
        except ValueError:
            # invalid file - replace it with valid empty file
            defs = {}

# do stuff...
defs['new definition'] = 'new value'

# save dict to the file
with open(FILE, 'w') as defs_file:
    json.dump(defs, defs_file)

rawDescription: How to Type a Word Into an Input, and Then Have Python Search for a Variable Named That in a Module?


code:
x = Symbol('x', real=True)
(log(exp(exp(x)))).simplify()

rawDescription: Simplify nested exponentials and logs with sympy


code:
import sys
sys.stdin.encoding
varString = 'Ramón'
varUnicode = u'Ramón'
newUnicode = unicode(varString, encoding='UTF-8') # or encoding=sys.stdin.encoding
varString; varUnicode; newUnicode
varUnicode == newUnicode

rawDescription: Python 2.7: 'Ramón' == u'Ramón'

description: Python 2.7: 'Ramón' == u'Ramón'


code:
class Trellis:
    trell = []
    def __init__(self, hmm, words):
        self.trell = []
        temp = {}
        for label in hmm.labels:
           temp[label] = [0,None]
        for word in words:
            self.trell.append([word,copy.deepcopy(temp)])
        self.fill_in(hmm)

    def fill_in(self,hmm):
        for i in range(len(self.trell)):
            for token in self.trell[i][1]:
                word = self.trell[i][0]
                if i == 0:
                    self.trell[i][1][token][0] = hmm.e(token,word)
                else:
                    max = None
                    guess = None
                    c = None
                    for k in self.trell[i-1][1]:
                        c = self.trell[i-1][1][k][0] + hmm.t(k,token)
                        if max == None or c > max:
                            max = c
                            guess = k
                    max += hmm.e(token,word)
                    self.trell[i][1][token][0] = max
                    self.trell[i][1][token][1] = guess

    def return_max(self):
        tokens = []
        token = None
        for i in range(len(self.trell)-1,-1,-1):
            if token == None:
                max = None
                guess = None
                for k in self.trell[i][1]:
                    if max == None or self.trell[i][1][k][0] > max:
                        max = self.trell[i][1][k][0]
                        token = self.trell[i][1][k][1]
                        guess = k
                tokens.append(guess)
            else:
                tokens.append(token)
                token = self.trell[i][1][token][1]
        tokens.reverse()
        return tokens

rawDescription: Python Implementation of Viterbi Algorithm


code:
from gi.repository import Gtk, Notify

def callback(notification, action_name):
    notification.close()
    Gtk.main_quit()

Notify.init('test')
notification = Notify.Notification.new('Title', '<body>')
notification.set_timeout(Notify.EXPIRES_NEVER)
notification.add_action('quit', 'Quit', callback)
notification.show()

rawDescription: Gtk notifications don't display body holding '<'


code:
import csv

my_dict1 = {"test": 1, "testing": 2}
my_dict2 = {"test": 3, "testing": 4}

my_dicts = my_dict1,my_dict2

with open('mycsvfile.csv', 'wb') as f:  # Just use 'w' mode in 3.x
    w = csv.DictWriter(f, my_dict1.keys())
    w.writeheader()
    w.writerows(my_dicts)

rawDescription: How to write two python dictionaries to a single csv?

description: Write two python dictionaries to a single csv


code:
#----lol.py----
import os,sys

f = open("foo.txt","w")
f.write("HI")
f.close() # HERE !
os.execl(sys.executable, sys.executable, "delfoo.py")

rawDescription: python: can't delete open file from os.execl'd python script on windows

description: Python: can't delete open file from os.execl'd python script on windows


code:
import tkinter as tk

# === constants ===

BLOCK_SIZE = 10
TIME = 50

# === functions ===

# create all rectangles on canvas
def create_snake(canvas, snake):
    snake_rect = []

    for x, y in snake:
        x1 = x * BLOCK_SIZE
        y1 = y * BLOCK_SIZE
        x2 = x1 + BLOCK_SIZE
        y2 = y1 + BLOCK_SIZE
        rect = canvas.create_rectangle(x1,y1,x2,y2, fill='red')
        snake_rect.append(rect)

    return snake_rect

# move snake - add first rectangle and remove last one
def move(canvas, snake, snake_rect, remove_last=True):

    # get head
    x, y = snake[0]

    # new head position
    if direction == 'up':
        y = y-1
    elif direction == 'down':
        y = y+1
    elif direction == 'left':
        x = x-1
    elif direction == 'right':
        x = x+1

    # add first - new head
    snake.insert(0, [x, y])

    x1 = x * BLOCK_SIZE
    y1 = y * BLOCK_SIZE
    x2 = x1 + BLOCK_SIZE
    y2 = y1 + BLOCK_SIZE
    rect = canvas.create_rectangle(x1,y1,x2,y2, fill='red')

    snake_rect.insert(0, rect)

    # remove last - tail (if snake doesn't eat 'apple')
    if remove_last:
        del snake[-1]

        canvas.delete(snake_rect[-1])
        del snake_rect[-1]

    # call `move` function again after TIME miliseconds
    root.after(TIME, move, canvas, snake, snake_rect)

# change direction
def change_direction(new_direction):
    global direction

    #print(new_direction)

    if new_direction == 'left':
        if direction != 'right':
            direction = new_direction
    elif new_direction == 'right':
        if direction != 'left':
            direction = new_direction
    elif new_direction == 'up':
        if direction != 'down':
            direction = new_direction
    elif new_direction == 'down':
        if direction != 'up':
            direction = new_direction

# === main ===

direction = 'up'

# ---

root = tk.Tk()

canvas = tk.Canvas(root)
canvas.pack()

# create long (curved) snake
snake = [[x,25] for x in range(10,35)] + [[35, y] for y in range(25, 1, -1)] + [[x, 1] for x in range(35, 1, -1)]
snake_rect = create_snake(canvas, snake)

# call `move` function after TIME miliseconds
root.after(TIME, move, canvas, snake, snake_rect)

# bind arrows to change snake direction
root.bind('<Left>', lambda event:change_direction('left'))
root.bind('<Right>', lambda event:change_direction('right'))
root.bind('<Up>', lambda event:change_direction('up'))
root.bind('<Down>', lambda event:change_direction('down'))

# start program
root.mainloop()

rawDescription: Python tkinter snake game drawing lag

description: Python tkinter snake game drawing lag


code:
for i in range(1, 30):
    t = timeit.Timer('Fib({:d})'.format(i), 'from problem1 import Fib').timeit()
    print('The time for {i:d} is {t:0.2f}'.format(i=i, t=t))

rawDescription: Running timeit in a for loop with index as input number


code:
import Tkinter as TK
import datetime

class countdown:
    def __init__(self, master, time):   # time in mm/dd/yy hh:mm:ss format
        self.master = master
        self.frame = TK.Frame(self.master)
        self.targetTime = datetime.datetime.strptime(time, "%m/%d/%y %H:%M:%S")
        self.timeRemainingLabel = TK.Label(self.frame)
        self.startButton = TK.Button(self.frame, text="Start countdown", command=lambda:self.master.after(1000, self.update))
        self.endTimeLabel = TK.Label(self.frame, text="Target time in mm/dd/yy hh:mm:ss format:")
        self.endTimeEntry = TK.Entry(self.frame)
        self.endTimeEntry.insert(0, time)
        self.frame.grid()
        self.timeRemainingLabel.grid(row=1,column=1, columnspan=3)
        self.startButton.grid(row=2, column=1, rowspan=2)
        self.endTimeLabel.grid(row=2, column=2)
        self.endTimeEntry.grid(row=3, column=2)

    def update(self):
        remaining = self.targetTime-datetime.datetime.now()
        daysRemaining = remaining.days
        hoursRemaining = int(remaining.seconds) / 3600
        minutesRemaining = int(remaining.seconds % 3600) / 60
        secondsRemaining = int(remaining.seconds % 60)
        self.timeRemainingLabel.config(text="Time remaining until {targetTime}:\n*** {days} days {hours} hrs {minutes} min {seconds} sec ***".format(targetTime=datetime.datetime.strptime(self.endTimeEntry.get(), "%m/%d/%y %H:%M:%S"), days=daysRemaining, hours=hoursRemaining, minutes=minutesRemaining, seconds=secondsRemaining))
        self.master.after(1000, self.update)

root = TK.Tk()
c = countdown(root, "08/31/13 01:01:01")
root.mainloop()

rawDescription: Tkinter python countdown from current date to a fixed date


code:
import argparse
# pylint: disable=C0103
PI = 3.14 # <--- should give no C0103
# pylint: enable=C0103
e = 2.71 # <-- should throw C0103

# pylint: disable=C0103
if __name__ == '__main__':
    parser = argparse.ArgumentParser() # <-- should give NO C0103
    PARSER = argparse.ArgumentParser()
# pylint: enable=C0103

rawDescription: How to partially disable/ignore pylint rules?

description: Partially disable/ignore pylint rules


code: [random.random() for _ in range(100)]

rawDescription: how can i create a random array of floats from 0 to 1

description: Create a random array of floats from 0 to 1


code:
def displayTrack(position):

    output='|'#value given to output
    track=[' ']*20# track is initially just a bunch of empty spaces
    track[position]= 'r'#AND track also contains an r icon
    print(' -'*20)#these are the top and bottom borders
    print(' 0 1 2 3 4 5 6 7 8 9 A B C D E F G H I J')#these represent each individual cell

    for i in range(len(track)):
        output= output +track[i] +'|'#append a "|" before and after each empty space " "
    print (output)#print the result
    print(' -'*20)

rawDescription: Python image creation loops

description: Python image creation loops


code: {{ request.user.date_joined|date:"Y-m-d H:i:s" }}

rawDescription: Change Date Format in Django

description: Change Date Format in Django


code:
class TreeView(QtGui.QTreeView):
    def __init__(self, parent=None):
        super(TreeView, self).__init__(parent)
        self.clicked.connect(self.getCurrentIndex)
        # self.connect(self, SIGNAL("clicked(QModelIndex)"), self.getCurrentIndex)

    def getCurrentIndex(self, index):
        print(index.data())
        # Use 'InternalId' obtain the corresponding text, not int and hoping to simple.

rawDescription: How to use InternalId to get text in the QTreeView on PyQt4

description: Use InternalId to get text in the QTreeView on PyQt4


code:
from pages.view_consignments import ViewConsignmentsPage

class AddConsignmentPage(BasePage):

    def __init__(self, driver):
        super(AddConsignmentPage, self).__init__(driver, self._title)
        self._title_uuid = get_random_uuid(7)
        ViewConsignmentsPage._title_uuid = self._title_uuid

rawDescription: Generate random value once for every issue Python


code:
import requests

s = requests.Session()
s.auth = (username, password)
s.verify = ssl_ca_file

s.get(base_url)

rawDescription: Python "requests" library: HTTP basic authentication for each request


code:
import os
os.system("mp3splt inputfile.mp3")

rawDescription: MP3 audio file splitting with Python

description: MP3 audio file splitting with Python


code: [ "%s %s" % x for x in l ]

rawDescription: Python - converting a list of tuples to a list of strings


code:
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# Plt with customized font settings
def make_plot(ax, x, y):
    # Set the font dictionaries (for plot title and axis titles)
    title_font = {'fontname':'Arial', 'size':'16', 'color':'blue', 'weight':'normal'}   # This can be a long dictionary

    # Set the font properties for other places
    font_path = 'C:\Windows\Fonts\comic.ttf'
    font = fm.FontProperties(fname=font_path, size=14)
    axis_font = fm.FontProperties(fname=font_path, size=13)

    # Set the tick labels font
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        # label.set_fontname('Arial')
        # label.set_fontsize(13)
        label.set_font_properties(font)

    ax.plot(x, y, 'r-', label=u'Thin Red Line')
    ax.set_xlabel(u"X axis", fontproperties=axis_font)
    ax.set_ylabel(u"Y axis", fontproperties=axis_font)
    ax.set_title(u"This is the Title", **title_font)
    ax.legend(loc='lower right', prop=font, numpoints=1)
    ax.text(0.1, 5, u"Some text", fontproperties=font)

# A regular plot with global fong settings:
def regular_plot(ax, x, y):
    ax.plot(x,y, 'b-', label=u'Blue Line')
    ax.set_xlabel(u"X axis")
    ax.set_ylabel(u"Y axis")
    ax.set_title(u"This is the Title", axes=ax1)
    ax.legend(loc='lower right', numpoints=1)

fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(9,3))
x = y = range(0, 10) # Some data

# 1st make a regular plot:
regular_plot(ax1, x, y)
# then make customized plot:
make_plot(ax2, x, y)
# then agains a regular plot:
regular_plot(ax3, x, y)
plt.show()

rawDescription: Change Matplotlib font without impacting global


code:
selenium.getEval("this.browserbot.getCurrentWindow().moveTo((" + h + "),(" + v + "))");
selenium.getEval("this.browserbot.getCurrentWindow().resizeTo(" + w + "," + h + ")");

rawDescription: How do I make Selenium RC to not move the browser window?

description: Make Selenium RC to not move the browser window


code:
class Scheduling(threading.Thread):
    def __init__(self):
            self.schedule = None
            threading.Thread.__init__(self)

    def run(self):
            self.schedule = threading.Timer(2, self.run)
            self.schedule.start()

    def cancel(self):
            self.schedule.cancel()

rawDescription: How can one do start - pause - continue - pause - continue - pause with the threading.timer?


code: [i for i in dir(__builtins__) if hasattr(getattr(__builtins__, i), "__add__")]

rawDescription: Standard python classes that support math operators?


code:
from Tkinter import *
import Tkinter as ttk
from ttk import *

root = Tk()
root.title("Age Selector")

mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 10, padx = 10)

var = StringVar(root)

# Use dictionary to map names to ages.
choices = {
    'Bob': '35',
    'Garry': '45',
    'John': '32',
    'Hank': '64',
    'Tyrone': '21',
}

option = OptionMenu(mainframe, var, *choices)
var.set('Bob')

option.grid(row = 1, column =1)

Label(mainframe, text="Age").grid(row = 2, column = 1)

age = StringVar()
# Bind age instead of var
age_ent = Entry(mainframe, text=age, width = 15).grid(column = 2, row = 2)

# change_age is called on var change.
def change_age(*args):
    age_ = choices[var.get()]
    age.set(age_)
# trace the change of var
var.trace('w', change_age)

root.mainloop()

rawDescription: Assigning variables using choices in TKInter dropdown menu - Python 2.7


code:
ch = rabbit.connection.channel()
method = ch.queue_declare('sandbox', passive=True)
method.method.message_count

rawDescription: re-queue all messages from one queue to another with pika

description: Re-queue all messages from one queue to another with pika


code:
import decimal
import webapp2
from google.appengine.ext import ndb
import json
from google.appengine.api import users

class Item(ndb.Model):
    author = ndb.UserProperty(required=False)
    summary = ndb.StringProperty(required=True)
    description = ndb.StringProperty()
    url = ndb.StringProperty()
    created = ndb.DateTimeProperty(auto_now_add=True)
    updated = ndb.DateTimeProperty(auto_now=True)
    updated = ndb.StringProperty()
    dueDate = ndb.StringProperty(required=True)
    finished = ndb.BooleanProperty()

class DateTimeEncoder(json.JSONEncoder):
    def default(self, obj):
        if hasattr(obj, 'isoformat'):
            return obj.isoformat()
        elif isinstance(obj, decimal.Decimal):
            return float(obj)
        else:
            return json.JSONEncoder.default(self, obj)

class GetAllItems(webapp2.RequestHandler):
    def get(self):
        item = Item(summary="Summary", dueDate="Date")
        item.put()

        text = json.dumps([i.to_dict() for i in Item.query().fetch()], cls=DateTimeEncoder)
        self.response.out.write(text)

app = webapp2.WSGIApplication(
    [
        ('/api/items', GetAllItems)
    ],
    debug=True)

rawDescription: JSON response in Google App Engine with Python


code:
@app.route('/user/<user_name>/<param>')
def show_param(user_name, param):
    if ' ' in param:
        param = param.replace(' ', '-')
        return redirect(url_for('show_param'), user_name=user_name, param=param)

rawDescription: Flask URL Display

description: Flask URL Display


code:
script =  ''.join(response.xpath('//script[14]/text()').extract())
json_data = script.split("initMap(")[1].replace("</script>","")[:-1]
data = json.loads('{"data":'+json_data+'}')
fields = data["data"]
for f in fields:
    id = f["ID"]
    field10 = f["field10"]
    field12 = f["field12"]

rawDescription: Using scrapy to get data within a script


code:
from django.template import Context, Template
from django.http import HttpResponse

def my_view(request):
    ...
    context = {'value': something, 'another_var': something_else}
    # Here, instead of returning `render`, render the template using the context manually
    template_content = DbTemplate.objects.get(name='my_template').content
    template = Template(template_content)
    return HttpResponse(template.render(Context(context)))

rawDescription: Django - Edit templates from django admin


code:
card_vals = {"Jack" : 5, "Queen": 15, "King": 20, "Ace":10}
card_vals.update({ x:x for x in range(2,11)})
card_vals["Jack"]
card_vals["Jack"]
card_vals[2]
card_vals[5]

rawDescription: Blackjack program in python

description: Blackjack program in python


code:
from PIL import Image

overlay = Image.open('overlay.png')
base = Image.open('base.png')

bands = list(overlay.split())
if len(bands) == 4:
    # Assuming alpha is the last band
    bands[3] = bands[3].point(lambda x: x*0.4)
overlay = Image.merge(overlay.mode, bands)

base.paste(overlay, (0, 0), overlay)
base.save('result.png')

rawDescription: Python (PIL): Lighten transparent image and paste to another one


code:
from gevent import monkey
monkey.patch_all(thread=False)

rawDescription: Thread count increases with running logger.info in greenlet


rawDescription: RegEx anomalous behavior in a program

description: RegEx anomalous behavior in a program


code:
import sys
from threading import Thread
from PyQt5 import QtWidgets, QtCore

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(100, 100, 100, 50))
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Test"))
        self.pushButton.setText(_translate("Dialog", "OK"))

class Ui_MainWindow(object):
    def setupUi(self, mainWindow):
        mainWindow.setObjectName("mainWindow")
        self.pushButton = QtWidgets.QPushButton(mainWindow)
        self.pushButton.setGeometry(QtCore.QRect(30, 20, 100, 60))
        self.pushButton.setObjectName("pushButton")

        self.retranslateUi(mainWindow)
        QtCore.QMetaObject.connectSlotsByName(mainWindow)

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("mainWindow", "Test"))
        self.pushButton.setText(_translate("mainWindow", "Push Me!"))

class TestDialog(QtWidgets.QDialog):
    signal = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(TestDialog, self).__init__(parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        # This message simply needs to go away
        self.ui.pushButton.clicked.connect(self.close)

    def show_message(self):
        # Use this to display the pop-up so the text can be altered
        super(TestDialog, self).exec_()
        self.signal.emit()

class Main(QtWidgets.QMainWindow):
    signal = QtCore.pyqtSignal()

    def __init__(self):
        super(Main, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.dialog = TestDialog()
        self.dialog_done = False

        self.ui.pushButton.clicked.connect(self.start_thread)

    def complete_dialog(self):
        self.dialog_done = True

    def wait_for_dialog(self):
        while not self.dialog_done:
            pass
        self.dialog_done = False

    def start_thread(self):
        t = Thread(target=self.show_dialog)
        t.daemon = True
        t.start()

    def show_dialog(self):
        # Do lots of background stuff here
        self.signal.emit()
        # Wait for the dialog to get closed
        self.wait_for_dialog()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    window = Main()
    window.show()
    dialog = TestDialog()
    window.signal.connect(dialog.show_message)
    dialog.signal.connect(window.complete_dialog)
    sys.exit(app.exec_())

rawDescription: PyQt5 QDialog in subsequent threads

description: PyQt5 QDialog in subsequent threads


code: glib-compile-schemas

rawDescription: Python,GioSettings create key

description: Python,GioSettings create key


code:
filehandle = open(PATH)

r = session.post(URL_IMPORT, data={},files = {'sync_config_import':filehandle})

rawDescription: Python requests api

description: Python requests api


code: radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')]

rawDescription: Adding commas in inputs in Python?

description: Adding commas in inputs in Python


code:
from hachoir_core.error import HachoirError
from hachoir_core.stream import InputIOStream
from hachoir_parser import guessParser
from hachoir_metadata import extractMetadata

def metadata_for_filelike(filelike):
    try:
        filelike.seek(0)
    except (AttributeError, IOError):
        return None

    stream = InputIOStream(filelike, None, tags=[])
    parser = guessParser(stream)

    if not parser:
        return None

    try:
        metadata = extractMetadata(parser)
    except HachoirError:
        return None

    return metadata

rawDescription: Python: Using Hachoir, how extract metadata for file-like objects?


code:
new_pixels = []
for row in pixels:
    new_row = array('B', row)
    i = 0
    while i < len(new_row):
        r = new_row[i]
        g = new_row[i + 1]
        b = new_row[i + 2]
        if r>threshold and g>threshold and b>threshold:
            m = int((r+g+b)/3)
            if nearly_eq(r,m,tolerance) and nearly_eq(g,m,tolerance) and nearly_eq(b,m,tolerance):
                new_row[i + 3] = 0
        i += 4
    new_pixels.append(new_row)

rawDescription: Image Gurus: Optimize my Python PNG transparency function


code:
class A:
    pass

a = A() # instantiate an object of class A

rawDescription: Turning a Variable into a Function? (Code works, interesting behavior)


code:
import platform
platform.linux_distribution()
dist = platform.linux_distribution()
"Red Hat" in dist[0] and dist[1].split('.')[0] == '6'

rawDescription: How to reliably check if I am above a certain CentOS version (CentOS 7) in a Python script?

description: Reliably check if I am above a certain CentOS version (CentOS 7) in a Python script


code:
import asyncio
from asyncio import subprocess

@asyncio.coroutine
def do_work():
    process = yield from asyncio.create_subprocess_exec(
        *["python", "program.py"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT
    )

    stdout, _= yield from process.communicate()
    print(stdout)

if __name__  == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(do_work())

rawDescription: Python Asyncio subprocess never finishes


code:
import os.path
from PIL import Image

def get_img_dir():
    src_dir = os.path.dirname(__file__)
    img_dir = os.path.join(src_dir, '..', 'img')
    return img_dir

def open_img():
    img_dir = get_img_dir()
    img_name = 'amsterdam.jpg'
    full_img_path = os.path.join(img_dir, img_name)
    img = Image.open(full_img_path)
    return img

def crop_image(img, xy, scale_factor):
    '''Crop the image around the tuple xy

    Inputs:
    -------
    img: Image opened with PIL.Image
    xy: tuple with relative (x,y) position of the center of the cropped image
        x and y shall be between 0 and 1
    scale_factor: the ratio between the original image's size and the cropped image's size
    '''
    center = (img.size[0] * xy[0], img.size[1] * xy[1])
    new_size = (img.size[0] / scale_factor, img.size[1] / scale_factor)
    left = max (0, (int) (center[0] - new_size[0] / 2))
    right = min (img.size[0], (int) (center[0] + new_size[0] / 2))
    upper = max (0, (int) (center[1] - new_size[1] / 2))
    lower = min (img.size[1], (int) (center[1] + new_size[1] / 2))
    cropped_img = img.crop((left, upper, right, lower))
    return cropped_img

def save_img(img, img_name):
    img_dir = get_img_dir()
    full_img_path = os.path.join(img_dir, img_name)
    img.save(full_img_path)

if __name__ == '__main__':
    ams = open_img()

    crop_ams = crop_image(ams, (0.50, 0.50), 0.95)
    save_img(crop_ams, 'crop_amsterdam_01.jpg')

    crop_ams = crop_image(ams, (0.25, 0.25), 2.5)
    save_img(crop_ams, 'crop_amsterdam_02.jpg')

    crop_ams = crop_image(ams, (0.75, 0.45), 3.5)
    save_img(crop_ams, 'crop_amsterdam_03.jpg')

rawDescription: Crop image with settable center and scale in Python PIL


rawDescription: the fastest way to create vector z, such that z[i] = 1/(1+i)

description: The fastest way to create vector z, such that z[i] = 1/(1+i)


code:
plt.scatter(x,y,edgecolors='none',s=marker_size,c=void_fraction,
                norm=matplotlib.colors.LogNorm())

rawDescription: A logarithmic colorbar in matplotlib scatter plot


code:
frame = Frame(master)
fig = Figure(**options)
figagg = FigureCanvasTkAgg(fig, frame)
canvas = figagg.get_tk_widget()
canvas.config(bd=0, highlightthickness=0) # <---
canvas.pack(expand=1, fill='both')

rawDescription: How to delete external Matplot frame in tkinter GUI

description: Delete external Matplot frame in tkinter GUI


code:
from collections import defaultdict

def ordered(data, N):
    edges = defaultdict()
    for v1, v2 in data:
        edges.setdefault(v1, []).append(v2)
        edges.setdefault(v2, []).append(v1)

    visited = [False] * N
    path = None
    for v in range(N):
        if not visited[v]:
            path = dfs(edges, visited, v)
            if path is not None: break
    if path is not None:
        return [[path[i], path[i + 1]] for i in range(len(path) - 1)]

def dfs(edges, visited, v1, vp=None):
    path = [v1]
    if visited[v1]: return path
    visited[v1] = True
    for v2 in edges[v1]:
        if v2 == vp: continue
        path_child = dfs(edges, visited, v2, v1)
        if path_child is not None: return path + path_child
    return None

data = [[0, 7], [1, 8], [2, 9], [3, 0], [4, 1], [5, 2], [6, 3], [4, 7], [8, 5], [9, 6]]
N = 10
ord = ordered(data, N)

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

rawDescription: Efficient grouping of rows from Nx2 integer numpy array to match sequential elements in rows


code: res = p.apply_async(testFunc, args=(2, 4), kwds={'calcY': False})

rawDescription: python multiprocessing with boolean and multiple arguments

description: Python multiprocessing with boolean and multiple arguments


code:
r = app.test_client().get(url,
                          headers={'Content-Type': 'application/json', 'Accept': 'application/json'},
                          query_string={'hateoas': False})

rawDescription: Flask / Eve: Internal GET request with parameters


code:
comment = '''/**
 * @param string username   required    the username of the registering user
 * @param string password   required
 * @param string first_name required
 * @param string last_name  required
 * @param string email      required
 * @package authentication
 * @info user registration
 * @description register a new user into the groupjump platform
 */'''
import re
desc = re.findall(r'@description (.*)', comment)
desc

rawDescription: Python 3 remove empty list

description: Python 3 remove empty list


code:
# Update or create the words and counts in the Words table.
for word, count in words.iteritems():
    Word.objects.update_or_create(word=word, defaults={'count': count})

rawDescription: Django way to modify a database table using the contents of another table


code:
from __future__ import print_function

def process(infile, keep):
    for line in infile:
        fields = line.split()
        yield ' '.join([_ for i, _ in enumerate(fields) if i in keep])

def main(infile, outfile):
    # The following line (taken from your example) will not work in Python 3 as
    # you cannot "add" ranges to lists. In Python 3 you would need to write:
    # >>> [14] + list(range(20, 27)
    keep = range(1, 3) + [14] + range(20, 27) + range(33, 38) + [43] + [45]
    for newline in process(infile, keep):
        print(newline, file=outfile)

if __name__ == '__main__':
    with open('so.txt') as infile, open('output.txt', 'w') as outfile:
        main(infile, outfile)

rawDescription: Remove specified elements from a list in a txt file


code:
print("If a hippo ways 2000 pounds, gives birth to a 100 pound calf and "
       "then eats a 50 pound meal how much does she weigh?")

rawDescription: How to make print statement one line in python?

description: Make print statement one line in python


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

sns.set_style("darkgrid")
plt.plot(np.cumsum(np.random.randn(1000,1)))
plt.show()

rawDescription: Simple line plots using seaborn

description: Simple line plots using seaborn


code:
for outer_key, inner_dict in example.items():
    if value in inner_dict:
        do_things()

rawDescription: Manipulation of keys in dict-of-dicts in python


code:
import bs4
import requests

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}

#just add to this list for each new player
#player name : url
queries = {"bledsoe":"https://www.google.com/search?q=%22eric+bledsoe%22&tbm=nws&tbs=qdr:d",
           "james":"https://www.google.com/search?q=%22lebron+james%22&tbm=nws&tbs=qdr:y"}

total = []

for player in queries: #keys

    #request the google query url of each player
    req  = requests.get(queries[player], headers=headers)
    soup = bs4.BeautifulSoup(req.text, "html.parser")

    #look for the main container
    for each in soup.find_all("div"):
        results = {player: { \
            "link": None,    \
            "title": None,   \
            "source": None,  \
            "time": None}    \
        }

        try:
          #if <div> doesn't have class="anything"
          #it will throw a keyerror, just ignore

          if "_cnc" in each.attrs["class"]: #mainstories
            results[player]["link"] = each.find("a")["href"]
            results[player]["title"] = each.find("a").get_text()
            sourceAndTime = each.contents[1].get_text().split("-")
            results[player]["source"], results[player]["time"] = sourceAndTime
            total.append(results)

          elif "card-section" in each.attrs["class"]: #buckets
            results[player]["link"] = each.find("a")["href"]
            results[player]["title"] = each.find("a").get_text()
            results[player]["source"] = each.contents[1].contents[0].get_text()
            results[player]["time"] = each.contents[1].get_text()
            total.append(results)

        except KeyError:
            pass

rawDescription: parsing google news using beautiful soup python

description: Parsing google news using beautiful soup python


code:
mainDict = dict()
file = open(filename, 'r')
for line in file:
    line = line.strip()
    if line == "" :
        continue
    if line.find("Head") :
        lastBlock = line
        mainDict[lastBlock] = dict()
        continue
    splitLine = line.partition(" ")
    mainDict[lastBlock][splitLine[0]] = splitLine[2]

rawDescription: Transforming non-tabular/chunked data into a nested dictionary in Python


code:
import copy

dic1 = {'a': set([1,2])}
dic2 = copy.deepcopy(dic1)
dic2['a'].discard(1)

rawDescription: How to remove set element in copied object

description: Remove set element in copied object


code:
import random
with open('the_file','r') as source:
    data = [ (random.random(), line) for line in source ]
data.sort()
with open('another_file','w') as target:
    for _, line in data:
        target.write( line )

rawDescription: randomly mix lines of 3 million-line file

description: Randomly mix lines of 3 million-line file


code:
from itertools import islice
import csv

test_filename = 'C:/Python33/test.CAR'

with open(test_filename, 'r') as infh, open('test.csv', 'w' ,newline='') as outfh:
    writer = csv.writer(outfh)
    writer.writerow(['DATE', 'TIME', 'NUMBER'])

    for line in infh:
        date1, time1, _, num1, _ = line.split(None, 4)
        num1 = float(num1)

        # skip 98 lines to read line number 99 from where we are now
        nextline = next(islice(infh, 98, 99), None)
        if nextline is None:
            break  # file is done early

        date2, time2, _, num2, _ = nextline.split(None, 4)
        num2 = float(num2)

        writer.writerow([date1, time1, num2 - num1])

rawDescription: subtract 2 numbers in one column one file using python

description: Subtract 2 numbers in one column one file using python


code:
import csv

with open('summ.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    kept2 = [row for row in reader]

rawDescription: Create lists of dictionaries from .CSV file using header words as keys


code:
while True:
  colour = input("black or white? ")
  if colour in ("black", "white"):
    print("Thank you")
    break
  else:
    print("Please choose one or the other")

rawDescription: Looping a python "if" statement

description: Looping a python "if" statement


code:
'q' in 'qeen'.replace('qu', '')
'q' in 'queen'.replace('qu', '')
'qeen'.replace('qu', 'q').replace('q', 'qu')

rawDescription: regex to see if one specific letter is always followed by another specific letter

description: Regex to see if one specific letter is always followed by another specific letter


code:
# creating the static box sizer
self.my_box = wx.StaticBox(self.panel, wx.ID_ANY, "Spam, spam, spam")
self.sizer_static_box = wx.StaticBoxSizer(self.my_box)

# then do something like this later
self.my_box.SetLabel("I hate spam!")

rawDescription: Modify StaticBoxSizer label on wxPython

description: Modify StaticBoxSizer label on wxPython


code:
import csv
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt

word_list = ['A','A','B','B','A','C','C','C','C']

counts = Counter(word_list)

labels, values = zip(*counts.items())

# sort your values in descending order
indSort = np.argsort(values)[::-1]

# rearrange your data
labels = np.array(labels)[indSort]
values = np.array(values)[indSort]

indexes = np.arange(len(labels))

bar_width = 0.35

plt.bar(indexes, values)

# add labels
plt.xticks(indexes + bar_width, labels)
plt.show()

rawDescription: How to generate a word frequency histogram, where bars are ordered according to their height

description: Generate a word frequency histogram, where bars are ordered according to their height


code:
from random import choice
def prbs():
    while True:
        yield choice([False, True])

rawDescription: Pseudo random binary sequences (prbs) in Python


code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot([0,1,2],[10,10,100],marker='o',linestyle='-')
ax.set_yscale('symlog')
ax.set_xscale('symlog')
plt.show()

rawDescription: Logscale plots with zero values in matplotlib


rawDescription: populate a numpy array with a normal array

description: Populate a numpy array with a normal array


code:
import subprocess
import sys

output = subprocess.check_output([sys.executable, 'program_module.py'])

rawDescription: Create different runs of a program and use its output


code:
import subprocess

try:
  mycommand = "ls"
  result = subprocess.check_output(mycommand, shell=True)
  print(result)
except subprocess.CalledProcessError as error:
  # Handle the error
  print("Error: Command exited with code {0}".format(error.returncode))

rawDescription: How get result of executed batch script as string in python?


code:
import demjson
demjson.decode('{suggestion:[{query:"London",interpretation: ...')

rawDescription: Convert Google results object (pure js) to Python object


code:
for item, location in ITEMS_IN_WORLD.iteritems():
 if (CURRENT_LOCATION==location):
  print ("Found!")  #Or whatever you intend to do

rawDescription: How to check if a dictionary value is equal to a variable's value

description: Check if a dictionary value is equal to a variable's value


code:
import cv2

# load image
fname = 'Myimage.jpg'
im = cv2.imread(fname,cv2.COLOR_RGB2GRAY)
# blur image
im = cv2.blur(im,(4,4))
# apply a threshold
im = cv2.threshold(im, 175 , 250, cv2.THRESH_BINARY)
im = im[1]
# show image
cv2.imshow('',im)
cv2.waitKey(0)

rawDescription: Remove points which contains pixels fewer than (N)


code:
cols = zip(*data)
data = zip(*sorted(cols))

rawDescription: Python: How to check that two CSV files with header rows contain same information disregarding row and column order?


code:
string = "if X > 3 :\n   print(\"X is Greater\")\nelse :\n   print(\"X is Lesser\")"
X = 6
exec(string)

rawDescription: Extension of Python's eval

description: Extension of Python's eval


code:
import itertools

for i1,i2 in itertools.product(xrange(len(Seq1)), xrange(len(Seq2))):
    a[i1,i2] = Seq1[i1] == Seq2[i2]

rawDescription: Compare values in two strings and then yield a result that can be placed in an array


code:
from zope.interface import Interface, Attribute, implements
class IFoo(Interface):
    x = Attribute("The X attribute")
    y = Attribute("The Y attribute")
class Foo(object):
    implements(IFoo)
    x = 1
    def __init__(self):
        self.y = 2
from zope.interface.verify import verifyObject
verifyObject(IFoo, Foo())
from zope.interface.verify import verifyClass
verifyClass(IFoo, Foo)

rawDescription: Purpose of Zope Interfaces?

description: Purpose of Zope Interfaces


code:
optionName, optionValue = readConfigFile()
setattr(configObject, optionName, optionValue)

rawDescription: Python setting attributes priority and overriding


code:
pm.glm.glm('y ~ x', data,
           family=pm.glm.families.Normal(priors={'sd': ('sigma', pm.Uniform.dist(0, 12000))}))

rawDescription: Regression using PYMC3

description: Regression using PYMC3


code:
formerGeometry = QtCore.QRect(tbw.geometry()) # storing previous geometry in order to be able to restore it later

hideAnimation = QtCore.QPropertyAnimation(tbw, "geometry")
hideAnimation.setDuration(2000) # chose the value that fits you
hideAnimation.setStartValue(formerGeometry)
#computing final geometry
endTopLeftCorner = QtCore.QPoint(tbw.pos() + QtCore.QPoint(0, tbw.height()))
finalGeometry = QtCore.QRect(endTopLeftCorner, QtCore.QSize(tbw.width(), 0))
hideAnimation.setEndValue(finalGeometry)

hideAnimation.start()

rawDescription: How to show/hide a child QWidget with a motion animation?

description: Show/hide a child QWidget with a motion animation


code:
import matplotlib.pyplot as plt

x = range(10)
y = range(10)

fig, ax = plt.subplots()

# Plot the line connecting the points
ax.plot(x, y)

# At each point, plot the y-value with a white box behind it
for xpoint, ypoint in zip(x, y):
    ax.annotate('{:.2f}'.format(ypoint), (xpoint,ypoint), ha='center',
                va='center', bbox=dict(fc='white', ec='none'))

# Manually tweak the limits so that our labels are inside the axes...
ax.axis([min(x) - 1, max(x) + 1, min(y) - 1, max(y) + 1])
plt.show()

rawDescription: python pyplot annotations

description: Python pyplot annotations


code:
from xml.dom.minidom import parseString
x = parseString('<abc>foo</abc>')
x.getElementsByTagName('abc')[0].firstChild.nodeValue

rawDescription: How do you get "some Text" from <abc>some Text</abc> with python?

description: Get "some Text" from <abc>some Text</abc> with python


code:
import httplib
from urlparse import urlparse

def url_exists(url):
    _, host, path, _, _, _ = urlparse(url)
    conn = httplib.HTTPConnection(host)
    conn.request('HEAD', path)
    return conn.getresponse().status < 400

rawDescription: Check if an s3 url exists

description: Check if an s3 url exists