code:
def collatz(number):
    number = int(number)
    while number != 1:
        if number % 2 == 0:
            number = number/2
        elif number % 2 != 0:  # could be just `else` -- either it's divisible by 2 or it isn't :)
            number = (number*3) + 1
    print("finished")

n = int(input('Pick a number'))
collatz(n)

rawDescription: Converting recursive to iterative in python


code:
df = pd.DataFrame(['foo', 'bar', 'baz'], columns=['col1'])
df
df.col1.str[1]

rawDescription: Python / Pandas: Get second character of the string, from every row


code:
import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x

class CycleThroughClass(object):
    def __init__(self, master):
        self.display_1=tk.Label(master, bg="lightblue")
        self.display_1.grid(row=0, column=0, sticky="nsew")
        self.display_2=tk.Label(master, bg="lightgreen")
        self.display_2.grid(row=0, column=1, sticky="nsew")

        tk.Button(master, text="next item", bg="khaki",
                  command=self.next_data_set).grid(row=1,
                  column=0, sticky="nsew")

        tk.Button(master, text="Quit", bg="orange",
                  command=master.quit).grid(row=2, column=0, sticky="nsew")

        self.ctr=0
        self.questions=[["one", 1], ["two", 2], ["three", 3],
                        ["four", 4], ["five", 5]]
        self.next_data_set()

    def next_data_set(self):
        if self.ctr < len(self.questions):
            question, number=self.questions[self.ctr]
            self.display_1.config(text=question)
            self.display_2.config(text=str(number))
            self.ctr += 1
        else:
            self.display_1.config(text="Sorry, no more")
            self.display_2.config(text="")

master=tk.Tk()
CT=CycleThroughClass(master)
master.mainloop()

rawDescription: Python 3.4 Make mouse click event advance through a list of data


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

class Unsubscription(models.Model):
    name = ...

    # These two fields allow you to manage the model & instance of object that
    # this unsubscribe model instance is related to
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    # This gives you an easy way to get access to the actual instance of the
    # instance above
    content_object = generic.GenericForeignKey('content_type', 'object_id')

# On the reverse end of the relationship you can add a Generic relation to
# easily get access to all unsubscriptions related to this contact via the GFK
from myapp.models import Unsubscription
class Contact(models.Model):
    name = ...

    unsubscribtions = generic.GenericRelation(Unsubscribtion)

rawDescription: Django reusable application with linked FK?


code:
from collections import Counter

c = Counter({'blue': 3, 'red': 2, 'green': 1})

keys = [key for key, val in c.most_common()]

print(keys)
# ['blue', 'red', 'green']

rawDescription: Ordering by frequency rather than alphabetically in a set (in Python)


code:
from oauth2client.client import GoogleCredentials
from oauth2client import GOOGLE_TOKEN_URI

access_token = YOUR_TOKEN
token_expiry = None
token_uri = GOOGLE_TOKEN_URI
user_agent = 'Python client library'
revoke_uri = None

credentials = GoogleCredentials(
    access_token,
    client_id,
    client_secret,
    refresh_token,
    token_expiry,
    token_uri,
    user_agent,
    revoke_uri=revoke_uri
    )

rawDescription: How do I get the youtube api client handle using access token

description: Get the youtube api client handle using access token


code:
class A:  pass

a = A()
a.foo = "bar"
import json

class MyEncoder(json.JSONEncoder):
   def default(self, obj):
      if isinstance(obj, A):
         return { "foo" : obj.foo }
      return json.JSONEncoder.default(self, obj)

json.dumps(a, cls=MyEncoder)

rawDescription: Make a Custom Class JSON serializable

description: Make a Custom Class JSON serializable


code:
import Queue, thread

# create a Queue.Queue here
queue = Queue.Queue()

print ("downloading and parsing Bibles...")
root = html.parse(open('links.html'))
for link in root.findall('//a'):
  url = link.get('href')
  queue.put(url) # produce

def thrad():
  url = queue.get() # consume
  name = urlparse.urlparse(url).path.split('/')[-1]
  dirname = urlparse.urlparse(url).path.split('.')[-1]
  f = urllib2.urlopen(url)
  s = f.read()
  if (os.path.isdir(dirname) == 0):
    os.mkdir(dirname)
  soup = BeautifulSoup(s)
  articleTag = soup.html.body.article
  converted = str(articleTag)
  full_path = os.path.join(dirname, name)
  open(full_path, 'wb').write(converted)
  print(name)

thread.start_new(thrad, ()) # start 1 threads

rawDescription: Multithreading for faster downloading

description: Multithreading for faster downloading


code:
var1, var2, var3 = (int(i) for i in a)
var1, var2, var3

rawDescription: Assign string elements as integers to variables in single line


code:
def execute(self):
    soup = BeautifulSoup(requests.get(self.url).text)
    threads = []
    for link in soup.find_all('a'):
        url = link.get('href')
        t = threading.Thread(target=self._check_url, args=(url,))
        t.start()
        threads.append(t)
    for thread in threads:
        thread.join()

rawDescription: Synchronise muti-threads in Python

description: Synchronise muti-threads in Python


code:
class State(object):
  def __init__(self, **kwargs):
    self.__dict__.update(kwargs)

  def state_name(self):
    return self.state

class County(object):
  def __init__(self, state, **kwargs):
    self.state=state # this will just reference the state object
    self.__dict__.update(kwargs)
  def getStateName(self):
    return self.state.state

class City(object):
  def __init__(self, county, **kwargs):
    self.county = county
    self.__dict__.update(kwargs)
  def getStateName(self):
    return self.county.getStateName()

rawDescription: Python - Inherit an Already Initialized Class Without Calling Super Constructor


code:
def getEventsForMonth(self, month, year):
  start_date = datetime.datetime(year, month, 1)
  if month == 12:
    end_date = datetime.datetime(year + 1, 1, 1)
  else:
    end_date = datetime.datetime(year, month + 1, 1)
  return Events.all().filter('date >=', start_date).filter('date <=', end_date).fetch(1000)

rawDescription: How can I query objects with a date field, using a specific month and year?

description: Query objects with a date field, using a specific month and year


code:
for l in line.split():
    print(l[0].upper(), end='')
print()

rawDescription: How do I output the acronym on one line

description: Output the acronym on one line


rawDescription: cleaning my list

description: Cleaning my list


code:
import pandas as pd

thelist = [ ['sentence 1'], ['sentence 2'], ['sentence 3'] ]
df = pd.Series( (v[0] for v in thelist) )

rawDescription: Convert a list object to Dataframe (series) object,python


rawDescription: Python: how to pass a index range as parameter


code:
import __main__
import os

appName = os.path.basename(__main__.__file__).strip(".py")

rawDescription: How to get the name of the top most (entry) script in python?

description: Get the name of the top most (entry) script in python


rawDescription: Merge columns of a dataframe into a list after merging by the first column


code:
with open(fname) as csvfile:
    forheader_IO2016 = csv.reader(csvfile, delimiter=',')
    header_IO2016 = []
    for row in forheader_IO2016:
        header_IO2016.append(row[0])

date = header_IO2016[7].split(" ")[2]
time = header_IO2016[8].split(" ")[2]
lat = float(header_IO2016[9].split(" ")[2])
lon = float(header_IO2016[10].split(" ")[4])

rawDescription: Reading in header information from csv file using Pandas


code:
alpha = list("bcdfghjklmnpqrstvwxyz")
def cow_latinify_word(word):
    if word[0].lower() in alpha:
        lista = (word.lower())
        return lista[1:] + lista[0] + "oo"
    else:
        return word + "moo"

def cow_latinify_sentence(sentence):
    words = sentence.split();
    return ' '.join([cow_latinify_word(word) for word in words])

rawDescription: Removing the square brackets, commas and single quote?


code:
def func(): pass
f1_ret = f1(arg)
f2_ret = f2(func)
func = f1_ret(f2_ret)

rawDescription: How does this function call work? (Involves multiple pairs of brackets and decorators)


code: db.foo.find({"purchase_date": {"$gt": monday_midnight, "$lte": tuesday_midnight}})

rawDescription: MongoDB/py-mongo for queries with date functions


code:
import re
text = 'foo&bar link'
re.sub(r'<.+?>', '', text)
# foo&bar link

rawDescription: strip HTML tags without removing & - ampersand in Python

description: Strip HTML tags without removing & - ampersand in Python


code:
df["x_dummy1"] = 0
df.loc[df.x==1, "x_dummy1"] = 1

rawDescription: Which statement should I use to replace custom defined function creating dummy variables to increase speed in python?


code: foobar = __import__("foo-bar")

rawDescription: Python Module with a dash, or hyphen (-) in its name


code:
import sys
import time

def ScrollingText(s):
     s=str(s)
     for letter in s:
          print(letter, end="")
          sys.stdout.flush()
          time.sleep(.05)
     print("")     # newline at the end

rawDescription: Python: time.sleep functions unexpectedly?


rawDescription: what is better way of getting windows version in python?

description: What is better way of getting windows version in python


code:
name = raw_input("What is your name?")
print ("Hello " + name)

rawDescription: Basic Python: exceptions.NameError

description: Basic Python: exceptions.NameError


rawDescription: Python: How to keep variable memory location across assignment?


code:
import collections
dd = collections.OrderedDict({
  'units': 'imperial',
  'fit': 'fit' ,
  'height': [ 'height' ],
  'weight': [ 'weight' ],
  'neck': [ 'neck' ],
})

print( dd )  #Order not preserved

#Pass an iterable of 2-tuples to preserve order.
ddd = collections.OrderedDict([
  ('units', 'imperial'),
  ('fit', 'fit') ,
  ('height', [ 'height' ]),
  ('weight', [ 'weight' ]),
  ('neck', [ 'neck' ]),
])

print( ddd ) #Order preserved

rawDescription: Alternatives to Dictionary in Python - Need to reference value by named key and iterate in insertion order


code:
import math
a = int(input("Input a number"))
a = math.abs(a)
print(a)

rawDescription: Calculate abs() value of input -- Python


