code:
os.dup2(oldstdout, 1)
os.close(oldstdout)
os.close(rd)

rawDescription: Capture output from subprocess.call that I have no control over


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

x = np.linspace(0,5, 1000)
y = np.sin(x**2)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xlabel(r'$x_1$')
ax.set_ylabel(r'$sin(x_1^2)$')
ax.text(.5, -.5, r'$\rm{this\ is}_\mathrm{subscript}$', fontsize=24)
ax.text(.5, -.7, r'$\rm{this\ is}^\mathrm{superscript}$', fontsize=24)
ax.text(.5, -.9, r'$\frac{2}{1+\frac{1}{3}}$', fontsize=24)

rawDescription: Matplotlib: set superscript font size

description: Matplotlib: set superscript font size


code:
for i in range((date2 - date1).days + 1):
    print (date1 + datetime.timedelta(days=i)).strftime('%Y.%m.%d')

rawDescription: Creating a loop for two dates

description: Creating a loop for two dates


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import bivariate_normal
from matplotlib.widgets import Slider, Button, RadioButtons

#Setup figure and data
fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)
delta = 0.5
t = np.arange(0.0, 100.0, 0.1)
x = np.arange(-3.0, 4.001, delta)
y = np.arange(-4.0, 3.001, delta)
X, Y = np.meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = (Z1 - Z2) * 5.
cmap = plt.cm.rainbow
im = ax.pcolormesh(X, Y, Z, cmap=cmap)
fig.colorbar(im)
axcolor = 'lightgoldenrodyellow'
axtime = plt.axes([0.25, 0.1, 0.65, 0.03], axisbg=axcolor)
stime = Slider(axtime, 'Time', 0.0, 100.0, valinit=50.0)

#Routines to reset and update sliding bar
def reset(event):
    stime.reset()

def update(val):
    time = stime.val/10.
    Z = (Z1 - Z2) * time
    im.set_array(Z.ravel())
    fig.canvas.draw()

#Bind sliding bar and reset button
stime.on_changed(update)
resetax = plt.axes([0.8, 0.025, 0.1, 0.04])
button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975')
button.on_clicked(reset)

plt.show()

rawDescription: How to add a time control panel to a FuncAnimation from matplotlib

description: Add a time control panel to a FuncAnimation from matplotlib


code:
if L:
    L = L.string

rawDescription: Is there a `?.` operator in Python?

description: Is there a `?.` operator in Python


code: x == eval(repr(x))

rawDescription: Learn Python the hard way, exercise 10.4


code:
def image_handler2(request):
    url = "http://someurl.com/image.png"
    image_blob = urllib2.urlopen(url).read()
    request.response.body = image_blob
    request.response.content_type = 'image/png'
    return request.response

rawDescription: How to send request to another server and response the result in pyramid view?

description: Send request to another server and response the result in pyramid view


code:
#! /usr/bin/python3

import re

string_line = '<[2{12.5 6.0}](3 -4 5)>'

while True:
    string_line, count = re.subn ('[{}<>\[\]()][{}<>\[\]()]', lambda x: '{} {}'.format (*x.group () ), string_line)
    if not count: break

print (string_line)

rawDescription: How can I use line.replace to add space around any brackets in a string that are elements in another bracket set, through a loop?

description: Use line.replace to add space around any brackets in a string that are elements in another bracket set, through a loop


code:
def DoesServiceExist(host, port):
    try:
        captive_dns_addr = socket.gethostbyname(host)
    except:
        pass

    try:
        host_addr = socket.gethostbyname(host)

        if (captive_dns_addr == host_addr):
            return False

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        s.connect((host, port))
        s.close()
    except:
        return False

    return True

@app.route("/some_url")
def some_urls_view():
    ServiceExists = DoesServiceExist(host, port)
    name = getname() #I don't know what name is but you'll have to pass it to the template
    return render_template("some_template", ServiceExists=ServiceExists, name=name)

rawDescription: Flask: Define and use methods within templates


code: '\n'.join(['first line', 'second line', 'third line'])

rawDescription: Python: Text saving issue

description: Python: Text saving issue


code: np.add.reduceat(b, i)

rawDescription: Digitize numpy array

description: Digitize numpy array


rawDescription: Weird string stripping

description: Weird string stripping


code:
pd.to_timedelta(df.index,unit='s') + pd.Timestamp('20141015 16:07:40')
(pd.to_timedelta(df.index,unit='s') + pd.Timestamp('20141015 16:07:40')).tolist()

rawDescription: Python3 Pandas column in seconds

description: Python3 Pandas column in seconds


code: date_format = "%m/%d/%y %H:%M:%S"

rawDescription: Calculating the time difference between two datetime values in Python


code:
from collections import OrderedDict

d  = OrderedDict()

s = """id1 V1 100
id1 V2 200
id1 V3 0
id2 V1 30
id2 V2 400
id2 V3 1"""

for a, _, c in map(str.split, s.splitlines()):
        d.setdefault(a, []).append(c)

rawDescription: convert data table format in python

description: Convert data table format in python


code:
def test_conditions(obj, **kwargs):
    if obj.a <= kwargs.get('a', 5):
        return False
    for k, v in kwargs.items():
        if getattr(obj, k) <= v:
            return False
    return True

rawDescription: Python - adding conditions in if only they are specified (domain)?


code:
def _check_return_type(signature, return_value):
    """Check that the return value of a function matches the signature."""
    annotation = signature.return_annotation

    if annotation is EMPTY_ANNOTATION:
        annotation = AnyType

    # If the return type is a tuple of typed values, and the length is greater than 1 (to prevent the actual tuple return type)
    if isinstance(annotation, tuple) and len(annotation) > 1:
        for p, a in zip(return_value, annotation):
            if not isinstance(p, a):
                raise TypeError('Incorrect return type: {} ({} required)'.format(type(p), a))

    else:
        if not isinstance(return_value, annotation):
            raise TypeError('Incorrect return type')
    return return_value

rawDescription: How do I return multiple values using annotations?

description: Return multiple values using annotations


code:
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from myapp.models import UserProfile

@login_required
def userinfo(request):
    try:
        ldapuserprofile = UserProfile.objects.get(uid=request.user.username)
    except UserProfile.DoesNotExist:
        return HttpResponseRedirect('/login/')
    context = {'request': request, 'ldapuser': ldapuserprofile,}
    return render(request, 'myapp/userinfo.html', context)

rawDescription: django-auth-ldap - Display user information from LDAP in custom view

description: Django-auth-ldap - Display user information from LDAP in custom view


code:
message = f.read()
crypt = ''.join(i for i in message if i.lower() in monocrypt)
encrypted_message = []
for letter in crypt:
    encrypted_message.append(monocrypt[letter.lower()])

rawDescription: How to keep "spaces" although dict contains it?

description: Keep "spaces" although dict contains it


rawDescription: How to merge one ordered dict and one dict together?

description: Merge one ordered dict and one dict together


code:
l = [(3, 1000), (4, 2000), (5, 500)]
estimated = sum(t[1] for t in l)
totalSize = sum(t[0] for t in l)

rawDescription: PriorityQueue is very slow

description: PriorityQueue is very slow


code:
def randn_skew_fast(N, alpha=0.0, loc=0.0, scale=1.0):
    sigma = alpha / np.sqrt(1.0 + alpha**2)
    u0 = np.random.randn(N)
    v = np.random.randn(N)
    u1 = (sigma*u0 + np.sqrt(1.0 - sigma**2)*v) * scale
    u1[u0 < 0] *= -1
    u1 = u1 + loc
    return u1

# lets check again
plt.subplots(figsize=(12,4))
for alpha_skew in SKEW_PARAMS:
    p = randn_skew_fast(NUM_SAMPLES, alpha_skew)
    sns.distplot(p)

rawDescription: generate N random numbers from a skew normal distribution using numpy

description: Generate N random numbers from a skew normal distribution using numpy


rawDescription: search the biggest number of one column in a list of list python

description: Search the biggest number of one column in a list of list python


code:
from operator import attrgetter
data_divs = map(attrgetter('div'), data) # or [r.div for r in data]

rawDescription: Import Data Into Namedtuple in Python

description: Import Data Into Namedtuple in Python


code: # self.position = self.position.add(self.velocity) * dt

rawDescription: lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place

description: Lerp movement and keyboard movement buttons - fast pressing cause a character stuck in place


code:
from Crypto.Cipher import AES
import base64

cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
encoded = base64.b64encode(cipher.encrypt(msg_text))
# ...
decoded = cipher.decrypt(baes64.b64decode(msg_text))

rawDescription: How do i decrypt using hashlib in python?

description: Decrypt using hashlib in python


code: bool(someDict.keys() & set(someSet ))

rawDescription: Optimize the performance of dictionary membership for a list of Keys


rawDescription: Automatically setting class member variables in Python


rawDescription: Python: split bytes with a hexadecimal delimiter


code:
with open("list1") as f:
    keys = [line.strip() for line in f]
with open("list2") as f:
    names = dict(line.strip().split(":", 1) for line in f)

rawDescription: Sort not identical lists Python

description: Sort not identical lists Python


rawDescription: how to check if a cell is empty in openpyxl python

description: Check if a cell is empty in openpyxl python


code:
driver.find_element_by_xpath("//span[contains(text(), 'Select Circle')]").click()
driver.find_element_by_xpath("//span[contains(text(), 'Mumbai')]/..").click()

rawDescription: Python selenium select option from angular js drop down


code:
available_files = os.listdir('./DSC_Saves/')
print(available_files)

while True:
    user_input = input('File name: ')

    if user_input in available_files:
        break

print("You have selected '{}'".format(user_input))

rawDescription: How can I perform an action if a users input is the name of a file in a directory. Python

description: Perform an action if a users input is the name of a file in a directory. Python


rawDescription: Re-order a numpy array python

description: Re-order a numpy array python


code:
import ast

for line in sys.stdin:
    dict = ast.literal_eval("{'waffle': 'delicious', 'pancake': 'mediocre'}")

rawDescription: MapReduce using hadoop streaming via python - Pass a list from mapper to reducer and Read it as a list


code:
OBJECT_CACHE = dict()
class Base(object):
    def __new__(cls, *args, **kwargs):
        class_addr = cls.name()
        obj = OBJECT_CACHE.get(class_addr)
        if obj is None:
            obj = super(Base, cls).__new__(cls, *args, **kwargs)
            OBJECT_CACHE[class_addr] = obj
        return obj
    @classmethod
    def name(cls):
        names = [k.__name__.lower() for k in cls.mro()
                if k != Base and issubclass(k, Base)]
        return '.'.join(names[::-1])

class F(Base): pass
class A(Base): pass
class E(A): pass
class B(A): pass
class C(B): pass
f = F()
a = A()
e = E()
b = B()
c = C()
print(OBJECT_CACHE.keys())

rawDescription: Make a hashable id for all subclasses of base class


code: {('column_%d' % i): range(i,81, 9) for i in xrange(9)}

rawDescription: Possible to compress into a dictionary comprehension?


code:
def running_sum(iterable):
    s = 0
    result = []
    for value in iterable:
        s += value
        result.append(s)
    return result
running_sum([1,2,3,4,5])

rawDescription: a function that takes a list of integers as a parameter and returns a list of running totals

description: A function that takes a list of integers as a parameter and returns a list of running totals


code:
a = response.xpath('//div[@class="entry vevent"] | //div[@id="page"]')
a[0].xpath('.//div[@class="header"]//text()').extract()
a[1].xpath('.//div[@class="header"]//text()').extract()
a[2].xpath('.//div[@class="header"]//text()').extract()

rawDescription: Item not included in for loop made in Scrapy


