code: transformed_A = [[item[0], transformed_B[item[0]]] if item[0] in transformed_B else item for item in A]

rawDescription: Replace elements in 2nd column of array with new value from 2nd column of smaller array when 1st column matches


code:
import boto.ec2
c = boto.ec2.connect_to_region('us-west-2')
reservations = c.get_all_instances(instance_ids='i-12345678')
instance = reservations[0].instances[0]
instance.add_tag('foo', 'bar')

rawDescription: How to update/change tag values of classic EC2 instances using boto library

description: Update/change tag values of classic EC2 instances using boto library


code:
def combinations(input_list, acc='', from_idx=0):

    if len(input_list) <= from_idx:
        yield acc
        return

    next_val = input_list[from_idx]

    for rest in combinations(input_list, acc, from_idx + 1):
        yield rest

    acc += next_val

    # In python 3.2, you can use "yield from combinations(input_list[1:], acc)"
    for rest in combinations(input_list, acc, from_idx + 1):
        yield rest

rawDescription: What's the most memory efficient way to generate the combinations of a set in python?


code:
from cStringIO import StringIO

imgfile = StringIO(self.request.get('datafile'))
img = Image.open(imgfile)

rawDescription: Converting binary file into PIL Image datatype in Google App Engine


code:
words = ["{}: {} and {}".format(i, x, y) for i, (x, y) in enumerate([(x, y) for x in firstList for y in secondList])]
print(*words)

rawDescription: Python Combining strings and printing multiple times


rawDescription: Nested grouping Regular Expression in Python


code:
def inAnyPolygon(x,y,polygons):
  for p in polygons:
    if point_in_poly(x,y,p):
      return True
  return False

rawDescription: Removing points inside several polygons

description: Removing points inside several polygons


code:
session.query(Association.association_property_1,
  func.abs(A.a_property_special - B.a.a_property_special)).\
  filter(B.a.a_property_special > 3.0)

rawDescription: In SQLAlchemy, how to access a referenced property in a query when having multiple relationships?


code:
class A(object, metaclass=MetaA):
    pass

rawDescription: How to write a static python getitem method?

description: Write a static python getitem method


code: win32api.keybd_event(win32con.VK_CONTROL, 0, win32con.KEYEVENTF_KEYUP, 0)

rawDescription: Generating Mouse-Keyboard combination events in python


code:
import pickle

high_scores = {"Adam Smith": 65536, "John Doe": 10000}
with open("highscores.pkl","wb") as out:
    pickle.dump(high_scores, out)

rawDescription: Keeping high scores in a text file

description: Keeping high scores in a text file


rawDescription: append to a key in a dictionary the union of other two keys using python

description: Append to a key in a dictionary the union of other two keys using python


rawDescription: Printing "*" characters separated by dashes with the print function's "sep" paramter


code:
import networkx as nx
import pylab as py

G = nx.Graph()

H = nx.Graph()
H.add_edges_from([(1,2), (2,3), (1,3)])

I = nx.Graph()
I.add_edges_from([(1,3), (3,2)])

G.add_edge(H,I)

Gpos = nx.spring_layout(G)
Hpos = nx.spring_layout(H)
Ipos = nx.spring_layout(I)

scalefactor = 0.1
for node in H.nodes():
    Hpos[node] = Hpos[node]*scalefactor + Gpos[H]

for node in I.nodes():
    Ipos[node] = Ipos[node]*scalefactor + Gpos[I]

nx.draw_networkx_edges(G, pos = Gpos)
nx.draw_networkx_nodes(G, pos = Gpos, node_color = 'b', node_size = 15000, alpha = 0.5)
nx.draw(H, pos = Hpos, with_labels = True)
nx.draw(I, pos = Ipos, with_labels = True)
py.savefig('tmp.png')

rawDescription: Drawing nested networkx graphs

description: Drawing nested networkx graphs


code: axes.lines.append(ax2[0])  # Puts the line back (the drawing order is changed, here)

rawDescription: matplotlib plt.show() only selected objects

description: Matplotlib plt.show() only selected objects


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
    '-t', '--temperature',
    help='performs temperature test (period in sec)',
    type=int,
    nargs='?',
    const=60,         # Default value if -t is supplied
    default=None,     # Default value if -t is not supplied
    metavar='PERIOD')

args = parser.parse_args()
print(args)

rawDescription: argparse: store_true and int at same time

description: Argparse: store_true and int at same time


code:
[{'Germany': {"Luge - Women's Singles": 'Gold'}},
{'Austria': {"Luge - Women's Singles": 'Silver'}},
{'Germany': {"Luge - Women's Singles": 'Bronze'}}]

rawDescription: How would I merged nested dictionaries in a list in python?


code:
dt = parser.parse("18:36")
hours = dt.hour
minute = dt.minute

rawDescription: Python: How can I convert string to datetime without knowing the format?


code: np.array([v for k,v in sorted(c.iteritems())])

rawDescription: Numpy bincount() with floats

description: Numpy bincount() with floats


code:
def import_data(column, *args, **kw):
    # make custom ContactCSVModel
    class ContactCSVModel(CsvModel):
        # IF column == x

        first_name = CharField()
        last_name = CharField()
        company = CharField()
        mobile = CharField()
        group = DjangoModelField(Group)
        contact_owner = DjangoModelField(User)

        class Meta:
            delimiter = ","
            dbModel = Contact
            update = {'keys': ["mobile", "group"]}

    return ContactCSVModel.import_data(*args, **kw)

# in another file, you can even mask it as your model class,
# I wouldn't do that however
import somemodule as ContactCSVModel

# Try and import CSV
ContactCSVModel.import_data(form, data=file, extra_fields=[
                           {'value': upload.group_id, 'position': 5},
                           {'value': upload.uploaded_by.id, 'position': 6}])

# or you could make a function that returns a class
def contact_model(column):
    # make class
    return ContactModel

# then
from somemodule import contact_model

ContactCSVModel = contact_model(column=form)

# then use as normally
ContactCSVModel.import_data(data=file, extra_fields=[
                           {'value': upload.group_id, 'position': 5},
                           {'value': upload.uploaded_by.id, 'position': 6}])

rawDescription: Django passing object to class

description: Django passing object to class


rawDescription: Map values to colors in matplotlib

description: Map values to colors in matplotlib


rawDescription: Windows path in python

description: Windows path in python


code: [[nltk.tag.str2tuple(re.sub('/NUM', '/N', w)) for w in s.split()] for s in t0]

rawDescription: operating on embedded tuples/strings, python

description: Operating on embedded tuples/strings, python


code:
phoneNumList = []
phoneNumList[:0] = "xxx-xxx-xxxx"
phoneNumList
print(*phoneNumList)
print(*phoneNumList, sep="", end="\n")

rawDescription: Inserting strings into lists in Python (v. 3.4.2)


rawDescription: How to setup string to float converters for numpy genfromtxt

description: Setup string to float converters for numpy genfromtxt


rawDescription: How do you evaluate a certain part of an array in Python?

description: Evaluate a certain part of an array in Python


code: numpy.where(ar == 'c')

rawDescription: python matrix search

description: Python matrix search


code:
import requests
requests.head('http://www.google.com')
_.headers['Location']

rawDescription: Why am I able to read a HEAD http request in python 3 urllib.request?


code:
a_map = Map('central_corridor')
a_game = Engine(a_map)

rawDescription: Learn Python the Hard Way - exercise 43 - Classes: passing one class instance to another class when instantiating


code:
## ...
## ...
## Your MWE starts up there...

ax18 = plt.subplot(gs[8:10, 4:6])
cm = plt.cm.get_cmap('RdYlBu_r')
sca = plt.scatter(x, y, s=20, c=z, cmap=cm, vmin=0, vmax=1)
plt.ylabel('$L$', fontsize=16)
plt.xlabel('$E$', fontsize=16)
# Plot colorbar.
#box = ax18.get_position()
#cbar_posit = [box.x1 * 0.93, box.y1 * 0.94, 0.04, 0.005]
#cbaxes = fig.add_axes(cbar_posit)
#cbar = plt.colorbar(cax=cbaxes, ticks=[0, 1], orientation='horizontal')
#cbar.ax.tick_params(labelsize=9)

## You keep creating and filling axes...
## ...
## ...

rawDescription: Can't fix position of colorbar in image with multiple subplots


code:
for line in f1:
    for i in range(len(KEYWORDS)):
        line = line.replace("#define " + KEYWORDS[i], "#define " + KEYWORDS[i] + " " + str(VALS[i]))
    f2.write(line)

rawDescription: Python script to replace #define values in C file


code: storage_ii = stroage_i + storage_ii

rawDescription: Python Global Variable: sharing between function class then function


code:
groups = data.groupby('Customer ID')
diff = groups['Date Accepted'].min() - groups['Date Offered'].min()
diff

rawDescription: Adding first date instances to a new column in pandas dataframe


code:
from collections import defaultdict
by_categories = defaultdict(list)
for customer in cdicts:
    for category in customer['categories']:
        by_categories[category].append(customer)

rawDescription: How to use a list item to address a dictionary key and append the respective value

description: Use a list item to address a dictionary key and append the respective value


rawDescription: How to pop up the python console?

description: Pop up the python console


code:
table
g = table.xs(2, level='c4', axis=1)
g
g.groupby(level='c2').apply(lambda x: x.iloc[0] - x.iloc[1])

rawDescription: how to perform calculations across specific rows and columns of a crosstabulation in pandas?

description: Perform calculations across specific rows and columns of a crosstabulation in pandas


code:
words = mystr.split()
two_word_sets = [" ".join(tup) for tup in zip(words[::2], words[1::2])]

rawDescription: Python - print tab delimited two-word set


code: df['Date_Time'] = pd.to_datetime(df['Date_Time'], coerce=True)

rawDescription: Unable to convert to datetime using pd.to_datetime


code:
def select_formula():
    equations = {frozenset(('a', 'vi', 'd' ,'t')): 'd = vi*t + .5*a*t^2'}
    variables = frozenset(input("Enter the variables to use: ").split())
    try:
        return equations[variables]
    except KeyError:
        return "No formula found"

rawDescription: Python: Raw Input and if statements

description: Python: Raw Input and if statements


code: listbox.insert(END, *(i, dic[i][0], dic[i][1], dic[i][2]))

rawDescription: Python Tkinter:When string with space inserted into Listbox, brackets appear


rawDescription: Python output complex line with floats colored by value


code:
def event_stream(request):
    """
    Stream worker events out to browser.
    """
    return events.SSEResponse(
        settings.EVENTS_PUBSUB_URL,
        channels=[settings.EVENTS_PUBSUB_CHANNEL],
        buffer_key=settings.EVENTS_BUFFER_KEY,
        last_event_id=request.META.get('HTTP_LAST_EVENT_ID')
    )

rawDescription: Django: Cleaning up redis connection after client disconnects from stream


code: df.fillna(axis=1, method='backfill')

rawDescription: Row-by-row fillna with respect to a specific column?


rawDescription: fast way to transpose and concat csv files in python?

description: Fast way to transpose and concat csv files in python


code:
import urllib2
req = urllib2.Request('https://api.twitch.tv/kraken/streams/test_channel')
req.add_header('Accept', 'application/vnd.twitchtv.v2+json')
resp = urllib2.urlopen(req)
content = resp.read()

rawDescription: Curl to Python Conversion

description: Curl to Python Conversion


code:
import rpy2.robjects as ro
preproc = [x[0] for x in ro.r('''
tweets = read.csv("tweets.csv", stringsAsFactors=FALSE)
library(tm)
library(SnowballC)
corpus = Corpus(VectorSource(tweets$Tweet))
corpus = tm_map(corpus, tolower)
corpus = tm_map(corpus, removePunctuation)
corpus = tm_map(corpus, removeWords, c("apple", stopwords("english")))
corpus = tm_map(corpus, stemDocument)''')]

