code:
def get_content_form(model_name):
    class DynamicContentForm(forms.ModelForm):
        parent = ModelTextField(queryset=Content.objects.all(), widget=JQueryAutocomplete(
                        source_url='%sjson/call_names.json' % NINJA_ADMIN_URL_PREFIX, jquery_opts = {'minLength': 2},
                        override_label='item.fields.call_name', override_value='item.fields.call_name'),
                        required=False)

        class Meta():
            model = get_ninja_type(model_name)
            widgets = {
                    'ninja_type': forms.widgets.HiddenInput(),
                }

        def clean_parent(self):
            call_name = self.cleaned_data['parent']
            if call_name:
                try:
                    parent = Content.objects.get(call_name=call_name)
                except Content.DoesNotExist:
                    raise forms.ValidationError("The call name '%s' doesn't exist. Choose another parent." % call_name)
                return parent
            else:
                return None
    return DynamicContentForm

rawDescription: Passing a Django Form Class variable to the nested class Meta, how?


code:
X, Y, K = np.meshgrid(x, y, k)
# sum over k after evaluating f_k
f = fk(X, Y, K).sum(axis=-1)

f.shape
# (100, 100)

rawDescription: Surface where height is a function of two functions, and a sum over the third


code: line.replace("ATOM", "1").replace("# ORB", " ")

rawDescription: Replacing a word in a text file with a value using python


code:
class Counter(collections.defaultdict):

    def __getattr__(self, name):
        return self[name]

rawDescription: Python: Cleaner ways to initialize

description: Python: Cleaner ways to initialize


rawDescription: Can't parse YAML correctly

description: Can't parse YAML correctly


code:
df = DataFrame(np.random.randn(10,2))
start=3
stop=4
df.iloc[(max(df.index.get_loc(start)-2,0)):min(df.index.get_loc(stop)+2,len(df))]

rawDescription: efficient way to find several rows above and below a subset of data

description: Efficient way to find several rows above and below a subset of data


rawDescription: Is LOGIN_REDIRECT_URL deprecated?

description: Is LOGIN_REDIRECT_URL deprecated


code:
a = numpy.arange(25).reshape((5, 5))
b = a.ravel()
b[0] = 55
a

rawDescription: How to flatten axes of a multidimensional array without making copies in NumPy?

description: Flatten axes of a multidimensional array without making copies in NumPy


rawDescription: How to find all the indices of all the elements in a 2d matrix using Python?

description: Find all the indices of all the elements in a 2d matrix using Python


code:
for char in usr_list[:]:  # this is the only part that changed; add [:] to make a copy
    if char in punctuation:
        usr_list.remove(char)

rawDescription: Loop to remove characters from list not working


code:
def validated_input(prompt, validate):
    valid_input = False
    while not valid_input:
        value = input(prompt)
        valid_input = validate(value)
    return value

rawDescription: How to redo an input if user enters invalid answer

description: Redo an input if user enters invalid answer


code:
drivers = {
    'David': 'Burger King',
    'Travis': 'Dr Pepper',
    # ...
}

rawDescription: Assignment: Python 3.3: add keys and values from dictionary to class


code: 8901088, u'Mayan Theatre'

rawDescription: Retrieving Venue Information with pylast and last.fm


code:
import commands
commands.getoutput('echo "foo." | swipl -q -f foo.pl')
x = commands.getoutput('echo "foo." | swipl -q -f foo.pl')
x

rawDescription: Python program calling prolog and print prolog output


code:
@restrict_attributes
class A(object):
    def __init__(self):
        with self.declare_attributes():
            self.a = 1
            self.b = 2
            self.c = 3

rawDescription: In Python, count the number of variables in a class or prevent adding new class variables


code:
from twisted.application.service import Application
from twisted.python.log import ILogObserver, FileLogObserver
from twisted.python.logfile import DailyLogFile

application = Application("myapp")
logfile = DailyLogFile("my.log", "/tmp")
application.setComponent(ILogObserver, FileLogObserver(logfile).emit)

rawDescription: How to format twisted logs?

description: Format twisted logs


code:
a = [1, 3, 1, 3, 3, 2, 4, 5]

def unit_percents(L1):
    ret = {}
    L = L1[:]
    sorted(L)
    if L:
        cur_count = 1
        for i in range(len(L)-1):
            cur_count+=1
            if L[i] != L[i+1]:
                ret[L[i]]=float(cur_count)/len(L)
                cur_count=1
        ret[L[-1]]=float(cur_count)/len(L)
    return ret

unit_percents(a)

rawDescription: Plotting data using percent unit

description: Plotting data using percent unit


rawDescription: print first paragraph in python

description: Print first paragraph in python


code:
open_file = Tkinter.Button(main_window, command=handle_file, padx=100, text="OPEN FILE")
open_file.pack()

rawDescription: python file dialog accessing file name

description: Python file dialog accessing file name


code:
class Created():
    def __init__(self, creator):
        self.parameter = self.creator.parameter

rawDescription: Can a class instance created by another class instance access the creator's members?


code:
def detect_runs_in_dict(d, n=3, searchval=0):
    return [uuid for uuid, val in d.items()
        if any(k == searchval and len(list(g)) >= n for k,g in groupby(val))]

rawDescription: Detect consecutive identical values in list


code:
list2 = []
for i in list:
    i = i.split(' ')
    i[1] = int(i[1])
    list2.append(i)

rawDescription: Paste list to an Excel file

description: Paste list to an Excel file


rawDescription: Concatenation of inner lists or ints

description: Concatenation of inner lists or ints


code: newlist = [v for i, v in enumerate(oldlist) if i not in removelist]

rawDescription: Remove multiple items from list in Python


code:
messages.success(request, "You're successfully logged in!")
return HttpResponseRedirect("/welcome/")

rawDescription: How to combine HttpResponseRedirect & render_to_response?

description: Combine HttpResponseRedirect & render_to_response


rawDescription: Convert a python list into function

description: Convert a python list into function


code:
from itertools import groupby

data = get_time_deltas(INFILE)
get_key = lambda x: int(x[0])  # function to get group key from data
bins = [(k, list(g)) for k, g in groupby(data, get_key)]

rawDescription: Grouping Messages by Time Intervals

description: Grouping Messages by Time Intervals


code:
x = x[x > 0.0]
y = y[x > 0.0]

plt.scatter(x, y)

rawDescription: Ignoring plotting data points of certain value


rawDescription: Selecting rows from numpy ndarray when groups are known


code:
if enter == "1":
    film=input("Please write a film name: ")
    database.write(film + "\n") #\n is the newline character
    database.close()

rawDescription: When I reopen the program is everything fades in txt file


code:
from PyQt4 import QtCore, QtGui
app = QtGui.QApplication([])

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__()
        names=['Zero','One','Two','Three','Four','Five','Six','Seven']
        self.setColumnCount(len(names))
        self.setHeaderLabels(names)
        item=QtGui.QTreeWidgetItem(names)
        self.addTopLevelItem(item)
        self.header().setStretchLastSection(False)
        self.header().setResizeMode(6, QtGui.QHeaderView.Stretch)
        self.resize(720,120)
        self.show()
tree=Tree()
sys.exit(app.exec_())

rawDescription: How to set last column header to a fixed size and maintain it

description: Set last column header to a fixed size and maintain it


rawDescription: Export Gmail using Python imaplib - text mangled with newline issues


rawDescription: How to transport " for remote execution?

description: Transport " for remote execution


code:
import csv

class DictReaderInsensitive(csv.DictReader):
    # This class overrides the csv.fieldnames property.
    # All fieldnames are without white space and in lower case

    @property
    def fieldnames(self):
        return [field.strip().lower() for field in super(DictReaderInsensitive, self).fieldnames]

    def __next__(self):
        # get the result from the original __next__, but store it in DictInsensitive

        dInsensitive = DictInsensitive()
        dOriginal = super(DictReaderInsensitive, self).__next__()

        # store all pairs from the old dict in the new, custom one
        for key, value in dOriginal.items():
            dInsensitive[key] = value

        return dInsensitive

class DictInsensitive(dict):
    # This class overrides the __getitem__ method to automatically strip() and lower() the input key

    def __getitem__(self, key):
        return dict.__getitem__(self, key.strip().lower())

rawDescription: Accessing csv header white space and case insensitive


code:
[(0.7897897, 'this is a foo bar sentence'),
 (0.325345, 'this is not really a foo bar')]

rawDescription: How do I remove element from a list of tuple if the 2nd item in each tuple is a duplicate?

description: Remove element from a list of tuple if the 2nd item in each tuple is a duplicate


code:
argv = '--conf-key-1 value1 --conf-key-2 value2'.split()
p = argparse.ArgumentParser()
args, extras = p.parse_known_args(argv)

def foo(astr):
    if astr.startswith('--conf-'):
        astr = astr[7:]
    astr = astr.replace('-','_')
    return astr

d = {foo(k):v for k,v in zip(extras[::2],extras[1::2])}
# {'key_1': 'value1', 'key_2': 'value2'}

rawDescription: Create variable key/value pairs with argparse (python)


code:
def __iter__(self):
    yield self.x
    yield self.y

rawDescription: python - cast a class to a tuple and "autobox" to a for loop

description: Python - cast a class to a tuple and "autobox" to a for loop


code:
seen = set()
imageFiles_new = []
for x in imageFiles:
    if x.md5 not in seen:
        imageFiles_new.append(x)
        seen.add(x.md5)
imageFiles = imageFiles_new

rawDescription: Eliminate Duplicates of Custom Datastructure


code:
function_dict = {1:func1, 2:func2, 3:func3, 4:func4, 5:func5, 6:func6,
                 7:func7, 8:func8, 9:func9, 10:func10, 11:func11}

possible_values = range(1,12)
selected_values = random.sample(possible_values,5)

for key in selected_values:
    function_dict[key]()

rawDescription: Call a different function based on a random number in python


code: session.query(Membership.user_id).filter(Membership.group_id == 3, Membership.joined_on.between(previous, now)).count()

rawDescription: make query ManyToMany in sqlalchemy?

description: Make query ManyToMany in sqlalchemy


rawDescription: MatPlotLib: Given a dataset of 3, graph the 2 and use the 3rd as a label


code:
from pyramid.i18n import TranslationStringFactory

myapp_domain = TranslationStringFactory(domain='myapp')

rawDescription: Pyramid TranslationString not working on json renderer


code:
# these are the tokens:
tokens = set(['Natural', 'Language', 'Processing', 'with', 'PythonNatural', 'Language', 'Processingwith', 'PythonNatural', 'Language', 'Processing', 'with', 'Python', 'Editor', ':', 'Production', 'Editor', ':', 'Copyeditor'])

# create a set containing the keywords
with open('keywords.txt', 'r') as keywords:
    keyset = set(keywords.read().split())

# write outputfile
with open('matches.txt', 'w') as matches:
    for word in keyset:
        if word in tokens:
            matches.write(word + '\n')

rawDescription: Python program to perform keyword matches for contents present in two files


code:
def foo():
    foo()

import pdb
pdb.run('foo()')

rawDescription: What does '*** Oldest frame' mean in ipdb?


code: os.system("python <path to .py file>")

rawDescription: Execute python files through code

description: Execute python files through code


code: df['group_indicator'] = df.group_id != df.group_id.shift(-1)

rawDescription: Select last observation per group

description: Select last observation per group


code:
run("foo", etc)               # Run
run("foo", etc, silent=True)  # RunSilent

rawDescription: Wrap a function in python supplying an additional boolean


rawDescription: Python: use the same class instance in multiple modules


code:
gd_client = gdata.contacts.client.ContactsClient('your-domain.com')
gd_client.auth_token = TokenFromOAuth2Creds(credentials)
xxx = gd_client.get_contacts()

rawDescription: Is it possible to use "Domain-wide Delegation of Authority" with gdata-python-client?


code: from fft import *

rawDescription: Mixing functions and subpackages in Python packages


