code:
groups_of_four = [] # The initial binary string needs to be broken into chunks of 4, as that is the key
x = len(binary)
for i in range(0, x, 4): # Create a range where successive elements differ by 4, and goes from 0 to x
    chunk = binary[i:i+4] # create a chunk of length 4
    groups_of_four.append(chunk)

rawDescription: binary to hex dictionary

description: Binary to hex dictionary


code:
awidth = max(len(x) for x in a)
...
ww.write("%-*s\t%s\n" % (awidth, a[each], b[each]))

rawDescription: writing to a text file with proper allign

description: Writing to a text file with proper allign


rawDescription: How do I remove the first Item from a Python list?

description: Remove the first Item from a Python list


code:
dir(A)
import dis
dis.dis(A.__init__)  # disassemble the bytecode for A.__init__
dir(B)

rawDescription: Why doesn't this superclass run methods in a subclass during initialization?


code:
def drill(f, n, d, items=()):
    if n > 1:
        for i in range(d+1):
            drill(f, n-1, d-i, items+(i,))
    else:
        f(list(items) + [d])

rawDescription: Undetermined number of for loops depending on one parameter


rawDescription: regular expression python `r'*(.|:|?|!)*'`

description: Regular expression python `r'*(.|:|?|!)*'`


code: df.Date = pd.to_datetime(df.Date)

rawDescription: count of last n days per group

description: Count of last n days per group


code:
blob_info = blobstore.get(request.args.get('key'))
response = make_response(blob_info.open().read())
response.headers['Content-Type'] = blob_info.content_type
response.headers['Content-Disposition'] = 'filename="%s"' % blob_info.filename

rawDescription: How to serve pdf (or non-image) files through google app engine with python flask?

description: Serve pdf (or non-image) files through google app engine with python flask


code:
class _Opaque(ctypes.Structure):
    pass

rawDescription: Is it acceptable to subclass c_void_p in ctypes?


code: encrypt = Button(master, text='Encrypt', command=on_click) # without ( )

rawDescription: Implement a dynamic dropdown menu based on on the number of lines of text file


code:
d={}
for key,value in preschool_kids.items():
    if value[0] == color:
        d[key] = value # right way to assign a value to a key
print(d) # this prints the entire dictionary, and not the dictionary at each step

rawDescription: Searching for value in dictionary and return a new dictionary with the corresponding key and value


rawDescription: Get context root of an installed application on WAS 7 via wsadmin


rawDescription: Using ipcluster to connect to an OS X server w/ EPD from Linux?


code:
result = add.delay(8, 8)
result.wait() # wait for and return the result

rawDescription: Django, Python calling Python code without waiting for response?


rawDescription: Dynamically Build Dictionary From Different Lists


code:
Abstract: ""
AbstractText: ""
AbstractSource: ""
AbstractURL: ""
Image: ""
Heading: ""
Answer: ""
Redirect: ""
AnswerType: ""
Definition: ""
DefinitionSource: ""
DefinitionURL: ""
RelatedTopics: [ ]
Results: [ ]
Type: ""

rawDescription: duckduckgo API not returning results

description: Duckduckgo API not returning results


code:
def ref():
    idx = random.randint(0, n)
    c = 0
    found = False
    for k in D:
        for v in D[k]:
            if c == idx:
                found = True
                # do_something_with_val(k, v);
                break
            c += 1
        if found:
            break

def uut():
    idx = random.randint(0, n)
    for k, v in D.items():
        if idx < len(v):
            # do_something_with_val(k, v[idx])
            break
        else:
            idx -= len(v)

if __name__ == '__main__':
    print(timeit.timeit('ref()', setup="from __main__ import ref", number=1000))
    print(timeit.timeit('uut()', setup="from __main__ import uut", number=1000))

rawDescription: Select random element from "non uniform" python dictionary


code: value in dictionary or any(value in dictionary[key] for key in dictionary)

rawDescription: Using 'if in' with a dictionary

description: Using 'if in' with a dictionary


code:
import theLoggerThing
class Formation( object ):
    pass # details omitted.
def createFormations( logger ):
    pass # details omitted
formations= createFormations( theLoggerThing.logger )

rawDescription: I can't but help get the idea I'm doing it all wrong (Python, again)


code:
available_bikes = Variation.objects.filter(...
    ).exclude(
    Q(rentdate__startCar__range=(start_date, end_date)) |
    Q(rentdate__endCar__range=(start_date, end_date))
    )

rawDescription: What is efficient way of detecting if date range of object is occupied?


code:
key = {'key':'value'}
data = {'key2':'value2', 'key3':'value3'};
coll.update(key, data, {upsert:true});

rawDescription: mongodb: insert if not exists

description: Mongodb: insert if not exists


code:
import ruamel.yaml

with open('aaa.yaml') as f:
    result = ruamel.yaml.round_trip_load(f)

ruamel.yaml.round_trip_dump(result, sys.stdout)

rawDescription: yaml anchors definitions loading in PyYAML

description: Yaml anchors definitions loading in PyYAML


code:
b3.bind('<Return>', lambda _: closewindow())
b3.focus_set()

rawDescription: Tkinter Initial Cursor position and Enter to press button


code:
class Connection_XML(XML_Element_Class):
    def __init__(self):
        self.name = None
        self.type = None
        self.ID = None
        self.max_size = None
        self.queue_size = None
        self.direction = None
    def do_something(self):
        pass

rawDescription: python how to save new objects into a list without duplication

description: Python how to save new objects into a list without duplication


rawDescription: adding matrices to n dimensional array with numpy

description: Adding matrices to n dimensional array with numpy


code:
class A(object):
    pass
x = 1

rawDescription: Creating a variable inside of a for loop


code:
class Fighter(object):
    def __init__(self, prenom, weapon_size=None):
        ...
        self.weapon_size = weapon_size
        ...

    @property
    def damage(self):
        if self.weapon_size:
            return self.weapon_size / 2
        return None

rawDescription: Perform method when an attribute is added to a class in Python


code:
while 1:
    c = stdscr.getch()
    if c == ord('p'):
        PrintDocument()
    elif c == ord('q'):
        break  # Exit the while()
    elif c == curses.KEY_HOME:
        x = y = 0

rawDescription: Why use curses.ascii.islower?

description: Why use curses.ascii.islower


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


code:
def Comment(text=None):
    element = Element(Comment)
    element.text = text
    return element

rawDescription: How to output CDATA using ElementTree

description: Output CDATA using ElementTree


code:
import sys
import xml.etree.ElementTree

tree = xml.etree.ElementTree.parse(sys.stdin)
root = tree.getroot()

for node in root.iter('something'):
    if node.text == 'REPLACEME':
        node.text == 'NEWWORD'

tree.write(sys.stdout)

rawDescription: Manipulating stdin and redirect to stdout in Python


code:
class FoodForm(forms.ModelForm):
    category = CategoryModelChoiceField(queryset=Category.objects.all())
    time = TimeModelChoiceField(queryset=Category.objects.all())
    preparation = PreparationModelChoiceField(queryset=Category.objects.all())
    content = ContentModelChoiceField(queryset=Category.objects.all())
    class Meta:
        model = FoodItems
        fields = ('name','time', 'category', 'content', 'preparation', 'comment',)

rawDescription: Returning multiple values independently from __str__ for ModelChoiceField


code: 'Diesel' and 'Hatchback' in mydict.get('Bri')

rawDescription: Make sure that there are two values in a Dictionaries Key Python


code: np.diff(a) > 0

rawDescription: Efficiently check if numpy ndarray values are strictly increasing


code:
def mycustom_parser(unmarshaller, data):
    unmarshaller.append(data.split())
    unmarshaller._value = 0
xmlrpclib.Unmarshaller.dispatch['mycustom'] = mycustom_parser

rawDescription: How can you adjust xmlrpclib to interpret custom types?

description: Adjust xmlrpclib to interpret custom types


code: ', '.join(a.get('term') for a in l)

rawDescription: Python - Correct Method of Parsing

description: Python - Correct Method of Parsing


rawDescription: Efficiently Searching Nested Lists

description: Efficiently Searching Nested Lists


code: item_name = Icecream.objects.get(pk=icecream_id).values_list('name', flat=True)

rawDescription: Django, get an attribute from a model

description: Django, get an attribute from a model


code:
def query_in_string(query, string):
    return any(all(word.strip() in string for word in term.split('AND'))
               for term in query.split('OR'))

rawDescription: Determining if a query is in a string

description: Determining if a query is in a string


code:
import pandas as pd

pd.read_table('test.csv')\
  .drop_duplicates(subset=['ID'])\
  .to_csv('output.csv', index=None, sep='\t')

rawDescription: Python - Selecting All Row Values That Meet A particular Criteria Once


code:
# Default file storage mechanism that holds media.
DEFAULT_FILE_STORAGE = 'django.core.files.storage.FileSystemStorage'

rawDescription: Local filesystem as a remote storage in Django


code:
hexDig = ''.join('%02x' % ord(x) for x in h.digest())
int(hexDig, 16)

rawDescription: Operations on Python hashes

description: Operations on Python hashes


rawDescription: BeautifulSoup counting tags without parsing deep inside them


code:
def show_word(self):
    """ Shows the word behind the cell """
    if self.hidden == True:
        self.hidden = False
    else:
        self.hidden = True

    self.button["text"] = str(self)

    if mem.choice1 == None:
        mem.choice1 = [self.word, self.hidden]
    else:
        mem.choice2 = [self.word, self.hidden]
        self.check(mem.choice1, mem.choice2)

def check(self, choice1, choice2):
    """ Checks if the chosen words are a pair """
    tries = 0
    if choice1 == choice2:
        pass
    else:
        self.show_word

    tries += 1

rawDescription: Something wrong without any error - Includes Tkinter


code:
from operator import attrgetter
class Obj:
    def __init__(self, val):
        self.attr = val
lst = [Obj(x) for x in range(10)]
obj = max(lst, key=attrgetter('attr'))
obj
obj.attr

rawDescription: Get the object with the max attribute value in a list of objects


code:
def get_records(user, dt):
    return [record for record in user.records if dt <= record.datetime < dt + timedelta(days=7)]

userInfo   = [(user, get_records(user, dt)) for user in users if len(get_records(user, dt))]

rawDescription: Extracting two sets (class + class property) using list comprehension


code:
words = list(''.join(letters) for letters in itertools.product(consonants, vowels, consonants))
words[:10]

rawDescription: Python Consonant/Vowel Permutations

description: Python Consonant/Vowel Permutations


code:
transparency = im.info['transparency']
im.save('icon.gif', transparency=transparency)

rawDescription: Python Django how to rotate image and remove black color?


code:
# settings.py
...
FIELDS_STORED_IN_SESSION = ['register']

rawDescription: Login vs Register in PythonSocialAuth

description: Login vs Register in PythonSocialAuth


code:
import random
while True: # loops until break
    number = int(input("Would you like to use a 4, 6 or 12 sided die?\n"))
    if number == 4:
        import random
        random4 = random.randint(1, 4)
        print("Your 4 sided die rolled a" ,random4)
        break
    elif number == 6:
        import random
        random6 = random.randint(1, 6)
        print("Your 6 sided die rolled a" ,random6)
        break
    elif number == 12:
        import random
        random12 = random.randint(1, 12)
        print("Your 12 sided die rolled a" ,random12)
        break

rawDescription: Not quite sure what's happening when using "or" in python


code:
import  csv

from itertools import islice

with open("in.csv") as f, open("out.csv","w") as out:
    r = csv.reader(islice(f, start=5,stop=None))
    wr = csv.writer(out)
    wr.writerows(r)

rawDescription: Skipping more than one row in Python csv