rawDescription: Exactly replicating R text preprocessing in python


code: os.environ['TERM'] = 'linux'

rawDescription: Sending curses application's output to tty1


code:
with open("in.txt") as f:
    for line in f:
        if line.startswith(("cn:","sn:", "description:", "uid:","userpassword:")):
            print(line.rstrip())

rawDescription: Parse file and extract lines between blocks with python


rawDescription: Split data into sub cubes in numpy

description: Split data into sub cubes in numpy


code: matching = (l > float(b * 1.1) for l, b in zip(L, B))

rawDescription: to check a condition for all the items in two list in python

description: To check a condition for all the items in two list in python


rawDescription: Dot product between a matrix and a 1d-array in numpy


code: text = re.sub("\w+", " ", text)

rawDescription: Delete HTML Tags from string Python

description: Delete HTML Tags from string Python


code:
from scrapy.http import HtmlResponse
response = HtmlResponse(url="my HTML string", body='
Test text
')
response.xpath('//div[@id="test"]/text()').extract()[0].strip()

rawDescription: scrapy: convert html string to HtmlResponse object

description: Scrapy: convert html string to HtmlResponse object


code:
from collections import Sequence
try:
    string_type = basestring
except NameError:
    string_type = str

def apply_recursive(ob, func):
    if not isinstance(ob, Sequence) or isinstance(ob, string_type):
        return func(ob)
    return [apply_recursive(elem, func) for elem in ob]

rawDescription: How to create a new nested list from a function and an existing nested list in python?

description: Create a new nested list from a function and an existing nested list in python


code:
import operator
map(operator.eq, "TICK", "TOCK").count(True)

rawDescription: Comparing Strings

description: Comparing Strings


code:
class ControllableIterator(object):
    def __init__(self, sequence):
        self.pos = 0
        self.seq = sequence
    def __iter__(self): return self
    def next(self):
        try:
            val = self.seq[self.pos]
        except IndexError:
            raise StopIteration
        self.pos += 1
        return val
    __next__ = next  # Python 3

rawDescription: Can you jump to the nth iteration in a loop?

description: Jump to the nth iteration in a loop


code:
import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])

ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

rawDescription: How to set xlim and ylim for a subplot in matplotlib

description: Set xlim and ylim for a subplot in matplotlib


rawDescription: Python: how to print exponential equations in matplotlib?


code:
my_csv = np.genfromtxt('./temp.csv', delimiter=',')
time, data = my_csv.transpose()

rawDescription: Use numpy to read a two-column csv file

description: Use numpy to read a two-column csv file


code:
histogram = {}
for i in list_:
    oldfreq = histogram.get(i, 0) # get the old number of times we've seen i, or 0 if we haven't seen it yet
    histogram[i] = oldfreq+1  # add one to the old count

rawDescription: Seeing if values in a list are of equal value ~Python


code: first_names = [n.split()[0] for n in names]

rawDescription: Best way to split strings

description: Split strings


code:
from twisted.internet import reactor

from scrapy import log, signals
from scrapy.crawler import Crawler
from scrapy.settings import Settings
from scrapy.xlib.pydispatch import dispatcher

from testspiders.spiders.followall import FollowAllSpider

def stop_reactor():
    reactor.stop()

dispatcher.connect(stop_reactor, signal=signals.spider_closed)
spider = FollowAllSpider(domain='scrapinghub.com')
crawler = Crawler(Settings())
crawler.configure()
crawler.crawl(spider)
crawler.start()
log.start()
log.msg('Running reactor...')
reactor.run()  # the script will block here until the spider is closed
log.msg('Reactor stopped.')

rawDescription: Scrapy crawl from script always blocks script execution after scraping


code: [['executeBuild', '--name', 'foobar1'], ['executeBuild', '--name', 'foobar2']]

rawDescription: Multiple invocation of the same subcommand in a single command line


code:
string = "Your Paragraph String"
string = string.split()
abc_version = string[string.index('abc')+3]

rawDescription: Split a paragraph into lines

description: Split a paragraph into lines


code: content = [x[1:].strip() for x in f]

rawDescription: When reading in a txt matrix, how can i skip first column


code:
len(e.elementB)
map(len, e.elementB)

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


code:
class Palette(list):
    def __init__(self, name=None, description=None, colors=None, *args):
        super(Palette, self).__init__(args)
        self.name = name
        self.description = description
        self.extend(colors)

    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

    @name.deleter
    def name(self):
        self.name = None

    @property
    def description(self):
        return self._description

    @description.setter
    def description(self, description):
        self._description = description

    @description.deleter
    def description(self):
        self.description = None

rawDescription: How can a class that inherits from list and uses keyword arguments be made to work in both Python 2 and Python 3?


code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

from kivy.lang import Builder

kv = '''
<MyButton>:
    text_size: self.size
    valign: "middle"
    halign: "center"
'''
Builder.load_string(kv)

class MyButton(Button):
    pass