code:
exams = Exam.objects.all()
transposed = {}

for exam in exams:
    transposed.setdefault(exam['name'], {}).update(
                        {'exam%s' % exam['exam']: exam['score']})

rawDescription: pivoting (row/column transpose) in django template

description: Pivoting (row/column transpose) in django template


rawDescription: how to copy only upper triangular values into array from numpy.triu()?

description: Copy only upper triangular values into array from numpy.triu()


rawDescription: finding the number of elements in a defaultdict(list) python

description: Finding the number of elements in a defaultdict(list) python


code: df.query("(value < 10) or (value == @nan)")

rawDescription: Querying for NaN and other names in Pandas


code:
import example
result = 0
def f(r):
    global result
    result = r
assert(result == 0)
example.http.get_async('www.google.com', f)
assert(result == 42)
try:
    example.http.get_async('www.google.com', 42)
    assert(False)
except TypeError:
   pass

rawDescription: Sending Python function as Boost.Function argument


code:
import os
import pathlib

with open(os.path.expanduser('~/matches.txt'), 'w') as f:
    for path in pathlib.Path(os.path.expanduser('~/x/y')).rglob('*'):
        f.write('{}\n'.format(path))

rawDescription: equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure?

description: Equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure


code:
from random import randint, choice

for _ in range(5):
    print(choice([randint(1,5),randint(9,15),randint(21,27)]))

rawDescription: Python- How to generate random integers with multiple ranges?


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Voronoi

points = np.array([[0, 0], [0, 1], [0, 2],
                   [1, 0], [1, 1], [1, 2],
                   [2, 0], [2, 1], [2, 2]])

vor = Voronoi(points)

fig = plt.figure()
plt.hold(True)

# Mark the Voronoi vertices.
plt.plot(vor.vertices[:,0], vor.vertices[:, 1], 'ko', ms=8)

for vpair in vor.ridge_vertices:
    if vpair[0] >= 0 and vpair[1] >= 0:
        v0 = vor.vertices[vpair[0]]
        v1 = vor.vertices[vpair[1]]
        # Draw a line from v0 to v1.
        plt.plot([v0[0], v1[0]], [v0[1], v1[1]], 'k', linewidth=2)

plt.show()

rawDescription: Voronoi Diagram Edges: How to get edges in the form (point1, point2) from a scipy.spatial.Voronoi object?


code:
def read_as_flat( someFile ):
    line_iter= iter(someFile)
    time_header= None
    for line in line_iter:
        words = line.split()
        if words[0] == 'time':
            time_header = [ words[1:] ] # the "time" line
            description= line_iter.next()
            time_header.append( description )
        elif words[0] in subjectNameSet:
            data = line_iter.next()
            yield time_header + data

rawDescription: processing text from a non-flat file (to extract information as if it *were* a flat file)

description: Processing text from a non-flat file (to extract information as if it *were* a flat file)


code:
rules = [('he','e'), ('ll','l'), ('e','ee')]
list(apply_rules(rules, 'hello'))

rawDescription: String Variations

description: String Variations


code:
building_file = open('tblBuilding.csv', newline='')
building = csv.DictReader(building_file, delimiter=',', quotechar='"')

for row in location:
    result = {}
    for build in building:
        if row['Build'] == build['BuildingName']:
            result['BuildingID'] = build['BuildingID']
    building_file.seek(0)  # rewind the underlying file object to the start again
    next(building)  # skip header row

rawDescription: Nested DictReaders not resetting

description: Nested DictReaders not resetting


code:
conn = api.connect() # This line is run only once when the process starts and the module is loaded

def view(request):
    conn.call_function() # This line is run every time a request is received

rawDescription: Django persistent API connections between requests


code:
def foo(s):
    def foo_helper(level=0):
        try:
            token = next(tokens)
        except StopIteration:
            if level != 0:
                raise Exception('missing closing paren')
            else:
                return []
        if token == ')':
            if level == 0:
                raise Exception('missing opening paren')
            else:
                return []
        elif token == '(':
            return [foo_helper(level+1)] + foo_helper(level)
        else:
            return [token] + foo_helper(level)
    tokens = iter(s)
    return foo_helper()

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

description: Parse a string and return a nested array


code:
import time
import sys
for x in range(101):
    sys.stdout.write('\r%d%%' % x)
    sys.stdout.flush()
    time.sleep(0.2)
sys.stdout.write('\n')

rawDescription: Bash or Python, When print characters to terminal, how to CHANGE a character at a FIXED position?


code:
class Browser:
    @asyncio.coroutine
    def go(self):
        print('go')
        return self

    @asyncio.coroutine
    def click(self):
        print('click')
        return self

    def text(self):
        print('text')
        return 5

@asyncio.coroutine
def main():
    text = yield from chain(Browser()).go().click().go().text()
    print(text)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

rawDescription: Method chaining with asyncio coroutines

description: Method chaining with asyncio coroutines


code:
def ttest(arr):
    return stats.ttest_1samp(arr, popmean=0)[1]

counts_and_means = \
    my_data.groupby("Category").agg (
        {
            "Category"  : np.count_nonzero ,
            "val_1"     : np.mean ,
            "val_2"     : [np.mean,ttest]
        }
    )

rawDescription: Pandas: Aggregating and applying multiple functions to same column


code:
class DBLoggingHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super(DBLoggingHandler, self).__init__(*args, **kwargs)
        self.db = sqlite3.connect(dbpath)
    def do_GET(self):
        self.db.execute("INSERT INTO GetLog (command, vers, path) VALUES (?, ?, ?)",
                        (self.command, self.request_version, self.path))
        return super(DBLoggingHandler, self).do_GET()

rawDescription: Parsing GET request data with from SimpleHTTPServer


rawDescription: Converting a List of Tuples into a Dict in Python


code:
def partition(values, indices):
    idx = 0
    for index in indices:
        sublist = []
        while idx < len(values) and values[idx] < index:
            sublist.append(values[idx])
            idx += 1
        if sublist:
            yield sublist

rawDescription: Python - split list in to sublists based on another list


code:
def get_token(backend, uid, *args, **kwargs):
    # get token from the oauth2 flow
    provider = backend.name
    social = backend.strategy.storage.user.get_social_auth(provider, uid)
    access_token = social.extra_data['access_token']
    refresh_token = social.extra_data.get('refresh_token')

rawDescription: Use Python social auth to only get tokens


code:
def notify_slack(host_list):
    # Don't notify Slack if list of hosts is empty
    if not host_list:
        return

    slack_msg = ' '.join(map(str, msg_list))
    slack.chat.post_message('#testbot', slack_msg,username='NMAP_bot')

rawDescription: How to print notification to slack by calling a function via python

description: Print notification to slack by calling a function via python


code:
if monkeys_punched_yet:
    description_text = ("You see a pile of bruised and battered monkeys "
                        "in a corner of the room.")
else:
    description_text = "You see a group of unsuspecting, punchable monkeys."
    options.append("punch monkeys")

rawDescription: How to disable/restrict a line of code after it has been run? (Python)

description: Disable/restrict a line of code after it has been run? (Python)


rawDescription: PyQt QLineEdit and 'paste' event?

description: PyQt QLineEdit and 'paste' event


code:
import  re
s = "E2_40873886"
print(re.search("\d{8}",nodeName).group())

rawDescription: Ignore all characters and just read numbers portion from the string


code:
import re
line = '1 VENT 19.03'
re.match(r'(?P<id>\d)\s+(?P<company>\w+)\s+(?P<price>[\.\d]+)', line).groupdict()

rawDescription: Grabbing String Contents Python

description: Grabbing String Contents Python


code:
re.split('Overview of (\w+) study', text)[1:]
l = re.split('Overview of (\w+) study', text)[1:]

rawDescription: how to make regex go line by line to match two strings at the same time?

description: Make regex go line by line to match two strings at the same time


code:
import numpy as np
A = np.zeros(10)
j = 1.

C = np.zeros([10, 3])
C[:, 0] = A
C[:, 1:] = j
C = C.ravel()

rawDescription: Numpy setting j, j+1, j+2 to a

description: Numpy setting j, j+1, j+2 to a


code: datawriter.writerow(each[:2] + each[3] + each[4])

rawDescription: splitting lists and values

description: Splitting lists and values


code:
w = WebPage("foo.html")

w.process()
print(w.head)
print(w.body)

rawDescription: Using variable inside a class function defintion, which created in other class function | python


code:
class Service(models.Model):
    created_on = models.DateTimeField(auto_now=True)
    service_name = models.CharField(max_length=200)
    service_code = models.IntegerField(default=0, unique=True)

rawDescription: Display data from models in website

description: Display data from models in website


code:
from functools import partial
gp.predict = partial(gp.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


rawDescription: Convert a complex array of array to a list


rawDescription: Average from two list of dictionaries

description: Average from two list of dictionaries


rawDescription: Can I have a temporary/alternative neo4j graph for testing?

description: Have a temporary/alternative neo4j graph for testing


code:
import re
p = re.compile(r'[\w.-]+@(?![\w.-]*\.(?:png|jpe?g|gif)\b)[\w.-]+\b')
test_str = "{'email': ['billy666@stanford.edu',\n           'cantorfamilies@stanford.edu',\n           'cantorfamilies@stanford.edu',\n           'cantorfamilies@stanford.edu',\n           'footer-stanford-logo@2x.png']}"
print(set(p.findall(test_str)))

rawDescription: Erase duplicate emails

description: Erase duplicate emails


code:
from collections import defaultdict
x = [(1,2), (3,4), (7,4), (5,4)]
d = defaultdict(int)
for v,k in x:
  d[k] = max(d[k],v)

y=[(k,v) for v,k in d.items()]
y

rawDescription: Python: conditionally delete elements from list


code:
# coding: utf8

# full width versions (SPACE is non-contiguous with ! through ~)
SPACE = '\N{IDEOGRAPHIC SPACE}'
EXCLA = '\N{FULLWIDTH EXCLAMATION MARK}'
TILDE = '\N{FULLWIDTH TILDE}'

# strings of ASCII and full-width characters (same order)
west = ''.join(chr(i) for i in range(ord(' '),ord('~')))
east = SPACE + ''.join(chr(i) for i in range(ord(EXCLA),ord(TILDE)))

# build the translation table
full = str.maketrans(west,east)

data = '''\
蝴蝶(A song)
心之城(Another song)
支持你的爱人(Yet another song)
根生的种子
鸽子歌(Cucurrucucu palo whatever)
林地之间
蓝光
在你眼里
肖邦离别曲
西行（魔戒王者再临主题曲）(Into something)
深陷爱河
钟爱大地
时光流逝
卡农
舒伯特小夜曲(SERENADE)
甜蜜的摇篮曲(Sweet Lullaby)
'''

# Replace the ASCII characters with full width, and create a song list.
data = data.translate(full).rstrip().split('\n')

# translate each printable line.
print(' ----------Songs-----------'.translate(full))
for i,song in enumerate(data):
    line = '|{:4}: {:20.20}|'.format(i+1,song)
    print(line.translate(full))
print(' --------------------------'.translate(full))

rawDescription: How to control padding of Unicode string containing east Asia characters

description: Control padding of Unicode string containing east Asia characters


code:
import argparse
import sys

class AddressAction(argparse.Action):
    def __call__(self, parser, args, values, option = None):
        args.address=values
        if args.query_type=='odam' and not args.address:
            args.address=[
                'master1.odamex.net:15000',
                'master2.odamex.net:15000',
                ]
        if not args.address:
            parser.error("If you are making a server query, you must pass an address.")

p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
        const='odam', help="Odamex Master query.")
