code:
bytestring = sock.recv(51)
[int(ch) for ch in bytestring]

rawDescription: Importing UDP Multicast signal into Python


code:
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    p = Pool(5)
    print(p.map(f, [1, 2, 3]))

rawDescription: Return results to parent process using joblib


code: return "".join("Hello({})".format(i) for i in range(100))

rawDescription: Builder pattern equivalent in Python

description: Builder pattern equivalent in Python


code:
from flask import url_for, current_app, redirect, request
from rauth import OAuth2Service

import json, urllib2

class OAuthSignIn(object):
    providers = None

    def __init__(self, provider_name):
        self.provider_name = provider_name
        credentials = current_app.config['OAUTH_CREDENTIALS'][provider_name]
        self.consumer_id = credentials['id']
        self.consumer_secret = credentials['secret']

    def authorize(self):
        pass

    def callback(self):
        pass

    def get_callback_url(self):
        return url_for('oauth_callback', provider=self.provider_name,
                        _external=True)

    @classmethod
    def get_provider(self, provider_name):
        if self.providers is None:
            self.providers={}
            for provider_class in self.__subclasses__():
                provider = provider_class()
                self.providers[provider.provider_name] = provider
        return self.providers[provider_name]

class GoogleSignIn(OAuthSignIn):
    def __init__(self):
        super(GoogleSignIn, self).__init__('google')
        googleinfo = urllib2.urlopen('https://accounts.google.com/.well-known/openid-configuration')
        google_params = json.load(googleinfo)
        self.service = OAuth2Service(
                name='google',
                client_id=self.consumer_id,
                client_secret=self.consumer_secret,
                authorize_url=google_params.get('authorization_endpoint'),
                base_url=google_params.get('userinfo_endpoint'),
                access_token_url=google_params.get('token_endpoint')
        )

    def authorize(self):
        return redirect(self.service.get_authorize_url(
            scope='email',
            response_type='code',
            redirect_uri=self.get_callback_url())
            )

    def callback(self):
        if 'code' not in request.args:
            return None, None, None
        oauth_session = self.service.get_auth_session(
                data={'code': request.args['code'],
                      'grant_type': 'authorization_code',
                      'redirect_uri': self.get_callback_url()
                     },
                decoder = json.loads
        )
        me = oauth_session.get('').json()
        return (me['name'],
                me['email'])

rawDescription: Using Google OAuth2 with Flask

description: Using Google OAuth2 with Flask


code:
with open("test.txt") as f,open("out.txt","w") as out:
    for line in f:
        if "Get location" in line:
            a,b,_ = line.rsplit(None,1)[1].strip("()").split(",", 2)
            out.write("{},{}\n".format(a,b))

rawDescription: Python - extracting particular numbers from each line in a file


code:
class my_defaultdict(collections.defaultdict):
    def __missing__(self, key):
        return '<unknown %s>' % key

rawDescription: Python "switch statement" and string formatting


code:
import redis
queue_name = "celery"
client = redis.Redis(host="localhost", port=6379, db=1)
length = client.llen(queue_name)

rawDescription: Django Celery get task count

description: Django Celery get task count


rawDescription: How to reset an unordered index to an ordered one in python?

description: Reset an unordered index to an ordered one in python


code:
qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

rawDescription: SQLAlchemy: how to filter date field?

description: SQLAlchemy: how to filter date field


code:
import datetime as dt
import time

now=dt.datetime.now()

rawDescription: Datetime to Second Conversion

description: Datetime to Second Conversion


code:
x = np.arange(6)
using_ufunc(x)

rawDescription: efficient numpy array creation

description: Efficient numpy array creation


code:
def neighbors(i, W, H, D):
  A = W * H

  plane = i / A
  plane_index = i % A
  row = plane_index / W
  col = plane_index % W

  r = -1 if row % 2 else 1   # (-1)**row
  p = -1 if plane % 2 else 1 # (-1)**plane

  nbors = []

  # first include neighbors in same plane
  if col != W-1: nbors.append(i+1)
  if col != 0:   nbors.append(i-1)
  if row != H-1: nbors.append(i+W)
  if row != 0:   nbors.append(i-W)
  if (col != 0 or r > 0) and (col != W-1 or r < 0):
    if row != H-1: nbors.append(i+W+r)
    if row != 0:   nbors.append(i-W+r)

  # now add neighbors from other planes
  if plane != D-1: nbors.append(i+A)
  if plane != 0:   nbors.append(i-A)

  if (col != 0 or p < 0) and (col != W-1 or p > 0):
    if plane != D-1: nbors.append(i+A-p)
    if plane != 0:   nbors.append(i-A-p)

  if ((col != W - 1 or p > 0 or r < 0) and
      (col != 0 or p < 0 or r > 0) and
      (row != H-1 or p < 0) and
      (row != 0 or p > 0)):
    if plane != D-1:
      nbors.append(i + A + p*W + (r-p)/2) #10
    if plane != 0:
      nbors.append(i - A + p*W + (r-p)/2) #11

  return nbors

rawDescription: Creating a sphere packing nearest neighbor list from integers


code:
{
    '()': logging.Formatter,
    'format': '{levelname} - {asctime} - {module} - {message}',
    'style': '{',
},

rawDescription: use str.format() in django logging

description: Use str.format() in django logging


rawDescription: I am having trouble with a Python list display using "in range"


code:
from kivy.app import App
from kivy.lang import Builder

root = Builder.load_string('''
FloatLayout:
    AnchorLayout:
        anchor_x: 'right'
        anchor_y: 'bottom'

        Button:
            text: 'Hello World'
            size: 100, 100
            size_hint: None, None

    AnchorLayout:
        anchor_x: 'left'
        anchor_y: 'center'

        Label:
            text: 'Am i a Label ?'
            size: 100, 100
            size_hint: None, None
''')

class MyJB(App):
    def build(self):
        return root

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

rawDescription: Anchor Layout to show many widgets in a screen at relative positions


code:
class SubMenu(QMenuBar):
    def __init__(self, parent=None):
        super(SubMenu, self).__init__(parent)
        self.addAction("File")
        self.addAction("View")
        self.setStyleSheet("""QMenuBar {
         background-color: blue;
        }

     QMenuBar::item {
         background: blue;
     }""")
        self.resize(320, 240)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    m = SubMenu()
    m.show()
    app.exec_()

rawDescription: Styling The Menu Bar in PyQT4

description: Styling The Menu Bar in PyQT4


code: feature = '[3.14, 2.12, 4.5]' # 3 elements only for clarity

rawDescription: Writing and reading floats and strings in a CSV file - python


code:
import itertools
s = [(3, 4), (1, 2)]
list(itertools.chain.from_iterable(s))

rawDescription: Opposite of zip(*[iter(s)]*n)

description: Opposite of zip(*[iter(s)]*n)


code:
def dict_replace(text, replacements):
    for key, val in replacements.iteritems():
        text = text.replace(key, val)
    return text

rawDescription: How to perform multiple replacements on string in Jinja2?

description: Perform multiple replacements on string in Jinja2


code:
# app_tags.py
from django import template
register = template.Library()

@register.inclusion_tag("templates/myappname/greeting.html")
def greet(name, end="!!!"):
     return { 'name': name,  'end': end }

rawDescription: Is it possible to have Django custom template tags load other templates in package