code:
class FakeRestaurant(models.Model):
    place_ptr = models.PositiveIntegerField(db_column="place_ptr_id", primary_key=True)
    serves_hot_dogs = models.BooleanField()
    serves_pizza = models.BooleanField()

    class Meta:
        app_label = Restaurant._meta.app_label
        db_table = Restaurant._meta.db_table
        managed = False

rawDescription: Django model inheritance: Delete subclass keep superclass


code:
s1 = 'ABC_config.txt'
s2 = 'ABC_other.txt'
s1.split('_')[0] == s2.split('_')[0]

rawDescription: extracting string before specific mark

description: Extracting string before specific mark


code:
import os
from urlparse import urljoin

from django.conf import settings
from django.core.files.storage import FileSystemStorage

gen_files_storage = MyFileSystemStorage('generated/')

rawDescription: Django migrations and FileSystemStorage depending on settings


rawDescription: Modified time using os.stat in Python gets lower when copying files


code: os.system("/bin/bash -c 'grep -w 1 pattern <(tail -f mylogfile.log)'")

rawDescription: python 2.3 how to run a piped command

description: Python 2.3 how to run a piped command


rawDescription: Is there a significant overhead by using different versions of sha hashing (hashlib module)


code: all([sum(t.children) == t.parent for t in trees])

rawDescription: How do I test a sum tree?

description: Test a sum tree


code:
A
thresh = 10
np.where((A < thresh).all(0),-1,(A >= thresh).argmax(0))

rawDescription: Find the lowest non-masked point with numpy efficiently


code:
def firstel(self):
    return self.q[0]

rawDescription: Numpy array assignment inside class

description: Numpy array assignment inside class


code: value = tryconvert(value, None, parsedatetime, int)

rawDescription: String checking on multiple types

description: String checking on multiple types


code: lambda x, a: (x * a).sum() - 10

rawDescription: Scipy, optimize a function with argument dependent constraints


code:
class MyDict(dict):
    def __add__(self, other):
        """Overload the + operator."""
...

rawDescription: Accessing the values of a key

description: Accessing the values of a key


code:
for a, b in enumerate(results):
    for i in b:
        if isinstance(i, (int, float)) and i > highest:
            highest = i
            row = a
            total = sum(i for i in b if isinstance(i, (int, float)))

rawDescription: Ignore str in sum()

description: Ignore str in sum()


code:
class Foo(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self,y):
        self._x = y

rawDescription: What is the difference between __set__ and __setattr__ in Python and when should which be used?


code:
r = requests.get("http://orlando.craigslist.org/search/apa")
from bs4 import BeautifulSoup

html = r.content

soup = BeautifulSoup(html)
prices = [int(pr.text.strip("$")) for pr in soup.select("span.price")]

# link to next 100 results
nxt = soup.select_one("a.button.next")["href"]

# keep looping until we find a page with no next button
while nxt:
    url = "http://orlando.craigslist.org{}".format(nxt)
    r = requests.get(url)
    soup = BeautifulSoup(r.content)
    # extend prices to our list
    prices.extend([int(pr.text.strip("$")) for pr in soup.select("span.price")])
    nxt = soup.select_one("a.button.next")
    if nxt:
        nxt = nxt["href"]

rawDescription: web scrapping craigslist appartment prices in python not showing highest cost appartment

description: Web scrapping craigslist appartment prices in python not showing highest cost appartment


code:
def flatten(*seq):
    for item in seq:
        if isinstance(item, basestring):
            yield item
        else:
            try:
                it = iter(item)
            except TypeError:
                yield item
                it = None
            if it is not None:
                for obj in flatten(it):
                    yield obj

rawDescription: How to convert dumbo sequence file input to tab separated text

description: Convert dumbo sequence file input to tab separated text


code:
from pyspark.sql.functions import col

result = users_df.where(col("_id") == chosen_user).select(col("gender"))

rawDescription: Getting specific field from chosen Row in Pyspark DataFrame


code:
if "Short".lower() in description.lower():
    ...

rawDescription: Python lightweight case insensitive if "x" in variable


code: 'ab', 'Alex'

rawDescription: Targeting specific sub-elements when parsing XML with Python


code:
import operator
sorted_list_of_rows = sorted(zip(*my_list_of_columns), key = operator.itemgetter(2,3))
list_of_columns = list(zip(*sorted_list_of_rows))

rawDescription: Python 3: sort rows in 2D matrix, where columns are lists


code:
rdd = sc.parallelize(range(10))

pairs = rdd.cartesian(rdd).filter(lambda x: x[0] < x[1])
pairs.count()

## 45

rawDescription: Upper triangle of cartesian in spark for symmetric operations: `x*(x+1)//2` instead of `x**2`


code:
from Queue import Queue
from threading import Thread
from usercode import fetch_url
import logging
import requests
import time

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)

class SilencableHandler(logging.StreamHandler):

    def __init__(self, *args, **kwargs):
        self.silenced = False
        return super(SilencableHandler, self).__init__(*args, **kwargs)

    def emit(self, record):
        if not self.silenced:
            super(SilencableHandler, self).emit(record)

requests_logger = logging.getLogger('requests')
requests_logger.propagate = False
requests_handler = SilencableHandler()
requests_logger.addHandler(requests_handler)

class Silenced(object):

    def __init__(self, handler):
        self.handler = handler

    def __enter__(self):
        log.info("Silencing requests logger...")
        self.handler.acquire()
        self.handler.silenced = True
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.handler.silenced = False
        self.handler.release()
        log.info("Requests logger unsilenced.")

NUM_THREADS = 2
queue = Queue()

URLS = [
    'http://www.stackoverflow.com',
    'http://www.stackexchange.com',
    'http://www.serverfault.com',
    'http://www.superuser.com',
    'http://travel.stackexchange.com',
]

for i in range(NUM_THREADS):
    worker = Thread(target=fetch_url, args=(i, queue,))
    worker.setDaemon(True)
    worker.start()

for url in URLS:
    queue.put(url)

log.info('Starting long API request...')

with Silenced(requests_handler):
    time.sleep(5)
    requests.get('http://www.example.org/api')
    time.sleep(5)
    log.info('Done with long API request.')

queue.join()

rawDescription: Disable logging for a python module in one context but not another


code:
def leaf(value):
    return BinTree(value=value)

def branch(left, right):
    return BinTree(left=left, right=right)

rawDescription: Haskell equivalent of data constructors in Python?


code:
from applications.topo.models import Topo
t = Topo()
type(t)

rawDescription: Need to find if the given variable is an instance or class


code:
class MyApp(Flask):
    def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
        if (view_func is not None):
            view_func = set_session(view_func)
        return super(MyApp, self).add_url_rule(rule, endpoint,
                                               view_func, **options)

rawDescription: Is there a more efficient way to set a session variable for each view?


code: toeplitz(np.roll(r[::-1], 1), r)

rawDescription: Building a matrix of 'rolled' rows efficiently in Numpy


code: A._DEFAULT_DETAILS = 'test'

rawDescription: Mocking class constructor default parameters in Python


code:
while i != 0 :
        i += 1

rawDescription: Python making list

description: Python making list


code:
#!/usr/bin/env python
import ctypes
import numpy as np
from numpy.ctypeslib import ndpointer

libf = ctypes.cdll.LoadLibrary('/path/to/lib.so')
libf.f.restype = ctypes.c_double
libf.f.argtypes = [ctypes.c_int, ndpointer(ctypes.c_double)]

def f(a):
    return libf.f(a.size, np.ascontiguousarray(a, np.float64))

if __name__=="__main__":
    # slice to create non-contiguous array
    a = np.arange(1, 7, dtype=np.float64)[::2]
    assert not a.flags['C_CONTIGUOUS']
    print(a)
    print(np.multiply.reduce(a))
    print(f(a))

rawDescription: calling c from python with ctypes: passing vectors

description: Calling c from python with ctypes: passing vectors


rawDescription: Batch Renaming of Files in a Directory

description: Batch Renaming of Files in a Directory


code: content = dict(zip(list2, list1))

rawDescription: Using two lists to define a variable in python


code:
try:
    tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
    tornado.ioloop.IOLoop.instance().stop()

rawDescription: How to stop the tornado web server with ctrl+c?

description: Stop the tornado web server with ctrl+c


code: {'Williams,': 1, 'Jones,': 1, 'Miller,': 2, 'Johnson,': 2}

rawDescription: How to parse txtfile and export into dictionary?

description: Parse txtfile and export into dictionary


code:
c =  Counter()

for name in names:
    c.update(name)

c = c.most_common()
most_com, least_com = c[0][0],c[-1][0]

rawDescription: Calculate most common string in a wxListBox


code:
def partialdft(d,step,w):
    i = 0
    x = d[:]
    #...

rawDescription: DFT gives different results if iterated

description: DFT gives different results if iterated


code:
from time import strftime
date = strftime('%m-%d-%y')
time = strftime('%I:%M%p')
print(date)
print(time)

rawDescription: Python- how do I write user input to an Excel file?


code:
from StringIO import StringIO

fake_file = StringIO()
thing.save(fake_file)  # Acts like a file handle
contents = fake_file.getvalue()
fake_file.close()

rawDescription: In-memory thumbnail generation in python


code:
class MathFunction(object):
    def __init__(self, code):
        self.code = code
        self._func = eval("lambda x: " + code)
    def __call__(self, arg):
        return self._func(arg)
    def __repr__(self):
        return "f(x) = " + self.code

rawDescription: Represent a function by a mathematical function


rawDescription: Inserting a variable in MongoDB specifying _id field


rawDescription: binarize a sparse matrix in python in a different way

description: Binarize a sparse matrix in python in a different way


code: result = pd.concat([b(df), df[1:]])

rawDescription: Passing DataFrame slice as argument to function without 'SettingWithCopyWarning'


rawDescription: sum each value in a list of tuples

description: Sum each value in a list of tuples


rawDescription: pandas rank function yielding non-integers?

description: Pandas rank function yielding non-integers


code:
class CourseInscription(ndb.Model):
    member = ndb.KeyProperty(kind='User', required=True)
    course = ndb.KeyProperty(kind='Course', required=True)
    is_active = ndb.BooleanProperty(default=True)

rawDescription: Efficient way to store relation values in NDB


rawDescription: Converting a list of 3d matrix into 4d matrix


code:
def transposed_mult(x, y):
    return (x.T * y).T

transposed_mult(x, y)

rawDescription: Elementwise multiply 1D-numpy arrays (shapes (k,1) or (k,)) and have result have the shape of the first


code:
import pandas as pd
import pyodbc

rawDescription: How to convert a Microsoft Access Database to a SQL database (and then open it with pandas)?

description: Convert a Microsoft Access Database to a SQL database (and then open it with pandas)


code:
STATIC_ROOT = '/var/www/localhost/htdocs/mysite/static/'
STATIC_URL = '/static/' # default

rawDescription: How to serve admin static files with django.contrib.staticfiles in Django 1.4 (using one Apache server)?

description: Serve admin static files with django.contrib.staticfiles in Django 1.4 (using one Apache server)


rawDescription: itertools product speed up

description: Itertools product speed up


code:
class TestLogout(TestCase):

   def test_logout(self):
        self.client = Client()
        response = self.client.get('/cost_control/logout/')

rawDescription: Coverage test django logout

description: Coverage test django logout


code:
import re
timeline = filter(lambda status: not any(re.findall(r"[a-zA-Z0-9]*"+word+r"[a-zA-Z0-9]*",status.text) for word in wordBlacklist), timeline)

rawDescription: Check if string (or split string) contains any words from list


code:
class Child():
    nmbrMovies = 0
    nmbrBooks  = 3

class Adult():
    nmbrMovies = 2
    nmbrBooks  = 5

class Member(Child):
    pass

x = Member()

rawDescription: change the superclass of object in Python

description: Change the superclass of object in Python


rawDescription: Python: Write a program that asks the user for a color, a line width, a line length and a shape


code: userInput = input("Type roll to roll the dice!\n")

rawDescription: How do I have python run (if statements) based on the users input.?

description: Have python run (if statements) based on the users input.


code:
def bar():
    pass