g.add_argument('--odas', dest='query_type', action='store_const',
        const='odas', help="Odamex Server query.")
p.add_argument('address', nargs='*', action=AddressAction)
args = p.parse_args()

rawDescription: Python argparse: nargs + or * depending on prior argument


rawDescription: How to slice and extend a 2D numpy array?

description: Slice and extend a 2D numpy array


code:
#!/usr/bin/env python3

import os, sys

def print_durations(durations):
    # this is to print nicely the durations
    pass

def calculate_durations(contents):
    # this is where the fun shall be, see implementation below
    pass

def main():
    if len(sys.argv) != 2:
        print("Usage: {} filename".format(sys.argv[0]))
        sys.exit(1)
    if not os.path.isfile(sys.argv[1]):
        print("Error: {} should be an existing file!".format(sys.argv[1]))
        sys.exit(2)
    with open(sys.argv[1], 'r') as f:
        durations = calculate_durations(f.readlines())
        print_durations(durations)

if __name__ == "__main__":
    main()

rawDescription: Python putting certain texts into a dictionary from a large string


code: sorted([[k, sorted(v.values())] for k, v in dict_1.iteritems()])

rawDescription: Sorting by the values of a sub-dictionary and then by primary keys


code:
import commands

node_free_mem = {}

for n in node_names:
    sys_output = commands.getoutput("ssh %s 'free -m'" % n)
    free_memory = sys_output.split()[9]
    node_free_mem[n] = int(free_memory)

rawDescription: Python: Associating Function Output to Strings, then Combining into Dictionary


code:
class A(object):

    def __init__(self):
        self.__prop = None

    @property
    def prop(self):
        return self.__prop

    @prop.setter
    def prop(self, value):
        self.__prop = value

class B(A):

    def __init__(self):
        super(B, self).__init__()

    @property
    def prop(self):
        value = A.prop.fget(self)
        value['extra'] = 'stuff'
        return value

    @prop.setter
    def prop(self, value):
        A.prop.fset(self, value)

rawDescription: Python - extending properties like you'd extend a function


code:
a = numpy.linspace(0, 26, 27).reshape(3, 3, 3)
a[1][0] = numpy.nan
a

rawDescription: How to iterate a 3D numpy array

description: Iterate a 3D numpy array


code: ' Thread: {} starting '.format(42).center(79, '=')

rawDescription: centering text using .format the right way?

description: Centering text using .format the right way


code: a.dtype.char == 'S'

rawDescription: Numpy: Check array for string data type

description: Numpy: Check array for string data type


code:
from itertools import count
c = count()
B = [[let, [n for n in nums if next(c) % 4 == 0]] for let, nums in A]
B

rawDescription: Splicing lists within a list

description: Splicing lists within a list


code: mod = import_by_name("itertools")

rawDescription: How to import from command line and then iterate over imported modules?

description: Import from command line and then iterate over imported modules


code: self.winner = None

rawDescription: How do I define a variable that identifies the background color of the window (python, tkinter)

description: Define a variable that identifies the background color of the window (python, tkinter)


code:
def getter_setter_gen(name, type_):
    def getter(self):
        return getattr(self, "__" + name)
    def setter(self, value):
        if not isinstance(value, type_):
            raise TypeError("%s attribute must be set to an instance of %s" % (name, type_))
        setattr(self, "__" + name, value)
    return property(getter, setter)

def auto_attr_check(cls):
    new_dct = {}
    for key, value in cls.__dict__.items():
        if isinstance(value, type):
            value = getter_setter_gen(key, value)
        new_dct[key] = value
    # Creates a new class, using the modified dictionary as the class dict:
    return type(cls)(cls.__name__, cls.__bases__, new_dct)

rawDescription: Force python class member variable to be specific type


code:
def makeMethod(idlCode):
    syntax = MyIDL.parse(idlCode)

    def newMethod(*args, **kw):
        if syntax.statementType == MyIDL.IF_STATEMENT:
            if secureLookup(mySyntaxTree.IF):
               return secureLookup(args[0])
            else:
               return secureLookup(args[1])
        ...

    return (syntax.methodName, newMethod)

rawDescription: Dynamically creating a class from file in Python


code: [item[0].__class__.__name__ for item in raw_list._meta.get_fields_with_model()]

rawDescription: How to get a list of datatypes on Django model?

description: Get a list of datatypes on Django model


rawDescription: Is there a python method to re-order a list based on the provided new indices?


code:
def daytime(val):
    hour, min = map(int, val.split(':'))
    if hour < 8:
        hour += 12
    return hour, min

rawDescription: Complex Sorting of a List

description: Complex Sorting of a List


code:
def product(a, b):
    print ("product is", a*b)

if __name__ == "__main__":
    product( int(sys.argv[1]), int(sys.argv[2]) )

rawDescription: os.exec. passing arguments to new file function

description: Os.exec. passing arguments to new file function


code:
def request_exit_signal(self, data):
    """
    When the server sends the command's exit status, record it for later
    delivery to the protocol.

    @param data: The network-order four byte representation of the exit
        signal of the command.
    @type data: L{bytes}
    """
    (signal,) = unpack('>L', data)
    self._reason = ProcessTerminated(None, signal, None)

rawDescription: How do I (can I?) get the exit status from a command?


code:
items = []
while stop != "stop":
    name = input("What is the name of the item?\n")
    price = float(input("What is the price of the item?\n"))
    quantity = float(input("How many of these items are there?\n"))
    items.append((name, price, quantity))

rawDescription: In Python, how do I create a new variable each time a loop goes around, and then send them all to a function to be processed?


code:
for line in s.splitlines():
    match = re.match(r'(\w+) is (\w+) of (.*)',line)
    if match:
        new_field,func,fields = match.groups()
        out.append({'new_field': new_field,
                    'func': func,
                    'fields': some_processing_func(fields)})

rawDescription: Match multiple lines on a pattern and return placeholders


code:
# Again using a map
ns = list(map('{:05}'.format, sorted(sample(range(99999), 10))))

# Using a list comprehension
ns = ['{:05}'.format(n) for n in sorted(sample(range(99999), 10))]

rawDescription: Generate lottery numbers - Convert R statement to Python


code: df_raw['PricePerSeat_Outdoor'] = pd.to_numeric(df_raw['PricePerSeat_Outdoor'], errors='coerce')

rawDescription: Convert a column in pandas dataframe from String to Float


code: df.loc[df.Z == 'xyz', 'Y'] = 'abc'

rawDescription: pandas dataframe update or set column[y] = x where column[z] = 'abc'

description: Pandas dataframe update or set column[y] = x where column[z] = 'abc'


rawDescription: How to split a Python string with numbers and letters?

description: Split a Python string with numbers and letters


code:
from fabric.api import task, run, get
from collections import Counter
from StringIO import StringIO

def worlds(data):
    return data.split()

@task
def count_worlds():
    s_fp = StringIO()
    # for big files better read to temp file
    get('/some/remote/file', s_fp)
    world_count = Counter(s_fp.getvalue())
    # do something with world_count

rawDescription: Python Word Count of a file using ssh from 100 machines


rawDescription: How to search & replace in Python?

description: Search & replace in Python


code: "\n".join([",".join(spl[i:i+3]) for i in range(0,len(spl),3)])

rawDescription: Replace every third comma with line break


code:
import re
s = "C BOS  - Traded from Royal Disappointments"
re.split(r'\s*-\s*', s)

rawDescription: Python Regular Expressions re.findall -- split a string into two


code:
for i in range(len(m) - 1, 0, -1):
    m.insert(i, 99)

rawDescription: Python for loop doesn't execute last iteration


code:
for word in folder:
    wordstrings = Counter(word)
    if all(wordstrings[k] - four[k] <= 0 for k in wordstrings):
            print(word)

rawDescription: sets operations on lists

description: Sets operations on lists


code:
foo = [['one', 1], ['two', 1], ['three', 1]]
bar = [['three', 1], ['four', 1], ['five', 1]]
from collections import Counter
Counter(dict(foo)) + Counter(dict(bar))

rawDescription: python: fast and easy way to compare these lists?

description: Python: fast and easy way to compare these lists


code:
from collections import Counter
from itertools import takewhile
def solve(lis):
    c = Counter(lis)
    mx = max(c.values())
    return [k for k, v in takewhile(lambda x: x[1]==mx, c.most_common())]

rawDescription: All the common elements present in the List of Python


code:
class Category(models.Model):

    def items(self):
        # probably need to import Item model here in order to avoid
        # circular import reference
        from myapp.models import Item
        return Item.objects.filter(categories__id=self.id)

rawDescription: Return Django queryset of items that appear in a single category when items can appear in multiple categories


code:
class Node(object):
    def __init__(self, initdata):
        self.data = initdata
        self.next = None

class UnorderedList(object):

    def __init__(self):
        self.head = None
        self.count = 0

    def __iter__(self):
        current = self.head
        while current is not None:
            yield current
            current = current.next

rawDescription: Python Linked List with Nodes. Iterable

description: Python Linked List with Nodes. Iterable


code:
Sekwencja1 = [a[i] for i in x1]
Sekwencja2 = [b[j] for j in y1]

rawDescription: Amino acid sequences in pyplot (Same regions in both sequences)


code:
from collections import defaultdict
OCR_dict = defaultdict(list)

with open('coors_test.csv', mode='r') as coors_infile:
    coors_reader = csv.reader(coors_infile)
    for row in coors_reader:
        chromo = row[0]
        start = row[1]
        end = row[2]
        # OCR_dict is a mapping `chromo -> [(start,end), (start,end), ...]`
        OCR_dict[chromo].append((start,end))

with open('transcripts_test.csv', mode='r') as transcripts_infile:
    transcripts_reader = csv.reader(transcripts_infile)
    for row in transcripts_reader:
        transcript_chromosome = row[1]
        # look that chromosome up in the dict and print it if it exists
        if transcript_chromosome in OCR_dict:
            print(transcript_chromosome, OCR_dict[transcript_chromosome])

rawDescription: Puzzling dictionary matching problem

description: Puzzling dictionary matching problem


code: ax = df.plot(kind='scatter', x='Date', y='Data')

rawDescription: dataframe.plot exclude missing data

description: Dataframe.plot exclude missing data


code: sorted(d, key=lambda x: d[x].lower())

rawDescription: dictionary keys sorted by value

description: Dictionary keys sorted by value


code:
Table1.objects.using('default').all()
Table1.objects.using('alias').all()

Table2.objects.using('default').all()
Table2.objects.using('alias').all()

rawDescription: Multiple concurrent database transactions with Django?


code:
def set(self, section, option, value):
    raise SyntaxError("No modification authorized")

rawDescription: Lock ConfigParser in read-only mode

description: Lock ConfigParser in read-only mode


code:
dictionary = {'Alice': ['10', '10'], 'Tom': ['9', '8'], 'Ben': ['10', '9']}

import csv
with open('eggs.csv', 'wb') as csvfile:
    spamwriter = csv.writer(csvfile, delimiter=',')
    for item in dictionary.items():
         spamwriter.writerow(item)

rawDescription: Arranging keys and values from a dictionary in a csv file - Python


code:
from yapsy.PluginManager import PluginManager

def main():
    # Load the plugins from the plugin directory.
    manager = PluginManager()
    manager.setPluginPlaces(["plugins"])
    manager.collectPlugins()

    # Loop round the plugins and print their names.
    for plugin in manager.getAllPlugins():
        plugin.plugin_object.print_name()

if __name__ == "__main__":
    main()

rawDescription: Yapsy minimal example

description: Yapsy minimal example


code:
import matplotlib.pyplot as plt

x = [1, 2, 3]
y =[1, 2, 3]