code:
[
{'company': {'employee': {'age': 20, 'name': 'john', 'others': {'grade': 'AB'}}}},
{'company': {'employee': {'age': 20, 'name': '$', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 20, 'name': '$', 'others': {'grade': 'AB'}}}},
{'company': {'employee': {'age': -1, 'name': 'john', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': -1, 'name': 'john', 'others': {'grade': 'AB'}}}},
{'company': {'employee': {'age': -1, 'name': '$', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': -1, 'name': '$', 'others': {'grade': 'AB'}}}},
{'company': {'employee': {'age': 100, 'name': 'john', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 100, 'name': 'john', 'others': {'grade': 'AB'}}}},
{'company': {'employee': {'age': 100, 'name': '$', 'others': {'grade': 'A'}}}},
{'company': {'employee': {'age': 100, 'name': '$', 'others': {'grade': 'AB'}}}}
]

rawDescription: Generate all combinations from a nested python dictionary and segregate them


code:
import io
import lxml.etree as ET

content='''\
<ACORD>
  <InsuranceSvcRq>
    <HomePolicyQuoteInqRq>
      <PersPolicy>
        <PersApplicationInfo>
            <InsuredOrPrincipal>
                <InsuredOrPrincipalInfo>
                    <InsuredOrPrincipalRoleCd>AN</InsuredOrPrincipalRoleCd>
                </InsuredOrPrincipalInfo>
                <GeneralPartyInfo>
                    <Addr>
                        <Addr1></Addr1>
                    </Addr>
                </GeneralPartyInfo>
            </InsuredOrPrincipal>
        </PersApplicationInfo>
      </PersPolicy>
    </HomePolicyQuoteInqRq>
  </InsuranceSvcRq>
</ACORD>
'''
tree=ET.parse(io.BytesIO(content))
path='//PersApplicationInfo/InsuredOrPrincipal[InsuredOrPrincipalInfo/InsuredOrPrincipalRoleCd="AN"]/GeneralPartyInfo'
result=tree.xpath(path)
print(result)

rawDescription: XPath predicate with sub-paths with lxml?


rawDescription: Why is numpy slower than python? How to make code perform better


code:
import random

def random_filename():
    return '{}.txt'.format(random.randrange(0, 100))

def write_file(contents):
    with open(random_filename(), 'w') as f:
        f.write(contents)
        f.close()
write_file('hello')

rawDescription: Attach random value

description: Attach random value


code:
make_treasure = RandomItemGenerator()
make_treasure.add_item("sword",    80)
make_treasure.add_item("sword +1", 19)
make_treasure.add_item("ring +2",   1)

rawDescription: Pythonic way of percentagechance

description: Pythonic way of percentagechance


code:
a =  "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.single.com'}]}]"
b = "[{'index': '1', 'selected': 'true', 'length': '0', 'completedLength': '0', 'path': '', 'uris': [{'status': 'used', 'uri': 'http://www.mirrors.com'}, {'status': 'used', 'uri': 'http://www.mirrors2.com'}]}]"
c = "[{'index': '1', 'selected': 'true', 'length': '103674793', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/002.mp3', 'uris': []}, {'index': '2', 'selected': 'true', 'length': '62043128', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/004.mp3', 'uris': []}, {'index': '3', 'selected': 'true', 'length': '57914945', 'completedLength': '0', 'path': '/home/dr/Maher_Al-Muaiqly_(MP3_Quran)/003.mp3', 'uris': []}]"

rawDescription: How to extract the uris lists by regex?

description: Extract the uris lists by regex


code:
make_tuple("(1)")
make_tuple("(1,)")

rawDescription: Parse a tuple from a string?

description: Parse a tuple from a string


rawDescription: Django Many-to-Many Relation or One-to-Many relation


code:
zero = lambda l: next(i for i,v in enumerate(l) if v==0)
ending_zero = q + zero(mylist[q:])
starting_zero = q - zero(mylist[:q:-1])
return mylist[starting_zero:ending_zero]

rawDescription: Cutting list tails based on condition

description: Cutting list tails based on condition


code: AAAAAAAA, BBBBBBBB, CCCCCCCC, DDDDDDDD

rawDescription: How do I fill in unused ip addresses in a python sublist?

description: Fill in unused ip addresses in a python sublist


code:
def my_request_view(request, id):
    ... # logic goes here

rawDescription: How to read parameters from request in django

description: Read parameters from request in django


code:
def deleteEmployee(self, employee):
    employee_to_delete = employee.key
    if employee_to_delete in self.employees:
        idx=self.employees.index(employee_to_delete)
        del self.employees[idx]
        self.put()

rawDescription: Mutating ndb repeated property

description: Mutating ndb repeated property


code: self.buttons = [ self.b1, self.b2 ]

rawDescription: Still struggling with class scope

description: Still struggling with class scope


rawDescription: How can I access the overridden properties of a .NET API object in IronPython?

description: Access the overridden properties of a .NET API object in IronPython


code:
from itertools import izip
lis = (2,6,4,8,7,9,14,3)
it1 = iter(lis)
it2 = iter(lis)
next(it2)
dict(izip(it1,it2))

rawDescription: Most efficient way of finding the next element in a tuple


code:
c = Counter(letters)
c
c['o']
c['z']

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


code:
x = stack.pop()
y = stack.pop()
stack.push(1 if x > y else 0)

rawDescription: Python operators returning ints

description: Python operators returning ints


code:
import pandas as pd

df = pd.DataFrame({
    'a': range(20)})
df['even'] = df.a % 2 == 0

rawDescription: How to write a conditional array operation on a Pandas DataFrame

description: Write a conditional array operation on a Pandas DataFrame


code:
for i in range(len(dfs)):
    dfs[i].set_index('num', inplace=True)

df = pd.concat(dfs, axis=1)

rawDescription: Merge of more than 2 python pandas data frames


code:
ts = pd.read_csv(file, sep=';', parse_dates=[0], index_col=0, dayfirst=True)

idx = pd.date_range('01.01.2000', '02.01.2000')

ts.index = pd.DatetimeIndex(ts.index)
ts = ts.reindex(idx, fill_value='NaN')
print(ts)

rawDescription: reindex to add missing dates to pandas dataframe

description: Reindex to add missing dates to pandas dataframe


code: all(value == 'some test string' for key, value in vars(ob))

rawDescription: Check for multiple attribute matches in an array of objects


code:
def thanks(person):
    print("%s: Thank you ..." % person)

polite = waiter(lambda: thanks("Person 2"), 3)

rawDescription: Most efficient way to perform a deferred action in Python


code:
import re
my_string
re.sub(".*VVV.*\n?","",my_string)

rawDescription: Removing pattern matched line from multiline string in python


code: account_summary_response = urllib.urlopen("%s?%s" % (account_summary_API_url,account_summary_params)).read()

rawDescription: How to enforce GET request using urllib.urlopen?

description: Enforce GET request using urllib.urlopen


rawDescription: How to replace different blocks of text in all combinations using awk?

description: Replace different blocks of text in all combinations using awk


code:
from unittest import TestCase
from nose.plugins.attrib import attr

@attr('sequential')
class MySequentialTestCase(TestCase):
    def test_in_seq_1(self):
        pass
    def test_in_seq_2(self):
        pass

class MyMultiprocessingTestCase(TestCase):
    def test_in_parallel_1(self):
        pass
    def test_in_parallel_2(self):
        pass

rawDescription: Python Nosetest multi-processing enable and disable at Class/Package level


rawDescription: Python 2.7: What print() does to the string inside of it


rawDescription: splitting string in Python (2.7)

description: Splitting string in Python (2.7)


code:
ContactForm.another_field = forms.CharField(...)
ContactForm.base_fields['another_field'] = ContactForm.another_field

rawDescription: what's the best way to modify django form at runtime?

description: What's the best way to modify django form at runtime


code:
# let lrm be a LogisticRegression Model
lrm.save(sc, "lrm_model.model")

rawDescription: How to save and load MLLib model in Apache Spark

description: Save and load MLLib model in Apache Spark


code:
import shlex
s = 'hello "quoted string" 123   \'More quoted string\' end'
s
shlex.split(s)

rawDescription: Parse User Input in Python

description: Parse User Input in Python


code:
from collections import Counter

def most_common_line_len(filename):
    with open('somefile.txt') as f:
        return Counter(map(len, f.read().splitlines())).most_common(1)[0][0]

print(most_common_line_len('somefile.txt'))  # --> 3 for your sample data

rawDescription: find the most common length of text line in a file with various line sizes present using python

description: Find the most common length of text line in a file with various line sizes present using python


code:
import dateutil.parser
date = '2014-12-18T19:00:00-07:00'
datetime_obj = dateutil.parser.parse(date)

rawDescription: python : convert string to time object

description: Python : convert string to time object


code:
def test3():
    l = []
    for i in range(1000):
        l += [i]  # or use l.extend([i])
    return l

rawDescription: Difference in complexity of append and concatenate for lists


rawDescription: pygame circle not changing

description: Pygame circle not changing


rawDescription: Dynamically delete an item from a nested dictionary


code:
with open('path/to/input') as infile:
  words = [line.strip()[::-1] for line in infile]

with open('path/to/output', 'w') as outfile:
  outfile.write('\n'.join(words[::-1]))

rawDescription: Is it possible to reverse the order of items in a list without using the built-in .reverse() function?


code:
def mplist(somelist):
    someset = set(somelist)
    with open(up) as U:
        return (line for line in U if line.split(None, 1)[0] in someset)

rawDescription: Python: Looping over 2mln lines

description: Python: Looping over 2mln lines


code:
import cmath
cmath.sin(2 + 3j)

rawDescription: Complex numbers usage in python

description: Complex numbers usage in python


code:
from itertools import product

def recursive_flatten(d, prefix=''):
    result = {}
    nested = {}

    # extract just the 'flat' keys for the result
    for key, value in d.iteritems():
        result_key = (prefix + '_' + key.rstrip('s')).lstrip('_')
        if isinstance(value, list) and value and isinstance(value[0], dict):
            # nested dictionaries are treated recursively
            nested[result_key] = value
            continue
        result[result_key] = value

    # no nested keys? We are done here
    if not nested:
        yield result
        return

    # produce a new copy for each combination of nested structures
    for nested_combos in product(*nested.values()):
        results = [result]
        for nested_key, nested_value in zip(nested, nested_combos):
            # multiply results with nested results
            results = [
                dict(r, **rec_result)
                for rec_result in recursive_flatten(nested_value, nested_key)
                for r in results]
        for result in results:
            yield result

rawDescription: Python recursion with dicts

description: Python recursion with dicts


code: n = raw_input("Enter a number: ")

rawDescription: Determining a Abundant Number when user inputs a nmber


code:
from sqlalchemy import func

properties = [3, 4]
db.session.query(Property.user_id)\
    .filter(Property.property_number.in_(properties))\
    .group_by(Property.user_id)\
    .having(func.count()==len(properties))\
    .all()

rawDescription: Sqlalchemy single query for multiple rows from one column in one table


code:
results = open('results.txt', 'w')

results.write('results') #This is going to need to be what the results of
                         #the test are, I.E. the numbers it produces, or such

results.close()

rawDescription: creating testsuite in python

description: Creating testsuite in python


code:
import ctypes

libz = ctypes.CDLL('zlib-1.2.8/libz.so.1.2.8')
libz.gzopen64('foo.gz', 'rb')

rawDescription: Python C extension link with a custom shared library


code:
def print_frame(n, m, c):
    print(c * m)
    for i in range(1, n - 1):
        print(c, ' ' * (m - 2), c, sep='')
    print(c * m)

print_frame(5, 6, '*')

rawDescription: Printing a frame in python

description: Printing a frame in python


code:
with open("output.txt", "w") as outf:
    for key,values in d.iteritems():
        outf.write("|".join([key]+values) + "\n")

rawDescription: Writing dictionary to text file with python


code:
import os

os.chdir(os.path.join(os.path.expanduser('~'), directory_name))
keys = [file for file in os.listdir(os.getcwd()) if os.path.isfile(file)]  # step 1

# Do something else in here...

values = [open(key).readlines()[0].split()[0] for key in keys]  # step 2

file_dict = dict(zip(keys, values))  # Map values onto keys to create the dictionary

rawDescription: Loop through files in a subdirectory, append filenames as dictionary keys


code: cars = ['Mazda', 'Ford', 'Dodge', 'Yugo']

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


code: # limited xpath support for element trees

rawDescription: ElementTree: What is the syntax for the 'match' argument to the 'find' method?


code:
class Image(models.Model):
    image = models.ImageField(upload_to=f, blank=True)

class Post(models.Model):
    post_title = models.CharField(max_length=113)
    text = models.CharField(max_length=1500)
    pub_date = models.DateTimeField('post date')
    images = models.ManyToManyField(Image)

rawDescription: Django Many to Many Fields - OK with large datasets?


rawDescription: Check if two nested lists are equivalent upon substitution


code:
bakeries = Bakery.objects.annotate(hottest_cake_baked_at=Max('cake__baked_at'))
hottest_cakes = Cake.objects.filter(baked_at__in=[b.hottest_cake_baked_at for b in bakeries])

rawDescription: Django Query That Get Most Recent Objects From Different Categories


code:
parent_parser = argparse.ArgumentParser(description="Read text files.")
parent_parser.add_argument('--verbose', '-v', action='store_true',
        help="Verbosity on")
child_parser = parent_parser.add_subparsers(title="subcommand",
        help="Subcommand help", dest='cmd')
open_file_command = child_parser.add_parser('open', help="Open text file")
open_file_command.add_argument('filename', help='TXT file')
new_file_command = child_parser.add_parser('new', help="New text file")
new_file_command.add_argument('filename', help='TXT file')
edit_file_command = child_parser.add_parser('edit', help="Edit existing text file")
edit_file_command.add_argument('filename', help='TXT file')

rawDescription: Create parser with subcommands in argparse, customize positional argument(s)


code:
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.utils import make_msgid
from email.utils import formatdate

def make_mail(address,body,format,mylist=[]):
    msg = MIMEMultipart()
    msg['To'] = address
    msg['From'] = 'ggous1@gmail.com'
    msg['Message-Id'] = make_msgid()
    msg['Date'] = formatdate(localtime=True)
    msg.attach(MIMEText(body, 'plain' if format == 'txt' else 'html'))
    for filename in mylist:
        part = MIMEApplication(open(filename).read())
        part.add_header('Content-Disposition',
                'attachment; filename="%s"' % os.path.basename(filename))
        msg.attach(part)
    return msg

def send_mail(msg):
    srv = smtplib.SMTP('smtp.gmail.com')
    srv.set_debuglevel(1)
    srv.ehlo()
    srv.starttls()
    srv.ehlo()
    srv.login('username','pass')
    srv.sendmail(msg['From'], msg['To'], msg.as_string())
    srv.quit()

if __name__=="__main__":
    address=raw_input('Enter an address to send email in the form "name@host.com" ')
    body=raw_input('Enter the contents of the email')
    format=raw_input('The format is txt or html?')
    question=raw_input('Do you have any files to attach?Yes or No?')
    mylist=[]
    if question=='Yes' or question=='yes':
        fn=raw_input('Enter filename')
        mylist.append(fn)

    msg = make_mail(address,body,format,mylist)
    send_mail(msg)

rawDescription: python can't send attachment files through email

description: Python can't send attachment files through email


rawDescription: How to implement session.add on this code:

description: Implement session.add on this code:


code:
sys.argv[1] == 'apple'
sys.argv[2] == 'pie'
sys.argv[3] == 'comma'
sys.argv[4] == 'poop'

rawDescription: Parsing command line parameters

description: Parsing command line parameters


rawDescription: Python: select a line if specific characters spaced by tab at end of line


code: from classroom_model import Classroom

rawDescription: Django: Get related model class from parent model class


code:
stage = OrderedDict([('a', '5678'), ('b', '56')])
print(stage["a"])
stage["a"] = 'changed'
print(stage)

rawDescription: Python / assign tuple

description: Python / assign tuple


rawDescription: How to use Python with different SOCKS 5 Proxies?

description: Use Python with different SOCKS 5 Proxies


rawDescription: Python Pandas: print the csv data in oder with columns


code:
import gobject
import gtk

class Bar(object):
    def __init__(self,widget):
        self.val=0
        self.scale = gtk.HScale()
        self.scale.set_range(0, 100)
        self.scale.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.scale.set_value(self.val)
        widget.add(self.scale)
        gobject.timeout_add(100, self.timeout)
    def timeout(self):
        self.val +=1
        self.scale.set_value(self.val)
        return True

if __name__=='__main__':
    win = gtk.Window()
    win.set_default_size(300,50)
    win.connect("destroy", gtk.main_quit)
    bar=Bar(win)
    win.show_all()
    gtk.main()

rawDescription: Periodically call a function in pygtk's main loop


rawDescription: Functional masking of numpy string array in Python


code:
def formula(*array):
    calculate = lambda x: sum(c * x ** p for p, c in enumerate(array))
    calculate.coefficients = array
    return calculate

def derivative(function):
    return (p * c for p, c in enumerate(function.coefficients[1:], 1))

rawDescription: Given f, is there an automatic way to calculate fprime for Newton's method?


code:
ndim = 2
A = np.zeros((x.size, ndim + 1), dtype=float)
for j in range(ndim + 1):
    A[:,j] = x**j

rawDescription: Building a covariance matrix in Python

description: Building a covariance matrix in Python


code: button.callback = new_callback

rawDescription: Anonymous Inner Class in Python

description: Anonymous Inner Class in Python


rawDescription: Indexing nodes in neo4j in python

description: Indexing nodes in neo4j in python


rawDescription: Handling Encoded Messages with Python and imaplib


rawDescription: How do I get a list of every possible combination of product prices to reach a target cost?

description: Get a list of every possible combination of product prices to reach a target cost


code:
df2['Appears'] = 1
df1.merge(df2, on='ID', how='left').fillna({'Appears':0})

rawDescription: Check if ID in one DF exists in another DF (Python 3, Pandas)


code:
for item in itertools.combinations(input_list, r = 8):
            yield "".join(list(item))

rawDescription: All possible words until the len 8

description: All possible words until the len 8


code: [el for el in a if el[0] in bset]

rawDescription: Python3 List: How do I remove el in list_a if el[0] is not in list_b?


code:
ABCW = ABCW.fillna(method = 'pad')
ABCW = ABCW.fillna(method = 'bfill')

rawDescription: Pandas df.fillna(method = 'pad') not working on 28000 row df


code: input_RDD.map(lambda x: x[1]).reduceByKey(lambda x,y: x+y)

rawDescription: PySpark IPython - reduce RDD into a new RDD with different key


rawDescription: How to read sql query to pandas dataframe / python / django

description: Read sql query to pandas dataframe / python / django


rawDescription: Convert list of lists to custom dictionary


rawDescription: How to change legend size with matplotlib.pyplot

description: Change legend size with matplotlib.pyplot


code:
finalPathList = [elem.replace("\\", "/") for elem in pathList]
finalPathList

rawDescription: Replacing characters within a list

description: Replacing characters within a list


code:
class MyRedirectHandler(urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, hdrs):
        if fp.geturl().startswith('http://www.facebook.com/'):
            # This will raise an exception similar to this:
            # urllib2.HTTPError: HTTP Error 302: FOUND
            return None
        else:
            # Let the default handling occur
            return super(MyRedirectHandler, self).http_error_302(req, fp, code, msg, hdrs)

rawDescription: How do I intercept a request after all redirects are resolved but before page download with urllib2?

description: Intercept a request after all redirects are resolved but before page download with urllib2


code:
Pxx.shape
freqs.shape
bins.shape

rawDescription: Cutting of unused frequencies in specgram matplotlib


code:
from functools import partial

self.moveset[0] = partial(punch, self.level)

rawDescription: Re-evaluating a function to get a new random value in python


code:
df
newdf = df.groupby(['x','y']).mean().reset_index()
newdf

rawDescription: Mean value by equality of rows

description: Mean value by equality of rows


code:
foo = TheClass()
foo.method()

rawDescription: in Python Is there ever a good time to use a global variable inside a class?

description: In Python Is there ever a good time to use a global variable inside a class


code:
{key: [sublist for sublist in value if sublist[1] != 8]
 for key, value in a.iteritems()}

rawDescription: eliminate entries in dictionary based on a certain value

description: Eliminate entries in dictionary based on a certain value


code:
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.properties import ListProperty

kv_string = '''
<MyWidget>:
    r_size: [root.size[0]/2, root.size[1]/2]
    canvas:
        Color:
            rgb: 0.1, 0.6, 0.3
        Rectangle:
            size: root.r_size
            pos: 0, root.size[1]-root.r_size[1]
'''

Builder.load_string(kv_string)

class MyWidget(Widget):
    r_size = ListProperty([0, 0])

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

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

rawDescription: Basic Kivy Q, Positioning Canvas Child {kivy language}


rawDescription: For loop when iterating over lines in a file?


rawDescription: Element Tree: How to find all child elements with a specific value


code:
smallcustdict[custID1] = customerdict[custID1]
smallcustdict[custID2] = customerdict[custID2]

rawDescription: Python memory management with list comprehensions


code:
def update(self):
    # While the pipe has data, read and update the StringVar
    while self.parent_pipe.poll():
        self.updating_int.set(self.parent_pipe.recv())
    dx = self.updating_int.get()
    self.area_barGraph.create_polygon(10,10, (10+dx),10, (10+dx),20, 10,20, outline='green', fill='yellow')
    # set the update method to run again in 1 seconds time
    self.parent.after(1000,self.update)

rawDescription: Python: How to update a GUI with variables from a separate process while maintaining GUI interactivity


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.select import Select
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
driver.get("http://jet2.com")

wait = WebDriverWait(driver, 10)
adults_element = wait.until(EC.presence_of_element_located((By.ID, "adults-number")))

select = Select(adults_element)
select.select_by_visible_text("4")

rawDescription: How to select a value from a drop down in python

description: Select a value from a drop down in python


code:
import re
def remove_times(s):
    return re.sub(r'[012]?[0-9]:[0-5][0-9]', '', s)

rawDescription: Stripping time (in the format hh:mm) from a string in Python 2


code: sprites = [(sprite, pygame.Clock()) for sprite in sprites]

rawDescription: Pygame sprites timer

description: Pygame sprites timer


code:
class StatsTrackerBorg():
    __shared_data = {'data':{}}
    # RHS guarantees a common dict named `data`

    def __init__(self):
        """Make every instance use StatsTrackerBorg.__shared_data
        for its attribute dict."""
        self.__dict__ = self.__shared_data

    # ... methods to update data, summarize it, etc. ...

rawDescription: Python Singleton design pattern tracking application stats


code:
import itertools
all_entries = itertools.chain.from_iterable(entryList)
def changebg(ientries):
    ientries = iter(ientries) #allow passing a list in as well ...
    entry = next(ientries,None)
    if entry is not None:
        entry['bg'] = 'yellow' #change the color of this widget
        root.after(300,lambda : changebg(ientries)) #wait 300ms and change color of next one.

changebg(all_entries)

rawDescription: Python: change entry colour dynamically with Tkinter


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

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


code: self.vertices = [[] for _ in range(size)]

rawDescription: How to initialize a two dimensional array in python

description: Initialize a two dimensional array in python


rawDescription: Using regex for mutliple lines

description: Using regex for mutliple lines


code:
ff = {'one': {'aaa': [1,2,3], 'bbb':[3,4,5] }, 'two': {'ccc' : [3,2,1] }}
{k: [(nk,) + tuple(nv) for nk, nv in v.iteritems()] for k, v in ff.iteritems()}

rawDescription: dictionary of lists to tuples

description: Dictionary of lists to tuples


code:
def rmRepeatedPatterns(line):
    return re.sub(r'\b(\S+?)\1\S*\b', '', line)

pCorp = [ rmRepeatedPatterns(line) for line in pCorp ]

rawDescription: Text mining and NLP: from R to Python

description: Text mining and NLP: from R to Python


code:
{'val3': {'higherPrice': [], 'nbOffers': 0, 'nbBestOffers': 0},
 'val2': {'higherPrice': [], 'nbOffers': 0, 'nbBestOffers': 0},
 'val1': {'higherPrice': [], 'nbOffers': 1, 'nbBestOffers': 0}}

rawDescription: Does dict.fromkeys assign the same reference over and over?


rawDescription: Index a Pandas dataframe grouped by date and aggregated?


code:
t
type(t)
enc_t = t.encode('utf_8')
enc_t
type(enc_t)
dec_t = enc_t.decode('unicode_escape')
type(dec_t)
dec_t

rawDescription: Convering double backslash to single backslash in Python 3


code: [(i >> x) & 0xFFFFFFFF for x in reversed(range(0, 128, 32))]

rawDescription: Split each after 32 bits of 128 bit input in Python


code:
temporary_list = []
for group in data:
    new_group = []
    for word in group:
        new_group.extend(word.split())
    temporary_list.append(new_group)
print(temporary_list)

rawDescription: Split element in string into segments

description: Split element in string into segments


code:
import module

print(module.getname())
module.changename()
print(module.getname())

rawDescription: Python: Import all variables

description: Python: Import all variables


code: df

rawDescription: Customizing rolling_apply function in Python pandas


code:
def __getitem__(self, n):
    maxindex = n
    if isinstance(maxindex, slice):
        maxindex = maxindex.indices(len(self))[1]
    while len(self) <= maxindex:
        self.append(self.dft)
    return super(ilist, self).__getitem__(n)

rawDescription: Is there a simple way to override the list object's method __getitem__?


code:
for k in pi:
    k1 = k.split(' ')[0]
    list2.append(k1)

rawDescription: append multiple results from one list to another

description: Append multiple results from one list to another


code:
import re
# group all strings separated by `|` and at least length 1
arr = re.findall('[^|]{1,}', "steve && chris || joe && george || sep && geo")
print(arr)  # ['steve && chris ', ' joe && george ', ' sep && geo']

rawDescription: capturing repeating groups with reg ex in python

description: Capturing repeating groups with reg ex in python


code:
from operator import itemgetter
print(max(lst, key=lst.count)) # ['sku', '3', 'batchid', 5]

rawDescription: Finding occurence in list of lists

description: Finding occurence in list of lists


rawDescription: How to switch tasks between queues in Celery

description: Switch tasks between queues in Celery


code:
def onChange(val):
    ...
    ...

    global container # Global is used here because this example is not done using classes

    for wid in container:
        wid.destroy() # Using destory instead of grid_forget

    container = [] # Reset container to empty list

    for x in range(r):
        e = tk.Entry(root)
        e.grid(row = 1 + x, column = 0)
        container.append(e) # Append widget to container list
...
...

# Container list for the Entry widgets
container = []

rawDescription: Python grid_remove

description: Python grid_remove


code:
import pprint
import pyparsing
NEWLINE = pyparsing.LineEnd().suppress()
VALID_CHARACTERS = pyparsing.srange("[a-zA-Z0-9_\-\.]")
COLON = pyparsing.Suppress(pyparsing.Literal(":"))
HYPHEN = pyparsing.Suppress(pyparsing.Literal("-"))
XX = pyparsing.Literal("XX")

list_item = HYPHEN + pyparsing.Combine(XX + pyparsing.Word(VALID_CHARACTERS))
list_of_items = pyparsing.Group(pyparsing.OneOrMore(list_item))

key = pyparsing.Word(VALID_CHARACTERS) + COLON
pair_value = pyparsing.Word(VALID_CHARACTERS) + NEWLINE
value = (pair_value | list_of_items)

#~ A: pair = pyparsing.Group(key + value)
pair = (key + value)

indentStack = [1]

section = pyparsing.Forward()
section_name = pyparsing.Word(VALID_CHARACTERS) + COLON
#~ A: section_value = pyparsing.OneOrMore(pair | section)
section_value = (pair | section)

#~ B: section_content = pyparsing.indentedBlock(section_value, indentStack, True)
section_content = pyparsing.Dict(pyparsing.ungroup(pyparsing.indentedBlock(section_value, indentStack, True)))

#~ A: section << Group(section_name + section_content)
section << (section_name + section_content)

#~ B: parser = pyparsing.OneOrMore(section)
parser = pyparsing.Dict(pyparsing.OneOrMore(pyparsing.Group(section)))

rawDescription: Cannot parse correctly this file with pyparsing


rawDescription: Multiple word replacement by list - duplicates creation


code:
import re

def str_replace(search, replace, subject):
    search = '|'.join(map(re.escape, search))
    return re.sub(search, replace, subject)

rawDescription: Python - How to match and replace words from a given string?


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

plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.rcParams['xtick.major.pad'] = 10
plt.rcParams['ytick.major.pad'] = 10

rawDescription: Axis and tick labels are bold when they shouldn't be - Matplotlib


code:
def handlePaintRequest(self, printer):
    document = self.makeTableDocument()
    document.print_(printer)

def makeTableDocument(self):
    document = QtGui.QTextDocument()
    cursor = QtGui.QTextCursor(document)
    rows = self.table.rowCount()
    columns = self.table.columnCount()
    table = cursor.insertTable(rows + 1, columns)
    format = table.format()
    format.setHeaderRowCount(1)
    table.setFormat(format)
    format = cursor.blockCharFormat()
    format.setFontWeight(QtGui.QFont.Bold)
    for column in range(columns):
        cursor.setCharFormat(format)
        cursor.insertText(
            self.table.horizontalHeaderItem(column).text())
        cursor.movePosition(QtGui.QTextCursor.NextCell)
    for row in range(rows):
        for column in range(columns):
            cursor.insertText(
                self.table.item(row, column).text())
            cursor.movePosition(QtGui.QTextCursor.NextCell)
    return document

rawDescription: How can I print data from my database while in QTableWidget?

description: Print data from my database while in QTableWidget


code: global var

rawDescription: Python: Difference between 'global' & globals().update(var)


code:
def currently_accepted_solution_augmented(targets, paragraph):
    def tester(s):
        def f(x):
            return len(re.findall(r"\b" + x + r"\b", s))
        return f
    return map(tester(paragraph), targets)

rawDescription: Using map() to get number of times list elements exist in a string in Python


code:
import re
pattern = re.compile(r'\d{2,3}\.\d{2,3}-A\d-\S*\Z')
pattern.match('87.98-A1-help')
pattern.match('123.45-A6-no whitespace allowed')
pattern.match('123.45-A6-everything_else_is_allowed')

rawDescription: using reg exp to check if test string is of a fixed format

description: Using reg exp to check if test string is of a fixed format


code:
import requests
import logging
logging.basicConfig(level=logging.DEBUG)
r = requests.get('http://httpbin.org/get?foo=bar&baz=python')

rawDescription: Log all requests from the python-requests module


code: lines = [[line.rstrip(), next(f).rstrip()] for line in f if line[0] != "-" and line.strip()]

rawDescription: PYTHON: Inserting all lines into array/list after specific symbol


code: a.index = a['Code']

rawDescription: how to group all the data as fast as possible?

description: Group all the data as fast as possible


code:
dummy = "beans"
newdummy = ""
for i in xrange(len(dummy)):
    newdummy += chr(ord(dummy[i])+5)
dummy = newdummy
print(dummy)

rawDescription: Python String Manipulation Concerns

description: Python String Manipulation Concerns


code:
a = [1, 2, 3, None, 4]
ma.masked_invalid(np.array(a, dtype=float), copy=False).astype(int)

rawDescription: Initializing numpy masked array from Python int list with None values


code:
import time
time.mktime((DT.datetime(1899,12,30) + DT.timedelta(days=39814)).timetuple())

rawDescription: Python returns 5 digit timestamp, what is this?


code:
from itertools import islice, chain
from collections import deque
import pandas as pd
import csv

def consume(iterator, n):
    "Advance the iterator n-steps ahead. If n is none, consume entirely."
    # Use functions that consume iterators at C speed.
    if n is None:
        # feed the entire iterator into a zero-length deque
        deque(iterator, maxlen=0)
    else:
        # advance to the empty slice starting at position n
        next(islice(iterator, n, n), None)

def parts(r, sec_len, skip):
    consume(r,skip)
    for sli in iter(lambda: list(islice(r, sec_len)), []):
        yield sli
        consume(r, skip)

with open("test.txt")as f:
    r = csv.reader(f)
    print(pd.DataFrame.from_records((chain.from_iterable(parts(r, 4, 2)))))

rawDescription: Skip every specified line before importing to pandas


code:
for dirpath, dirs, files in os.walk(rootdir):
    if not dirpath.endswith('output'):
       continue # look in the next folder
    # search files
    for file in files: ...

rawDescription: Entering folder based on name in python

description: Entering folder based on name in python


code: cut = df.groupby('userid').first()

rawDescription: Operating on multiindex dataframe

description: Operating on multiindex dataframe


rawDescription: How do I get a row of a 2d numpy array as 2d array

description: Get a row of a 2d numpy array as 2d array


code: [val for val in new_list if val.startswith("h")]

rawDescription: Python Coding Help Needed, searching list by first letter of each word


code:
def get_vector(a, b):
    """Calculate vector (distance, angle in degrees) from point a to point b.

    Angle ranges from -180 to 180 degrees.
    Vector with angle 0 points straight down on the image.
    Values increase in clockwise direction.
    """
    dx = float(b[0] - a[0])
    dy = float(b[1] - a[1])

    distance = math.sqrt(dx**2 + dy**2)

    if dy > 0:
        angle = math.degrees(math.atan(-dx/dy))
    elif dy == 0:
        if dx < 0:
            angle = 90.0
        elif dx > 0:
            angle = -90.0
        else:
            angle = 0.0
    else:
        if dx < 0:
            angle = 180 - math.degrees(math.atan(dx/dy))
        elif dx > 0:
            angle = -180 - math.degrees(math.atan(dx/dy))
        else:
            angle = 180.0

    return distance, angle

rawDescription: Counting Cars OpenCV + Python Issue

description: Counting Cars OpenCV + Python Issue


code:
def conditional(decorator):

    def conditional_decorator(fn):
        dec = decorator(fn)
        def wrapper(self, *args, **kw):
             if self.read_only:
                 return dec(self, *args, **kw)
             return fn(self, *args, **kw)
        return wrapper

    return conditional_decorator

rawDescription: Conditionally disable caching decorator based on instance variable


code:
for property in rule.style:
    name = property.name
    value = property.value

rawDescription: python how to parse css file as key value

description: Python how to parse css file as key value


code:
@jit
def numba_unroll2(A, B):
    C = np.empty(A.shape, dtype=np.uint8)
    for i in xrange(A.shape[0]):
        for j in xrange(A.shape[1]):
            C[i,j] = A[i,j]*B[i,j] + 4.1*A[i,j] > 2.5*B[i,j]

    return C

rawDescription: How does parakeet differ from Numba? Because I didn't see any improvements on some NumPy expressions


code:
import requests
from bs4 import BeautifulSoup
r = requests.get('http://www.amazon.ca/gp/bestsellers')
soup = BeautifulSoup(r.content)
soup.select('li > a[href^=http://www.amazon.ca/Best-Sellers]')[0]
r = requests.get('http://www.amazon.ca/gp/bestsellers', headers={
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36'})
soup = BeautifulSoup(r.content)
soup.select('li > a[href^=http://www.amazon.ca/Best-Sellers]')[0]

rawDescription: Python RE does not return anything after /ref=


code:
rank_list = []
already_scored = []
for m in A:
    score = 0
    for n in A:
        if (n[3] > m[3]) and (n in already_scored):
            score += 1
    rank_list.append(m + [score])
    already_scored.append(m)

rawDescription: Compare two nested lists and append a third list based on nested values - Python


code:
import tensorflow as tf

#####################
# preparation stuff #
#####################

# define input and output data
input_data = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]  # XOR input
output_data = [[0.], [1.], [1.], [0.]]  # XOR output

# create a placeholder for the input
# None indicates a variable batch size for the input
# one input's dimension is [1, 2] and output's [1, 1]
n_input = tf.placeholder(tf.float32, shape=[None, 2], name="n_input")
n_output = tf.placeholder(tf.float32, shape=[None, 1], name="n_output")

# number of neurons in the hidden layer
hidden_nodes = 5

################
# hidden layer #
################

# hidden layer's bias neuron
b_hidden = tf.Variable(tf.random_normal([hidden_nodes]), name="hidden_bias")

# hidden layer's weight matrix initialized with a uniform distribution
W_hidden = tf.Variable(tf.random_normal([2, hidden_nodes]), name="hidden_weights")

# calc hidden layer's activation
hidden = tf.sigmoid(tf.matmul(n_input, W_hidden) + b_hidden)

################
# output layer #
################

W_output = tf.Variable(tf.random_normal([hidden_nodes, 1]), name="output_weights")  # output layer's weight matrix
output = tf.sigmoid(tf.matmul(hidden, W_output))  # calc output layer's activation

############
# learning #
############
cross_entropy = -(n_output * tf.log(output) + (1 - n_output) * tf.log(1 - output))
# cross_entropy = tf.square(n_output - output)  # simpler, but also works

loss = tf.reduce_mean(cross_entropy)  # mean the cross_entropy
optimizer = tf.train.AdamOptimizer(0.01)  # take a gradient descent for optimizing with a "stepsize" of 0.1
train = optimizer.minimize(loss)  # let the optimizer train

####################
# initialize graph #
####################
init = tf.initialize_all_variables()

sess = tf.Session()  # create the session and therefore the graph
sess.run(init)  # initialize all variables

#####################
# train the network #
#####################
for epoch in xrange(0, 2001):
    # run the training operation
    cvalues = sess.run([train, loss, W_hidden, b_hidden, W_output],
                       feed_dict={n_input: input_data, n_output: output_data})

    # print some debug stuff
    if epoch % 200 == 0:
        print("")
        print("step: {:>3}".format(epoch))
        print("loss: {}".format(cvalues[1]))
        # print("b_hidden: {}".format(cvalues[3]))
        # print("W_hidden: {}".format(cvalues[2]))
        # print("W_output: {}".format(cvalues[4]))

print("")
print("input: {} | output: {}".format(input_data[0], sess.run(output, feed_dict={n_input: [input_data[0]]})))
print("input: {} | output: {}".format(input_data[1], sess.run(output, feed_dict={n_input: [input_data[1]]})))
print("input: {} | output: {}".format(input_data[2], sess.run(output, feed_dict={n_input: [input_data[2]]})))
print("input: {} | output: {}".format(input_data[3], sess.run(output, feed_dict={n_input: [input_data[3]]})))

rawDescription: TensorFlow MLP not training XOR

description: TensorFlow MLP not training XOR


rawDescription: Django Rest Framework 3.1 breaks pagination.PaginationSerializer


code: count[name, drink] += value

rawDescription: how to merge data in python

description: Merge data in python


rawDescription: Django Get multiple fields from database


rawDescription: Alias a fully static class's reference within itself


code:
import operator
sorted(some_list, key = operator.itemgetter(1))

rawDescription: python nested list on second item

description: Python nested list on second item


rawDescription: How to extend Django Group and still use in Django User

description: Extend Django Group and still use in Django User


code: string = raw_input("Proceed? [Yn] ")[:1].upper() or "Y"

rawDescription: How to set default value for variable?

description: Set default value for variable


code:
import pandas as pd
df = pd.read_table('data', sep='\s+')
mask = (df['action'] == 'sell') & (df['action'].shift(-1) != 'sell')
new = df.loc[mask].copy()
new['action'] = 'buy'
df = pd.concat([df, new])
df = df.sort(['date'])
df = df.reset_index(drop=True)
print(df)

rawDescription: Insert rows according to value of columns in pandas dataframes


code:
def count_numbers():
    query = list(Item.objects.order_by('-number')[:1])
    return query[0] + 1 if query else 0

rawDescription: Django 1.8 - How to pre-populate a Model's field based on values in that Model's QuerySet


code: master = Tk()

rawDescription: Python Tkinter Checkbutton Issue

description: Python Tkinter Checkbutton Issue


code:
replacement_map = {'123' : ('a123', '1234'), '456' : ('00456',)}
input = ['123', '456', '234', '123', '789']
output = []
for value in input:
    try:
        output.extend(replacement_map[value])
    except KeyError:
        output.append(value)

rawDescription: Python CSV: write rows according to dict mapping


code:
d = defaultdict(list)
with open('guesses.txt') as f:
    for line in f:
        name,val = line.split(":")
        d[name].append(int(val))

rawDescription: Reading data separated by colon per line in Python


rawDescription: Python Numpy Structured Array (recarray) assigning values into slices


code:
comment = Comment.objects.get(pk=1)
comment.user.image

rawDescription: Django query extended USER table

description: Django query extended USER table


rawDescription: Data-Binding in Python?

description: Data-Binding in Python


rawDescription: Python : compare lists of a list by length and create new lists of equal sizes


code:
def newcalc_D(I,nOcc,nVir,Ew):
    O = Ew[:nOcc]
    V = Ew[nOcc:]
    D = O[:,None,None,None] - V[:,None,None] + O[:,None] - V
    return (I/D).swapaxes(1,2)

rawDescription: Are there function calls that can replace the for loops in this code?


code:
from itertools import groupby
lst = [-0.23, -0.5, -0.3, -0.8, 0.3, 0.6, 0.8, -0.9, -0.4, 0.1, 0.6] # the list
minmax = [min(v) if k else max(v) for k,v in groupby(lst, lambda a: a < 0)]
[abs(j-i) for i,j in zip(minmax[:-1], minmax[1:])]

rawDescription: Calculate difference each time the sign changes in a list of values


code:
def heat(number):
    return 12 if number == "r" else (24 if number == "b" else 0.0)

rawDescription: Improving readability and functionality of a function


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

import matplotlib.cm as cm
import matplotlib.mlab as mlab

def get_rgba_bitmap(fig):
    fig.canvas.draw()
    tab = fig.canvas.copy_from_bbox(fig.bbox).to_string_argb()
    ncols, nrows = fig.canvas.get_width_height()
    return np.fromstring(tab, dtype=np.uint8).reshape(nrows, ncols, 4)

def black_white_to_black_transpa(rgba):
    rgba[:, :, 3] = 255 - rgba[:, :, 0]
    rgba[:, :, 0:3] = 0

def over(rgba1, rgba2):
    if rgba1.shape != rgba2.shape:
        raise ValueError("rgba1 and rgba2 shall have same size")
    alpha = np.expand_dims(rgba1[:, :, 3] / 255., 3)
    rgba =  np.array(rgba1 * alpha + rgba2 * (1.-alpha), dtype = np.uint8)
    return rgba[:, :, 0:3]

# fig 1)
fig1 = plt.figure(facecolor = "white")
fig1.set_dpi(300)
ax1 = fig1.add_subplot(1, 1, 1, aspect = "equal", axisbg = "black")
ax1.add_artist(plt.Circle((0., 0., .5), color =   "white"))
ax1.set_xlim(-5, 5)
ax1.set_ylim(-5, 5)
bitmap_rgba1 = get_rgba_bitmap(fig1)
black_white_to_black_transpa(bitmap_rgba1)

# fig 2
fig2 = plt.figure(facecolor = "white")
fig2.set_dpi(300)
delta = 0.025
ax2 = fig2.add_subplot(1, 1, 1, aspect = "equal", axisbg = "black")
ax2.set_xlim(-5, 5)
ax2.set_ylim(-5, 5)
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2-Z1  # difference of Gaussians
im = ax2.imshow(Z, interpolation='bilinear', cmap=cm.jet,
                origin='lower', extent=[-5, 5, -5, 5],
                vmax=abs(Z).max(), vmin=-abs(Z).max())
bitmap_rgba2 = get_rgba_bitmap(fig2)

# now saving the composed figure
fig = plt.figure()
fig.patch.set_alpha(0.0)
ax = fig.add_axes([0., 0., 1., 1.])
ax.patch.set_alpha(0.0)
ax.imshow(over(bitmap_rgba1, bitmap_rgba2))
plt.axis('off')
fig.savefig("test_transpa.png", dpi=300)

plt.show()

rawDescription: Making figure transparent with colored background


code: globals()

rawDescription: How to get the list of all initialized objects and function definitions alive in python?

description: Get the list of all initialized objects and function definitions alive in python


code:
for a in soup.select('div#galdiv a'):
    link = a.get('href')
    if not link.startswith('http'):
        link = urljoin(base_url, link)

    print(link)

rawDescription: Parse the relative link and absolute link using python


code:
def traverse(tree):
    if not isinstance(tree, dict):
        return tree.isalpha() # if leafs can't be alphabetic, simply return 0
    c = 0
    for k, v in tree.items():
        c += k.isalpha() + traverse(v)
    return c

rawDescription: Parse dictionaries within a dictionary in python


rawDescription: How to convert a python string

description: Convert a python string


code:
inds = []
seen = set()
for i, ele in enumerate(l):
    if ele not in seen:
        inds.append((i,ele))
    seen.add(ele)

rawDescription: Remove duplicates in python list but remember the index


code:
class Egg:
    x = 1
    y = 2

import example
example.by_value(Egg())
example.by_const_ref(Egg())
example.by_ref(Egg())
example.by_ptr(Egg())

rawDescription: Automatic conversion to boost shared_ptr in boost python


code: memoryview(buf)[:sizeof(f)] = (c_char * sizeof(f)).from_buffer(f)

rawDescription: How to copy bytes from a ctypes Structure to a buffer created from create_string_buffer

description: Copy bytes from a ctypes Structure to a buffer created from create_string_buffer


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kivy.uix.listview import ListView, ListItemButton
from kivy.app import App
from kivy.adapters.listadapter import ListAdapter
from kivy.properties import StringProperty
from kivy.uix.gridlayout import GridLayout
from kivy.clock import mainthread

beans = {}

class TeamsView(ListView):

    name = StringProperty()

    def __init__(self, **kwargs):
        super(TeamsView, self).__init__(**kwargs)
        self.fetch_teams_from_database()
        self.set_adapter()
        self.save_bean()

    def fetch_teams_from_database(self):
        self.teams = [
            {'team': 'Pogoń Szczecin', 'score': '55'},
            {'team': 'Arizona State', 'score': '32'},
            {'team': 'Idaho', 'score': '44'},
            {'team': 'Nebraska', 'score': '48'},
            {'team': 'dummy', 'score': '0'},
            {'team': 'dummy', 'score': '0'},
            {'team': 'dummy', 'score': '0'},
            {'team': 'dummy', 'score': '0'},
            {'team': 'dummy', 'score': '0'}
        ]

    def set_adapter(self):
        self.adapter = ListAdapter(
            data=self.teams,
            args_converter=self.args_converter,
            selection_mode='single',
            allow_empty_selection=True,
            cls=ListItemButton
        )

        self.adapter.bind(
            on_selection_change=self.on_selection_change)

    def args_converter(self, row_index, item):
        return {
            'text': item['team'],
            'size_hint_y': None,
            'height': 50
        }

    def on_selection_change(self, adapter):
        team_score, team_name = self.get_team(adapter)
        team_score = '[size=50]' + team_score + '[/size]'

        beans['score_grid'].ids[self.name + '_name'].text =\
            team_name + ' score:'
        beans['score_grid'].ids[self.name + '_score'].text =\
            team_score

    def get_team(self, adapter):
        try:
            for team in self.teams:
                if team['team'] in adapter.selection[0].text:
                    return team['score'], team['team']
        except IndexError:
            return '', ''

    @mainthread
    def save_bean(self):
        beans[self.name + 'list'] = self.proxy_ref

class ScoreGrid(GridLayout):

    def __init__(self, **kwargs):
        super(ScoreGrid, self).__init__(**kwargs)
        beans['score_grid'] = self.proxy_ref

class Test(App):
    pass

Test().run()

rawDescription: How do I capture text from ListItemButton click in listadapter?

description: Capture text from ListItemButton click in listadapter


code:
import numpy as np
import pandas as pd
from datetime import date

# Build data
prd = [1, 2, 3, 4, 1, 2]
grp = ['A', 'A', 'A', 'A', 'B', 'B']
yr =  [2010, 2010, 2010, 2010, 2000, 2000]
mth = [7, 7, 7, 7, 8, 8]
day = [1, 13, 13, 21, 20, 15]
dt = [date(y, m, d) for y, m, d in zip(yr, mth, day)]
# Create data frame
df = pd.DataFrame({'Period': prd, 'Group': grp, 'Dates': dt},
                  columns=['Period', 'Group', 'Dates'])

# Transformation function for the date column
def f(ser):
    v = ser.values
    # Get time difference in days
    delta = [float((ii-v[0]).days) for ii in v]
    # Get number of items to divide by
    dv = np.arange(len(delta))+1
    # Get cumulative average
    cumavg = [nm/dm for nm, dm in zip(delta, dv)]
    # Create output pandas Series object and return it
    out = pd.Series(cumavg, index=ser.index)
    return out

# Apply the transformation function to the Dates column
dfappend = pd.DataFrame({'Cum_Avg': df.groupby("Group").Dates.apply(f)})
# Delete the Dates column
del df['Dates']
# Merge to create the revised data frame
df = pd.merge(df, dfappend, left_index=True, right_index=True)
print(df)

rawDescription: How to do expanding window by group in pandas

description: Do expanding window by group in pandas


rawDescription: Converting php loop to python

description: Converting php loop to python


code: tree = KDTree(np.vstack((x,y,z)).T)

rawDescription: Search neighboring points using k-d trees


code:
#!/usr/bin/env python

''' animate text in a tkinter canvas

    See http://stackoverflow.com/q/34973060/4014959
    Written by PM 2Ring 2016.01.24
'''

import Tkinter as tk

class Application(object):
    def __init__(self):
        root = tk.Tk()
        self.canvas = tk.Canvas(root)
        self.canvas.pack()
        self.canvas_text = self.canvas.create_text(10, 10, text='', anchor=tk.NW)

        self.entry = tk.Entry(root)
        self.entry.bind("<Return>", self.entry_cb)
        self.entry.pack()
        root.mainloop()

    def animate_text(self, text, delta):
        ''' Animate canvas text with a time delay given in milliseconds '''
        delay = 0
        for i in range(len(text) + 1):
            update_text = lambda s=text[:i]: self.canvas.itemconfigure(self.canvas_text, text=s)
            self.canvas.after(delay, update_text)
            delay += delta

    def entry_cb(self, event):
        self.animate_text(self.entry.get(), 250)

app = Application()

rawDescription: How can i animate text by character in Tkinter?

description: Animate text by character in Tkinter


code: foo()

rawDescription: Prepend function call in other function in Python


code:
import csv
with open("data.txt", "r") as f:
  reader = csv.reader(f, delimiter=";")
  for row in reader:
    print(row)

rawDescription: reading data from file and printing specific colums per line

description: Reading data from file and printing specific colums per line


code:
with open('/etc/passwd') as f:
    print (list(f)[i])

rawDescription: Randomly generate a line from a .txt file


code:
ax.set_xticks([0., 15., 30., 45.])
num_ticks = 5.
ax.set_yticks(arange(num_ticks)/(num_ticks-1) * 50)

rawDescription: Editing Python plot surface ticks and their frequency


code:
import numpy as np

distance_matrix_np = np.array(distance_matrix)
stream_matrix_np = np.array(stream_matrix)
n = 4

def deltaC_np(r, s, sol):
    delta = 0
    sol_r, sol_s = sol[r], sol[s]

    K = np.array([i for i in xrange(n) if i!=r and i!=s])

    return np.sum(
        (stream_matrix_np[r,K] - stream_matrix_np[s,K]) \
        *  (distance_matrix_np[sol_s,sol[K]] - distance_matrix_np[sol_r,sol[K]]) + \
        (stream_matrix_np[K,r] - stream_matrix_np[K,s]) \
        * (distance_matrix_np[sol[K],sol_s] - distance_matrix_np[sol[K],sol_r]))

rawDescription: How to optimize math operations on matrix in python

description: Optimize math operations on matrix in python


code: [(utcdate, utcoffset, dstoffset, tzabbrev) for utcdate, (utcoffset, dstoffset, tzabbrev) in zip(tzone._utc_transition_times, tzone._transition_info)][:2]

rawDescription: Difference of two timedelta objects, with timezones


code:
class Global(dict):
    def undefined(self, *args, **kargs):
        return u'ran undefined'

    def __getitem__(self, key):
        if dict.has_key(self, key):
            return dict.__getitem__(self, key)
        return self.undefined

src = """
def foo():
    return u'ran foo'

print foo()
print callme(1,2)
"""

code = compile(src, '<no file>', 'exec')

globals = Global()
eval(code, globals)

rawDescription: How to override built-in getattr in Python?

description: Override built-in getattr in Python


code:
import hmac
hmac.new("9T5zhB4sTNGxMJ-iDdO-Ow"+"8rdp7erdig0m6aa72lhanvuk01"+"pizza1", "1387797294").hexdigest()

rawDescription: Convert Python Code to C# Code (generate HMAC)


code:
# First precalculate the static part of the string
template = 'prefix%s_' % day + '%s'

# Then, use the %s string interpolation instead of joining strings with '+'
# -->> Note: this proved to be wrong later...
signals = [template % s for s in signals]

# Alternatively you could use map to compare efficiency (be aware of differences between python 2 and 3)
signals = map(template.__mod__, signals)

rawDescription: Python, optimizing a list comprehension for string concatenation


code:
from bokeh.resources import CDN
CDN.js_files
CDN.css_files

rawDescription: Supplemental JavaScript for Bokeh Plot

description: Supplemental JavaScript for Bokeh Plot


code:
def predict(self, X):
    """Predict class labels for samples in X.

    Parameters
    ----------
    X : {array-like, sparse matrix}, shape = [n_samples, n_features]
        Samples.

    Returns
    -------
    C : array, shape = [n_samples]
        Predicted class label per sample.
    """
    scores = self.decision_function(X)
    if len(scores.shape) == 1:
        indices = (scores > 0).astype(np.int)
    else:
        indices = scores.argmax(axis=1)
    return self.classes_[indices]

rawDescription: How to fix the false positives rate of a linear SVM?

description: Fix the false positives rate of a linear SVM


code:
from scipy import integrate as integrate
def f(x,a,b,c):  #a is a parameter, x is the variable I want to integrate over
    return a*x + b + c

result = integrate.quad(f,0,1,args=(1,2,3))

rawDescription: How to evaluate single integrals of multivariate functions with Python's scipy.integrate.quad?

description: Evaluate single integrals of multivariate functions with Python's scipy.integrate.quad


code:
import wx
import sys
from wx.lib.mixins.listctrl import ListCtrlAutoWidthMixin

index=[1,2,3,4]
text=['animal','gv','asdfasdfasd','adfasdfasdf']
size=['1kb','2kb','3kb','4kb']
displaylist=[]
for i,j,l in zip(index,text,size):
    displaylist.append((i,j,l))

class AutoWidthListCtrl(wx.ListCtrl, ListCtrlAutoWidthMixin):
    def __init__(self, parent):
        wx.ListCtrl.__init__(self, parent, -1, style=wx.LC_REPORT)
        ListCtrlAutoWidthMixin.__init__(self)

class Actresses(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(380, 230))

        hbox = wx.BoxSizer(wx.HORIZONTAL)

        panel = wx.Panel(self, -1)

        self.list = AutoWidthListCtrl(panel)
        self.list.InsertColumn(0, 'index', width=140)
        self.list.InsertColumn(1, 'text', width=130)
        self.list.InsertColumn(2, 'filesize', wx.LIST_FORMAT_RIGHT, 90)

        for i in displaylist:
            index = self.list.InsertStringItem(sys.maxint, str(i[0]))
            self.list.SetStringItem(index, 1, i[1])
            self.list.SetStringItem(index, 2, i[2])

        hbox.Add(self.list, 1, wx.EXPAND)
        panel.SetSizer(hbox)

        self.Centre()
        self.Show(True)

app = wx.App()
Actresses(None, -1, 'file')
app.MainLoop()

rawDescription: String formating in wx.ListBox

description: String formating in wx.ListBox


code:
import json

json.dumps({'Names': y})

rawDescription: Python - How do I add the backslash characters when formatting a JSON string?


code:
df1['date'] = pd.to_datetime(df1.date)
df2['date'] = pd.to_datetime(df2.date)

rawDescription: Add elements of lists where dates match (Python)


code:
obs1 = obstacle()
obs2 = None

while q < 0:
  q = screen.getch()
  if obs1.pos < 0:
    obs1 = obstacle()
  if obs2 is not None and obs2.pos < 0:
    obs2 = obstacle()
  # Here's where we create obs2 on the fly
  if obs2 is None and obs1.pos == dims[0]/2:
    obs2 = obstacle()
  screen.clear()
  screen.addstr(obs1.pos, 0, obs1.s, curses.color_pair(1))
  if obs2 is not None:
    screen.addstr(obs2.pos, 0, obs2.s, curses.color_pair(1))
  obs1.scroll()
  if obs2 is not None:
    obs2.scroll()
  screen.refresh()
  time.sleep(.04)

rawDescription: Dealing with multiple strings in curses

description: Dealing with multiple strings in curses


code:
class Triangle:
    def __init__(self, a, b, c):
        self.side1 = a
        self.side2 = b
        self.side3 = c

    def getPerimeter(self):
        return self.side1 + self.side2 + self.side3

    def __str__(self):
        return "side1: {0.side1} side2: {0.side2} side3: {0.side3}".format(self)

rawDescription: How to make the input into a parameter in a class for Python

description: Make the input into a parameter in a class for Python


code:
if (with_numpy):
    incdir = incdir + list(nd.get_numpy_include_dirs())

rawDescription: how do i install pyffmpeg on windows 10

description: Install pyffmpeg on windows 10


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: d = pd.pivot_table(df,index='date',columns=['Location','method'], values='reading')

rawDescription: Reshaping pandas DataFrame

description: Reshaping pandas DataFrame


code:
class Foo(object):
    def __init__(self,pattern):
        self.count=1
        self.pattern=pattern
        self.grep=self._grep()
    @coroutine
    def _grep(self):
        while True:
            line = (yield)
            if self.pattern in line:
                print(self.count, line)
                self.count+=1
    def send(self,arg):
        self.grep.send(arg)

foo = Foo("python")
foo.send("Yeah, but no, but yeah, but no")
foo.send("A series of tubes")
foo.send("python generators rock!")
foo.pattern='spam'
foo.send("Some cheese?")
foo.send("More spam?")

# (1, 'python generators rock!')
# (2, 'More spam?')

rawDescription: python - support .send() for a class?

description: Python - support .send() for a class


code:
class groupby:
    # [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
    # [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
    def __init__(self, iterable, key=None):
        if key is None:
            key = lambda x: x
        self.keyfunc = key
        self.it = iter(iterable)
        self.tgtkey = self.currkey = self.currvalue = object()
    def __iter__(self):
        return self
    def __next__(self):
        while self.currkey == self.tgtkey:
            self.currvalue = next(self.it)    # Exit on StopIteration
            self.currkey = self.keyfunc(self.currvalue)
        self.tgtkey = self.currkey
        return (self.currkey, self._grouper(self.tgtkey))
    def _grouper(self, tgtkey):
        while self.currkey == tgtkey:
            yield self.currvalue
            try:
                self.currvalue = next(self.it)
            except StopIteration:
                return
            self.currkey = self.keyfunc(self.currvalue)

rawDescription: Unexpected Behavior of itertools.groupby


code:
counts = collections.Counter(lst)
new_list = sorted(lst, key=counts.get, reverse=True)

rawDescription: Sort list by frequency in python

description: Sort list by frequency in python


code:
from sqlalchemy.sql import expression
import sqlalchemy
from sqlalchemy.ext import compiler

class group_concat(expression.FunctionElement):
    name = "group_concat"

@compiler.compiles(group_concat, 'mysql')
def _group_concat_mysql(element, compiler, **kw):
    if len(element.clauses) == 2:
        separator = compiler.process(element.clauses.clauses[1])
    else:
        separator = ','

    return 'GROUP_CONCAT(%s SEPARATOR %s)'.format(
        compiler.process(element.clauses.clauses[0]),
        separator,
    )

rawDescription: How do I write a group_concat function in sqlalchemy?

description: Write a group_concat function in sqlalchemy


code: re.findall(r'\s', chrs, re.UNICODE)

rawDescription: In Python, how to list all characters matched by POSIX extended regex `[:space:]`?


code: dict(line.strip().split(',') for line in WDictionary)

rawDescription: Converting file to key/value dictionary

description: Converting file to key/value dictionary


rawDescription: Converting from hexadecimal to binary values


rawDescription: extract repeated elements in a list in python

description: Extract repeated elements in a list in python


code:
import multiprocessing
from multiprocessing.util import Finalize

resource_cm = None
resource = None

class Resource(object):
    def __init__(self, args):
        self.args = args

    def __enter__(self):
        print("in __enter__ of %s" % multiprocessing.current_process())
        return self

    def __exit__(self, *args, **kwargs):
        print("in __exit__ of %s" % multiprocessing.current_process())

def open_resource(args):
    return Resource(args)

def _worker_init(args):
    global resource
    print("calling init")
    resource_cm = open_resource(args)
    resource = resource_cm.__enter__()
    # Register a finalizer
    Finalize(resource, resource.__exit__, exitpriority=16)

def hi(*args):
    print("we're in the worker")

if __name__ == "__main__":
    pool = multiprocessing.Pool(initializer=_worker_init, initargs=("abc",))
    pool.map(hi, range(pool._processes))
    pool.close()
    pool.join()

rawDescription: Context managers and multiprocessing pools


code:
print(X[:5])
print(X_masked[:5])

rawDescription: Remove a specific feature in scikit learn


code: errorcheck = PyModule_AddObject(embmodule, "str", pyStr);

rawDescription: How to create and assign a Python variable in C?

description: Create and assign a Python variable in C


code:
def get_sublists(length):
    return [lst[i:i + length] for i in range(len(lst) - length + 1)]

rawDescription: Python get sublists

description: Python get sublists


rawDescription: View each result of a query with Jinja , python


rawDescription: How do i compute with (numpy) -arrays eloquently in python

description: Compute with (numpy) -arrays eloquently in python


code: [char * count for char, count in zip(string.ascii_lowercase, b)]

rawDescription: python list comprehension alphabet generation

description: Python list comprehension alphabet generation


code:
idx_tuple = tuple(np.ogrid[:M, :N, :2]) + (indices[..., None],)
P[idx_tuple]

rawDescription: Correctly indexing a multidimensional Numpy array with another array of indices


code: child_process.stdin.write("this goes to child")  #Popen(..., stdin=subprocess.PIPE)

rawDescription: Printing to stdout in subprocess

description: Printing to stdout in subprocess


code:
from bs4 import BeautifulSoup, Tag

data = """
<data>Here is some text about a frog.  <hello ref="1"/>This frog is <hello ref="2"/>orange<goodbye idref="2"/> and has polka-dots.<goodbye idref="1"/>  Isn't this interesting?</data>
"""
soup = BeautifulSoup(data, "xml")

text = ""
for elm in soup.find("hello", ref="1").next_siblings:
    if elm and elm.name == "goodbye" and elm.get("idref") == "1":
        break

    text += elm.get_text() if isinstance(elm, Tag) else elm

print(text)

rawDescription: lxml/beautifulsoup: Extracting text between two different tags

description: Lxml/beautifulsoup: Extracting text between two different tags


code: from functools import partial

rawDescription: Lock a choice in PyQt4 QComboBox using a QCheckBox


rawDescription: Get system metrics using PowerShell

description: Get system metrics using PowerShell


code: xVar, yVar = zip(*((x, y) for x, y in zip(xVar, yVar) if y <= 100))

rawDescription: python: How to remove values from 2 lists based on what's in 1 list

description: Python: How to remove values from 2 lists based on what's in 1 list


rawDescription: minimizing a given vector of components with a dataframe

description: Minimizing a given vector of components with a dataframe


code:
import networkx as nx
ba_g = nx.barabasi_albert_graph(10000,2)
ba_c = nx.degree_centrality(ba_g)
# To convert normalized degrees to raw degrees
#ba_c = {k:int(v*(len(ba_g)-1)) for k,v in ba_c.iteritems()}
ba_c2 = dict(Counter(ba_c.values()))

ba_x,ba_y = log_binning(ba_c2,50)

plt.xscale('log')
plt.yscale('log')
plt.scatter(ba_x,ba_y,c='r',marker='s',s=50)
plt.scatter(ba_c2.keys(),ba_c2.values(),c='b',marker='x')
plt.xlim((1e-4,1e-1))
plt.ylim((.9,1e4))
plt.xlabel('Connections (normalized)')
plt.ylabel('Frequency')
plt.show()

rawDescription: Plotting log-binned network degree distributions


code:
s = 'abasdf asdf qwert'
re.match('^(ab|a|)\w*\s*(?:(as|a)\w*|)\w*?\s*(qwe|qw|)',s).groups()
s = 'abab asf qwert'
re.match('^(ab|a|)\w*\s*(?:(as|a)\w*|)\w*?\s*(qwe|qw|)',s).groups()
s = 'abab qwert'
re.match('^(ab|a|)\w*\s*(?:(as|a)\w*|)\w*?\s*(qwe|qw|)',s).groups()
s = 'abab asfq'
re.match('^(ab|a|)\w*\s*(?:(as|a)\w*|)\w*?\s*(qwe|qw|)',s).groups()

rawDescription: Empty string taking precedence in python regex subpatterns with multiple groups


code:
narrative_list([])
narrative_list(["a"])
narrative_list(["a", "b"])
narrative_list(["a", "b", "c"])

rawDescription: Elegant way for creating a narrative string of a list


rawDescription: Qt GraphicsScene constantly redrawing

description: Qt GraphicsScene constantly redrawing


code:
from twisted.internet.protocol import Protocol, BaseProtocol
import inspect
from pprint import pprint
pprint(inspect.getclasstree(inspect.getmro(Protocol)))
dir(Protocol)

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


code:
for feat in tracts_geojson['features']:
    lat, long = feat['properties']['latitude'], feat['properties']['longitude']
    if (lat, long) in parking:
        feat['properties']['parking'] = parking[lat, long]

rawDescription: how to add information to json using Python in fast way

description: Add information to json using Python in fast way


rawDescription: deleting and inserting values in matrix multiplication python language

description: Deleting and inserting values in matrix multiplication python language


code:
for i in range(5):
    turn1l = []

rawDescription: Raise SystemExit not working

description: Raise SystemExit not working


code:
import pprint

pprint.pprint(men)

rawDescription: JSON or SimpleJSON and Python with Twython


rawDescription: How to quickly grab specific indices from a numpy array?

description: Quickly grab specific indices from a numpy array


rawDescription: Fastest Way to Sum Individual Columns

description: Fastest Way to Sum Individual Columns


code: result = result.fillna(0)

rawDescription: pandas - group and count nunique values

description: Pandas - group and count nunique values


code:
fig, ax = plt.subplots(num=None, figsize=(16, 12), dpi=80, facecolor='w', edgecolor='k')
## I changed the fig size to something obviously big to make sure it worked

rawDescription: Matplotlib Window Size, Title, etc

description: Matplotlib Window Size, Title, etc


code:
class dummy_class_1(object):
  def dummy_func_1(self, master):
    return
  def dummy_func_2(self):
    return

class dummy_class_2(object):
  def dummy_func_3(self, event):
    return
  def dummy_func_4(self):
    return

import dill

dill.dumps((dummy_class_1, dummy_class_2))

rawDescription: Serializing functions/classes in python

description: Serializing functions/classes in python


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


code:
['Mr. ', 'McCONNELL',
 '. yadda yadda jon stewart is mean to me. The ',
 'PRESIDING OFFICER', '. Suck it up. Mr. ',
 'McCONNELL', '. but noooo. Mr. ', 'REID', '. Really dude?']

rawDescription: split by elements of a string, and create a dictionary with {element used to split: that chunk of text}

description: Split by elements of a string, and create a dictionary with {element used to split: that chunk of text}


rawDescription: Variable alpha blending in pylab

description: Variable alpha blending in pylab


code:
import time

datestr = "Wed Apr 24 19:25:06 2013 GMT"
time.mktime(time.strptime(datestr, "%a %b %d %H:%M:%S %Y %Z")) * 1000

rawDescription: python linux timestamp to date time and reverse

description: Python linux timestamp to date time and reverse


code:
data
[data.sort(key=operator.itemgetter(x)) for x in [0,1,2]]
data

rawDescription: grouping with topology

description: Grouping with topology


code:
for b in driver.find_elements_by_xpath("//a/following-sibling::b"):
    print(b.text)

rawDescription: How to select all tags with selenium and python

description: Select all tags with selenium and python


code: df['index'] = range(4)*2

rawDescription: reshaping data frame in pandas

description: Reshaping data frame in pandas


code:
import argparse
import sys
import C
import B

def main(args):
    valA1 = args.param1A
    valA2 = args.param2A
    # do stuff
    return 0

if __name__ == '__main__':
    parser = C.create_parser()
    parser.add_argument("--param1A", type=int)
    parser.add_argument("--param2A", type=int)
    args = parser.parse_args()
    B.main(args)
    sys.exit(main(args))

rawDescription: Python: "importing" input arguments

description: Python: "importing" input arguments


code:
if " " in sheet.cell(row,col):
    values.append(str(sheet.cell(row,col).value.split(" ")))
else:
    values.append(str(sheet.cell(row,col)))

rawDescription: Count number of occurences of specific words in Excel sheet using python & xlrd


code: undecorated = [value[1] for value in decorated_sorted]

rawDescription: How can I sort list by second element without using lambda?

description: Sort list by second element without using lambda


code:
while True:
    process_new_file()     # does nothing if no new file
    time.sleep(60)

rawDescription: Updating CSV files automatically

description: Updating CSV files automatically


code:
fig = plt.figure()
ax = plt.subplot(111)
ax.xaxis.set_major_locator(mpl.dates.MonthLocator())
format = mpl.dates.DateFormatter('%m/%d') #explore other options of display
ax.xaxis.set_major_formatter(format)

ax.hist(stacked_dates) #plot the damned thing

plt.xticks(rotation='vertical') #avoid overlapping numbers
                           #make sure you do this AFTER .hist function

plt.show()

rawDescription: How to make a histogram from this nc file?

description: Make a histogram from this nc file


code:
class Computations(object):
    def __init__(self, name):
        self.name = name   # default value for area, circumference, distance to origin

    def __get__(self, instance, cls):
        if instance is None:
            print('this is the __get__ if statement running')
            return self
        else:
            print('this is the __get__ else statement running')
            return instance.__dict__[self.name]

    def __set__(self, instance, value):
        if hasattr(instance, self.name + '_is_set'):
            raise ValueError('Cannot set {} again.'.format(self.name[1:]))
        if isinstance(value, int):
            raise RuntimeError('Cant set formulas')
        else:
            instance.__dict__[self.name] = value
            setattr(instance, self.name + '_is_set', True)

rawDescription: Using descriptor class to raise RuntimeError when user tries to change object's value


code:
from itertools import product
a=['1','2','3']
b=['bc','b']
c=['#']
map("".join, product(a,b,c))

rawDescription: How can I simplify "for x in a for y in b for z in c ..." with the unordered?

description: Simplify "for x in a for y in b for z in c ..." with the unordered


rawDescription: Using numpy loadtext

description: Using numpy loadtext


code:
class HandlerManager:
    handlers = []
    @classmethod
    def register(cls, handler):
        print("registering", handler)
        cls.handlers.append(handler)

class HandlerRegisterer(type):
    def __init__(self, name, bases, attrs, register=True):
        super().__init__(name, bases, attrs)
        if register:
            HandlerManager.register(self)

    def __new__(metaclass, name, bases, attrs, register=True):
        return super().__new__(metaclass, name, bases, attrs)

class BaseHandler(metaclass=HandlerRegisterer, register=False):
    # not actually a real handler, so don't register this class
    pass

class MyHandler(BaseHandler):
    # only have to inherit from another handler to make sure this class
    # gets registered.
    pass

print(HandlerManager.handlers)
assert BaseHandler not in HandlerManager.handlers
assert MyHandler in HandlerManager.handlers

rawDescription: Is there a way to call a function after a class was loaded in python?


code: reduce(lambda x, y: x + len(y), d['childs'].itervalues(), 0)

rawDescription: Count the number of items from a dictionary inside another dictionary in Python


code:
{u'widget': {u'debug': u'on', u'window': {u'width': 500, u'height': 500, u'name': 'abcd', u'title': u'Sample Konfabulator Widget'}}}
abcd

rawDescription: How to add json array to a json document in python?

description: Add json array to a json document in python


rawDescription: Truncated versus floored division in Python


code:
def f(x):
    return x**2 + 1

rawDescription: How to define a mathematical function in SymPy?

description: Define a mathematical function in SymPy


code: request.POST.get("title", "")

rawDescription: Django - taking values from POST request


code:
def knights_tour(start, boardsize=boardsize, _debug=False):
    board = {(x,y):0 for x in range(boardsize) for y in range(boardsize)}
    move = 1
    P = chess2index(start, boardsize)
    moves.append(P)

    board[P] = move
    move += 1
    if _debug:
        print(boardstring(board, boardsize=boardsize))
    while move <= len(board):
        P = min(accessibility(board, P, boardsize))[1]
        moves.append(P)
        board[P] = move
        move += 1
        if _debug:
            print(boardstring(board, boardsize=boardsize))
            input('\n%2i next: ' % move)
    return moves

rawDescription: Simulating the Knight Sequence Tour

description: Simulating the Knight Sequence Tour


rawDescription: numpy array that is (n,1) and (n,)

description: Numpy array that is (n,1) and (n,)


rawDescription: Getting digits in an order (left to right) after OCR from x,y coordinates


code: sorted_names = sorted(rankednames.keys(), key=lambda x: int(rankednames[x]), reverse=True)

rawDescription: How can I sort a list numerically rather than alphabetically?

description: Sort a list numerically rather than alphabetically


rawDescription: How to list available tests with python?

description: List available tests with python


code:
def transpose_matrix(matrix):
    matrix[:] = list(map(list, zip(*matrix)))

rawDescription: Transpose this matrix(python3)

description: Transpose this matrix(python3)


rawDescription: How can i iterate over image pixels in a faster manner in python?

description: Iterate over image pixels in a faster manner in python


code:
def Child(Base):

    def __init__(self, attr1, attr2):
        self.attr1 = attr1
        self.attr2 = attr2

rawDescription: What is the practical use of the keyword super in Python inheritance?


code:
class Customers(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    cust_name = db.Column(db.String(64), info={'name': 'Customer name'})
    cust_area = db.Column(db.String(64), info={'name': 'Customer area'})
    cat_id = db.Column(db.Integer(8), index=True)

rawDescription: Flask-sqlalchemy column alias for browser output


code:
idx = tree.query_ball_point((4, 4), 2)
points_ref[idx]

rawDescription: Scipy cKDTree nearest neighbor including zeros distance


code:
from operator import sub
map(sub, x2, x1)
from itertools import imap
tuple(imap(sub, x2, x1))

rawDescription: Difference of two tuples containing Long numbers


code:
from sklearn import cluster as cluster
import numpy as np

km = cluster.KMeans(n_clusters=4)
example_data = np.asarray([1,2,3, 11,12, 20,21,22, 30,35])[:,None]

km.fit(example_data)

rawDescription: Splitting up a list into different length parts under special condition


code:
class Test(models.Model):
    person = models.ForeignKey(Person, related_name='tests')
    date = models.DateTimeField(auto_now_add=True)
    test_name = models.CharField(max_length=200,default='',blank=False)
    subject = models.CharField(max_length=100,default='')

rawDescription: django sort the query elements in a weekly monthly daily fashion

description: Django sort the query elements in a weekly monthly daily fashion


rawDescription: Remove repeating spaces manually in a string


code:
for i in range(len(l)):
    for k in range(i+1, len(l)):
        print(l[i], l[k])

rawDescription: Why is my for loop skipping an element in my list?


code:
hull = ConvexHull(df[['col_1','col_2']])
import matplotlib.pyplot as plt
plt.plot(df['col_1'], df['col_2'], 'o')
for simplex in hull.simplices:
    plt.plot(df['col_1'].iloc[simplex], df['col_2'].iloc[simplex], 'k-')

rawDescription: SciPy Convex Hull Error

description: SciPy Convex Hull Error


rawDescription: python function sorting alternating disks

description: Python function sorting alternating disks


rawDescription: How to configure ipy_user_conf.py to get IPython to to start with the right IDLE set as editor?

description: Configure ipy_user_conf.py to get IPython to to start with the right IDLE set as editor


code:
Example
text = """{
  "type": "Person",
  "subType": "Athlete",
  "subType": "AwardWinner"
}"""

rawDescription: SimpleJson handling of same named entities


code:
self.labelVariable.set("new value")
self.entryVariable.set("new value 2")

rawDescription: python to add variables to list by identifying from a line

description: Python to add variables to list by identifying from a line


code:
def rename(path):
    """ Renames all the files to be cropped-%d.xxx """
    count = 0
    for thing in os.listdir(path):
        root, ext = os.path.splitext(thing)
        old = os.path.join(path, thing)
        new = os.path.join(path, sys.argv[1] + ".cropped{0}".format(count) + ext)
        print("rename from {} to {}".format(old, new))
        os.rename(old, new)
        count += 1

rawDescription: Python renaming files being weird

description: Python renaming files being weird


code:
@register.simple_tag
def bitlyfy(the_url):
    endpoint = 'https://api-ssl.bitly.com/v3/shorten?access_token={0}&longUrl={1}&format=txt'
    req = urlencode(endpoint.format(settings.ACCESS_KEY, the_url))
    return urlopen(req).read()

rawDescription: URL detection and shortening in Django

description: URL detection and shortening in Django


rawDescription: Set DataFrame row index to a different column


code:
... is Ellipsis
Ellipsis in [...]
any(i is Ellipsis for i in [1, ..., 2])

rawDescription: What does Python mean by printing "[...]" for an object reference?


rawDescription: how to change [1,2,3,4] to '1234' using python

description: Change [1,2,3,4] to '1234' using python


code: return not any(dict[key] > otherDict[key] for key in dict)

rawDescription: comparing dictionary values with same keys

description: Comparing dictionary values with same keys


code:
SOCIAL_AUTH_PIPELINE += (
'<application>.pipelines.save_profile_picture',
)

rawDescription: Save facebook profile picture in model using python-social-auth


code:
count = 0
wordList=["hello","hi","is","and", "are", "you"]

#'are' appears twice and 'you' once - total should be 3
inList=["how", "are","you", "where", "are", "your", "friends" ]
count = 0
#count number of times the words in wordList appear in the input list 'inList'
for word in inList:
    if word in wordList:
        count += 1
print(count)

rawDescription: Write a loop that sums the number of times that the words in wordList occur in the list


code: Popen('vgremove -f <vgname>')

rawDescription: Popen a command that contains need to say yes for all outputs


code:
l = ['123','12\'3',"222'333"]
with open('b.csv','w') as f:
    writer = csv.writer(f,quotechar="'")
    writer.writerow(l)
with open('b.csv','r') as f:
    reader = csv.reader(f,quotechar="'")
    for line in reader:
            print(line)

rawDescription: Scrapping and string-formatting issue : one time scrap with '' another time with ""


code:
import re
import random
text = '000 #-tags-2-7-# 001 002 003 004 05 06 07 08 SDFGSDFG #-tags-3-9-#'
keys = ['key-1', 'key-2', 'key-3', 'key-4', 'key-5', 'key-6', 'key-7', 'key-8', 'key-9', 'key-10']

def tag_replace(match):
    start, end = map(int, match.groups())
    return ', '.join(random.sample(keys, random.randint(start, end)))

print(re.sub(r'#-tags-(\d)-(\d)-#', tag_replace, text))

rawDescription: Getting data for replacement (python 3.3)


rawDescription: compare similar items nested in a list, and removing them

description: Compare similar items nested in a list, and removing them


code: newL=[filter(len, e.split('&')) for l in LofL for e in l]

rawDescription: Finding and splitting at a character from a string inside a list of lists


code: sorted(entries, key=lambda t: (-t[0], t[1]))

rawDescription: How to sort this text file in descending order in python?

description: Sort this text file in descending order in python


code: self.player.rect.x += 5

rawDescription: Trying to make a "solid" block in pygame but it doesnt work


code:
monster = Monster(20, 'Boris')
monster.stats()
monster.health -= 5
monster.stats()

rawDescription: Pass variables set within a function to a method within a class


code:
class LJV7IF(object):
    # loading the DLL and defining prototypes should be done
    # only once, so we do this in the class (or module) definition.
    _dll = WinDLL("LJV7_IF")
    _dll.LJV7IF_Initialize()

    _dll.LJV7IF_GetStorageData.restype = c_long
    _dll.LJV7IF_GetStorageData.argtypes = (c_long,
                                           POINTER(GET_STORAGE_REQ),
                                           POINTER(STORAGE_INFO),
                                           POINTER(GET_STORAGE_RSP),
                                           POINTER(c_byte),
                                           c_uint)

    def __init__(self, device_id, record_type):
        self.device_id = device_id
        self.record_type = record_type

    def get_storage_data(self, count):
        storage_req = GET_STORAGE_REQ()
        storage_info = STORAGE_INFO()
        storage_rsp = GET_STORAGE_RSP()
        data_size = sizeof(self.record_type) * count
        data = (c_byte * data_size)()
        result = self._dll.LJV7IF_GetStorageData(self.device_id,
                                                 byref(storage_req),
                                                 byref(storage_info),
                                                 byref(storage_rsp),
                                                 data,
                                                 data_size)
        if result < 0: # assume negative means an error.
            raise DeviceError(self.device_id) # an Exception subclass.
        return (self.record_type * count).from_buffer(data)

rawDescription: How to interpret a integer as a float

description: Interpret a integer as a float


code:
fruits['banana'].append('1.80')
print( fruits['banana'] )

rawDescription: How do I generate a list for each list item

description: Generate a list for each list item


code:
import importlib  # just once
importlib.import_module(name)

rawDescription: Plugin manager in python

description: Plugin manager in python


code: ~array

rawDescription: python, numpy boolean array: negation in where statement

description: Python, numpy boolean array: negation in where statement


code: metaList[x] = tempList[:]

rawDescription: Issue filling a list with other lists containing random numbers.


code:
def sse_request():
    r = Response(data_stream(),  mimetype='text/event-stream')
    data_queue.put({'data': [{'lat':0, 'lg':0}]})
    return r

def collect_data():
    data_queue.put({"data": [request.get_json()]})
    ...

rawDescription: Using SSE to pass on data from other APIs in real time


code:
import zipfile

with zipfile.ZipFile('test.zip', "r") as z:
    z.extractall("C:\\")

rawDescription: Extracting zip file contents to specific directory in Python 2.7


code:
X_pred = vect.transform(['My new document'])
y_pred = model.predict(X_pred)

rawDescription: How do I use use the tfidf-calculating functions in scikit-learn?

description: Use use the tfidf-calculating functions in scikit-learn


code: plt.figure(figsize=(8,6)) # (width, height)

rawDescription: Plotting for conference posters (increase textsize, linewidth, ... at once)


rawDescription: How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?

description: Make a 'while' loop print the results of the loop's conditional into a single line(concatenated)


code:
class my_toolbar(NavigationToolbar2TkAgg):
    def set_message(self, msg):
        pass

rawDescription: Disable displaying coordinate in matplotlib plot


code:
col_names = df.columns
# start from one to exclude row, end at -1 to exclude alpha column
for x in range(1, len(col_names) - 1):
    new_column_name = col_names[x] + "_x_alpha" # get good new column names
    df = df.withColumn(new_column_name, (getattr(df, col_names[x]) * getattr(df, col_names[3])))

rawDescription: PySpark: running the same operation on multiple columns in one go