code:
svg = """
<svg height="640" version="1.1" width="1200" xmlns="http://www.w3.org/2000/svg" style="overflow: hidden; position: relative; left: -0.40625px;"><desc style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);">Created with Raphaël 2.1.0</desc><defs style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"></defs><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M411,109L411,110Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M411,110L412,111Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M412,111L413,113Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M413,113L413,114Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M413,114L414,116Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M414,116L414,117Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M414,117L415,119Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M415,119L415,121Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M415,121L415,122Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M415,122L415,123Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M415,123L416,124Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M416,124L416,125Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M416,125L416,124Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M416,124L416,124Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M406,212L407,212Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M407,212L407,213Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M407,213L408,213Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M408,213L408,214Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M408,214L410,215Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M410,215L411,215Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M411,215L412,216Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M412,216L413,217Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M413,217L415,218Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M415,218L416,219Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M416,219L418,220Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M418,220L420,221Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M420,221L421,221Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M421,221L423,222Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M423,222L424,222Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M424,222L426,223Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M426,223L427,223Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M427,223L429,224Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M429,224L431,224Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M431,224L433,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M433,225L435,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M435,225L436,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M436,225L438,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M438,225L439,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M439,225L441,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M441,225L442,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M442,225L443,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M443,225L444,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M444,225L445,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M445,225L446,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M446,225L446,225Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M321,231L325,231Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M325,231L329,231Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M329,231L339,231Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M339,231L344,229Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M344,229L354,228Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M354,228L360,226Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M360,226L369,224Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M369,224L379,220Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M379,220L385,219Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M385,219L390,216Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M390,216L392,216Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M392,216L394,215Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M394,215L394,214Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M394,214L395,214Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M395,214L395,214Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M461,74L461,75Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M461,75L461,76Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M461,76L461,77Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M461,77L461,78Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M461,78L461,79Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M461,79L462,80Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M462,80L462,81Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M462,81L462,83Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M462,83L462,85Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M462,85L462,86Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M462,86L463,87Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M463,87L463,88Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M463,88L463,89Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M463,89L463,90Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M463,90L463,91Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M463,91L463,92Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M463,92L464,93Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M464,93L464,95Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M464,95L464,96Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M464,96L465,97Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M465,97L465,98Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M465,98L465,99Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M465,99L465,100Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M465,100L465,101Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M465,101L465,102Z" stroke-width="3px"></path><path style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);" fill="none" stroke="#000000" d="M465,102L465,102Z" stroke-width="3px"></path></svg>
"""

from cairosvg import svg2pdf

svg2pdf(str(svg), write_to='testx.pdf')

rawDescription: How to convert svg to pdf in python 3+?

description: Convert svg to pdf in python 3+


code:
def BenfordsLaw4(maxvalue = 10**6):
    BenfordList = {str(i+1):0 for i in range(9)}
    for i in (str((i+1)**2)[0] for i in xrange(maxvalue)):
        BenfordList[i] += 1

rawDescription: A more efficient Benford's Law code?

description: A more efficient Benford's Law code


code:
def format_currency(value):
    return "${:,.2f}".format(value)

rawDescription: Jinja Templates - Format a float as comma-separated currency


code:
card_labels = {}

for i in range(2):
    for j in range(6):
        label = CardLabel(root)
        label.grid(row=i, column=j)
        label.configure(image=CardLabel.blank_image)
        card_labels[i, j] = label

rawDescription: How to attach i in 'for i in range(x)' to a label in python?

description: Attach i in 'for i in range(x)' to a label in python


code:
import sys
import subprocess

procs = []
for i in range(86):
    proc = subprocess.Popen([sys.executable, 'task.py', '{}in.csv'.format(i), '{}out.csv'.format(i)])
    procs.append(proc)

for proc in procs:
    proc.wait()

rawDescription: run multiple instances of python script simultaneously

description: Run multiple instances of python script simultaneously


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

fig,(ax1,ax2)=plt.subplots(2)

ax1.plot(np.arange(10000,10010,1))

ax2.plot(np.arange(10000,10010,1))
ax2.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.4e'))

plt.show()

rawDescription: matplotlib: format axis ticks without offset

description: Matplotlib: format axis ticks without offset


code:
current_vcodec = subprocess.check_output("mediainfo --Inform='Video;%%CodecID%%' %s" % source, shell=True)
current_acodec = subprocess.check_output("mediainfo --Inform='Audio;%%CodecID%%' %s" % source, shell=True)
duration = subprocess.check_output("mediainfo --Inform='Video;%%Duration%%' %s" % source, shell=True)

rawDescription: Python subprocess.check_output

description: Python subprocess.check_output


code:
import datetime
from collections import Counter
C = Counter()
L =     [{'campaign_id': 'cid2504649263',
  'country': 'AU',
  'count': 3000,            # <== changed this to "count"
  'region': 'Cairns',
  'utcdt': datetime.datetime(2013, 6, 4, 6, 0)},
 {'campaign_id': 'cid2504649263',
  'country': 'AU',
  'count': 3000,
  'region': 'Cairns',
  'utcdt': datetime.datetime(2013, 6, 4, 6, 0)},
 {'campaign_id': 'cid2504649263',
  'country': 'AU',
  'count': 3000,
  'region': 'Cairns',
  'utcdt': datetime.datetime(2013, 6, 4, 7, 0)}]
for item in L:                        # The ... represents the rest of the key
    C[item['campaign_id'], item['country'], ...,  item['utcdt']] += item['count']

rawDescription: how to combine hashes in a list of hashes?

description: Combine hashes in a list of hashes


code:
from collections import namedtuple
Container = namedtuple('Container', ('mac_0', 'mac_1'))
container = Container(mac_0=1, mac_1=2)
container[0]
container[1]
container.mac_0
container.mac_1

rawDescription: How to access elements in nametuples in python?

description: Access elements in nametuples in python


code:
WANTED = 20 #or however many characters you want after 'Figure'

with open('mytext.txt') as searchfile:
    for line in searchfile:
        left,sep,right = line.partition('Figure')
        if sep: # True iff 'Figure' in line
            print(right[:WANTED])

rawDescription: Python search text file, print characters following a string


code:
l = "big long list of space separated words"
re.split(r'[ ,|;"]+', l)

rawDescription: How do you dynamically identify unknown delimiters in a data file?

description: Dynamically identify unknown delimiters in a data file


code:
def deriv(func, order, x, e):
    if order < 0: raise ValueError
    if order == 0: return func(x)
    y = deriv(func, order-1, x, e)
    x1 = x + e
    y1 = deriv(func, order-1, x1, e)
    return float(y - y1)/(x - x1)

rawDescription: Can't figure out a recursive function

description: Can't figure out a recursive function


code:
def plot_yz_over_x_elementwise(zarray):
    for i in range(zarray.shape[1]):
        for j in range(zarray.shape[2]):
            plt.subplot2grid((zarray.shape[1],zarray.shape[2]),(i,j))
            plt.plot(zarray[:,i,j])
            frame = plt.gca()
            frame.axes.get_xaxis().set_ticks([])
            frame.axes.get_yaxis().set_ticks([1,0.5,0])
    plt.tight_layout()

rawDescription: Reshaping pyplot subplot

description: Reshaping pyplot subplot


code:
def __init__(self, values=None):
    if values is None:
        values = [0] * 10

rawDescription: Why do two class instances appear to be sharing the same data?


code:
class someForm(forms.Form):
    afield = CharField()

    def clean(self, **kwargs):
        cleaned_data = self.cleaned_data
        afield = cleaned_data.get('afield')
        if 'ip' in kwargs:
            ip = kwargs['ip']
            # ip check block, you migth use your cleaned data in here
        return cleaned_data

some_info = {'afield':123} #you will wish to use post or gt form data instead, but tihs iis for example
form = someForm(some_info)
if form.is_valid():
    data = form.clean({'ip':request.META['REMOTE_ADDR']}) # you pass a dict with kwargs, which wwill be used in custom clean method

rawDescription: Inside Django's models.py, if I am validating a form, how do I get the user's IP?


code:
def f1(arg):
    for i in range(10):
        yield 1, 2, 3, 4, 5

def f2(arg):
    for i in range(10):
        yield 6

arg = 1

for (a, b, c, d, e), f in zip(f1(arg), f2(arg)):
    print(a, b, c, d, e, f)

rawDescription: How to combine tuples from two generators in python

description: Combine tuples from two generators in python


code: self.save_name_for(*args, **kwargs)

rawDescription: How to pass through Python args and kwargs?

description: Pass through Python args and kwargs


code:
def transform(regex):
    return ''.join([
        "[%s%s]" % (c, c.upper())
            if c.islower()
            else c
        for c in regex
    ])

transformed = transform('Abcd')

rawDescription: Python regex partially case insensitive

description: Python regex partially case insensitive


code:
from itertools import product
list(product(*a))

rawDescription: How to make every combinaison of element from a list of n lists with m elements? (Python)

description: Make every combinaison of element from a list of n lists with m elements? (Python)


code:
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import csv

url = "http://www.sigmaaldrich.com/united-states.html"
cas = ['50893-53-3','2094-98-6']

with open('name.csv', 'w') as file:
    writer = csv.writer(file, delimiter = '\t', lineterminator = '\n',)
    for i in cas:
        driver = webdriver.Firefox()
        driver.get(url)

        inputElement = driver.find_element_by_name("Query")
        inputElement.send_keys(i)
        inputElement.submit()

        name = driver.find_element_by_css_selector("h2.name").text.encode("utf-8")
        purity = driver.find_element_by_css_selector("li.applicationValue a").text.encode('utf-8')
        purity = purity.replace("(Sigma-Aldrich)" , "")
        purity = purity.replace("(Aldrich)" , "")
        purity = purity.replace("(Sigma)", "")
        print [name, purity]

        driver.quit()

        writer.writerow([name, purity])

rawDescription: python writing for loop result to csv

description: Python writing for loop result to csv


code: [x for x in L for y in range(4)]

rawDescription: How to make duplicates of values in a list python

description: Make duplicates of values in a list python


code:
import os
import shutil
import random
import os.path

src_dir = 'C:\\'
target_dir = 'C:\\TEST'
src_files = (os.listdir(src_dir))
def valid_path(dir_path, filename):
    full_path = os.path.join(dir_path, filename)
    return os.path.isfile(full_path)
files = [os.path.join(src_dir, f) for f in src_files if valid_path(src_dir, f)]
choices = random.sample(files, 5)
for files in choices:
    shutil.copy(files, target_dir)
print ('Finished!')

rawDescription: Selecting and Copying a Random File Several Times


code:
lines = readin.readlines()
out1.write(''.join(lines[5:67]))
out2.write(''.join(lines[89:111]))

rawDescription: Selecting and printing specific rows of text file


code:
from dateutil.parser import parse
parse("2011-10-26")

rawDescription: Wrong Python date calculation.

description: Wrong Python date calculation.


code:
mystring = 'Main St and I295'
pattern = r'I(\d+)'
re.sub(pattern, 'I-\g<1>', mystring)

rawDescription: Add Character to Python regular exprsession


code: timestamp = time.strftime('%H:%M:%S')

rawDescription: 24 hour format for Python timestamp

description: 24 hour format for Python timestamp


code: A = IntVector('A', 112)

rawDescription: An array of a certain size in z3

description: An array of a certain size in z3


rawDescription: Returning indexes of intersected lists with Python


code: [[i for i, j in enumerate(c) if j is not None] for c in zip(*list1)]

rawDescription: Getting the indices of all non-None items from a sub-list in Python?


code:
# CPU usage

# +Apply here:
cpu_percentage = subprocess.call("top -p %d -b -n 1 | grep -w java | awk '{print $9}'" % PID, shell=True, stdout=devnull)

# +like you did here:
print('\nCPU percentage usage by Java: %s%%' % cpu_percentage)

rawDescription: Get CPU % of given PID without psutil

description: Get CPU % of given PID without psutil