class MyWidget(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.add_widget(MyButton(text="Example text which is too long to fit in one line"))
        self.add_widget(Button(text="Normal button"))
        self.add_widget(MyButton(text="Example text which is too long to fit in one line"))

class MyApp(App):
    def build(self):
        return MyWidget()

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

rawDescription: How do I set minimum allowable width/height for widget/layout in Kivy?

description: Set minimum allowable width/height for widget/layout in Kivy


code: ulimit -c

rawDescription: How to change the path of, or disable python's core dump?

description: Change the path of, or disable python's core dump


code: [x for x in a + b if (a + b).count(x) == 1]

rawDescription: Get the items not repeated in a list

description: Get the items not repeated in a list


code:
import argparse

def parse_range(astr):
    result = set()
    for part in astr.split(','):
        x = part.split('-')
        result.update(range(int(x[0]), int(x[-1]) + 1))
    return sorted(result)

parser = argparse.ArgumentParser()
parser.add_argument('-n', type=parse_range)
args = parser.parse_args()
print(args.n)

rawDescription: Parsing command line input for numbers

description: Parsing command line input for numbers


code:
result = None

for line in data:
    if re.match("(.*)(background-color:red)(.*)", line):
        result = line
        break

if result:
    # do something with `result`
    pass

rawDescription: End of for loop options in Python?

description: End of for loop options in Python


rawDescription: is TensorSharedVariable in theano initilized twice in function?

description: Is TensorSharedVariable in theano initilized twice in function


code: map(lambda inst: setattr(inst, 'some_setting', True), list_of_instances)

rawDescription: Setting attributes on object instances in Python via map builtin


code:
from time import clock
from itertools import product

def math_range(maxlen):
    pattern = "{{:0{}b}}".format(maxlen)
    for i in range(0, 2**maxlen, 2):
        if i ^ i*2 == i*3:
            yield pattern.format(i)

def math_while(maxlen):
    pattern = "{{:0{}b}}".format(maxlen)
    maxnum = 2**maxlen - 1
    i = 0
    while True:
        if i ^ i*2 == i*3:
            yield pattern.format(i)
        if i >= maxnum:
            break
        i += 2

def itertools_generator(max_len):
    return filter(lambda i: '11' not in i, (''.join(i) + '0' for i in product('01', repeat=max_len-1)))

def itertools_list(maxlen):
    return list(filter(lambda i: '11' not in i, (''.join(i) + '0' for i in product('01', repeat=maxlen-1))))

def string_based(maxlen):
    pattern = "{{:0{}b}}".format(maxlen)
    for i in range(0, 2**maxlen, 2):
        s = pattern.format(i)
        if "11" not in s:
            yield s

def generate(pre0, pre1, cur_len, max_len):
    if (cur_len == max_len-1):
        yield "".join((pre0, pre1, "0"))
        return

    if (pre1 == '1'):
        yield from generate(pre0+pre1, "0", cur_len+1, max_len)
    else:
        yield from generate(pre0+pre1, "0", cur_len+1, max_len)
        yield from generate(pre0+pre1, "1", cur_len+1, max_len)

def string_based_smart(val):
    yield from generate("", "", 0, val)

def benchmark(val, *funcs):
    for i, func in enumerate(funcs, 1):
        start = clock()
        for g in func(val):
            g
        print("{}. {:6.2f} - {}".format(i, clock()-start, func.__name__))

benchmark(24, string_based_smart, math_range, math_while, itertools_generator, itertools_list, string_based)

rawDescription: Generate all strings of length X that end with '0' and have no adjacent '1's


code:
for button in space_buttons:
    button.configure(state="disabled")

rawDescription: disable buttons in Python and Tk

description: Disable buttons in Python and Tk


code:
random.shuffle(l)
for f in l:
    f()

rawDescription: Generate random numbers in range without repetition


code:
stack
overflow

rawDescription: Google App Engine: store uploaded file in Google Cloud Storage


code:
import hello
hello.helloworld()

rawDescription: How to write a Python module?

description: Write a Python module


rawDescription: Python: Group List by Set of Keys

description: Python: Group List by Set of Keys


code:
from operator import mul
from functools import reduce # In python 3
def nck_safe(n, k):
    if k < 0 or n < k: return 0
    return reduce(mul, range(n, n-k, -1), 1) // reduce(mul, range(1, k+1), 1)

rawDescription: Find the index of a given combination (of natural numbers) among those returned by `itertools` Python module


rawDescription: How to specify the regex string in python

description: Specify the regex string in python


code:
from itertools import chain
def concatenate(*lists):
    return chain(lists)

rawDescription: concatenate an arbitrary number of lists in a function in Python

description: Concatenate an arbitrary number of lists in a function in Python


code:
change = map(int, raw_input("What number do you want to change in the list? And what number should it be? Separate both numbers with a space ").split())
[change[1] if x == change[0] else x for x in a]

rawDescription: Manually replace elements in a list

description: Manually replace elements in a list


rawDescription: Ignore strings which do not completely match regex?


rawDescription: Using argparse with function that takes **kwargs argument


code:
birthdate_str = raw_input('Enter your birthday (yyyy-mm-dd): ')
birthdatetime = datetime.datetime.strptime(birthdate_str, '%Y-%m-%d')
birthdate = birthdatetime.date()  # convert from datetime to just date
age = datetime.date.today() - birthdate
age

rawDescription: How can I compare dates using Python?

description: Compare dates using Python


rawDescription: django return foreign key object from queryset?

description: Django return foreign key object from queryset


code:
import pandas as pd

periods = ['2012-1st-quarter','2012-2nd-quarter', '2012-3rd-quarter', '2012-4th-quarter']
url = 'https://www.capitalbikeshare.com/assets/files/trip-history-data/{}.csv'
d = {period: pd.read_csv(url.format(period)) for period in periods}

rawDescription: generate multiple pandas data frames

description: Generate multiple pandas data frames


code:
getFromDict(dataDict, ["a", "r"])
getFromDict(dataDict, ["b", "v", "y"])
setInDict(dataDict, ["b", "v", "w"], 4)
import pprint
pprint.pprint(dataDict)

rawDescription: Access python nested dictionary items via a list of keys


code:
import threading

def synchronized(method):
    """ Work with instance method only !!! """

    def new_method(self, *arg, **kws):
        with self.lock:
            return method(self, *arg, **kws)

    return new_method

class Java:
    count = 0
    lock = threading.RLock()

    @synchronized
    def incremenet(self):
        Java.count += 1

rawDescription: python lock method annotation

description: Python lock method annotation


code:
import time
import itertools

minute = 60

for next_time in itertools.count(time.time() + minute, minute):
    doSomeWork()
    sleep_time = next_time - time.time()
    if sleep_time > 0:
        time.sleep(sleep_time)

rawDescription: python periodic looping idiom?

description: Python periodic looping idiom


code:
a = A()
a.all
a.a = 'a'
a.all

rawDescription: How can I set a variable within a class to include another variable and update when the other value changes?

description: Set a variable within a class to include another variable and update when the other value changes


rawDescription: normalize column in pandas dataframe based on value in another column

description: Normalize column in pandas dataframe based on value in another column


rawDescription: Regular expressions from a list previously specified


rawDescription: Comparing values in two list and updating it into the dictionary


code:
arcpy.ImportMetadata_conversion(tempXmlExportPath, "FROM_FGDC", featureClassPath)
shutil.rmtree(tempXmlExportPath)

rawDescription: updating metadata for feature classes programatically using arcpy

description: Updating metadata for feature classes programatically using arcpy


rawDescription: Python: How do I save generator output into text file?


code:
def methodName(parameter):
    Class_Name.CONSTANT_VARIABLE = parameter
methodName = some_decorator(methodName)

rawDescription: Basic Python method definitions

description: Basic Python method definitions


code:
loaded_data = np.arange(5)
np.column_stack((loaded_data, loaded_data))

rawDescription: What is the best way to reshape and/or slice this array to create the desired pairs of items using NumPy?


code: ''.join(map(str, binary(10)))

rawDescription: Recursive function that prints the binary representation of the integer


code: np.dot(Zij, G)

rawDescription: Compute each element of matrix

description: Compute each element of matrix


rawDescription: numpy element values do not change using indexing

description: Numpy element values do not change using indexing


code:
import csv
import re

with open("largefile.txt", "r") as myfile, open(outnamename,'wb') as fw:
    writer = csv.writer(fw, delimiter='|')

    record = []
    for line in myfile:
        if not line.strip() and record:
            # empty line is the end of a record
            writer.writerow(record)
            record = []
            continue

        field, value = line.split(': ', 1)
        record.append(value.strip())

    if record:
        # handle last record
        writer.writerow(record)

rawDescription: Parsing large (9GB) file using python

description: Parsing large (9GB) file using python


rawDescription: multiplication of all numbers (between 2 numbers) python

description: Multiplication of all numbers (between 2 numbers) python


code:
import csv

fields = ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H')

with open('inputfile.csv', newline='') as infh, open('output.csv', 'w', newline='') as outfh:
    reader = csv.reader(infh)
    writer = csv.DictWriter(outfh, fields)
    writer.writeheader()
    row = {}
    for key, value in reader:
        if key in row:
            # new row found, write old
            writer.writerow(row)
            row = {}
        row[key] = value
    # write last row
    if row:
        writer.writerow(row)

rawDescription: How to restart an iterator?

description: Restart an iterator


code:
offsets = [-15, -12, -5, -1, 1, 10, 20, 32]
A = {2, 8, 12, 15, 22, ...} # a set of length ~ 1000
test_range = range(min(A)+min(offsets),max(A)+max(offsets)+1)
THRESHOLD = 3

N = set()
for value in test_range:
    count = 0
    for offset in offsets:
        if value+offset in A: count += 1
        else: continue
        if count == 3:
            N.add(value)
            break

rawDescription: Find offset sequence in an array of integers


code:
class MyClass():
  field1 = "field 1"
x = MyClass()
x.another_field = "another field!"
x.field1
x.another_field
y = MyClass()
y.field1
y.another_field

rawDescription: Does django (python) reuse object?

description: Does django (python) reuse object


code:
import json
class FirstTenDict(dict):
    def __init__(self, pairs):
        super(FirstTenDict, self).__init__(pairs[:10])

json_data = '''\
{"foo42": "bar", "foo31": "baz", "foo10": "spam", "foo44": "ham", "foo1": "eggs",
 "foo24": "vikings", "foo21": "monty", "foo88": "python", "foo11": "eric", "foo65": "idle",
 "foo13": "will", "foo31": "be", "foo76": "ignored"}
'''
json.loads(json_data)
json.loads(json_data, object_pairs_hook=FirstTenDict)
import pprint
pprint.pprint(_)

rawDescription: Load part of a json in python

description: Load part of a json in python


code:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as mgrid
import pandas as pd

fig = plt.figure(figsize=(12,5))
grid = mgrid.GridSpec(nrows=2, ncols=1, height_ratios=[2, 1])

barax = fig.add_subplot(grid[0])
tsax = fig.add_subplot(grid[1])
data = pd.DataFrame(np.random.randn(10,3), columns=list('ABC'), index=pd.DatetimeIndex(freq='1M', start='2012-01-01', periods=10))

data['A'] **= 2
data['A'].plot(ax=barax, style='o--')
barax.set_ylabel('Miles')
tsax.set_ylabel('Miles/Gallon')

barax.xaxis.tick_top()

data['B'].plot(ax=tsax)
data['C'].plot(ax=tsax)
fig.tight_layout()

rawDescription: Plot bar graph and timeseries plot on different axis using pandas


code:
for x, x_next in zip(the_list, the_list[1:]):
    ...

rawDescription: Consecutive indices of a Python list in for loop, without specifying indices


code:
L.sort(key= lambda x:x['country'].lower())
L

rawDescription: sorting list of dictionnaries in python

description: Sorting list of dictionnaries in python


rawDescription: Accesing dictionaries that are in a list


code:
tmp = x[:]  # this only makes a copy, does nothing else
y = tmp[2]

rawDescription: Why doesn't the Python 2D array index order matter when used with colon ( : )


rawDescription: Removing quotation marks and convert to floats


code:
import os
import sys
import pythoncom, pyHook
import win32api
import subprocess
import ctypes
import threading
from multiprocessing import *

class vlcThread(threading.Thread):
    def __init__(self,filepath,vlcp,fl):
        threading.Thread.__init__(self)
        self.fn,self.vlcpath,self.flag=filepath,vlcp,fl
        self.daemon=True

        self.start() # invoke the run method

    def run(self):
        vlcinstance=vlc(self.fn,self.vlcpath)
        while True:
            if(self.flag.value==1):
                vlcinstance.play_next()
                self.flag.value=0
            if(self.flag.value==-1):
                vlcinstance.play_prev()
                self.flag.value=0

def kbeventhandler(event,flag):

    if event.Key=='Home':
        flag.value =-1
        return False
    if event.Key=='End':
        flag.value =1
        return False
    return True

class vlc(object):
    def __init__(self,filepath,vlcp):
        self.fn=filepath
        self.vlcpath=vlcp
        self.process = subprocess.Popen([self.vlcpath,self.fn],close_fds=True)
    def kill(self):
        p, self.process = self.process, None
        if p is not None and p.poll() is None:
            p.kill()
            p.wait()

    def play_next(self):
        self.kill()
        f=self.get_new_file(1)
        self.process = subprocess.Popen([self.vlcpath,f],close_fds=True)
        self.fn=f
    def play_prev(self):
        self.kill()
        f=self.get_new_file(-1)
        self.process = subprocess.Popen([self.vlcpath, f],close_fds=True)
        self.fn=f

    def get_new_file(self,switch):

        dirname= os.path.dirname(self.fn)
        supplist=['.mkv','.flv','.avi','.mpg','.wmv','ogm','mp4']
        files = [os.path.join(dirname,f) for f in os.listdir(dirname) if (os.path.isfile(os.path.join(dirname,f)) and os.path.splitext(f)[-1]in supplist)]
        files.sort()
        try: currentindex=files.index(self.fn)
        except: currentindex=0
        i=0
        if switch==1:
            if currentindex<(len(files)-1):i=currentindex+1

        else:
            if currentindex>0:i=currentindex-1

        return files[i]

def main():
    vlcpath='vlc'
    flag=Value('i')
    flag.value=0
    if os.name=='nt': vlcpath='C:/Program Files (x86)/VideoLAN/VLC/vlc.exe'
    fn='H:\\Anime\\needless\\Needless_[E-D]\\[Exiled-Destiny]_Needless_Ep11v2_(04B16479).mkv'
    if len(sys.argv)>1:
        fn=sys.argv[1] #use argument if available or else use default file

    t=vlcThread(fn,vlcpath,flag)
    hm = pyHook.HookManager()
    def kbwrap(event):
        return kbeventhandler(event,flag)
    hm.KeyDown = kbwrap
    hm.HookKeyboard()
    pythoncom.PumpMessages()

if __name__ == '__main__':
    main()

rawDescription: peculiar error on ntpath.py

description: Peculiar error on ntpath.py


code:
class CountByYear(object):
    def __init__(self, word, year, frequency):
        self.word = word
        self.year = year
        self.frequency = frequency

    def __repr__(self):
        return "CountByYear(year=%s, count=%s)" % (self.year, self.frequency)

rawDescription: Putting objects into a list into a dictionary


code:
from nltk.stem import WordNetLemmatizer
from nltk import pos_tag
wnl = WordNetLemmatizer()
wnl.lemmatize('resumed')
wnl.lemmatize('resumed', pos='v')

rawDescription: Python NLTK: how to lemmatize text include verb in english?


code: [' '.join(x) for x in grouper(4, truth.split())]

rawDescription: simple regex trouble

description: Simple regex trouble


code: ['bar', 'quux', 'foo']

rawDescription: Sorted Word frequency count using python


code:
def GetModelData(form, fields):
    """
    Extract data from the bound form model instance and return a
    dictionary that is easily usable in templates with the actual
    field verbose name as the label, e.g.

    model_data{"Address line 1": "32 Memory lane",
               "Address line 2": "Brainville",
               "Phone": "0212378492"}

    This way, the template has an ordered list that can be easily
    presented in tabular form.
    """
    model_data = {}
    for field in fields:
        model_data[form[field].label] = eval("form.data.%s" % form[field].name)
    return model_data

@login_required
def clients_view(request, client_id):
    client = Client.objects.get(id=client_id)
    form = AddClientForm(client)

    fields = ("address1", "address2", "address3", "address4",
              "phone", "fax", "mobile", "email")
    model_data = GetModelData(form, fields)

    template_vars = RequestContext(request,
        {
            "client": client,
            "model_data": model_data
        }
    )
    return render_to_response("clients-view.html", template_vars)

rawDescription: Iterate over model instance field names and values in template


rawDescription: Perl regex vs. Python regex non-capture seems to work differently


rawDescription: How can I send anything other than strings through Python sock.send()

description: Send anything other than strings through Python sock.send()


code:
averaged2 = reduce(lambda l, r: l + r,
    (misc.imread(f).astype(np.float32, copy = False) for f in files))\
    / len(files)

rawDescription: Averaged array calculation using numpy in Python


rawDescription: Discuss the "sorted" function in Python

description: Discuss the "sorted" function in Python


code: df

rawDescription: Pandas expand json field across records

description: Pandas expand json field across records


code:
import ctypes
PyCell_Set = ctypes.pythonapi.PyCell_Set

# ctypes.pythonapi functions need to have argtypes and restype set manually
PyCell_Set.argtypes = (ctypes.py_object, ctypes.py_object)

# restype actually defaults to c_int here, but we might as well be explicit
PyCell_Set.restype = ctypes.c_int

PyCell_Set(cell, new_value)

rawDescription: How to create new closure cell objects?

description: Create new closure cell objects


code:
d = {
  "request": {
    "slice": [
      {
        "origin": "AMS",
        "destination": "SYD",
        "date": "2015-06-23"
      }
    ],
    "passengers": {
      "adultCount": 1,
      "infantInLapCount": 0,
      "infantInSeatCount": 0,
      "childCount": 0,
      "seniorCount": 0
    },
    "solutions": 20,
    "refundable": False  # note how this is python False, not js false!
  }
}

# then you can do:
d["request"]["slice"][0]["date"] = "2015-05-23"

# and finally convert to json:
j = json.dumps(d)

rawDescription: build dynamical JSON/LIST obj in Python

description: Build dynamical JSON/LIST obj in Python


code: my_list = tuple(a.instances["name_"+str(i)] for i in range(4))

rawDescription: Python: List to tuple without "

description: Python: List to tuple without "


code:
import difflib
difflib.get_close_matches
df2.index = df2.index.map(lambda x: difflib.get_close_matches(x, df1.index)[0])
df2
df1.join(df2)

rawDescription: is it possible to do fuzzy match merge with python pandas?

description: Is it possible to do fuzzy match merge with python pandas


code:
import time

# Why do you need a measurement class which only acts as a list anyways?
my_measurements = []

def repeat(duration, function, args=(), kwargs={}, interval=1):
    """Repeat a function call for the given duration."""
    start_time = time.time()
    while duration > time.time() - start_time:
        function(*args, **kwargs)
        time.sleep(interval)

def add_time_measurement(measurements):
    measurements.append(time.time())

repeat(5, add_time_measurement, (my_measurements,))

rawDescription: Function as argument in python

description: Function as argument in python


code:
import numpy as np
from numpy.testing import assert_array_equal
import threading
from time import time

def blockshaped(arr, nrows, ncols):
    """
    Return an array of shape (nrows, ncols, n, m) where
    n * nrows, m * ncols = arr.shape.
    This should be a view of the original array.
    """
    h, w = arr.shape
    n, m = h // nrows, w // ncols
    return arr.reshape(nrows, n, ncols, m).swapaxes(1, 2)

def do_dot(a, b, out):
    #np.dot(a, b, out)  # does not work. maybe because out is not C-contiguous?
    out[:] = np.dot(a, b)  # less efficient because the output is stored in a temporary array?

def pardot(a, b, nblocks, mblocks, dot_func=do_dot):
    """
    Return the matrix product a * b.
    The product is split into nblocks * mblocks partitions that are performed
    in parallel threads.
    """
    n_jobs = nblocks * mblocks
    print('running {} jobs in parallel'.format(n_jobs))

    out = np.empty((a.shape[0], b.shape[1]), dtype=a.dtype)

    out_blocks = blockshaped(out, nblocks, mblocks)
    a_blocks = blockshaped(a, nblocks, 1)
    b_blocks = blockshaped(b, 1, mblocks)

    threads = []
    for i in range(nblocks):
        for j in range(mblocks):
            th = threading.Thread(target=dot_func,
                                  args=(a_blocks[i, 0, :, :],
                                        b_blocks[0, j, :, :],
                                        out_blocks[i, j, :, :]))
            th.start()
            threads.append(th)

    for th in threads:
        th.join()

    return out

if __name__ == '__main__':
    a = np.ones((4, 3), dtype=int)
    b = np.arange(18, dtype=int).reshape(3, 6)
    assert_array_equal(pardot(a, b, 2, 2), np.dot(a, b))

    a = np.random.randn(1500, 1500).astype(int)

    start = time()
    pardot(a, a, 2, 4)
    time_par = time() - start
    print('pardot: {:.2f} seconds taken'.format(time_par))

    start = time()
    np.dot(a, a)
    time_dot = time() - start
    print('np.dot: {:.2f} seconds taken'.format(time_dot))

rawDescription: Multi-threaded integer matrix multiplication in NumPy/SciPy


code:
mask = ~np.isnan(x) & ~np.isnan(y)
x = x[mask]
y = y[mask]

rawDescription: Removing nan in array at position from another numpy array


code: surfaceXY = [[0]*10 for i in range(10)]

rawDescription: Iterating in a area contained in a multidimensional array in python, why it doesn't work?


code: cs = (a, b, c, d)

rawDescription: Pythonic way to calculate the mean and variance of values in Counters


rawDescription: Naturally sort a list of alpha-numeric tuples by the tuple's first element in Python


code:
def get_links(url):
    soup = BeautifulSoup(urllib.urlopen(url).read())
    links = soup('a')
    if len(links) < 3:
        # base case
        return links
    else:
        # recurse on third link
        return links + get_links(links[2]['href'])

rawDescription: My loop isn't running

description: My loop isn't running


code:
import pandas

data = pandas.read_csv("testFile.csv", index_col=False, header = None)
dataGrouped = data.groupby(1).count() #Group by domain and count the values in the other fields
busyDomains = dataGrouped[dataGrouped[0]>2]

rawDescription: Python how to choose what to print in a networkX graph


code: ['6%s@32%s' % t for t in map(None, m1, m2)]

rawDescription: List comprehension to create list of strings from two lists


code:
xc = x-c
b_out = np.einsum('ij,jk,ik->i',xc,A,xc) <= 1

rawDescription: Dot product vectorization - NumPy

description: Dot product vectorization - NumPy


rawDescription: How to populate a QListView with value and display data?

description: Populate a QListView with value and display data


code: response.xpath("p[last()]/text()[contains(., '[')]").re(r"\d+ \w+ \d{4}")

rawDescription: Xpath extract dates between certain characters AND use as dates


code:
#the following code assumes that '.' appears once

def binToFloat(b):
    parts = b.split('.')
    s,t = parts
    x = 0 if len(s) == 0 else int(s,2)
    y = 0 if len(t) == 0 else int(t,2)
    return x + y/2**len(t)

rawDescription: Converting binary to float

description: Converting binary to float


rawDescription: Get Day name from Weekday int

description: Get Day name from Weekday int


code:
def replace_values(yaml_file):
    def _get(dict, list):
        return reduce(lambda d, k: d[k], list, dict)

    def _replace(obj):
        for k, v in obj.iteritems():
            if isinstance(v, dict):
                _replace(v)
            if isinstance(v, str):
                match = re.match(r'%(.*)%', v)
                if match:
                    reference = match.group(1).split('.')
                    replace = _get(yaml_file, reference)
                    obj[k] = re.sub(r'%.*%', replace, v)

    _replace(yaml_file)
    return yaml_file

rawDescription: Python YAML parameter reference (get value from other parameter)


rawDescription: Pandas: how to match multiple pattern (OR) with np.where


code:
try:
    print(subprocess.check_output(["where",'convert'],stderr=subprocess.STDOUT,shell=True))
except CalledProcessError as e:
    print(e)
    print(e.output)

rawDescription: running imagemagick convert (console application) from python

description: Running imagemagick convert (console application) from python


code:
x = Xobject()

x.dec_me_1()
x.dec_me_2()

decorate_object(x, decorator)

x.dec_me_1()
x.dec_me_2()

rawDescription: How to decorate all methods in a class? Can I just decorate the class?

description: Decorate all methods in a class? Can I just decorate the class


code:
import csv
with open('some_list_file.txt', 'rb') as list_file:
    reader = csv.reader(some_list_file)
    with open('Testit.txt', 'W+') as output_file:
        output_file.writelines(line[0] + '\n' for line in reader)

rawDescription: Replacing multiple characters in a string


code: pivoted

rawDescription: Create new pandas timeseries dataframe from other dataframe


code:
from keyword import iskeyword

def is_valid_variable_name(name):
    return name.isidentifier() and not iskeyword(name)

rawDescription: Pythoncially check if a variable name is valid


code:
import numpy as np
from itertools import izip
import matplotlib.pyplot as plt
from collections import defaultdict

# this requires you to know a head of time how many times you have
len = 10
d = defaultdict(lambda : np.zeros(len, dtype=np.bool)) # save space!
with open('test.txt', 'r') as infile:
    infile.next() # skip the header line
    for line in infile:
        tokens = line.rstrip().split(" ")
        time = int(tokens[0]) # get the time which is the first token
        for e in tokens[1:]:  # loop over the rest
            if len(e) == 0:
                pass
            d[e][time] = True

for k in d:
    d[k] = np.cumsum(d[k])

rawDescription: Efficiently displaying a stacked bar graph


code: sorted(d, key = lambda i: strptime(i.split('@')[0], '%d-%m-%Y'), reverse=True)

rawDescription: Sort by Date Python List

description: Sort by Date Python List


code:
import yagmail
yag = yagmail.SMTP()
yag.send(contents = ["See this attachment", "/local/path/to/song.mp3"])

rawDescription: Is it safe to send email through a python script


rawDescription: Customizing rolling_apply function in Python pandas


code:
with open("log.txt") as f:
    prev = ""
    for line in f:
        if not line.startswith("!NAME:") and prev.startswith("!NAME:"):
            key = next(cn)
            sections[key] += prev
            sections[key] += line
            for line in f:
                if line.startswith("!NAME:"):
                    break
                sections[key] += line
                prev = line
        prev = line

rawDescription: Get text between two identical lines in Python


code:
factorial(5)
factorial( 5, 6, 7 )
factorial( *[5, 6, 7] )

rawDescription: Single implementation to cover both single and multiple values in Python?


code:
import wx

class PageOne(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)

        vbox_left = wx.BoxSizer(wx.VERTICAL)
        vbox_right = wx.BoxSizer(wx.VERTICAL)

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        driveList=["D:/", "E:/"]

        font = wx.Font(14, wx.SWISS, wx.NORMAL, wx.NORMAL)

        label = wx.StaticText(self, -1, "Audio Source") # Add type/name of source
        label.SetFont(font)
        label.SetSize(label.GetBestSize())
        self.combo1 = wx.ComboBox(self, style=wx.CB_DROPDOWN, choices=driveList)
        self.listbox = wx.ListBox(self, 1, size=(380, 220))
        vbox_left.Add(label, 0, wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 5)
        vbox_left.Add(self.combo1, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.LEFT | wx.RIGHT, 15)
        vbox_left.Add(self.listbox, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 15)

        label = wx.StaticText(self, -1, "Local Disk") # Add disk name
        label.SetFont(font)
        label.SetSize(label.GetBestSize())
        self.combo2 = wx.ComboBox(self, style=wx.CB_DROPDOWN, choices=driveList)
        self.listbox = wx.ListBox(self, 0, size=(380, 220))
        vbox_right.Add(label, 0, wx.BOTTOM | wx.TOP | wx.ALIGN_CENTER_HORIZONTAL, 5)
        vbox_right.Add(self.combo2, 0, wx.EXPAND | wx.ALIGN_CENTER_HORIZONTAL | wx.LEFT | wx.RIGHT, 15)
        vbox_right.Add(self.listbox, 1, wx.EXPAND | wx.LEFT | wx.RIGHT | wx.TOP, 15)

        hbox.Add(vbox_left, 0, wx.EXPAND | wx.LEFT, 20)
        hbox.Add(vbox_right, 0, wx.EXPAND | wx.RIGHT, 20)
        self.SetSizer(hbox)
        self.Layout()

########################################################################
class MyFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title='Notebooks')
        panel = wx.Panel(self)
        notebook = wx.Notebook(panel)
        page_one = PageOne(notebook)
        notebook.AddPage(page_one, 'Page 1')

        main_sizer = wx.BoxSizer(wx.VERTICAL)
        main_sizer.Add(notebook, 1, wx.EXPAND)
        panel.SetSizer(main_sizer)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MyFrame()
    app.MainLoop()