rawDescription: Definition of a function that does nothing


rawDescription: Improving Functionality of Map Creator

description: Improving Functionality of Map Creator


rawDescription: Efficient replace value by value in other column


code: Factor.empty.var.append("a value")

rawDescription: Define a constant object in python

description: Define a constant object in python


code:
...
[u'Silva'] [u'Vila Nova-GO']
[u'Luizinho'] [u'Vila Nova-GO']
...
[u'Michel'] [u'Guarani']
[u'Wellyson'] [u'Guarani']
...

rawDescription: Not able to following links in Scrapy

description: Not able to following links in Scrapy


rawDescription: Are integers in Python passed by value or reference?


rawDescription: How to alter a part of an array

description: Alter a part of an array


code:
#Server Connection to MySQL:

import MySQLdb
conn = MySQLdb.connect(host= "localhost",
                  user="root",
                  passwd="newpassword",
                  db="engy1")
x = conn.cursor()

try:
   x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
   conn.commit()
except:
   conn.rollback()

conn.close()

rawDescription: How can I insert data into a MySQL database?

description: Insert data into a MySQL database


code: response['Set-Cookie'] = ('food=bread; drink=water; Path=/; max_age=10')

rawDescription: Django cookies and headers

description: Django cookies and headers


code:
result = regexHandler.search( pageData )
matchedText = result.groups()[0]

rawDescription: Python and web-tags regex

description: Python and web-tags regex


code: greet = my_decorator(greet)

rawDescription: How to use decorators (bottle.py)

description: Use decorators (bottle.py)


code:
strings = ["DC1","TIER2"]
with open(r"D:\kick-6.log", "r" ) as data:
    for deltaa in data:
        if any(x in deltaa for x in strings): #Check if any item in strings exits in deltaa
            print (deltaa)

rawDescription: Match multiple strings containing lines from file python


code:
with open(outfile_path, 'w') as outfile:
    for line in lines[-10:]:
        print(line, file=outfile)

rawDescription: How do i sort a lot of lists to get a top 10 in python?

description: Sort a lot of lists to get a top 10 in python


code:
for number in range(1, 11):
    line_contents = []
    for j in range(10):
        n = number + j * 10
        if (n % 3 == 0):
            line_contents.append("Biff")
        else:
            line_contents.append("{0:4d}".format(n))
    print(" ".join(line_contents))

rawDescription: Python: Change a number into a word inside a table


code:
def visit_Call(self, node):
    try:
        super().visit_Call(node)
    except AttributeError:
        pass

rawDescription: How to invoke super when the parent method may not be defined?

description: Invoke super when the parent method may not be defined


code:
import psycopg2
import numpy as np
from struct import pack
from io import BytesIO
from datetime import datetime

conn = psycopg2.connect("dbname=mydb user=postgres")
curs = conn.cursor()

# NumPy record array
shape = (7, 2000, 500)
print('Generating data with %i rows, %i columns' % (shape[1]*shape[2], shape[0]))

dtype = ([('id', 'i4'), ('node', 'i4'), ('ts', 'i2')] +
         [('s' + str(x), 'f4') for x in range(shape[0])])
data = np.empty(shape[1]*shape[2], dtype)
data['id'] = np.arange(shape[1]*shape[2]) + 1
data['node'] = np.tile(np.arange(shape[1]) + 1, shape[2])
data['ts'] = np.repeat(np.arange(shape[2]) + 1, shape[1])
data['s0'] = np.random.rand(shape[1]*shape[2]) * 100
prv = 's0'
for nxt in data.dtype.names[4:]:
    data[nxt] = data[prv] + np.random.rand(shape[1]*shape[2]) * 10
    prv = nxt

rawDescription: Use binary COPY table FROM with psycopg2


rawDescription: Representing Coordinates in GeoAlchemy2

description: Representing Coordinates in GeoAlchemy2


code:
import urllib
import urllib2

url = 'http://www.example.com'
values = {'var' : 500}

data = urllib.urlencode(values)
fullurl = url + '?' + data
response = urllib2.urlopen(fullurl)
page = response.read()

rawDescription: POSTing a form using Python and Curl

description: POSTing a form using Python and Curl


code:
seaborn.boxplot(x="centrality", y="score", hue="model", data=data,
                hue_order=["original", "Havel..","etc"])

rawDescription: Tweaking seaborn.boxplot

description: Tweaking seaborn.boxplot


code:
import multiprocessing
import threading
import socket

class Server(object):

    def handle(self, connection, address):
        print("OK...connected...")
        try:
            while True:
                data = connection.recv(1024)
                if data == "":
                    break
                connection.sendall(data)
        except Exception as e:
           print(e)
        finally:
            connection.close()
            print("Connection closed")

    def accept_forever(self):
        while True:
            # Accept a connection on the bound socket and fork a child process
            # to handle it.
            print("Waiting for connection...")
            conn, address = self.socket.accept()
            process = multiprocessing.Process(
                target=self.handle, args=(conn, address))
            process.daemon = True
            process.start()

            # Close the connection fd in the parent, since the child process
            # has its own reference.
            conn.close()

    def __init__(self, port, ip):
        self.port = port
        self.ip = ip
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.socket.bind((self.ip, self.port))
        self.socket.listen(1)

        # Spin up an acceptor thread
        self.worker = threading.Thread(target=self.accept_forever)
        self.worker.daemon = True
        self.worker.start()

    def join(self):
        # threading.Thread.join() is not interruptible, so tight loop
        # in a sleep-based join
        while self.worker.is_alive():
            self.worker.join(0.5)

# Create two servers that run in the background
s1 = Server(9001,"127.0.0.1")
s2 = Server(9002,"127.0.0.1")

# Wait for servers to shutdown
s1.join()
s2.join()

rawDescription: Start new process on __init__ (for TCP listener - server)


code:
import bisect
import random
try:
    from itertools import accumulate     # Python >= 3.2
except ImportError:
    def accumulate(weights):
        accumulator = 0
        for w in weights:
            accumulator += w
            yield accumulator

def count(iterable):
    return sum(1 for elem in iterable)

def get_nth(iterable, n):
    assert isinstance(n, int), "n must be an integer, got %r" % type(n)
    assert n > 0, "n must be greater than 0, got %r" % n
    for i, elem in enumerate(iterable, 1):
        if i == n:
            return elem

def weighted_select(filename):
    with open(filename) as f:
        n = count(f)
        if n == 0:
            return None

        # set up cumulative distribution
        weights = range(n, 0, -1)
        cumulative_dist = list(accumulate(weights))

        # select line number
        x = random.random() * cumulative_dist[-1]
        selected_line = bisect.bisect(cumulative_dist, x)

        # retrieve line from file
        f.seek(0)
        return get_nth(f, selected_line + 1)    # N.B. +1 for nth line

rawDescription: Weighted random choice from a variable length text file


code: board[y][x] = ' '

rawDescription: Displaying a moveable character inside of a grid


code: randomInts = [random.randrange(2000) for _ in range(100)]

rawDescription: Python random and int to string question


rawDescription: Writing/parsing a fixed width file using Python


rawDescription: ForeignKey to a Model field?

description: ForeignKey to a Model field


code:
c = get_config()
# ... Any other configurables you want to set
c.InteractiveShellApp.matplotlib = "inline"

rawDescription: Automatically run %matplotlib inline in iPython Notebook


rawDescription: How do I select from drop down menu with changing id on reload of webpage

description: Select from drop down menu with changing id on reload of webpage


code:
def getpass(database):
    with open("credentials.dat", "r") as f:
        for entry in [l.split("|") for l in f.readlines()]:
            if entry[0] == username:
                return entry[1]
    return None

rawDescription: Python Fabric load config from separate file


code: [predicted_label, predicted_confidence] = model.predict(image)

rawDescription: eigenfaces with openCV

description: Eigenfaces with openCV


rawDescription: Different integration results using Monte Carlo vs scipy.integrate.nquad


code:
class NestedContext(object):
    _current = None

    def __enter__(self):
        self.parent = self._current
        NestedContext._current = self

    def __exit__(self, _type, _value, _tb):
         NestedContext._current = self.parent

rawDescription: Class variable in python context class

description: Class variable in python context class


rawDescription: Python way for object method chaining for class instance variables


rawDescription: How to map a tuple of data to a tuple of functions?

description: Map a tuple of data to a tuple of functions


code:
step = 1.0 / (len(list1) - 1)
sortedlist = [l[:1] + [(len(list1) - i - 1) * step] + l[2:]
             for i, l in enumerate(sorted(list1, key=lambda item: item[1], reverse=True))]

rawDescription: Mapping linear ranks from data points in python


code:
[u'79000000 - Business services: law, marketing, consulting, recruitment, printing and security',
 u'79632000 - Personnel-training services',
 u'80000000 - Education and training services',
 u'80511000 - Staff training services',
 u'80530000 - Vocational training services']

rawDescription: BeautifulSoup beautifying an ugly process


rawDescription: Extracting a table from web with different hierarchical tags


rawDescription: Sorting list of lists based on number in inner list


code:
def process_ids(dir_path, ids_list, file_extension, callback):
    for itm_id in ids_list:
        id_dir = os.path.join(dir_path, itm_id)
        for path in glob(id_dir + '/*' + file_extension):
            callback(path)

rawDescription: Python statement as method's argument

description: Python statement as method's argument


code:
for cell in driver.find_elements_by_css_selector(".grid tr a[href$='fg=S2']"):
    gradesList = cell.text.split('\n')
    if len(gradesList) < 2:
        continue

    letter_grade, score = gradesList

    # Use variables...

rawDescription: Splitting a String and Assigning it Variables


rawDescription: Finding element with explicit wait using selenium webdriver in python


code:
class SomeModel(db.Model):
    pickled_data = db.BlobProperty()

your_model = SomeModel()
your_model.pickled_data = pickle.dumps(your_dict)

rawDescription: How to make persistent a python dictionary on google appengine

description: Make persistent a python dictionary on google appengine


code:
import csv

class CsvWriterPipeline(object):

    def __init__(self):
        self.csvwriter = csv.writer(open('items.csv', 'wb'))

    def process_item(self, domain, item):
        self.csvwriter.writerow([item['title'][0], item['link'][0], item['desc'][0]])
        return item

rawDescription: Newbie Q about Scrapy pipeline.py

description: Newbie Q about Scrapy pipeline.py


code:
# removes first and last character of every match
unquoted = [string[1:-1] for string in matches]

# removes first and last characters and converts match to number
numbers = [float(string[1:-1]) for string in matches]

rawDescription: How to print characters based on the surrounding characters

description: Print characters based on the surrounding characters


rawDescription: Python. Get flashing/blinking windows of a chat


code:
def view(person_id):
    person = Person.get(person_id) # or whatever source you get your data from
    return render_template('mypage.html', person=person)

rawDescription: passing a variable into a jinja import or include from a parent html file

description: Passing a variable into a jinja import or include from a parent html file


code:
for i in myObject:
    if myObject[i] == 'abc':
        return true

rawDescription: 'in' operator with boost::python

description: 'in' operator with boost::python


code:
df[ df.isnull() ] = np.nanmean( [ df.shift(x).values for x in
                                     range(-48*window,48*(window+1),48) ], axis=0 )

rawDescription: Fill data gaps with average of data from adjacent days


rawDescription: How to restore RDD of (key,value) pairs after it has been stored/read from a text file

description: Restore RDD of (key,value) pairs after it has been stored/read from a text file


code:
def _communicate(self, input):
    stdout = None # Return
    stderr = None # Return

    if self.stdout:
        stdout = []
        stdout_thread = threading.Thread(target=self._readerthread,
                                         args=(self.stdout, stdout))
        stdout_thread.setDaemon(True)
        stdout_thread.start()
    if self.stderr:
        stderr = []
        stderr_thread = threading.Thread(target=self._readerthread,
                                         args=(self.stderr, stderr))
        stderr_thread.setDaemon(True)
        stderr_thread.start()

rawDescription: Do any of python's built in modules use threads?