code:
class change_to_goodbye():
    def __init__(self, hw):
            self.helloWorld = hw

    #other code

rawDescription: Changing Variables in Class from Other Classes (Python)


code:
class SpamUpdateView(UpdateView):
    def get_queryset(self):
        return super(SpamUpdateView, self).get_queryset().filter(foo_type=FOO_TYPE_AUTO)

class SpamListView(ListView):
    def get_queryset(self):
        return super(SpamListView, self).get_queryset().filter(foo_type=FOO_TYPE_AUTO)

rawDescription: Django Different form validation when adding and changing instance


code:
for key, value in data.items():
    print(key, value)

rawDescription: Printing output from json

description: Printing output from json


rawDescription: Pass dbf data to sentence and save as text file using Python 2.7


code: visited_states = [False] * math.factorial(9)

rawDescription: Best way to hash ordered permutation of [1,9]

description: Hash ordered permutation of [1,9]


code:
# logging_setup.py
from framework import logutils
logutils.set_up()

rawDescription: Logging in a Framework

description: Logging in a Framework


code:
import re
my_expression = r'[a-z]+|#.+'
f = 'dog;cat;mouse;bird;turtle;# just some animals'
s = 'dog;cat;mouse;bird;turtle;horse cow # just some animals'
re.findall(my_expression, f)
re.findall(my_expression, s)

rawDescription: How to Split String Using Delimiters

description: Split String Using Delimiters


code:
def _get_elements_by_tagName_ns_helper(parent, nsURI, localName, rc):
    for node in parent.childNodes:
        if node.nodeType == Node.ELEMENT_NODE:
            if ((localName == "*" or node.localName == localName) and
                (nsURI == "*" or node.namespaceURI == nsURI)):
                rc.append(node)
            _get_elements_by_tagName_ns_helper(node, nsURI, localName, rc)
    return rc

rawDescription: How to search for XML elements in python?

description: Search for XML elements in python


code: list3 = [e for e in list2 if e[0] in list1]

rawDescription: Find matching values in a list of lists using python


code:
sudodate = subprocess.Popen(["sudo", "date", "-s", "Thu Aug  9 21:31:26 UTC 2012"])
sudodate.communicate()

rawDescription: change date/time using python in linux

description: Change date/time using python in linux


code:
from collections import defaultdict
D = defaultdict(list)
[D[v].append(i) for i, v in enumerate(A)]

rawDescription: Dictionary Comprehension for list values


code: np.c_[x, y]

rawDescription: Load data from file and normalize

description: Load data from file and normalize


code:
import csv
from itertools import groupby
grouper = lambda rec: len(rec) > 0
with open("data.txt") as f:
    reader = csv.reader(f, delimiter=" ")
    res = [floater(items) for group, items in groupby(reader, key=grouper) if group]
res

rawDescription: Dealing with a list of lists in Python and selecting a subset of lists


code:
def auth_with_password(self, email, password):
    request_ref = 'https://auth.firebase.com/auth/firebase?firebase={0}&email={1}&password={2}'.\
        format(self.fire_base_name, email, password)
    request_object = self.requests.get(request_ref)
    return request_object.json()

rawDescription: Python Firebase authentication

description: Python Firebase authentication


code:
def is_new_style(cls):
    return str(cls).startswith('<class ')

rawDescription: Identifying that a variable is a new-style class in Python?


code:
pw = pg.plot()
timer = pg.QtCore.QTimer()
def update():
    pw.plot(x, y, clear=True)
timer.timeout.connect(update)
timer.start(16)

rawDescription: What is the easiest way to achieve realtime plotting in pyqtgraph


rawDescription: Count number of non-NaN entries in each column of Spark dataframe with Pyspark


code:
from sqlalchemy.sql import not_

# This fetches rows in python to determine which ones were removed.
Session.query(Table1).filter(not_(Table1.table2s.any())).delete(
    synchronize_session='fetch')

# If you will not be referencing more Table1 objects in this session then you
# can just ignore syncing the session.
Session.query(Table1).filter(not_(Table1.table2s.any())).delete(
    synchronize_session=False)

rawDescription: Delete rows without a related record using SQLAlchemy


code:
shape = [784, 625]
weights = tf.Variable(tf.random_normal(shape, stddev=0.01)/tf.sqrt(n))

rawDescription: How to manually initialize the values for the weights?

description: Manually initialize the values for the weights


code:
from collections import defaultdict
D = defaultdict(list)
for i,item in enumerate(mylist):
    D[item].append(i)
D = {k:v for k,v in D.items() if len(v)>1}

rawDescription: Identify duplicate values in a list in Python


code:
# 5th row will have random values
cov[4,:] = np.random.random(num_vars)

# 6th row will have a simple geometric sequence
cov[5,:] = np.arange(num_vars)**2

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code:
g = df_users.groupby(['userID', 'requestDate'])
f = feature_rollup
logged_apply(g, f)

rawDescription: Progress indicator during pandas operations (python)


code:
for elem in document.iter():
    if elem.tag == 'p' and not elem.getnext():
        elem.tail = ''

rawDescription: How to remove text not in tag using lxml?

description: Remove text not in tag using lxml


code:
import matplotlib.pyplot as plt

plt.plotfile('data.dat', delimiter=' ', cols=(0, 1),
             names=('col1', 'col2'), marker='o')
plt.show()

rawDescription: How to plot files with numpy

description: Plot files with numpy


code:
class PerObjectBackend(ModelBackend):

    def has_perm(self, user_obj, perm, obj=None):
        allowed = ModelBackend.has_perm(self, user_obj, perm)
        if perm.find('any') >=0 :
            return allowed

        if perm.find('edit') >=0 or perm.find('delete') >=0:
            if obj is None:
                raise Exception("Perm '%s' needs an object"%perm)
            if not obj.is_owned_by(user_obj):
                return False

        return allowed

rawDescription: Adding per-object permissions to django admin


code:
tosearch = "This is a text string where I typed hlelo but I meant to type hello."
import string
exclude = set(string.punctuation)
tosearch = ''.join(ch for ch in tosearch if ch not in exclude)
tosearch
words = set(tosearch.split(" "))

rawDescription: find a list of keywords from a text string and find inexact matches

description: Find a list of keywords from a text string and find inexact matches


code: res.reindex(["A", "B", "C"], fill_value=0)

rawDescription: Dont drop non present indexes on group_by - Pandas


code:
s = {'abc', 'defg', 'hij', 'kl', 'mno', 'qr', 'stuv', 'wx', 'yz'}
minimal(s, len)

rawDescription: Find all minimal elements in a list or set as weighted by a function


code: chmod +x /path/to/python-script.py

rawDescription: Can't execute Python script from PHP document


code:
st = "www.a.com/thing1.html"
filename = re.findall(r"/(\w+).",st)
filename
filename = "".join(filename) + '.txt'
filename
f = open(filename,'w')
f.writelines(st)

rawDescription: Python - Parse large list into separate text files by name and content


code:
import inspect

def auto_assign(func):
    signature = inspect.signature(func)

    def wrapper(*args, **kwargs):
        instance = args[0]
        bind = signature.bind(*args, **kwargs)
        for param in signature.parameters.values():
            if param.name != 'self':
                if param.name in bind.arguments:
                    setattr(instance, param.name, bind.arguments[param.name])
                if param.name not in bind.arguments and param.default is not param.empty:
                    setattr(instance, param.name, param.default)
        return func(*args, **kwargs)

    wrapper.__signature__ = signature # Restore the signature

    return wrapper

class Foo:
    @auto_assign
    def __init__(self, foo, bar, a=1, b=2, c=3):
        pass

f = Foo(10, 20)
g = Foo(100, 200, a=999)

print(f.__dict__)
print(g.__dict__)
print(inspect.getargspec(Foo.__init__))

rawDescription: Set class attributes from default arguments


code:
div = '
SKU: E02165
'
html = BeautifulSoup(div)
div_sku = html.find('div', {'class': 'sku'})
value = div_sku.get_text(strip=True).encode('ascii', 'ignore').split('SKU:')[1]
value

rawDescription: get encoded content from an div using soup

description: Get encoded content from an div using soup


code:
class exampleClass:
    """
    This is an example class to demonstrate my question to stack exchange
    """

    def __init__( self, fileName ):
        # Note: this will be modified when a file is loaded
        self.name = None

        exampleClass.loadData( self, fileName )

rawDescription: Defining a class property within __init__ as opposed to within another class method -- python


code:
from itertools import chain
list(chain.from_iterable(rep.get(c, [c]) for c in orig))

rawDescription: Replacing list item with contents of another list


code:
import numpy
d = numpy.loadtxt("mdat.txt", skiprows=2)
d

rawDescription: Reading Data in Columns Python 2.7.3

description: Reading Data in Columns Python 2.7.3


code:
from flask import Flask, render_template

app = Flask('flaskwp1')
# webcode = open('webcode.html').read() - not needed

@app.route('/')
def webprint():
    return render_template('webcode.html')

if __name__ == '__main__':
    app.run(host = '0.0.0.0', port = 3000)

rawDescription: Simple flask application that reads its content from a .html file. External style sheet being blocked?


code:
#!/usr/bin/python
import sys
import csv

f1 = sys.argv[1]
f2 = sys.argv[2]

with open(f1) as i, open(f2) as j:
    a = csv.reader(i)
    b = csv.reader(j)
    for linea in a:
        lineb = next(b)
        seta = set([x for x in linea if len(x) > 0])
        setb = set([x for x in lineb if len(x) > 0])
        print(len(seta^setb)==0)

rawDescription: Compare lines in 2 text files with different number of columns


code:
from twisted.internet.protocol import Protocol

class RandomProtocol(Protocol):
    def connectionMade(self):
        self.transport.registerProducer(RandomProducer(self.transport), False)

rawDescription: sending random data with Twisted

description: Sending random data with Twisted


code: chat()

rawDescription: Making multiple list items apply in python


code: match[0].isdigit() or match[0] == '/'

rawDescription: How to I check that a string contains only digits and / in python?


code:
strippedstring = re.sub(r'"[^"]*"', '', myString)
re.findall(r"\bstring", strippedstring)

rawDescription: re.match return match object only if pattern is not inside escaped string

description: Re.match return match object only if pattern is not inside escaped string


code:
from django.utils.html import strip_tags
strip_tags(string_value)

rawDescription: Blocking HTML tags in a webpage

description: Blocking HTML tags in a webpage


code:
def __getitem__(self, key):
    return self[key]

rawDescription: Python: Easily access deeply nested dict (get and set)


code: a+b

rawDescription: Automatically truncate numpy arrays

description: Automatically truncate numpy arrays


code:
import copy_reg
def _reduce_method(m):
    if m.im_self is None:
        return getattr, (m.im_class, m.im_func.func_name)
    else:
        return getattr, (m.im_self, m.im_func.func_name)

copy_reg.pickle(type(a.z), _reduce_method)
pickle.dumps(a.z)

rawDescription: Why can I pass an instance method to multiprocessing.Process, but not a multiprocessing.Pool?


code:
import mymodule

mol = mymodule.Molecule.fromFile('toto')

rawDescription: Python object creation from a function

description: Python object creation from a function


code:
class AdminView(Roled, ModelView):

    def __init__(self, *args, **kwargs):
        self.roles_accepted = kwargs.pop('roles_accepted', list())
        super(AdminView, self).__init__(*args, **kwargs)

rawDescription: flask-admin is_accessible usage

description: Flask-admin is_accessible usage


code:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def root():
    return "Hello World!"

@app.route("/xyz")
def xyz():
    return "Hello XYZ!"

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

rawDescription: Flask routing issues on CherryPy

description: Flask routing issues on CherryPy


