code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
timer = fig.canvas.new_timer(interval)
timer.add_callback(function, args)

rawDescription: Python Matplotlib Buttons

description: Python Matplotlib Buttons


code:
a1 = np.load('a.npy')
a1

rawDescription: Python memory mapping

description: Python memory mapping


code:
import builtins
list = []
list()
list = builtins.list
list()

rawDescription: REPL - recover callable after redefining it


code: indices = [i for i,j in enumerate(dict['number']) if j==12]

rawDescription: Find all indices of a value in a dictionary python


rawDescription: Django using list of primary keys to fetch records


code:
import os
import sys
from time import sleep
# other imports

while True:
    file1 = os.stat('file.txt') # initial file size
    file1_size = file1.st_size

    # your script here that collects and writes data (increase file size)
    sleep(1)
    file2 = os.stat('file.txt') # updated file size
    file2_size = file2.st_size
    comp = file2_size - file1_size # compares sizes
    if comp == 0:
        sys.exit
    else:
        sleep(5)

rawDescription: Monitoring if a file stopped writing in python


code: glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT,  GL_TEXTURE_2D, self.texture[i], 0);

rawDescription: OpenGL Framebuffer with more than one texture


code: lines = (line.split(',',3) for line in f)

rawDescription: Import data into DataFrame with additional commas


code:
import socket
HOST = 'localhost'
PORT = 1024

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
while (1):
    conn, addr = socket.accept()
    reqFile = conn.recv(1024)
    with open(reqFile, 'rb') as file_to_send:
        for data in file_to_send:
            conn.sendall(data)
    conn.close()

socket.close()

rawDescription: How to download file from local server in Python

description: Download file from local server in Python


code:
BLACK = 0
BLUE = 1
GREEN = 2
CYAN = 3
RED = 4
MAGENTA = 5
BROWN = 6
LIGHTGRAY = LIGHTGREY = 7
DARKGRAY = DARKGREY = 8
LIGHTBLUE = 9
LIGHTGREEN = 10
LIGHTCYAN = 11
LIGHTRED = 12
LIGHTMAGENTA = 13
YELLOW = 14
WHITE = 15

rawDescription: Console colors (Windows)

description: Console colors (Windows)


code:
from multiprocessing import Process, current_process

if current_process().name == 'MainProcess':
    print('Hello from the main process')
else:
    print('Hello from child process')

def f(name):
    print('hello', name)

if __name__ == '__main__':
    p = Process(target=f, args=('bob',))
    p.start()
    p.join()

rawDescription: Is there a way to check if a module is being loaded by multiprocessing standard module in Windows?


code:
@register.filter
def to_json(value):
    return mark_safe(simplejson.dumps(value))

rawDescription: Converting dict object to string in Django/Jinja2 template


code:
import sys

if len(sys.argv) != 2 :
  sys.stderr.write('Usage: {} <nucleotide file>\n'.format(sys.argv[0]))
  sys.exit()

# assumes the file only contains dna and newlines
sequence = ''
for line in open(sys.argv[1]) :
  sequence += line.strip().upper()

sequence = sequence.replace('A', '1000')
sequence = sequence.replace('C', '0100')
sequence = sequence.replace('G', '0010')
sequence = sequence.replace('T', '0001')

outfile = open(sys.argv[1] + '.bin', 'wb')

outfile.write(sequence)

rawDescription: Python: How to encode DNA sequence using binary values?


code: contact = label.findNext('a', attrs={'href' : True})

rawDescription: Beautiful Soup - handling errors

description: Beautiful Soup - handling errors


rawDescription: In python, how do I cast a class object to a dict


rawDescription: String slicing with delimiter changing in length


rawDescription: Create GCE instance using Python API

description: Create GCE instance using Python API


code:
['parent_item1', 'parent_item2']
['parent_item1', 'parent_item2', 'child1_item']
['parent_item1', 'parent_item2', 'child2_item']

rawDescription: How do I extend a list from a parent class?

description: Extend a list from a parent class


code:
fig = plt.figure()
ax = fig.add_axes([.1, .1, .2, .8])

rawDescription: Creating two completely independent plots in matplotlib and going back and forth between them


rawDescription: create new rank column in python , or use sort and reset index rank - how to?

description: Create new rank column in python , or use sort and reset index rank - how to


code: open(filepath)

rawDescription: Using Pandas read_csv() on an open file twice


code: app.config['BABEL_DEFAULT_LOCALE'] = 'pt_BR' #(context locale to load language).

rawDescription: Python, flask, babel- message, and e.g. Spanish - How to


code: bins = np.linspace(0, 360, 10)

rawDescription: Plot timeseries of histograms in Python

description: Plot timeseries of histograms in Python


code:
def recv_exactly(sock, count):
    """receive exactly count bytes from socket. If socket is closed,
    empty string is returned even if some data received.
    """
    buf = []
    while count:
        data = sock.recv(count)
        if not data:
            return ''
        count -= len(data)
        buf.append(data)
    return ''.join(buf)

rawDescription: Python Socket Receive for multiple TCP headers


rawDescription: Convert a datetime.date object into a datetime.datetime object with zeros for any missing time attributes


code:
def cvsreader(string, q):
    q.put(np.genfromtxt(string, delimiter=',', unpack="true"))

rawDescription: How do I retrieve output from Multiprocessing in Python?

description: Retrieve output from Multiprocessing in Python


code:
def get_banner(target):
    #Finds urls of show images
    urls = []
    types = ['fanart', 'graphical', 'poster']
    tree = et.parse(target)
    root = tree.getroot()
    for banner in root.findall('Banner'):
        url = 'http://thetvdb.com/banners/' + banner.find('BannerPath').text
        type_ = banner.find('BannerType').text
        if not types:
            break
        elif type_ in types:
            urls.append(url)
            types.remove(type_)
    return urls

rawDescription: ElementTree, Python - find element with sub-element containing certain text and add another sub-element to a list


code:
app = wx.App(0)
#MainFrame().Show()
mainFrame = MainFrame() # or, insteadof making it a global variable, pass it as an argument to the objects you create, or store a reference to it anywhere else.
mainFrame.Show()
app.MainLoop()

rawDescription: Changing an element in a different Frame in wxPython


code:
import glob
import os
from datetime import datetime

current_day = datetime.now().strftime("%Y-%m-%d")

for source_name in glob.glob("/Users/shirin/Desktop/Artez/untitled.*"):
    path, fullname = os.path.split(source_name)
    basename, ext = os.path.splitext(fullname)
    target_name = os.path.join(path, '{}{}'.format(current_day, ext))
    os.rename(source_name, target_name)

rawDescription: Find and rename files using a Python script


code:
server.py
import asyncio

@asyncio.coroutine
def got_connection(reader, writer):
    msg = yield from reader.readline()
    message = 'another Test Message\n'.encode('ascii')
    print('Sending message to {}:{} - {}'.format('localhost', 5000, message))
    writer.write(message)

def run():
    loop = asyncio.get_event_loop()
    server = loop.run_until_complete(asyncio.start_server(
                                        got_connection, 'localhost', 5000))
    loop.run_until_complete(server.wait_closed())
    loop.close()

run()

rawDescription: Why is this Python 3 asyncio client sending the bytes only after the Python process is interrupted?


code:
bob : 10.0
fred : 3.0
george : 5.0

rawDescription: python split and reverse text file

description: Python split and reverse text file


code:
from subprocess import check_call

def validatec1(c1):
    return str(int(c1))

def validatec3(c3):
    c3 = c3.strip()
    if not c3:
        raise Exception('Column 3 {} is empty'.format(c3))
    if not c3.startswith('ZZ'):
        raise Exception('Invalid value for c3 {}'.format(c3))
    return c3

batch = []

with open('/tmp/so_insert_report20150804.txt') as fd:
    for lnum, line in enumerate(fd, 1):
        try:
            c1, c2, c3, c4 = line.strip().split('|')
            batch.append((validatec1(c1), validatec3(c3)))
        except Exception as e:
            print('Error processing input file at line {}:\n{}'.format(lnum, line))
            raise e

for v1, v2 in batch:
    check_call(['prosql', '-n', '/psd_apps/700p6/cus/so_insert.enq', v1, v2])

rawDescription: python, loop through a pipe delimited text file and run an sql

description: Python, loop through a pipe delimited text file and run an sql


code:
some_venue = the_user.venues[0] # the first from the list
some_venue.venue = 'At DC. square'
db.put(some_venue) # the entry will be updated

rawDescription: How to query datastore when using ReferenceProperty?

description: Query datastore when using ReferenceProperty


code:
def sim_distance(prefs, person1, person2):
    p1, p2 = prefs[person1], prefs[person2]
    s, t = set(p1), set(p2)
    return len(s.intersection(t)) / len(s.union(t))

rawDescription: Euclidian distance between posts based on tags


rawDescription: Mapping a list to a Huffman Tree whilst preserving relative order


code:
# to continue to fit the model, transform your raw JSON data to numeric value
X = transformer.fit_transform(data)
# import your estimator
from sklearn.naive_bayes import BernoulliNB
estimator = BernoulliNB()
# then start to fit and predict
# NOTE! require your y labels
estimator.fit(X, y)

rawDescription: SciKit-learn (python)--Create my dataset


rawDescription: Rendering vectors in a sphere, with better perception


rawDescription: Explaining the result of an if loop in python


code:
from itertools import ifilter

last_is_one = ifilter(lambda x: x[2] == 1, aList)
paired = pairwise(last_is_one)

rawDescription: generate min combining multiple lists, return lowest uncombined list?

description: Generate min combining multiple lists, return lowest uncombined list


code:
eth = Group("eth" + LBRACE +
                "src" + EQUAL + macAddress("src") + COMMA +
                "dst" + EQUAL + macAddress("dst") +
                RBRACE)
arp = Group("arp" + LBRACE +
                "sip" + EQUAL + ipAddress("sip") + COMMA +
                "tip" + EQUAL + ipAddress("tip") + COMMA +
                "op" + EQUAL + op("op") + COMMA +
                "sha" + EQUAL + macAddress("sha") + COMMA +
                "tha" + EQUAL + macAddress("tha") +
                RBRACE)
ipv4 = Group("ipv4" + LBRACE + "src" + EQUAL + ipAddress("src") + COMMA +
                "dst" + EQUAL + ipAddress("dst") + COMMA +
                "proto" + EQUAL + proto("proto") + COMMA +
                "tos" + EQUAL + tos("tos") + COMMA +
                "ttl" + EQUAL + ttl("ttl") + COMMA +
                "frag" + EQUAL + frag("frag") +
                RBRACE)
tcp = Group("tcp" + LBRACE +
                "src" + EQUAL + src("srcPkt") + COMMA +
                "dst" + EQUAL + dst("dstPkt") +
                RBRACE)

rawDescription: extract data from ovs dump-flow using pyparsing

description: Extract data from ovs dump-flow using pyparsing


code:
class Source(Base):
    __table__ = source

class Event(Base):
    __table__ = event
    source = relation(Source)

rawDescription: sqlalchemy 0.6 legacy database access?

description: Sqlalchemy 0.6 legacy database access


rawDescription: How do get matplotlib pyplot to generate a chart for viewing / output to .png at a specific resolution?


code: argsa = a.argsort()

rawDescription: Dictionaries containing the biggest values


code:
a = numpy.empty((3,3,))
a[:] = numpy.NAN
a

rawDescription: Initializing numpy matrix to something other than zero or one


code:
{'name': u'Text',
 'parameters': [{'id': u'str', 'name': u'Text', 'value': u'Everyone listen up.'},
                {'id': u'fontname', 'name': u'Font', 'value': u'Arial'},
                {'id': u'fontsize', 'name': u'Size', 'value': u'20'},
                {'id': u'fontstyle', 'name': u'Style', 'value': u'1'}]}