code:
import scipy.sparse as sps
def sparse_dummyvar(partitions):
    num_rows = np.sum(np.max(partitions, axis=1))
    nnz = np.prod(partitions.shape)
    as_part = np.argsort(partitions, axis=1)
    # You could get s_part from the indices in as_part, left as
    # an exercise for the reader...
    s_part = np.sort(partitions, axis=1)
    mask = np.hstack(([[True]]*len(items_per_row),
                      s_part[:, :-1] != s_part[:, 1:]))
    indptr = np.where(mask.ravel())[0]
    indptr = np.append(indptr, nnz)

    return sps.csr_matrix((np.repeat([1], nnz), as_part.ravel(), indptr),
                          shape=(num_rows, partitions.shape[1],))

rawDescription: numpy equivalent of matlab dummyvar

description: Numpy equivalent of matlab dummyvar


code:
def myfunction(x):
    return x in 'abcd'

print(''.join(filter(myfunction, animals)))

rawDescription: print found characters inside a string

description: Print found characters inside a string


rawDescription: Search for string in file while ignoring id and replacing only a substring


code:
{u'ListTopicsResponse':
  {u'ListTopicsResult':
    {u'NextToken': None,
     u'Topics': [
      {u'TopicArn': u'arn:aws:sns:us-east-1:467741034465:exampletopic'},
      {u'TopicArn': u'arn:aws:sns:us-east-1:467741034465:footopic'}
     ]
    },
  u'ResponseMetadata': {u'RequestId': u'aef821f6-d595-55e1-af14-6d3a8064536a'}}}

rawDescription: Boto - AWS SNS how to extract topic's ARN number


code:
import scipy.optimize
import numpy as np

xF = np.array([1.0, 2.0, 3.0, 4.0]) # Target value for fit
NOISE_LEVEL = 1.e-6 # The random noise level
RETURN_LEN = 1000  # The objective function return vector length

def func(x):
    if np.isnan(np.sum(x)):
        raise ValueError('Invalid x: %s' % x)
    v = np.random.rand(RETURN_LEN) * NOISE_LEVEL

    v[:len(x)] += xF - x

    return v[:len(x)]

iteration = 0
while iteration < 10:
    iteration += 1
    x = np.random.rand(len(xF))
    y = scipy.optimize.broyden1(func, x)
    print('%04d %s' % (iteration, y))

rawDescription: scipy.optimize.leastsq calls objective function with NaN

description: Scipy.optimize.leastsq calls objective function with NaN


rawDescription: create new column based on other column but stripping

description: Create new column based on other column but stripping


code:
df2 = pd.read_table('dummy.csv')
df2.T.drop_duplicates().T

rawDescription: python pandas remove duplicate columns

description: Python pandas remove duplicate columns


code: from __future__ import unicode_literals

rawDescription: Py2/3 compatibility for string input to dll used with ctypes


code:
numbers=[11, 12, 13, 10, 14, 2, 3]
suits=['D', 'D', 'D', 'D', 'D', 'C', 'C']

t = zip(numbers,suits)
t

from operator import itemgetter
sorted(t, key=itemgetter(0), reverse=True)#sort t by numbers from highest to lowest
sorted(t, key=itemgetter(1)) #sort t by suits
sorted(t, key=lambda s=itemgetter(0):suits.count(s[1]), reverse=True) #Sort by most occurence of cards

rawDescription: Reordering Python two lists without disturbing the compliments between the lists


rawDescription: What is the difference between a function, an unbound method and a bound method?


code: coast = land != erosion

rawDescription: Isolating coastal grids using convolving window (python)


code:
import time
import signal
import subprocess
import os

p = subprocess.Popen(["calc"])
time.sleep(4)
os.kill(p.pid, signal.SIGINT)

rawDescription: Subprocess management - Killing a subprocess


rawDescription: Tkinter set value of Button's corresponding Entry box


rawDescription: How to preserve column names while importing data using numpy?

description: Preserve column names while importing data using numpy


code:
import os
print(os.listdir('.'))

rawDescription: Execute a python command within vim and getting the output


rawDescription: How to write a csv from a fresh new line not \n

description: Write a csv from a fresh new line not \n


code:
from mynamespace.logging import custom_handlers
logging.custom_handlers = custom_handlers

rawDescription: Does python logging.handlers.RotatingFileHandler allow creation of a group writable log file?


code: fix_mac_adr = lambda adr: ':'.join([i.zfill(2) for i in adr.split(':')])

rawDescription: Perform a substring replacement in a single line in Python


code: c = nltk.corpus.whateverCorpusReaderYouChoose(directoryWithCorpus, regexForFileTypes)

rawDescription: How to extract words from sample corpus that comes with NLTK?

description: Extract words from sample corpus that comes with NLTK


code:
v = (country[i], )
[t + v for t in zip(name, age, city)]

rawDescription: adding the same variable to a list of tuples

description: Adding the same variable to a list of tuples


code: self.lbl = Label(text='Test', size_hint_x=1, size_hint_y=1)

rawDescription: Issues with Scatter size and position

description: Issues with Scatter size and position


code:
thedict
q.put(('foo', 'bar'))
thedict
q.put(Stop)
q.put(('baz', 'bar'))
thedict

rawDescription: Python threading in web programming

description: Python threading in web programming


code:
from nltk.stem import PorterStemmer
ps = PorterStemmer()
data0 = '''<Your Data0 string>'''
words = data0.split(" ")
stemmed_words = map(ps.stem, words)
print(list(stemmed_words))  # list cast needed because of 'map'

rawDescription: Stemming process not working in Python

description: Stemming process not working in Python


code:
import os
from bs4 import BeautifulSoup

do = dir_with_original_files = 'C:\\Users\\ADMIN\\Desktop\\RootFolder'
dm = dir_with_modified_files = 'C:\\Users\\ADMIN\\Desktop\\RootFolderNewImgSrc'

rawDescription: Updating image text programmatically

description: Updating image text programmatically


code:
#!/usr/bin/env python3

import matplotlib
from matplotlib import pyplot as plt
from matplotlib.ticker import MaxNLocator

data = range(5)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(data,data)

ax.xaxis.set_major_locator(MaxNLocator(5, prune='lower'))
ax.yaxis.set_major_locator(MaxNLocator(4, prune='lower'))

fig.tight_layout()

ax.text(-0.01, -0.02,
        "0",
        horizontalalignment = 'center',
        verticalalignment = 'center',
        transform = ax.transAxes)

fig.savefig("1.png")

rawDescription: Matplotlib: Tick labels position

description: Matplotlib: Tick labels position


code:
b = Bits().join(Bits(uint=x, length=p) for x in a)
b

rawDescription: Writing a numpy array to binary file with variable integer precision


code:
f = open(":test:", "w")
f.write("This is a test\n")
f.close()

f = open(":test:")
print(f.read())

rawDescription: (python) open a file in memory

description: (python) open a file in memory


code:
def to_unicode(s):
    return s.decode('utf-8') if isinstance(s, str) else s

the_list = [...]
the_list = [to_unicode(elem) for elem in the_list]

rawDescription: Python sort order unicode/ansi differs

description: Python sort order unicode/ansi differs


code:
raw_message='''Return-Path: <>
X-Original-To: bounces@mydomain.com
Delivered-To: bounces@mydomain.com
Received: from inmumg01.tcs.com (inmumg01.tcs.com [219.64.33.12])
    by smtp.mydomain.com (Postfix) with ESMTP id 603693FE11
    for <bounces@mydomain.com>; Tue, 15 Mar 2016 04:39:36 -0400 (EDT)
Received: from localhost by inmumg01.tcs.com;
  15 Mar 2016 14:09:38 +0530
Message-Id: <5aaa80$2543de@inmumg01.tcs.com>
Date: 15 Mar 2016 14:09:38 +0530
To: bounces@mydomain.com
From: "Mail Delivery System" <mail.notification@tcs.com>
Subject: Undeliverable Message

The following message to <vipul4.j@tcs.com> was undeliverable.
The reason for the problem:
5.1.0 - Unknown address error 550-'vipul4.j@tcs.com... No such user'

The IP address of the MTA to which the message could not be sent:
172.17.9.35

---------- A copy of the message begins below this line ----------
X-IronPort-Anti-Spam-Filtered: true
X-IronPort-Anti-Spam-Result: A0CGBgCEyedW/3zwO4tdHgEBAg4BgklMUm2nXoJekBMBDYFmBxUFAQ2HGwI4FAEBAQEBAQFkJ4RLIAoTAQEECCwGSQMBCQICMTsFHASHJ10FCatgZ4RBAQSLKQaBD4REgkIBhlERAWqCNBOBJ5MJhEuBLwKEPogSAoIuhnOFYo1YgUUBAUKBNgwBgj5OB4kqgTIBAQE
X-IPAS-Result: A0CGBgCEyedW/3zwO4tdHgEBAg4BgklMUm2nXoJekBMBDYFmBxUFAQ2HGwI4FAEBAQEBAQFkJ4RLIAoTAQEECCwGSQMBCQICMTsFHASHJ10FCatgZ4RBAQSLKQaBD4REgkIBhlERAWqCNBOBJ5MJhEuBLwKEPogSAoIuhnOFYo1YgUUBAUKBNgwBgj5OB4kqgTIBAQE
X-IronPort-AV: E=Sophos;i="5.24,338,1454956200";
   d="scan'208,217";a="72486315"
X-Amp-Result: Clean
X-Amp-File-Uploaded: False
Received: from smtp.mydomain.com ([139.59.240.124])
  by inmumg01.tcs.com with ESMTP/TLS/DHE-RSA-AES256-SHA; 15 Mar 2016 14:09:37 +0530
Received: from 128.199.202.14 (unknown [128.199.202.14])
    (Authenticated sender: mailsender)
    by smtp.mydomain.com (Postfix) with ESMTPA id 0D41F3FE11
    for <vipul4.j@tcs.com>; Tue, 15 Mar 2016 04:39:33 -0400 (EDT)
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=kitemailer.com;
    s=kitemail; t=1458031173;
    bh=1KFZSL77mNYuQ3iTjpNMdGcBOp2a4pGQnLVlq49ZrGg=;
    h=Date:From:To:Subject:List-Unsubscribe;
    b=Xxaf++WE0B7HL+FN28O76df7gYNEIKzk8eE9VpxrnMBCpGWPKWBMMfVDfCyie3NBJ
     GJiMxn/Yhn+ey6Mr5R5AK5JO5n72yWlytLm0RepMEydaeHHVQPx7bE+LMDMlORSFin
     bWdnz58lNMuZ3w9qtqjCXt22Sk5yXfCO71tRgfus=
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain.com;
    s=kitemail; t=1458031173;
    bh=1KFZSL77mNYuQ3iTjpNMdGcBOp2a4pGQnLVlq49ZrGg=;
    h=Date:From:To:Subject:List-Unsubscribe;
    b=FiGdkSE9LCjYkfYyWq65GbZoMZVCQs5OXXJA35CyGQtjPWbvwIKvx7Z6Ff39EBRLf
     Vu+6PUrvwyZLFh/1CW0NGOHDgUDjWWQ2jHfnNpJ9QEbHgOwomuMty10HDeZnIr0zM7
     8mFCgeCbiiyusQkhmXh5aYqqD+Q/1wFcrpLpkBZc=
Date: Tue, 15 Mar 2016 04:39:31 -0400 (EDT)
From: Kitemailer Newsletter <info@kitemailer.com>
To: vipul4.j@tcs.com
Message-ID: <15106466-1b13-4d64-b220-15f05f4815b7-1458031171312@smtp.mydomain.com>
Subject: KiteMailer | New Features this Week
MIME-Version: 1.0
Content-Type: multipart/mixed;
    boundary="----=_Part_44_1398250960.1458031171306"
List-Unsubscribe: <http://example.com/unsubscribe/dmlwdWw0LmpAdGNzLmNvbSM5Ng==>
Feedback-ID: 19:96:1520615:MyDomain'''

rawDescription: Python email parse non multipart

description: Python email parse non multipart


code:
partCount = len(pathParts) - 1