code:
def filesOlderThan(path,day,hour,mins):
    delta= datetime.timedelta(days=day,hours=hour,minutes=mins)
    now= datetime.datetime.now()
    file_list = []
    for root, dirs, files in os.walk(path):
        for a in files:
            path1 = os.path.join(root, a)
            c_time = datetime.datetime.fromtimestamp(os.path.getctime(path1))
            if(now - delta < c_time):
                file_list.append(path1)
    return file_list

rawDescription: Get files created before x days, y hours and z minutes in python?


rawDescription: How do I match for symbols like < and > with regex in Python?

description: Match for symbols like < and > with regex in Python


code:
for i in range(72):
    setattr(self, 'entry{0}'.format(x), None)

rawDescription: Python attributes from variables?

description: Python attributes from variables


code:
yourlst = [(5, 6), (4, 1), (6, 7)]
sorted(yourlst, key=lambda t: (abs(t[0] - t[1]), t[0]), reverse=True)

rawDescription: Breaking ties in Python sort

description: Breaking ties in Python sort


code:
def find(self, name=None, attrs={}, recursive=True, text=None,
         **kwargs):
    """Return only the first child of this Tag matching the given
    criteria."""
    r = None
    l = self.find_all(name, attrs, recursive, text, 1, **kwargs)
    if l:
        r = l[0]
    return r

rawDescription: Why doesn't Beautifulsoup find this input by name?


code:
import time

class Example(object):
    def __init__(self, sleep_func=time.sleep):
        self.sleep_func = sleep_func

    def foo(self):
        self.sleep_func(10)
        print('Done!')

rawDescription: Can Python do DI seamlessly without relying on a service locator?


code:
_F_Cassa.paneconfig(_F_Left, width = 120, height = 400, sticky = E+W+S+N)
_F_Cassa.paneconfig(_F_Right, width =  200, height = 400, sticky = E+W+S+N)

rawDescription: Python 3.4 Tkinter - not able to give a size to frames in PanedWindow


rawDescription: Disable scientific notation in python json.dumps output


code:
mylist = []
mylist.append(id1)  # or however you get your id values
mylist.append(id2)
# ..

rawDescription: How to store two different values returned from query into list data types to be used later(plpy python)

description: Store two different values returned from query into list data types to be used later(plpy python)


code:
table
p = pd.pivot_table(table, index=["weekday"], columns=["weekofyear"], values="people", aggfunc=np.sum)
p
p.columns

rawDescription: Pivot_table MultiIndex to columns

description: Pivot_table MultiIndex to columns


code: no_duplicates = a[unique]

rawDescription: Efficiently Removing Very-Near-Duplicates From Python List


code:
class MainWindow(QMainWindow):
    def __init__(self):
        super(QMainWindow,self).__init__()
        self.tabWidget = QTabWidget(self)
        self.setCentralWidget(self.tabWidget)
        self.tabWidget.tabBar().installEventFilter(self)
        self.tabWidget.tabBar().previousMiddleIndex = -1

    def eventFilter(self, object, event):
        if object == self.tabWidget.tabBar() and \
            event.type() in [QEvent.MouseButtonPress,
                             QEvent.MouseButtonRelease] and \
            event.button() == Qt.MidButton:
            tabIndex = object.tabAt(event.pos())
            if event.type() == QEvent.MouseButtonPress:
                object.previousMiddleIndex = tabIndex
            else:
                if tabIndex != -1 and tabIndex == object.previousMiddleIndex:
                    self.onTabMiddleClick(tabIndex)
                object.previousMiddleIndex = -1
            return True
        return False

    # function called with the index of the clicked Tab
    def onTabMiddleClick(self, index):
        pass

rawDescription: PyQt mouse events for QTabWidget

description: PyQt mouse events for QTabWidget


code:
shops=['A','B','C','D']
[["-".join((min(a,b), max(a,b))) for b in shops if b != a] for a in shops]

rawDescription: Fast way of crossing strings in a list

description: Fast way of crossing strings in a list


code:
class account_invoice(models.Model):
    _inherit = 'account.invoice'

    @api.multi
    def your_method_to_change_state(self):
        self.write({'state': 'XXXXX'})

rawDescription: Odoo change workflow state from "more" button


rawDescription: What is the best escape character strategy for Python/MySQL combo?


code:
with open('somefile') as fp:
    for i, line in enumerate(fp):
        if i == some_number:
            a, *b, c, d, e, f = line.strip().split('|')
            b = '|'.join(b)

rawDescription: Chopping A Line From A Text Document Into Different Strings


code:
d = {}
for x in mylist:
    d[x] = 1
mylist = list(d.keys())

rawDescription: Deleting repeats in a list python

description: Deleting repeats in a list python


code:
from inflection import parameterize
from werkzeug.routing import BaseConverter

class IDSlugConverter(BaseConverter):
    """Matches an int id and optional slug, separated by "/".

    :param attr: name of field to slugify, or None for default of str(instance)
    :param length: max length of slug when building url
    """

    regex = r'-?\d+(?:/[\w\-]*)?'

    def __init__(self, map, attr='title', length=80):
        self.attr = attr
        self.length = int(length)
        super(IDSlugConverter, self).__init__(map)

    def to_python(self, value):
        id, slug = (value.split('/') + [None])[:2]
        return int(id)

    def to_url(self, value):
        raw = str(value) if self.attr is None else getattr(value, self.attr, '')
        slug = parameterize(raw)[:self.length].rstrip('-')
        return '{}/{}'.format(value.id, slug).rstrip('/')

rawDescription: Create a url with an article's title

description: Create a url with an article's title


code:
import argparse

def print_file(filename):
    with open(filename) as fi:
        print(fi.read())

parser = argparse.ArgumentParser(description="A program to do something.")
parser.add_argument('-p', help='Print a plain file.', action='store')

args = parser.parse_args()

if args.p:
    print_file(args.p)

rawDescription: Storing code inside a dictionary

description: Storing code inside a dictionary


rawDescription: what would be the pythonic way to find out if a given date belongs to the current week?

description: What would be the pythonic way to find out if a given date belongs to the current week


code:
# folder2/__init__.py
from . import class2

rawDescription: Python - Import from deeper subfolder

description: Python - Import from deeper subfolder


code:
from matplotlib.collections import LineCollection
import matplotlib.dates as mpd

x=mpd.date2num(df.index.to_pydatetime())
y=df.winds.values
c=df['temp'].values
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
lc = LineCollection(segments, cmap=plt.get_cmap('copper'), norm=plt.Normalize(0, 10))
lc.set_array(c)
lc.set_linewidth(3)
ax=plt.gca()
ax.add_collection(lc)
plt.xlim(min(x), max(x))
ax.xaxis.set_major_locator(mpd.HourLocator())
ax.xaxis.set_major_formatter(mpd.DateFormatter('%Y-%m-%d:%H:%M:%S'))
_=plt.setp(ax.xaxis.get_majorticklabels(), rotation=70 )
plt.savefig('temp.png')

rawDescription: Pandas Dataframe Multicolor Line plot

description: Pandas Dataframe Multicolor Line plot


code:
m1 = create_matrix(100,13)
m2 = create_matrix(100,13)
m3 = create_matrix(100,13)
...

rawDescription: Python - How to Create N variables

description: Python - How to Create N variables


code:
import reprlib

obj = [[1, 2, 3], list(range(10000))]

print(reprlib.repr(obj))

rawDescription: Limiting print output

description: Limiting print output


rawDescription: Is there a more Pythonic way to pad a string to a variable length using string.format?


code:
class x(models.Model):
    date = models.DateField()
    value = models.FloatField()

rawDescription: Django Group By Weekday?

description: Django Group By Weekday


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

def random_data(N):
    # Generate some random data.
    return np.random.uniform(70., 250., N)

# Data lists.
N = 1000
x = random_data(N)
y = random_data(N)
z1 = random_data(N)
z2 = random_data(N)

order = np.argsort(-z1)
x = np.take(x, order)
y = np.take(y, order)
z1 = np.take(z1, order)
z2 = np.take(z2, order)

cm = plt.cm.get_cmap('RdYlBu')
plt.scatter(x, y, s=z1, c=z2, cmap=cm, alpha=0.7) # alpha can be 0 ~ 1
plt.colorbar()

plt.show()

rawDescription: Plot larger points on bottom and smaller on top


code:
import ruamel.yaml

copyfile('all.isv', '/home/ubuntu/tmp/deploy/all')
with open("/home/ubuntu/ansible-environments/aws/lp/all", 'r') as f1:
    oldvars = ruamel.yaml.round_trip_load(f1)

rawDescription: Copy content from one YAML to another YAML after comparison of keys


rawDescription: Execute code when extending a class in Python


code:
from urllib.request import FancyURLopener
urlretrieve = FancyURLopener().retrieve

rawDescription: Download progressbar for Python 3

description: Download progressbar for Python 3


code:
def merge(a, b):
    l = lambda x, y: y if np.isnan(x) else x
    l = np.vectorize(l)
    return map(l, a, b)

rawDescription: How to concatenate an empty array with Numpy.concatenate?

description: Concatenate an empty array with Numpy.concatenate


code:
class Report(object):
    """
    Contains all information contained in a report
    """
    def __init__(self, periodStart, periodEnd, sendTime):
        self.period_start = periodStart
        self.period_end = periodEnd
        self.send_time = sendTime
        self.send_timestamp = (sendTime - datetime(1970, 1, 1)).total_seconds()
        self.period_length = (periodEnd - periodStart).total_seconds()

    def __cmp__(self, other):
        return cmp(self.send_time, other.send_time)

rawDescription: how to sort class on datetime, sort collections.deque

description: Sort class on datetime, sort collections.deque


rawDescription: Python’s argh library: preserve docstring formatting in help message


code: list(getSubs(Root))

rawDescription: Static attribute that is True only for a concrete class, and False for its children in Python


code:
graph = sps.rand(10, 10, density=0.1, format='csr')
data, indptr, indices = graph.data, graph.indptr, graph.indices
non_empty_rows, = np.nonzero(np.diff(graph.indptr))
sorted_out = {}
for j in non_empty_rows:
    weight_slice = data[indptr[j]:indptr[j+1]]
    out_slice = indices[indptr[j]:indptr[j+1]]
    sorted_out[j] = out_slice[np.argsort(weight_slice)]

rawDescription: How to read a sparse directed graph in scipy

description: Read a sparse directed graph in scipy


code:
int(float(3289568273632879456235))  # Notice, the different result due to loss of precision.
int(float(3289568273632879456235)) == int(float(3289568273632879456236))  # different numbers, same result due to "truncation"

rawDescription: different answer in javascript and python with large number- Division or mod operator

description: Different answer in javascript and python with large number- Division or mod operator


code:
from __future__ import print_function

def contains(a, b):
    for v in b:
        if not any(v == u for u in a):
            return False
    return True

def match(a, b):
    return contains(a, b) and contains(b, a)

target = [1,2,3,4,5]
data = ([3,5,1,2,4], [1,2,3,4,5,6], [1,2,3,4,6], [3,1,2,1,4])

print(target)
for seq in data:
    print(seq, contains(target, seq), contains(seq, target), match(target, seq))

rawDescription: How can I use python code which will iterate into two list and will find out whether they matches or not

description: Use python code which will iterate into two list and will find out whether they matches or not


rawDescription: Sort python dictionaries with 'value' as primary key and 'key' as secondary


code:
comment_re = re.compile(
    r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
    re.DOTALL | re.MULTILINE
)

def comment_replacer(match):
    start,mid,end = match.group(1,2,3)
    if mid is None:
        # single line comment
        return ''
    elif start is not None or end is not None:
        # multi line comment at start or end of a line
        return ''
    elif '\n' in mid:
        # multi line comment with line break
        return '\n'
    else:
        # multi line comment without line break
        return ' '

