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

fig, axes = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True)

for ax in axes.flat:
    ax.bar(range(5), np.random.random(5), color=np.random.random((5,3)))
    ax.set(xlabel='X-axis', ylabel='Y-axis')

for ax, col in zip(axes[0,:], ['A', 'B', 'C']):
    ax.annotate(col, (0.5, 1), xytext=(0, 10), ha='center', va='bottom',
                size=20, xycoords='axes fraction', textcoords='offset points')

for ax, row in zip(axes[:,0], ['D', 'E', 'F']):
    ax.annotate(row, (0, 0.5), xytext=(-45, 0), ha='right', va='center',
                size=20, rotation=90, xycoords='axes fraction',
                textcoords='offset points')

plt.show()

rawDescription: How to label rows/cols of a matrix of plots?

description: Label rows/cols of a matrix of plots


code:
class Category(object):
    def __init__(self, parent, prefix):
        self.parent = parent
        self.prefix = prefix
    @property
    def ip(self):
        self.parent.data[self.prefix + "ip"]

class Router(object):
    def __init__(self, data):
        self.lan = Category(self, 'lan')
        self.wan = Category(self, 'wan')
        self.data = data

rawDescription: Dividing Python properties to categories


code:
def categories(request):   #written in some file named processor.py
    return {'categories': Categories.objects.all()}

rawDescription: Make custom variable in Django Context permanent


rawDescription: How to parse a string and return a nested array?

description: Parse a string and return a nested array


code:
[x * 2 if x % 2 == 0 else x
 for x in a_list]

rawDescription: Python list comprehension - simple

description: Python list comprehension - simple


code:
res = []
tmp = []

for i, line in enumerate(open('file.txt'), 1):
    tmp.append(line.strip())
    if i % 3 == 0:
        res.append(tmp)
        tmp = []

print(res)

rawDescription: Python - Importing strings into a list, into another list :)


rawDescription: Data-Binding in Python?

description: Data-Binding in Python


code:
class MyThread(Thread):

    def __init__(self):
        self.awake = False

    def run(self):
        time.sleep(x*60)
        self.awake = True

    def is_sleeping(self):
        return not self.awake() and self.isAlive()  # You need to know also if you already started the thread

rawDescription: Find a python threads state (whether sleeping or active)


code:
class uobj:
    def __init__(self, obj):
        self.obj = obj
    def __format__(self, format_spec):
        if format_spec == 's':
            return str(self.obj)
        else:
            # edit, shoehorning this in for completeness
            # to call an original format spec as should probably
            # happen after you do your own processing, use __format__
            if isinstance(self.obj, (int, float)):
                return self.obj.__format__(format_spec)
                # so then a :.2f spec on uobj(123.456) would work as expected
            return str(self.obj).replace('<', '<').replace('>', '>')
    def __getitem__(self, key):
        return uobj(self.obj[key])

rawDescription: Python/Cython custom formatter string presentation types


code:
dialog = LiveData.LiveData(self)
dialog.exec_()

rawDescription: Closing a QWidget opened from a QMainWindow


rawDescription: python - scipy.integrate.odeint returning wrong results

description: Python - scipy.integrate.odeint returning wrong results


code:
def valueChanged(self, text):
     if QtGui.QApplication.clipboard().text() == text:
         self.pasteEvent(text)

rawDescription: PyQt QLineEdit and 'paste' event?

description: PyQt QLineEdit and 'paste' event


code: items = []

rawDescription: List with all the files in directories &subdirectories with path (Python)


rawDescription: Removing a QGraphicsItem's parent

description: Removing a QGraphicsItem's parent


code: [p.next_sibling.strip() for p in soup.findAll('p')]

rawDescription: Python BeautifulSoup get text from HTML

description: Python BeautifulSoup get text from HTML


code:
num = 1 # Just to demonstrate
dir()

rawDescription: Regarding dir()

description: Regarding dir()


code:
class Conflict(object):
    __slots__ = ("combination", "message", "parser")

    def __init__(self, combination, message, parser):
        self.combination = combination
        self.message = str(message)
        self.parser = parser

    def accepts(self, options):
        count = sum(1 for option in self.combination if hasattr(options, option))
        return count <= 1

class ConflictError(Exception):
    def __init__(self, conflict):
        self.conflict = conflict

    def __str__(self):
        return self.conflict.message

class MyOptionParser(optparse.OptionParser):
    def __init__(self, *args, **kwds):
        optparse.OptionParser.__init__(self, *args, **kwds)
        self.conflicts = []

    def set_not_allowed(self, combination, message):
        self.conflicts.append(Conflict(combination, message, self))

    def parse_args(self, *args, **kwds):
        # Force-ignore the default values and parse the arguments first
        kwds2 = dict(kwds)
        kwds2["values"] = optparse.Values()
        options, _ = optparse.OptionParser.parse_args(self, *args, **kwds2)

        # Check for conflicts
        for conflict in self.conflicts:
            if not conflict.accepts(options):
                raise ConflictError(conflict)

        # Parse the arguments once again, now with defaults
        return optparse.OptionParser.parse_args(self, *args, **kwds)

rawDescription: How do you handle options that can't be used together (using OptionParser)?

description: Handle options that can't be used together (using OptionParser)


code:
from Tkinter import *
import tkMessageBox