rawDescription: wxPython Notebook Pages

description: WxPython Notebook Pages


rawDescription: Create a Python Dictonary by taking joins of two dictionary


rawDescription: Python sort list of lists over multiple levels and with a custom order


rawDescription: How to check parameters for os.makedirs?

description: Check parameters for os.makedirs


code: args = filter(lambda x: not x, args)

rawDescription: Python itertools: Cartesian product with filtering of empty strings


code: map(lambda x:x.count(' '),lst)

rawDescription: Finding how many of a certain character in each element in a list


rawDescription: Editing multi-dimensional arrays in Python


rawDescription: Create a list of dictionaries which contains nested dictionaries


code: op, value = operator.add, 0

rawDescription: How to go back to a specific line

description: Go back to a specific line


code: mock_post.assert_has_calls([mock.call(first_url, first_params), mock.call(second_url, second_params)])

rawDescription: Changing the second result of a function call with mock


code:
import sys
sys.version
sys.version_info

rawDescription: accessing ArgumentParser variable with environment variable

description: Accessing ArgumentParser variable with environment variable


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

first = -3
size  = (3-first)/100
xv,yv = np.meshgrid(np.linspace(-3,3,100),np.linspace(-3,3,100))
p = path.Path([(0,0), (0, 1), (1, 1), (1, 0)])  # square with legs length 1 and bottom left corner at the origin
flags = p.contains_points(np.hstack((xv.flatten()[:,np.newaxis],yv.flatten()[:,np.newaxis])))
grid = np.zeros((101,101),dtype='bool')
grid[((xv.flatten()-first)/size).astype('int'),((yv.flatten()-first)/size).astype('int')] = flags