plt.plot(x, y)
plt.text(2.85, 2.9, 'label',
         bbox={'facecolor':'white', 'edgecolor':'none', 'pad':10})

plt.show()

rawDescription: Remove matplotlib text plot border

description: Remove matplotlib text plot border


code:
class Example(models.Model):
    MAX_DESCRIPTION_LENGTH = 1024

    description = models.CharField(max_length=MAX_DESCRIPTION_LENGTH)
    description_length = models.IntegerField(
        validators=MaxValueValidator(MAX_DESCRIPTION_LENGTH))

rawDescription: Django form, change default max_length

description: Django form, change default max_length


rawDescription: compare elements of list to elements of list of lists and conditionally create new lists

description: Compare elements of list to elements of list of lists and conditionally create new lists


code:
def joined_snippets(l):
    ' '.join(['%-2s' % (i,) for i in l])

def joined_template(l):
    ' '.join(['%-2s' for i in l])%tuple(l)

def multiplied_template(l):
    ('%-2s ' * len(l))[:-1] % tuple(l)

from timeit import timeit
l = ["AA","BB","CC","DD"]
timeit('f(l)', 'from __main__ import l, joined_snippets as f')
timeit('f(l)', 'from __main__ import l, joined_template as f')
timeit('f(l)', 'from __main__ import l, multiplied_template as f')
l *= 10
timeit('f(l)', 'from __main__ import l, joined_snippets as f')
timeit('f(l)', 'from __main__ import l, joined_template as f')
timeit('f(l)', 'from __main__ import l, multiplied_template as f')

rawDescription: python print in format way unknow list length

description: Python print in format way unknow list length


code:
from clint.textui import puts, columns

width = 20

for term, definition in zip(column1, column2):
    puts(columns([term, width], [definition, None]))

rawDescription: Printing columns of an equal custom set spacing while not letting long strings flow over other columns. (using clint perhaps?)


rawDescription: Figuring out how to expand a grammar (Python)


rawDescription: One Way to Grab both text and percentages regex python


code:
import scrapy

class MySpider(scrapy.Spider):
    name = 'my-spider'
    start_urls = ['http://www.some-real-site-url.com']

    def __init__(self, start_url=None, *args, **kwargs):
        if start_url:
            self.start_urls = [start_url]

    ...

rawDescription: What's the easiest way to quickly check a Scrapy behaviour / bug?


code: list(zip(range(10), fib()))

rawDescription: bottom up fibonacci in python using O(1) space

description: Bottom up fibonacci in python using O(1) space


rawDescription: Joining/Merging two Pandas dataframes. Match the levels of one to the index of the other


code:
l = [3, 5, 3]
s = set()
s
for x in l:
    if x not in s:
        s.add(x)
    else:
        break

rawDescription: Python: Compare more numbers

description: Python: Compare more numbers


code:
from mymodule.database.dbclasses import MyDBClass
from mymodule.api.apiclasses import MyAPIClass
__all__ = ['MyDBClass', 'MyAPIClass']

rawDescription: Proper way to include files

description: Proper way to include files


code:
import sys

file = TeeFile(sys.stderr, output_file)
print("abc", end="", file=file)
file.flush()

rawDescription: writing file & displaying result in idle

description: Writing file & displaying result in idle


code: A = [[max(val, 0) for val in lst] for lst in A]

rawDescription: Replacing Negatives in an Array, Python

description: Replacing Negatives in an Array, Python


code:
sql.write_frame(df, con=con, name='table_name_for_df',
                if_exists='replace', flavor='mysql')

rawDescription: How to insert pandas dataframe via mysqldb into database?

description: Insert pandas dataframe via mysqldb into database


code:
class MyType(type):
    def __new__(cls, name, bases, attrs):
        #wraps the 'test' method to automate context management and other stuff
        new_class = super(MyType, cls).__new__(cls, name, bases, attrs)
        new_class.test = cls.other_wrapper(new_class.test, new_class)

    @classmethod
    def other_wrapper(cls, operation, new_class):
        def _wrapped(self, *args, **kwargs):
            #DO something with self and *args and **kwargs ...
            #ONLY if self is of type *new_class* !!!
            if type(self) == new_class:
                pass #do things
            return operation(self, *args, **kwargs)
        return _wrapped

rawDescription: Python : metaclass + wrapped methods + inheritance = problems


code: nodes = Node.objects.filter(Q(project__project_collaborators=user) | Q(collaborators=user)).select_related('project').distinct()

rawDescription: Select all of django foreign key model if condition or part if another condition


code:
list_a = range(100)
list_b = remove_percentage(list_a, 0.25)
len(list_a), len(list_b)
list_b

rawDescription: Is it possible to randomly *remove* a percentage/number of items from a list & then *append* them to another list?


code:
k.metadata.update({'myKey':'myValue'})
k2 = k.copy(k.bucket.name, k.name, k.metadata, preserve_acl=True)
k2.metadata = k.metadata    # boto gives back an object without *any* metadata
k = k2;

rawDescription: How to change metadata on an object in Amazon S3

description: Change metadata on an object in Amazon S3


code:
c = Counter()
for xs in seq:
    for x in set(xs):
        c[x] += 1
c

rawDescription: Using Counter with list of lists

description: Using Counter with list of lists


rawDescription: Computation time insanely long in python


code: pricelist[0:20] #returns members 0 to 19 of pricelist

rawDescription: Only last iteration of while loop saves

description: Only last iteration of while loop saves


code: katt

rawDescription: Python re.findall fails at UTF-8 while rest of script succeeds


code:
mask = b >= a[..., -1:]
index = np.argmax(mask, axis=-1) - 1

rawDescription: Gridwise application of the bisection method


code:
content = response.xpath('//meta[@id="_bootstrap-neighborhood_card"]').xpath('@content').extract_first()
data = json.loads(content)
from pprint import pprint
pprint(data)

rawDescription: Decoding HTML character entities in JSON


code:
doc = """

Name

Fees

Awards

Total

Tony

    7,800
    7
    15,400

Paul

    7,800
    7
    15,400

Richard

    7,800
    7
    15,400

"""
import lxml.html
root = lxml.html.fromstring(doc)
root.xpath('//tr/td//text()')

rawDescription: python parse html table using lxml

description: Python parse html table using lxml


rawDescription: Using python requests to mask as a browser and download a file


code:
from pylab import *

# from http://matplotlib.org/examples/pylab_examples/boxplot_demo.html

# fake up some data
spread= rand(50) * 100
center = ones(25) * 50
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
data =concatenate((spread, center, flier_high, flier_low), 0)

# fake up some more data
spread= rand(50) * 100
center = ones(25) * 40
flier_high = rand(10) * 100 + 100
flier_low = rand(10) * -100
d2 = concatenate( (spread, center, flier_high, flier_low), 0 )
data.shape = (-1, 1)
d2.shape = (-1, 1)
#data = concatenate( (data, d2), 1 )
# Making a 2-D array only works if all the columns are the
# same length.  If they are not, then use a list instead.
# This is actually more efficient because boxplot converts
# a 2-D array into a list of vectors internally anyway.
data = [data, d2, d2[::2,0]]

# multiple box plots on one figure
figure()

# get dictionary returned from boxplot
bp_dict = boxplot(data, vert=False)

for line in bp_dict['medians']:
    # get position data for median line
    x, y = line.get_xydata()[1] # top of median line
    # overlay median value
    text(x, y, '%.1f' % x,
         horizontalalignment='center') # draw above, centered

for line in bp_dict['boxes']:
    x, y = line.get_xydata()[0] # bottom of left line
    text(x,y, '%.1f' % x,
         horizontalalignment='center', # centered
         verticalalignment='top')      # below
    x, y = line.get_xydata()[3] # bottom of right line
    text(x,y, '%.1f' % x,
         horizontalalignment='center', # centered
             verticalalignment='top')      # below

show()

rawDescription: Overlaying the numeric value of median/variance in boxplots


code:
words = [('Rock', 'Physical Object'), ('Play', 'Action'), ... ]
featuresets = [(word_features(n), g) for (n,g) in words]
train_set, test_set = featuresets[500:], featuresets[:500]
classifier = nltk.NaiveBayesClassifier.train(train_set)

rawDescription: What area deals with the extraction of words with similar characteristics?


code: what = add(age, subtract(height, multiply(weight, divide(iq, 2))))

rawDescription: Learn Python The Hard Way Exercise 21 Extra Credit


rawDescription: Python 2.7 Etree/lxml minimizing

description: Python 2.7 Etree/lxml minimizing


code:
def iterproduct(*args):
    """
    list(iterproduct('ABCD', 'xy')) --> Ax Ay Bx By Cx Cy Dx Dy
    """
    pools = map(tuple, args)
    if len(pools) == 1:
        for y in pools[0]:
            yield (y,)
    else:
        for x in iterproduct(*pools[:-1]):
            for y in pools[-1]:
                yield x + (y,)

rawDescription: Challenge: Creating a list of tuples of different combinations with different value 'options' in each location of the tuple.


code:
# Write the array to disk
with file('test.txt', 'w') as outfile:
    # I'm writing a header here just for the sake of readability
    # Any line starting with "#" will be ignored by numpy.loadtxt
    outfile.write('# Array shape: {0}\n'.format(array_.shape))

    # Iterating through a ndimensional array produces slices along
    # the last axis. This is equivalent to array_[i,:,:] in this case
    for data_slice in array_:

        # The formatting string indicates that I'm writing out
        # the values in left-justified columns 7 characters in width
        # with 2 decimal places.
        np.savetxt(outfile, data_slice, fmt='%-7.2f')

        # Writing out a break to indicate different slices...
        outfile.write('# New slice\n')

rawDescription: Write numpy array to csv file with a specific number of columns


code:
def flash(event):
    b.config(bg = 'orange')
    b.update_idletasks()
    sleep(1)
    b.config(bg='green')

rawDescription: Button Colour Doesn't Change in Function (Python tkinter)


code:
df['block'] = (df.A.shift(1) != df.A).astype(int).cumsum()
df

rawDescription: Finding consecutive segments in a pandas data frame


code:
class AnswerForm(forms.Form):
    answer = forms.ModelMultipleChoiceField(
        queryset = Answer.objects.all(),
        widget = forms.CheckboxSelectMultiple,
    )

    def __init__(self, *args, **kwargs):
        q_pk = kwargs.pop('q_pk', None)
        super(AnswerForm, self).__init__(*args, **kwargs)
        self.fields['answer'].queryset = Answer.objects.filter(question__pk=q_pk)

rawDescription: Primary keys as choices in MultipleChoiceField


code:
import numbers
[x for x in list_1 if isinstance(x, numbers.Number)]

rawDescription: Is there a way to output the numbers only from a python list?


code:
t = ""
for car in carList:
    t += "Your car is a {}, {}, {}. ".format(car['level']['status'], car['color'], car['type'])
t[:-1]

rawDescription: Generate String From List

description: Generate String From List


code:
df = pd.DataFrame({'val': np.random.randn(100),
                   'group': np.repeat([0, 1], 50)})

rawDescription: Customizing annotation with Seaborn's FacetGrid


code:
import re
original_string = open('foo.txt').read()
new_string = re.sub('[^a-zA-Z0-9\n\.]', ' ', original_string)
open('bar.txt', 'w').write(new_string)

rawDescription: How to replace all those Special Characters with white spaces in python?

description: Replace all those Special Characters with white spaces in python


code: sorted(yourdict.items(), key=lambda i: int(i[0]))

rawDescription: Sorting dictionary for printing

description: Sorting dictionary for printing


code: odd = number & 1

rawDescription: how to find the bit on the right in python

description: Find the bit on the right in python