rawDescription: how to parse xml data by the text value name? By python minidom

description: Parse xml data by the text value name? By python minidom


code:
if id not in D:
    D[id] = {}

rawDescription: Ordering a nested dictionary by the frequency of the nested value


code: df = userdata.query('A != "a" and B != "b"')

rawDescription: Append new data to a dataframe

description: Append new data to a dataframe


code:
sub_dicts = [lower_dict for lower_dict in mydict.values()]
list_of_lists = [[[lower_key]+[lower_dict[my_field] for my_field in my_ordered_fields] for lower_key,lower_dict in sub_dict.items()] for sub_dict in sub_dicts]

rawDescription: Inserting complex dictionaries into a sqlite database?


code:
with open('movie-matrix.txt', 'r', encoding="ISO-8859-1") as f:
    movMat = list(f)

rawDescription: Python list of lists no loops

description: Python list of lists no loops


code:
def build_symmetric_list_with_references(n) :
    l = []
    for x in range(0,n) :
        ll = []
        for y in range(0,n) :
            if x<= y :
                ll.append((x,y))
            else :
                ll.append(l[y][x]) #by reference
        l.append(ll)
    return l

@profile
def test_b() :
    b = build_symmetric_list_with_references(1000)
test_b()

rawDescription: Large symmetric list in python: will references contribute to size in ram?


code:
var_map = {1: 'foo', 2: 'bar', 10: 'spam'}
var = var_map[a]

rawDescription: Reduced if/else block

description: Reduced if/else block


code:
from urllib import urlencode
from urllib2 import urlopen

ACCESS_KEY = 'blahblah'
long_url = 'http://www.example.com/foo/bar/zoo/hello/'
endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt'
req = urlencode(endpoint.format(ACCESS_KEY, long_url))
short_url = urlopen(req).read()

rawDescription: URL detection and shortening in Django

description: URL detection and shortening in Django


code:
#!/usr/bin/env python
from subprocess import check_call

check_call('someprogram <(someprocess) <(anotherprocess)',
           shell=True, executable='/bin/bash')

rawDescription: Multiple pipes in subprocess

description: Multiple pipes in subprocess


code: print("".join("{:12.6f}".format(item) for item in x))

rawDescription: How to quickly used format to print a list?

description: Quickly used format to print a list


code: timeit.Timer('a("something")', 's = []; a = s.append').timeit()

rawDescription: In Python, what is the difference between ".append()" and "+= []"?


code:
import re
def splitter(fl):
   for line in fl:
     # By using a generator, you are only accessing one line of the file at a time.
     yield re.split('[,/]',line.strip())

rawDescription: Splitting string with multiple delimiters


code:
import timeit
timeit.timeit('[item for item in stringy.split() if item.isdigit()]', 'from __main__ import stringy')
timeit.timeit('integers.findall(stringy)', 'from __main__ import stringy, integers')

rawDescription: Python 2.7: Faster/better way to extract all integer values from a string?


code:
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative.api import declarative_base
from sqlalchemy.orm import relationship, backref
from sqlalchemy.orm.session import Session
from sqlalchemy.sql.schema import Column, ForeignKey
from sqlalchemy.sql.sqltypes import Integer, String, Float, Date

Base = declarative_base()

class Sentence(Base):
    __tablename__ = 'sentence'

    id = Column(Integer, primary_key=True)
    text = Column(String, index = True)

    sentence_words = relationship('WordInSentence')
    words = association_proxy("sentence_words", "word")

class Word(Base):
    __tablename__ = 'word'

    id = Column(Integer, primary_key=True)
    word = Column(String, index = True)

    word_sentences = relationship('WordInSentence')
    sentences = association_proxy("word_sentences", "sentence")

    def __repr__(self):
        return "<Word: " + str(self.word) + ">"

class WordInSentence(Base):
    __tablename__ = "word_in_sentence"

    word_id = Column(Integer, ForeignKey(Word.id),
        primary_key=True)
    sentence_id = Column(Integer, ForeignKey(Sentence.id),
        primary_key=True)
    space_after = Column(String)
    tag = Column(String)
    position = Column(Integer)

    word = relationship(Word)
        #backref=backref("word_sentences", lazy="dynamic"))
    sentence = relationship(Sentence)
        #backref=backref("sentence_words", lazy="dynamic"))

engine = create_engine('sqlite://')
Base.metadata.create_all(engine)

session = Session(engine)

rawDescription: Bidirectional relationship with association_proxy


code: zip(*(row for row in zip(*Matrix) if all(e != ['-'] for e in row)))

rawDescription: Delete Column IF all column cell contain NULL value


rawDescription: Group list-items by order of appearance in unsorted list


code: { s['SnapshotId']:s['StartTime'] for s in data['Snapshots'] }

rawDescription: Query 2 keys from Python dict

description: Query 2 keys from Python dict


code: streams[0].dtype = ">i"

rawDescription: Fast way to read interleaved data?

description: Fast way to read interleaved data


code:
class Test():
    def __init__(self, attr=[]):
        self.attr = attr

a = Test()
b = Test()
a.attr.append(1)
a.attr
b.attr

rawDescription: How should I declare default values for instance variables in Python?


code:
class Seeder:
    def __init__(self):
        self.seeds = set()
        self.cache = dict()

    def get_seed(self, word):
        LIMIT = 2
        seed = self.cache.get(word,None)
        if seed is not None:
            return seed
        for seed in self.seeds:
            if self.distance(seed, word) <= LIMIT:
                self.cache[word] = seed
                return seed
        self.seeds.add(word)
        self.cache[word] = word
        return word

    def distance(self, s1, s2):
        l1 = len(s1)
        l2 = len(s2)
        matrix = [range(zz,zz + l1 + 1) for zz in xrange(l2 + 1)]
        for zz in xrange(0,l2):
            for sz in xrange(0,l1):
                if s1[sz] == s2[zz]:
                    matrix[zz+1][sz+1] = min(matrix[zz+1][sz] + 1, matrix[zz][sz+1] + 1, matrix[zz][sz])
                else:
                    matrix[zz+1][sz+1] = min(matrix[zz+1][sz] + 1, matrix[zz][sz+1] + 1, matrix[zz][sz] + 1)
        return matrix[l2][l1]

import itertools

def group_similar(words):
    seeder = Seeder()
    words = sorted(words, key=seeder.get_seed)
    groups = itertools.groupby(words, key=seeder.get_seed)
    return [list(v) for k,v in groups]

rawDescription: Fuzzy Group By, Grouping Similar Words

description: Fuzzy Group By, Grouping Similar Words


code:
class B(A):
    attribute = A.attribute.copy()
    attribute.update({
          6: 'f',
          7: 'g',
          })

print(B().attribute) # --> {1:'a', ..., 5:'e', 6:'f', 7:'g'}
print(A().attribute) # --> {1:'a', ..., 5:'e'}

rawDescription: Best practice: update/extend subclass class attribute


code:
import re

addr_pat = re.compile("""
    [ ,]*       # zero or more optional leading space or commas
    [0-9]{1,3}  # 1-3 consecutive digits
    \s{0,1}     # one optional whitespace (instead you could just write \s?)
    (/|-|bt.)   # either forward-slash, minus or "bt[any character]" e.g. "bte"
    \s{0,1}     # one optional whitespace
    [0-9]{1,3}  # 1-3 consecutive digits
                # we omitted the trailing " " whitespace you inadvertently had
""", re.VERBOSE)

m3 = addr_pat.search("Rue Saint-Martin 51 bte 7 ")

rawDescription: Why is my address-filtering regexp breaking?


code: '{%(score)s-%(numrep)s}' % d

rawDescription: List of dictionaries - how to format print output


code:
from itertools import combinations_with_replacement

L1 = ['b', 'c', 'd', 'e', 't', 'w', 'x', 'y', 'z']
L2 = ['the onion', 'be your self', 'great zoo', 'x men', 'corn day']

phrase_map = {}

for phrase in L2:
    word_count = {word: phrase.count(word) for word in L1 if word in phrase}

    occurrence_map = {}
    for x, y in combinations_with_replacement(word_count, 2):
        occurrence_map[(x,y)] = occurrence_map[(y,x)] = \
            word_count[x] * word_count[y]

    phrase_map[phrase] = occurrence_map

return phrase_map

rawDescription: Python Co-occurrence matrix of words and phrases


code: listB = listA

rawDescription: Pairwise addtion of two lists mutating one of the source lists


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

for index, file_name in enumerate(available_files, start=1):
    print('{:2} {}'.format(index, file_name))

while True:
    try:
        user_input = int(input('Please select a file number: '))

        if 1 <= user_input <= len(available_files):
            selected_file = available_files[user_input-1]
            break
    except ValueError as e:
        pass

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

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

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


code:
genre = etree.Element("Genre")
genre.text = "New Genre"
tree.xpath('/Title/Genre[last()]')[0].addnext(genre)

rawDescription: Python ElementTree XML Modifying Elements with Multiple Values


code:
bp = titanic.boxplot(column='age', by='pclass', grid=False)
for i in [1,2,3]:
    y = titanic.age[titanic.pclass==i].dropna()
    # Add some random "jitter" to the x-axis
    x = np.random.normal(i, 0.04, size=len(y))
    plot(x, y, 'r.', alpha=0.2)

rawDescription: Adding a scatter of points to a boxplot using matplotlib


code:
d = Distance('1302.09029321 mts')
d.meters
d.feet
d.inch
d.miles
d.miles = 1
d.meters
d.feet
d.inch = .0002
d.inch
d.feet
d.meters
d.miles
d.feet = 1
d.meters
d.miles

rawDescription: The dateutil.parser.parse() of distance strings?


code:
r = requests.get("http://www.december.com/html/demo/hello.html", prefetch=False)
peek = r.iter_content(256).next()
mime = magic.from_buffer(peek, mime=True)

if mime == "text/html":
    contents = peek + ''.join(r.iter_content(10 * 1024))
    encoding = r.encoding
    if encoding is None:
        # detect encoding
        encoding = chardet.detect(contents)['encoding']
    try:
        textcontent = unicode(contents, encoding, errors='replace')
    except (LookupError, TypeError):
        textcontent = unicode(contents, errors='replace')
    print(textcontent)

rawDescription: python-requests: fetching the head of the response content without consuming it all

description: Python-requests: fetching the head of the response content without consuming it all


rawDescription: Python/Pandas - Best way to group by criteria?


rawDescription: Keep getting syntax error. What do I need to do?


code: ['my', 'beautiful', '15 years old', 'always']

rawDescription: Extract single words or phrases from list of strings which are not in base string


code:
import numpy as np

A = np.arange(4 * 2 * 5).reshape(4, 2, 5)
B = np.arange(4 * 2).reshape(4, 2) % 5

C = A[np.arange(A.shape[0])[:, np.newaxis], np.arange(A.shape[1]), B]

rawDescription: Indexing tensor with index matrix in theano?


rawDescription: Passing multiple columns of a 2D array into a lambda function and returning a single column array


code:
def freq_sorted(iterable, key=None, reverse=False, include_freq=False):
  """Return a list of items from iterable sorted by frequency.

  If include_freq, (item, freq) is returned instead of item.

  key(item) must be hashable, but items need not be.

  *Higher* frequencies are returned first.  Within the same frequency group,
  items are ordered according to key(item).
  """
  if key is None:
    key = lambda x: x

  key_counts = collections.defaultdict(int)
  items = {}
  for n in iterable:
    k = key(n)
    key_counts[k] += 1
    items.setdefault(k, n)

  if include_freq:
    def get_item(k, c):
      return items[k], c
  else:
    def get_item(k, c):
      return items[k]

  return [get_item(k, c) for k, c in
          sorted(key_counts.items(),
                 key=lambda kc: (-kc[1], kc[0]),
                 reverse=reverse)]

rawDescription: Ranking Elements of multiple Lists by their count in Python