xi,yi = np.random.randint(-300,300,100)/100,np.random.randint(-300,300,100)/100
vflag = grid[((xi-first)/size).astype('int'),((yi-first)/size).astype('int')]
plt.imshow(grid.T,origin='lower',interpolation='nearest',cmap='binary')
plt.scatter(((xi-first)/size).astype('int'),((yi-first)/size).astype('int'),c=vflag,cmap='Greens',s=90)
plt.show()

rawDescription: What's the fastest way of checking if a point is inside a polygon in python


code:
indexed_changes = enumerate(input)
indexed_and_sorted_by_length = sorted(indexed_changes, key=lambda change: len(change[1][1]), reverse=True)
largest_3_indexed_changes = indexed_and_sorted_by_length[:3]
largest_3_indexed_sorted_by_index = sorted(largest_3_indexed_changes)
largest_3_changes_in_original_order = [indexed_change[1] for indexed_change in largest_3_indexed_sorted_by_index]

rawDescription: Parsing diff results (list of tuples) with python


code:
class Worker(object):
    def __init__(iserver,login,password,proxyUser,proxyPass,proxyServer,service):
        self.iserver = iserver
        self.login = login
        self.password = password
        self.proxyUser = proxyUser
        self.proxyPass = proxyPass
        self.proxyServer = proxyServer
        self.service = service

    def version_check(self): ...

    def version_get(self): ...

    def version_send(self): ...

rawDescription: Best approach to pass and handle arguments to function


rawDescription: Get a list (object in new line) and print a list in one line


code:
files = ["image-000001.png", "image-000002.png", "001_sequence.png",
         "002_sequence.png", "not an image 1.doc", "not an image 2.doc",
         "other stuff.txt", "singular image.jpg"]

import re
image_files = [f for f in files if re.match(r".*\d+.*\.(jpg|png)", f)]

rawDescription: How to identify files that have increasing numbers and a similar form of filename?

description: Identify files that have increasing numbers and a similar form of filename


code:
newbuf = libc.strdup(mybuf)
s = newbuf.value
libc.free(newbuf)
# now use s, which is just a Python bytes object, so it's GC-able

rawDescription: Memory leaks in Python when using an external C DLL


rawDescription: Access Pandas Data Frame row with index value


code: {'Sport': u'Ping Pong', 'name': u'Michael Jordan', 'team': u'Real Madrid'}

rawDescription: BeautifulSoup: Get the class text

description: BeautifulSoup: Get the class text


code:
extra_patterns = patterns('',
    url(r'blog/(?P<blog_id>[0-9]+)/view/(?P<content_id>[0-9]+)/$', 'blog.views.view'),
    url(r'blog/(?P<blog_id>[0-9]+)/$', 'blog.views.main'),
    url(r'blog/(?P<blog_id>[0-9]+)/(?P<page>[0-9]+)/$', 'blog.views.main'),                      #pagination for main

    # Categories
    url(r'category/(?P<category_id>[0-9]+)/$', 'category.views.category'),
    url(r'category/(?P<blog_id>[0-9]+)/category/(?P<category_id>[0-9]+)/(?P<page>[0-9]+)/$', 'category.views.category'),   #pagination for main

    # Content
    url(r'^content/(?P<blog_id>[0-9]+)/edit/$', 'content.views.edit'),
    url(r'^content/(?P<blog_id>[0-9]+)/edit/(?P<content_id>[0-9]+)/$', 'content.views.edit'),
)

urlpatterns = patterns('',
    # Basic product functions
    url(r'^create/$', 'product.views.create'),
    url(r'^save/$', 'product.views.save'),
    url(r'^save/(?P<product>[a-z0-9\-]+)/$', 'product.views.save'),
    url(r'^edit/(?P<product>[a-z0-9\-]+)/$', 'product.views.edit'),
    url(r'^publish/(?P<product>[a-z0-9\-]+)/$', 'product.views.publish'),
    url(r'^upload_image/(?P<product>[a-z0-9\-]+)/$', 'product.views.upload_image'),

    # Blog
    url(r'^(?P<product>[a-z0-9\-]+)/', include(extra_patterns)),
)

rawDescription: Grouping URL patterns that are similar

description: Grouping URL patterns that are similar


code:
index = search.Index(name='item_autocomplete')
for item in items:  # item = ndb.model
    doc_id = item.key.urlsafe()
    name = ','.join(tokenize_autocomplete(item.name))
    document = search.Document(
        doc_id=doc_id,
        fields=[search.TextField(name='name', value=name)])
    index.put(document)

rawDescription: Partial matching GAE search API

description: Partial matching GAE search API


code:
r = []
for a in A:
  for b in B:
    r.append(v)

rawDescription: Different results from yield vs return

description: Different results from yield vs return


code:
def simplify(tree, threshold):
    # simplify tree bottom-up
    for key, child in tree.items():
        if isinstance(child, dict):
            tree[key] = simplify(child, threshold)
    # all child-nodes are leafs and smaller than threshold -> return max
    if all(isinstance(child, str) and float(child) <= threshold
           for child in tree.values()):
        return max(tree.values(), key=float)
    # else return tree itself
    return tree

rawDescription: Python Dictionary - Consolidating Leaf Nodes below a threshold


rawDescription: Getting bandwidth used by SciPy's gaussian_kde function


code:
import dateutil.parser as p
d = {}
for snapshot in snapshots:
    snapshot["created_at"] = p.parse(snapshot["created_at"])
    try:
      d[snapshot["volume_id"]].append(snapshot)
    except KeyError:
      d[snapshot["volume_id"]]=[snapshot]

rawDescription: keep n retention and delete old one

description: Keep n retention and delete old one


rawDescription: Write to a masked array in numpy

description: Write to a masked array in numpy


code:
def extractYear(s):
    if len(s) >= 6:
        year = s[-6:]
        p = re.compile('\(\d{4,4}\)')
        if p.match(year):
            return s[:-6], s[-6:]
    return s, None

rawDescription: Splitting string with optional year

description: Splitting string with optional year


code:
from twisted.internet.iocpreactor import tcp, udp
#
#
#
def connectTCP(self, host, port, factory, timeout=30, bindAddress=None):
    """
    @see: twisted.internet.interfaces.IReactorTCP.connectTCP
    """
    c = tcp.Connector(host, port, factory, timeout, bindAddress, self)
    c.connect()
    return c

rawDescription: How do Twisted python Factory and Protocol interfaces work?


code:
from collections import defaultdict

grouped_by_md5 = defaultdict(list)
db = sqlite3.connect('imges.db')
with db:
    cur = db.cursor()
    cur.execute("SELECT row1, row3 FROM IMAGES")

    for row1, row3 in cur:
        grouped_by_md5[row3].append(row1)

rawDescription: How to find duplicates in tuples with Python, using sqlite3?

description: Find duplicates in tuples with Python, using sqlite3


rawDescription: I cannot understand function comparisons in Python


rawDescription: High Memory Usage Using Python Multiprocessing


code:
A
B
B[np.argmin(cdist(A,B),1)]

rawDescription: How to find the closest corresponding vectors between two coordinate matrices?

description: Find the closest corresponding vectors between two coordinate matrices


code:
import array

def read_complex_array2(filename, M, N):
    result = []
    with open(filename, "rb" ) as input:
        for col in xrange(M):
            reals = array.array('h')
            reals.fromfile(input, N)
            # reals.byteswap()  # if necessary
            imags = array.array('h')
            imags.fromfile(input, N)
            # imags.byteswap()  # if necessary
            cmplx = [complex(r,i) for r,i in zip(reals, imags)]
            result.append(cmplx)
    return result

rawDescription: Reading complex binary file in python

description: Reading complex binary file in python


code:
def scramble(r_letters, s_letters):
    if s_letters:
        words.add(s_letters)
    for i in range(len(r_letters)):
        scramble(r_letters[:i] + r_letters[i+1:], s_letters + r_letters[i])

rawDescription: program takes long time to calculate........recursion(python)

description: Program takes long time to calculate........recursion(python)


code: [np.max(np.where(z[i]<big))+1 for i in range(nmax+1)]

rawDescription: Is there a more pythonic way to write

description: Is there a more pythonic way to write


code:
class Search:
    def run(self): # need the self parameter

        data = requests.get("http://boards.4chan.org/g/catalog").text
        match = re.match(".*var catalog = (?P<catalog>\{.*\});.*", data)

        if not match:
            print("Couldn't scrape catalog")
            exit(1)
        catalog = json.loads(match.group('catalog'))
        running = True
        while running:
            try:
                filtertext = ("tox")
                for number, thread in catalog['threads'].items():
                    sub, teaser = thread['sub'], thread['teaser']
                    if filtertext in sub.lower() or filtertext in teaser.lower():
                        return teaser  # return the value of the variable teaser defined above
                running = False
            except KeyboardInterrupt:
                running = False

s = Search() # create instance
print (s.run()) # call run method

rawDescription: Search has no attribute teaser

description: Search has no attribute teaser


code:
from collection import defaultdict
list1 = open('file1.txt', 'r').readlines()
list2 = open('file2.txt', 'r').readlines()
d = defaultdict(list)
for item in list1 + list2:
    k,v = item.split(':')
    d[k].append(v)
with open('file3.txt', 'a') as output:
    output.writelines(['{}:{}\n'.format(k,d[k][0]) for k in d if len(d[k]) == 1])

rawDescription: Compare lines of 2 input files, and output third file with differences


code: assert all(w in allwords for w in (wordsfrom('thistles', allwords_by_count)))

rawDescription: Python- Possible English one-word anagrams given input letters


code:
from collections import defaultdict
orig = ['a=1', 'b=2', 'c=3', 'd=4', 'd=5', 'd=6', 'e=7']
d = defaultdict(list)
for item in orig:
    k,v = item.split('=',1)
    d[k].append(v)

new = ['{0}={1}'.format(k,','.join(v)) for k,v in d.items()]
print(new)  #['a=1', 'c=3', 'b=2', 'e=7', 'd=4,5,6']

rawDescription: Collect parts of duplicated elements in a list and merge them in just one element


code:
import datetime as dt
data=[
    {"time": "2010-11-11 03:23:59"},
    {"time": "2010-11-12 10:16:15"},
    {"time": "2010-11-12 14:51:13"},
    ]

def freq(data):
    dates=[dt.datetime.strptime(dct['time'],'%Y-%m-%d %H:%M:%S') for dct in data]
    date_min=min(dates)
    date_max=max(dates)
    span=date_max-date_min
    l=len(dates)
    if span<dt.timedelta(hours=1):
        duration='an hour'
    elif span<dt.timedelta(hours=24):
        duration='a day'
    elif span<dt.timedelta(days=7):
        duration='a week'
    else:
        duration='all'
    return l,duration

num,duration=freq(data)
print('{n} times in {d}'.format(n=num,d=duration))