def remove_comments(text):
    return comment_re.sub(comment_replacer, text)

rawDescription: Python regex question: stripping multi-line comments but maintaining a line break


code:
fig = plt.figure()
a = fig.add_subplot(1,1,1, rasterized=True)

rawDescription: rasterizing matplotlib axis contents (but not frame, labels)

description: Rasterizing matplotlib axis contents (but not frame, labels)


code: -math.pow(3, float(1)/3)

rawDescription: Cubic root of the negative number on python


rawDescription: Pandas: Number of unique days in a timestamp Series


code:
inside = ['thing', 'other thing']
in_hand = ['sword', 'lamp']
inside += in_hand
inside

rawDescription: Good way to concatenate str to list?

description: Good way to concatenate str to list


code: import conf.general

rawDescription: Importing modules to a package

description: Importing modules to a package


code:
from itertools import chain

writer.writerow(chain([ID], wordList))

rawDescription: write two values to csv row in python

description: Write two values to csv row in python


code:
bus = dbus.SessionBus()
dbusWindowOne = bus.get_object('com.example.MyInterface', '/com/example/MyInterface/WindowOne')
showWindowOne = dbusWindowOne.get_dbus_method('show', 'com.example.MyInterface.Window')
updateWindowOne = dbusWindowOne.get_dbus_method('update', 'com.example.MyInterface.WindowOne')

rawDescription: How export methods with dbus in a extended class in python, inherited methods?


code:
pprint.pprint(browser.form.controls[-2].items)
# [<Item name='1' id=None selected='selected' contents='Volume of orders for the domestic market' value='1' label='Volume of orders for the domestic market'>,
#  <Item name='2' id=None contents='Orders for export' value='2' label='Orders for export'>,
#  <Item name='3' id=None contents='The volume of production' value='3' label='The volume of production'>,
#  <Item name='4' id=None contents='The volume of sales' value='4' label='The volume of sales'>,
#  <Item name='5' id=None contents='Stocks of finished goods' value='5' label='Stocks of finished goods'>,
#  <Item name='6' id=None contents='Access to credit for the company' value='6' label='Access to credit for the company'>,
#  <Item name='7' id=None contents='Change in the number of employees' value='7' label='Change in the number of employees'>]

choices=[item.attrs['value'] for item in browser.form.controls[-2].items]
print(choices)
# ['1', '2', '3', '4', '5', '6', '7']

browser.form['name_tatser']=['2']
browser.submit()

rawDescription: How can I scrape data from the Israeli Bureau of Statistics web query tool?

description: Scrape data from the Israeli Bureau of Statistics web query tool


code:
for name in dir():
    if not name.startswith('_'):
        del globals()[name]

rawDescription: Is there a way to delete created variables, functions, etc from the memory of the interpreter?


code: pd.to_timedelta(df['time'], unit='s') + pd.Timestamp('2014-01-01')

rawDescription: How to generate time series from a series of ordered numbers in Python's pandas

description: Generate time series from a series of ordered numbers in Python's pandas


code:
def lisp(x):
    return '(%s)' % ' '.join(lisp(y) for y in x) if isinstance(x, list) else x

d = lisp(d[0])

rawDescription: Parsing a lisp file with Python

description: Parsing a lisp file with Python


code:
captcha_count = CaptchaStore.objects.count()
self.failUnlessEqual(captcha_count, 1)

rawDescription: How to unit test a form with a captcha field in django?

description: Unit test a form with a captcha field in django


code:
from django.contrib import admin
from myproject.myapp.models import Author

admin.site.register(Author)

rawDescription: how can I display models data in django

description: Display models data in django


code:
CMS_PLUGIN_PROCESSORS = (
    'yourapp.cms_plugin_processors.wrap_plugin',
)

rawDescription: Wrap every plugin separately in Django CMS


code:
PARAMETERS = [
    'param1',
    'param2',
    # ...
]

meta = Meta()
for name in PARAMETERS:
    setattr(meta, name, param[name])

rawDescription: Dealing with a high volume of query params in python


code:
Category: Orange
OR - ORANGE
LI - LIME
LE - LEMON

Category: Red
AP - APPLE
ST - STRAWBERRY

rawDescription: How to match up two dictionaries in Python

description: Match up two dictionaries in Python


code:
fig, ax = plt.subplots(1, 1)
ax.get_xaxis().set_visible(False)   # Hide Ticks
df.plot(table=np.round(df.T, 2), ax=ax)

rawDescription: Adding datalabels - matplotlib barchart

description: Adding datalabels - matplotlib barchart


code:
def edit_article(request):
    article = Article.get(...)
    data = request.POST or {}
    data.setdefault('fieldname','default value')
    form = MyForm(data, article)

rawDescription: how to give a pre-defined value to TexareaField?

description: Give a pre-defined value to TexareaField


code:
def cartesian(a, b, c):
    for items in product(get_chunks(a, 2), get_chunks(b), get_chunks(c)):
        yield items

rawDescription: Cartesian product that returns outputs of varied lengths


rawDescription: Add some characters at the beginning of each line


code:
def power_at_each_point(x_cord, y_coord):
    f = lambda x: cal_pow_rec_plandwall(x, [x_coord, y_coord])
    return max(f(each_node) for each_node in xrange(1, len(Node_Positions_Ascending) + 1))

rawDescription: I want to sort a list in a method with respect to the method's argument


code:
self.sorted_data = [(updated_records.pop(recid, value), recid)
                    for (value, recid) in self.sorted_data]

rawDescription: Python: update a list of tuples... fastest method


code:
N = 10
[random.randint(0,sys.maxsize) for _ in range(N)]

rawDescription: How to Generate N random numbers in Python 3 between 0 to infinity


code:
('root', 130)
('unutbu', 55)
('www-data', 7)
('avahi', 2)
('haldaemon', 2)
('daemon', 1)
('messagebus', 1)
('syslog', 1)
('Debian-exim', 1)
('mysql', 1)

rawDescription: How to print the top 10 users by the number of processes?

description: Print the top 10 users by the number of processes


code:
some_data = list(range(4))
export_with_name(some_data)

rawDescription: Export function that names the export file after the input variable


code:
from math import floor
def floored_percentage(val, digits):
    val *= 10 ** (digits + 2)
    return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

floored_percentage(0.995, 1)
floored_percentage(0.995, 2)
floored_percentage(0.99987, 2)

rawDescription: Python string.format() percentage to one decimal place


code:
with open('youtube-dl', 'rb') as f:
    header = f.readline()
    zipfile = f.read()

with open('youtube-dl-new', 'wb') as f:
    print >> f, '#!/your/new/hashbang/line'
    f.write(zipfile)

rawDescription: Python youtube-dl recompile

description: Python youtube-dl recompile


code:
import signal
signal.signal(signal.SIGINT, signal.SIG_IGN)

import subprocess
cat = subprocess.Popen(['cat'])
subprocess.call(['gdb', '--pid=%d' % cat.pid])

rawDescription: How do you automate the launching/debugging of large scale projects?

description: Automate the launching/debugging of large scale projects


code:
d.x[0:3] = [8, 8, 8]
# an index operation is really a function call on the given object
# eg. the following has the same effect as the above
d.x.__setitem__(slice(0, 3, None), [8, 8, 8])

rawDescription: Use built-in setattr simultaneously with index slicing


code:
replacement_map = {}
for key, value in zip(list1, list2):
    try:
        replacement_map[key].append(value)
    except KeyError:
        replacement_map[key] = [value]

rawDescription: Python CSV: write rows according to dict mapping


rawDescription: argument order in numpy.apply_along_axis

description: Argument order in numpy.apply_along_axis


code:
class ManyToManyTagField(ManyToManyField):

    def formfield(self, **kwargs):
        defaults = {
            'form_class': TagField,
        }
        return super(ManyToManyTagField, self).formfield(**defaults)

    def save_form_data(self, instance, data):
        tags = []
        for tag_id in data:
            autocompletedTag = tag_id.find('___')
            if autocompletedTag > 0:
                parts = tag_id.split('___')
                tags.append(parts[0])
            else:
                newTag = Tag(name=tag_id, category=TagCategory.objects.get(name='New'))
                newTag.save()
                tags.append(newTag.id)

        return super(ManyToManyTagField, self).save_form_data(instance, tags)

rawDescription: Django model pre save for custom ManyToManyField


code: fields = tuple(field.strip() for field in line.split(','))

rawDescription: Creating a python dictionary from a line of text


code:
import pandas as pd
nfp = pd.read_csv("NFP.csv", parse_dates=[0], infer_datetime_format=True)
temp = pd.DatetimeIndex(nfp['DateTime'])
nfp['Date'] = temp.date
nfp['Time'] = temp.time
del nfp['DateTime']

print(nfp)

rawDescription: Split datetime64 column into a date and time column in pandas dataframe


code:
('a' or 'b' or 'c')
('b' or 'a' or 'c')
('' or '' or 'a')
(0 or 0 or 1)
(False or False or True)

rawDescription: Python - function to do string comparison


rawDescription: Adding one polygon to a plot using matplotlib-basemap


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-u", action='store_true')
parser.add_argument("-d")
args = parser.parse_args()

if args.u and not args.d:
    parser.error('You must use the -d switch when setting -u!')

rawDescription: Python handling options and args

description: Python handling options and args


code:
# Setup
from collections import deque
from random import choice
used = deque(maxlen=7)

# Now your sampling bit
item = random.choice([x for x in list1 if x not in used])
used.append(item)

rawDescription: Display random choice (Python)

description: Display random choice (Python)


code:
data = dict()
for covar_type in covs:
    for num in num_comp:
        # covar_type is the same for all iterations of this loop
        # hence only the last one "survives"
        data[covar_type] = GMM(...)

rawDescription: Python: list iteration only returns last value


code:
if isinstance(tag,BeautifulSoup.Tag) and tag.name in ('a','b','i'):
    if tag.name=='a':
        del tag['onclick']
    print(tag)

rawDescription: Using Beautiful Soup to strip html tags from a string


code:
def heatmap_binary(df,
            edgecolors='w',
            #cmap=mpl.cm.RdYlGn,
            log=False):
    width = len(df.columns)/7*10
    height = len(df.index)/7*10

    fig, ax = plt.subplots(figsize=(20,10))#(figsize=(width,height))

    cmap, norm = mcolors.from_levels_and_colors([0, 0.05, 1],['Teal', 'MidnightBlue'] ) # ['MidnightBlue', Teal]['Darkgreen', 'Darkred']

    heatmap = ax.pcolor(df ,
                        edgecolors=edgecolors,  # put white lines between squares in heatmap
                        cmap=cmap,
                        norm=norm)
    data = df.values
    for y in range(data.shape[0]):
        for x in range(data.shape[1]):
            plt.text(x + 0.5 , y + 0.5, '%.4f' % data[y, x], #data[y,x] +0.05 , data[y,x] + 0.05
                 horizontalalignment='center',
                 verticalalignment='center',
                 color='w')

    ax.autoscale(tight=True)  # get rid of whitespace in margins of heatmap
    ax.set_aspect('equal')  # ensure heatmap cells are square
    ax.xaxis.set_ticks_position('top')  # put column labels at the top
    ax.tick_params(bottom='off', top='off', left='off', right='off')  # turn off ticks

    ax.set_yticks(np.arange(len(df.index)) + 0.5)
    ax.set_yticklabels(df.index, size=20)
    ax.set_xticks(np.arange(len(df.columns)) + 0.5)
    ax.set_xticklabels(df.columns, rotation=90, size= 15)

    # ugliness from http://matplotlib.org/users/tight_layout_guide.html
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", "3%", pad="1%")
    fig.colorbar(heatmap, cax=cax)