code: value = intToDelim( data[8:], b'\x04' )

rawDescription: How can I convert a byte array to an integer more elegantly in Python

description: Convert a byte array to an integer more elegantly in Python


code: slugify(u'My International Text: åäö', delim='_')

rawDescription: Normalizing unicode text to filenames, etc. in Python


rawDescription: What statistical learning algorithm library should I use?


code:
stack = ['testing', 'this']
' '.join(stack)
stack

rawDescription: Adding a string with spaces to a stack

description: Adding a string with spaces to a stack


code:
# Filter unwanted lines
a = filter(lambda x: not x.startswith("%s:%s"%(args[1], sender.getName())), \
            textfile.readlines())

# Write filtered lines to file
textfile.seek(0)
textfile.truncate()
textfile.writelines(list(x.strip() for x in a))
textfile.close()

rawDescription: Deleting line that startswith in txt file?


code: [x*10**pow for pow in range(6) for x in range(3,10,3)]

rawDescription: how to generate the following list with few words in python?

description: Generate the following list with few words in python


rawDescription: Is there a better way to combine multiple items in a python list


rawDescription: Python Data Structure Selection

description: Python Data Structure Selection


code:
if exit_status:
    self.output = stderr.readlines()
else:
    self.output =  stdout.readlines()[1:-1]

rawDescription: Python Class For Reading List Element ,__str__ and class questions


rawDescription: Not sure how to parse this

description: Not sure how to parse this


code:
from PyEPL.display import VideoTrack
from PyEPL.sound import AudioTrack
from PyEPL.textlog import LogTrack
...

rawDescription: Help with PyEPL logging

description: Help with PyEPL logging


rawDescription: Parsing string containing Unicode character names


rawDescription: Implement this situation in numpy

description: Implement this situation in numpy


code:
os.getenv.__name__
os.getenv.__module__

rawDescription: Pythonic way to intercept calls to a function?


code:
def loop(data):
    output = []
    for datum in data: # This outputs on (3x2) matrix after the other
        d0 = datum[0]
        dr = datum[1:]
        output.append(dr-d0)
    return output

def listcomp(data):
    output = [dr-d0 for (d0, dr) in zip(data[:,0], data[:,1:])]
    return output

def sub(data):
    output = data[:,1:] - data[:,0,None]
    return output

rawDescription: How would you efficiently vectorize that kind of operation using numpy?


code:
def pad(array, reference, offsets):
    """
    array: Array to be padded
    reference: Reference array with the desired shape
    offsets: list of offsets (number of elements must be equal to the dimension of the array)
    """
    # Create an array of zeros with the reference shape
    result = np.zeros(reference.shape)
    # Create a list of slices from offset to offset + shape in each dimension
    insertHere = [slice(offset[dim], offset[dim] + array.shape[dim]) for dim in range(a.ndim)]
    # Insert the array in the result at the specified offsets
    result[insertHere] = a
    return result

rawDescription: python how to pad numpy array with zeros

description: Python how to pad numpy array with zeros


code:
import os
import re
import logging
import config
import json

import webapp2
import jinja2

from google.appengine.ext import ndb
from models.story import Story

class RootPage(webapp2.RequestHandler):
    def get(self):
        story = Story.get_or_insert('Some id or so', title='A voting story again...')
        jinja_environment = self.jinja_environment
        template = jinja_environment.get_template("/index.html")
        self.response.out.write(template.render({'story': story}))

    @property
    def jinja_environment(self):
        jinja_environment = jinja2.Environment(
            loader=jinja2.FileSystemLoader(
                os.path.join(os.path.dirname(__file__),
                             '../views'
                ))
        )
        return jinja_environment

class VoteHandler(webapp2.RequestHandler):
    def post(self):
        logging.info(self.request.body)
        data = json.loads(self.request.body)
        story = ndb.Key(Story, data['storyKey']).get()
        story.vote_count += 1
        story.put()
        self.response.out.write(json.dumps(({'story': story.to_dict()})))

rawDescription: How to use AJAX with Google App Engine (Python)

description: Use AJAX with Google App Engine (Python)


code:
df
df['char_length'] = df['string'].str.len()
df

rawDescription: Adding a data frame column with len() of another column's values


code:
def get_paginate_by(self, queryset):
    if self.request.mobile:
        return 5
    return 20

rawDescription: Django Class model access self

description: Django Class model access self


rawDescription: Static method-only class and subclasses in Python - is there a better design pattern?


code: {k: list_stats[i*7+1:(i+1)*7] for i, k in enumerate(list_stats[::7])}

rawDescription: Rewrite a Python Code

description: Rewrite a Python Code


code:
arg = "school"
arg_2 = "college"
school = "enjoy"
college = "study"
locals()[arg]
locals()[arg_2]

rawDescription: how to get string itself as a variable

description: Get string itself as a variable


rawDescription: Python json parser allow duplicate keys

description: Python json parser allow duplicate keys


code: tmp = sp.call('cls',shell=True)

rawDescription: Python: Clear screen in shell

description: Python: Clear screen in shell


code:
from threading import current_thread
current_thread()

rawDescription: django.utils.thread_support in django 1.5

description: Django.utils.thread_support in django 1.5


code: ', '.join(i[1] for i in item[0] if i[1] not in blockedList)

rawDescription: Python: Short way implementation

description: Python: Short way implementation


code:
out = []

for ele in l:
    for patt in ["%d/%m/%Y","%d-%m-%Y"]:
        try:
            p1 = datetime.strptime(ele,patt).strftime("%Y-%m-%d")
            if p1:
                out.append(p1)
                break
        except ValueError as e:
            print(e)
    else:
        out.append(ele)

print(out)
['1', '2', '2015-01-02', '3', '4', '2015-01-05', '5', 'Anot/her Ex/ample', '6']

rawDescription: Python - Regular Expression to find dates in list


code:
def function(user,b):
    user.getApple().eatTheApple(b, 2000, 50, 1, 8663, 4444)

rawDescription: Use a variable in a function

description: Use a variable in a function


code: comments = Comment.query.filter(Comment.parent_id == None)  # same order_by goes here

rawDescription: Iterate through Python Flask/Jinja2 adjacency list


code:
import numpy as np
l = np.array([(1, 2), (1, 3)])
m = np.array([(3, 1), (2, 4)])
my_list = [l, m]

s = sum(my_list)
for my_element in my_list:
    avg_of_others = (s - my_element) / float(len(my_list) - 1)

rawDescription: Python split list by one element

description: Python split list by one element


code:
pylab.figure()
pylab.plot(t)
pylab.yscale('close_to_one', nines=3)
pylab.grid(True)

rawDescription: Logarithmic plot of a cumulative distribution function in matplotlib


code:
import Tkinter as tk
import tkMessageBox
import codecs
import itertools
import sys

alfabetet = (u"abcdefghijklmnopqrstuvwxyz"
             u"\N{LATIN SMALL LETTER AE}"
             u"\N{LATIN SMALL LETTER O WITH STROKE}"
             u"\N{LATIN SMALL LETTER A WITH RING ABOVE}")

encoding = sys.stdin.encoding
with codecs.open('norsk.txt','r',encoding) as fil:
    ordliste = set(line.rstrip(u'\n') for line in fil)

def get_unicode(widget):
    streng = widget.get()
    if isinstance(streng,str):
        streng = streng.decode('latin-1')
    return streng

def siord():
    alfa=lagtabell()
    try:
        streng = get_unicode(ordinn)
        ordene=finnord(streng,alfa)
        if len(ordene) == 0:
            # There are no words that match
            tkMessageBox.showinfo('Dessverre..','Det er ingen ord som passer...')
        else:
            # Done: The words that fit the pattern
            tkMessageBox.showinfo('Ferdig',
                'Ordene som passer er:\n'+ordene.encode('utf-8'))
    except Exception as err:
        # There has been a mistake .. Check your word
        print(repr(err))
        tkMessageBox.showerror('ERROR','Det har skjedd en feil.. Sjekk ordet ditt.')

def finnord(streng,alfa):
    liste = set()
    for substitution in itertools.permutations(alfa,streng.count(u'*')):
        s = streng
        for ch in substitution:
            s = s.replace(u'*',ch,1)
        if s in ordliste:
            liste.add(s)
    liste = [streng]+list(liste)
    return u','.join(liste)+u'.'

def lagtabell():
    tinbox = get_unicode(bokstinn)
    if not tinbox.isalpha():
        alfa = alfabetet
    else:
        alfa = tinbox.lower()
    return alfa

root = tk.Tk()
root.title('FeudHjelper av Martin Skow Røed')
root.geometry('400x250+450+200')
# root.iconbitmap('data/ikon.ico')

skrift1 = tk.Label(root,
                text = '''\
Velkommen til FeudHjelper. Skriv inn de bokstavene du har, og erstatt ukjente med *.
F. eks: sl**ge
Det er kun lov til å bruke tre stjerner, altså tre ukjente bokstaver.''',
                font = ('Verdana',8), wraplength=350)
skrift1.pack(pady = 5)

ordinn = tk.StringVar(None)
tekstboks = tk.Entry(root, textvariable = ordinn)
tekstboks.pack(pady = 5)

# What letters do you have? Eg "ahneki". Leave blank here if you want all the words.
skrift2 = tk.Label(root, text = '''Hvilke bokstaver har du? F. eks "ahneki". La det være blankt her hvis du vil ha alle ordene.''',
                font = ('Verdana',8), wraplength=350)
skrift2.pack(pady = 10)

bokstinn = tk.StringVar(None)
tekstboks2 = tk.Entry(root, textvariable = bokstinn)
tekstboks2.pack()

knapp = tk.Button(text = 'Finn ord!', command = siord)
knapp.pack(pady = 10)
root.mainloop()

rawDescription: UnicodeWarning: special characters in Tkinter


code: {"test_id1" : (resultValue, timeChecked)}

rawDescription: python dictionary with two values for each key or class?

description: Python dictionary with two values for each key or class


code:
names = {}
with open('yourfile') as fin:
    lines = (line.strip().partition(': ') for line in fin)
    for fst, sep, snd in lines:
        if sep:
            name = fst
        names.setdefault(name, []).append(snd or fst)

rawDescription: Read a file line by line,and get the line that starts with some word?


code:
t = ParentedTree.fromstring('(S (NP (D the) (N dog)) (VP (V chased) (NP (D the) (N cat))))')
np_pos = (1,1)
np = t[np_pos]
print(np)

rawDescription: How many leaves are there before a subtree?


code:
mybins = np.arange(0,48,2)

nA,binsA = np.histogram(setA,bins=mybins,normed=True)
nB,binsB = np.histogram(setB,bins=mybins,normed=True)
nC,binsC = np.histogram(setC,bins=mybins,normed=True)

# Since the sum of each of these will be 1., lets divide by 3.,
# so the sum of the stacked histogram will be 1.
nA/=3.
nB/=3.
nC/=3.

# Use bottom= to set where the bars should begin
plt.bar(binsA[:-1],nA,width=2,color='b',label='setA')
plt.bar(binsB[:-1],nB,width=2,color='g',label='setB',bottom=nA)
plt.bar(binsC[:-1],nC,width=2,color='r',label='setC',bottom=nA+nB)

rawDescription: Normalising Histograms Matplotlib

description: Normalising Histograms Matplotlib


code:
# astimezone converts timezone-aware datetimes to other timezones.
date_in_utc = date_in_newyork.astimezone(utc)
print(date_in_utc)
# 2012-08-12 14:00:00+00:00

rawDescription: What is the local timezone

description: What is the local timezone


code:
from itertools import islice, chain, repeat

def gen_users(users, total):
    return islice(chain(users, repeat(users[-1])), total)

list(gen_users([1,2,3], 5))
list(gen_users([1,2,3], 3))
list(gen_users([1,2,3], 2))