rawDescription: Regex to capture option and string following it from a menu


code:
with mock.patch.object(subprocess, 'Popen') as mocked_popen:
    mocked_popen.return_value.communicate.return_value = some_fake_result
    function_which_uses_popen_communicate()

rawDescription: How to unit test a function that uses Popen?

description: Unit test a function that uses Popen


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

shifts = np.linspace(1, 50, 25)[:, np.newaxis]
x = np.arange(50)[np.newaxis, :]
data = np.exp(-(x - shifts)**2 / 50) * shifts

fig, (ax1, ax2) = plt.subplots(2, 1)

im1 = ax1.imshow(data, interpolation='none', cmap='viridis')
fig.colorbar(im1, ax=ax1, label='raw values')

norm_data = (data - np.min(data, axis=1)[:, np.newaxis]) / np.ptp(data, axis=1)[:, np.newaxis]
im2 = ax2.imshow(norm_data, interpolation='none', cmap='viridis')
fig.colorbar(im2, ax=ax2, label='normalized by row')

rawDescription: How to scale values in the heamap in row direction using Matplotlib's "imshow"?

description: Scale values in the heamap in row direction using Matplotlib's "imshow"


code: number = long(v)

rawDescription: Getting address from gdb.Value

description: Getting address from gdb.Value


code: result = result[(result['var']>0.25) | (result['var']<-0.25)]

rawDescription: Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()


rawDescription: subtract from value inside dictionary in a list python

description: Subtract from value inside dictionary in a list python


code:
#save
file_handler = open("myfile.pkl", "w")
pickle.dump(me, file_handler)

#load
file_handler = open("myfile.pkl", "r")
me = pickle.load(file_handler)

rawDescription: How to store an instance of a Class into a file

description: Store an instance of a Class into a file


code:
for line, item in zip (open ('myfile.txt'), mylist):
  print (line)
  print (item)

rawDescription: How do I read a file line by line and read a list element by element simultaneous in python

description: Read a file line by line and read a list element by element simultaneous in python


code:
import re
string = 'Tweet_id:"123456789","text":"What an episode","truncated":"false,Tweet_id:"12345678910","text":My number is fascinating","truncated":false'
re.findall('\"text\":(.*?),', string)

rawDescription: Python extraction of variable length text from a file


rawDescription: Efficient way of summing the values in specified ranges of a column


code:
class MyTestClass:
  def test_method1():
    test_something()

  def test_method2():
    test_something_else()

rawDescription: How to prevent Selenium from closing browser after each function?

description: Prevent Selenium from closing browser after each function


code:
fig = plt.figure()
data = str2[0].data
plt.plot(data)
plt.hold(True) #equivalent of matlab hold on
plt.axvline(x=on_off[0,0], c='r')
npts2 = str2[0].stats.npts
plt.title(str2[0].stats.starttime)
l = plt.axhline(y=-4000, xmin=on_off[0,0]/npts2, xmax=on_off[0,1]/npts2, linewidth=4, color='r')
plt.show()

rawDescription: Annotating figures in the obspy module of Python


code:
df = pd.DataFrame(dict(A=[5,3,5,6], C=["foo","bar","fooXYZbar", "bat"]))
df
df[df.C.str.contains("XYZ") == False]

rawDescription: How to drop rows from pandas data frame that contains a particular string in a particular column?

description: Drop rows from pandas data frame that contains a particular string in a particular column


code:
@login_required
def upload_view(request):

    print_setting = []  # or list()

    template_var = {}
    settings = Tracks.objects.filter(album__exact=None).values_list('file', flat=True)
    for setting in settings:
        list_setting = setting.split("/", 4)

        print_setting.append(str(list_setting[4]))

        template_var["trackfiles"] = print_setting
        pprint.pprint(template_var["trackfiles"])
    return render_to_response('tracks/test.html', template_var, context_instance=RequestContext(request))

rawDescription: list output in template

description: List output in template


code:
import re

def searchReplace(file, search, replace):
    with open (file,'r') as f:
        f_content= f.read()
    # Re to search and replace
    f_content = (re.sub(search, replace, f_content))
    #write file with replaced content
    with open (file,'w') as f:
        f.write(f_content)

searchReplace("file.txt","sys.test1.pwd = 1234","sys.test1.pwd = 4321")

rawDescription: How to replace the data into a line of a file?

description: Replace the data into a line of a file


code:
job = Job.objects.get(pk=1)
array_result = serializers.serialize('json', [job], ensure_ascii=False)
just_object_result = array_result[1:-1]

rawDescription: Django serializer for one object

description: Django serializer for one object


code:
x = np.array([[3,5,9],[6,0,7],[2,3,4]])
m = np.array([[1,1,2],[2,1,1],[2,1,2]])
indices = np.where(m == 1)  # indices contains two arrays, the column and row indices
values = x[indices]

rawDescription: Return the indices of unmasked elements that are both zero and not zero


code:
# Returns True if point yt is in the range (y0, y1) inclusive
def _in(yt, y): return y[0] <= yt <= y[1]

# Returns True if either segment intersects (or is contained in the other), False otherwise
def intersects(s1, s2): return _in(s1[0], s2) or _in(s1[1], s2) or _in(s2[0], s1) or _in(s2[1], s1)

# Returns an (i,e) tuple for each element e of lst that "intersects" (see prev. function) list lst
#   i is index of element e in lst
def find_intersections(s, lst): return [(i,e) for (i,e) in enumerate(lst) if intersects(s,e)]

# Returns a 2-tuple containing the minimum and maximum of the input segments s1, s2
def merge(s1, s2): return (min(s1[0], s2[0]), max(s1[1], s2[1]))
# Note: The functions _in and merge assume that y0,y1 are sorted, ascending

data = { (622, 633): 'text1', (604, 619) : 'text2', (596, 633) : 'text3', (577, 587) : 'text4', (551, 587) : 'text5'  }
new_data = {}

lst = list(data.keys())
while len(lst):
    rng = lst.pop()

    keys = [rng,]
    while True:
        updated = False
        for (i,match) in find_intersections(rng, lst):
            updated = True
            keys.append(match)
            rng = merge(rng, match)
            lst.pop(i)
        if not updated: break

    new_data[rng] = ' '.join(sorted(data[k] for k in keys))

print(new_data)      # {(551, 587): 'text4 text5', (596, 633): 'text1 text2 text3'}

rawDescription: python 3 how to compress a dictionary with tuple keys representing overlapping coordinates

description: Python 3 how to compress a dictionary with tuple keys representing overlapping coordinates


code:
from tqdm import trange
from time import sleep
t = trange(100, desc='Bar desc', leave=True)
for i in t:
    t.set_description("Bar desc (file %i)" % i)
    sleep(0.01)

rawDescription: can I add message to the tqdm progressbar

description: Add message to the tqdm progressbar


rawDescription: Python 3.4 Pandas DataFrame Structuring

description: Python 3.4 Pandas DataFrame Structuring


code:
from M2Crypto import RSA
RSA.load_key('mykey.pem').save_pub_key('mykey.pub')

rawDescription: extracting public key from private key dynamically using M2Crypto

description: Extracting public key from private key dynamically using M2Crypto


code:
import subprocess
import time

p = None
while True:
   if p and p.poll() is None:
       print("Process is currently running. Do nothing.")
   else:  # No process running
       if p:  # We've run the process at least once already, so get the result.
           ret = p.returncode
           print("Last run returned {}".format(ret))
       p = subprocess.Popen(["some_command", "some arg"])
   time.sleep(3)  # Wait a few seconds before iterating again.

rawDescription: stop subprocess from initiating a process more than once

description: Stop subprocess from initiating a process more than once


code:
from Tkinter import *

class App(Tk):
    def __init__(self, *args, **kargs):
        Tk.__init__(self, *args, **kargs)
        self.focused_box = None
        for i in range(4):
            box = Listbox(self)
            box.pack()
            box.insert(END, "box item #1")
            box.bind("<FocusIn>", self.box_focused)
            box.bind("<FocusOut>", self.box_unfocused)

        button = Button(text="add item to list", command=self.add_clicked)
        button.pack()

    #called when a listbox gains focus
    def box_focused(self, event):
        self.focused_box = event.widget

    #called when a listbox loses focus
    def box_unfocused(self, event):
        self.focused_box = None

    #called when the user clicks the "add item to list" button
    def add_clicked(self):
        if not self.focused_box: return
        self.focused_box.insert(END, "another item")

App().mainloop()

rawDescription: Python tkinter to modify only listbox with focus


code:
import gphoto2 as gp
from gi.repository import Gio, GdkPixbuf
camera = gp.Camera()
context = gp.Context
camera.init(context)
file = gp.CameraFile()
camera.capture_preview(file, context)
data = memoryview(file.get_data_and_size())
loader = GdkPixbuf.PixbufLoader.new()
loader.write(data)
pixbuf = loader.get_pixbuf()
# use the pixbuf
loader.close()

rawDescription: Python PyGObject pixbuf memory leak

description: Python PyGObject pixbuf memory leak


code:
img = PIL.Image.new("RGB", (12, 12))
img.show() # see a black image
pixels = [(255,0,0)]*(12*12)
img.putdata(pixels)
img.show() # see a red image

rawDescription: Python loop for image and pil module

description: Python loop for image and pil module


code:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3
import matplotlib.animation as animation

def make_helix(n):
    theta_max = 8 * np.pi
    theta = np.linspace(0, theta_max, n)
    x, y, z = theta, np.sin(theta), np.cos(theta)
    helix = np.vstack((x, y, z))

    return helix

def update_lines(num, dataLines, lines) :
    for line, data in zip(lines, dataLines) :
        line.set_data(data[0:2, num-1:num])
        line.set_3d_properties(data[2,num-1:num])
    return lines

# Attach 3D axis to the figure
fig = plt.figure()
ax = p3.Axes3D(fig)

n = 100
data = [make_helix(n)]

lines = [ax.plot(data[0][0,0:1], data[0][1,0:1], data[0][2,0:1], 'o')[0]]

# Setthe axes properties
ax.set_xlim3d([0.0, 8*np.pi])
ax.set_xlabel('X')

ax.set_ylim3d([-1.0, 1.0])
ax.set_ylabel('Y')

ax.set_zlim3d([-1.0, 1.0])
ax.set_zlabel('Z')

ax.set_title('3D Test')

# Creating the Animation object
ani = animation.FuncAnimation(fig, update_lines, n, fargs=(data, lines),
                              interval=50, blit=False)
plt.show()

rawDescription: Animating the motion of a particle in 3D in Python


code:
#!/usr/bin/env python
# coding=utf-8
from collections import Iterator, deque
import threading