rawDescription: Annotate heatmap with value from Pandas dataframe


code:
class Stats(object):
   def __init__(self):
      self.count = 0
      self.subdirs = {}

counts = Stats()
for p in paths:
   parts = p.split('/')
   branch = counts
   for part in parts[1:]:
      branch = branch.subdirs.setdefault(part, Stats())
   branch.count += 1

rawDescription: Python: recursively create dictionary from paths


code:
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
_, axes = plt.subplots(subplot_kw=dict(projection='3d'))
axes.plot_surface(x, y, z, cmap=plt.get_cmap('winter'))
plt.show()

rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code: output = list(grouper(paths))

rawDescription: Group Python list of lists into groups based on overlapping items


code:
by_factory
by_factory["Bali"]

rawDescription: Python - sumif from csv

description: Python - sumif from csv


code:
with open(filec , 'r') as f:
    lines = f.readlines() # readlines creates a list of the lines

rawDescription: Ways to read/edit multiple lines in python


code: df['date'] = pd.to_datetime(df['year'] + df['month'].str.zfill(2), format='%Y%m')

rawDescription: Converting date using to_datetime

description: Converting date using to_datetime


code: key_name = vertex1.name + ' > ' + vertex2.name

rawDescription: Storing a directed, weighted, complete graph in the GAE datastore


code:
like_apples_keys = UserLikes.all(keys_only=True).filter(food='apples')
user_keys = [key.parent() for key in like_apples_keys]
users_who_like_apples = db.get(user_keys)

rawDescription: modelling the google datastore/python

description: Modelling the google datastore/python


code: tables = root.cssselect('h3:contains(Impact) ~ table')

rawDescription: How to find and select a table in html code with xpath

description: Find and select a table in html code with xpath


code:
'demo  with   multiple    spaces'.split(' ')
'demo  with   multiple    spaces'.split()

rawDescription: What happens if we split by a delimiter yet have multiple of those delimiters in a row?


rawDescription: python encode hex pad every character with 00

description: Python encode hex pad every character with 00


code: help(re)

rawDescription: regEx: To match two groups of chars

description: RegEx: To match two groups of chars


code:
import itertools as it

# setup: create a map with tuples [(0,0,0,0)‥(3,3,3,3)] as keys
# and values [chr(0)‥chr(255)], because PIL does not yet support
# 4 colour palette images

TUPLE2CHAR= {}

# Assume (b7, b6) are pixel0, (b5, b4) are pixel1…
# Call it "big endian"

KEY_BUILDER= [
    (0, 64, 128, 192), # pixel0 value used as index
    (0, 16, 32, 48), # pixel1
    (0, 4, 8, 12), # pixel2
    (0, 1, 2, 3), # pixel3
]
# For "little endian", uncomment the following line
## KEY_BUILDER.reverse()

# python2.6 has itertools.product, but for compatibility purposes
# let's do it verbosely:
for ix0, px0 in enumerate(KEY_BUILDER[0]):
    for ix1, px1 in enumerate(KEY_BUILDER[1]):
        for ix2, px2 in enumerate(KEY_BUILDER[2]):
            for ix3, px3 in enumerate(KEY_BUILDER[3]):
                TUPLE2CHAR[ix0,ix1,ix2,ix3]= chr(px0+px1+px2+px3)

# Another helper function, copied almost verbatim from itertools docs
def grouper(n, iterable, padvalue=None):
    "grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')"
    return it.izip(*[it.chain(iterable, it.repeat(padvalue, n-1))]*n)

# now the functions
def seq2str(seq):
    """Takes a sequence of [0..3] values and packs them into bytes
    using two bits per value"""
    return ''.join(
        TUPLE2CHAR[four_pixel]
        for four_pixel in grouper(4, seq, 0))

# and the image related function
# Note that the following function is correct,
# but is not useful for Windows 16 colour bitmaps,
# which start at the *bottom* row…
def image2str(img):
    return seq2str(img.getdata())

rawDescription: How do I convert any image to a 4-color paletted image using the Python Imaging Library?

description: Convert any image to a 4-color paletted image using the Python Imaging Library


rawDescription: ropemacs USAGE tutorial

description: Ropemacs USAGE tutorial


code:
class SpinBox(BoxLayout):
    """A widget to show and take numeric inputs from the user.

    :param min_value: Minimum of the range of values.
    :type min_value: int, float
    :param max_value: Maximum of the range of values.
    :type max_value: int, float
    :param step: Step of the selection
    :type step: int, float
    :param value: Initial value selected
    :type value: int, float
    :param editable: Determine if the SpinBox is editable or not
    :type editable: bool
    """

    min_value = NumericProperty(float('-inf'))
    max_value = NumericProperty(float('+inf'))
    step = NumericProperty(1)
    value = NumericProperty(0)
    range = ReferenceListProperty(min_value, max_value, step)

    def __init__(self, btn_size_hint_x=0.2, **kwargs):
        super(SpinBox, self).__init__(orientation='horizontal', **kwargs)

        self.value_label = Label(text=str(self.value))
        self.inc_button = TimedButton(text='+')
        self.dec_button = TimedButton(text='-')

        self.inc_button.bind(on_press=self.on_increment_value)
        self.inc_button.bind(on_time_slice=self.on_increment_value)
        self.dec_button.bind(on_press=self.on_decrement_value)
        self.dec_button.bind(on_time_slice=self.on_decrement_value)

        self.buttons_vbox = BoxLayout(orientation='vertical',
                                      size_hint_x=btn_size_hint_x)
        self.buttons_vbox.add_widget(self.inc_button)
        self.buttons_vbox.add_widget(self.dec_button)

        self.add_widget(self.value_label)
        self.add_widget(self.buttons_vbox)

    def on_increment_value(self, btn_instance):
        if float(self.value) + float(self.step) <= self.max_value:
            self.value += self.step

    def on_decrement_value(self, btn_instance):
        if float(self.value) - float(self.step) >= self.min_value:
            self.value -= self.step

    def on_value(self, instance, value):
        instance.value_label.text = str(value)

rawDescription: How to allow infinite integer values in a spinner?

description: Allow infinite integer values in a spinner


code:
#!/usr/bin/env python3.5
import sys
from pathlib import Path

src_dir = Path('/Users/alowe/Desktop/testdir2') # source directory
for path in src_dir.glob('*.mp3'): # list all mp3 files in source directory
    if '-' in path.name: # move the mp3 file if the hyphen is present in the name
        dst_dir = src_dir / path.name.split('-', 1)[0].rstrip() # destination
        dst_dir.mkdir(exist_ok=True) # create the leaf directory if necessary
        path.replace(dst_dir / path.name) # move file

rawDescription: Automatically move files with python

description: Automatically move files with python


rawDescription: How to rapidly create array of N 3x3 matrices from 9 arrays of size N?

description: Rapidly create array of N 3x3 matrices from 9 arrays of size N


code:
def foo(x, k=None):
    if k is None:
        k = len(x)
    ...

rawDescription: How do I change an argument in a python function?

description: Change an argument in a python function


code:
arr = np.memmap('mm', dtype='float32', mode='w+', shape=(1,10000000))
type(arr)
x = np.ones((1,10000000))
type(x)
arr[:] = x
type(arr)
arr = x
type(arr)

rawDescription: Correct way to do operations on Memmapped arrays


code: '|'.join(['nn' if i.startswith('gw') else i for i in s.split('|')])

rawDescription: How to use regex substitute using different capture and match strings?

description: Use regex substitute using different capture and match strings


code:
import re
s1 = "Fantini, Rauch, C.Straus, Priuli, Bertali: 'Festival Mass at the Imperial Court of Vienna, 1648' (Yorkshire Bach Choir & Baroque Soloists + Baroque Brass of London/Seymour)"
s2 = "Vinci, Leonardo {c.1690-1730}: Arias from Semiramide Riconosciuta, Didone Abbandonata, La Caduta dei Decemviri, Lo Cecato Fauzo, La Festa de Bacco, Catone in Utica. (Maria Angeles Peters sop. w.M.Carraro conducting)"
s1w = re.findall('\w+', s1.lower())
s2w = re.findall('\w+', s2.lower())

rawDescription: Python: how many similar words in string?


code:
if hasattr(time, 'tzset'):
    # Move the time zone info into os.environ. See ticket #2315 for why
    # we don't do this unconditionally (breaks Windows).
    os.environ['TZ'] = self.TIME_ZONE
    time.tzset()

rawDescription: Does configuring django's setting.TIME_ZONE affect datetime.datetime.now()?


code:
import mechanize
br=mechanize.Browser()
br.open('http://www.yourfavoritesite.com')
br.select_form(nr=0) #check yoursite forms to match the correct number
br['Username']='Username' #use the proper input type=text name
br['Password']='Password' #use the proper input type=password name
br.submit()
br.retrieve('https://www.yourfavoritesite.com/pagetoretrieve.html','yourfavoritepage.html')

rawDescription: Python Auto Fill with Mechanize

description: Python Auto Fill with Mechanize


rawDescription: reinterpret signed long as unsigned in Python

description: Reinterpret signed long as unsigned in Python


code:
import glob
from datetime import datetime
from lxml import etree

def file_timestamp(filepath):
    """Return the timestamp from a file name"""
    filename = os.path.split(filepath)[1]
    filename = os.path.splitext(filename)[0]
    if '_' in filename:
        return filename.split('_')[1]
    return None

class Datafiles(object):
    def __init__(self, dir_path):
        self.date_cache = {}
        self.dir_path = dir_path

    def __iter__(self):
        return self.files()

    def next(self):
        return self.files().next()

    def files(self):
        filepaths = glob.glob(self.dir_path + '*_*.xml')
        filepaths = sorted(filepaths, key=file_timestamp)

        for filepath in filepaths:
            ## Parse data (xml)
            data = self.parse_file(filepath)
            ## If year/month is seen before, skip
            date = datetime.strptime(data['period'].text, '%m%Y')
            month = (date.year, date.month)
            if month in self.date_cache:
                continue

            ## Else store date and yield
            self.date_cache[month] = filepath
            yield data

    def parse_file(self, filepath):
        # YOUR XML PARSING HERE
        return etree.parse(filepath)

rawDescription: python 2.7 working with multiple xml

description: Python 2.7 working with multiple xml


code:
import re
re.match('(\s*)(.*)', "    That's four spaces").groups()

rawDescription: Split leading whitespace from rest of string


code:
import scipy.stats as ss
import numpy as np
np.random.seed(0)
data = np.random.randn(100)
ss.kstest(data, "t", args = (2, ))
Out[45]: KstestResult(statistic=0.093219139130061066, pvalue=0.33069879934011182)

rawDescription: What Arguments to use while doing a KS test in python with student's t distribution?


rawDescription: Find right URLs using Python and regex

description: Find right URLs using Python and regex


code:
def valid_date(datestring):
    try:
        datetime.datetime.strptime(datestring, '%Y-%m-%d')
        return True
    except ValueError:
        return False

rawDescription: match dates using python regular expressions

description: Match dates using python regular expressions


rawDescription: how to access values of nested dictionary keys in python?

description: Access values of nested dictionary keys in python


code:
def f(n):
    for x in range(2, n + 1): # Since smaller will be at most n
        y = 2 * n - x # Since x + y must be 2 * n
        if is_prime(x) and is_prime(y):
            return [x, y]

rawDescription: Finding a pair of prime numbers with a given arithmetic average using Python


rawDescription: How does struct.unpack and struct.pack works?


code: obj == eval(repr(obj))

rawDescription: When __repr__() is called?

description: When __repr__() is called


rawDescription: Rearranging a (list of lists) matrix using list comprehensions only


code:
import re
link_re = re.compile('(https?://\S+)')
links = link_re.findall(text)