path = "/"
for i in range(2, partCount):
    path += pathParts[i] + "/"

rawDescription: Pythonic URL Parsing

description: Pythonic URL Parsing


rawDescription: Passing multple files with asterisk to python shell in Windows


code:
def call_special(receiver, *args, **keys):
    return receiver.__call_special__(*args, **keys)

rawDescription: What is the best-maintained generic functions implementation for Python?


rawDescription: Removing the first part of a concatenated string with Python


code:
filename = os.path.join(getenv("APPDATA"), "File")
if os.path.isfile(filename):
    print("Found file!")

rawDescription: Python - cannot "find" files with "getenv("APPDATA")"?


code: setattr(syslog, "LOG_LOCAL0", "The log value")

rawDescription: Getting value of a functions attribute from a string


rawDescription: Choosing random items from a Spark GroupedData Object


code: ['name', 'age', 'title', 'name']

rawDescription: Using a function to return a count of keys within a dictionary


code:
#!/usr/bin/env python
from BeautifulSoup import BeautifulSoup

fileString='''bazfoo
baby foo
baby foo
baby foo
bar'''
soup = BeautifulSoup(fileString)
print(soup.body)
# foo
# baby foo
# baby foo
# baby foo
#

print(soup.findAll('body'))
# [foo
# baby foo
# baby foo
# baby foo
# , bar]

rawDescription: Python RegEx skipping the first few characters?


code:
def function1_and_something():
    function1()
    #Do something

def function2_and_something_else():
    function2()
    #Do something else

random.choice([function1_and_something, function2_and_something_else])() # chose and call

rawDescription: Odd behavior when randomly choosing function from list and testing which function it was


code:
def get_security(filename, client_id):
    with open(filename, 'r') as f:
        for line in f:
            if client_id in line:
                return line[5:13]

client = input("What is your Client ID. CaSe SeNsItIvE")
security = get_security('clientIntensity.txt', client)
if security is None:
    print ("Client ID not found")
elif security.startswith('High'):
    print('Good')
elif security == 'Moderate':
    print('Bad')
else:
    print('There has been an error')

rawDescription: Reading from a .txt file and making conditions from it


code:
socket.setblocking(False)
while True:
    data = socket.recv(1024)
    if data:
        self.process_data(data)
    else:
        select([socket], [], [])

rawDescription: Twisted wait for event in loop

description: Twisted wait for event in loop


rawDescription: Unique representations of Python objects


code: set2 = filter(lambda item: filtCheck(item, 'Hi'), set1)

rawDescription: Passing a parameter through a python filter function


rawDescription: python 3.4, timer count down not working

description: Python 3.4, timer count down not working


code: return render(request, 'polls/productpage.html', {'product': product, 'image':image})

rawDescription: Django multiple contexts within a single view


code: cursor.execute("SELECT * FROM hiking WHERE name IN {}".format(tuple(name)))

rawDescription: Python cursor.fetchall() returns empty tuple


code: my_value = request.session['my_key']

rawDescription: Pass value to another view django

description: Pass value to another view django


code:
def callback(ch, method, properties, body):
    print(" [x] Received %r" % body)

rawDescription: Can I have a Python script listen on a message queue continuously or do I have to loop?

description: Have a Python script listen on a message queue continuously or do I have to loop


code: a != np.array(None)

rawDescription: efficient way of removing None's from numpy array

description: Efficient way of removing None's from numpy array


code:
e = 3
k = 7
x = modinv(e,k)
x
e*x % k

rawDescription: Solving a modular equation (Python)

description: Solving a modular equation (Python)


code:
import random

def playgame():
    s = random.randint(1,100) #grabs a random integer between 1 and 100
    POSS = range(1,7) #range ignores the last number, so this is [1,2,3,4,5,6]
    if not s % 7: #if s%7 != 0
        print("I lose")
        return #exit the function
    while s > 0: #while s is still positive
        choice = 0 #set choice to 0 (this may as well have been "foo",
                   #                 I just needed it to not be in POSS)
        while choice not in POSS: #until the user picks a valid number
            choice = int(input("Select a number between 1 and 6: ")) #prompt for input
        s -= choice #subtract choice from s, then set the difference to s
        print("You subtracted {}, leaving {}".format(choice,s)) #print for the user
        comp_choice = s%7 #the computer's choice is always s%7
        s -= comp_choice #subtract the comp's choice from s, then set the diff to s
        print("I subtracted {}, leaving {}".format(comp_choice,s)) #print for user
    print("I win!") #since we know computer will always win, I don't have to do a check

playgame() #run the function

rawDescription: Need help writing algorithm in Python/Sage


rawDescription: Selenium/python - fails to find partial link text


code:
def foo(value, arr=[]):
    arr.append(value)
    return arr

rawDescription: Does Python have a default Caching service


code:
from scrapy.http.request import Request

class StartRequestsCountMiddleware(object):

    start_urls = {}

    def process_start_requests(self, start_requests, spider):
        for i, request in enumerate(start_requests):
            self.start_urls[i] = request.url
            request.meta.update(start_request_index=i)
            yield request

    def process_spider_output(self, response, result, spider):
        for output in result:
            if isinstance(output, Request):
                output.meta.update(
                    start_request_index=response.meta['start_request_index'],
                )
            else:
                spider.crawler.stats.inc_value(
                    'start_requests/item_scraped_count/{}'.format(
                        self.start_urls[response.meta['start_request_index']],
                    ),
                )
            yield output

rawDescription: How many items has been scraped per start_url


code:
from string import ascii_lowercase as letters
def find_words(digits):
    if not digits:
        yield ''
        return
    first = letters[int(digits[0])]
    for remainder in find_words(digits[1:]):
        yield first + remainder
    if len(digits) > 1 and int(digits[:2]) < 26:
        firsttwo = letters[int(digits[:2])]
        for remainder in find_words(digits[2:]):
            yield firsttwo + remainder

for word in find_words('1213'):
    print(word)

rawDescription: Convert a number representing the position of the characters in the dictionary to the original string


code:
# asd.pyxbdl
def make_ext(modname, pyxfilename):
    from distutils.extension import Extension
    return Extension(name=modname,
                     sources=[pyxfilename],
                     extra_link_args=['-fopenmp'],
                     extra_compile_args=['-fopenmp'])

rawDescription: Parallelise python loop with numpy arrays and shared-memory


code:
{'prefix': ('setup.cfg', '/my/prefix'),
 'install_scripts': ('setup.cfg', '$base/scripts')}

rawDescription: Referring to existing distutils options inside setup.cfg and setup.py


code:
from types import FunctionType

# check if an object should be decorated
def do_decorate(attr, value):
    return ('__' not in attr and
            isinstance(value, FunctionType) and
            getattr(value, 'decorate', True))

# decorate all instance methods (unless excluded) with the same decorator
def decorate_all(decorator):
    class DecorateAll(type):
        def __new__(cls, name, bases, dct):
            for attr, value in dct.iteritems():
                if do_decorate(attr, value):
                    dct[attr] = decorator(value)
            return super(DecorateAll, cls).__new__(cls, name, bases, dct)
        def __setattr__(self, attr, value):
            if do_decorate(attr, value):
                value = decorator(value)
            super(DecorateAll, self).__setattr__(attr, value)
    return DecorateAll

# decorator to exclude methods
def dont_decorate(f):
    f.decorate = False
    return f

rawDescription: Automatically decorating every instance method in a class


code:
fig=plt.figure()
ax = fig.add_subplot(111)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
colLabels=("Structure", "Energy", "Density")
the_table = ax.table(cellText=clust_data,
          colLabels=colLabels,
          loc='center')
plt.savefig("table.png")

rawDescription: Creating tables in matplotlib

description: Creating tables in matplotlib


rawDescription: matplotlib - Error passing line argument through **kwargs

description: Matplotlib - Error passing line argument through **kwargs


code:
import datetime
import pprint

def parse(date):
    return datetime.date(*[int(i) for i in d.split('-')])

def get_ranges(dates):
    while dates:
        end = 1
        try:
            while dates[end] - dates[end - 1] == datetime.timedelta(days=1):
                end += 1
        except IndexError:
            pass

        yield {
            'start-date': dates[0],
            'end-date': dates[end-1]
        }
        dates = dates[end:]

dates = [
    '2011-02-27', '2011-02-28', '2011-03-01',
    '2011-04-12', '2011-04-13',
    '2011-06-08'
]

# Parse each date and convert it to a date object. Also ensure the dates
# are sorted, you can remove 'sorted' if you don't need it
dates = sorted([parse(d) for d in dates])

pprint.pprint(list(get_ranges(dates)))

rawDescription: Python: how to compute date ranges from a list of dates?


code:
element = {'Request': (16, 2), 'Params': ('Typetext', [16, 2], 2), 'Service': 'Servicetext', 'Responses': ({'State': 'Positive', 'PDU': [80, 2, 0]}, {})}
for path, value in objwalk(element):
    if isinstance(value, int):
        parent = element
        for step in path[:-1]:
            parent = parent[step]
        parent[path[-1]] = hex(value)

element

rawDescription: Iterate over nested lists, tuples and dictionaries


code: result[:numpy.nonzero(x)[0][0]] = 0

rawDescription: Count since last occurence in NumPy

description: Count since last occurence in NumPy


rawDescription: All possible combinations of value-pairs (2-item tuples) in a sequence - PYTHON 2.7


rawDescription: Efficient way of making a list of pairs from an array in Numpy


rawDescription: condensing the code or a one liner possible for this code in python

description: Condensing the code or a one liner possible for this code in python


code: [(ch.tag,ch.text) for e in tree.findall('file') for ch in e.getchildren()]

rawDescription: Parse XML file into Python object

description: Parse XML file into Python object


code:
import json
counter
json.dumps(counter)

rawDescription: Can you make Counter not write-out "Counter"

description: Make Counter not write-out "Counter"


code:
import random
a = random.randrange(0,50)
b = random.randrange(0,a)
while b > a:
    b = random.randrange(0,a)

rawDescription: Python Random Random

description: Python Random Random


code:
#!/usr/bin/env python
import flask
from breadcrumb import breadcrumb

app = flask.Flask(__name__)

@app.route('/')
@breadcrumb('The index page')
def index():
    return flask.render_template('page.html')

@app.route('/a')
@breadcrumb('Aardvark')
def pagea():
    return flask.render_template('page.html')

@app.route('/b')
@breadcrumb('Banana')
def pageb():
    return flask.render_template('page.html')

@app.route('/c')
@breadcrumb('Chimp')
def pagec():
    return flask.render_template('page.html')

@app.route('/d')
@breadcrumb('Donkey')
def paged():
    return flask.render_template('page.html')

if __name__ == '__main__':
    app.secret_key = '83cf5ca3-b1ee-41bb-b7a8-7a56c906b05f'
    app.debug = True
    app.run()

rawDescription: Implementing breadcrumbs in Python using Flask?


rawDescription: fastest way to find the smallest positive real root of quartic polynomial 4 degree in python

description: Fastest way to find the smallest positive real root of quartic polynomial 4 degree in python


code:
import re
num = 557
suggestion="557::Voyage to the Bottom of the Sea (1961)::Adventure|Sci-Fi"

suggestionDict = re.search(r'%d::(?P<Title>[a-zA-Z0-9 ]+)\s\((?P<Date>\d+)\)::(?P<Genres>[a-zA-Z1-9|]+)' % num, suggestion).groupdict()
#printing to show if it works/doesn't
print('\n'.join(["%s:%s" % (k,d) for k,d in suggestionDict.items()]))
#clearer example of how to use
print("\nCLEAR EXAMPLE:")
print(suggestionDict["Title"])

rawDescription: Using variables in a reg-ex

description: Using variables in a reg-ex


rawDescription: OO Aproach python

description: OO Aproach python


code:
a, b = tee(it)
next(a)

rawDescription: Python itertools tee, clones and caching