class ForkableIterator(Iterator):
    def __init__(self, iterator, buffer=None, *args, **kwargs):
        self.iterator = iter(iterator)
        if buffer is None:
            self.buffer = deque()
        else:
            self.buffer = buffer

        args = iter(args)

        self.refs = kwargs.get('refs', next(args, {}))
        self.refs.setdefault('base', 0)
        self.pointer = kwargs.get('pointer', next(args, 0))
        self.lock = kwargs.get('lock', next(args, threading.Lock()))

    @property
    def pointer(self):
        return self.refs[self] + self.refs['base']

    @pointer.setter
    def pointer(self, value):
        self.refs[self] = value

    def __del__(self):
        del self.refs[self]

    def __iter__(self):
        return self

    def next(self):
        with self.lock:
            if len(self.buffer) - self.pointer == 0:
                elem = next(self.iterator)
                self.buffer.append(elem)
            else:
                if self.pointer == min(self.refs.itervalues()):
                    elem = self.buffer.popleft()
                    self.refs['base'] -= 1
                else:
                    elem = self.buffer[self.pointer]

            self.pointer += 1

            return elem

    def fork(self):
        return self.__class__(self.iterator, self.buffer,
                              refs=self.refs, pointer=self.pointer,
                              lock=self.lock)

rawDescription: Forkable iterator - is there any implementations of it in Python?


code:
FIELD_NAME_MAPPING = {
    'field1': 'html_field1',
    'field2': 'html_field2'
}

class MyForm(forms.ModelForm):
    def add_prefix(self, field_name):
        # look up field name; return original if not found
        field_name = FIELD_NAME_MAPPING.get(field_name, field_name)
        return super(MyForm, self).add_prefix(field_name)

rawDescription: Override Django form field's name attr

description: Override Django form field's name attr


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

def zipdir(path, ziph):
    # ziph is zipfile handle
    for root, dirs, files in os.walk(path):
        for file in files:
            ziph.write(os.path.join(root, file))

if __name__ == '__main__':
    zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
    zipdir('tmp/', zipf)
    zipf.close()

rawDescription: How to create a zip archive of a directory

description: Create a zip archive of a directory


rawDescription: Python smoothing data

description: Python smoothing data


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

def readColors(ifile):
    """Read colors from input file and return a python list with all them"""
    a = []
    fd = open(ifile,"r")
    for i in fd:
        if not i.startswith('//'):
            a.append(i)
    return a

def rgb2html(col):
    """Converts a color: from (255,255,255) to #ffffff"""
    r,g,b = col
    return "#%x%x%x" % (r,g,b)

def html2rgb(col):
    """Converts a color: from #ffffff to (255,255,255)"""
    s=col.strip('#')
    r=int(s[:2],16)
    g=int(s[2:4],16)
    b=int(s[4:6],16)
    return r,g,b

def nextColor():
    """Gets next html color from color list"""
    col = html2rgb(nextColor.array[nextColor.counter])
    nextColor.counter +=1
    return col

def isNextColor():
    """Is there another color or list is over?"""
    return nextColor.counter<isNextColor.colorslenght

def isPageEnded(y,sizey):
    """Is there enough room to draw another square?"""
    return (y+100)>=sizey

def newPage(sizex,sizey):
    """Returns a new image"""
    image = pdb.gimp_image_new(sizex, sizey, RGB)
    layer = pdb.gimp_layer_new(image, sizex, sizey, RGB, "layer", 0, 0)
    pdb.gimp_image_add_layer(image, layer, 0)
    drw = pdb.gimp_image_active_drawable(image)
    pdb.gimp_context_set_background((255,255,255))
    pdb.gimp_drawable_fill(drw, BACKGROUND_FILL)
    pdb.gimp_context_set_brush('Circle (01)')
    return image

def savePage(image,filename):
    """Saves composed image to filename"""
    layers = image.layers
    last_layer = len(layers)-1
    try:
        disable=pdb.gimp_image_undo_disable(image)
        pdb.gimp_layer_add_alpha(layers[0])
        pdb.plug_in_colortoalpha(image,image.active_layer,(0,0,0))
        layer = pdb.gimp_image_merge_visible_layers(image, 1)
        enable = pdb.gimp_image_undo_enable(image)
        pdb.file_png_save(image, image.active_layer, filename, filename, 0,9,1,0,0,1,1)
    except Exception as e:
        raise e

def drawRect(x,y,color,image):
    """draw a single square"""
    text = rgb2html(color)
    pdb.gimp_image_select_rectangle(image, 2, x, y, 100, 100)
    pdb.gimp_context_set_background(color)
    pdb.gimp_edit_fill(image.active_layer, 1)
    try:
        text_layer = pdb.gimp_text_fontname(image, None, x, y+(100/2), text, 2, 1, 18, 0, "Sans")
        pdb.gimp_image_merge_down(image, text_layer, 0)
    except Exception as e:
        raise e

def draw(ifile,odir,prefix,sizex,sizey):
    """Main method. it manage page's room, slicing it in several 100x100 squares"""
    colorArray = readColors(ifile)
    nextColor.counter = 0
    nextColor.array = colorArray
    isNextColor.colorslenght = len(colorArray)
    pc = x = y = 0
    image = newPage(sizex,sizey)
    try:
        while(isNextColor()):
            pdb.gimp_context_push()
            drawRect(x,y,nextColor(),image)
            x += 100#cambia colonna
            if x+100>=sizex:#cambia riga
                x = 0
                y += 100
            if isPageEnded(y,sizey):#salva pagina
                savePage(image,odir+'\\'+prefix+str(pc)+".png")
                pc += 1
                image = newPage(sizex,sizey)
                x = y = 0
            savePage(image,odir+'\\'+prefix+str(pc)+".png")
            pdb.gimp_context_pop()
    except Exception as e:
        raise e

register(
    "draw-colors",
    N_("Create a color map from a text color file"),
    "Create a color map from a text color file",
    "Alberto",
    "@Copyright Alberto 2014",
    "2014/10/21",
    N_("Draw Colors..."),
    "",
    [
        (PF_FILE, "ifile", N_("Color input file:"), 'default\\input\\colorfile\\path\\colorlist.txt'),

        (PF_DIRNAME, "odir", N_("Path for png export:"), 'default\\output\\path'),
        (PF_STRING, "prefix",  N_("Filename prefix for export:"),  "table"),
        (PF_INT8, "sizex", N_("Image's x size:"), 1024),
        (PF_INT8, "sizey", N_("Image's y size:"), 1024)
    ],
    [],
    draw,  #main method call
    menu="<Image>/Filters/Alberto",
    domain=("gimp20-python", gimp.locale_directory)
    )

main()

rawDescription: python-fu Copy an Image

description: Python-fu Copy an Image


code:
import string
my_string = my_string.rstrip(string.ascii_letters + string.whitespace)

rawDescription: Python remove last character of string if its a letter


code:
from astropy.io import fits

new_hdul = fits.HDUList()
new_hdul.append(fits.PrimaryHDU(header=headermain))
new_hdul.append(fits.ImageHDU(data1, header=header1, name='name1'))
new_hdul.append(fits.ImageHDU(data2, header=header2, name='name2'))

new_hdul.writeto('test.fits', clobber=True)

rawDescription: Save 2 fits files with 3 headers astropy or pyfits


code:
from sqlalchemy import func

session.query(Item.item_name, func.replace(Item.item_name, '-', '').label('new_name')).filter(func.replace(Item.item_name, '-', '').like('ABC%')).all()

rawDescription: In sqlalchemy, how would I query a table, filtering on a translation of a column?


code:
instructions = {
  '+': increment,
  '-': decrement,
  # Other functions
}

def run(tape):
  ch = next_token(tape)
  if ch in instructions:
    instructions[ch]()

rawDescription: Better way to implement interpreter in Python


code:
class FooManager(BaseManager):

    def no_bar(self):
        return self.get_queryset().filter(bar__isnull=True)

rawDescription: Django Queryset filter checks if related objects exist


code:
np.fill_diagonal(matrix[:-1, 1:], upper)
np.fill_diagonal(matrix[1:, :-1], lower)
matrix

rawDescription: Is there a function in numpy to replace lower and upper diagonal values of a numpy array?


code:
import random

list_of_words = ["apple", "table", "words", "beers", "plural", "hands"]
word = random.choice(list_of_words)

# changed the loop to a 'while', because i don't want to count the invalid length answers
# and wanted to exit the loop, when the user guessed correctly
attempts = 5
attempt = 0
correct = False
while attempt < attempts and not correct:
    if attempt == 0:
        # i stored a working copy of the initial hint (ex: "w....")
        # i'll use this to store the previously correctrly guessed letters
        tempList = list(word[0] + ("." * 4))
        print("The first letter of the word we are looking for: %s" % "".join(tempList))

    answer = raw_input("What is the word we are looking for?:")
    if len(answer) != 5:
        print("Please enter a 5 letter word")
    else:
        if answer != word:
            # i simplified this loop to comparing the wordlist and answerlist and update templist accordingly
            wordlist = list(word)
            answerlist = list(answer)
            for i in range(min(len(wordlist), len(answerlist))):
                if wordlist[i] == answerlist[i]:
                    tempList[i] = wordlist[i]
            print(tempList)
        else:
            correct = True
            print("Correct, you have guessed the word in %s attempts" % (attempt + 1))
        attempt += 1

if answer != word:
    # also i used string formatting on your prints, so is prints as a string, and not as a tuple.
    print("Sorry maximum number of tries, the word is: %s" % word)

rawDescription: python improving word game

description: Python improving word game


code:
def form_invalid(self, form):
    return HttpResponseRedirect(self.get_success_url())

rawDescription: Django: CreateView fail_url

description: Django: CreateView fail_url


code:
fig,ax=plt.subplots()
x=linspace(0,10,1000)
x.plot(x,exp(-(x-pi)**2))
plt.draw()#this is required, or the ticklabels may not exist (yet) at the next step
labels = [ w.get_text() for w in ax.get_xticklabels()]
locs=list(ax.get_xticks())
labels+=[r'$\pi$']
locs+=[pi]
ax.set_xticklabels(labels)
ax.set_xticks(locs)
ax.grid()
plt.draw()

rawDescription: Adding a custom tick and label

description: Adding a custom tick and label


code:
import Image
import ImageDraw

img = Image.new("RGB", (400,400), "white")
draw = ImageDraw.Draw(img)

coords = [(100,70), (220, 310), (200,200)]
dotSize = 2

for (x,y) in coords:
    draw.rectangle([x,y,x+dotSize-1,y+dotSize-1], fill="black")

img.show()

rawDescription: PIL selection of coordinates to make an image


code:
data = response.read()
length = len(data)

rawDescription: Determine content-length using urllib2

description: Determine content-length using urllib2


code:
match = re.search("(?m)^jil[^\n]+?jil.*?$", subject, re.IGNORECASE)
if match:
    result = match.group()
else:
    result = ""

rawDescription: Python regex search (frustrated with regex)


code:
if len(sys.argv) > 2:
    filename = sys.argv[2]

rawDescription: Quoted string as optional argument to Python script