rawDescription: Turning a unicode code point into a unicode character in Python


code:
import nltk
paragraph = u"Hi, this is my first sentence. And this is my second. Yet this is my third."
sentences = nltk.sent_tokenize(paragraph)

rawDescription: Python cut a string after Xth sentence

description: Python cut a string after Xth sentence


code: another_simple_call = simple_call

rawDescription: Is it possible to use Lambdas like this in Ruby?


code:
total = sum(l2)
l3 = [[i*total] for i in l1]

rawDescription: Iterating over two lists and resulting in a third one


code:
weights_np = weights_np.reshape((-1, 3))
weights_np

rawDescription: convert list of strings to numpy list of lists

description: Convert list of strings to numpy list of lists


code:
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    'full/path/to/your/templates/dir',
    )

rawDescription: Django Userena - Correctly override default django app templates?


code:
def _get_server_info(self):
    if not self._server_info:
        self._server_info = self._info.find_server_repository_info(self)

    return self._server_info

rawDescription: Field Population (ReviewBoard code)

description: Field Population (ReviewBoard code)


code:
card_names = {'ace': 1, 'jack': 11, 'queen': 12, 'king': 13}
for i in range(2, 11):
    card_names[str(i)] = i

rawDescription: Python card guessing game

description: Python card guessing game


rawDescription: How can I iterate over an 1D array and build a 2D array in Numpy?

description: Iterate over an 1D array and build a 2D array in Numpy


code:
class MyNewModel(TitleMixin):
    pass

rawDescription: Alternatives to creating and iterating through a list for "bad" values each time clean is called in django?


rawDescription: python api call using JSON data

description: Python api call using JSON data


code: {20001: 'World Economies', 20002: 'Bill Clinton', 20004: 'Internet Law', 20005: 'Philipines Elections', 20006: 'Israel Politics', 20008: 'Golf', 20009: 'Music', 20010: 'Disasters'}

rawDescription: Making a python dictionary from a huge textfile?


rawDescription: Transform an array of shape (n,) to a numpy array of shape (n,1)


code: len(clean(map(chr, range(0x110000))))

rawDescription: Removing non-printable "gremlin" chars from text files


code:
def sign(num):
    return -1 if num < 0 else 1

rawDescription: Any way to extract the sign of a number in Python?


rawDescription: Create empty csv file with pandas

description: Create empty csv file with pandas


rawDescription: Finding combinations where the length of the combination is more then the variables being used


code:
from scikits.audiolab.pysndfile.matapi import oggread
data, fs, enc = oggread("myfile.ogg")

rawDescription: How do you play ogg files in Python in Linux?

description: Play ogg files in Python in Linux


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

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


code:
myrecipe = recipe.objects.get(...)
SearchQuerySet().models(user).filter(ingredient__in=myrecipe.recipe_ingredient.all())

rawDescription: Django manytomany field, how to get check for 80% subset/ match?


code:
def shashank1(seq, index):
    return seq[:-index or None]

def shashank2(seq, index):
    return index and seq[:-index] or seq

def shashank3(seq, index):
    return seq[:-index] if index else seq

rawDescription: List slicing with dynamic index on [:index]


code:
with open(path, 'rb') as f:
    "X'{0}'".format(r.read().encode('hex'))

rawDescription: Python2.7 Generate sql query with format() and buffer object from sqlite


code:
import wx

class Cartesian(wx.Frame):
    def __init__(self, parent=None, id=-1, title=""):
        wx.Frame.__init__(self, parent, id, title, size=(640, 480))

        self.panel = wx.Panel(self)

        wx.StaticLine(self.panel, pos=(320, 0), size=(1, 480), style=wx.LI_VERTICAL)
        wx.StaticLine(self.panel, pos=(0, 240), size=(640, 1), style=wx.LI_HORIZONTAL)

app = wx.App(False)
frame = Cartesian()
frame.Show()
app.MainLoop()

rawDescription: Drawing a Cartesian plane in wxPython

description: Drawing a Cartesian plane in wxPython


rawDescription: Sum of precipitation per Timeframe in pandas DataFrame


code: [ float(i) * 100 / max(l) for i in l ]

rawDescription: Google Chart API - Line Chart: Averaging data


code:
x = [s for s in x if s]
print(x)

rawDescription: Removing Punctuation From Python List Items


code:
def maxrow(x, col):
    ser = x.loc[x[col].idxmax()]
    df = pd.DataFrame({ser.name: ser}).T
    return df

rawDescription: How to get rows in pandas data frame, with maximal values in a column and keep the original index?

description: Get rows in pandas data frame, with maximal values in a column and keep the original index


code:
name,age,street;number;type
John,46,longroad;12;"main address"
John,46,summerroad;12;"summer house"

rawDescription: Which is the best way to label a csv file for being converted into json file in python


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

data = np.random.random((100,100))

xslice, yslice = slice(20, 30), slice(45, 65)

plt.imshow(data, cmap=cm.gray)

x, y = np.mgrid[xslice, yslice]
plt.contour(x, y, data[xslice, yslice])

plt.show()

rawDescription: Setting position of contour sub-plot in Matplotlib


code:
items = {
  'an apple': '',
  'a pear': '',
  'an orange': ''
}

rawDescription: Returning HTML elements from a view in Django


code: dist = np.einsum('jkd,jkd->jk', deltas, deltas)

rawDescription: Fast evaluation of a product

description: Fast evaluation of a product


rawDescription: Put zeros in front of a number to make it 4 digits


code: result

rawDescription: convert column into headings for dataframe

description: Convert column into headings for dataframe


code:
body=BinOp(
    left=Compare(
        left=Name(id='x', ctx=Load()),
        ops=[Lt()],
        comparators=[Num(n=5)]
    ),
    op=BitAnd(),
    right=Compare(
        left=Name(id='x', ctx=Load()),
        ops=[Gt()],
        comparators=[Num(n=-5)]
    )
)

rawDescription: Defining new semantics for expressions in Python


rawDescription: Pandas combine multiple excel worksheets on specific index


code:
div_parents = root_element.xpath('//div[div]')

for outer_div in div_parents:
    if len(outer_div.getchildren()) == 1:
        inner_div = outer_div[0]
        # Copy the children of innder_div to outer_div
        for e in inner_div: outer_div.append( copy.deepcopy(e) )
        # Remove inner_div from outer_div
        outer_div.remove(inner_div)

rawDescription: lxml - how to remove element but not it's content?

description: Lxml - how to remove element but not it's content


code:
from blqblq.lqlqlqlq.bla import (
                                 fobarbazbarbarbazar
                                 as foo)
from matplotlib.backends.backend_qt4agg import (
                                                 FigureCanvasQTAgg
                                                 as FigureCanvas)

rawDescription: Long imports in Python

description: Long imports in Python


code:
class Foo(object):
    __slots__ = ('bar', 'spam')

obj = Foo()
obj.bar = 42
{s: getattr(obj, s) for s in obj.__slots__ if hasattr(obj, s)}
{s: getattr(obj, s, None) for s in obj.__slots__}

rawDescription: How can I convert python class with slots to dictionary?

description: Convert python class with slots to dictionary


code: c.execute("DELETE FROM storedTweets WHERE tweetDate < date('now','-30 days')")

rawDescription: Comparing dates from from two different sources


code:
class ListPointer(object):
    def __init__(self, myList,i=0):
         self.myList = myList
         self.i = i % len(self.myList)

    def __repr__(self):
         return 'ListPointer(' + repr(self.myList) + ',' + str(self.i) + ')'

    def __str__(self):
        return str(self.myList[self.i])

    def __call__(self,*value):
        if len(value) == 0:
            return self.myList[self.i]
        else:
            self.myList[self.i] = value[0]

    def pp(self):
        self.i = (self.i + 1) % len(self.myList)

rawDescription: List element Pointer in Python

description: List element Pointer in Python


code: description = movie.get('plot outline')

rawDescription: How to retrieve the storyline paragraph with imdbpy?

description: Retrieve the storyline paragraph with imdbpy


code:
@login_manager.user_loader
def load_user(userid):
    # just query for user
    return User.query.get(userid) # User.query is Flask-SQLAlchemy extension, it's same to session.query(User).get(userid)

rawDescription: Application Layout with Groups of single items in Python


code:
class toolsGUI(Frame):
    def __init__(self, rootWin):
        Frame.__init__(self, rootWin)

    def frame(self):
        frame = Frame(self)
        ...
a = Tk()
t = toolsGUI(a)
t.pack(fill="both", expand=True)
a.mainloop()

rawDescription: How to automatically insert several tkinter items in Tk() window using classes

description: Automatically insert several tkinter items in Tk() window using classes


code: [e in lestring for e in lelist if e in lestring]

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


code:
from ast import literal_eval

with open('%s.log'%hname, 'wb') as outfile:
    outfile.writelines(literal_eval(line.rstrip()) for line in open('%s_tmp.log' %hname) if 'word' in line)

rawDescription: python line strip \n and write line

description: Python line strip \n and write line


rawDescription: How to get rows which match a list of 3-tuples conditions with SQLAlchemy

description: Get rows which match a list of 3-tuples conditions with SQLAlchemy


rawDescription: Rename files using python

description: Rename files using python


code:
def slices(seq, length, prefer_last=False):
  unique = {}
  if prefer_last: # this doesn't have to be a parameter, just choose one
    for start in xrange(len(seq) - length + 1):
      unique[seq[start:start+length]] = start
  else: # prefer first
    for start in xrange(len(seq) - length, -1, -1):
      unique[seq[start:start+length]] = start
  return unique

# or find all locations for each slice:
import collections
def slices(seq, length):
  unique = collections.defaultdict(list)
  for start in xrange(len(seq) - length + 1):
    unique[seq[start:start+length]].append(start)
  return unique

rawDescription: Python, Huge Iteration Performance Problem


code:
import cv2
import numpy as np
import time

# ...

CAMERA_1 = 0
CAMERA_2 = 1

def load_timestamps(camera):
    pass # Implement this

def get_next_frame(camera):
    pass # Implement this

# ...

timestamps = [
    load_timestamps(CAMERA_1)
    , load_timestamps(CAMERA_2)
    ]

start_time = None

frame_index = [0, 0]
video_done = [False, False]

# Make those default blank images the size of your video...
# Adjust number of channels if you're using grayscale
image =  [np.zeros((100,100,3),np.uint8)] * 2

while True:
    real_time = time.time()
    if start_time is None: # First iteration only
        start_time = real_time
    current_ts = real_time - start_time
    print("ts=%0.3f s" % current_ts)

    # Advance both cameras up to current_ts
    for i in [CAMERA_1, CAMERA_2]:
        while True:
            # Get timestamp of the frame at current position
            current_index = frame_index[i]
            if current_index >= len(timestamps[i]):
                video_done[i] = True
                break # End of the video
            video_ts = timestamps[i][current_index]
            if current_ts < video_ts:
                break # The frame is in future, stop
            # The frame is in the past or present
            print("  camera %d: frame %d" % (i+1, frame_index[i]))
            image[i] = get_next_frame(i)
            frame_index[i] += 1

    cv2.imshow("Output", np.hstack([image[0], image[1]]))
    cv2.waitKey(20) # Max 50 FPS, but probably slower

    if video_done[CAMERA_1] and video_done[CAMERA_2]:
        break

rawDescription: Displaying frames from 2 separate videos according to timestamps stored in a text file


code: len(np.unique(dm_s) * s_dist) == len(np.unique(dm_s))

rawDescription: Efficient way to iterate through numpy arrays in parallel and create a new resultant array


code: zip(a,b)

rawDescription: Sequence Generation with Number applied to string