rawDescription: Get the average number of occurrences in a list of dicts


code: (depth,position,match, max_depth) = recurse(root_node,target_id)

rawDescription: How to find position of nodes in binary tree?

description: Find position of nodes in binary tree


code: peakIndex = numpy.argmax(myArray)

rawDescription: Getting index of numpy.ndarray

description: Getting index of numpy.ndarray


code:
import turtle
def draw_sierpinski(length,depth):
    if depth==0:
        for i in range(0,3):
            t.fd(length)
            t.left(120)
    else:
        draw_sierpinski(length/2,depth-1)
        t.fd(length/2)
        draw_sierpinski(length/2,depth-1)
        t.bk(length/2)
        t.left(60)
        t.fd(length/2)
        t.right(60)
        draw_sierpinski(length/2,depth-1)
        t.left(60)
        t.bk(length/2)
        t.right(60)

window = turtle.Screen()
t = turtle.Turtle()
draw_sierpinski(100,2)
window.exitonclick()

rawDescription: Sierpinski triangle recursion with python using turtle


code:
def expand(s1):
    i = 0
    s2 = bytearray()
    while i < len(s1):
        c = s1[i]
        i += 1
        if (i + 1) < len(s1) and s1[i] == ord(b'-') and s1[i + 1] >= c:
            i += 1
            while c < s1[i]:
                s2.append(c)
                c += 1
        else:
           s2.append(c)
    return bytes(s2)

rawDescription: converting a C function into Python3 form?

description: Converting a C function into Python3 form


code: learning_set = data_list_1[:int(round(len(data_list_1)*border))] + data_list_2[:int(round(len(data_list_2)*border))]

rawDescription: Python "input data"

description: Python "input data"


code:
def reverse(word):
    return word[::-1]

rawDescription: Reverse String Function in Python (Primitive Steps)


code:
words = ['a','la','los','shrimp']
sentence = 'They eat shrimp in Mexico, and more these days'
[word for word in words if word in sentence]
any(word in sentence for word in words)

rawDescription: Best performance method for evaluating presence of substrings within strings in python?


code:
{'some_string0': {'some_string3': -1,
                  'some_string4': -1,
                  'some_string5': {'some_string9': {'some_string11': -1}}},
 'some_string1': {'some_string6': -1, 'some_string7': {'some_string10': -1}},
 'some_string2': {'some_string8': -1}}

rawDescription: convert array to json object

description: Convert array to json object


code:
import importlib
process = importlib.import_module('gateway_interface.'+gateway_file).process

rawDescription: Create an import statement using variable "interpolation"


code:
with lock:
    next_id += 1
    if next_id == size: next_id = 0
    if arr[next_id] is None:
        arr[next_id] = job
        return next_id

rawDescription: Implementing a Timer in Python

description: Implementing a Timer in Python


rawDescription: Conditionally combine columns in pandas data frame


code:
from swampy.Lumpy import Lumpy
lump = Lumpy()
x = ["one","two",3,5.0]
y = x
x[3] = 4
lump.object_diagram()

rawDescription: Equal strings auto updating (List object reference)


code:
s = """\
                     ###                    \
                     #####                  \
                     #######                \
                    #######                 \
                     ######                 \
                     ###### ##              \
                     ####  #####            \
                       ## ######        ####\
                    #    ######       ####  \
                  ###  ##########    #####  \
                #######  ####  ##   ######  \
                ######### ##   #      ##### \
      #           ####   ###          ###   \
     #####        ####    #     ##     ##   \
     #####                    ######    #   \
    ######                   ########       \
     ####                     ########      \
                              #######       \
                              #######       \
"""
representatives = {i: i for i, c in enumerate(s) if c == '#'}
nrows, ncols = 19, 44

def neighbours(idx):
    i, j = divmod(idx, ncols)
    if i > 0: yield idx - ncols
    if i < nrows - 1: yield idx + ncols
    if j > 0: yield idx - 1
    if j < ncols - 1: yield idx + 1

def representative(a):
    while representatives[a] != a: a = representatives[a]
    return a

def join(a, b):
    repr_a, repr_b = representative(a), representative(b)
    if repr_a != repr_b: representatives[repr_a] = repr_b

for idx in representatives:
    for n in neighbours(idx):
        if s[n] == '#': join(idx, n)

cluster_count = len(set(map(representative, representatives)))

rawDescription: Find clusters of bacteria

description: Find clusters of bacteria


rawDescription: How to a query a set of objects and return a set of object specific attribute in SQLachemy/Elixir?

description: A query a set of objects and return a set of object specific attribute in SQLachemy/Elixir


code:
import argparse

parser = argparse.ArgumentParser()

def int_range(start, end):
    def range_type(arg):
        try:
            val = int(arg)
        except ValueError:
            raise argparse.ArgumentTypeError("Invalid value for range (%d, %d): %r" % (start, end, arg))
        if val not in range(start, end):
            raise argparse.ArgumentTypeError("%d not in range (%d, %d)" % (val, start, end))
        return val
    return range_type

parser.add_argument('--foo', type=int_range(10, 100))

args = parser.parse_args()

print("Foo is %d" % args.foo)

rawDescription: Equivalent of Julia's ArgParse range_teser in Python's argparse?


rawDescription: Add values for different years

description: Add values for different years


rawDescription: Python: Drunkard's walk

description: Python: Drunkard's walk


code:
router = DefaultRouter()
router.register(r'users', PeopleViewSet)
router.register(r'consents', ConsentViewSet)
consents_router = NestedSimpleRouter(router, r'consents', lookup='consent')
consents_router.register(r'chat', NestedChatViewSet)

rawDescription: Unable to extend Django REST Framework viewset to handle multi-level API


rawDescription: How to render contents of a tag in unicode in BeautifulSoup?

description: Render contents of a tag in unicode in BeautifulSoup


code: [x for x in list1 if x not in set(list2)]

rawDescription: python function slowing down for no apparent reason

description: Python function slowing down for no apparent reason


code:
def line_to_tuple(line):
    data = line.split()
    return (data[0],int(data[1]),int(data[2]))

rawDescription: Sorting data by multiple columns

description: Sorting data by multiple columns


code:
big
list

rawDescription: Avoiding nesting two for loops

description: Avoiding nesting two for loops


code:
relabeled = list((n % 3, row) for n, row in enumerate(AA[1:]))
todrop = set(n for n, row in relabeled if '0' in row)  # Will save {1} for Y
filtered = list(row for n, row in relabeled if n not in todrop)

rawDescription: How to delete every nth row of an if one contains a zero?

description: Delete every nth row of an if one contains a zero


code:
a = ['this;mango', 'is:red', 'test;cat']
b = ['man', 'is', 'can']

import re
[elem for elem in b if any(re.search(r'\b' + re.escape(elem) + r'\b', test) for test in a)]

rawDescription: string comparison on 2 lists

description: String comparison on 2 lists


code:
def extract_groups(s):
    separator = re.compile("(-?\|[\w ]+\|)")
    components = separator.split(s)
    groups = []
    for component in components:
        component = component.strip()
        if len(component) == 0:
            continue
        elif component[0] in ['-', '|']:
            groups.append(component.replace('|', ''))
        else:
            groups.extend(component.split(' '))

    return groups

rawDescription: Splitting a python string

description: Splitting a python string


some: meta info

rawDescription: Combine DataFrame as JSON with additional data


code:
prod = Product.objects.get(uuid=product)
#order.products.add(prod)
q = product_quantity
order = order # order record must be created before

OrderProduct.objects.create(order=order, product=prod, quantity=q)

rawDescription: Django, m2m with same model

description: Django, m2m with same model


code:
async def main():
    asyncio.ensure_future(async_foo())  # fire and forget

    print('Do some actions 1')
    await asyncio.sleep(0.1)
    print('Do some actions 2')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

    # Let's also finish all running tasks:
    pending = asyncio.Task.all_tasks()
    loop.run_until_complete(asyncio.gather(*pending))

rawDescription: "Fire and forget" python async/await

description: "Fire and forget" python async/await


code:
import csv

with open('my_data.csv') as data_file,\
     open('values.csv') as value_file, \
     open('my_new_data.csv', 'wb') as out_file:

    data_reader = csv.reader(data_file, delimiter=' ', skipinitialspace=True)
    value_reader = csv.reader(value_file, delimiter=',')
    writer = csv.writer(out_file, delimiter=' ')
    while True:
        try:
            row = next(data_reader)
            row[1:4] = next(value_reader)
            writer.writerows([row, next(data_reader), next(data_reader)])
        except StopIteration:
            break

rawDescription: change multiple lines in file python using regex

description: Change multiple lines in file python using regex


code:
import types, functools, sys

class VerboseMetaclass(type):

    def __new__(cls, name, bases, classdict):
        for key in sorted(filter(
            lambda name: isinstance(name, str), classdict)):
            classdict[key] = cls.wrap('{}.{}'.format(name, key), classdict[key])
        return super().__new__(cls, name, bases, classdict)

    @classmethod
    def wrap(cls, name, value):
        if isinstance(value, types.FunctionType):
            return cls.wrap_function(name, value)
        if isinstance(value, classmethod):
            return classmethod(cls.wrap_function(name, value.__func__))
        if isinstance(value, staticmethod):
            return staticmethod(cls.wrap_function(name, value.__func__))
        try:
            return VerboseData(name, value)
        except NameError:
            return value

    def wrap_function(name, func):
        @functools.wraps(func)
        def verbose_function(*args, **kwargs):
            args_str = tuple((object.__repr__(item)
                              if isinstance(item, VerboseData)
                              else repr(item)) for item in args)
            kwargs_str = tuple('{!s}={!r}'.format(*pair)
                               for pair in sorted(kwargs.items()))
            signature = '{}({})'.format(name, ', '.join(args_str + kwargs_str))
            print('[ -> ] {}\n'.format(signature))
            try:
                value = func(*args, **kwargs)
                print('[ <- ] {!s} [return {!r}]\n'.format(signature, value))
                return value
            except:
                value = sys.exc_info()[1]
                print('[ <- ] {!s} [raise {!r}]\n'.format(signature, value))
                raise
        return verbose_function

class VerboseData(metaclass=VerboseMetaclass):

    def __init__(self, name, value):
        vars(self).update(locals())

    def __repr__(self):
        return repr(self.value)

    def __get__(self, instance, owner):
        value = self.value
        if isinstance(value, (property, VerboseData)):
            value = value.__get__(instance, owner)
        print('[ get ] {!s} = {!r}\n'.format(self.name, value))
        return value

    def __set__(self, instance, value):
        print('[ set ] {!s} = {!r}\n'.format(self.name, value))
        if isinstance(self.value, (property, VerboseData)):
            self.value.__set__(instance, value)
        else:
            self.value = value

    def __delete__(self, instance):
        print('[ XX ] {}\n'.format(self.name))
        if isinstance(self.value, (property, VerboseData)):
            self.value.__delete__(instance)
        else:
            del self.value

    def __iter__(self):
        return iter(self.value)

class Metaclass(VerboseMetaclass, metaclass=VerboseMetaclass):

    @classmethod
    def __prepare__(metacls, name, bases):
        return super().__prepare__(name, bases)

    def __new__(cls, name, bases, classdict):
        for key, value in {'__new__': cls.new, '__init__': cls.init}.items():
            if key in classdict:
                classdict[key.encode()] = classdict[key]
                classdict[key] = value
        return super().__new__(cls, name, bases, classdict)

    def __init__(self, name, bases, classdict):
        return super().__init__(name, bases, classdict)

    def __call__(self, *args, **kwargs):
        return super().__call__(*args, **kwargs)

    def new(cls, *args, **kwargs):
        for base in cls.__mro__:
            try:
                return vars(base)[b'__new__'](cls, *args, **kwargs)
            except KeyError:
                pass
        return object.__new__(cls, *args, **kwargs)

    def init(self, *args, **kwargs):
        for base in self.__class__.__mro__:
            try:
                return vars(base)[b'__init__'](self, *args, **kwargs)
            except KeyError:
                pass
        return object.__init__(self)