code:
def stuff():
    x = [100]
    def g():
        x[0] = x[0]*2
        return x[0]
    def h():
        x[0] = x[0]*4
        return x[0]
    return (g,h)
a, b = stuff()
print(a())

rawDescription: Using a closure with multiple functions without making variable global in Python


code:
allKeys = {}
for subdict in (LowKeys, MidKeys, ..., FlatHighKeys):
    allKeys.update(subdict)

notes = [allKeys[note] for note in notes]

rawDescription: Replace items in a list using a dictionary


code:
import sys
import os
import comtypes.client
in_file = os.path.abspath('')
out_file = os.path.abspath('yesblue') #name of output file added to the current working directory
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open('yesblue.doc') #name of input file
doc.SaveAs(out_file, FileFormat=16)  # output file format to Office word Xml default (code=16)
doc.Close()
word.Quit()

rawDescription: Reading a .doc extension file ,ElementTree


code:
for key, value in d2.iteritems():
    if key in d1:
        d1[key].append(value)

rawDescription: Python 2.7 append values to dictionary

description: Python 2.7 append values to dictionary


rawDescription: Quickest way to find nth largest value in a numpy Matrix


code:
df = df.unstack('Severity') # This is your current dataframe

df = df['Number of Vulnerabilities'][['moderate', 'high', 'critical']] # reoder
df.plot(kind='barh', stacked=True) #plot

rawDescription: Unstack a MultiIndex pandas DataFrame counter-clockwise instead of clockwise


code:
import subprocess
child = subprocess.Popen('nmap_command',stdout=subprocess.PIPE,shell=True)
output = child.communicate()[0]
# do your stuff with output

rawDescription: Create list from pexpect expect data

description: Create list from pexpect expect data


code:
from django import forms

from .models import MyModel

class MyForm(forms.ModelForm):
    """
    MyForm is a nice a simple ModelForm using
    labels from MyModel.
    """

    class Meta:
        model = MyModel
        fields = ['created', ]

# views.py
from django.views.generic.edit import CreateView
from django.core.urlresolvers import reverse_lazy

from .forms import MyForm

class MyObjCreate(CreateView):
    form_class = MyForm

rawDescription: Purpose of ugettext inside of Models

description: Purpose of ugettext inside of Models


code:
from paste.reloader import watch_file

#
# logic that puts list of your non-source file names suitable
# for open() into iterable non_source_file_list
#

for non_source_file in non_source_file_list:
    watch_file(non_source_file_name)

rawDescription: Python Paste and auto-restart on non Python source file change


code:
charOne = input("Please input your first character's name: ")
charTwo = input("Please input your second character's name: ")

chooseCharacter = input("What character do you want to use? (%s or %s): " % (charOne, charTwo))

rawDescription: How to include variables in a string?

description: Include variables in a string


code:
from threading import  Thread

def take_data():
    while 1:
        data = go_fetch_more_data()

data_thread = Thread(target=take_data)
data_thread.start()

while 1:
    sleep_seconds = random.randint(0, 60)
    time.sleep(sleep_seconds)
    toggle_power()

rawDescription: Asynchronous events in Python

description: Asynchronous events in Python


code:
result = numpy.empty(data.shape[0])
for i in range(len(data)):
    result[i] = foo(data[i])

rawDescription: Mapping functions of 2D numpy arrays

description: Mapping functions of 2D numpy arrays


code:
from mako.template import Template
from rst2pdf.createpdf import RstToPdf

mytext = """This is the first line
Then there is a second
Then a third
    How about an indent?

I'd like it to maintain the formatting."""

template = """
<%!
def wrap(text):
    return text.replace("\\n", "\\n| ")
%>

My PDF Document
===============

It starts with a paragraph, but after this I'd like to insert `mytext`.
It should keep the formatting intact.

| ${mytext | wrap}

"""

mytemplate = Template(template)
pdf = RstToPdf()
#print mytemplate.render(mytext=mytext)
pdf.createPdf(text=mytemplate.render(mytext=mytext),output='foo.pdf')

rawDescription: maintaining formatting of imported text with mako and rst2pdf

description: Maintaining formatting of imported text with mako and rst2pdf


code:
import csv

b = open('test.csv', 'wb')
a = csv.writer(b)

s = ''
with open ("book2.csv", "rb") as annotate:
    for col in annotate:

        ann = col.lower().strip('\n').split(",")
        s += ann[0] + ','
s = s[:-1] # Remove last comma

a.writerow([s])
b.close()

rawDescription: How to merge multiple rows into single cell in csv separated by comma using Python

description: Merge multiple rows into single cell in csv separated by comma using Python


code:
def app_path():
    """Returns the base application path."""
    if hasattr(sys, 'frozen'):
        # Handles PyInstaller
        return os.path.dirname(sys.executable)
    return os.path.dirname(__file__)

rawDescription: wxPython to exe with PyInstaller?

description: WxPython to exe with PyInstaller


code:
my_dimensional_array = [(1,'a'),(1,'b'),(2,'c')]
[item for item in my_dimensional_array if item[0]==1]

rawDescription: Get subarray from bi-dimensional array in just one line


code:
def display():
    print('This program will tell you the area some shapes')
    print('You can choose between...')
    print('1. rectangle')
    print('or')
    print('2. triangle')

def shape():
    shap = int(input('What shape do you choose?'))
    if shap == 1: rectangle()
    elif shap == 2: triangle()
    else:
        print('ERROR: select either rectangle or triangle')
        shape()

def rectangle():
    l = int(input('What is the length?'))
    w = int(input('What is the width?'))
    areaR=l*w
    print('The are is...')
    print(areaR)

def triangle():
    b = int(input('What is the base?'))
    h = int(input('What is the height?'))
    first=b*h
    areaT=.5*first
    print('The area is...')
    print(areaT)

if __name__=="__main__":
    display() #cal display to execute it
    shape() #cal shape to execute it

rawDescription: Tell me whats wrong with this python code?


code: pat1 = re.compile("CREATE TABLE .+ FROM (\w+)\..+")

rawDescription: Finding groups in Regex - Python

description: Finding groups in Regex - Python


code:
from itertools import groupby
from operator import itemgetter

key = itemgetter(0)

maxprices = {id_: max(g)[1] for id_, g in groupby(sorted(pairs, key=key), key=key)}

rawDescription: Finding the maximum value of an id:value pair in an tuple when there are multiple of the same ids


code:
import ftplib

ftp_srv = 'ftp.example.com'
ftp_usr = 'user'
ftp_pass = 'password'

ftp = ftplib.FTP(ftp_srv)
ftp.login(ftp_usr, ftp_pass)

files = [('remote_file1', 'local_file1'), ('remote_file2', 'local_file2')]

for file_ in files:
    with open(file_[1], "wb") as f:
        ftp.retrbinary("RETR " + file_[0], f.write)
ftp.quit()

rawDescription: Python - download a file from a ftp server to a different local name


code:
class collection_details(osv.osv):
 _name = "collection.details"
 _description = "Collection Details"
 _columns={
    'state': fields.selection([
            ('draft', 'Draft Sales Order'),
            ('done', 'Done'),
            ], 'Status', readonly=True, invisible=True, track_visibility='onchange',
            help="", select=True),
    'client_id': fields.char('Client Id',size=64,readonly=True,states={'draft': [('readonly', False)]}),
 }
 _defaults = {
        'state': 'draft',
    }

rawDescription: Readonly field is not saving in database in openerp?


code:
x
x.reshape(-1, 1).tolist()

rawDescription: How to convert array to list?

description: Convert array to list


code:
font = self.menuBar().font()
font.setPointSize(20)
self.menuBar().setFont(font)

rawDescription: How to resize the QMenuBar in PyQt4 for a 4K display

description: Resize the QMenuBar in PyQt4 for a 4K display


rawDescription: Why is `if` so much faster when checked before a statement than after a statement?


code: zlib.decompress(inf, 16+zlib.MAX_WBITS)

rawDescription: Zip, Encrypted, Gziped files with Python


code:
while count==1 or returnValue['again'] == 1:
    returnValue = draw()

rawDescription: Calling a function multiple times with return value


code:
def ordertest(A):
    for i in xrange(len(A) - 1):
        if A[i]<A[i+1]:
            return False

    return True

rawDescription: Determine if a list is in descending order


rawDescription: How do I set a variable to quotations in python?

description: Set a variable to quotations in python


code:
for row in result:
    email, url, date = row
    # here you can format date as you want

rawDescription: python tuple returns datetime.datetime

description: Python tuple returns datetime.datetime


rawDescription: How to plot in python where x-axis values appears more than once, like 0 1 2 3 2 1 0

description: Plot in python where x-axis values appears more than once, like 0 1 2 3 2 1 0


code:
import sys
import time
import itertools

for c in itertools.cycle('/-\|'):
    sys.stdout.write('\r' + c)
    sys.stdout.flush()
    time.sleep(0.2)

rawDescription: python script to show progress

description: Python script to show progress


code:
def hide():
    btn1.grid_forget()
    btn1.after(2000,hide)

def show():
    btn1.grid(row=0,column=0)
    btn1.after(3000,show)

root = Tk()

root.geometry("350x150+400+400")

c=random.randint(20,40)

btn1 = Button(root, bd=c, text="Hello\nWorld",
              relief="ridge", cursor="trek")
btn1.grid(row=0,column=0)

btn1.after(2000,hide)
btn1.after(3000,show)

root.mainloop()

rawDescription: Python 3.4 tkinter button

description: Python 3.4 tkinter button


code: random_key = os.urandom(16)

rawDescription: How to generate strong one time session key for AES in python

description: Generate strong one time session key for AES in python


code: subprocess.call(["mv"] + unpack + ["/destination_path"])

rawDescription: Unpack list of strings inside another list of strings


code:
def find_sequence_in_list(list_to_check, values):
    for i in range (len(list_to_check) - len(values) + 1):
        #print(list_to_check[i:i + len(values)])
        if list_to_check[i:i + len(values)] == values:
            return True

    return False

values = [1, 2, 3]
data1 = [1, 1, 2, 3, 1]
data2 = [1, 1, 4, 3, 1, 2, 1]

print(find_sequence_in_list(data1, values))
print(find_sequence_in_list(data2, values))

rawDescription: Python check next three elements in list


code:
qc1 = QuestionContent()
qc1.append_field('Title','DATE:')

constraints1 = [RegExConstraint("***REGEX HERE****",
                                error_text="ERROR.",
                                flags='i')]

fta1 = FreeTextAnswer(constraints=constraints, default="", num_lines=1)

q1 = Question(identifier="date",
              content=qc1,
              answer_spec=AnswerSpecification(fta1))

rawDescription: Add AnswerFormatRegex constraint to Mechanical Turk item using BOTO


rawDescription: Python Celery - Switch TaskRegistry implementation


code:
from django.db.models import Q
Advertisement.objects.filter( Q(name = 'Paris') | Q(name = 'New York') )