rawDescription: Pandas Dataframe split in to sessions

description: Pandas Dataframe split in to sessions


code:
with open("my_out.json","ab") as f:
    for item in foo_now():
        json.dump(item,f)

rawDescription: Stream to JSON file using yield

description: Stream to JSON file using yield


code:
import os
import sys

scriptpath = os.path.dirname(__file__)
os.chdir(scriptpath)

rawDescription: Python: why would Python stop saving in the present working directory


code:
foobarfoo
foobarbafoo

rawDescription: Is there a "startswith" method in pyparsing


code: listOfFlowMaps = []

rawDescription: How to create a vector of Matrices in python

description: Create a vector of Matrices in python


code:
def find_peak(start, grad):
    for index, gr in enumerate(grad[start:]):
        if gr < 0:
            return index + start

def find_end(peak, grad):
    for index, gr in enumerate(grad[peak:]):
        if gr >= 0:
            return index + peak + 1

def find_peaks(grad):
    peaks=[]
    i = 0
    while i < len(grad[:-1]):
        if grad[i] > 0:
            start = i
            peak_index = find_peak(start, grad)
            end = find_end(peak_index, grad)
            area = np.trapz(y_data[start:end], x_data[start:end])
            peaks.append((x_data[peak_index], y_data[peak_index], area))
            i = end - 1
        else:
            i+=1
    return peaks

y_data = np.where(y_data > 5000, y_data, 0)

grad = np.diff(y_data)

peaks = find_peaks(grad)

from pylab import *
plot(x_data, y_data)
for peak in peaks:
    text(peak[0], 1.01*peak[1], '%d'%int(peak[2]))
grid(True)
show()

rawDescription: Image analysis on scientific chromatograms


code: code = data2.split('|', 1)[0]

rawDescription: Replacing data to different file

description: Replacing data to different file


code:
schema = StructType(
    [StructField(x, LongType(), False) for x in ("c_id", "cn_id", "cn_value")])

df2 = (sqlContext.read
    .format('com.databricks.spark.csv')
    .schema(schema)
    .options(header='false')
    .load(file2))

rawDescription: Python Spark How to Map Fields of one rdd to another rdd


rawDescription: Defining multiple variables at once in one line with one value?


code:
profile = user.get_profile()
profile.verified = False
profile.ip_address = get_client_ip()
profile.save()

rawDescription: Setting the UserProfile values

description: Setting the UserProfile values


code: self.sizer.Add(self.listBox, proportion=1, flag=wx.TOP | wx.EXPAND | wx.LEFT, border=5)

rawDescription: Putting Buttons underneath listbox in wxpython?


code:
from collections import defaultdict

df = pd.read_csv('emails.csv')
grouped = defaultdict(str)
for i, text in zip(df.sender_id, df.text):
    grouped[i] += text + ' '

with open('/storage/test.csv', 'w') as csvfile:
    test_writer = csv.writer(csvfile)
    for i in grouped.items():  # use iteritems in Python2
        test_writer.writerow(i)

rawDescription: These 8 lines of python + pandas would take ~1 month to execute, help me speed them up?


rawDescription: Python, random sample from a vector's non-zero indices


code:
def wp1_bubble(blist):
    cmpcount, swapcount = 0, 0
    while True:
        swapped = False
        for i in range(1, len(blist)):
            cmpcount += 1
            if blist[i-1] > blist[i]:
                swapcount += 1
                blist[i-1], blist[i] = blist[i], blist[i-1]
                swapped = True
        if not swapped:
            break
    return blist, cmpcount, swapcount

rawDescription: Is this most efficient to bubble sort a list in python?


code:
from mock import patch

with patch('module1.function1') as function1:
    function1.side_effect = function_object
    # Do stuff

rawDescription: Python assign a function to another function


code: sorted(fechas_, key=lambda entry: meses_ord[entry['month']])

rawDescription: Order a list of dictionaries based on another dictionary


code: ', '.join(inside)

rawDescription: Good way to concatenate str to list?

description: Good way to concatenate str to list


code:
import math
math.factorial(40) / (math.factorial(20) * math.factorial(40-20))

rawDescription: Finding the different combinations

description: Finding the different combinations


rawDescription: Python pandas.read_csv split column into multiple new columns using comma to separate


code:
from collections import Counter
dict(Counter(a)+Counter(b))

rawDescription: "Adding" Dictionaries in Python?

description: "Adding" Dictionaries in Python


rawDescription: Python Slice Notation with Comma/List

description: Python Slice Notation with Comma/List


code:
from itertools import permutations, zip_longest

perms = permutations(word_list, 2)

st = set(word_list)
for a, b in perms:
    res = "".join("".join(tup) for tup in zip_longest(a,b,fillvalue=""))
    if res in st:
        print(res)

rawDescription: Looping a function over a list in Python


rawDescription: Sort list according given text of months


code:
namedict = ({"first_name":"Joshua", "last_name":"Drake"},
            {"first_name":"Steven", "last_name":"Foo"},
            {"first_name":"David", "last_name":"Bar"})

rawDescription: How do I get a scrapy item (or a dict / named tuple) into a postgres stored procudure (function) performing an insert using psycopg2

description: Get a scrapy item (or a dict / named tuple) into a postgres stored procudure (function) performing an insert using psycopg2


code:
first_condition = df['GVKEY'] == df['GVKEY'].shift()
second_condition = df['EXEC_FULLNAME'] !=  df['EXEC_FULLNAME'].shift()
df['FLAG'] = first_condition & second_condition

rawDescription: Iterate and compare values through a dataframe


code:
word_list = '''\
the      8512
and      7759
i        6182
to       6027
a        4716
of       4619
he       2873
in       2846
you      2777
was      2457
'''.splitlines()
d = dict(line.split() for line in word_list)
sorted_list = sorted(d.items(), key=lambda i: i[1], reverse=True)
for index, (value,num) in enumerate(sorted_list, start=1):
    print("{}.\t{:<5}\t{:>5}".format(index, value,num))

rawDescription: Creating numbered list of output

description: Creating numbered list of output


code:
def subplot_class_factory(axes_class=None):
    # This makes a new class that inherits from SubplotBase and the
    # given axes_class (which is assumed to be a subclass of Axes).
    # This is perhaps a little bit roundabout to make a new class on
    # the fly like this, but it means that a new Subplot class does
    # not have to be created for every type of Axes.
    if axes_class is None:
        axes_class = Axes

    new_class = _subplot_classes.get(axes_class)
    if new_class is None:
        new_class = new.classobj("%sSubplot" % (axes_class.__name__),
                                 (SubplotBase, axes_class),
                                 {'_axes_class': axes_class})
        _subplot_classes[axes_class] = new_class

    return new_class

rawDescription: There is a class matplotlib.axes.AxesSubplot, but the module matplotlib.axes has no attribute AxesSubplot


code:
for x in break_down('the fast dog'):
    print(x)
for x in break_down('the really fast dog'):
    print(x)

rawDescription: Split a string into all possible ordered phrases


rawDescription: zip 2 lists of dictionaries into 1

description: Zip 2 lists of dictionaries into 1


code:
if len(a) == len(b):
    same_structure(a[1:],b[1:])

rawDescription: How to find out two lists with same structure in python?

description: Find out two lists with same structure in python


code:
investment_df['quintile'] = pd.qcut(investment_df['investment'], 5, labels=np.arange(5, 0, -1))
investment_df['decile'] = pd.qcut(investment_df['investment'], 10, labels=np.arange(10, 0, -1))
investment_df

rawDescription: How to create a Decile and Quintile columns to rank another variable based on size using Python, Pandas?

description: Create a Decile and Quintile columns to rank another variable based on size using Python, Pandas


code:
def event_handler(self, event):

    if event.type == pygame.KEYDOWN:
        if event.key == pygame.K_a:
            velX = -5
        elif event.key == pygame.K_d:
            velX = +5
    elif event.type == pygame.KEYUP:
        if event.key in (pygame.K_a, pygame.K_d):
            velX = 0

rawDescription: Pygame - AttributeError: 'int' object has no attribute 'y'


code:
def smallest_value_of_key_startswith(a, d):
    min(((d[s],s) for s in d if s.startswith(a)))[1][len(a):]

rawDescription: Python dictionaries - find second character in a 2-character string which yields minimum value


rawDescription: Flatten doubly nested lists

description: Flatten doubly nested lists


code:
import re
re.split('\s+', line, 8)

rawDescription: Read text file and take region names in Python


code: re.match(..., content, re.DOTALL)

rawDescription: Extracting a table from webpage with regex


code:
i = np.random.random((3,2))
j = np.random.random((3,2))
i
j
map(np.correlate, i, j)

rawDescription: Operations between two dataframes or equivalently between two multidimensional arrays


rawDescription: Word-counter won't print foreign characters


code:
# creates a reference to the method f
In [190]: f = a.f
# creates a reference to the method g
In [191]: g = a.g
# cannot reuse the memory location of f as it is still referenced
In [192]: id(f) == id(g)
Out[192]: False

rawDescription: Why do different methods of same object have the same `id`?


code:
a0 = a[:,0]
c = np.true_divide(a[:,1],b[np.searchsorted(a0,b[:,0],sorter=a0.argsort()),1])

rawDescription: Checking to see if array elements are equal


rawDescription: making exe file from python that uses command line arguments

description: Making exe file from python that uses command line arguments


code:
#!/usr/bin/python
import json
import requests

r = requests.get('https://github.com/timeline.json')

with open("yourfilepath.json", "w") as f:
    f.write(json.dumps(r.json))

rawDescription: Write Python dictionary obtained from JSON in a file


rawDescription: convert a flat list to list of list in python

description: Convert a flat list to list of list in python


code:
# 59:59 - It's all right. - He saw us!
# 01:00:01 I heard you the first time.

rawDescription: python regex sub %H:%M:%S to %M:%s or 01:%M:%s

description: Python regex sub %H:%M:%S to %M:%s or 01:%M:%s


code:
['<s>', 'Assembly', 'session', 'brought', 'much', 'good', '</s>']
['<s>', 'The', 'General', 'Assembly', ',', 'which', 'adjourns', 'today', ',', 'has', 'performed', 'in', 'an', 'atmosphere', 'of', 'crisis', 'and', 'struggle', 'from', 'the', 'day', 'it', 'convened', '</s>']
['<s>', 'It', 'was', 'faced', 'immediately', 'with', 'a', 'showdown', 'on', 'the', 'schools', ',', 'an', 'issue', 'which', 'was', 'met', 'squarely', 'in', 'conjunction', 'with', 'the', 'governor', 'with', 'a', 'decision', 'not', 'to', 'risk', 'abandoning', 'public', 'education', '</s>']
['<s>', 'There', 'followed', 'the', 'historic', 'appropriations', 'and', 'budget', 'fight', ',', 'in', 'which', 'the', 'General', 'Assembly', 'decided', 'to', 'tackle', 'executive', 'powers', '</s>']
['<s>', 'The', 'final', 'decision', 'went', 'to', 'the', 'executive', 'but', 'a', 'way', 'has', 'been', 'opened', 'for', 'strengthening', 'budgeting', 'procedures', 'and', 'to', 'provide', 'legislators', 'information', 'they', 'need', '</s>']

rawDescription: NLTK tokenize questions

description: NLTK tokenize questions


rawDescription: Concise way to remove elements from list by index in Python


rawDescription: How to efficiently index into a 1D numpy array via slice ranges

description: Efficiently index into a 1D numpy array via slice ranges


code:
for j in i:
    c[j[1]]=j[2].lower()

rawDescription: how to make two or more combinations of specific letter?

description: Make two or more combinations of specific letter