code:
def minsub(a, b):
    target_hist = collections.Counter(b)
    current_hist = collections.Counter()
    # Skip all the useless characters
    idx = min_idx(a, target_hist)
    if idx is None:
        return []
    a = a[idx:]
    # Build a base substring
    i = iter(a)
    current = []
    while not issubset(target_hist, current_hist):
        t = next(i)
        current.append(t)
        if t in target_hist:
            current_hist[t] += 1
    minlen = len(current)
    shortest = current
    #current = []
    for t in i:
        current.append(t)
        current_hist[t] += 1
        # Shorten the substring from the front as much as possible
        if t == current[0]:
            #idx = min_idx(current[1:], target_hist) + 1
            idx = 0
            while issubset(target_hist, current_hist):
                u = current[idx]
                current_hist[u] -= 1
                idx += 1
            idx -= 1
            u = current[idx]
            current_hist[u] += 1
            current = current[idx:]
        if len(current) < minlen:
            minlen = len(current)
            shortest = current[:]
    return shortest

rawDescription: Finding shortest substring containing certain characters in linear time


code:
df = pd.merge(
    df,
    df.some.groupby(df.id).apply(lambda g: 'Yes' if 'Yes' in g.values else 'No').reset_index(),
    how='left')

rawDescription: Python - Panda's dataframes - generate column with group level information