if __name__ == '__main__':
    class Test(metaclass=Metaclass):

        def __new__(cls):
            return super().__new__(cls)

        def __init__(self):
            return super().__init__()

        def run(self):
            pass

    Test().run()

rawDescription: What causes a method wrapped via a metaclass to forget self when called?


rawDescription: How to add/remove said a curve to/from a plot in Python with Matplotlib

description: Add/remove said a curve to/from a plot in Python with Matplotlib


code: points = [map(int, x.split(',')) for x in s]

rawDescription: better way to convert list element into a list like this one

description: Better way to convert list element into a list like this one


code:
df1 = pd.DataFrame({'A' : uniques.take(np.random.randint(0,len(uniques)/2+5,size=1000000))})
df1.head()
df1.A.nunique()
df2 = pd.DataFrame({'A' : uniques.take(np.random.randint(0,len(uniques),size=1000000))})
df2.head()
df2.A.nunique()

rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
import pandas as pd

def booleator(col):
    if str(col).lower() in ['true', 'yes']:
        return True
    #elif str(col).lower() == "false":
    #    return False
    else:
        return False

df = pd.read_csv('data.csv', sep='\s*,\s*', index_col=0,
                 converters={'roughness': booleator, 'unstab': booleator},
                 engine='python')
print(df)
print(df.dtypes)

rawDescription: How to completely ignore whitespaces in csv with Pandas

description: Completely ignore whitespaces in csv with Pandas


code:
def test(t):
    return t

class ClassTest(object):
    def test_def(self):
        test_msg = test('Hi')
        print(test_msg)

# Creates new instance.
my_new_instance = ClassTest()
# Calls its attribute.
my_new_instance.test_def()

rawDescription: Call Outside Function In Python

description: Call Outside Function In Python


code:
new=ET.SubElement(item[1],'Data')
new.text='FOUR'
new=ET.SubElement(item[1],'Data')
new.text='FIVE'

rawDescription: python elementtree xml append

description: Python elementtree xml append


rawDescription: get specific content from file python

description: Get specific content from file python


code:
def undoublequotes(fobject):
    for line in fobject:
        yield line.replace('""', '"')

rawDescription: csv import with pythons QUOTE_NONNUMERIC not working as expected

description: Csv import with pythons QUOTE_NONNUMERIC not working as expected


code:
class AutoLogout:
    def process_request(self, request):
        if not request.user.is_authenticated() :
            return HttpResponseRedirect(reverse('app_name:url_name'))

        try:
            if datetime.now() - request.session['last_touch'] > timedelta( 0, settings.AUTO_LOGOUT_DELAY * 60, 0):
                auth.logout(request)
                del request.session['last_touch']
                return HttpResponseRedirect(reverse('app_name:url_name'))
        except KeyError:
            pass

        request.session['last_touch'] = datetime.now()

rawDescription: middleware is not work expected

description: Middleware is not work expected


code:
class my_bar(foo.bar, NewFuncMixin): pass
class my_spam(foo.spam, NewFuncMixin): pass
class my_eggs(foo.eggs, NewFuncMixin): pass

rawDescription: Extending a class hierarchy in Python

description: Extending a class hierarchy in Python


code:
with open(fname, 'r') as f:
  words = re.split('(["\'@&,;:\(\)\s+\*\?\.]|\w+)', f.read())

#because each list element is separated from the next by an empty string:
while '' in words:
    words.remove('')
print (words)

rawDescription: Parse all whitespace and grammar

description: Parse all whitespace and grammar


rawDescription: f2py -- prevent array reordering

description: F2py -- prevent array reordering


code:
for row in range(sh.nrows):
    new_row = [int(x) for x in sh.row_values(row)]
    writetab.writerow(new_row)

rawDescription: Convert Float to Integer During xcel to Tab Delimited File Conversion


code: new_items = [x if x % 2 else None for x in items]

rawDescription: Replace values in list using Python

description: Replace values in list using Python


code:
import example
x = example.get_value("string")
x
type(x)
x = example.get_value("int")
x
type(x)
x = example.get_value("")
x
type(x)

rawDescription: Return int or string from C++ function exposed to Python


code:
import ast
dumb_parameters = ["1,3,2", "4,5,6"]
parameters = [ast.literal_eval(s) for s in dumb_parameters]
parameters
random.triangular(*parameters[0])

rawDescription: Entering Parameters in Python

description: Entering Parameters in Python


code: '0 MT VERNON ST NW'

rawDescription: Fastest Way To Round Number Inside List of Strings Python


code: points = list(map(int, input().split()))

rawDescription: Accepting an unknown number of variables using input()


code:
from scipy.spatial.distance import cdist
count = (cdist(listScore,np.atleast_2d([2,0]))==0).sum()

rawDescription: Equivalent of count list function in numpy array


rawDescription: Config file for Python with repeated sections/objects


code:
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        up = UserProfile.objects.create(user=instance)
        up.save()
        tasks.send_welcome_email(up.user.id, template=template)

rawDescription: how to use django-background-tasks

description: Use django-background-tasks


rawDescription: Reading a CSV-file with uncomplete headers


rawDescription: reindex (remapping) column's value

description: Reindex (remapping) column's value


code:
a = xrange(10)
b= list(make_b(a,something))

rawDescription: how to rewrite this loop in a more efficient way in python

description: Rewrite this loop in a more efficient way in python


code:
dims = np.maximum(A.max(0),D.max(0))+1
mask = np.ravel_multi_index(D.T,dims)[:,None] == np.ravel_multi_index(A.T,dims)

rawDescription: Numpy Vectorization While Indexing Two Arrays


code: command < infilename > outfilename

rawDescription: How to replace command line argument of filename with python string of the equivalent file content

description: Replace command line argument of filename with python string of the equivalent file content


code:
import collections

def list_to_bigrams(somelist):
    it = iter(somelist)
    old = next(it, None)
    for new in it:
        yield old, new
        old = new

def find_top_bigrams(n, *manylists):
    c = collections.Counter()
    for somelist in manylists:
        c.update(list_to_bigrams(somelist))
    return c.most_common(n)

rawDescription: Bigram function using python

description: Bigram function using python


code: [[n, ws] for n, ws in data if all(w not in neg_words for w in ws.split())]

rawDescription: Removing sublist from nested lists based on element values


rawDescription: How to initialize NumPy array with different default value for each column?

description: Initialize NumPy array with different default value for each column


rawDescription: Finding Interfaces

description: Finding Interfaces


code: self.l_user, = self.ax.plot_date([],self.user, label='Total %')

rawDescription: matplotlib axes formatting

description: Matplotlib axes formatting


code:
from operator import itemgetter
map(itemgetter(0), groupby(L))

rawDescription: Removing elements that have consecutive dupes


code:
fullfilename = os.path.join(myPath, filename)
urllib.urlretrieve(url, fullfilename)

rawDescription: Saving files downloaded from Urlretrieve to another folder other


code: os.environ['SETTINGS_MODE'] = 'prod'

rawDescription: Using SQLAlchemy on App Engine development server


rawDescription: How to Force Django's urls.py regex to restrict to ASCII digits only?


rawDescription: Problems on how to transpose single column data in python


rawDescription: Why an iterative algorithm for finding epsilon in python takes virtually roughly 0 seconds?


code:
b = np.append(a, [ False ])
d = np.diff(np.asarray(b, dtype=int))
...

rawDescription: How can I tell whether a numpy boolean array contains only a single block of `True`s?

description: Tell whether a numpy boolean array contains only a single block of `True`s


code:
def edit_question(request):
    AnswerFormset = forms.models.inlineformset_factory(
         Question, Answer, formset=AnswerFormSet, extra=4, max_num=4)
    if request.method == 'POST':
        question = Question()
        question_form = QuestionForm(request.POST, instance=question)
        answer_formset = AnswerFormset(request.POST, instance=question)
        # Check these separately to avoid short-circuiting
        question_valid = question_form.is_valid()
        answer_valid = answer_formset.is_valid()
        if question_valid and answer_valid:
            question_form.save()
            # No need to add new question as it was already set as the instance above
            answer_formset.save()
        # etc

rawDescription: django multiple ModelForms with the same model and ForeignKeys

description: Django multiple ModelForms with the same model and ForeignKeys


rawDescription: numpy vstack vs. column_stack

description: Numpy vstack vs. column_stack


code:
mymodel = forms.ModelChoiceField(
                required=True,
                queryset=ships.models.Authority.objects.all(),
          )

rawDescription: django-autocomplete-light simple usage

description: Django-autocomplete-light simple usage


code:
default_value=1
try:
   switch[49]()
except KeyError:
   switch[default_value]()

rawDescription: Is this a "pythonic" method of executing functions as a python switch statement for tuple values?


code:
s = cast(v.vendorName, c_char_p).value.decode("ascii")
s
type(s)
s.lower()

rawDescription: Print a C string in Python

description: Print a C string in Python


rawDescription: How can trailing spaces be removed from Python CSV import?


code: gobject.timeout_add(500, self.update)

rawDescription: How to display continuous data in a py-gtk window?

description: Display continuous data in a py-gtk window


code:
d3.values
dict(d3.values)

rawDescription: Pandas: Most efficient way to make dictionary of dictionaries from DataFrame columns


code: indices = np.unique(a[:,0])

rawDescription: Show all values in an array for a particular number in one column


code: inner_function = lambda x: x * (x + 1) / 2

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


rawDescription: updating a numpy array efficiently when the conditions are two

description: Updating a numpy array efficiently when the conditions are two


code:
from application import app
app.run(debug=True, host='0.0.0.0')

rawDescription: Error while a Flask project turning into a package


code:
df =pd.DataFrame( range(72), index = pd.date_range('1/1/2011', periods=72, freq='D'))

df.resample('MS', how='mean')

rawDescription: Convert daily pandas stock data to monthly data using first trade day of the month


code: a.reshape((-1, 3)).max(axis=1)

rawDescription: pythonic way for partwise max in a numpy array

description: Pythonic way for partwise max in a numpy array


code: pprint([[[i+b[k],j+b[k]] for (i,j) in a[k]] for k in range(len(a))])

rawDescription: Adding value to range of values in a list?


rawDescription: Python: sorting multilevel dictionary by part of key


rawDescription: compress a string in python 3?

description: Compress a string in python 3


code:
def get_text(el): return el.text
def get_href(el): return el['href']

# map tag names to functions (what to retrieve from the tag)
what_todo = {
    'title': get_text,
    'link': get_href,
}
for el in soup.select('head *'): # To retrieve all children inside `head`
    f = what_todo.get(el.name)
    if not f: # skip non-title, non-link tags.
        continue
    print('name={} value={}'.format(el.name, f(el)))

rawDescription: Python HTML parse, gettting tag name with its value


code:
clean = df[idx == False]
clean

rawDescription: Pandas Dataframe drop items where index condition is true


rawDescription: Numpy sum of operator results without allocating an unnecessary array


code:
if 'VGA' in line:
    return "VGA " + line.split('VGA')[1]

rawDescription: Command output parsing in Python2.7

description: Command output parsing in Python2.7


code: im.thumbnail(maxsize, Image.ANTIALIAS)

rawDescription: how to fit image to label in Python

description: Fit image to label in Python


rawDescription: Understanding a custom encryption method in python