code:
f = pickle.loads(pickle.dumps(set.union))
f(set([1, 2, 3]), set([5]))

rawDescription: Pickling method descriptor objects in python


code:
print('I picked: {}'.format(names[index]))
nextname = input('Who is next?')
if nextname == names[index + 1]:
    print('Correct! It is indeed {}'.format(names[index + 1]))

rawDescription: how to find unknown variable in list?

description: Find unknown variable in list


code:
df['High'][s.values]
# Or: df[s.values]['High']

rawDescription: Select from pandas dataframe using boolean series/array


code: Z = mixed_model_pdf(coords).reshape(Y.size, Y.size)

rawDescription: Matplotlib: How to make a contour plot?

description: Matplotlib: How to make a contour plot


code: sorted(your_list, key=lambda x: x[1], reverse=True)

rawDescription: Trying to sort a list very specifically in Python


code:
import multiprocessing as mp
import time
import random
import subprocess
import logging
logger = mp.log_to_stderr(logging.WARN)

def popen_wrapper(i):
    logger.warn('echo "hi"')
    return i

def log_result(retval):
    results.append(retval)

if __name__ == '__main__':

    num_to_run = 15
    max_parallel = 3
    results = []

    pool =  mp.Pool(max_parallel)
    for i in range(num_to_run):
        pool.apply_async(popen_wrapper, args=(i,), callback=log_result)
    pool.close()
    pool.join()

    logger.warn(results)

rawDescription: python multiprocessing - select-like on running processes to see which have one have finished

description: Python multiprocessing - select-like on running processes to see which have one have finished


code:
def pretty_time(t):
    """takes a time, in seconds, and formats it for display"""
    m, s = divmod(t, 60)
    h, m = divmod(m, 60)
    s = round(s) #Rounds seconds to the nearest whole number
    h = str(h).rjust(2,'0') #covert to strings,
    m = str(m).rjust(2,'0') #adding 0 if necessary to make
    s = str(s).rjust(2,'0') #each one two digits long
    return "{}:{}:{}".format(h,m,s)

rawDescription: Calculate the elapsed time in python

description: Calculate the elapsed time in python


code:
left("10001").related()
right("qwer")
right(left("10001").related()['key'])
right("qwer") is left("10001").related()

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


code:
fields = ['id', 'name', 'row3', 'row4']
values = ['b', 'diego', 3, 4]

fields_str = (", ").join([x for x in fields])
values_str = (", ").join([("'" + str(x) + "'") for x in values])

cursor.execute("INSERT IGNORE INTO a (" + fields_str + ") VALUES (" + values_str + ")")

rawDescription: How to easily concatenate strings from a list with some format in python?

description: Easily concatenate strings from a list with some format in python


code:
import numpy
import scipy.misc
import matplotlib.pyplot

# Get classic image processing example image, Lena, at 8-bit grayscale
# bit-depth, 512 x 512 size.
lena = scipy.misc.lena()
# lena is now a Numpy array of integers, between 245 and 25, of 512 rows and
# 512 columns.

def get_indices(size):
    """
    Returns each fourth index in a Numpy vector of the passed in size.
    Specifically, return a vector of booleans, where all indices are set to
    False except those of every fourth element. This vector can be used to
    index another Numpy array and select *only* those elements. Example use:

        >>> import numpy as np
        >>> vector = np.array([0, 1, 2, 3, 4])
        >>> get_indices(vector.size)
        array([ True, False, False, False,  True], ...)

    """
    arr = numpy.arange(size)
    return arr % 4 == 0

# Keep a copy of the original image
lena1 = lena.copy()

# Use the defined function to get every fourth index, first in the x direction,
# then in the y direction
xindices = get_indices(lena.shape[0])
yindices = get_indices(lena.shape[1])

# Set every pixel that equals true in the vectors further up to 0. This
# selects **each fourth pixel on the diagonal** (from up left to bottom right).
lena[xindices, yindices] = 0

# Create a Matplotlib plot, with 2 subplots, and selects the one on the 1st
# colum, 1st row. The layout for all subplots is determined from all calls to
# subplot, i.e. if you later call `subplot(212)` you will get a vertical layout
# in one column and two rows; but if you call `subplot(221)` you will get a
# horizontal layout in two columns and one row.
matplotlib.pyplot.subplot(211)
# Show the unaltered image on the first subplot
matplotlib.pyplot.imshow(lena1)
# You could plot the modified original image in the second subplot, and compare
# to the unmodified copy by issuing:
#matplotlib.pyplot.subplot(212)
#matplotlib.pyplot.imshow(lena)

matplotlib.pyplot.show()

rawDescription: Breaking down numpy code

description: Breaking down numpy code


rawDescription: Extra credit in Django tutorial

description: Extra credit in Django tutorial


code:
with open('the_file_name.txt','w') as f:
    for elem in data:
        f.write('{artist}\n{title}\n{album}\n\n'.format(**elem['metadata']))

rawDescription: Extract/scrape specific data from JSON file


rawDescription: Reopen file for appending

description: Reopen file for appending


code:
from collections import defaultdict
tries_dict = defaultdict(lambda: 'next',
                         {1:'first', 2:'second', 3:'third', 4:'fourth', ub_tries:'last'})
tries_dict
tries_dict[5]
tries_dict

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


rawDescription: Add values in column of Panda Dataframe

description: Add values in column of Panda Dataframe


code: TTTCGGAA

rawDescription: I need to replace all the characters of string in python


code:
rand_pos = np.random.rand(900, 3)
gal_pos = np.random.rand(1e5, 3) # 10x smaller than OP's data set

rawDescription: Trying to perform an operation on all sub arrays inside a numpy array without using a for (or similar) loops


code:
import re
re.sub('<a href="/name/.{9}', '', string)

rawDescription: python string.replace() a string + 12 characters following

description: Python string.replace() a string + 12 characters following


code:
x = 2

x             # only the first-if changed the value of x, rest of them

rawDescription: If Elif statements in python

description: If Elif statements in python


code:
df["TimeReviewed"] = pd.to_datetime(df["TimeReviewed"])
df["TimeReviewed"]
df["TimeReviewed"].dt
df["TimeReviewed"].dt.year
df["TimeReviewed"].dt.month
df["TimeReviewed"].dt.minute

rawDescription: Convert Pandas Series to DateTime in a DataFrame


rawDescription: Concatenate lines with similar key

description: Concatenate lines with similar key


rawDescription: How would I go about improving/making this run faster?


code: intersection = {email: group for email, group in dict_2.iteritems() if email in dict_1}

rawDescription: Different __hash__ and __eq__ methods for use in set


code:
from __future__ import print_function
from collections import OrderedDict

d = OrderedDict()
with open('descr2semtype_short.txt') as f:
    for line in f:
        line = line.rstrip()
        a, b = line.split()
        if a not in d:
            d[a] = []
        d[a].append(b)

for k,v in d.items():
    print(k + ' ' + ' '.join(v))

rawDescription: Print lines with constraint in Python

description: Print lines with constraint in Python


rawDescription: Adding scrolling to a top/down shooter

description: Adding scrolling to a top/down shooter


code:
fig, axes = plt.subplots(nrows=4)
for y, ax in zip(ydata, axes):
    ax.plot(x, y, color='salmon')
    ax.locator_params(axis='y', nbins=5, prune='both')
plt.show()

rawDescription: Python Numpy 2D plot set total number of y-tics with autoscaling


rawDescription: Python: Function with matrix in argument


code:
df
d
key = 'Cyp26_G_rep1'

rawDescription: Using lambda function to multiply columns of a pandas dataframe by a different value for each column


code:
def findKSmallest( self, k ):
    if k == 0:
        return []
    leftSmallest = self.left.findKSmallest( k ) if self.left != None else []
    rightSmallest = self.right.findKSmallest( k - 1 ) if self.right != None else []
    mySmallest = sorted( leftSmallest + [self.data] + rightSmallest )
    return mySmallest[:k]

rawDescription: Python recursion - how to exit early

description: Python recursion - how to exit early


code: i = StringIO(i.getvalue())  # create a cStringIO.StringO instance for a cStringIO.StringI instance.

rawDescription: Convert pyBarcode output to PIL Image file


code: links = [link.get('href') for link in soup.select('div.product-image > a:nth-of-type(1)')]

rawDescription: Beautifulsoup to retrieve the href list

description: Beautifulsoup to retrieve the href list


code:
s.value = v
s.value
s[:]

rawDescription: Porting a VBA Type / C struct to a Python ctypes.Structure: array of strings with fixed length


code: struct.pack('20d', *data)

rawDescription: Making lookup table in python, writing to a binary file that can be read in in a C program


code: a.get('foo',my_default) or my_default

rawDescription: Checking if a key exists and its value is not an empty string in a Python dictionary


code: [r[:,-1] for r in rays]

rawDescription: Efficient way of appending / extracting list elements


code:
x = 0

def increment_x():
    global x
    x += 1
    return x

rawDescription: Why aren't my globals global?

description: Why aren't my globals global


code:
# yourModule.py
from myModule import foo

rawDescription: Python: Can i set global variables in a package __init__ module?


code: getattr(server, vars["fnc"])(vars)

rawDescription: python variable function definition

description: Python variable function definition


code:
import types

class Foo:
    pass

if isinstance(Foo, types.ClassType):
    print("Yep, it's old-style class")

rawDescription: How to check if module attribute is a Class

description: Check if module attribute is a Class


code:
X.shape
lsa.components_.shape
km.cluster_centers_.shape
weights = np.dot(km.cluster_centers_, lsa.components_)
weights.shape

rawDescription: sklearn decomposition top terms

description: Sklearn decomposition top terms


code:
from abc import ABCMeta, abstractmethod
from six import add_metaclass
@add_metaclass(ABCMeta)
class MyABC(object):
    @abstractmethod
    def gamma(self): pass

MyABC()

rawDescription: How to write a Python ABC with a concrete initializer in python 2.6 to 3.5?

description: Write a Python ABC with a concrete initializer in python 2.6 to 3.5


code:
import to_import_from

class Instrument(to_import_from.InstrumentBase):
    def __init__(self):
        ...

rawDescription: Importing methods for a Python class

description: Importing methods for a Python class


code:
from django import forms
from django.forms import ModelForm
from django.db import models

class Poll(models.Model):
    RATING_CHOICES = [(i,i) for i in range(1,6)]
    question = models.TextField()
    rating = models.PositiveSmallIntegerField(choices=RATING_CHOICES)

class PollForm(ModelForm):
    class Meta:
        model = Poll
        fields = ('question', 'rating')
        widgets = {'rating': forms.RadioSelect}

rawDescription: Adding mulitple choice poll to sentence and writing result to csv file (Django/Python)


rawDescription: Python print " character

description: Python print " character


code:
if pts2 == "1":
    skills["Strength"] += pts
    points -= pts
...

rawDescription: Programming Python for absolute beginners: Chapter 5 Challenge #2


code:
data_dict = {k : list(g)
             for k, g in groupby(sorted(data,
                                        key = itemgetter('key')),
                                 key = itemgetter('key'))}

rawDescription: nicer way to merge list of dictionaries by key

description: Nicer way to merge list of dictionaries by key


code:
import fnmatch
import shutil
import os

def my_copy(indir, outdir):

    special = []

    def is_special_dir(path, names):
        """directories are special if they have .bar files"""
        if fnmatch.filter(names,'*.bar'):
            special.append(path)
            return names
        return []

    shutil.copytree(indir, outdir, ignore=is_special_dir)
    print('Found special dirs:',special)

    for src in special:
        rel = os.path.relpath(src,indir)
        dst = os.path.join(outdir,rel)
        os.rmdir(dst)
        print('Zip "{}" to "{}.zip"'.format(src,dst))