code:
def gen_random_vid(vids, denom=2):
    '''return  a random vid id that hasn't been recently watched'''
    recently_watched = collections.deque(maxlen=len(vids)//denom)
    while True:
        selection = random.choice(vids)
        if selection not in recently_watched:
             yield selection
             recently_watched.append(selection)

rawDescription: How to choose a random but non-recent asset from a list?

description: Choose a random but non-recent asset from a list


rawDescription: Mean of a correlation matrix - pandas data fram


code:
row
row["User"]
row["Tag"]

rawDescription: How to perform functions over groupby results in pandas in python?

description: Perform functions over groupby results in pandas in python


rawDescription: How to index and automate processing of list using input csv file

description: Index and automate processing of list using input csv file


code:
class GroupHierarchy(Hierarchy):
    group = models.ForeignKey(Group)

    def __unicode__(self):
        return self.group.name

rawDescription: hierarchal permission on same model

description: Hierarchal permission on same model


code:
start = "2.1.0"
end   = "2.1.3"

def get_dotted_range(start, end):
    # break into number-pieces
    start = start.split(".")
    end   = end  .split(".")
    # remove last number from each
    x = int(start.pop())
    y = int(end  .pop())
    # make sure start and end have the same number of sections
    #   and all but the last number is the same
    if start != end:
        return []
    else:
        head = ".".join(start) + "."
        return [head + str(i) for i in range(x, y + 1)]

rawDescription: Python: get the range between two dotted numbers


code: print ('A %s gives B %s \n' % (name, str(mobile)))

rawDescription: python print to file prints correctly in console but not in file

description: Python print to file prints correctly in console but not in file


code:
type(('hello'))
type(('hello',))  # notice the trailing `,`

rawDescription: printing string containing variables in python

description: Printing string containing variables in python


code:
import pandas as pd

df = pd.read_csv("M:/test.csv")
gr_data = df.groupby('unique_pid2')
def foo(grp):
    mask = ((grp['age'].cumsum()>0) & (grp['moved'].cumsum()>0)
            & (grp['age'] == 0) & (grp['moved'] == 0))
    grp.loc[mask, ['age', 'moved']] = 'foo'
    return grp
df = gr_data.apply(foo)
print(df)

rawDescription: Python pandas: replace select values in groupby object


code:
def parse(source):

    def expr(tokens):
        t = tokens.pop(0)
        if t != '(':
            return {'value': t}
        key, val = tokens.pop(0), {}
        while tokens[0] != ')':
            val.update(expr(tokens))
        tokens.pop(0)
        return {key:val}

    tokens = re.findall(r'\(|\)|[^\s()]+', source)
    lst = []
    while tokens:
        lst.append(expr(tokens))
    return lst

rawDescription: regular expression for a string format

description: Regular expression for a string format


code:
class MyModel(ndb.Model):
  foo = StringProperty('bar')

rawDescription: NDB query filtering by property (string)


code:
import os
import sys
import site

ALLDIRS = ["C:\pyenv\tggs18\Lib\site-packages"]

# Add each new site-packages directory.
for directory in ALLDIRS:
    site.addsitedir(directory)

sys.path.append("C:/wamp/www/tggs/tggs")
sys.path.append("C:/wamp/www/tggs")

activate_env_file = "C:\\pyenv\\tggs18\\Scripts\\activate_this.py"
execfile(activate_env_file, dict(__file__=activate_env_file))

os.environ["DJANGO_SETTINGS_MODULE"] = "tggs.settings"

from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

rawDescription: How can I serve 2 Django applications in different virtual environments on Apache Windows?

description: Serve 2 Django applications in different virtual environments on Apache Windows


code:
tab
getSum(tab,1) # sum of squares of size 1
getSum(tab,2) # sum of squares of size 2
getSum(tab,3) # sum of squares of size 3
getAllSums(tab) # sum of squares of all sizes

rawDescription: How can I vectorize and speed up this large array calculation?

description: Vectorize and speed up this large array calculation


code:
class Conf(object):
    pass

def read():
    while True:
        try:
            file = open("agData.txt", "r")
        except:
            exec(open("agCreation.py").read())
            break
        break
    file = open("agData.txt", "r")
    data = file.readlines(0)
    encrypFName = data[0]
    encrypSName = data[1]
    encrypAge = data[2]
    encrypGender = data[3]
    encrypHealth = data[4]
    encrypMaxHealth = data[5]
    encrypArmour = data[6]
    encrypMaxArmour = data[7]
    encrypHealthPotions = data[8]
    encrypExp = data[9]
    encrypMaxExp = data[10]
    encrypLevel = data[11]
    encrypGold = data[12]
    encrypMaxGold = data[13]
    encrypPowerLevel = data[14]
    encrypMaxPowerExp = data[15]
    encrypPowerExp = data[16]
    encrypStage = data[17]

    conf = Conf()

    conf.fName = encrypFName.strip()
    conf.sName = encrypSName.strip()
    conf.age = encrypAge.strip()
    conf.gender = encrypGender.strip()
    conf.health = encrypHealth.strip()
    conf.maxHealth = encrypMaxHealth.strip()
    conf.armour = encrypArmour.strip()
    conf.maxArmour = encrypArmour.strip()
    conf.healthPotions = encrypHealthPotions.strip()
    conf.exp = encrypExp.strip()
    conf.maxExp = encrypMaxExp.strip()
    conf.level = encrypLevel.strip()
    conf.gold = encrypGold.strip()
    conf.maxGold = encrypMaxGold.strip()
    conf.powerLevel = encrypPowerLevel.strip()
    conf.maxPowerExp = encrypMaxPowerExp.strip()
    conf.powerExp = encrypPowerExp.strip()
    conf.stage = encrypStage.strip()
    return conf

rawDescription: Setting variables in a function and importing them


code:
def print_slot(slot):
    for row in slot:
        print(" ".join(row))

rawDescription: ultimate fixed width Python board array

description: Ultimate fixed width Python board array


code:
for i, d in enumerate(data):
    if i > 0:
        if d[0] - data[i-1][1] > datetime.timedelta(0):
            print("Gap")

rawDescription: How to get gap between dates?

description: Get gap between dates


code:
n = 1
dfs[n].m_ta.plot(title='Month {0}'.format(n));
dfs[n].monthly_mean.plot();
(dfs[n].monthly_mean + dfs[n].monthly_std).plot();
(dfs[n].monthly_mean - dfs[n].monthly_std).plot()

rawDescription: calculate standard deviation and plot the curving fit using Python 2.7

description: Calculate standard deviation and plot the curving fit using Python 2.7


code:
class StateMachine(object):

    def dispatch(self, *args, **kwgs):
        getattr(self, 'do_{}'.format(self.state))(*args, **kwgs)

    def do_new(self):
        print('new')

    def do_archive(self):
        print('archive')

sm = StateMachine()
sm.state = 'new'
sm.dispatch()
sm.state = 'archive'
sm.dispatch()

rawDescription: Singledispatch based on value instead of type


code:
def get_factorization_factorial(n):
    primes = sieve(n)
    factors = []
    for p in primes:
        factors.append((p, exp_for_factor_in_factorial(p, n)))
    return factors

rawDescription: Find the number of divisors of (N!)^2

description: Find the number of divisors of (N!)^2


rawDescription: Print to stdout with space's between result?


code:
class ContactCSVModel(CsvModel):
    pass

for form_field in form:
    field_name = form_field.value
    model_field = CharField()
    model_field.contribute_to_class(ContactCSVModel, field_name)

rawDescription: Django ordering code in class

description: Django ordering code in class


code:
def any(list, condition):
  for a in list:
    if condition(a):
      return true
  return false

rawDescription: How does all() in python work on empty lists


code: ['value 1', 'value 2']

rawDescription: Remove unicode in Python from databse?

description: Remove unicode in Python from databse


code:
c.x           # getter
c.x = [1,2,3] # setter

rawDescription: Python property on a list

description: Python property on a list


code: a

rawDescription: Find if value exists in multiple lists

description: Find if value exists in multiple lists


rawDescription: How to Read Reg_Binary type values in string format from Registry in python


code:
NaN = float('nan')
import math
math.isnan(1)
math.isnan(NaN)

rawDescription: How to delete [NaN] from a list of lists?

description: Delete [NaN] from a list of lists


code:
class Calendar2(Calendar):
    def __init__(self, master=None, call_on_select=None, **kw):
        Calendar.__init__(self, master, **kw)
        self.set_selection_callbeck(call_on_select)

    def set_selection_callbeck(self, a_fun):
         self.call_on_select = a_fun

    def _pressed(self, evt):
        Calendar._pressed(self, evt)
        x = self.selection
        #print(x)
        if self.call_on_select:
            self.call_on_select(x)

rawDescription: python calendar widget - return the user-selected date

description: Python calendar widget - return the user-selected date


rawDescription: How to convert list into set in pandas?

description: Convert list into set in pandas


rawDescription: Ignore minimum size when resizing QWidget


rawDescription: Conditionally formatting text strings from Excel using python


code:
min_dist = np.empty(n)
for i, point in enumerate(points):
    min_dist[i] = np.min([point.distance(line) for line in lines])
df_points['min_dist_to_lines'] = min_dist
df_points.head(3)

rawDescription: Calculate Distance to Nearest Feature with Geopandas


code:
stream = StringIO( myXmlString )
buffer = self.myRichTextCtrl.GetBuffer()
# you have to specify the type of data to load and the control
# must already have an instance of the handler to parse it
buffer.LoadStream(stream, wx.richtext.RICHTEXT_TYPE_XML)
myRichTextCtrl.Refresh()

rawDescription: WxRichTextCtrl python retrieving entries from file


code:
lb = MyLabelBinarizer()
label1 = lb.fit_transform(['yes', 'no', 'no', 'yes'])
print(label1)
print(lb.inverse_transform(label1))
label2 = lb.fit_transform(['yes', 'no', 'no', 'yes', 'maybe'])
print(label2)
print(lb.inverse_transform(label2))

rawDescription: sklearn LabelBinarizer returns vector when there are 2 classes

description: Sklearn LabelBinarizer returns vector when there are 2 classes


rawDescription: Regarding Killing the switch in Python

description: Regarding Killing the switch in Python


code: new_long_string = replacer.sub(lambda m: '<b>%s</b>' % m.group(0), long_string)

rawDescription: How to preserve case using re.IGNORECASE and .sub?


rawDescription: How to coloring specific region (or grid) on 3d object (i.e. sphere) in matplotlib3d

description: Coloring specific region (or grid) on 3d object (i.e. sphere) in matplotlib3d


code: [i.split('.')[1] for i in list1]

rawDescription: Get all characters after a certain character?


code:
if normalised_delta/20 == 0.005:
  step_size = 0.005
elif normalised_delta/20 <= 0.01:
  step_size = 0.01
elif normalised_delta/5 >= 0.05:
  step_size = 0.05

rawDescription: Ticking function grapher

description: Ticking function grapher


code:
one = df.xs('one', level=1, axis=1)
one
pyplot.show(one.plot())

rawDescription: Selecting a column on a multi-index pandas DataFrame


code:
posters = Poster.objects.filter(city__country=country)
poster_cities = {}
for poster in posters:
    if city not in poster_cities:
        poster_cities[city] = []
    poster_cities[city].append(poster)

rawDescription: Django Query and Grouping

description: Django Query and Grouping


code:
is_valid_python('1 // 2')
is_valid_python('1 /// 2')

rawDescription: How to tell if a string contains valid Python code

description: Tell if a string contains valid Python code


code:
#!python3
#coding: utf8
symbols = ' {}&+()"=!.?.:../|»©:><#«,123456789_-+;[]%'
D = str.maketrans('','',symbols)
with open('All12.txt','a',encoding='utf8') as t, open('All11.txt','r',encoding='utf8') as n:
    while True:
        block = n.read(100*1024*1024)
        if not block:
            break
        t.write(block.translate(D))

rawDescription: Removing symbols from a large unicode text file


code:
updated = Votes.objects(pizza=Spicy,
                        vote=FiveStar,
                        upsert=True).update(addToSet__voters=Rozza)

rawDescription: MongoDB, MongoEngine: unique list items

description: MongoDB, MongoEngine: unique list items


rawDescription: scaling numbers column by column with pandas [python]

description: Scaling numbers column by column with pandas [python]


code:
miss
miss
hit
miss
miss
hit
miss
hit
hit
hit
miss
hit
{0: ['a', 'b'], 1: ['c', 'd'], 2: ['e'], 3: ['f']}

rawDescription: Python - anyone have a memoizing decorator that can handle unhashable arguments?


code:
logging.basicConfig(
    level=logging.DEBUG,
    format='%(real_func_name)20s - %(message)s',
)

...

logging.info(statement, extra={'real_func_name': func.__name__})

rawDescription: Using functools.wraps with a logging decorator


code:
return output_list
return key_list

rawDescription: Python No Action on 2nd Statement After 'IF'


code:
regex = re.compile(r'''
           (?:\d{1,2}\s)(block\s\w*) # rule 1
             |   # or
           (?:(phase|apartment|building).*?)(block\s\w+) # rule 2
             ''', re.X)

found = regex.finditer(strings)

for i in found:
    print(i.groups())

rawDescription: Conditioning on Regex

description: Conditioning on Regex


code:
reg = re.compile(r'^[01]{8}$')

def typecheck(value):
    return isinstance(value, str) and bool(reg.match(value))

rawDescription: Function that returns true or false if certain conditions are met?


code:
a = b = 1
b += 1     # in-place operation, this will work differently for mutable objects
a, b       # a is still unchanged

rawDescription: Updating elements in nested list using 'for' won't work in python list


code: unique = set(map(frozenset, list_of_lists))

rawDescription: Deleting duplicates from a list of lists if some duplicates do not have the same order


code: os.sys.path.insert(0, "")

rawDescription: importing from venv folder with same file name

description: Importing from venv folder with same file name


rawDescription: Flask - How to use CSS when i'm using Response(stream_template) with generator


code:
import numpy as np
src_np = np.array(src)
mask_np = np.array(mask)
mask_np[mask_np > 0] = src_np[mask_np > 0]

rawDescription: Python lambda with double loops

description: Python lambda with double loops


code:
length = 10 # Line size
thickness = 2
angle = math.atan2(X0[1] - X1[1], X0[0] - X1[0])

rawDescription: Pygame draw anti-aliased thick line

description: Pygame draw anti-aliased thick line


code:
def distance(lista, listb):
    runsum = 0.0
    for a, b in zip(lista, listb):
        # square the distance of each
        #  then add them back into the sum
        runsum += (b - a) ** 2

    # square root it
    return runsum **.5

rawDescription: algorithm to compare lists of numbers for similarity?

description: Algorithm to compare lists of numbers for similarity


code:
pts = np.random.random((5,3))
transform_matrix = np.random.random((3,3))

pts_brute = pts.copy()
for i in range(len(pts_brute)):
        pts_brute[i] = transform_matrix.dot(pts_brute[i])

pts_einsum = np.einsum("ij,kj->ik", pts, transform_matrix)
np.allclose(pts_brute, pts_einsum)

rawDescription: Use numpy to multiply a matrix across an array of points?


code:
def growing_sequence():
    M = []
    counter = 0
    while True:
        M.append(counter)
        counter += 1
        yield M[:]

rawDescription: Most Pythonic way to iteratively build up a list?


rawDescription: Numpy: use dtype from genfromtxt() when exporting with savetxt()


code:
from ctypes import *

class TestStruct(Structure):
    _fields_ = [("a", c_int),
                ("array", (c_float * 4) * 30)]

slib = CDLL("slib.dll")
slib.print_struct.argtypes = [POINTER(TestStruct)]
slib.print_struct.restype = None

t = TestStruct()

for i in range(30):
    for j in range(4):
        t.array[i][j] = i + 0.1*j

slib.print_struct(byref(t))

rawDescription: Python, ctypes, multi-Dimensional Array

description: Python, ctypes, multi-Dimensional Array


code:
def up():
    y=y+1

def down():
    y=y-1

def left():
    x=x-1

def right():
    x=x+1

d = {'up': up, 'down': down, 'left': left, 'right': right};

rawDescription: Storing code in a list or dictionary?

description: Storing code in a list or dictionary


rawDescription: regex sbustitute only specific hit sequence

description: Regex sbustitute only specific hit sequence


code:
def chain(start, countries):
    remaining = list(countries)
    del remaining[remaining.index(start)]
    possibles = [x for x in remaining if x[:1] == start[-1:]]
    maxchain = []
    for c in possibles:
        l = chain(c, remaining)
        if len(l) > len(maxchain):
            maxchain = l
    return [start] + maxchain

rawDescription: Longest chain of elements from list in Python


code: tree.write("output.xsd", method="html")

rawDescription: Python 2.7 Etree/lxml minimizing

description: Python 2.7 Etree/lxml minimizing


code:
import pandas as pd
# read the csv as DataFrame, probably there is a way to get it from
# the API directly without saving to a file
# specify header as the first row
df = pd.read_csv("test.csv", header=0)
# empty dict
d = {}
# iterate over lines, I use this way, but I don't like it in fact
for i, key_id in enumerate(df["id"]):
    # assign the values the way you want it
    # however you need to specify it by names
    # or indices
    d[key_id.strip()] = {df.loc[i, "loc_name"]:df.loc[i, "qty"],
                         df.loc[i, "loc_name.1"]:df.loc[i, "qty.1"]}
print(d)
#{'"NM003"': {'SLD': 25, 'KMG': 15}, '"NM001"': {'HLR': 10, 'KBD': 20}}

rawDescription: Read CSV for same headers and separate in dict


code: data[row[0]] = float(row[1])

rawDescription: Extracting data from a text file

description: Extracting data from a text file


code:
users1 = name_starts_with(active_users(), 'A').order_by(User.last_visited)
users2 = name_starts_with(recent_users(), 'B').filter(lambda user: user.online)

rawDescription: Writing select functions for customized Pony


code:
import urllib.request
import csv

# the images list should be outside the with block
images = []
IMAGE_COLUMN = 14

with open('test.csv') as csvfile:
    # read csv
    readCSV = csv.reader(csvfile, delimiter=",")
    for row in readCSV:
        # I guess 14 is the column-index of the image-name like 'image.jpg'
        # I've put it in some constant

        # now append all the image-names into the list
        images.append(row[IMAGE_COLUMN])

        # no need for the following
        # image = row[14]
        # images.append(image)

# make sure, root_url ends with a slash
# x was some strange name for an url
root_url = 'http://www.fakesite.com/pimages/'

# iterate through the list
for image in images:
    # you don't need os.path.join, because that's operating system dependent.
    # you don't need to urlsplit, because you have created the url yourself.
    # you don't need to split the filename as it is the image name
    # with the following line, the root_url must end with a slash
    url = root_url + image

    # urlretrieve saves the file as whatever image is into the current directory
    urllib.request.urlretrieve(url, image)

rawDescription: Download files from FTP or HTTP using filenames in CSV - Python 3


code: filter_ind = [i for i, id in enumerate(oids) if id != '-1']

rawDescription: Filter dict by certain values

description: Filter dict by certain values


code:
W=""

for i in A:    # for each key in the dictionary
    W+="{0} {1}\n".format(i,A[i])     # Append to W a dictionary key , a space , the value corresponding to that key and start a new line

with open("text.txt","w") as O:
    O.write(W)

rawDescription: How to write to a specific line in a text file

description: Write to a specific line in a text file


code:
s = dt.strftime('%Y-%m-%d %H:%M:%S')
s

rawDescription: Python - Convert epoch time with nanoseconds to human-readable?


code:
entries = []

for k, v in myDict.iteritems():
   entries.append({ "entry": k, "count": v })

rawDescription: Converting a python dictionary to a JSON - like object


code:
import numpy as np
mask = np.repeat(mask, 4, axis=0).repeat(4, axis=1)
# Then you apply the mask using
values = np.array(data)[mask]

rawDescription: Slicing array in regions - Python

description: Slicing array in regions - Python


code:
def setEditorData(self, widget, index):
    widget.setCurrentIndex(index.data(Qt.UserRole+1))

rawDescription: Displaying QComboBox text rather than index value in QStyledItemDelegate


code:
import os

def replaceProgramFilesPath(filenameBr):
  new_path = os.environ.get("PROGRAMFILES") + chr(92)
  return filenameBr.replace("<ProgramFilesPath>", new_path)

rawDescription: Is there a way to convert code to a string and vice versa in Python?


code:
class_info = df.pivot_table(rows="Location", cols="Class", aggfunc='size', fill_value=0)
class_info

rawDescription: Pandas summing up different data types using counts and conditions


rawDescription: Python: Concatenate (or clone) a numpy array N times


code: user_input = raw_input()

rawDescription: How do I automatically pass arguments to a function on certain objects

description: Automatically pass arguments to a function on certain objects


rawDescription: Building a "complete" number range w/out overlaps


code:
df = pd.DataFrame([
  {'code': '0101010C0AAAAAA', 'chemical': '0101010C0', 'is_generic': True, 'format': 'AAAA'},
  {'code': '0101010C0BBAAAA', 'chemical': '0101010C0', 'is_generic': False, 'format': 'AAAA'},
  {'code': '0101010F0AAAUAU', 'chemical': '0101010F0', 'is_generic': True, 'format': 'AUAU'},
  {'code': '0101010F0BCAAAU', 'chemical': '0101010F0', 'is_generic': False, 'format': 'AAAU'},
  {'code': '0101010G0AAABAB', 'chemical': '0101010G0', 'is_generic': False, 'format': 'ABAB'}
])

groups = df.groupby('is_generic')
pd.merge(groups.get_group(False), groups.get_group(True), on='chemical', how='left')

rawDescription: Find equivalent rows in pandas?

description: Find equivalent rows in pandas


code:
- reST
"""
:param param1: Description of param1
:type param1: type of param1

:return: description of returned value
:rtype: type of returned value
"""

rawDescription: Python: Standard way to denote return and parameter types


code:
df['year'] = df.index.year
df['week'] = df.groupby('year').cumcount()+1

rawDescription: Issue with merging time series variables to create new DataFrame with arbitrary index


rawDescription: Pandas dataframe apply refer to previous row to calculate difference


rawDescription: Python: Cumulative insertion of values in a sparse matrix (lil_matrix) due to repeated indices


code:
import __builtin__

class MetaClass(type):
    def __new__(mcls, name, *args):
        # do something in the metaclass
        return super(MetaClass, mcls).__new__(mcls, name, *args)

orig_object = __builtin__.orig_object

class metaobject(orig_object):
    __metaclass__ = MetaClass

def enable():
    # *replace* object with one that uses your metaclass
    __builtin__.object = metaobject

def disable():
    __builtin__.object = orig_object

rawDescription: Python: Setting the metaclass for all files in a folder


code:
for line in f:
    row = line.split()
    if not row:
        continue
    if row[0] == 'H':
        header = dict_from_row(row[1:4])
    elif line[0] == 'XBO':
        xbo = dict_from_row(row[1:11])

rawDescription: Converting CNC drillings from old to new system (using Python)


code:
for name in alerts:
    disable_alert(name, alerts[name])

rawDescription: Using dictionary as a list

description: Using dictionary as a list


rawDescription: What's the pythonic way to cut a string at multiple positions?


code:
class Item(object):
    def __init__(self,name,price):
        self.name=name
        self.price=price

rawDescription: python list of dicts how to merge key:value where values are same?

description: Python list of dicts how to merge key:value where values are same


code:
s = 'AAAC**ACGTACGTA**ATTCC**GTGTGT**CCCC**TATACGTATACG**TTT'
sub=[]
l=[]
regon=[]
new=[re.search(r'(.+)\1+',i).group(0) for i in s.split('**')]
for i in new:
   p=principal_period(i)
   if p is not None and len(p)>1:
       l.append(p)
       sub.append(i)

for t in sub:
   regons.append(re.search(t,s).span())

z=zip(sub,l,regons)
out={i :{'repeat':i.count(j),'region':reg} for i,j,reg in z}
out

rawDescription: A more complex version of "How can I tell if a string repeats itself in Python?"


rawDescription: How to sort on number of visits in Django app?

description: Sort on number of visits in Django app


code:
approved_by = dom.getElementsByTagName('approved-by')
approved = approved_by[0].attributes['approved'].value

rawDescription: How to get sub attribute value in Python

description: Get sub attribute value in Python


code:
def read_config(section):
    defaults = {'apple': None,
                'pear': None,
                'banana': None }
    config = configparser.ConfigParser(defaults = defaults)
    config.read(location)
    if not config.has_section(section):
        config.add_section(section)

    apple = config.get(section,'apple')
    pear = config.get(section, 'pear')
    banana = config.get(section, 'banana')

    return apple, pear, banana

rawDescription: Python configparser getting and setting without exceptions


code:
for each_div in soup.find_all('div',{'class':'username'}):
    f.write(str(each_div.text) + "\n")

rawDescription: Python How to remove characters from a string inside a list


code:
ranges = [[np.min(lats), np.max(lats)], [np.min(longs), np.max(longs)]]
h, lat_range, long_range = np.histogram2d(lats, longs, bins=(400,400), range=ranges)
bad_h, lat_range2, long_range2 = np.histogram2d(bad_lats, bad_longs, bins=(400,400), range=ranges)

rawDescription: 3g coverage map - visualise lat, long, ping data


code:
# -*- coding: utf-8 -*-
from flask.ext.script import Manager
from extension import make_celery
from app import create_app

app = create_app()

celery = make_celery(app)

rawDescription: how to run celery if i use fbone?

description: Run celery if i use fbone


code:
# create sample data
foo = User(
    email='foo@example.com',
    tagset={'footag', 'something', 'tagbar'}
)
bar = User(
    email='bar@example.com',
    tagset={'something', '3rdtag'}
)
session.add(foo)
session.add(bar)
session.commit()

bar = session.query(User).get(2)
assert 'something' in bar.tagset
bar.tagset.remove('something')
assert 'something' not in bar.tagset

rawDescription: Creating a set-like mapped attribute in SQLAlchemy


rawDescription: How do I select and store columns greater than a number in pandas?

description: Select and store columns greater than a number in pandas


code: test(test=1, asterisk=2)

rawDescription: Is there any benefits for using * or ** in python?


code: 'The number is {:.0f}'.format(number)

rawDescription: Preventing auto scientific form for numbers in python3


code:
plt.fill(Router*rs[:,0], Router*rs[:,1],'blue')
plt.fill(Rinner*rs[:,0], Rinner*rs[:,1],'white')
plt.plot([0], [0], 'oy', ms=100)

rawDescription: How to fill between two rings with matplotlib

description: Fill between two rings with matplotlib


code:
tty_in = open('/dev/tty', 'r')
tty_out = open('/dev/tty', 'w')
fn = tty_in.fileno()
poll = select.poll()
poll.register(fn, select.POLLIN)

while True:
    if os.getpgrp() == os.tcgetpgrp(fn) and poll.poll(10):  # 10 ms
        # poll should only return if the input buffer is filled,
        # which is triggered when a user enters a complete line,
        # which lets the following readline call to not block on
        # a lack of input.
        userInput = tty_in.readline()
        # This should allow us to exit out
        if userInput.strip() == "quit":
            sys.exit()

rawDescription: Python script hanging when running in the background


rawDescription: How to define date range that spans years, months in Django?

description: Define date range that spans years, months in Django


code:
import monetdb.control

control=control.Control(port=port,passphrase=None)
control.create(database)
control.release(database)

rawDescription: How to setup a (new) monetdb db from scratch in python?

description: Setup a (new) monetdb db from scratch in python


code:
import unittest
import doctest
from project import views

def suite():
    suite = unittest.TestSuite()
    suite.addTest(doctest.DocTestSuite(views))
    return suite

rawDescription: Django doctests in views.py

description: Django doctests in views.py


code:
args=parser.parse_args(['--example','1'])
args
args.example *= 2

rawDescription: Create arg string from ArgumentParser parsed args in Python


code:
def f(): print("Foo!")

f()
f

rawDescription: Python: Why does calling just "f" run >4x faster than "f()"?


code:
sepration = 0.008 # decrease separation

Intensity = np.empty([points,points],np.float)

for i in range(points):
    y = sepration*(i - points/2) # centre on image
    for j in range(points):
        x = sepration*(j - points/2)

rawDescription: Density plot with python making a Diffraction pattern with Bessel Integrals but it wont stop running


code:
if (len(mapping) == len(collection) and
    len(set(itertools.chain.from_iterable(mapping.values()))) == len(collection)):
    print('A bijection exists')

rawDescription: Python Detect if one-to-one onto mapping exists


code:
listA = [0,1,2,1,2,1,2,3,4,5,3,4,5,6,0]
listB = [0,1,2,1,2,1,0]

def get_repeated_seq(seq, start, length):
    ref = seq[start:start+length]
    #print("Ref", ref)
    for pos in range(start+length, len(seq)-length):
        compare = seq[pos:pos+length]
        #print("Pos", pos, compare)
        if compare == ref:
            print("Found", ref, "at", pos)
            return pos
    return False

def get_repeated_seqs(seq):
    for size in reversed(range(2, len(seq)/2)):
        for pos in range(0, len(seq)-size):
            print("Check rep starting at pos %s for size %s" % (pos, size))
            get_repeated_seq(seq, pos, size)

print(get_repeated_seqs(listA))

rawDescription: Remove repeated sequence of integers from list in Python


code:
def func1 ():
  a = 1
  b = 2
  return a,b

def func2 (a, b):
  c = 3
  d = 4
  e = a * c
  f = b + d

a, b = func1()
print(a, b)
func2(a, b)

rawDescription: Python, simple example of multiple variables passed to another function


code:
from pamie30 import PAM30

ie1 = PAM30.PAMIE("http://www.google.com")
ie2 = PAM30.PAMIE("http://news.google.com")

rawDescription: How to open a New window in Python PAMIE

description: Open a New window in Python PAMIE


code: [man] [uomo]

rawDescription: Detect what is in brackets in two lines

description: Detect what is in brackets in two lines


code:
class CompetitionSearchForm(forms.Form):
    name = forms.CharField(required=False)
    type = forms.ChoiceField(choices=COMP_TYPE_CHOICES_AND_EMPTY, required=False)

rawDescription: ChoiceField doesn't display an empty label when using a tuple - am I doing something wrong?


rawDescription: Filter Pandas DataFrame by group with tag values


code: df.groupby(['Country', 'Product']).apply(lambda sdf: sdf[(sdf.Week.diff(1).fillna(1) != 1).astype('int').cumsum() == 0]).reset_index(drop=True)

rawDescription: Python Pandas: Eliminate a row from a dataframe if a value in a any preceding row in a groupby meets a certain criteria


code:
for dir, dirs, files in os.walk(src):
    files = [os.path.join(dir, f) for f in files if not f.endswith('.txt')]

rawDescription: How to exclude files extension from os.walk

description: Exclude files extension from os.walk


code: func_dict = dict((s, getattr(operator, s)) for s in ['lt', 'gt'])

rawDescription: Python: Pass inequality as string in dict for evaluation


code:
msg = 'ü' # len(msg) is 1 character
encoded_msg = msg.encode('utf-8') # len(encoded_msg) is 2 bytes
encoded_prefix = '{:0>5d}'.format(len(encoded_msg)).encode('utf-8')
full_message = encoded_prefix + encoded_msg # both are bytes, so we can concat

print(full_message) # prints: b'00002\xc3\xbc'

rawDescription: Byte formatting in python 3

description: Byte formatting in python 3


rawDescription: Why is day of pandas date_range not what I specified?


code:
# File: a.py

class Klass(object):
    pass

rawDescription: alias for python class in another module

description: Alias for python class in another module


code:
class Test(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    test_date = db.Column(db.DateTime)

    def __init__(self, test_date=None):
        if test_date is None:
            test_date = datetime.utcnow()

rawDescription: Parse date from string and insert with Sqlalchemy tosqlite


code: all(x == y for x, y in zip(variables, stuff))

rawDescription: Looking for a special PEP for IF Python statement


rawDescription: What is a more efficient way in Python to return list elements which are not in a second list?


code:
word_docxml = 'some text here {{form.letterdate|date:"Y-m-d"}} and " more text'
re.sub(r"(\{\{[^}]+}\})", lambda m: re.sub(""", '"', m.group(1)), word_docxml)

rawDescription: Between double curly braces: replace particular text


code:
from itertools import product, combinations

def all_fill(source, num):
    output_len = len(source) + num
    for where in combinations(range(output_len), len(source)):
        # start with every possibility
        poss = [[0,1]] * output_len
        # impose the source list
        for w, s in zip(where, source):
            poss[w] = [s]
        # yield every remaining possibility
        for tup in product(*poss):
            yield tup

rawDescription: Add bits in all possible places

description: Add bits in all possible places


rawDescription: How do I get the instance method's next-in-line parent class from `super()` in Python

description: Get the instance method's next-in-line parent class from `super()` in Python


code:
def matchIt(needle, haystack):
    """
    @param needle:   string, text to seek
    @param haystack: string, text to search in

    Return number of times needle is found in haystack,
        allowing overlapping instances.

    Example: matchIt('abab','ababababab') -> 4
    """
    lastSeenAt = -1
    timesSeen = 0
    while True:
        nextSeen = haystack.find(needle, lastSeenAt+1)
        if nextSeen==-1:
            return timesSeen
        else:
            lastSeenAt = nextSeen
            timesSeen += 1

rawDescription: Simplifying for-if messes with better structure?


code:
output_file = open(path_to_stored_dictionary, 'w')
output_file.write(str(my_dictionary))
output_file.close()

rawDescription: Make dictionary from dictionary string

description: Make dictionary from dictionary string


code: root.bind('<Control-Q>', _quit())

rawDescription: Tkinter bind problem

description: Tkinter bind problem


code:
hashstr = '%08X' % hash
hashstr = "".join(reversed([hashstr[i:i+2] for i in range(0, len(hashstr), 2)]))

rawDescription: Convert Delphi BufferToHex function to Python


code:
class MyClass(object):
    def __init__(self, val):
        self._foo = val
    def __repr__(self):
        return 'MyClass({})'.format(self._foo)
    @property
    def foo(self):
        return self._foo

import operator
min([MyClass(3), MyClass(1), MyClass(2)], key=operator.attrgetter('foo'))

rawDescription: min/max based on property (not attribute) of class object in python

description: Min/max based on property (not attribute) of class object in python


code: LOGIN_URL = 'django.contrib.auth.views.login' # path to view function

rawDescription: Django - use reverse url mapping in settings