rawDescription: Is there a better way to define this generator?


code:
# Assuming data is a byte string.
# (If you're dealing with a Unicode string, encode it first.)
content_length_header = "Content-Length: {0}\r\n".format(len(data))

rawDescription: Web server in Python 2.7: Browser not displaying page


code:
x = np.arange(3)
y = np.arange(4)
np.outer(x, y)

rawDescription: product of arrays of different sizes in numpy

description: Product of arrays of different sizes in numpy


rawDescription: what is the most efficient way to creating a dict with two lists?

description: What is the most efficient way to creating a dict with two lists


code: for _, row in df.iterrows(): row['Day'] = 2

rawDescription: Why doesn't this function "take" after I iterrows over a pandas DataFrame?


code:
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
[tr.find('td').text for tr in soup.findAll('tr')]

rawDescription: BeautifulSoup HTML extracting tabular data


code:
import shelve
d = shelve.open('myfile.db')
data = d['data']
d.close()

rawDescription: Python - Saving Data outside of program

description: Python - Saving Data outside of program


rawDescription: EOL whilst scanning string literal - Python


code: [MyClass(*args) for name, args in objects.items()]

rawDescription: create multiple objects of a class with different arguments

description: Create multiple objects of a class with different arguments


code:
def autopct_generator(limit):
    def inner_autopct(pct):
        return ('%.2f' % pct) if pct > limit else ''
    return inner_autopct

ax.pie(df[col], labels=df.index, autopct=autopct_generator(20), colors=colors)

rawDescription: Conditional removal of labels in Matplotlib pie chart


code:
with open(HASHES) as hashes:
    for line in hashes:
        hash = line.strip()
        if hash in cracked:
            print('Found:', hash, 'which maps to', cracked[hash])

rawDescription: two lists, faster comparison in python

description: Two lists, faster comparison in python


code:
import re
list(zip(*sorted(zip(*lst), key=lambda x: (re.search(r'\bRZ', x[2]) != None, x[2]))))

rawDescription: Sorting columns in Python 3.3 nested list by partial comparison


code:
from PIL import Image
from collections import defaultdict
import pprint

img = Image.open("kEwfFs3.png")
rgbimg = Image.new("RGBA", img.size)
rgbimg.paste(img)

found_colors = defaultdict(int)
for x in range(0, rgbimg.size[0]):
    for y in range(0, rgbimg.size[1]):
        pix_val = rgbimg.getpixel((x, y))
        found_colors[pix_val] += 1
pprint.pprint(dict(found_colors))

rgbimg.save('kEwfFs3.jpg')

rawDescription: Python Pil Change GreyScale Tif To RGB

description: Python Pil Change GreyScale Tif To RGB


code:
sounds = [SoundLoader.load("sound.wav") for _ in range(10)]
index = 0

rawDescription: Python Kivy: Play sound multiple times at once


code:
class Post(models.Model):
    ...

class Comment(models.Model):
    user = models.ForeignKey(User)
    post = models.ForeignKey(Post)
    text = models.CharField(...)

rawDescription: Django newbie having hard time with models and reusable business logic


rawDescription: Stripping empty elements from lists

description: Stripping empty elements from lists


rawDescription: PrettyPrint indent/line break each level


code: dictionary['firstname']

rawDescription: how I should proceed to extract the value id for keys from the .json file in python using the keys

description: How I should proceed to extract the value id for keys from the .json file in python using the keys


code:
class MyFuzzyTerm(FuzzyTerm):
     def __init__(self, fieldname, text, boost=1.0, maxdist=2, prefixlength=1, constantscore=True):
         super(D, self).__init__(fieldname, text, boost, maxdist, prefixlength, constantscore)
         # super().__init__() for Python 3 I think

rawDescription: python fuzzy text search

description: Python fuzzy text search


rawDescription: Python: pop item in list of lists by index


code:
seq = ('a', 'b', 'c')
joined = '-'.join(seq)
print('The join output is:', joined, 'The length is:', len(seq))

rawDescription: Print and join statement in python

description: Print and join statement in python


rawDescription: python changing integers/ floats to None in list

description: Python changing integers/ floats to None in list


code: [int(round(x)) for x in np.linspace(0, 2, 9)]

rawDescription: Rescale a numpy array

description: Rescale a numpy array


code:
npnanmin(wind_speed, axis=0)
npnanmax(wind_speed, axis=0)

rawDescription: Finding minimum and maximum value for each row, excluding NaN values


rawDescription: Python Multiple Variable Declaration

description: Python Multiple Variable Declaration


code:
# forms.py
from django import forms
from .models import Document

class DocumentForm(forms.ModelForm):
    class Meta:
        model = Document

rawDescription: Adding additional data fields when uploading file to Database w/ Django


code:
G = nx.Graph()
G.add_nodes_from([1,2])
weight=random.randint(1, 10)
G.add_edge(1, 2, weight=weight, label=str(weight))

rawDescription: How to represent networkx graphs with edge weight using nxpd like outptut

description: Represent networkx graphs with edge weight using nxpd like outptut


code:
samples = [None] * 6
for k in range(6):
    with open('genes.csv') as f: #but something specific to k
        cread = list(csv.reader(f, delimiter = '\t'))
        samples[k] = {i: float(j) for i, j in cread}

rawDescription: Create multiple dictionaries from a single iterator in nested for loops


rawDescription: take snapshots every second using artist animation

description: Take snapshots every second using artist animation


code:
import time

FPS = 30
last_time = time.time()
# whatever the loop is...
while True:
    # draw animation
    # pause so that the animation runs at 30 fps
    new_time = time.time()
    # see how many milliseconds we have to sleep for
    # then divide by 1000.0 since time.sleep() uses seconds
    sleep_time = ((1000.0 / FPS) - (new_time - last_time)) / 1000.0
    if sleep_time > 0:
        time.sleep(sleep_time)
    last_time = new_time

rawDescription: Python Animation Timing

description: Python Animation Timing


rawDescription: Parse output to get a list in python

description: Parse output to get a list in python


code:
statement = {
    "Bob": lambda: print("Looking good, Bob!"),
    "Jane": lambda: print("Greetings, Jane!"),
    "Derek": lambda: print("How goes it, Derek?")
}[person]()

rawDescription: Is there anything like a "void lambda" in Python?


code: numpy.random.randint(2, size=100) < 1

rawDescription: An explanation of randint(2) < 1 in python, I cannot understand what the < 1 does


rawDescription: scikit-learn how to know documents in the cluster?

description: Scikit-learn how to know documents in the cluster


code: value=json.dumps({"data":data })

rawDescription: Order list of Json object by value using python


rawDescription: Variable scope for nested functions in python


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

# get some data with true @ probability 80 %
data = np.random.random((20, 500)) > .2

fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(data, aspect='auto', cmap=plt.cm.gray, interpolation='nearest')

rawDescription: Matplot: How to plot true/false or active/deactive data?


code:
s = 'More stuffText inside of the bodyRandom text'
s.split('')[1].split('')[0]

rawDescription: How can I extract the contents of the <body> tag?

description: Extract the contents of the <body> tag


code:
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib.colors as colors
from mpl_toolkits.mplot3d import Axes3D
import pylab
from scipy.interpolate import griddata

dat = open('ex.csv', 'w')
dat.write('x,y,z,c\n')
for x in range(20):
    for y in range(20):
         for c in range(0,7):
             dat.write(','.join([str(s) for s in [x,y,x+y+c,c/10.0,'\n']]))
dat.close()

fig = matplotlib.pyplot.gcf()
dat = np.genfromtxt('ex.csv', delimiter=',',skip_header=1)
X_dat = dat[:,0]
Y_dat = dat[:,1]
Z_dat = dat[:,2]
C_dat = dat[:,3]

# Create a Normalize instance.
norm = colors.Normalize(vmin=C_dat.min(),vmax=C_dat.max())

ax1 = fig.add_subplot(111, projection='3d')
for color in np.unique(C_dat):
    X, Y, Z, C = np.array([]), np.array([]), np.array([]), np.array([])
    for i in range(len(X_dat)):
        if C_dat[i]==color:
            X = np.append(X,X_dat[i])
            Y = np.append(Y,Y_dat[i])
            Z = np.append(Z,Z_dat[i])
            C = np.append(C,C_dat[i])

    xi = np.linspace(X.min(),X.max(),100)
    yi = np.linspace(Y.min(),Y.max(),100)

    zi = griddata((X, Y), Z, (xi[None,:], yi[:,None]), method='cubic')
    ci = griddata((X, Y), C, (xi[None,:], yi[:,None]), method='cubic')

    xig, yig = np.meshgrid(xi, yi)

    # Note the use of norm in the facecolors option
    surf = ax1.plot_surface(xig, yig, zi,facecolors=cm.rainbow(norm(ci)), alpha = 0.7)

m = cm.ScalarMappable(cmap=cm.rainbow)
m.set_array(np.unique(C_dat))

col = plt.colorbar(m)

plt.show()

rawDescription: matplotlib correct colors/colorbar for plot with multiple surfaces each of a different color

description: Matplotlib correct colors/colorbar for plot with multiple surfaces each of a different color


code:
for x in range(251):
    print("{:b}".fromat(x))

rawDescription: Printing Binary in Python

description: Printing Binary in Python


code:
p = multiprocessing.Process(target=test_def)
p.start()
p.join()

rawDescription: Python Mulitprocessing

description: Python Mulitprocessing


code:
my_dict={}
with open("traits.csv","rb") as f:
   cr = csv.reader(f, delimiter=',', lineterminator='\n')
   for row in cr:
       my_dict.setdefault(row[0].strip('" '),[]).append(row[1].strip('" '))

rawDescription: How to combine multiple lines in CSV into one line

description: Combine multiple lines in CSV into one line


code:
def test(lst1):
    lst2 = [i for i in lst1 if i not in lst2]
dis.dis(test)

rawDescription: Accessing the List Being Generated by List Comprehension


code:
dofw = "Mon Tue Wed Thu Fri Sat Sun".split()
grid = daily.unstack('D').rename(columns=lambda x: dofw[x-1])
grid

rawDescription: Pandas: how to plot yearly data on top of each other


code:
class A:
    def __del__(self):
        print("A is going away")

class C:
    def __init__(self):
        self.self = self
        self.a = A()

rawDescription: How many times can `__del__` be called per object in Python?


code: point_b = convertAtoB(s, point_a, dummy)

rawDescription: swig typemap for python: input and output arrays

description: Swig typemap for python: input and output arrays


code:
class Logic_Value(object):
    def __init__(self, name, negation=False):
        self.name = name
        self.negation = negation

    def __neg__(self):
        return Logic_Value(self.name, not self.negation)

    def __str__(self):
        return '~' + self.name if self.negation else self.name

rawDescription: Python: Check if list item has a complement


code:
from collections import Counter
from string import punctuation

cnt = Counter(word for line in text.lower() for word in
              (word.rstrip(punctuation) for word in line.split()
               if word not in ignore))

rawDescription: get some words sorted by occurrence and some words should be ignored from a string

description: Get some words sorted by occurrence and some words should be ignored from a string


code:
import numpy.lib.recfunctions as rf
rf.append_fields( ... )

rawDescription: Add new items to some structured array in a dictionary-like way


code:
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('first_name', 'salary', 'dept_name')

rawDescription: using Django Rest framework to serialize custom data types and return response

description: Using Django Rest framework to serialize custom data types and return response


code: help(foo)

rawDescription: Find what is in a PYC file

description: Find what is in a PYC file


code: model = joblib.load('saved_model.pkl')

rawDescription: moving classification to production environment

description: Moving classification to production environment


code:
pat = re.compile(r"""
    (?:\w+-)+?      # some number of groups of words followed by a hyphen
    Version=        # the literal string Version=
    ([0-9.]+)       # capture the version number""", re.X)