rawDescription: Make filters of an object list

description: Make filters of an object list


code:
df
rest = df.groupby(['Team'])['Date'].diff() - datetime.timedelta(1)
df['HomeRest'] = rest[df.HomeTeam]
df['AwayRest'] = rest[~df.HomeTeam]
df

rawDescription: python pandas timedelta specific rows

description: Python pandas timedelta specific rows


code:
tags = self.request.get('tags').split(',')
img_ref.tags.extend(tags)
img_ref.put()

rawDescription: adding to StringListProperty

description: Adding to StringListProperty


code:
import datetime

format = '%Y%m%d%H%M%S%f'
dt1 = datetime.datetime.strptime(str(t1), format)
dt2 = datetime.datetime.strptime(str(t2), format)

difference = (dt2 - dt1).total_seconds()

rawDescription: Find difference between dates in YYYYmmddHHMMSSfraction format


rawDescription: open a file which name is contained in a variable

description: Open a file which name is contained in a variable


code:
import pandas
y = pandas.Series([2,3])
x = pandas.Series([4,5])
z = pandas.DataFrame([x,y])
z
z.loc[3,3] = 6
z

rawDescription: Equivalent of adding a value in a new row/column to numpy that works like R's data.frame


code:
if os.fork():
    sys.exit()
# Child code goes here

rawDescription: Bring the current Python program to background


code:
import operator

def search(request):
    terms = request.GET.get('search', '').split(' ')
    q_list = []
    for term in terms:
        if term:
            q_list.append(Q(title__contains=query))
            q_list.append(Q(author__contains=query))
            q_list.append(Q(description__contains=query))
            q_list.append(Q(reagents__contains=query))
            q_list.append(Q(protocol_steps__contains=query))

    if q_list:
        results = Protocol.objects.filter(reduce(operator.or_, q_list))
    else:
        results = ''
    return render(request, 'protocat_app/search_protocols.html',{'results':results})

rawDescription: searching textfield for each keyword

description: Searching textfield for each keyword


code:
my_dict = {'zebra':1, 'the':201, 'apple':1, 'chicken':58}
sorted(my_dict.items(), key=lambda x: (-x[1], x[0]))

rawDescription: Sorting a dictionary by REVERSE VALUE then NON-REVERSE KEY


code:
from google.appengine.api import xmpp
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

class FooHandler(webapp.RequestHandler):
    def get(self):
        xmpp.send_invite('example@gmail.com')