rawDescription: Translating PHP’s preg_match_all to Python


code:
with open(outfile, "w+") as fOut:
    strArray = list(map(str, array))
    fOut.writelines(strArray)

rawDescription: Writing Array to txt file with requested name


code:
def do_stuff(sender, user, request, **kwargs):
    if getattr(request, 'user', None) and not request.user.is_superuser:
        request.do_stuff = True

rawDescription: Django Middleware, single action after login


code:
from ete3 import Tree, TreeStyle, add_face_to_node, TextFace

from random import randint

def rotation_layout(node):
    if node.is_leaf():
        F = TextFace(node.name, tight_text=True)
        F.rotation = randint(0, 360)
        add_face_to_node(TextFace("third" ), node, column=8, position="branch-right")
        add_face_to_node(TextFace("second" ), node, column=2, position="branch-right")
        add_face_to_node(F, node, column=0, position="branch-right")

        F.border.width = 1
        F.inner_border.width = 1

def get_example_tree():
    t = Tree()
    t.populate(10)
    ts = TreeStyle()
    ts.rotation = 45
    ts.show_leaf_name = False
    ts.layout_fn = rotation_layout

    return t, ts

if __name__ == "__main__":
    t, ts = get_example_tree()
    t.show(tree_style=ts)

rawDescription: How to change the font orientation on node labels with ETE Toolkit (Python)

description: Change the font orientation on node labels with ETE Toolkit (Python)


code:
given_list = ["e.x.a", "m.p.l.e", "ex.am.ple"]
given_list.sort(key=lambda x: (x.count("."), len(x)), reverse=True)
given_list

rawDescription: Sorting a list using two keys

description: Sorting a list using two keys


code:
for args in handlers:
    some_method(*args)

rawDescription: elegant unpacking variable-length tuples

description: Elegant unpacking variable-length tuples


code:
same_list = ['Time - is an illusion.', 'Lunchtime - which is delicious - is an illusion.']
end_matches(*same_list)          # unpack the list into individual positional arguments

rawDescription: strings match after a certain character

description: Strings match after a certain character


code:
class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.TextField(default='This user hasn\'t said anything about themselves yet')
    img = models.ImageField(upload_to=gen_name, default="static/imgs/default/default_user.jpg")
    points = models.IntegerField(default=0)
    liked_replies = models.ManyToManyField(ForumReply)

rawDescription: Django voting system: Prevent duplicate votes


code:
if not hasattr(obj, "__iter__"): #returns True if type of iterable - same problem with strings
    obj = list(obj)
return obj

rawDescription: python, wrap and object into a list if not is an iterable

description: Python, wrap and object into a list if not is an iterable


code: GameFormSet = modelformset_factory(Game, form=GameForm, extra=1)

rawDescription: How can I have a modelformset with inline modelform?

description: Have a modelformset with inline modelform


code:
class proto(parentProtocol):
    def stringReceived(self, data):
        if data == "this":
            self.sendString("that")
        elif data == "foo":
            self.sendString("bar")
        # and so on

rawDescription: How to properly trigger a python twisted transport?

description: Properly trigger a python twisted transport


code:
def Element(_tag, attrib=None, nsmap=None, **_extra):
    return _makeElement(_tag, NULL, None, None, None, None, attrib, nsmap, _extra)

rawDescription: Adding a tail to lxml.etree.Element upon creation


code:
from locale import atof
import locale

locale.setlocale(locale.LC_ALL, 'de_DE')
import re

wrong_type = object()

def atof_try(x):
    try:
        return atof(x.split()[0])
    except ValueError:
        return wrong_type

def atof_pre(x, patt=re.compile("^\d+")):
    try:
        _atof = atof_try(x)
        if _atof is not wrong_type:
            return _atof
        temp = patt.search(x)
        return int(temp.group())
    except (ValueError, IndexError, AttributeError):
        return wrong_type

def merge_types(l, out):
    for ele in l:
        if atof_pre(ele) is not wrong_type:
            yield ele
        else:
            out.append(ele)

rawDescription: Sort numeric lines with thousand separators


code: tree.insert('', 'end', text = 'your text', tags = ('oddrow',))

rawDescription: ttk treeview: alternate row colors

description: Ttk treeview: alternate row colors


code:
def readn(sock, n):
    buf = ''
    while n > len(buf):
        newbuf = sock.recv(n - len(buf))
        if not newbuf:
            raise something
        buf += newbuf
    return buf

def readmsg(sock):
    msgtype = readn(sock, 4).decode('ascii')
    size = struct.unpack('!I', readn(sock, 4))
    data = readn(sock, size)
    return msgtype, size, data

rawDescription: Why callbacks are "ugly"?

description: Why callbacks are "ugly"


code:
keys = set()
for subdct in dct.values():
    keys |= set(subdct)

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code: (used-cached)/total

rawDescription: Python system resources enumeration

description: Python system resources enumeration


code:
import itertools

def all_permutations_substrings(a_str):
    return (
        ''.join(item)
        for length in xrange(1, len(a_str)+1)
        for item in itertools.permutations(a_str, length))

rawDescription: Python permutations including substrings


code:
import serial
import time

x = [0,0,0]
ser = serial.Serial('/dev/ttyAMA0', 9600)
buffer = ''
clear_buffer = time.time() + 60
while True:
    if time.time() >= clear_buffer:
        buffer = ''
        clear_buffer = time.time() + 60
    buffer += ser.read(ser.inWaiting())
    if '\n' in buffer:
        if buffer[0] == '$':
            x1 = buffer.rstrip()
            x2= x1.split(",")
            print((x2[0]),(x2[1]),(x2[2]))
        buffer = ""
        clear_buffer = time.time() + 60

rawDescription: Timeout after X second in Python

description: Timeout after X second in Python


code:
p = Point()
hexadecimal_id = hex(id(p))
present = hexadecimal_id in repr(p)

rawDescription: Object's unique identifier (translate from hexadecimal into decimal)