...
for line in f:
    match = pat.match(line)
    if match:
        version = match.groups(1)
        break

rawDescription: Reading for a specific value in a file

description: Reading for a specific value in a file


code:
from datetime import datetime
time_list = []
time_list.append(datetime.now())

rawDescription: Python list and time

description: Python list and time


rawDescription: Replace specific values in a matrix using Python


code: [(float(row[0]), int(row[1]), parse(row[2])) for row in res]

rawDescription: what is this saying in python

description: What is this saying in python


rawDescription: Python - Retrieve and replace based on a regex


code:
mi1 = MultiIndex.from_tuples([('bar', 'y'), ('bar', 'z'), ('baz', 'y'), ('baz', 'z'), ('foo', 'y'), ('foo', 'z')],names=['first','second'])
dfa = DataFrame(np.random.randn(6),index=mi1)
dfa

rawDescription: How to sort a pandas dataframe by columns and a part of multi index simultaneously without modifying the dataframe

description: Sort a pandas dataframe by columns and a part of multi index simultaneously without modifying the dataframe


code:
ctags -R
ctags --append -R /path/to/python-source

rawDescription: ctags info for built-in functions in PHP/Python/Etc

description: Ctags info for built-in functions in PHP/Python/Etc


code: z = a + bx + cx^2 + dy + ey^2

rawDescription: Fit data to curve using polyfit with multiple variables in python using numpy polyfit


code: [k for k,v in dic.items() if "1200" in v]

rawDescription: A function that displays a search from another function; dictionaries?


code:
import numpy as np
g = (x>0 for x in array([-10,1,2]))
g
l = list(g)
l
np.sum(l)

rawDescription: All command in Python

description: All command in Python


code:
class Foo(object):
    ...

rawDescription: Equivalent of struct members in Python (mainly for documentation and reading code)


rawDescription: Traversing from one node in xml to another using Python


code:
from time import sleep
delay = 0.5
tlist = [threading.Thread(target=search_sl, args=(ra,dec, q)) for ra, dec in candidates ]
map(lambda t:t.start(), tlist)
while(any(map(lambda t:t.isAlive()))): sleep(delay)

rawDescription: python, how to incrementally create Threads

description: Python, how to incrementally create Threads


code:
def vector_length(x, y):
    return math.sqrt(x*x + y*y)

def normalize_vector(x, y):
    norm = vector_length(x, y)
    return x/norm, y/norm

target = normalize_vector(bpos[1] - mpos[1], bpos[0] - mpos[0])

rawDescription: Pygame Sprite Moving at Constant Speed

description: Pygame Sprite Moving at Constant Speed


rawDescription: Adding key-value pairs to a dictionary in an ascending order


code:
from datetime import datetime, time, timedelta
import random
now = datetime.now()
midnight = datetime.combine(now.date(), time.min)
delta = int((now - midnight).total_seconds())
midnight + timedelta(seconds=random.randrange(delta))
midnight + timedelta(seconds=random.randrange(delta))
midnight + timedelta(seconds=random.randrange(delta))
midnight + timedelta(seconds=random.randrange(delta))
midnight + timedelta(seconds=random.randrange(delta))

rawDescription: Get Random Time Between Midnight to Current Time


code:
## Line 732
self.sock.connect(self.url, header = self.header)

rawDescription: How to add more headers in websocket python client

description: Add more headers in websocket python client


code:
for i in range(len(x)):
    words = []
    z = y-x[i]
    words.append(str(x[i]))
    words.append(", ".join((str(_z) for _z in z)))
    outfile.write(": ".join(words))
    outfile.write("\n")

rawDescription: How to solve an equation with two variables in python

description: Solve an equation with two variables in python


code: data = [ [arr[0], int(arr[1]), int(arr[2])] for arr in arrs ]

rawDescription: spliting a list into [ ]

description: Spliting a list into [ ]


code: del open

rawDescription: Undo Overwrite of Python Built-In

description: Undo Overwrite of Python Built-In


code:
import subprocess

# CURRENT DIRECTORY OF SCRIPT (ASSUMING R SCRIPT IN SAME DIRECTORY)
cd = os.path.dirname(os.path.abspath(__file__))

# COMMAND LINE ARGUMENTS (IF RSCRIPT.EXE IS PATH VARIABLE, LEAVE OUT DIRECTORY)
cmd = ["path/to/RScript", os.path.join(cd, "HistPlotScriptName.R")]

# SUBPROCESS CALL
a = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output,error = a.communicate()

# R CONSOLE OUTPUT PRINTED TO PYTHON CONSOLE
if a.returncode == 0:               # SUBPROCESS SUCCESSFUL
    print(output.decode("utf-8"))
else:                               # SUBPROCESS FAILED
    print(error.decode("utf-8"))

rawDescription: Converting R to ryp2

description: Converting R to ryp2


code: ','.join(d[key] for key in sorted(d.keys()) if d[key])

rawDescription: remove unnecessary comma from python dict

description: Remove unnecessary comma from python dict


rawDescription: Using HybridProperty to count previous sibblings


code:
import pprint

def traverse(root, branch):
    if not branch:
        return
    if branch[0] not in root:
        root[branch[0]] = {}
    traverse(root[branch[0]], branch[1:])

# Or rather, uglify
def prettify(root):
    res = []
    for k, v in root.iteritems():
        d = {}
        d['name'] = k
        d['children'] = prettify(v)
        res.append(d)
    return res

d = {}
branches = [['root','n1','l1'],['root','n1','l2'],['root','n2','l3'],['root','n2','l4']]
for b in branches:
    traverse(d, b)
pprint.pprint(d)
pprint.pprint(prettify(d))

rawDescription: Reconstructing a tree from lists of branches


code:
def get_all_sub_mat(mat):
    rows = len(mat)
    cols = len(mat[0])
    def ContinSubSeq(lst):
        size=len(lst)
        for start in range(size):
            for end in range(start+1,size+1):
                yield (start,end)
    for start_row,end_row in ContinSubSeq(list(range(rows))):
        for start_col,end_col in ContinSubSeq(list(range(cols))):
            yield [i[start_col:end_col] for i in mat[start_row:end_row] ]

rawDescription: Find all submatrices of a given matrix

description: Find all submatrices of a given matrix


code:
with open(json_file_path, "r") as json_file:
    for line in json_file:
        data = json.loads(line)
        process_data(data)

rawDescription: Update json file

description: Update json file


code:
import editdistance
editdistance.eval(list1, list2)

rawDescription: Token-based edit distance in Python?

description: Token-based edit distance in Python


code:
def levelorder(tree):
    levels = [ [tree.root] ]
    while levels [-1]:
        nextLevel = []
        for node in levels [-1]:
            nextLevel.extend ( [node for node in (node.left, node.right) if node] )
        levels.append (nextLevel)
    return levels # or maybe levels [:-1]

rawDescription: Print Levels Of A Binary Tree by Level Iteratively


rawDescription: Python re finding string between underscore and ext


code:
import subprocess
import shlex
import os

fd=os.open('passphrase.txt',os.O_RDONLY)
cmd='gpg --passphrase-fd {fd} -c'.format(fd=fd)
with open('filename.txt','r') as stdin_fh:
    with open('filename.gpg','w') as stdout_fh:
        proc=subprocess.Popen(shlex.split(cmd),
                              stdin=stdin_fh,
                              stdout=stdout_fh)
        proc.communicate()
os.close(fd)

rawDescription: Write to file descriptor 3 of a Python subprocess.Popen object


rawDescription: sorting of python dict, first by value then by key

description: Sorting of python dict, first by value then by key


code:
cont = soup.select_one("div.covMainBoxContent")

print([a["href"] for a in cont.select("a[href]")])

rawDescription: Getting TypeError when trying to concatenate 'str' and 'NoneType' objects


code:
pops = (20, 30, 44)
alleles = (('A', 'A'), ('A', 'a'), ('a', 'a'))

population = [a for n, a in zip(pops, alleles) for _ in range(n)]

rawDescription: Populate list with tuples

description: Populate list with tuples


code: df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')

rawDescription: Replacing few values in a pandas dataframe column with another value


code:
from collections import namedtuple
...
max_gravity = 100
Move = namedtuple('Move', ['up', 'left', 'right'])
while True:
    screen.fill((25,30,90))
    mse = pygame.mouse.get_pos()
    key = pygame.key.get_pressed()

    for event in pygame.event.get():
       ...

    move = Move(key[K_UP], key[K_LEFT], key[K_RIGHT])
    for p in player:
        p.update(move, blocklist)
        screen.blit(p.sprite, p.rect)

rawDescription: Add collision detection to a plattformer in pygame


code:
def comments(request):
    value = float(request.GET['value'])
    return render(request, 'comments.html',
                 {'comments': comments.objects.filter(min__lte=value,
                                                      max__gte=value)})

rawDescription: Django- Using Parameters To Display Entry


code:
class Variable(object):
   def __init__ (self, state_dynamic, state_static, control_static, control_dynamic, scheduling):
      self.state_dynamic = state_dynamic
      self.state_static = state_static
      self.control_static = control_static
      self.control_dynamic = control_dynamic
      self.scheduling = control_dynamic

rawDescription: Using class to define multiple variables in python


code:
from application import db
...

rawDescription: Python clean imports for models - SQL Alchemy


code:
names = custom_sample(population, 5)
names

rawDescription: randomly choose from list using random.randint in python

description: Randomly choose from list using random.randint in python


code:
def toppings(bacon,lettuce,tomato,mayo):
    args = (bacon,lettuce,tomato,mayo)
    if any(args):
       condiments = ('bacon','lettuce','tomato','mayo')
       return "The food has "+" ".join(x for x,y in zip(condiments,args) if y) + '.'
    else:
       return "You must be full"

rawDescription: Python, inserting a boolean to a corresponding value


rawDescription: Get mean value of certain part of array

description: Get mean value of certain part of array


code:
from numba import autojit
import numpy as np

@autojit
def my_filter_nb(X, Y):
    Y[0] = X[0]
    for i in range(1, len(X)):
        Y[i] = max(.99*Y[i-1], X[i])
    return Y

def my_filter_fast(X):
    Y = np.empty(len(X))
    my_filter_nb(X, Y)
    return Y

rawDescription: Iteratively-defined Numpy Array Creation