application = webapp.WSGIApplication([('.*', FooHandler)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: To send Chat Invitation, to GTalk using Google App Engine(Python)?


code:
player = None

def video():
    global player
    form = VideoForm()
    if form.validate_on_submit():
        url = form.url.data
        vid_output = form.vid_output.data
        player = Player(url=url, output=vid_output)

def video_pause():
    global player
    if not player:
        return
    player.toggle_pause()

def video_stop():
    global player
    if not player:
        return
    player.exit_omx_player()
    player = None

rawDescription: Python Flask persistent object between requests


rawDescription: How to convert a list of tuples into different csv files

description: Convert a list of tuples into different csv files


code:
# the array passed into your function
ax = NP.random.randint(10, 99, 20).reshape(5, 4)

# just define a function to operate on some data
fnx = lambda x : NP.sum(x)**2

# apply the function directly to the numpy array
new_row = NP.apply_along_axis(func1d=fnx, axis=0, arr=ax)

# 'append' the new values to the original array
new_row = new_row.reshape(1,4)
ax = NP.vstack((ax, new_row))

rawDescription: Building up an array in numpy/scipy by iteration in Python?


code:
import sys
from PyQt5.QtCore import QRect, QRectF, QSizeF, QPointF, Qt
from PyQt5.QtGui import QPainter, QPicture, QFont, QColor
from PyQt5.QtWidgets import QApplication, QLabel

def drawNode(painter, angle, radius, text):
    size = 32767.0;
    painter.save();
    painter.rotate(-angle);
    painter.translate(radius, 0);
    painter.drawText(QRectF(0, -size/2.0, size, size), Qt.AlignVCenter, text);
    painter.restore();

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

    pic = QPicture()
    pic.setBoundingRect(QRect(-100, -100, 200, 200))
    p = QPainter(pic)

    p.drawEllipse(0, 0, 3, 3)
    p.setFont(QFont("Helvetica", 25))
    for angle in range(0, 359, 30):
        drawNode(p, angle, 50, str(angle))
    p.end()

    l = QLabel()
    l.setPicture(pic);
    l.show();

    sys.exit(app.exec_())

rawDescription: creating a text wheel QT/PYQT

description: Creating a text wheel QT/PYQT


code:
def descendants(aclass):
  directones = aclass.__subclasses__()
  if not directones: return
  for c in directones:
    yield c
    for x in descendants(c): yield x

rawDescription: Finding all classes that derive from a given base class in python


code:
import sys
reload(sys)
sys.setdefaultencoding('UTF8')

rawDescription: Pandas UTF-8 Write to Excel Issue on Windows Only


code:
def touchSensor(self):
    self.after_idle(self.touchSensorLoop, time.time())

def touchSensorLoop(self, time_at_program_start):
    self.myObject.setOutputState(0, False)
    if time.time() - time_at_program_start < 30:
        if self.myObject.getSensorValue(2) > 900:
            self.myObject.setOutputState(0, True)
            self.after(2000, self.touchSensorLoop, time_at_program_start)
        else:
            self.after_idle(self.touchSensorLoop, time_at_program_start)

rawDescription: Making a Tkinter button do something while the program is within a loop


rawDescription: Reshape using a shape which is not a divisible factor of length of the list


code:
import ast

...

with open("/path/to/file", "r") as data:
    dictionary = ast.literal_eval(data.read())

rawDescription: How to read dictionary data from a file in python?

description: Read dictionary data from a file in python


code:
from django.db.models import Max

lettersAll = Letter.objects.filter(
        item=i_iID,
        deleted__isnull=True
    ).annotate(
        last_created_version=Max('letterversion_created')
    ).order_by('-last_created_version')[:3]

rawDescription: Django: Selecting model and ordering by sub-models create details


code:
def dual_pivot_sort(list, start, top):
    if top <= start:
        return
    p = start
    q = top
    k = p+1
    h = k
    l = q-1
    if list[p] > list[q]:
        list[p], list[q] = list[q], list[p]
    while k <= l:
    # the last non-check index is l,as l+1 to top - 1 is the part III,
    #where all elements > list[top]
        if list[k] < list[p]:
            list[h], list[k] = list[k], list[h]
            #h is the first element of part II
            h += 1
            #increase h by 1, for pointing to the first element of part II
            k += 1
            #increase k by 1, because we have checked list[k]
        elif list[k] > list[q]:
        #l is the last element of part IV
            list[k], list[l] = list[l], list[k]
            #don't increase k, as we have not check list[l] yet
            l -= 1
            #after swap, we should compare list[k] with list[p] and list[q] again
        else: k += 1
        # no swap, then the current k-th value is in part II, thus we plus 1 to k
    h -= 1#now,h is the last element of part I
    l += 1 #now, l is the first element of part III
    list[p], list[h] = list[h], list[p]
    list[q], list[l] = list[l], list[q]
    dual_pivot_sort(list, start, h-1)
    dual_pivot_sort(list, h+1, l-1)
    dual_pivot_sort(list, l+1, top)

rawDescription: how to implement dual-pivot quicksort in Python

description: Implement dual-pivot quicksort in Python


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

arr = np.genfromtxt('data', dtype=None)
n = len(arr)
centers = np.arange(n)
colors = cm.RdYlBu(np.linspace(0, 1, n))
pylab.bar(centers, arr['f0'], color=colors, align='center')
ax = pylab.gca()
ax.set_xticks(centers)
ax.set_xticklabels(arr['f1'], rotation=0)
pylab.show()

rawDescription: Python: plot data from a txt file

description: Python: plot data from a txt file


code: pandas.concat([df1, df2], axis=1)

rawDescription: Combine two Pandas dataframes with the same index


code: df.apply(lambda x: x.dropna().iloc[-2], axis=1)

rawDescription: Pandas Retrieve value from last [-kth] column before null


code:
def worker(self):
    cmd = ["/home/orlando/CountMem","400000000","2000"]
    p = subprocess.Popen(cmd,stdout=subprocess.PIPE)
    id_list = []
    id_list.append(p.pid)

    while len(id_list) > 0:
         for num in id_list:
             stat_file = open("/proc/{0}/status".format(num))
             mem_dict = {}
             for i, line in enumerate(stat_file):
                 if i == 3:
                    #print line
                     mem_dict['ID'] = line
                     print(mem_dict)
                 if i == 10:
                    #print line
                     mem_dict['Mem'] = line
                     print(mem_dict)
         p.poll()
    return id_list

if __name__ == '__main__':
    count = multiprocessing.cpu_count()
    pool = multiprocessing.Pool(processes = count)
    print(pool.map(worker,['ls']*count))

rawDescription: Get rid of zombie processes

description: Get rid of zombie processes


code:
import json
data=[{'total': 1744, 'name': u'x'}, {'total': 13, 'name': u'm'}, {'total': 126, 'name': u'n'}]
json.dumps([i.values()[::-1] for i in data])

rawDescription: django remove unicode from query result

description: Django remove unicode from query result


code:
def TopCloses():
    top.destroy()
    #Call the setTopLevel method and assign the attribute toplevel value None
    guiObject.setTopLevel(None)

top.protocol("WM_DELETE_WINDOW", TopCloses)
root.mainloop()

rawDescription: Prevent multiple toplevels from opening?

description: Prevent multiple toplevels from opening


code:
first = textViewer.GetFirstVisibleLine()
textViewer.ScrollToLine(first + n)

rawDescription: How can I get consistent behavior on my wxPython StyledTextControl?

description: Get consistent behavior on my wxPython StyledTextControl


code:
import platform
platform.uname()

rawDescription: Is there a reliable way to determine the system architecture using python?


code:
ctrl = br.form.find_control('ctl00$ContentPlaceHolder1$fooBar')
ctrl.disabled = True

rawDescription: How to remove a control in python - mechanize?

description: Remove a control in python - mechanize


code:
def login(request):
    """
    Check for login and store the result in login_successful
    """
    path = request.GET.get("next")
    if login_successful:
        if path:
            return HttpResponseRedirect(path)
        else:
            return HttpResponseRedirect(your_earlier_path)

rawDescription: Properly use 'next' paramater in URL, Django


code:
def dictelem(input):
    parts   = input.split('&')
    listing = [part.split('=') for part in parts]

    result = {}
    for entry in listing:
        head, tail = entry[0], ''.join(entry[1:])
        if ':' in tail:
            entries = tail.split(',')
            result.update({ head : dict(e.split(':') for e in entries) })
        else:
            result.update({head: tail})

    return result

rawDescription: Parse string with three-level delimitation into dictionary


code:
def in_box(X, B):
    """
    Takes an Nx2 NumPy array of points and a 4x2 NumPy array of corners that
    form an axis aligned box.
    """
    xmin = B[:,0].min(); xmax = B[:,0].max()
    ymin = X[:,1].min(); ymax = X[:,1].max()
    return X[X[:,0] > xmin & X[:,0] < xmax & X[:,1] > ymin & X[:,1] < ymax]

rawDescription: Python point lookup (coordinate binning?)


code: hex(int(string1, 16) ^ int(string2, 16))

rawDescription: How to XOR two hex strings in Python 3?

description: XOR two hex strings in Python 3


code:
import datetime
x = '2015-01-01'
date = datetime.datetime.strptime(x, "%Y-%m-%d")
print(date.date())

rawDescription: Date format without hour, minutes and seconds


code:
toflip = []
for x, y in [(0,1), (1,1), (1,0), (1,-1), (0,-1), (-1,-1), (-1,0), (-1,1)]: # directions
    try:
        potential_flips = []
        for d in range(1,10):  # distances
            if boardArray[row+y*d][col+x*d] == self._playerTurn: # friendly piece found
                toflip.extend(potential_flips)
                break
            elif boardArray[row+y*d][col+x*d] == 3-self._playerTurn: # other player's piece
                potential_flips.append((col+x*d, row+y*d))
            else: # empty square found, give up on this direction
                break
    except IndexError: # ran off an edge of the board before finding a friendly piece
        pass
if toflip: # valid move, causes some of the opponents pieces to be flipped
    for x, y in toflip:
        boardArray[y][x] = self._playerTurn
else: # invalid move, doesn't flip anything
    raise ValueError("invalid move") # or report an error code some other way

rawDescription: Easier way to search all directions of a 2D list?


code: package_dir = {'': 'src'},

rawDescription: how can I make pip/setuptools understand that my package is in ./src?

description: Make pip/setuptools understand that my package is in ./src


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

def show_values(pc, fmt="%.2f", **kw):
    '''
    Heatmap with text in each cell with matplotlib's pyplot
    Source: http://stackoverflow.com/a/25074150/395857
    By HYRY
    '''
    from itertools import izip
    pc.update_scalarmappable()
    ax = pc.get_axes()
    for p, color, value in izip(pc.get_paths(), pc.get_facecolors(), pc.get_array()):
        x, y = p.vertices[:-2, :].mean(0)
        if np.all(color[:3] > 0.5):
            color = (0.0, 0.0, 0.0)
        else:
            color = (1.0, 1.0, 1.0)
        ax.text(x, y, fmt % value, ha="center", va="center", color=color, **kw)

def cm2inch(*tupl):
    '''
    Specify figure size in centimeter in matplotlib
    Source: http://stackoverflow.com/a/22787457/395857
    By gns-ank
    '''
    inch = 2.54
    if type(tupl[0]) == tuple:
        return tuple(i/inch for i in tupl[0])
    else:
        return tuple(i/inch for i in tupl)

def heatmap(AUC, title, xlabel, ylabel, xticklabels, yticklabels, figure_width=40, figure_height=20, correct_orientation=False, cmap='RdBu'):
    '''
    Inspired by:
    - http://stackoverflow.com/a/16124677/395857
    - http://stackoverflow.com/a/25074150/395857
    '''

    # Plot it out
    fig, ax = plt.subplots()
    #c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap='RdBu', vmin=0.0, vmax=1.0)
    c = ax.pcolor(AUC, edgecolors='k', linestyle= 'dashed', linewidths=0.2, cmap=cmap)

    # put the major ticks at the middle of each cell
    ax.set_yticks(np.arange(AUC.shape[0]) + 0.5, minor=False)
    ax.set_xticks(np.arange(AUC.shape[1]) + 0.5, minor=False)

    # set tick labels
    #ax.set_xticklabels(np.arange(1,AUC.shape[1]+1), minor=False)
    ax.set_xticklabels(xticklabels, minor=False)
    ax.set_yticklabels(yticklabels, minor=False)

    # set title and x/y labels
    plt.title(title)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)

    # Remove last blank column
    plt.xlim( (0, AUC.shape[1]) )

    # Turn off all the ticks
    ax = plt.gca()
    for t in ax.xaxis.get_major_ticks():
        t.tick1On = False
        t.tick2On = False
    for t in ax.yaxis.get_major_ticks():
        t.tick1On = False
        t.tick2On = False

    # Add color bar
    plt.colorbar(c)

    # Add text in each cell
    show_values(c)

    # Proper orientation (origin at the top left instead of bottom left)
    if correct_orientation:
        ax.invert_yaxis()
        ax.xaxis.tick_top()

    # resize
    fig = plt.gcf()
    #fig.set_size_inches(cm2inch(40, 20))
    #fig.set_size_inches(cm2inch(40*4, 20*4))
    fig.set_size_inches(cm2inch(figure_width, figure_height))

def plot_classification_report(classification_report, title='Classification report ', cmap='RdBu'):
    '''
    Plot scikit-learn classification report.
    Extension based on http://stackoverflow.com/a/31689645/395857
    '''
    lines = classification_report.split('\n')

    classes = []
    plotMat = []
    support = []
    class_names = []
    for line in lines[2 : (len(lines) - 2)]:
        t = line.strip().split()
        if len(t) < 2: continue
        classes.append(t[0])
        v = [float(x) for x in t[1: len(t) - 1]]
        support.append(int(t[-1]))
        class_names.append(t[0])
        print(v)
        plotMat.append(v)

    print('plotMat: {0}'.format(plotMat))
    print('support: {0}'.format(support))

    xlabel = 'Metrics'
    ylabel = 'Classes'
    xticklabels = ['Precision', 'Recall', 'F1-score']
    yticklabels = ['{0} ({1})'.format(class_names[idx], sup) for idx, sup  in enumerate(support)]
    figure_width = 25
    figure_height = len(class_names) + 7
    correct_orientation = False
    heatmap(np.array(plotMat), title, xlabel, ylabel, xticklabels, yticklabels, figure_width, figure_height, correct_orientation, cmap=cmap)

def main():
    sampleClassificationReport = """             precision    recall  f1-score   support

          Acacia       0.62      1.00      0.76        66
          Blossom       0.93      0.93      0.93        40
          Camellia       0.59      0.97      0.73        67
          Daisy       0.47      0.92      0.62       272
          Echium       1.00      0.16      0.28       413

        avg / total       0.77      0.57      0.49       858"""

    plot_classification_report(sampleClassificationReport)
    plt.savefig('test_plot_classif_report.png', dpi=200, format='png', bbox_inches='tight')
    plt.close()

if __name__ == "__main__":
    main()
    #cProfile.run('main()') # if you want to do some profiling

rawDescription: How to plot scikit learn classification report?

description: Plot scikit learn classification report


code: values = ", ".join(["NULL" if x == "" else "\"%s\"" % x for x in row])

rawDescription: List comprehension with if-condition

description: List comprehension with if-condition


code:
#in mymoduleforthisuglysolution.py
from threading import local

mylocal = local()

#in your middleware definition file
from mymoduleforthisuglysolution import mylocal

class DefinedRouteDataBase(object):

    def process_request(self, request):
        #if request.method == 'POST':
        #    request.COOKIES['token'] = request.POST['token']
        #    print ('Middlewares:', str(request.COOKIES['token']))
        mylocal.request = request
        return None

#in your router definition file
from mymoduleforthisuglysolution import mylocal

class DatabaseAppsRouter(object):

    def db_for_read(self, model, **hints):
        print('Router R:')
        return mylocal.request.COOKIES['token'] if mylocal.request else 'default'

    def db_for_write(self, model, **hints):
        print ('Router W:')
        return 'default'

    def allow_relation(self, obj1, obj2, **hints):
        return None

    def allow_syncdb(self, db, model):
        return True

rawDescription: Using request.cookies in routeDataBase Django


code:
from scipy.ndimage.filters import gaussian_filter
arr=np.zeros((20,20))
arr[0,:]=3
arr[0,0]=20
arr[19,19]=30
arr[10:12,10:12]=10

filtered_arr=gaussian_filter(arr, sigma)
plt.imshow(filtered_arr)

rawDescription: smoothing imshow plot with matplotlib

description: Smoothing imshow plot with matplotlib


code:
import memcache

mc = memcache.Client(hosts, debug=1)

# to lock:
def request_lock(key, timeout=300):
    if mc == None:
        raise Exception("Memcache is not connected!")

    # just store a "1" in that location - this is an atomic operation so if two
    # nodes request a lock at the same time, only one of them will get a True
    return mc.add(key, "1", timeout)

# to unlock:
def request_unlock(key):
    if mc == None:
        raise Exception("Memcache is not connected!")

    return mc.delete(key) > 0

rawDescription: Is there a Python equivalent of Ruby's officer gem?


code:
def foo(df_of_grouped_data):
    group_length = len(df_of_grouped_data)

    if group_length == 1:
        return df_of_grouped_data
    else:
        dates = df_of_grouped_data['MODIFIED_DATE'].values
        if all_same(dates):
            return df_of_grouped_data[df_of_grouped_data.STATUS == '1']
        else:
            return df_of_grouped_data[df_of_grouped_data.MODIFIED_DATE == most_recent(dates)]

result = card_groups.apply(foo)

rawDescription: Operating on Pandas groups

description: Operating on Pandas groups


code:
screen = gtk.gdk.screen_get_default()
root = screen.get_root_window()
root.set_events(gtk.gdk.SUBSTRUCTURE_MASK)
root.add_filter(event_filter)

def event_filter(event, user_data):
        # process event
        return gtk.gdk.FILTER_CONTINUE

rawDescription: Python/X11: find out if user switches virtual desktops


code: np.random.exponential(5, size=10)

rawDescription: can python numpy poission generate a float?

description: Can python numpy poission generate a float


rawDescription: RTMP stream monitoring in python

description: RTMP stream monitoring in python


code:
grouped = {}
for k, v in zip(list2, list3):
    grouped.setdefault(k, []).append(v)
new_list = [grouped[k] for k in list1]

rawDescription: creating a list of lists based on same index and item

description: Creating a list of lists based on same index and item


code:
from django.contrib.sites.models import Site
Site.objects.get_current().domain
'http://%s/path/to/file.ext' % Site.objects.get_current().domain

rawDescription: equivalent of $_SERVER['HTTP_HOST'] of PHP in Python , or get domain name in python django

description: Equivalent of $_SERVER['HTTP_HOST'] of PHP in Python , or get domain name in python django


code:
def _check_unique_insesitive(self, cr, uid, ids, context=None):
    sr_ids = self.search(cr, 1 ,[], context=context)
    lst = [
            x.FIELD.lower() for x in self.browse(cr, uid, sr_ids, context=context)
            if x.FIELD and x.id not in ids
          ]
    for self_obj in self.browse(cr, uid, ids, context=context):
        if self_obj.FILD and self_obj.FILD.lower() in  lst:
            return False
    return True

_constraints = [(_check_unique_insesitive, 'Error: UNIQUE MSG', ['FIELD'])]

rawDescription: OpenERP Unique Constraint

description: OpenERP Unique Constraint


code:
import os
print(os.path.isdir("/home/el"))
print(os.path.exists("/home/el/myfile.txt"))

rawDescription: How to find if directory exists in Python

description: Find if directory exists in Python


code:
from PySide import QtCore, QtGui

class Program(QtGui.QWidget):
    def __init__(self):
        super(Program, self).__init__()
        self.textBrowser = QtGui.QTextBrowser(self)
        self.button = QtGui.QPushButton('Hide', self)
        self.button.clicked.connect(self.toggleTextBrowser)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.textBrowser)
        layout.addWidget(self.button)

    def toggleTextBrowser(self):
        if self.textBrowser.isHidden():
            self.button.setText('Hide')
            self.textBrowser.show()
            self.resize(461, 444)
        else:
            self.button.setText('Show')
            self.textBrowser.hide()
            self.resize(461, 200)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Program()
    window.setGeometry(500, 300, 461, 444)
    window.show()
    sys.exit(app.exec_())