code: valid_end = (int(len(instances)*VALIDATION_END) // CHANNELS + 1) * CHANNELS

rawDescription: Whats the most pythonic way to do this?

description: Whats the most pythonic way to do this


code:
allDays = np.array([day1, day2, day3])
allDays.shape

rawDescription: How to merge multiple arrays in python?

description: Merge multiple arrays in python


code:
with open("greenEggsAndHam.txt", "r") as myfile:
   for line in myfile:
       print(" ".join([w.upper() if w == "i" else w for w in line.split()]))

rawDescription: How do I make a single letter in a string uppercase

description: Make a single letter in a string uppercase


code: months = ["jan", "feb", "mar", ... ]

rawDescription: Python-Rainfall Statistics

description: Python-Rainfall Statistics


code:
class MyDefaultdict(defaultdict):
    new_attr = None
d = MyDefaultdict(int)
d.new_attr = "some value"

rawDescription: Giving attributes to an object in Python


rawDescription: How to minimize chi squared for 3 linear fits

description: Minimize chi squared for 3 linear fits


code:
def flat(lst):
    for i in lst:
        if isinstance(i, list):
            for j in flat(i):
                yield j % 2
        else:
            yield i % 2

print(sum(flat(list_of_lists)))

rawDescription: Count odds in list of lists

description: Count odds in list of lists


code:
import numpy
from scipy.spatial import KDTree
tree = KDTree(numpy.array(ecef_cities))

rawDescription: Python - how to speed up calculation of distances between cities


code:
def getLen(obj):
    val = nested_getattr(obj, field)
    if val is None:
        return 0
    else:
        return len(val)
return maxk(obj, key=getLen)

rawDescription: Handling NoneType in len() while in a Python lambda expression?


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

spf = wave.open('music.wav','r')

signal = spf.readframes(-1)
signal = np.fromstring(signal, 'Int8')

plt.figure(1)
plt.title('Signal Wave...')
plt.plot(signal)
plt.show()

rawDescription: Python wav plot, the graph is not plotting


rawDescription: Python Version Specific Code

description: Python Version Specific Code


code:
my_function(test, this, out, like, so,
                   something, indent)

rawDescription: Python coding style on function call with multiple parameters


code:
# reshape array that is (N,M) to one that is (N,M,1)   no increase in size happens.
n1=np.reshape(noisyImage,noisyImage.shape+(1,))
if(i==1):
    result=n1
else:
#   concatenate the N,M,1 version of the array to the stack using the third index (last index) as the axis.
    result=np.concatenate(result,n1,axis=n1.ndim-1)

rawDescription: Stacking images as numpy array

description: Stacking images as numpy array


code:
test = test if is_iterable(test) else [test]
for x in test:
    do_stuff
    ...

rawDescription: Pythonic way of looping over variable that is either an element or a list


rawDescription: Dictionary value sorting

description: Dictionary value sorting


code:
X = np.arange(10*2).reshape((10,2)); X
L = np.random.randint(0,2,10); L
L.choose(X.T)
# or otherwise
np.choose(L, X.T)

rawDescription: Slicing numpy.ndarray by column index

description: Slicing numpy.ndarray by column index


code:
class DefaultDict(dict):
    defaults = {}

    def __getitem__(self, key):
        if key in self.defaults:
            return self.defaults[key](self)
        return super(DefaultDict, self).__getitem__(key)

    def __setitem__(self, key, value):
        if key in self.defaults:
            raise RuntimeError('Default key: %s' % key)
        super(DefaultDict, self).__setitem__(key, value)

# alt. 1
o1 = DefaultDict()
o1.defaults = {'c': lambda d: d['a'] + d['b']}
o1['a'] = 1
o1['b'] = 2
assert o1['c'] == 3

# alt. 2
class DefaultDict1(DefaultDict):
    defaults = {'c': lambda d: d['a'] + d['b']}

o2 = DefaultDict1()
o2['a'] = 1
o2['b'] = 2
assert o2['c'] == 3

rawDescription: derived value in a python map

description: Derived value in a python map


code:
import mycext
mycext.do_stuff()

rawDescription: How to Reload a Python3 C extension module?

description: Reload a Python3 C extension module


code:
def login(browser):
    browser.open(config.login_url)
    browser.select_form(nr=0)
    browser[config.username_field] = config.username
    browser[config.password_field] = config.password
    browser.submit()
    return browser

rawDescription: python and mechanize.open()

description: Python and mechanize.open()


code:
df.insert(0,'adjusted_day',df.index)
df.adjusted_day = df.adjusted_day.apply(lambda x: (x + timedelta(days=-plus_days)).day)
df[(df.index.day>=from_day) | ((df.adjusted_day <=from_day) & (df.adjusted_day >=from_day-plus_days))]

rawDescription: Select day of month as start of date range using Pandas


code:
from mod import fn
...
fn()

rawDescription: personal libraries C-like in Python

description: Personal libraries C-like in Python


code:
from operator import mul
reduce(mul, (v + 1 for v in d.values()))

rawDescription: Setting a variable equal to a returned value from a for loop in Python


code:
self.slider = tk.Scale(self.root, label="First Slider", from_=0, to=100, orient="horizontal")
self.slider.bind("<ButtonRelease-1>", self.updateValue)

rawDescription: Python - Tkinter - Get the name and value of scale/slider


code:
import numpy as np

def periodic_corr_np(x, y):
    """Periodic correlation, implemented using np.correlate.

    x and y must be real sequences with the same length.
    """
    return np.correlate(x, np.hstack((y[1:], y)), mode='valid')

rawDescription: circular cross correlation python

description: Circular cross correlation python


rawDescription: list of dicts to/from dict of lists

description: List of dicts to/from dict of lists


rawDescription: python - how to convert a nested list to a list of all individual sub-lists

description: Python - how to convert a nested list to a list of all individual sub-lists


code:
def OnTossUpTimer(self, event):
    self.tossuptimer -= 1
    if self.tossuptimer > 0:
        self.tossupbutton.SetLabel(str(self.tossuptimer) + "Seconds")
    else:
        self.tossupbutton.SetLabel("Time is Up!")
        self.tossuptimer_timer.Stop()

def TossUpTimer(self, event):
    self.tossuptimer = 5
    self.tossupbutton.SetLabel(str(self.tossuptimer) + "Seconds")
    self.tossuptimer_timer = wx.Timer(self)
    self.Bind(wx.EVT_TIMER, self.OnTossUpTimer, self.tossuptimer_timer)
    self.tossuptimer_timer.Start(1000, False)

rawDescription: While loop is taking forever and freezing screen?


code:
dists = np.arange(0,10,.5)
r = 5
dr = 1
np.where(dists >= r)
np.where(dists <= r+dr)
np.where(dists >= r) and np.where(dists <= r+dr)

rawDescription: Numpy where function multiple conditions


code:
from StringIO import StringIO
reader = StringIO(my_string)
integer, short = struct.unpack('>ih', reader.read(6))
custom = customType.Unpack(reader.read(3))

rawDescription: Read bytes from string in Python

description: Read bytes from string in Python


code:
import csv
with open('<inputfile>','r') as f , open('<outputfile>','w') as of:
    reader = csv.reader(f, delimiter=' ')
    writer = csv.writer(of, delimiter=' ')
    for lines in reader:
            key = lines.pop(0)
            for i in range(0,len(lines),2):
                    writer.writerow([key, lines[i], lines[i+1]])

rawDescription: Convert adjacency matrix to a csv file

description: Convert adjacency matrix to a csv file


code: self.dimension = 1 if self.texture_size[0] < self.texture_size[1] else 0

rawDescription: How can I fit text in label in Kivy?

description: Fit text in label in Kivy


code:
yield self.sleepjob(timedelta(seconds=1))
yield self.sleepjob(seconds=1)

rawDescription: Python generator's 'yield' in separate function


code:
import requests
from bs4 import BeautifulSoup

url = "http://www.animeplus.tv/anime-show-list/"
session = requests.session()
session.get(url)
response = session.get(url)  # open up the page second time
soup = BeautifulSoup(response.content)
print(soup.title.text)  # prints: "Watch Anime | Anime Online | Free Anime | English Anime | Watch Anime Online - AnimePlus.tv"

rawDescription: Python error trying to parse webpage

description: Python error trying to parse webpage


code: complement(l, range(12))

rawDescription: Python: How do I find the complement of a list?


code:
correct_order = ['AAA', 'AA+',...,'BBB+', 'BBB', 'BB+',...]
the_lists.sort(key=lambda l: correct_order.index(l[0]))

rawDescription: Custom Sort List Using a Reference Order


code:
for node in traverse_nodes(nodes[0]):
    print(node)

rawDescription: Chaining of Python generators to traverse a nested data structure; best practices


code:
import collections
import itertools

a = 2#define the variables
b = 1
c = 7
d = 4
e = (a*b)+b#calcualtions
f = c+b
g = (d/a)-b
h = c*a
i = a+b+d
j = c-a
k = c-d*f
l = c+a
m = (c*a)-b
n = a*d
o = a+d-b
p = (c*d)-a*(b+d)
q = a*(c+(d-b))
r = (d*d)-b
s = r-f-g

dat = collections.defaultdict(list)
for c in "abcdefghijklmnopqrs":
    dat[eval(c)].append(c)

rawDescription: Python 2D array with same values

description: Python 2D array with same values


code:
for list in list_of_lists:
    list[2:] = list[2:].clip(0, None)

rawDescription: numpy array - replace certain values

description: Numpy array - replace certain values


code:
def sequences(l):
    x2 = cycle(l)
    next(x2)
    grps = groupby(l, key=lambda j: j + 1 == next(x2))
    yield from (tuple(v) + (next((next(grps)[1])),) for k,v in grps if k)

print(list(sequences(x)))

rawDescription: Finding groups of increasing numbers in a list


rawDescription: "Slicing" in Python Expressions documentation


code:
N = source_ax.xaxis.get_major_ticks()
target_ax.xaxis.set_major_locator(LinearLocator(N))

rawDescription: align grid lines on two plots

description: Align grid lines on two plots


code:
re.search(r'(?<=//).+(?= \" target)',
          'http://example.com/path/to/whatever " target').group(0)

rawDescription: Regex to return all characters until "/" searching backwards


rawDescription: Extracting subplot coordinates in Python


rawDescription: Numpy: how to roll 1 "row" in an array of arrays


rawDescription: Splitting a string and adding the digits inside of the string


code:
#views.py
@view_config(route_name='view_customer', renderer='templates/view_customer.jinja2')
def view_page(request):
    customer_no = request.matchdict['customer']
    cust_slcustm = DBSessionRO.query(Slcustm).filter(Slcustm.customer == customer_no).first()
    cust_customer = DBSessionRO.query(Custom).filter(Custom.cu_custref== customer_no).first()
    cust_books = DBSessionRW.query(Customer).filter(Customer.name == customer_no).first()

    # Return a 404 if a result isn't found, slcustm and customer share one2one relationship on customer_no
    if cust_slcustm is None:
        return HTTPNotFound('No such customer')

    return dict(cust_slcustm=cust_slcustm, cust_customer=cust_customer, cust_books=cust_books)

rawDescription: SQLAlchemy Query foreignkey field(s)

description: SQLAlchemy Query foreignkey field(s)


rawDescription: Python re.sub back reference not back referencing


code:
import pandas as pd

def value(item):
    return item[item.find('=')+1:]

df = pd.read_table('data.txt', header=None, delimiter=',',
                   converters={i:value for i in range(5)},
                   names='symbol exchange timestamp price quantity'.split())
print(df)

rawDescription: Reading key-value pairs into Pandas

description: Reading key-value pairs into Pandas


code:
from datetime import datetime
import pytz
LA = pytz.timezone('America/Los_Angeles')
UTC = pytz.UTC

dt = LA.localize(datetime(2011, 11, 5, 12, 30))
dt7_bad = next_7am(dt)      # pytz won't like this
dt7_good = LA.localize(next_7am(dt.replace(tzinfo=None)))

dt_utc = dt.astimezone(pytz.UTC)
print(dt7_bad.astimezone(pytz.UTC) - dt_utc)   # 18:30:00 (Wrong)
print(dt7_good.astimezone(pytz.UTC) - dt_utc)  # 19:30:00 (Right)

rawDescription: How do I find the next 7am in a timezone

description: Find the next 7am in a timezone


code: document: 7   # < the 8th document

rawDescription: Load specific PyYAML documents from file


code:
import math
test = math.inf

rawDescription: How can I represent an infinite number in Python?

description: Represent an infinite number in Python


code:
def row_gen(cursor, some=1000):
    fetch = cursor.fetchmany
    while True:
        rows = fetch(some)
        if not rows: break
        for row in rows:
            yield row

rawDescription: Inserting query results into new table using loop instead of fetchall (Python, SQLite)


code:
from collections import Counter
d1 = {'eggs':3, 'ham':2, 'toast':1}
d2 = {'eggs':2,'ham':1}
dresult = Counter(d1) + Counter(d2)  #Counter({'eggs': 5, 'ham': 3, 'toast': 1})

rawDescription: Merge dictionaries without overwriting, rather an addition of value if key equality


code:
class TransactionForm(forms.ModelForm):

    # Replace category in the model with hieararchial category list
    category = TreeNodeChoiceField(queryset=Category.objects.all())

    class Meta:
        model = Transaction
        fields = ('transaction_type', 'notes', 'category', 'amount', 'date')

    def __init__(self, *args, **kwargs):
        # Get the user
        user_id = kwargs.pop('user_id')
        super(TransactionForm, self).__init__(*args, **kwargs)
        categories = self.fields['category'].queryset
        # Use the user to filter categories by user
        # Only change the queryset of the category field
        self.fields['category'].queryset = categories.filter(user=user_id) #just temporary, without check.

    def save(self):
        super(TransactionForm, self).save()

rawDescription: Django TreeNodeChoiceForm update

description: Django TreeNodeChoiceForm update


code: date = VALID_DATE.match(text)

rawDescription: Naming convention for Python regular expressions?


rawDescription: Recalling information from dictionaries within dictionaries


code:
from flask import send_file

@app.route('/path')
def view_method():
    response = send_file(tempFileObj, as_attachment=True, attachment_filename='myfile.jpg')
    return response

rawDescription: How to send image generated by PIL to browser?

description: Send image generated by PIL to browser


code:
lol = [[1,3],[3,4]]
from operator import setitem

map(lambda x: setitem(x, 1, -2), lol)
print(lol)
[[1, -2], [3, -2]]

rawDescription: How to perform a 'one-liner' assignment on all elements of a list of lists in python

description: Perform a 'one-liner' assignment on all elements of a list of lists in python


code:
c = self.request.get("category")
cat_get = Category.all().filter("title =", c).get()

rawDescription: GAE: How to use ReferenceProperty in django forms?


code: output = check_output(command.split(" "),stderr=subprocess.STDOUT)

rawDescription: Split check_output return value

description: Split check_output return value


code:
last_month = today.month - 1 if today.month>1 else 12
last_month_year = today.year if today.month > last_month else today.year - 1

Order.objects.filter(created_at__year=last_month_year, created_at__month=last_month)

rawDescription: How can i query for objects in current year , current month in django

description: Query for objects in current year , current month in django


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button

Builder.load_string("""
<Boxes>:
    boxes: _boxes
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        ScreenManager:
            size_hint: 1, .9
            id: _screen_manager
            Screen:
                name: 'screen1'
                BoxLayout:
                    orientation: 'vertical'
                    padding: 50
                    id: _boxes
            Screen:
                name: 'screen2'
                Label:
                    text: 'Another Screen'
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'bottom'
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, .1
            Button:
                text: 'Go to Screen 1'
                on_press: _screen_manager.current = 'screen1'
            Button:
                text: 'Go to Screen 2'
                on_press: _screen_manager.current = 'screen2'""")

class Boxes(FloatLayout):
    def __init__(self, **kwargs):
        super(Boxes, self).__init__(**kwargs)
        bx1 = BoxLayout(orientation='horizontal')
        bx2 = BoxLayout(orientation='horizontal')
        bx3 = BoxLayout(orientation='horizontal')
        bx4 = BoxLayout(orientation='horizontal')

        for i in range(1,2):
            bx1.add_widget(Button(text=str(i)))
        for i in range(2,5):
            bx2.add_widget(Button(text=str(i)))
        for i in range(5,7):
            bx3.add_widget(Button(text=str(i)))
        for i in range(7,11):
            bx4.add_widget(Button(text=str(i)))

        self.boxes.add_widget(bx1)
        self.boxes.add_widget(bx2)
        self.boxes.add_widget(bx3)
        self.boxes.add_widget(bx4)

class TestApp(App):
    def build(self):
        return Boxes()

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

rawDescription: Making a layout with variable number of columns per row in kivy?


code:
# use xrange
for i in xrange(0, count):
    # UNPACK FIXED LENGTH OF BINARY DATA HERE
    yield (field1, field2, field3)

rawDescription: How to write a memory efficient Python program?

description: Write a memory efficient Python program


code:
m = Message.objects.create(*args)
emails = ModelWithEmails.active.values_list('email', flat=True)
Recipient.objects.bulk_create([Recipient(message=m, email=email) for email in emails])

rawDescription: Creating many related objects like INSERT ... SELECT in SQL


code:
def _get(self, section, conv, option):
    return conv(self.get(section, option))

def getfloat(self, section, option):
    return self._get(section, float, option)

rawDescription: Why does ConfigParser items() give raw strings while get() returns bool/float/etc?


code:
from itertools import takewhile
beginPosit = tempans.index('007 A000000 Y')
new=takewhile(lambda x: '007 ' in x, tempans[beginPosit:])

rawDescription: Program Control-Flow in Python

description: Program Control-Flow in Python


code: url(r'^', include('polls.urls')),

rawDescription: How do I setup django with apache so that my appliction is at the root url?

description: Setup django with apache so that my appliction is at the root url


code:
from collections import Counter
counter = Counter([1,2,5,3,2])
counter[1]

rawDescription: Histogram which do not use bin intervals but concrete values


rawDescription: Python Numpy intersect1d on 1D array with 2D array


code:
t = time.strptime('2015-8-10','%Y-%m-%d')
t
t.tm_mon
type(t.tm_mon)
str(t.tm_mon)

rawDescription: Python And Date Formats

description: Python And Date Formats


code: a[row, col] = values

rawDescription: Convert row-column-value data to an array - numpy


code:
from genshi.template import TextTemplate
ip_vlan1 = TextTemplate("10.10.${id+100}.5")
ip_vlan2 = TextTemplate("10.11.${2*id+1}.6")
print( ip_vlan1.generate(id=3) ) # prints 10.10.103.5
print( ip_vlan2.generate(id=5) ) # prints 10.11.11.6

rawDescription: How to calculate value for a expression in a string, then return a new string?

description: Calculate value for a expression in a string, then return a new string


rawDescription: Sorting 5 elements with minimum element comparison


code:
template.format(a=a,
                b=b,
                c=c,
                d=d)

rawDescription: Python: split method call into multiple lines


code:
def flatten(lst):
    for elem in lst:
        if isinstance(elem, (list, tuple)):
            for nested in flatten(elem):
                yield nested
        else:
            yield elem

def nested(x, ys):
    return any(x == nested for nested in flatten(ys))

rawDescription: How to check if an element is in a nested list?

description: Check if an element is in a nested list


rawDescription: Functional assignment in numpy

description: Functional assignment in numpy


code:
pd.DataFrame({
    'date': pd.to_datetime(s).dt.date,
    'time': pd.to_datetime(s).dt.time})

rawDescription: How can I split a DataFrame column with datetimes into two columns: one with dates and one with times of the day?

description: Split a DataFrame column with datetimes into two columns: one with dates and one with times of the day


code:
two_skip_bigrams = list(skipgrams(text, n=2, k=2))
two_skip_trigrams = list(skipgrams(text, n=3, k=2))

rawDescription: How to compute skipgrams in python?

description: Compute skipgrams in python


code:
import wx
class oranges(wx.Frame):

    def __init__(self,parent,id):
        wx.Frame.__init__(self,parent,id,'Testing',size=(300,300))
        self.frame=wx.Panel(self)
        subtract=wx.Button(self.frame,label='-',pos=(80,200),size=(30,30))
        self.Bind(wx.EVT_BUTTON,self.sub,subtract)

        self.trying=[]
        self.trying.append(wx.StaticText(self.frame,-1,'',pos=(200,200)))
        self.trying.append(wx.StaticText(self.frame,-1,'',pos=(250,200)))

        self.something=0

    def sub(self,event):
        self.something += 1
        for i in self.trying:
            i.SetLabel(str(self.something))

if __name__ =='__main__':
    app = wx.PySimpleApp()
    window = oranges(parent=None,id=-1)
    window.Show()
    app.MainLoop()

rawDescription: Why can't I destroy my StaticText in wxPython?


code:
capitalLetters = len([letter for letter in x if letter.isupper()])
print(capitalLetters)

rawDescription: Counting if the word entered is a capital letter in a loop in Python 3


code: ((i + 40) * i for i in xrange(60))

rawDescription: What is correct python syntax for this kind of list comprehension?


code: dic = { k: [(x, y[0]) for x,y in v]  for k,v in dic.items()}

rawDescription: How to change a tuple within a value of a dictionary?

description: Change a tuple within a value of a dictionary


code:
FunctionType = type(lambda: 0)
help(FunctionType)

rawDescription: Synthetic functions in python

description: Synthetic functions in python


code:
class MyObject(object):
    def __init__(self):
        self.l=[]

def ret(self):
    self.l.append(randint(10,15))
    return self

rawDescription: Return statement in method that modifies in-place


code:
xx = [2, 1]
xx.sort()
print(xx)

rawDescription: how to sort the date list in python

description: Sort the date list in python


code:
import sys

def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True,
             "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")