code:
from subprocess import Popen, PIPE
s = Popen(['cat', '-'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
input = 'España'
output, errs = s.communicate(input.encode())
output, errs = output.decode(), errs.decode()

rawDescription: Subprocess writing stdin and reading stdout python 3.4


rawDescription: Why is the value of p[1] is '0' immediately after entering the for loop?


code: mylist = map(math.sqrt,xrange(0,101))

rawDescription: Python SyntaxError when creating a list using a generator


code:
def a_function(n, a, b, c):
    if n == 1:
        return ((a,b),)
    else:
        x = a_function(n-1, a, c, b)
        return x + ((a,b),) + a_function(n-1, c, b, a)

rawDescription: Changing outputs into tuple [python]

description: Changing outputs into tuple [python]


code:
rd.fit(X, y)
re.predict_proba(X_test)

rawDescription: Using ranking data in Logistic Regression


code:
import re
with open('fileA.txt') as A:
    A_content=[x.strip() for x in A]
with open('fileB.txt') as B:
    B_content=[x.strip() for x in B]
output=[]
for line_A in A_content:
    for line_B in B_content:
        #do whatever formatting you need on the text,
        # I am just surrounding it with *'s here

        replace = "**" + line_B + "**"

        #use re.sub,
        # details here: https://docs.python.org/2/library/re.html#re.sub

        line_A = re.sub(line_B, replace , line_A)
    #I am adding everything to the output array but you can check if it is
    # different from the initial content. I leave that for you to do
    output.append(line_A)

rawDescription: Match rows between two files and mark the matched strings


code: ['http://EEE', 'http://EKK']

rawDescription: Data from XML to Python list

description: Data from XML to Python list


code:
from multiprocessing import Pool
p = Pool(5)
def f(x):
     return x*x
p.map(f, [1,2,3])

rawDescription: Anything behind 'if __name__ == "__main__":' not executing


code: re.split(r': | - | -|- ', string, maxsplit=1)

rawDescription: Python - defining string split delimiter?


code:
def function(astring):
  return eval(astring)

rawDescription: Function internally using exec(astring) with a variable definition inside astring can not return the variable in python 3


code:
@register.inclusion_tag('pages/tags/menu.html')
def get_pagestatiques_structured(cat=None, template_name='pages/tags/menu.html'):
    category = Categorie.objects.all().get(slug=cat)
    subcategories = Categorie.objects.all().filter(parent=category.id)
    return locals()

rawDescription: Django-CMS: Apps with nested pages

description: Django-CMS: Apps with nested pages


code:
class Thing(object):
    ...

rawDescription: How to extend Python class init

description: Extend Python class init


code:
text = """
G J T P B A V K U V L V
M N Q H S G M N T C E E
Y H I J S G Q E N Y C W
G S K M G H C B M U T H
R A T V M N V D G V U T
E P G U E A B P W Q R T
T J C I D D R Q T E E C
U P C I S E N G B U O B
P S J C I V N F O U N N
M P R O J E C T R R A M
O H Q T P P D S H A P G
C O W U K Q E G I J M S"""

#cleans the input puzzleBoard
text = text.replace(' ', '').strip()
#gets the width and height of the puzzleboard
width = len(text.splitlines()[0])
text = text.replace('\n', '')
height = len(text) / width

#a dictionary storing the human readable directions
directions={0:'NW',1:'N',2:'NE',3:'W',4:'',5:'E',6:'SW',7:'S',8:'SE'}

#tries to find a word in a text
#returns x,y of the first character and the orientation of the word
def find_word(text, word):
    pos = 0
    while pos != -1:
        pos = text.find(word[0], pos)
        if pos > -1:
            for ori in [0,1,2,3,5,6,7,8]:
                found = True
                i = 0
                x = pos % width
                y = pos // height

                while found:
                    i += 1
                    if i == len(word) and found:
                        return (pos % width, pos // height, directions[ori])
                    #moves x,y in the selected direction
                    x += ori % 3 - 1
                    y += ori // 3 - 1
                    if x < width and y < height and x > -1 and y > -1:
                        found = text[width * y + x] == word[i]
                    else:
                        found = False
            pos += 1
    #nothing found
    return(-1, -1, directions[4])

rawDescription: Recursively search

description: Recursively search


code:
executor = ThreadPoolExecutor(2)

async def download(url):
    response = await loop.run_in_executor(executor, requests.get, url)
    return response.text

rawDescription: When to use and when not to use Python 3.5 `await` ?


rawDescription: Using MongoDB as a persistent Hashtable

description: Using MongoDB as a persistent Hashtable


code:
lst = [i for i in range(11)]
lst
_13

rawDescription: Programmatically get current Ipython notebook cell output?


rawDescription: Numpy array values changed without being aksed?


code:
from itertools import chain

list(chain.from_iterable([-x,x+1] for x in range(0,20,5)))

rawDescription: Map Python list element to multiple elements, avoiding nested lists


code:
from django.test.runner import DiscoverRunner
from django.db import transaction

class ExistingDBTestRunner(DiscoverRunner):

    def run_tests(self, test_labels, extra_tests=None, **kwargs):
        self.setup_test_environment()
        suite = self.build_suite(test_labels, extra_tests)
        #old_config = self.setup_databases()
        result = self.run_suite(suite)
        #self.teardown_databases(old_config)
        self.teardown_test_environment()
        return self.suite_result(suite, result)

rawDescription: Run Unittest On Main Django Database

description: Run Unittest On Main Django Database


code:
gdb.execute("set logging on")
gdb.execute("set logging file gdbout")
gdb.execute("set pagination off")
gdb.events.stop.connect(event_handler)

rawDescription: Continue after SIGNAL with a python script in gdb


code:
from collections import Counter

date_counts = Counter(d['date'] for d in xs)
most_common = {'date': date_counts.most_common(1)[0][0]}

rawDescription: python: get the most frequent value in a list of dictionaries

description: Python: get the most frequent value in a list of dictionaries


code:
def main():
    sound = get_sound()
    key = find_key()
    make_video(sound, key)

rawDescription: How to assign values returned from a function to another function

description: Assign values returned from a function to another function


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self, rows, columns):
        QtGui.QWidget.__init__(self)
        self.table = QtGui.QTableWidget(rows, columns, self)
        for column in range(columns):
            for row in range(rows):
                item = QtGui.QTableWidgetItem('Text%d' % row)
                if row % 2:
                    item.setFlags(QtCore.Qt.ItemIsUserCheckable |
                                  QtCore.Qt.ItemIsEnabled)
                    item.setCheckState(QtCore.Qt.Unchecked)
                self.table.setItem(row, column, item)
        self.table.itemClicked.connect(self.handleItemClicked)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.table)
        self._list = []

    def handleItemClicked(self, item):
        if item.checkState() == QtCore.Qt.Checked:
            print('"%s" Checked' % item.text())
            self._list.append(item.row())
            print(self._list)
        else:
            print('"%s" Clicked' % item.text())

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window(6, 3)
    window.resize(350, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: PyQt allign checkbox and put it in every row


code:
from werkzeug.contrib.cache import SimpleCache

class Cache(object):
    cache = SimpleCache(threshold = 1000, default_timeout = 3600)

    @classmethod
    def get(cls, key = None):
        return cls.cache.get(key)
    @classmethod
    def delete(cls, key = None):
        return cls.cache.delete(key)
    @classmethod
    def set(cls, key = None, value = None, timeout = 0):
        if timeout:
            return cls.cache.set(key, value, timeout = timeout)
        else:
            return cls.cache.set(key, value)
    @classmethod
    def clear(cls):
        return cls.cache.clear()

rawDescription: How to execute a block of code only once in flask?

description: Execute a block of code only once in flask


code: MagicMock(data={'points': [(0,1), (2,3), (4,5)]}, x_coords=HoldsData.__dict__['x_coords'])

rawDescription: Mocking a class's construction

description: Mocking a class's construction


rawDescription: Can't get this scrollbar to work with Text widet in Tkinter?


code:
robjects.r['d'][0]
robjects.r['d'][1]

rawDescription: Loading .RData files into Python

description: Loading .RData files into Python


code:
def floateq(a, b, tolerance=0.00000001):
    return abs(a-b) < tolerance

rawDescription: How do I get a whole number as a result for a cube root?

description: Get a whole number as a result for a cube root


code:
def transformed(it):
    it = iter(it)
    for char in it:
            if char.isalpha():
                    yield ord(char) - ord("a")
list(transformed("hello, world"))

rawDescription: Txt file substitution in Python

description: Txt file substitution in Python


rawDescription: partial word search with haystack/elasticsearch

description: Partial word search with haystack/elasticsearch


rawDescription: Selenium WebDriver - Disable Native Events (Enable Synthesized Events)


code: db.arachnid.update({'label': 'binomialAuthority'}, {'$set': dict([('classification.' + key, value) for key, value in data.items()])}, multi=True)

rawDescription: mongodb python Updating a subfield with a condition

description: Mongodb python Updating a subfield with a condition


code:
df_subset = df.loc[:, df.columns.str.contains('bid')]
df_subset[df_subset != 0].mean(axis=1)

rawDescription: Conditional dataframe calculations based on a columns suffix


code: fig, (ax1, ax2, ax3, ax4) = plt.subplots(nrows=2, ncols=2)

rawDescription: How to aggregate plots into figure with subplots

description: Aggregate plots into figure with subplots


code:
def get(self, request, *args, **kwargs):
    user = User.objects.get(username=request.user.username)
    beac_data = user.get_profile().owned_beacons.all()

    return render(request, self.template_name, {
        'form': self.form,
        'location': location,
        'beac_data': beac_data
    })

rawDescription: Iterating through database objects and rendering them to the template


code:
dummytuple = collision_list[numbers[tiles[int(tile)]]]
collision_list[numbers[tiles[int(tile)]]] = dummytuple, tiles[int(tile)].rect

rawDescription: Add object to existing value in dictionary


rawDescription: Looping between different lists in python


rawDescription: With the Python Imaging Library (PIL), how does one compose an image with an alpha channel over another image?


code:
json=open('file.json')

data = json.load(json)

rawDescription: multiple Json objects in one file extract by python

description: Multiple Json objects in one file extract by python


rawDescription: Simple Django request and response

description: Simple Django request and response


rawDescription: Optimising string generate and test

description: Optimising string generate and test


code:
import struct
x=(65,222,102,102)
struct.unpack('>L',struct.pack('4B',*x))[0]

rawDescription: Little bit complicated hex to decimal

description: Little bit complicated hex to decimal


code:
unique = set([ 'one', 'two', 'two'])
unique.add('three')

# unique now contains {'one', 'two', 'three'}

rawDescription: Counting the number of unique words in a list


code:
# ----- test classes -----
class Event:
    def __init__(self):
        self.funcs = []

    def bind(self, func):
        self.funcs.append(func)

    def __call__(self, *args, **kwargs):
        message = type('EventMessage', (), kwargs)
        for func in self.funcs:
            func(message)

# ----- implementation -----

class BindFunction:
    def __init__(self, func):
        self.func = func
        self.event = Event()

    def __call__(self, *args, **kwargs):
        out = self.func(*args, **kwargs)
        self.event(source=None)
        return out

    def bind(self, func):
        self.event.bind(func)

class BindMethod(BindFunction):
    def __init__(self, instance, func):
        super().__init__(func)
        self.instance = instance

    def __call__(self, *args, **kwargs):
        out = self.func(self.instance, *args, **kwargs)
        self.event(source=self.instance)
        return out

class Descriptor(BindFunction):
    methods = {}

    def __get__(self, instance, owner):
        if not instance in Descriptor.methods:
            Descriptor.methods[instance] = BindMethod(instance, self.func)
        return Descriptor.methods[instance]

def bindable(func):
    return Descriptor(func)

# ----- usage -----
class list:
    def __init__(self, seq=()):
        self.__list = [el for el in seq]

    @bindable
    def append(self, p_object):
        self.__list.append(p_object)

    def __str__(self):
        return str(self.__list)

@bindable
def x():
    print('calling x')

# ----- tests -----

def f (event):
    print('calling f')
    print('source type: %s' % type(event.source))

def g (event):
    print('calling g')
    print('source type: %s' % type(event.source))

a = list()
b = list()

a.append.bind(f)
b.append.bind(g)

a.append(5)
print(a)

b.append(6)
print(b)

print('----')

x.bind(f)
x()

rawDescription: Python 3 bound methods subscription

description: Python 3 bound methods subscription


code:
env = Environment()
# Builds sub/foo from sub/foo.c
env.Program(target = 'foo', source = 'foo.c')

SConscript('dir/SConscript')

rawDescription: Creating a Hierarchical Build with SCons


code:
from twisted.application import service, internet

site = SpellingSite()
application = service.Application('WebSpell')
# attach the service to its parent application
service_collection = service.IServiceCollection(application)
internet.TCPServer(PORT, site).setServiceParent(service_collection)

rawDescription: Python, Twisted, Django, reactor.run() causing problem


code:
import ftplib
ftplib

rawDescription: Where is builtins module located?

description: Where is builtins module located


code:
df
df['Sentence'].str.count(pat='to')

rawDescription: Pandas add column to df based on list of regex patterns


code: a * b + a

rawDescription: How to perform arithmetic on the same line as a augmented assignment in Python 3.x.x?

description: Perform arithmetic on the same line as a augmented assignment in Python 3.x.x


code:
def view(request) :
  msg = "& == & in HTML"

rawDescription: Django Double Escaping Quotes etc

description: Django Double Escaping Quotes etc


rawDescription: How to launch a couple of python scripts from a first python script and then terminate them all at once?

description: Launch a couple of python scripts from a first python script and then terminate them all at once


code:
PASSWORD_HASHERS = (
    'django.contrib.auth.hashers.PBKDF2PasswordHasher',
    'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
    'django.contrib.auth.hashers.BCryptPasswordHasher',
    'django.contrib.auth.hashers.SHA1PasswordHasher',
    'django.contrib.auth.hashers.MD5PasswordHasher',
    'django.contrib.auth.hashers.CryptPasswordHasher'
)

rawDescription: Django make_password too slow for creating large list of users programatically


rawDescription: Adaptable descriptor in Python

description: Adaptable descriptor in Python


code: icmp[icmptype] != icmp-echo and icmp[icmptype] != icmp-echoreply

rawDescription: Filter options for sniff function in scapy


code:
import sys
import Tkinter as tk
E=tk.E
W=tk.W
N=tk.N
S=tk.S
def main():
    app = App()
    app.master.title("Sample application")
    app.mainloop()

class App(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid(sticky=N+S+E+W)

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

        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)
        self.__createWidgets()

    def __createWidgets(self):
        self.f1 = tk.Frame(self, height=100, width=200, bg='green')
        self.f1.grid(row=0, sticky=E+W)

        self.f2 = myTestFrame(self, bg='yellow', height=100, width=200)

        self.f3 = tk.Frame( self, bg = "cyan", height = 100, width = 200)
        self.f3.grid(row=2, sticky=E+W)

        self.quitButton = tk.Button(self, text="Quit", command=self.quit)
        self.quitButton.grid(row=4, column=0, sticky=E+W)

class myTestFrame( tk.Frame ):
    def __init__(self, parent, cnf={}, **kw):
        tk.Frame.__init__(self, parent, cnf, **kw)
        self.grid(row=1, sticky=N+S+E+W)
        self.rowconfigure(0, weight=1)
        self.columnconfigure(0, weight=1)
        self.myText = tk.Text(self)
        self.myText.grid(row=0, sticky=N+S+E+W)

if __name__ == "__main__":
    main()

rawDescription: Python Classes in Tkinter's Grid Manager


code:
def replace_with_hash(match):
    return 'HASH({})'.format(_hash(match.group(2)))

new_line = re.sub(r'HASH\((["\'])(.*?)\1\)', replace_with_hash, line)

rawDescription: Getting the same sha1 hash with all strings


code: float(sum(len(w)*c for w,c in counts.iteritems())) / len(filtered)

rawDescription: real word count in NLTK

description: Real word count in NLTK


rawDescription: Capitalize doesn't work on special characters - Python


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

# Some fake data
timeDate = np.arange(256)
Y = timeDate * 1.1 + 2
V = timeDate * 3 + 1

# Select the color map named rainbow
cmap = cm.get_cmap(name='rainbow')

# Plot each vector with a different color from the colormap.
for ind, (t, y, v) in enumerate(zip(timeDate, Y, V)):
    plt.vlines(t,y,v ,color = cmap(ind))

plt.show()

rawDescription: Plotting 'vectors' with different colors in matplotlib


code:
z = np.array([1+2j, -3+4j, 5.0j], dtype=np.complex64)
lib.foo(z, z.size)

rawDescription: How to interface a NumPy complex array with C function using ctypes?

description: Interface a NumPy complex array with C function using ctypes


code:
def print_it(person, consolidated_ranges, fmt):
    for (s, e) in consolidated_ranges:
        print(person, s.strftime(fmt), e.strftime(fmt))

rawDescription: How to combine records based on date using python connected components?

description: Combine records based on date using python connected components


rawDescription: How to handle commands containing "-" in python sh module?

description: Handle commands containing "-" in python sh module


code:
from functools import wraps

from django.db import transaction
from mock import patch

def rollback_db_changes(func):
    """Decorate a function so that it will be rolled back once completed."""
    @wraps(func)
    @transaction.commit_manually
    def new_f(*args, **kwargs):
        def fake_commit(using=None):
            # Don't properly commit the transaction, so we can roll it back
            transaction.set_clean(using)
        patcher = patch('django.db.transaction.commit', fake_commit)
        patcher.start()
        try:
            return func(*args, **kwargs)
        finally:
            patcher.stop()
            transaction.rollback()
    return new_f

rawDescription: How can I clean up database changes made in django-nose test functions?

description: Clean up database changes made in django-nose test functions


rawDescription: print out a randint and append it to a list, then loop over and print a totaly different list

description: Print out a randint and append it to a list, then loop over and print a totaly different list


code: ['traffic', 'apple', 'sample']

rawDescription: How to write Regex for extracting tags?

description: Write Regex for extracting tags


code:
for obj in [x]:
    A.obj = obj

rawDescription: Creating a variable inside of a for loop


code:
import scipy.stats as ss
import numpy as np
import matplotlib.pyplot as plt
alpha, loc, beta=5, 100, 22
data=ss.gamma.rvs(alpha,loc=loc,scale=beta,size=5000)
myHist = plt.hist(data, 100, normed=True)
rv = ss.gamma(alpha,loc,beta)
x = np.linspace(0,600)
h = plt.plot(x, rv.pdf(x), lw=2)
plt.show()

rawDescription: python: plotting a histogram with a function line on top

description: Python: plotting a histogram with a function line on top


code:
a = 1       # assign 1 to a
b = a+2     # assign 3 to b, leave a at 1

rawDescription: Why are integers immutable in Python?

description: Why are integers immutable in Python


code:
try:
    int(5) + str(5)
except:
    pass

rawDescription: Python ignore \x00\x00\x00\x00

description: Python ignore \x00\x00\x00\x00


rawDescription: Regex Expression with special charachters


code:
import math
math.sqrt(100)==100**0.5

rawDescription: isPrime Function for Python Language

description: IsPrime Function for Python Language


rawDescription: Find all delimiters next to substring in string and replace in python


rawDescription: Python: Get relative path from comparing two absolute paths


code:
# user input in user_input
new_list = [item if item != user_input else "yes" for item in old_list]

rawDescription: Changing a string in a list of strings

description: Changing a string in a list of strings


code:
class BaseHandler(webapp.RequestHandler):
    def some_function(self):
        if data['user'].new_user and not self.request.path == '/main/new':
            self.redirect('/main/new')
            return False
        else:
            return True

class Dashboard(BaseHandler):
    def get(self):
        if not self.some_function():
            self.response.out.write('Some output here')

rawDescription: How can I kill off a Python web app on GAE early following a redirect?

description: Kill off a Python web app on GAE early following a redirect


code:
country = session.query(Country).filter_by(name='Spain').one()
new_user = User(name='Johnny', country=country)

rawDescription: SQLAlchemy ORM Insertion based on related object


rawDescription: How to recognize whether a script is running on a tty?

description: Recognize whether a script is running on a tty


code: dict1.update((k, dict2[k]) for k in set(dict2).intersection(dict1))

rawDescription: Update dict without adding new keys?

description: Update dict without adding new keys


code: x * y[..., np.newaxis]

rawDescription: Adding and multiplying columns of a numpy array with another array


code:
from bs4 import BeautifulSoup
import  requests
url = "http://espn.go.com/mlb/schedule"

soup = BeautifulSoup(requests.get(url).content)

table = soup.select_one("table.schedule.has-team-logos")

print([a["title"] for a in table.select("a.team-name abbr")])

rawDescription: How to get a specific tag attribute text in Python with BeautifulSoup?

description: Get a specific tag attribute text in Python with BeautifulSoup


code:
f_matrix = numpy.matrix(f)
D = f_matrix.T * f_matrix

rawDescription: Vectorized assignment of a 2-dimensional array


code: data = pandas.read_csv('filename.txt', delim_whitespace=True, index_col=0)

rawDescription: loading a table in numpy as in R?

description: Loading a table in numpy as in R


code: np.subtract(b[:, :, np.newaxis], c, a)

rawDescription: Memory growth with broadcast operations in NumPy


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.text = tk.Text(self, wrap=None)
        self.vsb = tk.Scrollbar(self, command=self.text.yview, orient="vertical")
        self.text.configure(yscrollcommand=self.vsb.set)

        self.vsb.pack(side="right", fill="y")
        self.text.pack(side="left", fill="both", expand=True)

        self.text.tag_configure("even", background="#e0e0e0")
        self.text.tag_configure("odd", background="#ffffff")

        with open(__file__, "r") as f:
            tag = "odd"
            for line in f.readlines():
                self.text.insert("end", line, tag)
                tag = "even" if tag == "odd" else "odd"

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

rawDescription: Changing background color for every other line of text in a tkinter text box widget


code:
import Tkinter as tk
import TkMessageBox as messagebox

board = [ [None]*10 for _ in range(10) ]

counter = 0
root = tk.Tk()

def check_board():
    freespaces = 0
    redspaces = 0
    greenspaces = 0
    for i,row in enumerate(board):
        for j,column in enumerate(row):
            if board[i][j] == "red":
                redspaces += 1
            elif board[i][j] == "green":
                greenspaces += 1
            elif board[i][j] == None:
                freespaces += 1

    if freespaces == 0:
        if greenspaces > redspaces:
            winner = "green"
        elif greenspaces < redspaces:
            winner = "red"
        else:
            winner = "draw"

        if winner != "draw":
            messagebox.showinfo("Game Over!",winner+" wins!")
        else:
            messagebox.showinfo("Game Over!","The game was a draw!")

def on_click(i,j,event):
    global counter
    if counter < 100:
        if board[i][j] == None:
            color = "green" if counter%2 else "red"
            enemycolor = "red" if counter%2 else "green"
            event.widget.config(bg=color)
            board[i][j] = color
            for k in range(-1,2):
                for l in range(-1,2):
                    try:
                        if board[i+k][j+l] == enemycolor:
                            board[i+k][j+l] = color
                    except IndexError:
                        pass
            counter += 1
            global gameframe
            gameframe.destroy()
            redraw()
            root.wm_title(enemycolor+"'s turn")
        else:
            messagebox.showinfo("Alert","This square is already occupied!")
        check_board()

def redraw():
    global gameframe
    gameframe = tk.Frame(root)
    gameframe.pack()

    for i,row in enumerate(board):

        for j,column in enumerate(row):
            name = str(i)+str(j)
            L = tk.Label(gameframe,text='    ',bg= "grey" if board[i][j] == None else board[i][j])
            L.grid(row=i,column=j,padx='3',pady='3')
            L.bind('<Button-1>',lambda e,i=i,j=j:on_click(i,j,e))

redraw()
root.mainloop()

rawDescription: Python board game with tkinter

description: Python board game with tkinter


code: print("Randy's phone # is %s" % people['Randy']['phone'])

rawDescription: Accessing nested dictionary items in Python


rawDescription: Re-shape pandas dataframe stack/unstack

description: Re-shape pandas dataframe stack/unstack


code:
def main():
    section = (input('What section are you inputing ticket numbers for? '))
    if section == 'a' or 'A': # You mean if section in 'Aa':
        limit = 300
        cost = 20
    if section == 'b' or 'B': # You mean elif section in 'Bb':
        limit = 500
        cost = 15
    if section == 'c' or 'C': # You mean elif section in 'Cc':
        limit = 200
        cost = 10
    ticketSold = getTickets(section, limit)
    calcIncome(ticketSold, cost)

def getTickets(section, limit): # Doesn't actually use section.
    ticketSold = int(input('How many tickets were sold? '))
    return int(ticketSold) # Everything after this is dead code.
    if ticketsValid(ticketSold, limit): # Even if this did get called,
        return ticketsValid # What should it return if the tickets aren't valid? 0?

rawDescription: How do I repeat this and save the result for each section?

description: Repeat this and save the result for each section


code:
import math
number = 0.5 * math.floor(2.0 * number)

rawDescription: Python: weird floating-point math results


code:
notebook = gtk.Notebook
def create_tab():
    page = gtk.Label( "THis is a page")
    page.show()
    tab = gtk.HBox()#The custom tab-label widget
    tab_label = gtk.Label( "Tab")
    tab_label.show()
    tab.pack_start( tab_label)
    tab_close = CloseButton(page)#pass a reference to page

    tab_close.connect( 'clicked', destroy_tab )
    tab_close.show()
    tab.pack_end( tab_close)
    tab.show()

    notebook.append_page(page, tab)

def destroy_tab( widget, data=None):
    page_num = notebook.page_num( widget.widget_ref )
    notebook.remove_page( page_num )
    widget.destroy()

rawDescription: pygtk notebook page close memory leak

description: Pygtk notebook page close memory leak


code:
a
tolerance = 2
R,C = np.triu_indices(a.shape[0],1)
I
G

rawDescription: Finding duplicate matrices in Python?

description: Finding duplicate matrices in Python


code:
while absolute_avg > calculated_std:
    ...

rawDescription: python while loop iteration

description: Python while loop iteration


rawDescription: Sorting dictionary using operator.itemgetter


code:
def whois(k,  i):
    k = k[i]
    who = check_output(['whois',  k], universal_newlines=True)
    return  dict(map(str.strip,ele.split(":",1)) for ele in re.findall(r'^\w+:\s+.*', who, re.M))

rawDescription: re.split return None in function but normaly works OK

description: Re.split return None in function but normaly works OK


code:
#Defines builder and glade file.#
builder = gtk.Builder()
builder.add_from_file("GUI.glade")

#Gets the main widow and shows it.#
main_Window = builder.get_object("blasterbot_mainwindow")
main_Window.show_all()
#Gets some buttons.#
deploy_button = builder.get_object("tool_deploy_button")

#Starts the thread and the main loop.#
thread = T()
def bot_thread(*args):
    if not thread.is_alive():
        thread.start()
        thread.loop.set()
        #deploy_button.set_label('Disconnect') - Old Sutff
        return

    if thread.loop.is_set():
        thread.loop.clear()
        #deploy_button.set_label('Connect') - Old Sutff
    else:
        thread.loop.set()
        #deploy_button.set_label('Disconnect') - Old Sutff

rawDescription: Making a irc bot with a gui. Dificulties with desconecting on toggle button toggle


code:
from django.views.generic.simple import redirect_to

urlpatterns = patterns('',
    (r'^one/$', redirect_to, {'url': '/another/'}),

    #etc...
)

rawDescription: Python + Django page redirect

description: Python + Django page redirect


code:
from pprint import pprint
import re

import requests

url = 'http://www.heteropharmacy.com/jScript/myScript.js'
with requests.Session() as session:
    response = session.get(url)

    pattern = re.compile(r"states_arr\['(\w+)'\]= new Array\((.*?)\);", re.MULTILINE | re.DOTALL)

    results = {state: [item.strip()[1:] for item in pharmacies.split('",')]
               for state, pharmacies in pattern.findall(response.content)}

    pprint(results)

rawDescription: Scraping data from a JavaScript code that is present inside an HTML file


code:
import collections
def top5_words(text):
    counts = collections.Counter(text.lower().split())
    return [elem for elem, _ in sorted(counts.most_common(),key=lambda x:(-x[1], x[0]))[:5]]
top5_words("""As the title says, I need to write a code that returns a list of 5 words (from an input string) that have the highest frequency. This is what I have so far""")

rawDescription: Python - Return top 5 words with highest frequency


code:
list(chunk((i for i in range(3)), 3))
list(chunk((i for i in range(6)), 3))
list(chunk((i for i in range(8)), 3))

rawDescription: python: is there a library function for chunking an input stream?

description: Python: is there a library function for chunking an input stream


code: soup.select('.r a')

rawDescription: Not Getting proper links from google search results using mechanize and Beautifulsoup


code:
karta = []
for i in range(10):
    karta.append(karte())

rawDescription: python how to make dynamic object name

description: Python how to make dynamic object name


code:
from cStringIO import StringIO

def f4(foo=foo):
    stri = StringIO(foo)
    while True:
        nl = stri.readline()
        if nl == '': break
        yield nl.strip('\n')

rawDescription: Iterate over the lines of a string

description: Iterate over the lines of a string


code: df = pd.concat([df,pd.DataFrame(columns = list(col_add))])

rawDescription: Pandas append list to list of column names


rawDescription: Truth tables in python using sympy

description: Truth tables in python using sympy


rawDescription: dealing with dimensions in scikit-learn tree.decisiontreeclassifier

description: Dealing with dimensions in scikit-learn tree.decisiontreeclassifier


code:
res = s.groupby(s.index).apply(f)
res

rawDescription: Python: indexing pandas series by datetime


code: received: HELLO

rawDescription: How to create channel with socket in Python

description: Create channel with socket in Python


code:
from collections import defaultdict

keyed = defaultdict(int)

for d in (d0, d1, d2):
    keyed[(d['a'], d['b'])] += d['c']

dictionaries = [{'a': a, 'b': b, 'c': c} for (a, b), c in keyed.items()]

rawDescription: "Adding" dictionaries in python if some (key, value) pairs match


code:
class MyItem(Item):
    date = Field()
    home_team = Field()
    away_team = Field()

rawDescription: How to scrape contents from multiple tables in a webpage

description: Scrape contents from multiple tables in a webpage


code: scipy.toimage(image, cmin=0, cmax=255, mode='I').save("image.png")

rawDescription: Save image without rescaling

description: Save image without rescaling


code:
import argparse
from envdefault import EnvDefault

parser=argparse.ArgumentParser()
parser.add_argument(
    "-u", "--url", action=EnvDefault, envvar='URL',
    help="Specify the URL to process (can also be specified using URL environment variable)")
args=parser.parse_args()

rawDescription: Setting options from environment variables when using argparse


rawDescription: join - duplicates in nested lists

description: Join - duplicates in nested lists


code:
xs = [ 1 ]
for x in xs:
    xs.append(x+1)

rawDescription: Python 2.7 delete items form list while looping


code: np.insert(F, insert_indices, values).reshape(A.shape[0], A.shape[1]+1)

rawDescription: Efficent insertion of not aligned elements in a numpy array


code:
from collections import namedtuple

A = namedtuple("A", ["x", "y"])
a = A(Foo(), y=Foo())       # can use positional or keyword arguments

a.x.DoFoo()      # this still works!
a.x = "something else"      # but this will raise an error

rawDescription: Object trees in Python

description: Object trees in Python


code:
df = pd.DataFrame([[np.arange(10000)]])
df  # Note: pandas printing is different!!
s = StringIO()
df.to_csv(s)
s.getvalue()  # ellipsis

rawDescription: Pandas to_csv always substitute long numpy.ndarray with ellipsis


code: R[i, j]

rawDescription: Explanation of python code snippet >>numpy.nonzero(row == max(row))[0][0]<< from a script using numpy


code: word_list = [word.rstrip() for word in open("words.txt","r")]

rawDescription: Where should I declare a list of 5,000+ words?


rawDescription: python regular expression across multiple lines

description: Python regular expression across multiple lines


rawDescription: Regarding ascii and python packing

description: Regarding ascii and python packing


rawDescription: in Python, how to convert list of float numbers to string with certain format?

description: In Python, how to convert list of float numbers to string with certain format


code:
import csv
from itertools import groupby

with open('state.csv', 'rb') as f:
    id2name = dict(csv.reader(f))

with open('csv_file.csv', 'rb') as ifile, open('output.csv', 'wb') as ofile:
    reader = csv.reader(ifile)
    next(reader)  # skip the header
    writer = csv.writer(ofile)

    # Group by the state_id, which is the first field (record[0])
    group_by_state_id = groupby(reader, lambda record: record[0])
    for state_id, record_group in group_by_state_id:
        state = id2name[state_id]
        values = [value for state_id, year, value in record_group]
        writer.writerow([state] + values)

rawDescription: How to map state code from one csv file to state name in another csv file in python?

description: Map state code from one csv file to state name in another csv file in python


rawDescription: Converting an open curve to a list of ordered pixels: a Python test code with numpy


code:
import numpy as np
import pandas as pd

#create sample data
nrows = 500000
ncols = 21

nones = int(70e6)
ntwos = int(20e6)
nthrees = int(10e6)

rint = np.random.randint

counts = np.zeros((nrows, ncols), dtype=np.int8)
counts[rint(0, nrows, nones), rint(0, ncols, nones)] = 1
counts[rint(0, nrows, ntwos), rint(0, ncols, ntwos)] = 2
counts[rint(0, nrows, nthrees), rint(0, ncols, nthrees)] = 3

columns = ["c%03d" % i for i in range(ncols)]
index = ["%014d" % i for i in range(nrows)]

df = pd.DataFrame(counts, index=index, columns=columns)

rawDescription: Generating Rows from Values in Several Columns


code:
a = numpy.arange(2 * 3 * 4 * 5).reshape(2, 3, 4, 5)
mask = a[0,...] > 29
numpy.ma.MaskedArray(a, mask)

rawDescription: Appending 3d array into 4d array, the 4th dimension being number of 3D arrays


code:
class C():
  def demo(): pass

C.demo

rawDescription: How to decorate (monkeypatch...) a Python class with methods from another class?

description: Decorate (monkeypatch...) a Python class with methods from another class


code:
import win32api
win32api.ShellExecute(0,'open','mailto:',None,None ,0)

rawDescription: Python: launch default mail client on the system


code:
def get_neighbors(word, choices):
    return set(x for x in choices if x[0] == word[-1])

def longest_path_from(word, choices):
    choices = choices - set([word])
    neighbors = get_neighbors(word, choices)

    if neighbors:
        paths = (longest_path_from(w, choices) for w in neighbors)
        max_path = max(paths, key=len)
    else:
        max_path = []

    return [word] + max_path

def longest_path(choices):
    return max((longest_path_from(w, choices) for w in choices), key=len)

rawDescription: Python word game. Last letter of first word == first letter of second word. Find longest possible sequence of words


code:
def is_digital(offers):
    return any(offer.get('digital') for offer in offers)

rawDescription: Reduce a list using lambda

description: Reduce a list using lambda


rawDescription: Splitting a string where it switches between numeric and alphabetic characters


rawDescription: matching between two columns and taking value from another in pandas

description: Matching between two columns and taking value from another in pandas


rawDescription: sort dictionary by multiple keys and values are string,python

description: Sort dictionary by multiple keys and values are string,python


code:
df_m = pd.melt(df, id_vars=["State", "Item #"], var_name="Value")
df_m["rank"] = df_m.groupby("State")["value"].rank(ascending=False)
df_m["top"] = rank <= 5
df_m.groupby(["State", "Item #"], as_index=False)["top"].sum()

rawDescription: How to rank values in different columns based on a criteria in Python (transferring Excel calculations to Python)?

description: Rank values in different columns based on a criteria in Python (transferring Excel calculations to Python)


code: re.search(r'%s$' % name1, name2, re.IGNORECASE)

rawDescription: re.search() exact comparison at end of string

description: Re.search() exact comparison at end of string


code:
def group(elements, key_func):
    groups = {}
    for x in elements:
        key = key_func(x)
        if key in groups:
            groups[key].append(x)
        else:
            groups[key] = [x]
    return groups

rawDescription: Gather elements from list into lists of lists of equal elements?


rawDescription: Python - Safe Indexing with boolean

description: Python - Safe Indexing with boolean


code: pd.options.display.max_colwidth  # default is 50

rawDescription: How to configure display output in IPython pandas

description: Configure display output in IPython pandas