rawDescription: PySide how to toggle visibility of QTextBrowser


code:
import pickle
import ast
pickle.loads(ast.literal_eval("'''" + cookies.values()[0] + "'''")[1:-1])

rawDescription: Requests dict from cookiejar issue with escaped chars


code:
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.db import models

class ThingTwo(models.Model):
    #Your stuff

    def clean(self):
        """
        Validate custom constraints
        """
        if self.use_thingone and self.thingone is None:
            raise ValidationError(_(u"Thing One is to be used, but it not set!"))

rawDescription: Require model field in admin site only if another model field is true


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.image as mimage
import scipy.misc as misc
import itertools as IT

height, width = 400, 400
nrows, ncols = 2, 4

# load some arrays into arrs
filenames = ['grace_hopper.png', 'ada.png', 'logo2.png']
arrs = list()
for filename in filenames:
    datafile = cbook.get_sample_data(filename, asfileobj=False)
    arr = misc.imresize(mimage.imread(datafile), (height, width))[..., :3]
    arrs.append(arr)
arrs = IT.islice(IT.cycle(arrs), nrows*ncols)

# make a big array
result = np.empty((nrows*height, ncols*width, 3), dtype='uint8')
for (i, j), arr in IT.izip(IT.product(range(nrows), range(ncols)), arrs):
    result[i*height:(i+1)*height, j*width:(j+1)*width] = arr

fig, ax = plt.subplots()
ax.imshow(result)
plt.show()

rawDescription: Multiple picture background matplotlib

description: Multiple picture background matplotlib


code:
def OnChar(self, evt):

    key = chr(evt.GetKeyCode())
    if ord(key) in [wx.WXK_BACK, wx.WXK_DELETE]:
        evt.Skip()
    if self.flag  == LETTERS and key not in string.ascii_letters:
        return
    if self.flag  == DECIMAL_DIGITS and key not in string.digits:
        return
    if self.flag  == HEX_DIGITS and key not in string.hexdigits:
        return
    if self.flag  == NUMERIC and key not in '0123456789.':
        return
    if self.flag  == DATE_TIME and key not in '0123456789/: ':
        return
    evt.Skip()

rawDescription: Check for BS (backspace) in User Input

description: Check for BS (backspace) in User Input


code:
class ModelAAdmin(admin.ModelAdmin):
    list_display = (..., 'get_valid_until')

    def get_valid_until(self, obj):
        return obj.modelb_set.last()
    get_valid_until.short_description = 'Valid until'

rawDescription: Access and display value from a related model in Django


code:
import pyx
c = pyx.canvas.canvas()
c.insert(pyx.epsfile.epsfile(0, 0, "1.eps", align="tl"))
c.insert(pyx.epsfile.epsfile(0,0,"2.eps", align="tr"))
c.writeEPSfile("combined.eps")

rawDescription: How can I automatically combine matplotlib graphs with Adobe Illustrator vector illustrations?

description: Automatically combine matplotlib graphs with Adobe Illustrator vector illustrations


rawDescription: How to find the common values in a particular column in a particular table and display the intersected output

description: Find the common values in a particular column in a particular table and display the intersected output


code:
urlpatterns = patterns('',
    url(r'^mysite/polls/', include('polls.urls', namespace="polls")),
    url(r'^mysite/admin/', include(admin.site.urls)),
)

rawDescription: Django Change Root URL

description: Django Change Root URL


code:
def textSearch(substring,overlapping):
    def parametrisedTextSearch(text):
        # Do Stuff. Can refer to substring and overlapping here.
        return index
    return parametrisedTextSearch

mySearch = textSearch(substring = whatever, overlapping = whatever)

mySearch("Pancakes")

rawDescription: Customizing a function at run-time based on parameters


code:
import boto3
s3 = boto3.client("s3")
all_objects = s3.list_objects(Bucket = 'my-bucket-name')

rawDescription: Retrieving subfolders names in S3 bucket from boto3


code:
def comment_handler(sender, comment, request, **kwargs):
    profile = request.user.get_profile()
    profile.points += 2
    profile.save()

from django.contrib.comments.signals import comment_was_posted
comment_was_posted.connect(comment_handler, sender=Comment)

rawDescription: How to use Post_save in Django

description: Use Post_save in Django


code:
class SomeClass(db.Model):
  item = None

class AnotherClass(db.Model):
  otherItem = db.ReferenceProperty(SomeClass)

SomeClass.item = db.ReferenceProperty(AnotherClass)

rawDescription: Referencing classes in Python

description: Referencing classes in Python


rawDescription: Exclude on a many-to-many relationship through a third table


code:
def _update(self, iterable):
    # The main loop for update() and the subclass __init__() methods.
    data = self._data

    # Use the fast update() method when a dictionary is available.
    if isinstance(iterable, BaseSet):
        data.update(iterable._data)
        return

    value = True

    if type(iterable) in (list, tuple, xrange):
        # Optimized: we know that __iter__() and next() can't
        # raise TypeError, so we can move 'try:' out of the loop.
        it = iter(iterable)
        while True:
            try:
                for element in it:
                    data[element] = value
                return
            except TypeError:
                transform = getattr(element, "__as_immutable__", None)
                if transform is None:
                    raise # re-raise the TypeError exception we caught
                data[transform()] = value
    else:
        # Safe: only catch TypeError where intended
        for element in iterable:
            try:
                data[element] = value
            except TypeError:
                transform = getattr(element, "__as_immutable__", None)
                if transform is None:
                    raise # re-raise the TypeError exception we caught
                data[transform()] = value

rawDescription: How to Identify the elements which are removed from set() in python?


code:
from Tkinter import *
import ttk

def main_change(*args):
    second.set('--None--')
    second['values'] = categories.get(main_selected.get(), ['--None--'])

categories = {'Fruit': ['Apples', 'Grapes', 'Bananas'], 'Vegetables': ['Peas', 'Carrots']}

root = Tk()

main_selected = StringVar()
main_selected.trace('w', main_change)

main = ttk.Combobox(root, values=list(categories.keys()), textvariable=main_selected)
main.pack()
second = ttk.Combobox(root, values=['--None--'])
second.pack()

root.mainloop()

rawDescription: list tkinter combobox options with suboptions

description: List tkinter combobox options with suboptions


rawDescription: Pandas: Group by Time, then plot density per group


code:
from datetime import datetime
days_sorted = sorted(days, key=lambda day: datetime.strptime(day, "%d/%b/%Y"))

rawDescription: Sort a list of dates by month in python

description: Sort a list of dates by month in python


code:
imagepath = os.join.path (currentdirectory, fruit, size, fruitproperty + ".html")
htmlfile.write((' '+fruitproperty+'
\n').format(imagepath = imagepath))

rawDescription: How to insert html page saved in a folder using href in Python script

description: Insert html page saved in a folder using href in Python script


code:
class JobForm(forms.ModelForm):
    class Meta:
        fields = ['name', 'job']

class TitleForm(forms.ModelForm):
    class Meta:
        fields = ['name', 'title']

class AuthorUpdate(UpdateView):
    model = Author

    def get_form_class(self):
        if self.request.user.pk == 1:
            return JobForm
        else:
            return TitleForm

rawDescription: UpdateView - different fields list for specific user type


code:
class BlackListModel(models.Model):
   blacklist = ['a', 'b', 'c']

   # your model fields definitions...

   def save(self, *args, **kwargs):
        if self.blacklist_field in self.blacklist:
            raise Exception("Attempting to save a blacklisted value!")
        return super(BlackListModel, self).save(*args, **kwargs)

rawDescription: Django CharField limitations

description: Django CharField limitations


code:
for c in range(1, a.shape[1]):
    a[c:,c] = a[:-c,c]
    a[:c, c] = np.nan

rawDescription: shift columns of a dataframe without looping?

description: Shift columns of a dataframe without looping


code:
class MyObjectAdminForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean_tags(self):
        tags = self.cleaned_data['tags']
        if len(tags) > 3:
            raise ValidationError("....")
        return tags

class MyObjectAdmin(admin.ModelAdmin):
    form = MyObjectAdminForm

rawDescription: How can you limit the maximum number of tags an object can have in django-taggit?

description: Limit the maximum number of tags an object can have in django-taggit


code:
headers = ['Color:', color, 'State:', state, 'Age:', str(age)]
writer.writerow(headers)

rawDescription: Writing a row in Python, what is the best data structure to use?


code: df['dxCount'] = [len(c) for c in df['dxCodes']]

rawDescription: Python Add Column to Pandas Dataframe That is a Count of List Elements in Another Column


code:
tmp = C.swapaxes(1, 2)
tmp[:] = s
C = tmp.swapaxes(1, 2)

rawDescription: assigning to multi-dimensional array

description: Assigning to multi-dimensional array


code:
df.Temp_Rating.fillna(df.Farheit, inplace=True)
del df['Farheit']
df.columns = 'File heat Observations'.split()

rawDescription: Python Pandas replace NaN in one column with value from corresponding row of second column


code:
@app.route('/add')
def add():
    a, b = request.args['a'], request.args['b']
    c = a + b
    return json.dumps({'c': c})

rawDescription: Python - Do math from url parameters

description: Python - Do math from url parameters


code:
# Now we will find the conditional distribution of x given y
(con_cen, con_cov, new_p_k) = gmm.cond_dist(np.array([np.nan, y]), \
    cen_lst, cov_lst, p_k)

rawDescription: Finding conditional Gaussian Mixture Model using scikit-learn.mixture.GMM


code: result = re.sub(r"http\S+", "", subject)

rawDescription: Expression to remove URL links from Twitter tweet