rawDescription: python command line yes/no input

description: Python command line yes/no input


rawDescription: Django slice template tag not working with negative indices


rawDescription: Regex Python not matching, but does on regexpal


code:
frank
rachel
james

rawDescription: Using Python to generate URLs with names from txt


rawDescription: Defining variables efficiently according to a parameter that may take several values


code: a = array.array('c', open(filename, 'rb').read())

rawDescription: Open file into array, search for string and return value


code:
d={'^name':'Data','name^':'DATA','na^me':'DAta'}
for i in l :
  s=s.replace(i,d[i])

s

rawDescription: search substrings and replace them after analyzing

description: Search substrings and replace them after analyzing


rawDescription: How to mix named and unnamed string formatting

description: Mix named and unnamed string formatting


code:
import inspect
import linecache

class X():

    def __init__(self):
        if not linecache.getline(__file__,
            inspect.getlineno(inspect.currentframe().f_back)
        ).startswith("with "):
            raise Exception("Should only be used with `with`")

    def __enter__(self):
        return self

    def __exit__(self, *exc_info):
        pass

rawDescription: How to check if an object is created with `with` statement?

description: Check if an object is created with `with` statement


code:
s = "Cat(Money(8)Points(80)Friends(Online(0)Offline(8)Total(8)))Mouse(Money(10)Points(10000)Friends(Online(10)Offline(80)Total(90)))"
tokens = iter(s.replace("(", " ( ").replace(")", " ) ").split())
pprint(parse(tokens))

rawDescription: Extract data from within parenthesis in python


code: df.pivot_table(index='id', columns='name', values='value', aggfunc='sum')

rawDescription: pivot table(?) with a Pandas Dataframe

description: Pivot table(?) with a Pandas Dataframe


code: file_handle.write('\t'.join('%s' % f for f in fruits))

rawDescription: write fortran-like format to file in python

description: Write fortran-like format to file in python


rawDescription: How do I turn my urls into readable names?

description: Turn my urls into readable names


rawDescription: Decimal to hex in python

description: Decimal to hex in python


code:
with open("input.fasta") as ecoli: # will close your file automatically
    from collections import defaultdict
    counts = defaultdict(int)
    for line in ecoli: # iterate over file object, no need to read all contents into memory
        if line.startswith(">"): # skip lines that start with >
            continue
        for char in line: # just iterate over the characters in the line
            if char in {"A", "C", "D", "E", "F", "G", "H", "I", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y"}:
                    counts[char] += 1
    total = float(sum(counts.values()))
    for key,val in counts.items():
        print("{}: {}, ({:.1%})".format(key,val, val / total))

rawDescription: Python Dict and Forloop with FASTA file

description: Python Dict and Forloop with FASTA file


code:
self.widget_dict = {}
some_boxsizer.Add(some_widget)  # this is the first widget, so its ID is zero
self.widget_dict[some_widget] = 0

rawDescription: wxPython: access sizer of GUI generated by wxFormBuilder and replace child

description: WxPython: access sizer of GUI generated by wxFormBuilder and replace child


code: result = gateway.transaction.create({'amount': ...})

rawDescription: Braintree + Python: Configure credential at transaction level rather than module


code:
with open("newport", "w") as newport:
    newport.write("19")

exit()

rawDescription: Python equivalent to Bash comand "echo"?

description: Python equivalent to Bash comand "echo"


code: xx = xx + 2

rawDescription: How to change speed of scrolling background pygame?

description: Change speed of scrolling background pygame


code:
pmatch = dict([])
def partial_match(a,b):
  # for instance ...
  return sum(ea == eb for (ea,eb) in zip(a,b)) >= 2
for el_a in results_a:
  pmatch[el_a] = [el_b for el_b in results_b if partial_macth(el_a,el_b)]

rawDescription: SQLite compare query Python

description: SQLite compare query Python


code:
import urllib.request
import urllib.parse

# Create dict of form values
example_data = urllib.parse.urlencode({'user': 'ThisIsMyUserName'})

# Create request
example_url = 'http://www.w3schools.com/html/html_form_action.asp'
get_url = example_url + '?' + example_data

# Open the page and read content
web_page = urllib.request.urlopen(get_url)
print(web_page.read().decode(web_page.info().get_param('charset', 'utf8')))

rawDescription: Python 2&3: both urllib & requests POST data mysteriously disappears


code:
# Remixed from: http://www.dabeaz.com/coroutines/cosax.py
# Don't shy away from reading http://www.dabeaz.com/coroutines/ if the stuff below
# seems weird.

from xml.sax import ContentHandler, parse
from collections import namedtuple

ElementStart = namedtuple('ElementStart', 'name attrs')
ElementEnd = namedtuple('ElementEnd', 'name')

class LazySax(ContentHandler):
    def __init__(self, target):
        self.target = target
    def startElement(self, name, attrs):
        self.target.send(ElementStart(name, attrs._attrs))
    def endElement(self, name):
        self.target.send(ElementEnd(name))

def pull_tuples(tuples):
    while True:
        event = yield
        if isinstance(event, ElementStart) and event.name == 'vehicle':
            vid = event.attrs['id']
            edges = None
            while True:
                event = yield
                if isinstance(event, ElementStart) and event.name == 'route':
                    edges = event.attrs['edges']
                elif isinstance(event, ElementEnd) and event.name == 'vehicle':
                    tuples.append((vid, edges))
                    break

rawDescription: Python RE: how can I neglect empty space between tags?


code:
cols = dict((x,y) for y,x in enumerate('de'))
rows = dict((x,y) for y,x in enumerate('ABCD'))
len_cols = 2
len_rows = 4
matrix = [[0 for i in range(len_cols)] for j in range(len_rows)]
update('B','e',1)
update('D','d',3)
matrix

rawDescription: Create a matrix with headers and inserting values by calling the headers


rawDescription: Python 3.5.1 from PixelAcces Objects to CSV dataset


rawDescription: masking the built-in variable with its magic behavior?

description: Masking the built-in variable with its magic behavior


rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
def find_anagrams_in_wordlist(candidate, word_list):  # Name your variables clearly
    results = list()  # For accumulating your results
    sorted_candidate = sorted(candidate)  # You only need to sort your candidate once
    for word in word_list:  # This is the cleanest way to loop through an iterable
        sorted_word = sorted(word)  # Sort the word once
        if sorted_candidate == sorted_word:  # Now check for equality: an additional function can obfuscate things
            results.append(word)  # If it's equal, add it to your results
    return results  # Send back your results

rawDescription: Anagram Function Returning None

description: Anagram Function Returning None


code:
[a for a,b in zip("cat feet".split(), "cat shoes".split()) if a == b]
[a for a,b in zip("feet cat".split(), "cat shoes".split()) if a == b]

rawDescription: Compare or match 2 strings and display matched word


code: r = np.sqrt(x*x + y*y)

rawDescription: Log scale on radial contour plot with matplotlib


rawDescription: pandas vectorized operation to get the length of string

description: Pandas vectorized operation to get the length of string


code: person['speak']()

rawDescription: Javascript-style object methods in Python?


code: json.dump(strdata, f)

rawDescription: Not about to deserialize json kept as string in Python using json.load


code: retcode = subprocess.call(["123.exe"])

rawDescription: Python script executes another script and resumes after second script completes its job