code:
def generate_data_files(prefix, tree, file_filter=None):
    """
    Walk the filesystem starting at "prefix" + "tree", producing a list of files
    suitable for the data_files option to setup(). The prefix will be omitted
    from the path given to setup(). For example, if you have

        C:\Python26\Lib\site-packages\gtk-2.0\runtime\etc\...

    ...and you want your "dist\" dir to contain "etc\..." as a subdirectory,
    invoke the function as

        generate_data_files(
            r"C:\Python26\Lib\site-packages\gtk-2.0\runtime",
            r"etc")

    If, instead, you want it to contain "runtime\etc\..." use:

        generate_data_files(
            r"C:\Python26\Lib\site-packages\gtk-2.0",
            r"runtime\etc")

    Empty directories are omitted.

    file_filter(root, fl) is an optional function called with a containing
    directory and filename of each file. If it returns False, the file is
    omitted from the results.
    """
    data_files = []
    for root, dirs, files in os.walk(os.path.join(prefix, tree)):
        to_dir = os.path.relpath(root, prefix)

        if file_filter is not None:
            file_iter = (fl for fl in files if file_filter(root, fl))
        else:
            file_iter = files

        data_files.append((to_dir, [os.path.join(root, fl) for fl in file_iter]))

    non_empties = [(to, fro) for (to, fro) in data_files if fro]

    return non_empties

rawDescription: Bundling GTK resources with py2exe

description: Bundling GTK resources with py2exe


code:
MAX_LEN = 50
...
threads = [... for job in job_list[:MAXLEN]]
...
return [q.get() for _ in job_list[:MAXLEN]]

rawDescription: Thread/Queue hanging issue

description: Thread/Queue hanging issue


code:
import twitter

def get_tweets(hashtag):
    api = twitter.Api(consumer_key='consumer_key',
                      consumer_secret='consumer_secret',
                      access_token_key='access_token',
                      access_token_secret='access_token_secret')
    api.VerifyCredentials()
    results = api.GetSearch(hashtag)
    return results

rawDescription: Programming a web API with test driven development


code:
years = json.loads(years)
# years string "[1999, 2000, 2001]"
# becomes list [1999, 2000, 2001]
# without parsing the string manually
return render_template('years.html', years=years)

rawDescription: Call a Python function from a Jinja template


code: s = s.split("\t")

rawDescription: Tab separated data python

description: Tab separated data python


code:
g = df.groupby(['col1', 'col2'])
df['session_number'] = g['col3'].apply(lambda s: (s - s.shift(1) > 0.5).fillna(0).cumsum(skipna=False))

rawDescription: Pandas Dataframe split in to sessions

description: Pandas Dataframe split in to sessions


code:
grid = [[True]]*10
grid = [True]*10
[id(e) for e in grid]

rawDescription: Modify element [0][0] in a Python 2D list


code:
def nodistinctcols_orig(M):
    setofcols = set()
    for column in M.T:
        setofcols.add(repr(column))
    return len(setofcols)

rawDescription: Speed up counting number of distinct columns


code:
for prop in ('a', 'b'):
    i2prop = getattr(Item2, prop)
    if getattr(Item1, prop) != i2prop:
        setattr(Item1, prop, i2prop)

rawDescription: How to change object variables in for loop in python

description: Change object variables in for loop in python


code:
lst = [2, 5, 7, 3, 8]
indexes = 1, 3, 4
for i in reversed(indexes):
    del lst[i]
lst

rawDescription: Removing indexes from a list

description: Removing indexes from a list


code:
substance_dict = {'H' : Substance('hydrogen'),
                  'C': Substance('carbon')}
regime_dict    = {'S1': Regime('Surface 1'),
                  'S2': Regime('Surface 2')}
pop = Population(substance_dict['H'], regime_dict['S1'], 1000)
pop_break = Population(Substance('hydrogen'), substance_dict['C'], 1000)

rawDescription: multiple inheritance, validation, python

description: Multiple inheritance, validation, python


code:
pd.options.display.float_format = '{:12,.9f}'.format
df_corr = pd.DataFrame()
diffs = np.arange(4)
for i in range(20):
    df = pd.DataFrame({ 'x': [1,1,1,1], 'y':[5,7,8,6] })
    df['x'] = df['x'] + diffs*.1**i
    df_corr = df_corr.append( pd.rolling_corr(df.x,df.y,3)[2:4], ignore_index=True )

rawDescription: Pandas.rolling_correlation, threshold?

description: Pandas.rolling_correlation, threshold


code:
u = np.zeros((l, l))
wp = np.zeros((l,2))
# some code which edits u and wp

m = u*wp[:, 1]
for x in range(N):
    wavg = np.dot(wp[:, 0], wp[:, 1])
    wp[:, 0] = 1.0/wavg*np.dot(m, wp[:, 0])

rawDescription: Numpy dot in a for loop

description: Numpy dot in a for loop


code: Button(root, text = "example", command = self.example_action).grid(row = count.next())

rawDescription: Python post increment variable in function call


code:
def paw_image(paw):
    from scipy.ndimage import map_coordinates
    ny, nx = paw.shape

    # Trim off any "blank" edges around the paw...
    mask = paw > 0.01 * paw.max()
    y, x = np.mgrid[:ny, :nx]
    ymin, ymax = y[mask].min(), y[mask].max()
    xmin, xmax = x[mask].min(), x[mask].max()

    # Make a 20x20 grid to resample the paw pressure values onto
    numx, numy = 20, 20
    xi = np.linspace(xmin, xmax, numx)
    yi = np.linspace(ymin, ymax, numy)
    xi, yi = np.meshgrid(xi, yi)

    # Resample the values onto the 20x20 grid
    coords = np.vstack([yi.flatten(), xi.flatten()])
    zi = map_coordinates(paw, coords)
    zi = zi.reshape((numy, numx))

    # Rescale the pressure values
    zi -= zi.min()
    zi /= zi.max()
    zi -= zi.mean() #<- Helps distinguish front from hind paws...
    return zi

rawDescription: How to sort my paws?

description: Sort my paws


code:
session = Session()
session.add(Address(user=User(name='test')))
session.query(Address).join(User).filter(User.name == 'test').first()

rawDescription: SQLAlchemy declarative property from join (single attribute, not whole object)


code:
b = json.dumps(a).encode('utf-8')
s.sendall(b)

rawDescription: How to send the content of a dictionary properly over sockets in python3x?

description: Send the content of a dictionary properly over sockets in python3x


rawDescription: Refactor this block cipher keying function


rawDescription: What representation should I use in Pandas for data valid throughout an interval?


rawDescription: negatives and positives in lists

description: Negatives and positives in lists


code: x = random.randint(0, 9)

rawDescription: List index out of range and random number to choose an item in list


code:
foo = [[[1,2],[3,4]],[[5,6],[7,8]]]

result = None
while True:
    try:
        result = foo[0]
    except TypeError:
        break

rawDescription: Python: Get first element of list potentially containing sublists


code:
data = [0.2, 6.4, 3.0]
bins = [(0.0, 1.0), (1.0, 4.0), (4.0, 10.0)]  # assumed (lower, upper] format
cats = []

for elem in data:
    for idx, bounds in enumerate(bins, start=1):
        if bounds[0] < elem <= bounds[1]:
            cats.append(idx)
            break
    else:
        raise ValueError('No bin for {}'.format(elem))

rawDescription: Python identify in which interval the numbers are


code:
dt = np.dtype(np.int32)
dt.itemsize

rawDescription: easy way of getting number of bits from a numpy type?

description: Easy way of getting number of bits from a numpy type


code: result = [[dictionaries[j][item] for j, item in enumerate(row)] for row in data]

rawDescription: Convert data based on multiple dictionaries


code:
with open('document.json') as f:
    d = json.load(f)

time_minutes_coords = d['boxes']['time_minutes']['coord']
time_seconds_coords = d['boxes']['time_seconds']['coord']
score_home_coords = d['boxes']['score_home']['coord']

rawDescription: Create named variables in the local scope from JSON keys


code: cursor.executemany("INSERT INTO product VALUES(?,?,?)",(href, name, newprice))

rawDescription: Python MySQL data insert

description: Python MySQL data insert


code:
import functools

def decorator(function):
    @functools.wraps(function)
    def wrapper(*a, **kw):
        return function(*a, **kw)

    return wrapper

rawDescription: A more elegant way for this python decorator


code:
from pprint import pprint as pp

myList = [[0 for x in range(5)] for x in range(5)]

for i in range(9):
    userInput = int(input("Enter an item: "))
    isFound = False # This flag is used to prevent duplicate entries.

    for rowIndex, row in enumerate(myList):
        for colIndex, column in enumerate(row):
            if column == 0 and not isFound:
                myList[rowIndex][colIndex] = userInput
                isFound = True
                break
    pp(myList)

rawDescription: Is there a way to add to a next free space in a two-dimensional array? (Python 3.x)


rawDescription: comparing numpy structured arrays

description: Comparing numpy structured arrays


code:
daily['year'] = daily.index.year
daily['day'] = daily.index.dayofyear
daily.head()

rawDescription: Align years of daily data

description: Align years of daily data


code:
MaxRSS = []
for count in range(self.files/self.block_length):
    RSS = scipy.fromfile(self.hfile2, dtype=self.datatype, count=self.block_length)
    MaxRSS.append(np.max(RSS))

rawDescription: Building an array in a loop

description: Building an array in a loop


code: test = int(raw_input("answer"))

rawDescription: Python maths does not multiply, it uses string instead?


code:
def qux(self, myvalue = None):
    if myvalue is not None:
        return myvalue + 3
    else:
        return self.bar() + 3

rawDescription: How can I make a method takes the value(s) from another method from within the same class in Python

description: Make a method takes the value(s) from another method from within the same class in Python


code:
import android, time

droid = android.Android()
class Task():
    SET_VARIABLE = 547
    def new_task(self):
        self.action_cnt = 0
        self.extras = {'version_number': '1.0', 'task_name': 'task' + str(time.time()), 'task_priority': 9 }
    def set_var(self, varname, value):
        self.action_cnt += 1
        self.extras['action' + str(self.action_cnt)] = {'action': self.SET_VARIABLE, 'arg:1': varname, 'arg:2': value, 'arg:3': False, 'arg:4': False, 'arg:5': False}
    def run_task(self):
        taskIntent = droid.makeIntent('net.dinglisch.android.tasker.ACTION_TASK', None, None, self.extras).result
        droid.sendBroadcastIntent(taskIntent)
    def set_var_now(self, varname, value):
        self.new_task()
        self.set_var(varname, value)
        self.run_task()

t = Task()
t.set_var_now("%Var", "Your variable value")

rawDescription: Show data on android desktop with SL4A Python (example)


rawDescription: Reimplementing function using regular expression


code: data['uuid1']['checked'] = True

rawDescription: How do I order dict by iterating list of uuids in django template language?

description: Order dict by iterating list of uuids in django template language


code:
for tool in find_tools():
    # Build a custom meta-class to provide __doc__.
    class _ToolMetaclass(type):
        def _get_doc(self):
            return create_docstring(tool)
        __doc__ = property(_get_doc)

    # Build a callable class to wrap the tool.
    class _ToolWrapper(object):
        __metaclass__ = _ToolMetaclass
        def _get_doc(self):
            return create_docstring(tool)
        __doc__ = property(_get_doc)
        def __call__(self, *args):
            validate_args(tool, args)
            execute_tool(tool, args)

    # Add the tool to the module.
    setattr(module, tool.name, _ToolWrapper())

rawDescription: Dynamic function docstring

description: Dynamic function docstring


code:
begin = datetime.datetime.strptime('12:14', '%H:%M').time()
end = datetime.datetime.strptime('12:16', '%H:%M').time()
result = YourModel.objects.filter(time__range=(begin, end))

rawDescription: Django filter on TimeField

description: Django filter on TimeField