my_copy('dir1','dira')
my_copy('dir1','dirb')

rawDescription: Implementing a recursive copy in Python with special case handling


code:
def makesample(N, buckelems, mi, ma, bs):
    s = []
    for _ in range(N):
        buck = random.choice(buckelems)
        x = random.uniform(mi+buck*bs, mi+(buck+1)*bs)
        s.append(x)
    return s

rawDescription: create distribution from a list and generate random numbers which follow that distribution in Python

description: Create distribution from a list and generate random numbers which follow that distribution in Python


code:
@staticmethod
def gettransaction(): return db.transaction

rawDescription: python: cleanest way to wrap each method in parent class in a "with"

description: Python: cleanest way to wrap each method in parent class in a "with"


code: gtk.TreeViewColumn ('...', gtk.CellRendererCombo (), text = N, model = M)

rawDescription: Conditional CellRenderCombo in pyGTK TreeView


code:
for line in nX.splitlines():
    pn(line)

rawDescription: How can I do lines of a single string sleep before being printed?

description: Do lines of a single string sleep before being printed


rawDescription: Numpy selecting specific column index per row by using a list of indexes


rawDescription: dataframe pandas subset series

description: Dataframe pandas subset series


rawDescription: Multiple page PDF with multiple charts per page from matplotlib


rawDescription: Finding a position of web images in a scrape


code:
tracer(fact)
new_fact = tracer(fact)
new_fact
new_fact(2)

rawDescription: higher order function python walkthrough

description: Higher order function python walkthrough


code: AUTH_USER_MODEL = 'myapp.CachedUser'

rawDescription: How to get Django Cache Machine to work on django.contrib.auth.models.User?

description: Get Django Cache Machine to work on django.contrib.auth.models.User


code: Arg = Kx[m,n]*u[i] + Ky[m,n]*v[j]

rawDescription: Numpy multiplication of vectors of different size avoiding for loops


code:
class MyForm(Form):
    field1 = IntegerField(widget=HiddenInput())

rawDescription: How can I use a HiddenField to coerce integer data in WTForms?

description: Use a HiddenField to coerce integer data in WTForms


code:
import pandas as pd

df = pd.DataFrame({
        'foo': [1, 1, 2, 2, 3, 3],
        'bar': [1, 2, 3, 4, 5, 6]
    })

def compute_thing(group):
    return pd.DataFrame({
            'foo_mu': group['foo'].mean(),
            'bar_mu': group['bar'].mean()
        }, index=[0])

df.groupby('foo').apply(compute_thing)

rawDescription: pandas - Compute a function of each group in different columns

description: Pandas - Compute a function of each group in different columns


rawDescription: python regex with unicode to match a city name

description: Python regex with unicode to match a city name


rawDescription: Calculate date variance based on common id


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

def compileCells(cellArray, nrows, ncols, cellHeight, cellWidth):
    display = np.empty((cellHeight*nrows, cellWidth*ncols, 3), dtype=np.uint8)
    for i, j in IT.product(range(nrows), range(ncols)):
        # arr = cellArray[i*ncols+j].image  # you may need this
        arr = cellArray[i*ncols+j]          # my simplified cellArray uses this
        x, y = i*cellHeight, j*cellWidth
        display[x:x+cellHeight, y:y+cellWidth, :] = arr
    return display

cellHeight, cellWidth = 80, 60
nrows = ncols = numberOfCells = 10

cellArray = [np.full((cellHeight, cellWidth, 3), i)
             for i in np.linspace(0, 255, nrows*ncols)]
display = compileCells(cellArray, nrows, ncols, cellHeight, cellWidth)
plt.imshow(display)
plt.show()

rawDescription: Faster way than concatenate of combining multiple cv2 images (numpy arrays) in python?


code:
normed = (dist ** 2).sum(axis=2) ** 0.5
normed.mean(axis=1)
min_window = normed.mean(axis=1).argmin()
arr2[:,[min_window, min_window + 1]]

rawDescription: Distance between numpy arrays, columnwise


code: filtered_df = df[df['Loan_Status'].isin(positive + negative)].copy()

rawDescription: Python way to convert categorical values into binary in the same column


code:
def format_elapsed_time(seconds):
    seconds = int(seconds + 0.5)  # round to nearest second
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

rawDescription: python - get time in specific format

description: Python - get time in specific format


code:
child_proc_th = Process(target=child_proc, args=(3,))
child_proc_th.start()
child_proc_th.join()

rawDescription: signal.signal receives sigint/sigterm when child process ends

description: Signal.signal receives sigint/sigterm when child process ends


code:
def writeFile (filename, text):
    with open(filename,'w') as file:
        for line in text:
            file.write(line)

def main():
    result=[]
    big_nums = ['no','One','Two','Three','Four','Five','Six','Seven','Eight','Nine','Ten']
    text_one = (' green bottles \nHanging on the wall\n')
    small_nums = [' no',' one',' two',' three',' four',' five',' six',' seven',' eight',' nine',' ten']
    text_two = ('And if one green bottle \nShould accidentally fall\nThere\'ll be')
    text_three = (' green bottles \nHanging on the wall\n \n')
    new_string=''
    text = new_string

    for i in range(0,10):
        result.append(big_nums[i] + str( text_one))
        #result.append(big_nums[i] + str( text_one))
        result.append(text_two + small_nums[i-1] + text_three)
        #return result('')
        #print(''.join(main(text)))

    writeFile('greenBottle.txt',result)

main()

rawDescription: why is my code not writing to a new text file

description: Why is my code not writing to a new text file


code: command = lambda: saver(each)

rawDescription: Store the values of Radiobuttons and Checkbuttons


code:
string = " this is how i do is it..is this is how we do it.. this is how everyone do it is"

from collections import Counter

s_count = Counter(string)

def score_count(x):
    return sum(s_count[ele] for ele in x)

most_imp = None
high_val = 0
n = 10

for i in xrange(0, len(string) - n):

    temp_value = score_count(string[i: i + n])

    if temp_value > high_val:
        high_val = temp_value
        most_imp = string[i : i + n]

rawDescription: select a chunk with maximum score in a string python

description: Select a chunk with maximum score in a string python


code:
from functools import reduce
reduce(lambda res, cur: {cur: res}, reversed("foo/bar/baz".split("/")), 1)

rawDescription: How can I split a string and form a multi-level nested dictionary?

description: Split a string and form a multi-level nested dictionary


code:
import kivy
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.video import Video
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import *
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from random import random
from kivy.properties import ListProperty

from kivy.uix.floatlayout import FloatLayout

kv = '''
<ColoredLabel>:
    size: (150, 200)
    pos: (50, 150)
    background_color:
    canvas.before:
        Color:
            rgba: self.background_color
        Rectangle:
            pos: self.pos
            size: self.size
    '''

Builder.load_string(kv)

class ColoredLabel(Label):
    background_color = ListProperty((0,0,0,1))

class MyApp(App):
    def build(self):
        f = FloatLayout()
        label = ColoredLabel(text="Hello World!", size_hint=(None, None), background_color=(random(), random(), random(), 1))
        f.add_widget(label)

        return f

if __name__ == "__main__":
    MyApp().run()

rawDescription: python kivy add text inside rectangle

description: Python kivy add text inside rectangle


code:
from __future__ import absolute_import

d1 = {'a':1,'b':2,'c':3}
d2 = {'a':9,'d':10}

c = {k:(d2[k] if k in d2 else v) for k,v in d1.items()}

print(c)

rawDescription: Copy key value pair from one dictionary to another if the same key exists in both the dictionaries in Python


code:
from itertools import zip_longest

def find_first_diff(list1, list2):
    for index, (x, y) in enumerate(zip_longest(list1, list2,
                                               fillvalue=object())):
        if x != y:
            return index

rawDescription: Python: Fastest Way to compare arrays elementwise


rawDescription: Python's ConfigParser unique keys per section


code:
def get_strings(words, pad, length):
    from itertools import combinations
    nwords = len(words)
    npad = length - sum(len(word) for word in words)
    nslots = nwords + npad
    for ix in combinations(range(nslots), nwords):
        result = [pad] * nslots
        i = 0
        for j in ix:
            result[j] = words[i]
            i += 1
        yield "".join(result)

rawDescription: Generate a list of strings in python

description: Generate a list of strings in python


code: segment_tab = [line.split('\t') for line in in_file]

rawDescription: How to not include '\n' and the next index entry while appending values from a certain index to a list

description: Not include '\n' and the next index entry while appending values from a certain index to a list


code:
for row in data.split(','):
    file.write(row + '\n')

rawDescription: Python reading in file and creating new lines


code:
#!/usr/bin/env python
from geopy import geocoders # pip install "geopy[timezone]"

g = geocoders.GoogleV3()
for coords in [(18.4372,  -67.159), (41.9782,  -71.7679), (61.1895,  -149.874)]:
    print(g.timezone(coords).zone)

rawDescription: pytz: return Olson Timezone name from only a GMT Offset

description: Pytz: return Olson Timezone name from only a GMT Offset


rawDescription: Edit Dictionary in python

description: Edit Dictionary in python


rawDescription: Multidimensional array for a text based game


code:
from django.conf.urls.defaults import *

urlpatterns = patterns('myproject.views',
    url(r'^$', 'index', name='index'),
)

rawDescription: How does one put a link / url to the web-site's home page in Django?

description: Put a link / url to the web-site's home page in Django


code: result.div(result.sum()).cumsum() < 0.9

rawDescription: pandas: how to aggregate a subset of groupby rows into a single row?

description: Pandas: how to aggregate a subset of groupby rows into a single row


code:
class MyHandler:
    def GET(self):
        raise MultipleChoices(['http://example.com/', 'http://www.google.com/'])

rawDescription: Webpy: how to set http status code to 300


rawDescription: Adding 'vote' buttons to django objects

description: Adding 'vote' buttons to django objects


code:
with open("mylist.txt") as f: #in read mode, not in write mode, careful
    rd=f.readlines()
print (rd)

rawDescription: Python Storing Data

description: Python Storing Data


code: name = 'C'

rawDescription: Function object in Python

description: Function object in Python


code:
max_q = max([self.getQValue(nextState, action) for action in legal_actions])
max_q = max(self.getQValue(nextState, action) for action in legal_actions)

rawDescription: max([x for x in something]) vs max(x for x in something): why is there a difference and what is it?

description: Max([x for x in something]) vs max(x for x in something): why is there a difference and what is it


rawDescription: python dict to numpy structured array

description: Python dict to numpy structured array


code:
new_ticks = np.linspace(0, 1, 11)       # 0.0, 0.1, 0.2, ..., 1.0
ax.set_xticks(new_ticks)

rawDescription: How can I set the x-axis tick locations for a bar plot created from a pandas DataFrame?

description: Set the x-axis tick locations for a bar plot created from a pandas DataFrame


code:
stg = "abcde123]\nefghi456}\njk{lmn789"
import numpy as np

arr = np.array([ch for line in stg for ch in line if ch.isdigit() or ch.isalpha()])

rawDescription: Convert a long string into a matrix, cleaning it


code:
import os
import subprocess

foo = ('String', 'Tuple', 'From', 'Python' )

os.putenv('FOO', ' '.join(foo))

subprocess.call('./foo.sh')

rawDescription: Passing python array to bash script (and passing bash variable to python function)


rawDescription: how to add thousands separator to a number that has been converted to a string in python?

description: Add thousands separator to a number that has been converted to a string in python


rawDescription: Searching from Bottom to Top in Python

description: Searching from Bottom to Top in Python


rawDescription: Interface with remote computers using Python