class MainWindow(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("input")
        self.master.minsize(150, 50)
        self.grid(sticky=E+W+N+S)

        top=self.winfo_toplevel()
        top.rowconfigure(0, weight=1)
        top.columnconfigure(0, weight=1)

        for i in range(1):self.rowconfigure(i, weight=1)
        self.columnconfigure(1, weight=1)

        self.label0 = Label(self, text="Data:    ")
        self.label0.grid(row=0, column=0, padx=2)

        self.entry11 = Entry(self)
        self.entry11.grid(row=0, column=1, pady=2, padx=2, sticky=E+W+N+S)

        self.CheckVar_theta = IntVar()
        self.check = Checkbutton(self, text="", variable=self.CheckVar_theta,
                                 onvalue = 0, offvalue = 1, command=self.switch)
        self.check.grid(row=0, column=3, pady=0, padx=0, sticky=E+W+N+S)

    def switch(self):
        if self.CheckVar_theta.get():
            self.entry11.config(state=DISABLED)
        else:
            self.entry11.config(state=NORMAL)

if __name__=="__main__":
   d=MainWindow()
   d.mainloop()

rawDescription: Python: Tkinter active and deactive entry space with checkutton


rawDescription: How to sort a dictionary by a value passed through a function?

description: Sort a dictionary by a value passed through a function


code:
print("{{TITLE:^{PAGE_WIDTH}}}".format(PAGE_WIDTH=80).format(TITLE="HIGH SCORES"))
print("-" * 80)
for name,score in high_scores.items():
    print("{{name:>{col_width}}} | {{score:<{col_width}}}".format(col_width=(80-3)//2).format(name=name, score=score))

rawDescription: Keeping high scores in a text file

description: Keeping high scores in a text file


code: pipeline.steps[-1][-1].predict = partial(pipeline.steps[-1][-1].predict, batch_size=10)

rawDescription: How to pass a keyword argument to the predict method in a sklearn pipeline

description: Pass a keyword argument to the predict method in a sklearn pipeline


code:
def col_display(data, file):
    widths = [0] * len(data[0])
    for row in data:
        widths[:] = [max(widths[index], len(str(col))) for index, col in enumerate(row)]
    for row in data:
        output = "  ".join(["%-*s" % (widths[index], col) for index, col in enumerate(row)])
        print(output)
        file.write(output + '\n')

outputLine = ["NIST line", "CG100", "CG050", "FactoryCal", "HMFW (nm)-original", "(SIGMA)", "WCalFunctionDerivatives"]
wlines = [[123.1234567890] * 7] * 4
lines = [outputLine] + wlines

with open('output.txt', 'w') as f_output:
    col_display(lines, f_output)

rawDescription: Tabular display of output

description: Tabular display of output


code: print(input())

rawDescription: Python argv and cmd

description: Python argv and cmd


rawDescription: Fastest way to find elements in list

description: Fastest way to find elements in list


code:
df
pd.isnull(df[['a','b']]).any(axis=1)
df.ix[pd.isnull(df[['a','b']]).any(axis=1)]
df.ix[pd.isnull(df[['a','b']]).any(axis=1), 'c']

rawDescription: Collect values of pandas dataframe column A if column B is NaN (Python)


code: plt.hist(img.flatten(), bins=100, facecolor='green', alpha=0.75)

rawDescription: Change visual of histogram from image using matplotlib in Python


rawDescription: How can i find next highest value in django query

description: Find next highest value in django query


rawDescription: How to find the number of edges bewteen any two nodes using networkx?

description: Find the number of edges bewteen any two nodes using networkx


code: final_list = [[k, NO_dict[k], EN_dict[k]] for k in NO_dict]

rawDescription: Python: Compare lists and combine in common fields


code:
import glob
import numpy as np

array_files = glob.glob('*.corr.npy')
for fname in array_files:
    x = np.load(fname)
    plt.plot(x)

rawDescription: Plot arrays same extension Matlotlib

description: Plot arrays same extension Matlotlib


code:
def sort_uniq(alist):
   d = {}
   mod_list = [d.setdefault(i,i) for i in alist if i not in d]
   mod_list.sort()
   return mod_list

rawDescription: Dedupe and sort a list in Python 2.2

description: Dedupe and sort a list in Python 2.2


code:
params = {'name': ['val1', 'val2', 'val3', 'val4']}

response = requests.post(url, data=params)

rawDescription: Post request with many params in Python

description: Post request with many params in Python


rawDescription: String translate using dict

description: String translate using dict


code:
def abs_diff(x, y):
    return abs(x - y)

rawDescription: Column Differences in Python Pivot-Table


code:
min_value = min(d.itervalues())
min_keys = [k for k in d if d[k] == min_value]

rawDescription: Python: get key with the least value from a dictionary BUT multiple minimum values


code:
def capitals(word):
    return [i for i, ch in enumerate(word) if ch.isupper()]

rawDescription: How do I get the index of multiple occurrences of the same character in a string?

description: Get the index of multiple occurrences of the same character in a string


code:
manager = RequestManager()
request = manager.generate_request('I-95')
if request is not None:
    print(request.response()) # "foo"

rawDescription: Creating a set of Python classes

description: Creating a set of Python classes


code:
xCoords = []
yCoords = []
zCoords = []
xCoords.append([])
yCoords.append([])
zCoords.append([])

rawDescription: Question about Arrays in Python and Perl?


code:
def user_new_unicode(self):
    return self.get_full_name()

# Replace the __unicode__ method in the User class with out new implementation
User.__unicode__ = user_new_unicode

# or maybe even
User.__unicode__ = User.get_full_name()

rawDescription: Django - User full name as unicode

description: Django - User full name as unicode


code:
def make_combo_dict(nums, max_):
    nums = sorted(set(nums))
    prev = {0: [""]}    # base state: no combinations
    for num in nums:
        nxt = defaultdict(list)
        for total, ways in prev.items():
            # k = 0
            nxt[total] = ways
            # k > 0
            max_k = (max_ - total) // num
            for k in range(1, max_k + 1):
                nxt[total + k*num].extend(
                    "{}{}{}*{}"
                    .format(way, " + " if way else "", k, num)
                    for way in ways
                )
        prev = nxt
    return prev

rawDescription: Generating addition combinations from an int list in python


code:
import sys
name = 'foo.bar.baz'
__import__(name)
baz = sys.modules[name]
baz

rawDescription: Python dynamic class names

description: Python dynamic class names


code:
size = len(b0)  # Must be 4096

# Initialize output as a 2D array with zeros that would also hold all elements
# from the six inputs
out = np.zeros((size,8),dtype=b0.dtype)

# Leave first two elements in each row and
# put inputs-concatenated and flipped version into the output array
out[:,2:] = np.concatenate((b0,b1,r0,g0,r1,g1)).reshape(-1,size)[:,::-1].T

# Finally convert to list if needed
data_bin_out = out.ravel().tolist()

rawDescription: sort multible numpy arrays into one like: [1,2,..n, 1,2..n]

description: Sort multible numpy arrays into one like: [1,2,..n, 1,2..n]


code:
from flask import send_file

@app.route('/path')
def view_method():
     path_to_file = "/test.wav"

     return send_file(
         path_to_file,
         mimetype="audio/wav",
         as_attachment=True,
         attachment_filename="test.wav")

rawDescription: How to send audio wav file generated at the server to client browser?

description: Send audio wav file generated at the server to client browser


code:
import time
import smtplib
import xoauth

consumer = xoauth.OAuthEntity('anonymous', 'anonymous')
access_token = xoauth.OAuthEntity('1/MI6B2DqJP4FEkDRLUKrD5l46sQ0758-2ucEKBY-DeB0', 'NysqNqVTulFsdHpSRrPP56sF')

xoauth_string = xoauth.GenerateXOauthString(consumer, access_token, 'testing.oauth.1@gmail.com', 'smtp', 'testing.oauth.1@gmail.com', str(xoauth.random.randrange(2**64 - 1)), str(int(time.time())))

smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo()
smtp_conn.starttls()
smtp_conn.ehlo()
smtp_conn.docmd('AUTH', 'XOAUTH ' + xoauth.base64.b64encode(xoauth_string))

header = 'To:testing.oauth.1@gmail.com\n' + 'From: testing.oauth.1@gmail.com\n' + 'Subject:testing \n'
msg = header + '\n this is test msg from me \n\n'
smtp_conn.sendmail('testing.oauth.1@gmail.com', 'testing.oauth.1@gmail.com', msg)

rawDescription: python & smtplib: Is sending mail via gmail using oauth2 possible?

description: Python & smtplib: Is sending mail via gmail using oauth2 possible


code:
integers = []
while len(integers) < 10:
    a = input("Enter an integer: ")
    if a in integers:
        print("Sorry, that number was already entered.")
    else:
        integers.append(a)

rawDescription: how to reject duplicate values

description: Reject duplicate values


code:
import random
print(*range(random.randrange(100)))
print(*range(random.randrange(100)))

rawDescription: randrange inside for loop in python 3.5

description: Randrange inside for loop in python 3.5


code:
class Wallet:

    #Grab the initial balance in the account
    def __init__(self, initial_balance):
        self.balance = initial_balance

    #method that deposits funds to the balance
    def deposit(self, deposit_amount):
        self.balance += deposit_amount

    #method that attempts to withdraw from the balance
    def withdraw(self, withdraw_amount):
        if withdraw_amount <= self.balance:
            self.balance -= withdraw_amount
        else:
            print("Insufficient funds. You have " + str(self.balance) + " in your account. Please deposit more or withdraw less.")

    #display the balance
    def display_balance(self):
        print("The current balance in the account is " + str(self.balance))
        print("-----")

#Check if this module is the one currently being run
if __name__ == "__main__":
    #Ask user for initial balance
    initial_balance = int(input("Initial balance in account: "))
    #initiate the class, passing the initial balance
    wallet = Wallet(initial_balance)
    wallet.display_balance()
    while True:
        #Pick an option to withdraw, deposit or exit
        print("1: Deposit funds")
        print("2: Withdraw funds")
        print("3: Exit")
        type = int(input("Please select an option (1, 2 or 3): "))
        if type == 1:
            deposit_amount = int(input("Please specify amount to deposit: "))
            wallet.deposit(deposit_amount)
            wallet.display_balance()
        elif type == 2:
            withdraw_amount = int(input("Please specify amount to withdraw: "))
            wallet.withdraw(withdraw_amount)
            wallet.display_balance()
        elif type == 3:
            break
        else:
            print("Invalid selection, please type either 1, 2 or 3")

rawDescription: What am i doing wrong in this attempt at an infinite loop?


rawDescription: Find a dictionary in a list of dictionaries


code: _, itemIDs, itemNames = GetItems()

rawDescription: How to use a .NET method which modifies in place in Python?

description: Use a .NET method which modifies in place in Python


code:
#!/usr/bin/kivy
import kivy
kivy.require('1.9.1')

from kivy.app import App
from kivy.lang import Builder
from kivy.properties import NumericProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

Builder.load_string('''
<MyButton>:
    on_press: print(self.np)
''')

class MyButton(Button):
    np=NumericProperty(100)

class MainApp(App):
    def build(self):
        mb1 = MyButton(text="mb1")
        mb2 = MyButton(text="mb2")

        layout = BoxLayout()
        layout.add_widget(mb1)
        layout.add_widget(mb2)
        return layout

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

rawDescription: Dynamically adding properties with kivy discouraged – why?


code:
while len(q) > 0:
    smaller = MAX_LENGTH
    for i in q:
      if dist[i] < smaller:
        smaller = dist[i]
        pos = i
    u = q[q.index(pos)]
    q.pop(q.index(pos))
    if dist[u] == float('inf'):
          break

rawDescription: searching a database for partial matches on strings.(python)

description: Searching a database for partial matches on strings.(python)


code:
follow_loop = range(1, 11)
for x in follow_loop:
    xpath = "/html/body/div[7]/div/div/div[2]/div["
    xpath += str(x)
    xpath += "]/div[2]/div[1]/div/button"
    driver.find_element_by_xpath(xpath).click()

rawDescription: How to nest loop number into an xpath in python?

description: Nest loop number into an xpath in python


code:
base_prompt = 'Enter number of random points'
user_input = raw_input(base_prompt)
while True:
    try:
        input_number = int(user_input)
    except ValueError:
        user_input = raw_input('%s not an interger\n%s' % (user_input, base_prompt))
    else:
        if 1 <= input_number <= 100:
            break
        else:
            user_input = raw_input('%d out of range (1 to 100)\n%s' % (input_number, base_prompt))

rawDescription: If statement for number in a range

description: If statement for number in a range


code:
# The author keyword will only be checked if
# author is not in request.form or content
myform = ContentForm(request.form, obj=content, author=user)

rawDescription: SQLAlchemy/WTForms: set default selected value for QuerySelectField


code:
class Article(db.Model):
  tags = db.ListProperty(Tag)

  @staticmethod
  def select_by_tag(tag):
    return Article.all().filter("tags", tag).run()

rawDescription: Choose between many-to-many techniques in App Engine DB


code:
valid_forms = list(filter(lambda fm: fm.is_val(),
                          map(ArticleForm, some_list_of_dictionaries)))

rawDescription: Django: validating forms declared on client side with angularjs


rawDescription: efficient expanding linregress

description: Efficient expanding linregress


code:
def __iter__(self):
    return self.dict().iteritems()

rawDescription: How should I do a RedisDict in python?

description: How should I do a RedisDict in python


rawDescription: (Python) adding a list to another without the brackets


code:
import os

def upload_to(instance, filename):
    return os.path.join([conf.TEMPLATES_UPLOAD_DIR, filename])

rawDescription: Django migrations and customizable reusable apps


code:
if __name__ == "__main__":
    command= " ".join( sys.argv[1:] )
    eval( command )

rawDescription: execute python script with function from command line, Linux

description: Execute python script with function from command line, Linux


code:
# File: factories.py
from .models import Book
import factory

class BookFactory(factory.Factory):
  # Note that starting_seq_num cannot be set here in the class definition,
  # because Factory will then pass it as a kwarg to the model's create() method
  # and cause an exception.  It must be set outside the class definition.
  FACTORY_FOR = BookModel
  title = factory.Sequence(lambda n: u'Title #{}'.format(n))

  @classmethod
  def _setup_next_sequence(cls):
      return getattr(cls, 'starting_seq_num', 0)

# File: make_data.py
from factories import BookFactory

BookFactory.starting_seq_num = 100
BookFactory().create()

rawDescription: How to pass in a starting sequence number to a Django factory_boy factory?

description: Pass in a starting sequence number to a Django factory_boy factory


code:
def mapper (x):
    return x["_id"]

map(mapper,result)

rawDescription: Conditions in Find, Mongo

description: Conditions in Find, Mongo


rawDescription: Calling Python file from within PHP

description: Calling Python file from within PHP


code:
with open('infile.txt') as f, open('outfile.txt', 'w') as outfile:
    reader = csv.reader(f, delimiter='\t')
    writer = csv.writer(outfile, delimiter='\t')
    writer.writerow(next(reader, None))  # Write out the header row
    for row in reader:
        # Note: Python lists begin with [0],
        #       so the 13th column will have an index of 12
        row[12] = row[12].replace('-', ' ')
        writer.writerow(row)

rawDescription: Splitting information in a specific column python?


code: NOT (taget_end_date < source_begin_date or target_begin_date > source_end_date )

rawDescription: query to get date overlaping

description: Query to get date overlaping


rawDescription: Django ORM and templates, how do I view all of the variables available for a given QuerySet?


code:
from flask_sqlalchemy import SQLAlchemy as BaseSQLAlchemy, Model, _BoundDeclarativeMeta, _QueryProperty
from sqlalchemy import MetaData

class SQLAlchemy(BaseSQLAlchemy):
    def make_declarative_base(self):
        metadata = MetaData(naming_convention={
            'pk': 'pk_%(table_name)s',
            'fk': 'fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s',
            'ix': 'ix_%(table_name)s_%(column_0_name)s',
            'uq': 'uq_%(table_name)s_%(column_0_name)s',
            'ck': 'ck_%(table_name)s_%(constraint_name)s',
        })
        base = declarative_base(metadata=metadata, cls=Model, name='Model', metaclass=_BoundDeclarativeMeta)
        base.query = _QueryProperty(self)
        return base

rawDescription: Changing constraint naming conventions in Flask-SQLAlchemy


code:
def round(x):
    return int(x + 0.5)

rawDescription: How to get real three digits of microseconds in Python?

description: Get real three digits of microseconds in Python


code:
def remove_whitespace_from_assignments():
    separator = "="
    config_path = "config.ini"
    lines = file(config_path).readlines()
    fp = open(config_path, "w")
    for line in lines:
        line = line.strip()
        if not line.startswith("#") and separator in line:
            assignment = line.split(separator, 1)
            assignment = map(str.strip, assignment)
            fp.write("%s%s%s\n" % (assignment[0], separator, assignment[1]))
        else:
            fp.write(line + "\n")

rawDescription: How to remove spaces while writing in INI file- Python

description: Remove spaces while writing in INI file- Python


code: data <- read.csv('sample_data.csv')

rawDescription: Code for determining number of 15 minute periods


code:
def threadmain():
    t = tk.Tk()
    t.iconbitmap('icon.ico')
    b = tk.Button(text='test', command=exit)
    b.grid(row=0)
    t.mainloop()

if __name__ == '__main__':
    thread.start_new_thread(threadmain, ())

    while 1:
        sleep(1)

rawDescription: Tkinter locks python when Icon loaded and tk.mainloop in a thread


code:
model.Pi.stats()
model.Tj.stats()

rawDescription: How do I get parameters from a posterior distribution in PyMC?

description: Get parameters from a posterior distribution in PyMC


code:
def numbers_in_lists(string):
    """Describe what it does here!"""
    output = []
    sublist = []
    for num in map(int, string):
        if not output or num > output[-1]:
            if sublist:
                output.append(sublist)
                sublist = []
            output.append(num)
        else:
            sublist.append(num)
    if sublist:
        output.append(sublist)
    return output

rawDescription: list of list concept in python

description: List of list concept in python


code:
class CustomInputConsole(code.InteractiveConsole):
    def __init__(self, input_file):
        code.InteractiveConsole.__init__(self) # old style class, so can't use super() here
        self.input_file = input_file

    def raw_input(self, prompt=""):
        self.write(prompt)
        line = self.input_file.readline()
        if line:
            return line.rstrip("\n")
        raise EOFError()

    def runcode(self, _code):
        try:
            old_stdin = sys.stdin
            sys.stdin = self.input_file
            code.InteractiveConsole.runcode(self, _code)
        finally:
            sys.stdin = old_stdin

rawDescription: InteractiveConsole.raw_input override not working


code:
print(getColor())
drawFace(40,50)
print(getColor())
drawFace(90,100)
print(getColor())
drawFace(30,200)
print(getColor())
drawFace(280,50)
print(getColor())
drawFace(90,100)

rawDescription: How to get different colors in python turtle

description: Get different colors in python turtle


code: df.column.fillna(0 ,inplace = True)

rawDescription: Pandas: how to fill null values matching the right types of that column?


code: ('This', 'POS_DT', 'is', 'POS_VBZ', 'POS', 'POS_NNP', 'example', 'POS_NN')

rawDescription: python: How to use POS (part of speech) features in scikit learn classfiers (SVM) etc

description: Python: How to use POS (part of speech) features in scikit learn classfiers (SVM) etc


rawDescription: How to check if a number is within a group of non-consecutive ranges?

description: Check if a number is within a group of non-consecutive ranges


code:
hsv = plt.get_cmap('hsv')
hsv(float(i)/(len(data)-1))

rawDescription: matplotlib large set of colors for plots

description: Matplotlib large set of colors for plots


code:
import pandas as pd
import numpy as np

def combine(values):
    if any(isinstance(v, basestring) for v in values):
        result = values.dropna().tolist()
    else:
        result = values.sum()
    return result

dict1 = { 'M1': {'H': 1, 'J' : 2, 'D' : 'ABC/DEF1.txt'},
          'M2': {'H': 1, 'J' : 2, 'D' : 'ABC/DEF2.txt'},
          'M3': {'H': 1, 'J' : 2, 'D' : 'ABC/DEF3.txt'} }
dict2 = { 'M1': {'H': 4, 'J' : 6, 'D' : 'ABC/DEF1.txt'},
          'M2': {'H': 2, 'J' : 5, 'D' : 'ABC/DEF2.txt'},
          'M4': {'H': 9, 'J' : 8, 'D' : 'ABC/DEF3.txt'}}

df1 = pd.DataFrame(dict1).T
df2 = pd.DataFrame(dict2).T
df = df1.join(df2, rsuffix = '_', how = 'outer').T
grouped = df.groupby(lambda label: label.rstrip('_'))
print(grouped.aggregate(combine).T)

rawDescription: Merging CSV data and counting cell values in python pandas


code:
aLabel = MyLabel('Label text')
aLabel.setStyleSheet('color: yellow')

rawDescription: Implement event handlers for QWidget and derived classes and avoid code duplication


rawDescription: Packing 4 Integers as ONE BYTE?

description: Packing 4 Integers as ONE BYTE


code: SPLASH_URL_PASS = (r'.',)

rawDescription: Python/Scrapy: Scraping Nasdaq's data?

description: Python/Scrapy: Scraping Nasdaq's data


code:
def get_depth_group(name, depth):
    arr = (df2.name == name) & (df2.bottom_depth > depth) & (depth > df2.top_depth)
    return df2.iloc[arr.argmax()] if any(arr) else np.nan

rawDescription: In Pandas, merge two dataframs with complex multi-indexing


rawDescription: Numpy.cumsum in reverse

description: Numpy.cumsum in reverse


code: {'Jon Skeet': 2, 'Dr. House': 2, 'Spiderman': 2}

rawDescription: Is there a dictionary-like datastructure that would allow searches for 'key' and for 'value'


code:
def for_half_year(row, data):
    date = row['Date']
    pid = row['PictureID']
    # Do this 6 month checking better
    if '__start' not in data or (date - data['__start']).days > 6*30:
        # Reset values
        for key in data:
            data[key] = 0
        data['__start'] = date
    data[pid] = data.get(pid, -1) + 1
    return data[pid]

df['PastSix'] = df.apply(for_half_year, args=({},), axis=1)

rawDescription: Dataframe Wrangling with Dates and Periods in Pandas


rawDescription: Taking multiple lines of strings as command line input in Python


code: np.repeat(np.repeat(a,2, axis=0), 2, axis=1)

rawDescription: Resizing and stretching a NumPy array

description: Resizing and stretching a NumPy array


code:
for root, dirs, files in os.walk('/mydir'):
    for names in files:
        if names.startswith("Mod"):
             mylist.append(os.path.join(root, names))

rawDescription: Filename scanning for certain names Python


code: [[d.get('name') for d in lst] for lst in response]

rawDescription: List of values for a key in List of list of dictionaries?


rawDescription: Closing a QWidget opened from a QMainWindow


rawDescription: Change mutliple Directory keys at once in python


code:
from collections import namedtuple
from operator    import itemgetter

def smooth(iq_data, alpha=1, today=None):
    """Perform exponential smoothing with factor `alpha`.

    Time period is a day.
    Each time period the value of `iq` drops `alpha` times.
    The most recent data is the most valuable one.
    """
    assert 0 < alpha <= 1

    if alpha == 1: # no smoothing
        return sum(map(itemgetter(1), iq_data))

    if today is None:
        today = max(map(itemgetter(0), iq_data))

    return sum(alpha**((today - date).days) * iq for date, iq in iq_data)

IQData = namedtuple("IQData", "date iq")

if __name__ == "__main__":
    from datetime import date

    days = [date(2008,1,1), date(2008,1,2), date(2008,1,7)]
    IQ = [110, 105, 90]
    iqdata = list(map(IQData, days, IQ))
    print("\n".join(map(str, iqdata)))

    print(smooth(iqdata, alpha=0.5))

rawDescription: calculate exponential moving average in python

description: Calculate exponential moving average in python


code:
s = '12212'

s.count('12') # this equals 2

rawDescription: Does Python have a string contains how many substring method, allowing for overlap?


rawDescription: python matching list of lists

description: Python matching list of lists


code:
data = "3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk=----------:jhawrewre:--\r\n"
remove_tail(data).decode('base64')

rawDescription: How to extract valid string from beginning to the first no base64 valid character?

description: Extract valid string from beginning to the first no base64 valid character


rawDescription: Finding letters in a string

description: Finding letters in a string


code: invid, stock, published, price, invtype, title, author = read_one_file()

rawDescription: Passing variables in Python

description: Passing variables in Python


code:
class timeval32(Structure):
    _fields_ = [('tv_sec', c_int32),
                ('tv_usec', c_int32)]

class if_data64(Structure):
    _pack_ = 4
    _fields_ = [('ifi_type', c_ubyte),
                ('ifi_typelen', c_ubyte),
                ('ifi_physical', c_ubyte),
                ('ifi_addrlen', c_ubyte),
                ('ifi_hdrlen', c_ubyte),
                ('ifi_recvquota', c_ubyte),
                ('ifi_xmitquota', c_ubyte),
                ('ifi_unused1', c_ubyte),
                ('ifi_mtu', c_uint32),
                ('ifi_metric', c_uint32),
                ('ifi_baudrate', c_uint64),    # was c_uint32
                ('ifi_ipackets', c_uint64),
                ('ifi_ierrors', c_uint64),
                ('ifi_opackets', c_uint64),
                ('ifi_oerrors', c_uint64),
                ('ifi_collisions', c_uint64),
                ('ifi_ibytes', c_uint64),
                ('ifi_obytes', c_uint64),
                ('ifi_imcasts', c_uint64),
                ('ifi_omcasts', c_uint64),
                ('ifi_iqdrops', c_uint64),
                ('ifi_noproto', c_uint64),
                ('ifi_recvtiming', c_uint32),
                ('ifi_xmittiming', c_uint32),
                ('ifi_lastchange', timeval32)] # was missing

rawDescription: Garbage uint64 values from ctypes

description: Garbage uint64 values from ctypes


rawDescription: finding duplicates in a list of lists

description: Finding duplicates in a list of lists


code:
import coverage
import os
cov = coverage.Coverage()
cov.load()

with open(os.devnull, "w") as f:
    total = cov.report(file = f)

print("Total: {0:.0f}".format(total))

rawDescription: How do I access coverage.py results programmatically?

description: Access coverage.py results programmatically


code:
params = [('title', 'file1'), ('title', 'file2'), ('title', 'file3')]
r = requests.post('http://example.com',
                  files=files, headers=headers, params=params)

rawDescription: how to POST multipart list of JSON/xml files using python requests


code:
add(
    age, subtract(
        height, (weight * (iq / 2))
    )
)

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


code:
for col in ['Start_Time', 'End_Time']:
    df[col] = pd.to_datetime(df['Date'] + ' ' + df[col])

rawDescription: How to convert the time from 00:00 to 24:00 in python

description: Convert the time from 00:00 to 24:00 in python


code: {'age': 22, 'name': 'Gunjan', 'addresses': [{'city': 'Kolkata', 'state': 'West Bengal', 'district': 'Jalpaiguri'}, {'city': 'Siliguri', 'state': 'West Bengal', 'district': 'Darjeeling'}]}

rawDescription: Json serialization python

description: Json serialization python


code:
# Model definitions

class RawAddress(Base):
    __tablename__ = 'rawaddresses'

    id = Column(Integer, primary_key=True)
    source_of_address = Column(String(50))

    full_address = Column(
        ForeignKey('geocodedaddresses.full_address'),
        nullable=True,
    )

class GeocodedAddress(Base):
    __tablename__ = 'geocodedaddresses'

    full_address = Column(String(400), primary_key=True)
    lat = Column(Float)
    lng = Column(Float)

    raw_addresses = relationship(RawAddress, backref="geocoded_address")

rawDescription: SQL alchemy - specifying relationships when foreign key may not exist


code: all([np.arange(3), np.arange(3)])

rawDescription: matplotlib.pyplot vs matplotlib.pylab

description: Matplotlib.pyplot vs matplotlib.pylab


code:
import re
demo = '8 y 13 houses, 13 y 8 houses, 13 y 13 houses, 8 y 8 houses, 120 y 8 houses, 8 y 120 houses, 13,5 y 8 houses, 13,5 y 120 houses'
pattern = re.compile(r"\b([1-2]?\d(?:,\d)?)\s[y+]\s([1-2]?\d(?:,\d)?)\shouses\b")
pattern.findall(demo)

rawDescription: Regex to capture numbers up to 2 digits and coma if followed by another word and number


code:
cursor.execute("select user_name from users where user_id=? for xml auto", userid)
rows = cursor.fetchall()
xml = ''.join(row[0] for row in rows)

rawDescription: return sql query in xml format in python

description: Return sql query in xml format in python


code:
x = set(range(3))
x
x.add(-1)
x

rawDescription: Given a bunch of ranges of numbers, get all the numbers within those ranges?


code:
with open(filename, 'w') as f:
    writer = csv.writer(f)

    # write the file header
    fieldnames = ['local time', 'GMT time', 'date', 'product id', 'manuf id',
            'case', 'pallet', 'id', 'code', 'company id', 'location', 'secondary code']
    writer.writerow(fieldnames)

    # process each line
    for line in lines:
        new_list = do_something()

        writer.writerow(new_list) # write to the file

rawDescription: Python 3.5 csv parsing with special characters


code: Counter(sublist[0] for sublist in my_list)

rawDescription: counting element occurences in nested lists

description: Counting element occurences in nested lists


rawDescription: combining two lists of dicts to one list of dicts by specific key

description: Combining two lists of dicts to one list of dicts by specific key


code:
from collections import defaultdict
d = defaultdict(int)
for x in lVals:
    d[x] += 1

rawDescription: count each element in list without .count

description: Count each element in list without .count


code:
from collections import defaultdict  # available in Python 2.5 and newer

urls_d = defaultdict(int)
for url in list_of_urls:
    urls_d[url] += 1

urls = [{"url": key, "nbr": value} for key, value in urls_d.items()]

rawDescription: Python : List of dict, if exists increment a dict value, if not append a new dict


code: day_generator = itertools.cycle(days)

rawDescription: Infinite generator in Python for days of week


code:
# convert all of the prices to lists (even if they only have one element)
df.prices = df.prices.apply(lambda x: x if isinstance(x, list) else [x])

# Create a new dataframe which splits the lists into separate columns.
# Then flatten using stack. The explicit MultiIndex allows us to keep
# the item_name and product_id associated with each price.
idx = pd.MultiIndex.from_tuples(zip(*[df['item_name'],df['product_id']]),
                                names = ['item_name', 'product_id'])
df2 = pd.DataFrame(df.prices.tolist(), index=idx).stack()

# drop the hierarchical index and select columns of interest
df2 = df2.reset_index()[['product_id', 0, 'item_name']]
# rename back to prices
df2.columns = ['product_id', 'prices', 'item_name']

rawDescription: Pandas write variable number of new rows from list in Series


code:
code = '''line 1
    __LINE TO CHANGE__
line 3'''

print('\n'.join(replace_line(
    code.split('\n'),                           # one string per line
    '__LINE TO CHANGE__',                       # the string to replace
    ["added code line a", "added code line b"]  # the strings to replace with
)))

rawDescription: How can I keep the indentation between lines?

description: Keep the indentation between lines


code:
from snakebite.client import Client

host = ...
port = ...
client = Client(host, port)
client.delete(some_path, recurse=True)

rawDescription: pyspark and HDFS commands

description: Pyspark and HDFS commands


code:
for n in drugs:
    df[n] = df[['MED1','MED2','MED3','MED4','MED5']].isin([drugs[n]]).any(1)

rawDescription: check for value in list of Pandas data frame columns

description: Check for value in list of Pandas data frame columns


code:
person = Person.objects.get(name="the person's name")
person.add(item)
person.save

rawDescription: can't get the objects of foreign keys of django models also my design is probably bad

description: Can't get the objects of foreign keys of django models also my design is probably bad


rawDescription: How to calculate the intercept using numpy.linalg.lstsq

description: Calculate the intercept using numpy.linalg.lstsq


code:
from collections import defaultdict

index_on_1 = defaultdict(list)
index_on_2 = defaultdict(list)
index_on_3 = defaultdict(list)

for i, (val1, val2, val3) in enumerate(yourstructure):
    index_on_1[val1].append(i)
    index_on_2[val2].append(i)
    index_on_3[val3].append(i)

rawDescription: How to assign a collection of 3 pieces of data

description: Assign a collection of 3 pieces of data


code:
def chunk_sizes(filesize, num_chunks):
    d, r = divmod(filesize, num_chunks)
    result = [d] * num_chunks
    result[-1] += r
    return result

rawDescription: Partitioning a file for parallel download


code:
with open('my_file.py', 'r') as f:
    lines = [line for line in f if not line.replace(' ','').lower().startswith("#'test/")]

with open('my_file.py', 'w') as f:
    f.writelines(lines)

rawDescription: as removing a line commented python file?

description: As removing a line commented python file


code:
from myapp.forms import FooForm

class Model1CreateView(CreateView):
    model = Model1
    fields = ['field1', 'field2']
    form_class = FooForm

rawDescription: Specifying a css class for a field of a generic form


code:
from Crypto.Cipher import Blowfish
KEY = "AAAAAAAA000000000000000000000000".decode('hex')
IV = "AAAAAAAA00000000".decode('hex')
cipher = Blowfish.new(KEY, Blowfish.MODE_CBC, IV)
ciphertext = "eAIUXziwB8QbBexkiIDR3A==".decode('base64')
cipher.decrypt(ciphertext)

rawDescription: How to decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python?

description: Decrypt unsalted openssl compatible blowfish CBC/PKCS5Padding password in python


rawDescription: python regexp remove last numbers from string

description: Python regexp remove last numbers from string


rawDescription: Django and SaaS. How to use separate database for each Django site?


code:
from xml.etree.ElementTree import ElementTree

f = open('/path/to/xml/file', 'r')

xml = ElementTree(file=f)
for person in xml.findall('person'):
    print(person.attrib['name'])
    for number in person.findall('number'):
        print('%s -> %s' % (number.attrib['type'], number.attrib['value']))

rawDescription: Is there something like LINQ to XML in python for appengine?


rawDescription: python: find and replace numbers < 1 in text file

description: Python: find and replace numbers < 1 in text file


code:
for link in links:
    print(link.get_attribute("href"))

rawDescription: Python SeleniumExtract href containing specific strings


code:
def add_abilities(abilities_m_l):
    jobs_dict = OrderedDict()
    for data_dict in abilities_m_l:
        o_code = data_dict['O*NET-SOC Code']
        activity = data_dict['Element Name']
        activities_so_far = jobs_dict.setdefault(o_code, OrderedDict())
        activities_so_far[activity] = True
    return [{o_code: activities.keys()} for o_code, activities in jobs_dict.iteritems()]

rawDescription: Not appending to list

description: Not appending to list


rawDescription: Different return when using base64.encodestring with database and session variable


code:
import pandas as pd
df = pd.DataFrame({'ADMIT_DATE': [200110, 201604]})
df['ADMIT_DATE'] = pd.to_datetime(df['ADMIT_DATE'].astype(str), format='%Y%m')
df
df.dtypes

rawDescription: How to convert a column of type integer to type datetime in python?

description: Convert a column of type integer to type datetime in python


rawDescription: Can yield produce multiple consecutive generators?


rawDescription: Finding minimum value element-wise in three 2d submatrices


code: np.nonzero(np.all(a != 0, axis=0))[0]

rawDescription: Find Indices Of Columns Having Some Nonzero Element In A 2d array


code:
import re
re.findall(r"\w", "'a','b'")

rawDescription: Coverting a string to an array in python


code: keywords = [''.join(i) for i in itertools.product(alphabets, repeat = 3)]

rawDescription: What is the best way to generate all possible three letter strings?


code:
print("Hello and welcome to Shahaad's quiz!") #Introduction
name = input("What is your name? ")
print("Alright", name,", these will be today's topics:")  #Topics
print("a) Video Games")
print("b) Soccer")
print("c) Geography")
choice = input("Which topic would you like to begin with?")
if choice == 'video games' or choice == 'Video Games' or choice == 'Video games' or choice == 'a)' or choice == 'a':
    print("You picked Video Games.")
print("Question number one:")                                      #Question one
print("What is the most popular FPS (First Person Shooter) game?")
print("a) Call of Duty")
print("b) Battlefield")
print("c) Grand Theft Auto 5")
print("d) Counter Strike")
maxGuesses = 2 #Max number of attempts for the problem
guessesTaken = 0
points = 0
question = input("Your answer: ")
if question == 'Call of duty' or question == 'call of duty' or question == 'Call Of Duty' or question == 'Call of Duty' or question == 'a' or question == 'a)':
    print("You are correct! You guessed the question on the first try!")
    points = points + maxGuesses-guessesTaken
    print("You scored",(maxGuesses-guessesTaken), "points!")
else:
    print("Incorrect!")
    print("You have", (maxGuesses-guessesTaken-1), "guesses remaining!")
    answerb = input("Your answer: ")
    if answerb == 'Call of duty' or answerb == 'call of duty' or answerb == 'Call Of Duty' or answerb == 'Call of Duty' or answerb == 'a' or answerb == 'a)':
        print("You are correct!")
        points = points + maxGuesses-guessesTaken
    print("You scored", (maxGuesses-guessesTaken-1), "points!")

rawDescription: Python using variables and if statements


code: compare = lambda word: sum([scores.get(letter,0) for letter in word])

rawDescription: python - how to compare a key of the dictionary with a string character

description: Python - how to compare a key of the dictionary with a string character


code:
[dict(zip(('lblA', 'lblB', 'lblC'), term)) for term in
  itertools.product((False, True) , (False, True), (0, 1, 2))]

rawDescription: Best way to enumerate a cartesian product with labels in python?

description: Enumerate a cartesian product with labels in python


code:
target = pd.DataFrame(0, index=df.index, columns=range(1,13))
target

rawDescription: Pandas Dataframe - How To Convert Date to Boolean Columns?


code:
test = [[] for _ in range(4)]
heappush(test[2],6)
heappush(test[2],7)
test

rawDescription: How to use a array of heaps in python

description: Use a array of heaps in python


code:
counts = {}
current = None

with open(filename) as fo:
   for line in fo:
       if line.startswith('>'):
           current = line.strip()
           counts[current] = 0
       else:
           counts[current] += 1

rawDescription: Count lines after line with specific character


rawDescription: Reverse the content of each element in a list python


code:
a = ['dwe','fw4fe4f','gvfes','fw4f',44,'vwe4d','sv','vsed']
for i,each in enumerate(a,start=1):
    print ("{}.{}".format(i,each))

rawDescription: Printing list in Python with serial numbers


code:
for step in (1, 25, 50):
    plt.plot(t[::step], x[::step], label='step=%d'%step)
#                ^^^^       ^^^^
plt.ylim((-1.05, 1.05))
plt.legend(loc='best')

rawDescription: Efficiently drawing lines using python

description: Efficiently drawing lines using python


code:
n = len(a)
ngroup = 10

counts = np.ones(ngroup, int)*(n//ngroup)
counts[:n%ngroup] += 1

q = np.r_[0, np.cumsum(counts / float(n))]
q[-1] = 1.0
r2 = pd.qcut(a, q)
np.bincount(r2.labels)

rawDescription: Python Pandas qcut behavior with # of observations not divisible by # of bins


rawDescription: dict.setdefault appends one extra (default?) item into the value list

description: Dict.setdefault appends one extra (default?) item into the value list


code: urllib.urlretrieve(url, filename)

rawDescription: Downloading files using Python

description: Downloading files using Python


code: any(e in lestring for e in lelist)

rawDescription: Python - Fastest way to check if a string contains specific characters in any of the items in a list


code:
from lxml import etree
import pandas
import HTMLParser

inFile = "./thedoc.xml"
outFile = "./theprocdoc.csv"

#It is likely that your XML might be too big to be parsed into memory,
#for this reason it is better to use the incremental parser from lxml.
#This is initialised here to be triggering an "event" after a "doc" tag
#has been parsed.
ctx = etree.iterparse(inFile, events = ("end",), tag=("doc",))

hp = HTMLParser.HTMLParser()
csvData = []
#For every parsed element in the "context"...
for event, elem in ctx:
    #...isolate the tag's attributes and apply some formating to its text
    #Please note that you can remove the cgi.escape if you are not interested in HTML escaping. Please also note that the body is simply split at the newline character and then rejoined to ommit the title.
    csvData.append({"id":elem.get("id"),
                    "url":elem.get("url"),
                    "title":elem.get("title"),
                    "body":hp.unescape("".join(elem.text.split("\n")[2:]))})
    elem.clear() #It is important to call clear here, to release the memory occupied by the element's parsed data.

#Finally, simply turn the list of dictionaries to a DataFrame and writeout the CSV. I am using pandas' to_csv here for convenience.
pandas.DataFrame(csvData).to_csv(outFile, index = False)

rawDescription: Converting "document format" / XML to CSV


code:
from sqlalchemy import func

class BaseQuery(Query):
    def count_star(self):
        count_query = (self.statement.with_only_columns([func.count()])
                       .order_by(None))
        return self.session.execute(count_query).scalar()

rawDescription: How to count rows with SELECT COUNT(*) with SQLAlchemy?

description: Count rows with SELECT COUNT(*) with SQLAlchemy


code:
for (word, count) in file1_common_words.items():
    try:
        count_in_file2 = file2_common_words[word]
    except KeyError:
        # if the word is not present file2_common_words,
        # then its count is 0.
        count_in_file2 = 0
    print("{0}\t{1}\t{2}".format(word, count, count_in_file2))

rawDescription: How to compare most common words in on text file to other text file

description: Compare most common words in on text file to other text file


code:
def extract_time(line):
    ...
    return time

rawDescription: Sort list by given order of indices -Python


rawDescription: Sorting a list based on associated scores


code:
str = """<office:annotation office:name="__Annotation__45582_97049284">
</office:annotation>
    case 1 there can be an arbitrary text with any symbols
<office:annotation-end office:name="__Annotation__45582_97049284"/>

<office:annotation office:name="__Annotation__19324994_2345354">
</office:annotation>
    case 2there can be an arbitrary text with any symbols
<office:annotation-end office:name="__Annotation__19324994_2345354"/>"""
m = re.findall(r'<\/office:annotation>\s*(.*)(?=\n<office:annotation-end)', str)
m

rawDescription: Python regular expression extract the text between two values


code:
import numpy as np
a = np.arange(12).reshape(4,3)
a.sum(axis=0)

rawDescription: How to calculate the sum of all columns of a 2D numpy array (efficiently)

description: Calculate the sum of all columns of a 2D numpy array (efficiently)


code:
def test_install_package(test_package):
    package = test_package(version='1.1')
    ...
    assert ...

rawDescription: py.test: Pass a parameter to a fixture function

description: Py.test: Pass a parameter to a fixture function


code: return ' '.join(pig_words)

rawDescription: Python Simple Loop in function

description: Python Simple Loop in function


code:
from exifread import process_file

with open('dfround2.jpg', 'rb') as f:
    tags = process_file(f)
    time = tags['Image DateTime']
    orig = tags['EXIF DateTimeOriginal']
    print [str(time), str(orig)]
    # ['2014:12:05 18:12:09', '2013:07:20 15:53:30']

rawDescription: Get the right value in my array

description: Get the right value in my array


code:
import matplotlib
matplotlib.use('Qt4Agg')
matplotlib.rcParams['backend.qt4']='PySide'
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT
import matplotlib.pyplot as plt

from PySide import QtGui
import sys

def new_figure():

    fig = plt.figure()
    plt.plot([0, 1], [2, 3])
    plt.close(fig)
    return fig

class myFigCanvas(QtGui.QWidget):

    def __init__(self, fig, parent=None):
        super(myFigCanvas, self).__init__(parent)

        #---- create new canvas and toolbar --

        canvas = FigureCanvasQTAgg(fig)
        toolbar = NavigationToolbar2QT(canvas, self)

        #---- setup layout of GUI ----

        grid = QtGui.QGridLayout()
        grid.addWidget(canvas, 0, 0)
        grid.addWidget(toolbar, 1, 0)

        self.setLayout(grid)

if __name__ == '__main__':

    app = QtGui.QApplication(sys.argv)

    fig = new_figure()
    new_canvas = myFigCanvas(fig)
    new_canvas.show()

    sys.exit(app.exec_())

rawDescription: Matplotlib: how to show a figure that has been closed


code:
def getEpisodeTuple(iterable):
    for chunk in iterable:
        echunk = episodeChunk(chunk)
        if echunk:
            return echunk

rawDescription: My first Python program! Anyone care to review it an help me improve?


code:
now = datetime.datetime.now()
delta = (0 if now.microsecond < 500000 else 1000000) - now.microsecond
now_frmt = now + datetime.timedelta(microseconds=delta)

rawDescription: Python: format datetime efficiently whilst leaving it as a datetime object


code:
x1 = np.linspace(0, 0.4, 100)
y1 = -100 * x1 + 100
plt.figure(figsize = (7,7))
plt.subplot(111)

plt.plot(x1, y1, linestyle = '-.', linewidth = 0.5, color =  'black')
for i in range(5):
    x_val = np.linspace(x[0, i] - 0.05, x[-1, i] + 0.05, 100)
    poly = np.polyfit(x[:, i], y[:, i], deg=2)
    y_int  = np.polyval(poly, x_val)
    plt.plot(x[:, i], y[:, i], linestyle = '', marker = 'o')
    plt.plot(x_val, y_int, linestyle = ':', linewidth = 0.25, color =  'black')
    ix = quadratic_intersections(poly, [0, -100, 100])
    plt.scatter(*ix, marker='x', color='black', s=40, linewidth=2)

plt.xlabel('X')
plt.ylabel('Y')
plt.xlim([0,.35])
plt.ylim([40,110])
plt.show()

rawDescription: How to find the points of intersection of a line and multiple curves in Python?

description: Find the points of intersection of a line and multiple curves in Python


code:
with open('sample','w') as textwriter:
    for line in subbedlines:
        textwriter.write("%s\n" % line)

rawDescription: Replacing 'match' object with string, Python


code:
def using_merge(df1, df2):
    merged = pd.merge(df1, df2, on=["obs", "year"], how="left")
    mask = ~np.isfinite(merged.val_x)
    merged.loc[mask, 'val_x'] = merged.loc[mask, 'val_y']
    return merged['val_x']

def using_update(df1, d2):
    merged = pd.merge(df1, df2, on=["obs", "year"], how="left")
    merged['val_y'].update(merged['val_x'])
    return merged['val_y']

def using_set_index(df1, df2):
    df1 = df1.set_index(['obs','year'])
    df2 = df2.set_index(['obs','year'])
    return df1['val'].combine_first(df2['val'])

rawDescription: pandas DataFrame update/combine when indices don't align

description: Pandas DataFrame update/combine when indices don't align


code:
#config.py
class Configuration:
    __shared_state = {}
    def __init__(self, *import_sections):
        self.__dict__ = self.__shared_state
        if not import_sections: # we are not initializing this time
            return
        #your old code verbatim

rawDescription: Access instance in other modules

description: Access instance in other modules


code:
dt1=np.dtype([('anything', 'V',10), ('counter','i4')])
A1=np.zeros(5,dt1)
A1['anything'][0]=b'anything'
A1['anything'][1]=b'0123456789'
A1['anything'][2]=pickle.dumps((1,2))
pickle.loads(A1['anything'][2])

rawDescription: Understanding numpy "void" dtype and generic arrays


code:
X, Y = np.indices(data.shape)
mask = ~np.isnan(data)
x = X[mask]
y = Y[mask]
data = data[mask]

rawDescription: Python 2D Gaussian Fit with NaN Values in Data


rawDescription: How to compare a list of lists/sets in python?

description: Compare a list of lists/sets in python


code: sum(z for z in y if isinstance(z, int))

rawDescription: How do you set a conditional in python based on datatypes?

description: Set a conditional in python based on datatypes


code:
var = sys.modules['Test2'].var
function = sys.modules['Test2'].function

rawDescription: python: imported module is in a different context

description: Python: imported module is in a different context


code:
'Inside = ' + str(inside)
'Inside = ' + ', '.join(inside)

rawDescription: Good way to concatenate str to list?

description: Good way to concatenate str to list


code: new_im.paste(old_im,(0,0), mask=old_im)  # Using old_im as the mask argument should tell the paste function to use old_im's alpha channel to combine the two images.

rawDescription: Python: Combining images using paste with overlapping pixels and areas with alpha channel=0


rawDescription: Selenium and Python 3 – unable to find element


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code:
import re
numbers = re.compile('\d+(?:\.\d+)?')
numbers.findall("It took 2.3 seconds")

rawDescription: Python: Strip Everything but Numbers

description: Python: Strip Everything but Numbers


rawDescription: Create a new array from numpy array based on the conditions from a list


code:
from functools import lru_cache

@lru_cache(maxsize=None)
def callTest2(n, k):
    if k == 0:
        return 1
    elif k == n:
        return 1
    elif (1 <= k) and (k <= (n-1)):
        result = ((callTest2(n-1, k) + callTest2(n-1, k-1)))
    print(result)
    return result

rawDescription: Memoization Usage/Cache Storing

description: Memoization Usage/Cache Storing


rawDescription: Pandas - series creation results in NaN when index is passed in?


code:
planet = IntVar()
planet.set(0)

buttonBlue = Radiobutton(wind, text="Blue Planet", variable=planet, value=1)
buttonOrange = Radiobutton(wind, text="Orange Planet", variable=planet, value=0)
...
def choice (event):#Function binded to can, move the selected planet (blue = 1, prange = 0)
    if planet.get() == 0:
        moveOrange(event)
    else :
        moveBlue(event)

rawDescription: How to avoid global variables in command function call

description: Avoid global variables in command function call


code:
class Project(models.Model):
    contact = models.ForeignKey(Contact)
    title = models.CharField(max_length=100)
    address1 = models.CharField(max_length=200)
    valueProposed = models.IntegerField(default=0)
    valueActual = models.IntegerField(default=0)

    def __str__(self):
        return self.title

class ProjectTask(models.Model):
    project = models.ForeignKey(Project, related_name='tasks')
    description = models.CharField(max_length=200)
    contact = models.ForeignKey(Contact)
    amount = models.IntegerField(default=0)

    def __str__(self):
        return self.description

rawDescription: django parent child summation in view and pass to a template

description: Django parent child summation in view and pass to a template


code:
class User(object):
   first_name = models.CharField(max_length=255)

   def get_username(self):
       return self.username

class Employee(User):
   title = models.CharField(max_length=255)

rawDescription: django abstract models versus regular inheritance

description: Django abstract models versus regular inheritance


rawDescription: Django REST framework foreign keys and filtering


code: max_row_in_col_j = np.argmax(F[:,j])

rawDescription: Numpy.argmax() on certain axis in 2D matrix


code: allList = list(itertools.chain(list1, list2, list3))

rawDescription: how do I concatenate 3 lists using a list comprehension?

description: Concatenate 3 lists using a list comprehension


code:
import re
found = re.findall('|'.join(searchList),cleanText)

rawDescription: Fastest way in python to search for multiple items in a body of text


code:
A = numpy.random.randint(100,size=(5,10))
B = np.column_stack(([4,2,1,3,4],np.zeros(5)))

rawDescription: numpy array slicing to avoid for loop

description: Numpy array slicing to avoid for loop


code:
df['idx'] = df.groupby('Salesman').cumcount()

tmp = []
for var in ['product','price']:
    df['tmp_idx'] = var + '_' + df.idx.astype(str)
    tmp.append(df.pivot(index='Salesman',columns='tmp_idx',values=var))

reshape = pd.concat(tmp,axis=1)

rawDescription: Pandas long to wide reshape

description: Pandas long to wide reshape


code:
result.index = [d.strftime('%Y-%m') for d in df.loc[1::2, 'Idx']]
print(result)
#          A  B  C
# 2004-04  2  2  0
# 2004-05  0  0  0

# [2 rows x 3 columns]

rawDescription: Pandas Python: Merging every two rows in one dataframe


code:
import bottle

config_app = bottle.Bottle()

@config_app.route('/config1')
def config1():
    return 'some config data'

rawDescription: Inserting a folder containing specific routes to a bottle application in Python


code: {k: v.tolist() for k,v in df.groupby("category")["ID"]}

rawDescription: fast sorting of a csv file in python

description: Fast sorting of a csv file in python


code:
cursor.execute('''
    SELECT
        col3 as aaa, col9 as bbb,
        col6 || ' (' || col5 || ')' as hhh,
        col9 || ' ? ' || col10 as jjj
    FROM SOME_TABLE
''')

rawDescription: Improve loop efficiency

description: Improve loop efficiency


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

data = np.random.rand(10, 10)

cmap = matplotlib.cm.binary
plt.imshow(data, interpolation="nearest", cmap=cmap)
plt.show()

rawDescription: Spectrogram - Whitening out specific areas


code:
work
call
work
call
work
return

rawDescription: Understanding recursion in Python 2 (Think Python, exercise 5)


code:
for seq in sequences:
    lower_output.append(re.findall("[a-z]+", seq)) # add substrings

rawDescription: Using regex to findall lowercase letters in string append to list. Python


code:
b_iter = iter(b)
a = [next(b_iter) if i is None else i for i in a]

rawDescription: minimize memory consumption when dealing with python list assignment

description: Minimize memory consumption when dealing with python list assignment


rawDescription: trouble appending lists to another list

description: Trouble appending lists to another list


code:
import requests
from bs4 import BeautifulSoup
import pandas as pd

url = "http://api.turfgame.com/v3/zones"
r = requests.get(url)
soup = BeautifulSoup(r.content)

col_names = ["name", "lat", "lng", "points_take", "points_hold"]
data = []

def get_all_zones():
    for attr in soup.find_all("zone"):
        col_values = [attr.get("name"), attr.get("lat"), attr.get(
            "lng"), attr.get("points_take"), attr.get("points_hold")]
        data.append(col_values)
    dfi = pd.DataFrame(data, columns=col_names)

    return dfi

dfi = get_all_zones()
print(dfi)

rawDescription: Creating a DataFrame using .loc to set with enlargement


code:
@property
def has_access_token(self):
    return True

rawDescription: How do I turn a django model method into a parameter?

description: Turn a django model method into a parameter


rawDescription: Python: I have a dual key list, which is the most effective storage object for retreival


rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


code:
s.index = s.index.to_period('M').to_timestamp('M')
s

rawDescription: How to iterate over time periods in pandas

description: Iterate over time periods in pandas


rawDescription: Summing 2nd list items in a list of lists of lists


code:
ub_tries = 8
tries_dict = {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'}
tries_dict.update({i: 'next' for i in range(5, ub_tries)})
tries_dict
tries_dict[6]

rawDescription: use a range as a dictionary key in Python, what option do I have?

description: Use a range as a dictionary key in Python, what option do I have


code:
x = uuid.uuid1()
x
x.int
((((((((((x.time_low << 16) | x.time_mid) << 16) | x.time_hi_version) << 8) | x.clock_seq_hi_variant) << 8) | x.clock_seq_low) << 48) | x.node) == x.int
x.time
(((((x.time_hi_version & 0xFFF) << 16) | x.time_mid) << 32) | x.time_low) == x.time

rawDescription: Sorting a list of UUID v1 in python

description: Sorting a list of UUID v1 in python


code:
def visit_Attribute(self, node):
    print('  attribute %s' % node.attr)
    self._visit_children(node)

rawDescription: Python ast package: traversing object hierarchies


code:
class ProxyCall(object):
   '''Class implementing the dispatch for a certain method call'''
   def __init__(self, proxy, methodname):
      self.proxy = proxy
      self.methodname = methodname

   def __call__(self, *p, **kw):
      if p[0] == "EU": # or however you determine the destination
         return getattr(self.proxy.EU, self.methodname)(*p, **kw);
      else:
         return getattr(self.proxy.OTHER, self.methodname)(*p, **kw);

class Proxy(object):
   '''Class managing the different "equivalent" instances'''
   def __init__(self, EU, OTHER):
      self.EU = EU
      self.OTHER = OTHER

   def __getattr__(self, name):
      if not hasattr(self.EU, name):
         # no such method
         raise AttributeError()
      else:
         # return object that supports __call__ and will make the dispatch
         return ProxyCall(self, name)

rawDescription: Is there a way to inspect incoming args from within __getattr__ or to somehow otherwise redirect a call based upon incoming arguments?


rawDescription: Regex insert space every third character, except at end of line


code: result.to_csv( 'result.txt', sep='\t')

rawDescription: Pandas DataFrame - Combining one column's values with same index into list


code:
import matplotlib.pyplot as plt # I include a module which contains the plotting functionality I need: https://docs.python.org/2/tutorial/modules.html
plt.plot(X_cord,   # here go the X coordinates
         Y_cord,   # here go the Y coordinates
         marker='x', # as I'm plotting only one point here, I'd like to make it extra visible
         markersize=10 # by choosing a nice marker shape ('x') and large size
         )
plt.show() # this shows the current plot in a pop-up window

rawDescription: Plotting a graph in python

description: Plotting a graph in python


code:
dict_of_lists = {}

for item in my_list:
    _, key, _ = item
    if key in dict_of_lists.keys():
        dict_of_lists[key] = dict_of_lists[key] + item
    else:
        dict_of_lists[key] = item

rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


code:
class process:
    def __call__(self, lst):
        if len(lst) < 1:
            return lst

        self.prev = lst[0]
        self.n = 0

        return [ list(g) for k, g in itertools.groupby(lst, self._grouper) ]

    def _grouper(self, x):
        if x < self.prev:
            self.n += 1

        self.prev = x
        return self.n

data = [45,78,120,47,58,50,32,34]
print (list(process()(data)))

rawDescription: Python: Find monotonic sequences in a list


code:
class DumbArgWrapper(object):
    def __init__(self, *args):
        self.args = args

class Resize(DumbArgWrapper): pass
class Cutoff(DumbArgWrapper): pass
class Blur(DumbArgWrapper): pass

class ImageProcessor(object):
    def preprocess(self, *args):
        for arg in args:
            if isinstance(arg, Resize):
                do_resize(*arg.args)
            # etc.

rawDescription: Handling arguments in order for preprocessing in Python, when order matters


rawDescription: Inserting binary notation of numbers in python list


code:
import numpy as np
a = np.random.randint(0, 5, size=(5, 4))
a
b = a < 3
b

c = b.astype(int)
c

rawDescription: Replacing Numpy elements if condition is met


code: sample_average = mc.Lambda('sample_average', lambda x=list_of_samples, n=samples_to_average: np.mean(x[:n]))

rawDescription: Passing parameters to deterministic variables, pymc


rawDescription: Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes


code:
class Dishes(models.Model):
    name = models.CharField(max_length=40, unique=True)
    likes = models.ManyToManyField(Likes)

class Likes(models.Model):
    dish = models.ForeignKey(Dishes)
    user = models.ForeignKey(User)
    date_added = models.DateTimeField(auto_now_add=True)

rawDescription: How to show whether user already liked object instance in Django

description: Show whether user already liked object instance in Django


code: some_list = [item for item in some_iterable]

rawDescription: python - beautifulsoup - find variable amount of text in between tags

description: Python - beautifulsoup - find variable amount of text in between tags


code:
head = soup.head
head.append(soup.new_tag('style', type='text/css'))
head.style.append('body {background-color:#b0c4de;}')

rawDescription: How can I add background color inside html code using beautifulsoup?

description: Add background color inside html code using beautifulsoup


code:
def dfs_code_key(pm):
    return (pm.from_label, pm.edge_label, pm.to_label)

rawDescription: Sorting a list of dictionary key objects with custom comparison function in Python


code:
df = pd.DataFrame(dict(Independent=[-1,0,1,4,0], Column2=[0,1,0,2,2]))
df

rawDescription: Pandas if statements

description: Pandas if statements


code:
def as_quat_array(a):
    "View a float array as an array of floats with one extra dimension of size 4"
    if(a.shape[-1]==4) :
        return a.view(np.quaternion).reshape(a.shape[:-1])
    return a.view(np.quaternion).reshape(a.shape[:-1]+(a.shape[-1]//4,))

rawDescription: Creating new numpy scalar through C API and implementing a custom view


code:
someperson = {0 : {name:"Dannnno", income:100}}
someotherperson = {1: {name:"kcd", income:100}}

rawDescription: Best way to make 'n' objects with each with unique data contents?

description: Make 'n' objects with each with unique data contents


code:
from IPy import IP
IP('127.0.0.1')

rawDescription: How to check if a string matches an IP adress pattern in python?

description: Check if a string matches an IP adress pattern in python


code: [0 for j in range(colNum)]

rawDescription: Cannot understand a python code

description: Cannot understand a python code


code:
for each_username in usernames:
    if (username==each_username):
        pass_result=cursor.execute('SELECT PASSWORD from validate where username=?',(each_username,))
    password1=[row[0] for row in pass_result.fetchall()]
    for each_password in password1:
        if (each_password==password):
            print('Login Success')
            execfile(PATH_TO_THE_FILE+"./welcome.py")
        else:
            print('Login Failure')

rawDescription: How to execute another python program when some condition is met?

description: Execute another python program when some condition is met


rawDescription: Efficient way of appending / extracting list elements


code:
from bisect import bisect
for s in l1:
    ind = bisect(l2, s, hi=len(l2) - 1)
    ind -= s - l2[ind-1] < l2[ind] - s
    tmp = l2[ind]
    print("{} -> {}".format(s,tmp if tmp  - s < 6 else "NULL"))

rawDescription: Using bisect for combing items with a distance condition


code: matches = [line for line in lines if line == lineA]

rawDescription: Python - most efficient way of matching a list


code:
[{'count': 5, 'text': 'hallo world', 'num': 1},
{'count': 1, 'text': 'hallo world', 'num': 2},
{'count': 1, 'text': 'haltlo world', 'num': 1}]

rawDescription: python 2.6-removing and counting duplicates in a list of dictionaries effeciently

description: Python 2.6-removing and counting duplicates in a list of dictionaries effeciently


code:
self.config = {
                  'user': 'begueradj',
                  'passwd': 'begueradj',
                  'host': '127.0.0.1',
                  'db': 'begueradj',
        }

rawDescription: how to connect to mysql database from gui made in python

description: Connect to mysql database from gui made in python


rawDescription: Removing empty entries and adding them as a whitespace in the previous entry of a list


code:
count = np.bincount(zones.flat)
tot = np.bincount(zones.flat, weights=values.flat)
avg = tot/count
result_data2 = avg[zones]

rawDescription: python numpy mask mean performance

description: Python numpy mask mean performance


code:
import imdb
import re

ia = imdb.IMDb()
avatar = ia.get_movie("0120667")
ia.update(avatar, 'business')
opening_weekends = avatar['business']['opening weekend']

def parseDate(date):
    result = {}

    if re.match(".*\d{4}$", date):
        result['year'] = date[-4:]

    m = re.match(".*(?P<month>January|February|March|April|May|June|July|"
                "August|September|October|November|December).*", date, re.I)
    if m:
        result['month'] = m.group('month').lower()

        # try to grab date too then
        daymatch = re.match("^(?P<day>\d{1,2}).*", date)

        if daymatch:
            result['day'] = daymatch.group('day')
    return result

def parseBudget(amount):
    """
    assumptions:
    - currency is always before the number
    - no fractions
    """

    # find index first number
    for i in range(len(amount)):
        if amount[i] in "0123456789":
            amount_idx = i
            break

    currency = amount[:amount_idx].strip()
    amount = re.sub("\D", "", amount[amount_idx:])

    return amount, currency

def parseWeekendGross(gross_text):
    g = gross_text.split(' (')
    if not len(g) == 4:
        return ""
    amount, currency = parseBudget(g[0])
    country = g[1].lstrip('(').rstrip(')')
    date = parseDate(g[2].lstrip('(').rstrip(')'))
    day, month, year = date['day'], date['month'], date['year']
    screens = re.sub("\D", "", g[3])
    if not screens:
        screens = "''"

    return amount, currency, country, day, month, year, screens

for entry in opening_weekends:
    amount, currency, country, day, month, year, screens = parseWeekendGross(entry)
    if country == "USA":
        print("Country: %s" % country)
        print("Date: %s %s %s" % (day, month, year))
        print("Screens: %s" % screens)
        break

rawDescription: IMDBpy getting screen information

description: IMDBpy getting screen information


rawDescription: Python: a could be rounded to b in the general case


code:
class ASearcher:
    def __init__(self, a):
        self.a = a
    def isin(self, b):
        a = self.a
        a0 = a[0]
        lena = len(a)
        i = 0
        try:
            while 1:
                j = b.index(a0, i) # raises ValueError if not found
                if a == b[j: j+lena]:
                    return True
                i = j+1  # start search over 1 position later
        except ValueError:
            return False

rawDescription: Python 3: check if the entire list is inside another list


code:
s = fh.read().replace('\n', '')
# or
s = "".join(s.readLines())

rawDescription: Searching a string for a substring of characters in a list


code:
def process_view(self, request, view_func, view_args, view_kwargs):
    company = view_kwargs.get('company', None)

rawDescription: Django: How to access URL regex parameters inside a middleware class?


rawDescription: Vectorizing feature hashing in python

description: Vectorizing feature hashing in python


code: return [(item, value) for item, value in config.items(section)]

rawDescription: Python - Return values from a function

description: Python - Return values from a function


code:
from django.http import HttpResponsePermanentRedirect
from django.test.client import Client

class MyTestClass(unittest.TestCase):

    def test_my_method(self):

        client = Client()
        response = client.post('/some_url/')

        self.assertEqual(response.status_code, 301)
        self.assertTrue(isinstance(response, HttpResponsePermanentRedirect))
        self.assertEqual(response.META['HTTP_LOCATION'], '/url_we_expect_to_be_redirected_to/')

rawDescription: Django: How to test for 'HttpResponsePermanentRedirect'


code:
class RawUsageHelpFormatter(argparse.HelpFormatter):
    def _format_usage(self, usage, actions, groups, prefix):
        # use actions in the order that they are define
        # no line wrapping
        if prefix is None:
            prefix = 'usage: '
        if usage is not None:
            usage = usage % dict(prog=self._prog)
        elif usage is None and not actions:
            usage = '%(prog)s' % dict(prog=self._prog)
        elif usage is None:
            prog = '%(prog)s' % dict(prog=self._prog)
            format = self._format_actions_usage
            action_usage = format(actions, groups)
            usage = ' '.join([s for s in [prog, action_usage] if s])
        return '%s%s\n\n' % (prefix, usage)

rawDescription: python argparse parameter order

description: Python argparse parameter order


code:
def genDigit():
    return random.randint(0, 9)

def genNumber():
    return [genDigit() for c in range(4)]

rawDescription: Appending result of function into a list


rawDescription: Python generate from list instead of Genfromtext


code:
isinstance(eval(word), type)
isinstance(eval('list'), type)

rawDescription: Probing a python function

description: Probing a python function


code:
str = "h3110 23 cat 444.4 rabbit 11 2 dog"
[int(s) for s in str.split() if s.isdigit()]

rawDescription: Python: Extract numbers from a string

description: Python: Extract numbers from a string


code:
import re
re.sub(r'\ba\b(?=\s+[aeiouAEIOU])', 'an', "a acrobat jumped over a bridge")
re.sub(r'\ba\b(?=\s+[aeiouAEIOU])', 'an', "a elephant")

rawDescription: Replacing regex with new regex

description: Replacing regex with new regex


code: df.groupby('Chain_key').filter(lambda x: len(x) >= 2)

rawDescription: pandas count number of same element in column and erase if the number is small

description: Pandas count number of same element in column and erase if the number is small


rawDescription: Remove ' from python list

description: Remove ' from python list


code:
import requests

word_site = "http://svnweb.freebsd.org/csrg/share/dict/words?view=co&content-type=text/plain"

response = requests.get(word_site)
WORDS = response.content.splitlines()

rawDescription: Random word generator- Python

description: Random word generator- Python


code: deltas[(deltas<0) | (deltas>100)]=0

rawDescription: Can I cleanse a numpy array without a loop?

description: Cleanse a numpy array without a loop


code:
a = np.arange(10)
np.where(np.in1d(a,b), 999, a)

rawDescription: change value in numpy array based on presence in another array

description: Change value in numpy array based on presence in another array


code:
from django.db.models import get_model
model = get_model("string name of model class")
return model.objects.all()

rawDescription: making a variable name variable?

description: Making a variable name variable


code:
import matplotlib.pyplot as plt
from matplotlib import gridspec
from calendar import month_name

cols = 7 # corresponding to days of the week
rows = 5 # int(np.ceil(31/7)), 31=max(days in a month)
num_days = rows * cols

for i, month in enumerate(months):
    gs = gridspec.GridSpec(rows, cols)
    fig = plt.figure()
    plt.suptitle(month_name[month], size='x-large')

    for day in range(num_days):
        # filter pressure on a daily basis according to month and day
        daily_pressure = noisy_pressure[(time.month==month) & (time.day==day+1)]
        # need to tile array in order to plot it with plt.pcolormesh
        daily_pressure_2d = np.tile(daily_pressure, (2, 1)).T

        if daily_pressure_2d.size > 0:
            ax = fig.add_subplot(gs[day])
            cmesh = ax.pcolormesh(X, hours_2d, daily_pressure_2d,
                                  vmin=noisy_pressure.min(),
                                  vmax=noisy_pressure.max())
            # remove x and y ticklabels and x tick marks
            ax.set_xticklabels([]); ax.set_xticks([])
            ax.set_yticklabels([])
            ax.set_xlabel('{month} {day}'.format(
                month=month_name[month][:3], day=day+1))
            ax.set_ylim((hours.min(), hours.max()))
        else:
            # basically create an empty plot for days without pressure data
            ax = fig.add_subplot(gs[day])
            ax.axis('off')

    plt.tight_layout() # for nicer formatting
    fig.subplots_adjust(top=0.9) # create room for suptitle
    fig.subplots_adjust(right=0.85) # create room for colorbar
    # create colorbar with customized location
    cbar_ax = fig.add_axes([0.87, 0.05, 0.03, 0.85])
    fig.colorbar(cmesh, cax=cbar_ax)

rawDescription: Plotting colormap graph for each day side by side


code: dict.__add__ = lambda x, y: None

rawDescription: Override operator of built-in object

description: Override operator of built-in object


code:
def wow(amount):
    if amount <= 0:
        return "Don't be so negative!"
    elif amount == 1:
        return "Wow!"
    else:
        return inner_wow("", amount)

    def inner_wow(wow_str, amount):
        if amount == 0:
            return
        else:
            wow_str += "Wow! \n"
            return wow(wow_str, amount - 1)

rawDescription: Recursive function without return - Python 2.7


rawDescription: Solve for the positions of all six roots PYTHON


code:
my_query = '''SELECT val_1, val_2
              FROM   my_table
              WHERE  val_1 IN ({:s});'''.format(",".join("?"*len(key_indexes)))
# -> 'SELECT val_1, val_2 FROM my_table WHERE val_1 IN (?,?,?);'
c.execute(myquery, ind).fetchall()

rawDescription: sqlite3 in Python extract entries that correspond to values in tuple

description: Sqlite3 in Python extract entries that correspond to values in tuple


code:
# Open for read/write with file initially at beginning
with open("file.txt", "r+") as f:
    lines = list(f)
    f.seek(0)
    for i in range(min(len(lines), len(alist))):
        f.write(lines[i].rstrip('\n'))
        f.write(' ')
        f.write(str(alist[i]))
        f.write('\n')
    # Uncomment the following lines to keep all lines from the file without
    # matching values in alist
    #if len(lines) > len(alist):
    #    f.writelines(lines[len(alist):])
    f.truncate()  # Not needed here, but good habit if file might shrink from change

rawDescription: Appending each element of list at the end of file lines


code: [{'5IVUPHE42HP1NEYvKb7qSvpX2Cm': {'ab_leads': 1, 'cp_leads': 0}}, ...]

rawDescription: How to write a reduce phase function in erlang on riak database

description: Write a reduce phase function in erlang on riak database


code:
class WeirdString2(str):
    split = remove_empty(str.split)

WeirdString2('This decorator is unnecessary\n\n\n').split('\n')

rawDescription: Is it possible to apply my own decorators to builtin methods in Python?


code:
import base64

with open('frameBorder.gif', 'wb') as f:
    decoded = base64.decodestring(b"""
    R0lGODlhQABAAPcAAHx+fMTCxKSipOTi5JSSlNTS1LSytPTy9IyKjMzKzKyq
    rOzq7JyanNza3Ly6vPz6/ISChMTGxKSmpOTm5JSWlNTW1LS2tPT29IyOjMzO
    zKyurOzu7JyenNze3Ly+vPz+/OkAKOUA5IEAEnwAAACuQACUAAFBAAB+AFYd
    QAC0AABBAAB+AIjMAuEEABINAAAAAHMgAQAAAAAAAAAAAKjSxOIEJBIIpQAA
    sRgBMO4AAJAAAHwCAHAAAAUAAJEAAHwAAP+eEP8CZ/8Aif8AAG0BDAUAAJEA
    AHwAAIXYAOfxAIESAHwAAABAMQAbMBZGMAAAIEggJQMAIAAAAAAAfqgaXESI
    5BdBEgB+AGgALGEAABYAAAAAAACsNwAEAAAMLwAAAH61MQBIAABCM8B+AAAU
    AAAAAAAApQAAsf8Brv8AlP8AQf8Afv8AzP8A1P8AQf8AfgAArAAABAAADAAA
    AACQDADjAAASAAAAAACAAADVABZBAAB+ALjMwOIEhxINUAAAANIgAOYAAIEA
    AHwAAGjSAGEEABYIAAAAAEoBB+MAAIEAAHwCACABAJsAAFAAAAAAAGjJAGGL
    AAFBFgB+AGmIAAAQAABHAAB+APQoAOE/ABIAAAAAAADQAADjAAASAAAAAPiF
    APcrABKDAAB8ABgAGO4AAJAAqXwAAHAAAAUAAJEAAHwAAP8AAP8AAP8AAP8A
    AG0pIwW3AJGSAHx8AEocI/QAAICpAHwAAAA0SABk6xaDEgB8AAD//wD//wD/
    /wD//2gAAGEAABYAAAAAAAC0/AHj5AASEgAAAAA01gBkWACDTAB8AFf43PT3
    5IASEnwAAOAYd+PuMBKQTwB8AGgAEGG35RaSEgB8AOj/NOL/ZBL/gwD/fMkc
    q4sA5UGpEn4AAIg02xBk/0eD/358fx/4iADk5QASEgAAAALnHABkAACDqQB8
    AMyINARkZA2DgwB8fBABHL0AAEUAqQAAAIAxKOMAPxIwAAAAAIScAOPxABIS
    AAAAAIIAnQwA/0IAR3cAACwAAAAAQABAAAAI/wA/CBxIsKDBgwgTKlzIsKFD
    gxceNnxAsaLFixgzUrzAsWPFCw8kDgy5EeQDkBxPolypsmXKlx1hXnS48UEH
    CwooMCDAgIJOCjx99gz6k+jQnkWR9lRgYYDJkAk/DlAgIMICkVgHLoggQIPT
    ighVJqBQIKvZghkoZDgA8uDJAwk4bDhLd+ABBmvbjnzbgMKBuoA/bKDQgC1F
    gW8XKMgQOHABBQsMI76wIIOExo0FZIhM8sKGCQYCYA4cwcCEDSYPLOgg4Oro
    uhMEdOB84cCAChReB2ZQYcGGkxsGFGCgGzCFCh1QH5jQIW3xugwSzD4QvIIH
    4s/PUgiQYcCG4BkC5P/ObpaBhwreq18nb3Z79+8Dwo9nL9I8evjWsdOX6D59
    fPH71Xeef/kFyB93/sln4EP2Ebjegg31B5+CEDLUIH4PVqiQhOABqKFCF6qn
    34cHcfjffCQaFOJtGaZYkIkUuljQigXK+CKCE3po40A0trgjjDru+EGPI/6I
    Y4co7kikkAMBmaSNSzL5gZNSDjkghkXaaGIBHjwpY4gThJeljFt2WSWYMQpZ
    5pguUnClehS4tuMEDARQgH8FBMBBBExGwIGdAxywXAUBKHCZkAIoEEAFp33W
    QGl47ZgBAwZEwKigE1SQgAUCUDCXiwtQIIAFCTQwgaCrZeCABAzIleIGHDD/
    oIAHGUznmXABGMABT4xpmBYBHGgAKGq1ZbppThgAG8EEAW61KwYMSOBAApdy
    pNp/BkhAAQLcEqCTt+ACJW645I5rLrgEeOsTBtwiQIEElRZg61sTNBBethSw
    CwEA/Pbr778ABywwABBAgAAG7xpAq6mGUUTdAPZ6YIACsRKAAbvtZqzxxhxn
    jDG3ybbKFHf36ZVYpuE5oIGhHMTqcqswvyxzzDS/HDMHEiiggQMLDxCZXh8k
    BnEBCQTggAUGGKCB0ktr0PTTTEfttNRQT22ABR4EkEABDXgnGUEn31ZABglE
    EEAAWaeN9tpqt832221HEEECW6M3wc+Hga3SBgtMODBABw00UEEBgxdO+OGG
    J4744oZzXUEDHQxwN7F5G7QRdXxPoPkAnHfu+eeghw665n1vIKhJBQUEADs=""")
    f.write(decoded)

rawDescription: Tkinter image as frame style

description: Tkinter image as frame style


code:
Instantiating
__init__

rawDescription: get notified whenever a certain class I don't control is instantiated in python

description: Get notified whenever a certain class I don't control is instantiated in python


code:
whole_file_text.replace('\n', ' ')
whole_file_text.replace('\n', '')

rawDescription: Read text file as a whole

description: Read text file as a whole


code:
def LIS(A):

    # make a list of lists
    L = list()
    for i in range(0, len(A)):
        L.append(list())

    # the first increasing subsequence is the first element in A
    L[0].append(A[0])

    for i in range(1, len(A)):
        for j in range(0, i):

            # a new larger increasing subsequence found
            if (A[j] < A[i]) and (len(L[i]) < len(L[j])):
                'throw the previous list'
                L[i] = []
                'add all elements of L[j] to L[i]'
                L[i].extend(L[j])
        L[i].append(A[i])

    for i in range(len(A)):
    # print an increasing subsequence
        print (L[i])
A = [3, 5, 10, 0, 1, 100, 2, 4, 7]
LIS(A)

rawDescription: Obtaining the longest increasing subsequence in Python


code:
data = {'networks': {'prod': 'value'}, 'services': {'web': {'name': 'x'}}}
modification = {'services.web.name': 'new'}

for key, value in modification.items():
    keyparts = key.split('.')
    to_modify = data
    for keypart in keyparts[:-1]:
        to_modify = to_modify[keypart]
    to_modify[keyparts[-1]] = value

print(data)

rawDescription: Use list of indices to manipulate a nested dictionary


code:
from copy import deepcopy
c = deepcopy(a)
c.update(b)
type(c)  #returns a dict
print(a)
print(b)
print(c)

rawDescription: update method of python dictionary did not work

description: Update method of python dictionary did not work


code:
source = sources[0]
eval(source, func.__globals__)

rawDescription: Is it possible to access inner functions and classes via code objects?


code:
if arow == '*': continue
# process the row

rawDescription: Removing rows dependent on one column Python


code:
import subprocess

executable_code = """
print 'inside script'
print 123
"""

code_with_exception = """
raise Exception()
"""

ok_rc = subprocess.call(['python', '-c', executable_code])
assert ok_rc == 0

bad_rc = subprocess.call(['python', '-c', code_with_exception])
assert bad_rc == 1

rawDescription: How to execute a string containing a script using python subprocess module

description: Execute a string containing a script using python subprocess module


code:
import re

quotes = re.findall('"([^"]*)"', string)

rawDescription: How can I select a string using start and endpoints (characters)?

description: Select a string using start and endpoints (characters)


rawDescription: Trying to create a list of users in AD

description: Trying to create a list of users in AD


code: k

rawDescription: Vectorized Splitting of String on Character Count using Numpy or Pandas


code:
from itertools import izip
zipped = izip(list1, list2, list3)
with open('existing.csv', 'rb') as infile, open('out_file.csv', 'wb') as outfile:
    reader = csv.reader(infile)
    headers = next(reader)
    writer = csv.writer(outfile)
    writer.writerow(headers+["list1", "list2", "list3"])
    for  row in  reader:
        row.extend(next(zipped))
        writer.writerow(row)

rawDescription: Adding headers to a csv file

description: Adding headers to a csv file


code:
import socket
import imaplib
socket.setdefaulttimeout(10)
imap = imaplib.IMAP4('test.com', 666)

rawDescription: Does Python's imaplib let you set a timeout?


code:
actual_hosts = set()
for result in results.ResultsReader(job.results()):
    actual_hosts.update(results.values())

rawDescription: Store OrderedDict Values to Set in Python


code:
import csv
with open("output.csv","w",newline='') as f:
    output = csv.writer(f)
    for line in csv.reader(open("input.csv")):
        for item in line[2:]:

            #to skip empty cells
            if not item.strip():
                continue

            item = item.split(":")
            print([line[1]+item[0],item[1].rstrip("%")])
            output.writerow([line[1]+item[0],item[1].rstrip("%")])

rawDescription: Data parsing/importing, formatting and exporting using python-2.7


code:
for a in args:
    i, j = a.shape
    result[:i, :j] += a

rawDescription: adding numpy arrays of differing shapes

description: Adding numpy arrays of differing shapes


code:
with open('some_file.csv', 'wb') as f:
    outfileWriter = csv.writer(f,delimiter='\t')
    for n in G:
        outfileWriter.writerow([n,betweenness_centr[n],eigenvector_centr[n]])

rawDescription: Networkx: What is the best way to list centralities for each node?


code:
class Request(db.Model):
    id = db.Column(db.Integer, autoincrement=True, primary_key=True)
    description = db.Column(db.Text(250))

    notification_id = db.Column(db.Integer, ForeignKey('notification.id'))
    notification = db.relationship('Notification')

    type = db.Column(db.String(50))

    __mapper_args__ = {
        'polymorphic_identity': 'request',
        'polymorphic_on': type,
    }

class DailyLeaveRequest(Request):
    id = db.Column(db.Integer, db.ForeignKey('request.id'), primary_key=True)

    demand_date = db.Column(db.Date, nullable=False)

    __mapper_args__ = {
        'polymorphic_identity': 'dailyleave',
    }

class HourlyLeaveRequest(Request):
    id = db.Column(db.Integer, db.ForeignKey('request.id'), primary_key=True)

    demand_date = db.Column(db.Date, nullable=False)
    time_from = db.Column(db.String(10), nullable=False)
    time_to = db.Column(db.String(10), nullable=False)

    __mapper_args__ = {
        'polymorphic_identity': 'hourlyleave',
    }

def FundRequest(Request):
    id = db.Column(db.Integer, db.ForeignKey('request.id'), primary_key=True)

    amount = db.Column(db.Integer)

    __mapper_args__ = {
        'polymorphic_identity': 'hourlyleave',
    }

rawDescription: Bidirectional behavior in relationships to different models


rawDescription: Numpy, how to convert a 2D array to 3D (by grouping cols to 2 list)


code:
from collections import Sequence
from itertools import chain, count

def depth(seq):
    for level in count():
        if not seq:
            return level
        seq = list(chain.from_iterable(s for s in seq if isinstance(s, Sequence)))

rawDescription: Counting "deepness" or the deepest level a nested list goes to


rawDescription: Extract words between the 2nd and the 3rd comma


code:
template = loader.get_template('config.html')
context = RequestContext(request, {"config_data": config_data})
return HttpResponse(template.render(context))

rawDescription: Returning python object in httpresponse

description: Returning python object in httpresponse


code:
a = a.reshape(1,3)
b = b.reshape(3,1)
a
b
np.dot(a,b)
np.dot(b,a)
np.dot(a,a)

rawDescription: numpy: 1D array with various shape

description: Numpy: 1D array with various shape


code:
from collections import defaultdict

def processClickOutData(cls, raw_data):
    absolute_total = 0
    absolute_total_true = 0

    list_channels = set()
    list_tids = set()

    total = defaultdict(int)
    total_true = defaultdict(int)
    total_position = defaultdict(int)
    total_position_true = defaultdict(int)

    def defaultdict_int():
        return defaultdict(int)

    singles = defaultdict(defaultdict_int)
    singles_true = defaultdict(defaultdict_int)
    channels = defaultdict(defaultdict_int)
    channels_true = defaultdict(defaultdict_int)
    tid_position = defaultdict(defaultdict_int)
    tid_position_true = defaultdict(defaultdict_int)
    channel_position = defaultdict(defaultdict_int)
    channel_position_true = defaultdict(defaultdict_int)

    for gap, count, prefered, channel, position in raw_data:
        list_channels.add(channel)
        list_tids.add(tid)

        absolute_total += count
        total[gap] += count
        singles[gap][tid] += count
        channels[gap][channel] += count
        total_position[position] += count
        tid_position[position][tid] += count
        channel_position[position][channel] += count

        if prefered == 0:
            absolute_total_true += count
            total_true[gap] += count
            singles_true[gap][tid] += count
            channels_true[gap][channel] += count
            total_position_true[position] += count
            tid_position_true[position][tid] += count
            channel_position_true[position][channel] += count

    final_values = {"singles" : singles, "singles_true" : singles_true, "total" : total, "total_true": total_true, "absolute_total": absolute_total, "absolute_total_true": absolute_total_true, "channel_totals" : channels, "list_channels" : list_channels, "list_tids" : list_tids, "channel_totals_true" : channels_true,
                     "total_position" :  total_position, "total_position_true" : total_position_true, "tid_position" : tid_position, "channel_position" : channel_position, "tid_position_true" : tid_position_true, "channel_position_true" : channel_position_true }
    return final_values

rawDescription: Python trying to Refactor (DRY out) a long Control Flow


code:
class ClassA(object):
    def __new__(cls,theirnumber):
        if theirnumber > 10:
            # all big numbers should be ClassB objects:
            return ClassB.ClassB(theirnumber)
        else:
            # numbers under 10 are ok in ClassA.
            return super(ClassA, cls).__new__(cls, theirnumber)

rawDescription: How to replace an instance in __init__() with a different object?

description: Replace an instance in __init__() with a different object


code: {int(float(i)):i for i in sorted(l,cmp=cmp_tasks)}.values()

rawDescription: Python way of getting max of list containing integers and floats


code:
class ParametersField(serializers.WritableField):
    def from_native(self, parameters_dict):
        """
        Transform a dictionary of parameters to Django model objects.

        :param parameters_dict: A dictionary of parameters keyed by name.
        :type  parameters_dict: dict

        :returns: A list of Parameter model instances.
        :rtype: list
        """

        print(str([Parameter(key=name, value=value)
                  for name, value in parameters_dict.iteritems()]))
        return [Parameter(key=name, value=value)
                for name, value in parameters_dict.iteritems()]

    def to_native(self, parameter_set):
        """
        Transform the parameters to a dictionary.

        :param parameters: A list of Parameter model instances.
        :type  parameters: list

        :returns: A dictionary of parameters keyed by name.
        :rtype: dict
        """

        parameters_dict = {}
        for parameter in parameter_set.all():
            parameters_dict[parameter.key] = parameter.value
        return parameters_dict

rawDescription: How to serializer/deserialize Django models

description: Serializer/deserialize Django models


code:
class Player():
    print("here")
    life = randint(25,30)
    maxhealth = life
    attack = 5
    name = ""

rawDescription: In python, how do I call a class multiple times and have randint be random?


code:
book = Book(title='title')
if publisher is not None:
    book.publisher = publisher
book.save()

rawDescription: django passing arguments based on value

description: Django passing arguments based on value