code:
df
df1=df.set_index('col2').sort_index()
df1
df1['cumsum']=df1.groupby('col1')['col3'].transform(pd.Series.cumsum)
df1

rawDescription: cumsum per group in column ordered by second column append to original dataframe

description: Cumsum per group in column ordered by second column append to original dataframe


code: x = int(x == 'true')

rawDescription: How to convert false to 0 and true to 1 in python

description: Convert false to 0 and true to 1 in python


rawDescription: Get original values from cumulative sum

description: Get original values from cumulative sum


code:
for cat, text in tuples:
    tokenized = tokenize(text)
    # now do whatever you want with the category and the tokenized text

rawDescription: Parsing text in a tuple

description: Parsing text in a tuple


code:
import csv

my_list = []

with open('file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        my_list.append(myClass(row[0], row[1], row[2:]))

rawDescription: Making objects from a CSV file Python

description: Making objects from a CSV file Python


code:
import bs4
import requests

response = requests.get('http://my.gwu.edu/mod/pws/courses.cfm?campId=1&termId=201501&subjId=ACCY')
soup = bs4.BeautifulSoup(response.text)

for tr in soup.findAll('tr')[11:]:
    stack = []
    for td in tr.findAll('td'):
        stack.append(td.text.strip())
    print(",".join(stack))

rawDescription: Extract html cell data with BeautifulSoup and Requests


code:
import os
from subprocess import check_call

check_call([os.path.join(bin_path, 'pip.exe')] +
           'install -r dev_requirements.txt'.split())

rawDescription: How to run `pip` in a virtualenv with subprocess.Popen()?

description: Run `pip` in a virtualenv with subprocess.Popen()


code:
import numpy as np

matrix = np.zeros((2,3,10))
second_col = matrix[:,1,:]

rawDescription: Create empty matrix Python

description: Create empty matrix Python


code:
plot_date(dates, y1)
plot_date(dates, y2)

rawDescription: plotting multiple time series, with single date series and with py_date()

description: Plotting multiple time series, with single date series and with py_date()


code:
import sys
with open(sys.argv[1]) as f, open('out.txt', 'w') as out:
    for line in f:
       if line.strip():                     #checks if line is not empty
           out.write(line.split()[0]+'\n')

rawDescription: Write array to text file. Each element on a new line in Python 2.7


code:
statue_a = Statue()
statue_a._meta.get_field('ref_id').rel.to

rawDescription: Get referenced Model by field name on Django?


code:
from functools import partial
my_list = partial(list, 'Hello world!')
my_list
my_list()

rawDescription: Set callback along with its parameters and invoke the callback later


code:
def main_func():
    from impl import a, b, c

    a()
    b()
    c()

rawDescription: Python code/function layout

description: Python code/function layout


code:
m = 'Some Text That exists version 1.0.41.476 Fri Jun  4 16:50:56 EDT 2010'
import re
re.search(r'version (\S+)', m).group(1)

rawDescription: Using RE to retrieve an ID

description: Using RE to retrieve an ID


code:
import requests
import urllib

from bs4 import BeautifulSoup

params = {
    "type":"team-detail",
    "league":"ncb",
    "stat_id":"3083",
    "season_id":"312",
    "cat_type":"2",
    "view":"stats_v1",
    "is_previous":"0",
    "date":"04/06/2015"
}

content = urllib.request.urlopen("http://www.teamrankings.com/ajax/league/v3/stats_controller.php",data=urllib.parse.urlencode(params).encode('utf8')).read()
soup = BeautifulSoup(content)

table = soup.find("table", attrs={'class':'sortable'})

data = []
rows = table.findAll("tr")
for tr in rows:
    cols = tr.findAll("td")
    for td in cols:
        text = ''.join(td.find(text=True))
        data.append(text)

print(data)

rawDescription: Python web scraping - how to get resources with beautiful soup when page loads contents via JS?


code:
class MyDict(dict):
    def __init__(self, factory):
        self.factory = factory
    def __missing__(self, key):
        self[key] = self.factory(key)
        return self[key]

d = MyDict(lambda x: -x)
d[1]
d

rawDescription: Accessing key in factory of defaultdict

description: Accessing key in factory of defaultdict


code: writer = csv.writer(f, delimiter=";")

rawDescription: Writing Excel to CSV file, how can I use another delimiter?


code:
pynotify.init("app_name")
n = pynotify.Notification("", "message A", icon='some_icon')
n.set_urgency(pynotify.URGENCY_CRITICAL)
n.set_timeout(1000)
n.show()
n.update("","message B")
n.show()

rawDescription: pynotify linux changing the text

description: Pynotify linux changing the text


code:
import re
import sys

file = open("fixVel.txt")
textfile = file.readlines()
count = -1
matrix = []
for row in textfile:
    if row.find("Time") == 0:
        count = count + 1
        matrix.append([])
    if row.find("DICPCG") == 0:
        index = row.find("Initial residual")
        index1 = row[index:].find(",")
        matrix[count].append(row[index+19:index+index1])
#print matrix
for i in matrix:
    for j in i:
        sys.stdout.write(j + " ")
    print

rawDescription: I want to extract data from a txt file with python


code:
import copy
def remove_empty(x):
    for c in copy.copy(x):
        if not c:
            x.discard(c)
    return x

df['new_col'] = zip(df.lat, df.long)
df['new_col'] = df['new_col'].apply(set)
df['new_col'] = df['new_col'].apply(remove_empty)

rawDescription: How to form tuple column from two columns in Pandas of only non empty values

description: Form tuple column from two columns in Pandas of only non empty values


rawDescription: how to compute 'nearby' nodes with networkx

description: Compute 'nearby' nodes with networkx


code: globals()['FooClass'](**d)

rawDescription: Pass kwargs to dynamically instantiated Python Class


code:
posts = Post.objects.filter(...)[:20]

post_id_map = {}
for post in posts:
    post_id_map[post.id] = post
    # Iteration causes the queryset to be evaluated and cached.
    # We can therefore annotate instances, e.g. with a custom `tag_list`.
    # Note: Don't assign to `tags`, because that would result in an update.
    post.tag_list = []

# We'll now need all relations between Post and Tag.
# The auto-generated model that contains this data is `Post.tags.through`.
for t in Post.tags.through.select_related('tag').filter(post_id__in=post):
    post_id_map[t.post_id].tag_list.append(t.tag)

# Now you can iterate over `posts` again and use `tag_list` instead of `tags`.

rawDescription: Django: optimizing many to many query

description: Django: optimizing many to many query


code: page_number = int(re.sub('[^0-9]', '', total_matches)) + 1

rawDescription: Is there any way to write it better?

description: Is there any way to write it better


code:
from urllib.parse import parse_qsl

def application(environ, start_response):
    try:
        path = environ['PATH_INFO']
    except KeyError:
        path = environ['REQUEST_URI'].decode('utf-8').split('=', 1)[1]
    method = environ['REQUEST_METHOD']
    get = dict(parse_qsl(environ['QUERY_STRING'], keep_blank_values=True))
    post = dict(parse_qsl(environ['wsgi.input'].read().decode('utf-8')))

    if path == '/my_form':
        start_response('200 OK', [('Content-Type', 'text/html; charset=utf-8')])
        yield '''\
<form action="" method="POST">
    What is your name?
    <input type="text" name="name"/>
    <input type="submit"/>
</form>'''.encode('utf-8')
        if method == 'POST' and 'name' in post:
            yield "
Hello, {}!
".format(post['name']).encode('utf-8')
    else:
        start_response('404 Not Found', [('Content-Type', 'text/html')])
        yield "
404 Not Found
".encode('utf-8')

rawDescription: Bare bones web form example using python3 & mod_wsgi (no Django)?


code:
import json
value = "{\\x22username\\x22:\\x229\\x22,\\x22password\\x22:\\x226\\x22,\\x22id\\x22:\\x222c8bfa56-f5d9\\x22, \\x22FName\\x22:\\x22AnkQcAJyrqpg\\x22}"
value.decode('string_escape')
json.loads(value.decode('string_escape'))

rawDescription: how to convert characters like \x22 into string

description: Convert characters like \x22 into string


code:
def accuracy(n, i):
    return round(float(n) / 10**i) * 10**i

rawDescription: python function to set accuracy of float

description: Python function to set accuracy of float


code: None not in lst

rawDescription: A concise way to say "none of the elements of an array are None"?


code:
from mpl_toolkits.axes_grid1 import ImageGrid
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(20, 12))
grid = ImageGrid(fig, 111, nrows_ncols=(3, 4), axes_pad=1, aspect=False)

#get the extent of the largest box containing all the axes/subplots
extents = np.array([a.get_position().extents for a in grid])  #all axes extents
bigextents = np.empty(4)
bigextents[:2] = extents[:,:2].min(axis=0)
bigextents[2:] = extents[:,2:].max(axis=0)

#text to mimic the x and y label. The text is positioned in the middle
labelpad=0.08  #distance between the external axis and the text
xlab_t = fig.text((bigextents[2]+bigextents[0])/2, bigextents[1]-labelpad, 'x label',
    horizontalalignment='center', verticalalignment = 'bottom')
ylab_t = fig.text( bigextents[0]-labelpad, (bigextents[3]+bigextents[1])/2, 'y label',
    rotation='vertical', horizontalalignment = 'left', verticalalignment = 'center')

rawDescription: How can I create single axes labels for an entire figure created with ImageGrid

description: Create single axes labels for an entire figure created with ImageGrid


code:
from django.db import models
class M(models.Model):
    pass
m = M()
dir(m)

rawDescription: What are the implicit fields available in a Django model?


code: pd.to_datetime('20140415 ' + df.hhmm)

rawDescription: Pandas to_datetime - setting the date when only times (HH:MM) are input


code:
import warnings
warnings.filterwarnings('always')
import numpy as np
np.uint8(250) * np.uint8(2)
np.uint8(250) * np.uint8(2)

rawDescription: Configure IPython to show warnings all the time


rawDescription: extend/append list

description: Extend/append list


code:
from scrapy.xlib.pydispatch import dispatcher
from scrapy import signals

class MySpider(Spider):
    def __init__(self, *args, **kwargs):
        dispatcher.connect(self.spider_closed, signal=signals.spider_closed)
        super(MySpider, self).__init__(*args, **kwargs)

    def spider_closed(self, spider):
        log.msg('The spider {0} finished working on'.format(self.name), level=log.INFO)

rawDescription: spider_closed function is not fired

description: Spider_closed function is not fired


code:
myImage = getImage(visibleCards[0])
b1 = Button(root, image=myImage)
b1.grid(column = 0, row = 0)

root.mainloop()

def getImage(card):
    currentPath = "Pictures//"
    currentColor = card.color
    currentPath = currentPath + currentColor
    currentShading = card.shading
    currentPath = currentPath + currentShading
    currentNumber = card.number
    currentPath = currentPath + currentNumber
    currentPath = currentPath + card.symbol
    currentPath = currentPath + ".gif"

    currentImage=PhotoImage(file=currentPath)
    currentImage = currentImage.subsample(x = "2", y = "2")

    return currentImage

rawDescription: Python Tkinter Buttons just work with hardcoded Images


code:
p,m,n,r = a.shape
a.reshape(-1,r)[np.arange(p*m*n),b.ravel()] = 1

rawDescription: NumPy array indexing a 4D array

description: NumPy array indexing a 4D array


code:
def make_duplicate_request(request):
    """
    Since werkzeug request objects are immutable, this is needed to create an
    identical request object with mutable values
    """
    class Req(object):
        method = 'GET'
        path = ''
        headers = []
        args = []
    r = Req()
    r.path = request.path
    r.headers = request.headers
    r.is_xhr = request.is_xhr
    r.args = request.args
    return r

rawDescription: Changing values on a werkzeug request object


code:
def records(stream):
    while stream:
        lines = []
        for line in stream:
            lines.append(line)
            if line.startswith('//'):
                break
        record = ''.join(lines)
        yield record

for record in records(data):
    if "5'UTR\nNO information" not in record:
        output.write(record)

rawDescription: Deleting the text preceeding a given sentence


code:
import collections
d = collections.deque([0,3,5,1,5,8])
5 in d
20 in d

rawDescription: How do I find out if a value is in a deque?

description: Find out if a value is in a deque


code:
import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '{"query":{"bool":{"must":[{"text":{"record.document":"SOME_JOURNAL"}},{"text":{"record.articleTitle":"farmers"}}],"must_not":[],"should":[]}},"from":0,"size":50,"sort":[],"facets":{}}'
response = requests.get(url, data=data)

rawDescription: Making a request to a RESTful API using python


code:
import re

def get_some_name(some_name, line):
    regex = r'{0}="([^"]*)"'.format(some_name)
    some_value = re.search(regex, line).groups()[0]
    return some_value

line = 'bla bla bla- 3 [saa@dsds aaa="789" SomeName="35229644" vv="typw" ee="o" Task="None"] >bla bla bla'

print(get_some_name(some_name="SomeName", line=line))

rawDescription: I need a python code that will parse a line and get values which I need


code:
import clr
clr.AddReference('ClassLibrary1')
from ClassLibrary1 import MmsValue
from System import UInt32

uint32_mmsValue = MmsValue.__new__.Overloads[UInt32](MmsValue, 1)

rawDescription: How to invoke a .Net method with unsigned integer argument from IronPython

description: Invoke a .Net method with unsigned integer argument from IronPython


code:
import re
_split_new = re.compile(r"(PROD\s+\d+\s+\d+)(.*)")

# create an index for the PROD items to be updated

# this might be a bit more understandable...
#with open('updates.txt') as updates:
#    new_data = {}
#    for line in updates:
#        match = _split_new.match(line)
#        if match:
#            key, value = match.groups()
#            new_data[key] = value

# ... but this is fancier (and likely faster)
with open('updates.txt') as updates:
    new_data = dict(match.groups()
        for match in (_split_new.search(line) for line in updates)
        if match)

# then process the updates
with open('origstuff.txt') as orig, open('newstuff.txt', 'w') as newstuff:
    # for each line in the original...
    for line in orig:
        match = _split_new.match(line)
        # ... see if its a PROD line
        if match:
            key, value = match.groups()
            # ... and rewrite with value from indexing dict (defaulting to current value)
            newstuff.write("%s%s\n" % (key, new_data.get(key, value)))
        else:
            # ... or just the original line
            newstuff.write(line)

rawDescription: Set of lines to replace in file - python


code:
from itertools import izip_longest
from operator import mul

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

for g in grouper(5, b, fillvalue=''):
    # And to work out the product of the digits
    num = ''.join(g)
    prod = reduce(mul, map(int, num))

rawDescription: Subset a large number into smaller series of numbers using python


code: shlex.split("name1=abc name2='def' name3=\"ghi klm\"")

rawDescription: Simulate normalizing arguments

description: Simulate normalizing arguments


code: sorted(files, key=lambda d: d["name"].lower().replace("_", "}"))

rawDescription: Sorting with underscores

description: Sorting with underscores


code:
from chameleon import PageTemplateFile

path = os.path.dirname(__file__)
main_template = PageTemplateFile(os.path.join(path, '..', 'templates', 'restaurant.pt'))
lizard = PageTemplateFile(os.path.join(path, '..', 'emails', template+'.pt'))
html = lizard(main_template=main_template, **data)

rawDescription: Chameleon macros without Pyramid

description: Chameleon macros without Pyramid


code:
seenpositions = set()
currentpositions = set([startingposition])
while currentpositions:
  nextpositions = set()
  for p in currentpositions:
    seenpositions.add(p)
    succ = possiblesuccessors(p)
    for np in succ:
      if np in seenpositions: continue
      if isending(np): raise FoundSolution(np)
      nextpositions.add(np)
  currentpositions = nextpositions
raise NoSolutionExists()

rawDescription: Depth-First search in Python

description: Depth-First search in Python


code:
from django.views.generic import RedirectView

url(r'^accounts/signup/$',
    RedirectView.as_view(url='/', permanent=False),
    name='userena_signup'),

rawDescription: Class Based View alternative for deprecated redirect_to in Django 1.3 onwards


code:
listUpdate = [('f1', 'i'), ('f2', '2')]

setCommand = ', '.join([' %s = %s' % x for x in listUpdate])
all_columns = 'id, id2, num1, num2'
vals = '%s, %s, %s, %s'

update_query = """
               INSERT INTO `my_table`
               ({all_columns}) VALUES({vals})
               ON DUPLICATE KEY SET {set}
               """.format(all_columns=all_columns, vals=vals, set=setCommand)

print(update_query)

rawDescription: Is it possible to create a query command that takes in a list of variables in python-mysql


code:
import ctypes
from ctypes import wintypes

lib = ctypes.WinDLL(dllnamehere)
lib.VCS_GetProtocolStackSettings.argtypes = [wintypes.HANDLE,wintypes.PDWORD,wintypes.PDWORD,wintypes.PDWORD]
lib.VCS_GetProtocolStackSettings.restype = wintypes.BOOL

def VCS_GetProtocolStackSettings(KeyHandle):
    baudrate = wintypes.DWORD()
    timeout = wintypes.DWORD()
    errorcode = wintypes.DWORD()
    result = lib.VCS_GetProtocolStackSettings(KeyHandle,ctypes.byref(baudrate),ctypes.byref(timeout),ctypes.byref(errorcode))
    if not result:
        raise RuntimeError('error code = {}'.format(errorcode.value))
    return baudrate.value,timeout.value

rawDescription: pulling return parameters using ctypes

description: Pulling return parameters using ctypes


code:
ax = pylab.gca()
ax.yaxis.set_visible(False)
pylab.show()

rawDescription: How do I remove the y-axis from a Pylab-generated picture?

description: Remove the y-axis from a Pylab-generated picture


code:
import urllib.request

words = []

url='https://www.cs.uoregon.edu/Classes/15F/cis122/data/sowpods_short.txt'

with urllib.request.urlopen(url) as webpage:
    for line in webpage:
        line = line.strip().decode('utf-8')
        if line[0] != "#":
            words += line.split(',')

print(words)

while True:
    question = input("type word or `q` to quit: ")

    if question == 'q':
        break

    if question in words:
        print("yes,", question, " was on the list")
    else:
        print("not on the list")

rawDescription: Converting a webpage into a list

description: Converting a webpage into a list


code:
from django import forms

class NewProjAccount(forms.Form):
    #form attributes

    def clean(self):
        cleaned_data = super(NewProjAccount, self).clean()
        perforce_depot = cleaned_data.get("perforce_depot")
        perforce_depot_size = cleaned_data.get("perforce_depot_size")

        if perforce_depot and not perforce_depot_size:
            raise forms.ValidationError("perforce_depot_size needs to be set to true.")

        # Always return the full collection of cleaned data.
        return cleaned_data

rawDescription: validate field if another field is set in django form

description: Validate field if another field is set in django form


code:
import os
from PIL import Image

dirPath = r"D:\Fraps\Movies\Screens"
dirList = os.listdir(dirPath)
outPath = r"D:\Fraps\Movies\Screens\Output"

for (dirname, dirs, files) in os.walk(dirPath):
   for filename in files:
       if filename.endswith('.png'):
            print("Opening:"+filename)
            thefile = os.path.join(dirname,filename)
            im = Image.open(thefile)
            #im.load()

            width, height = im.size

            im_rgb = im.convert('RGB')

            for x in range(0, width):
                for y in range(0,height):
                    r, g, b = im_rgb.getpixel((x, y))
                    im_rgb.putpixel((x, y), (b, g, r))

            print("Saving:"+filename)
            #outfile, ext = os.path.splitext(infile)
            outfile = os.path.join(outPath,filename)
            im_rgb.save(outfile, "PNG")

print("Ding!")

rawDescription: Swap R and B color channel values in a directory of images? Python


code:
a = collections.defaultdict(None, {'Devicename1': {'OS': 'version', 'Name': 'name'}, 'Devicename2': {'OS': 'version', 'Name': 'name'}})
HEADER = '''

Summary

        Device: {0}

         Name: {1}
         OS: {2}

'''
for key,d in a.items():
    print(HEADER.format(key, d['Name'], d['OS']))

rawDescription: String formating with nested dictionary

description: String formating with nested dictionary


code:
nxn = np.arange(n**2).reshape(n, -1)
for i in xrange(0, 2**(n**2)):
    arr = (i >> nxn) % 2
    # do smthng with arr

rawDescription: Iterate over matrices in numpy

description: Iterate over matrices in numpy


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

class Tree(QtGui.QTreeWidget):
    def __init__(self, *args, **kwargs):
        super(Tree, self).__init__()
        parentItem=QtGui.QTreeWidgetItem('P')
        self.addTopLevelItem(parentItem)
        childItem=QtGui.QTreeWidgetItem('C')
        parentItem.insertChild(0, childItem)
        self.expandToDepth(0)
        self.show()
tree=Tree()
sys.exit(app.exec_())

rawDescription: How to auto-expand QTreeWidget items

description: Auto-expand QTreeWidget items


code:
req = urllib2.Request("http://example.com", data, {'Content-Type': 'application/octet-stream'})
urllib2.urlopen(req)

rawDescription: How to send binary post data via HTTP?

description: Send binary post data via HTTP


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Add localhost alias, `proxy` , in /etc/hosts.
'''

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

def cors():
  if cherrypy.request.method == 'OPTIONS':
    # preflign request
    # see http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
    cherrypy.response.headers['Access-Control-Allow-Methods'] = 'POST'
    cherrypy.response.headers['Access-Control-Allow-Headers'] = 'content-type'
    cherrypy.response.headers['Access-Control-Allow-Origin']  = '*'
    # tell CherryPy no avoid normal handler
    return True
  else:
    cherrypy.response.headers['Access-Control-Allow-Origin'] = '*'

cherrypy.tools.cors = cherrypy._cptools.HandlerTool(cors)

class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>
      <html>
      <head>
      <meta content='text/html; charset=utf-8' http-equiv='content-type'>
      <title>CORS AJAX JSON request</title>
      <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
      <script type='text/javascript'>
        $(document).ready(function()
        {
          $('button').on('click', function()
          {
            $.ajax({
              'type'        : 'POST',
              'dataType'    : 'JSON',
              'contentType' : 'application/json',
              'url'         : 'http://proxy:8080/endpoint',
              'data'        : JSON.stringify({'foo': 'bar'}),
              'success'     : function(response)
              {
                console.log(response);
              }
            });
          })
        });
      </script>
      </head>
      <body>
        <button>make request</button>
      </body>
      </html>
    '''

  @cherrypy.expose
  @cherrypy.config(**{'tools.cors.on': True})
  @cherrypy.tools.json_in()
  @cherrypy.tools.json_out()
  def endpoint(self):
    data = cherrypy.request.json
    return data.items()

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: 415 exception Cherrypy webservice

description: 415 exception Cherrypy webservice


code:
while true:
   if i >= len(myString): # Exit condition
      break

   # do something with myString[i]

   # set i as you want

rawDescription: Python: Progress the index for a for loop


code:
raw = open(filename).read()
docs = []
for raw_doc in raw.split('---'):
    try:
        docs.append(yaml.load(raw_doc))
    except SyntaxError:
        docs.append(raw_doc)

rawDescription: Loading document as raw string in yaml with PyYAML


rawDescription: Find repeated characters (standing apart)


code:
import itertools as it
keys = sorted(objs.keys(), key=lambda k: objs[k]) # Make sure `objs` with the same value be arranged next to each other
groups = it.groupby(keys, lambda k: d[k]) # so that we can group them by value
match_list = [list(keys) for v, keys in groups]

rawDescription: python: find matching values in nested dictionary

description: Python: find matching values in nested dictionary


code:
import nose
from nose.plugins.base import Plugin

class ExtensionPlugin(Plugin):

    name = "ExtensionPlugin"

    def options(self, parser, env):
        Plugin.options(self,parser,env)

    def configure(self, options, config):
        Plugin.configure(self, options, config)
        self.enabled = True

    def wantFile(self, file):
        return file.endswith('.py')

    def wantDirectory(self,directory):
        return True

    def wantModule(self,file):
        return True

if __name__ == '__main__':
    includeDirs = ["-w", ".", ".."]
    nose.main(addplugins=[ExtensionPlugin()], argv=sys.argv.extend(includeDirs))

rawDescription: How to make py.test or nose to look for tests inside all python files?

description: Make py.test or nose to look for tests inside all python files


code:
from time import mktime
from datetime import datetime

dt = datetime.fromtimestamp(mktime(struct))

rawDescription: How do you convert a Python time.struct_time object into a datetime object?

description: Convert a Python time.struct_time object into a datetime object


code:
s = 'B-F'
list(map(chr, range(ord(s[0]), ord(s[-1]) + 1)))

rawDescription: Expand alphabetical range to list of characters in Python


code:
import csv

filereader = csv.reader(open("tests.csv", "r"), delimiter=",")
filewriter = csv.writer(open("test_step1.csv", "wb"), delimiter=",", newline="")
#Delete header
for row in filereader:
    if row[0].isdigit():
        filewriter.writerow(row)

rawDescription: Empty space in between rows after using writer in python


rawDescription: Audio signal processing using Python

description: Audio signal processing using Python


rawDescription: How do I map my data from a list into tuple?

description: Map my data from a list into tuple


code:
import json

import re
from urllib import quote_plus

import scrapy

class UdacityItem(scrapy.Item):
    name = scrapy.Field()
    users = scrapy.Field()

class DmozSpider(scrapy.Spider):
    name = "UdSpider"
    allowed_domains = ["udacity.com"]
    start_urls = ["https://www.udacity.com/courses/all"]

    def parse(self, response):
        sites = response.xpath('//h3/a')
        for s in sites:
            t = UdacityItem()
            # name & url
            t['name'] = s.xpath('text()').extract()[0].strip()
            url = response.urljoin(s.xpath('@href').extract()[0])
            # request
            req = scrapy.Request(url, callback=self.second)
            req.meta['item'] = t
            # execute
            yield req

    def second(self, response):
        queries = [{
            "limit": 1,
            "model": "CourseStudentsSummary",
            "locator": {
                "sample_frequency": "daily",
                "content_context": [{
                    "node_key": re.search(r'--(.*?)$', response.url).group(1)
                }]
            }
        }]
        yield scrapy.Request(method="GET",
                             url="https://www.udacity.com/api/summaries?queries=" + quote_plus(json.dumps(queries)),
                             callback=self.parse_totals)

    def parse_totals(self, response):
        print(json.loads(response.body[5:].strip())["summaries"]["default"][0]["data"]["total_enrollments"])

rawDescription: Scraping interactive website

description: Scraping interactive website


code:
def percentage(list_of_lists, substring):
    percentage = []
    for item in list_of_lists:
        count = 0.0
        for i in item:
            if substring == i[0:3]:
                count += 1
        percentage.append(int(count / len(item) * 100))
    return percentage

# Test
In [17]: l = [['aaa111', 'aba123', 'aaa123'], ['aaa302', 'cad222']]
In [18]: s = 'aaa'
In [19]: percentage(l,s)
Out[19]: [66, 50]

rawDescription: Python - occurrence of substring in a list of lists


code:
url(r'^test/(\d+)/$', 'test_view', name='test-view'),
url(r'^test/$', 'test_view', name='test-view'),

rawDescription: Django using url to get only the url part of a named view with parameters


code:
class UserUpload(models.Model):
    file = models.FileField(...)
    description = models.CharField(...)
    user = models.ForeignKey(User)

rawDescription: I want a Django user to upload an arbitrary number of files


code:
def breadcrumb(self):
    breadcrumb = self.name
    def get_next_parent(obj=None):
        if obj is None:
            return None
        if obj.parent:
            return obj.parent
        return None
    obj = self
    while get_next_parent(obj=obj):
        obj = get_next_parent(obj=obj)
        breadcrumb = '%s > %s' % (obj.name, breadcrumb)
    return breadcrumb

rawDescription: select_related() on self for breadcrumb

description: Select_related() on self for breadcrumb


rawDescription: Convert pandas.Series from dtype object to float, and errors to nans


code:
import codecs

with codecs.open(file, "r", "utf-8-sig") as f:
    a, b, c= map(int, f.readline().split(","))

rawDescription: Dealing with UTF-8 numbers in Python

description: Dealing with UTF-8 numbers in Python


code:
import pandas as pd
import io
content = '''\
<<PASTE DATA HERE>>
'''

df = pd.read_table(io.BytesIO(content), ...)

rawDescription: How to embed data in an IPython Notebook?

description: Embed data in an IPython Notebook


code:
def foo():
    somedict = {}
    somedict['bar'] = 'spam'

import dis
dis.dis(foo)

rawDescription: Python dictionary needs synchronization?

description: Python dictionary needs synchronization


code:
a = 5
globals()['a']

rawDescription: How to get the value of a variable given its name in a string?

description: Get the value of a variable given its name in a string


code:
class Something( object ):
    def __init__( self ):
        self.a= 2
        self.b= 3

x= Something()
getattr( x, 'a' )
getattr( x, 'b' )

rawDescription: Python's equivalent of $this->$varName

description: Python's equivalent of $this->$varName


rawDescription: Number of matches in regex substitution

description: Number of matches in regex substitution


rawDescription: Get derivative of data in python

description: Get derivative of data in python


code:
"""
open another terminal and run
nc -l 8080
type something in the both terminals>
"""
import sys
from socket import socket, AF_INET, SOCK_STREAM
from select import select

host = 'localhost'
port = 8080

sock = socket(AF_INET, SOCK_STREAM)
sock.connect((host, port))
reader = sock.makefile('r', 0)
writer = sock.makefile('w', 0)
while True:
    ins, _, _ = select([reader, sys.stdin],[],[])
    for i in ins:
        if i == reader:
            sys.stdout.write(i.read(1))
        if i == sys.stdin:
            writer.write(sys.stdin.read(1))

rawDescription: Connect two sockets together without writing byte-manipulating plumbing code?


code:
from fabric import env
env.hosts = ['user1@host1:port1', 'user2@host2.port2']
env.passwords = {'user1@host1:port1': 'password1', 'user2@host2.port2': 'password2'}

rawDescription: Python Fabric Laibrary ssh connection

description: Python Fabric Laibrary ssh connection


code:
sentence = "Abraham Lincoln Hotel is very beautiful place and i want to go there with Barbara Palvin. Also there are stores like Adidas, Nike, Reebok."
all_words = sentence.split()
last_word_index = -100
proper_nouns = []
for idx, word in enumerate(all_words):
    if(word.istitle() and word.isalpha()):
        if(last_word_index == idx-1):
            proper_nouns[-1] = proper_nouns[-1] + " " + word
        else:
            proper_nouns.append(word)
        last_word_index = idx
print(proper_nouns)

rawDescription: Python - Group Sequential Array Members

description: Python - Group Sequential Array Members


code:
NS_MAP = {"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
        "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
        "art": "http://simile.mit.edu/2003/10/ontologies/artstor#",
        "foaf": "http://xmlns.com/foaf/0.1/",
        "dcterms": "http://purl.org/dc/terms/",
        "sioc": "http://rdfs.org/sioc/ns#",
         "oa": "http://www.openannotation.org/ns/"}
#short hands the ns
RDF = "{%s}" % NS_MAP['rdf']
RDFS = "{%s}" % NS_MAP['rdfs']
ART = "{%s}" % NS_MAP['art']
FOAF = "{%s}" % NS_MAP['foaf']
DCTERMS = "{%s}" % NS_MAP['dcterms']
SIOC = "{%s}" % NS_MAP['sioc']
OA = "{%s}" % NS_MAP['oa']

rawDescription: Python XML parsing and default NS

description: Python XML parsing and default NS


code:
sql = f.read() # watch out for built-in `str`
cur.executescript(sql)

rawDescription: Python and sqlite3 - importing and exporting databases


code:
# Create the number of tasks we need to perform
for i in range(5):
    # Define the task as executing the function myfunction with a random execution time
    task_time = random.randint(1, 9)
    task = threading.Thread(target=myfunction, args=(i, task_time))
    #task.daemon = True
    # append each task to the task list
    task_list.append(task)

    # start the task
    task.start()

# All tasks are now started, we can wait for each to finish without
# causing sequential execution
for task in task_list:
    task.join()

rawDescription: Python threading: Running task concurrently inside sequential sections


rawDescription: Import modules after compilation with py2exe


code:
def run():
   select_funct = random.choice(functs)
   select_funct()

rawDescription: Some issue with random.choice and variables?


code:
import codecs
codecs.decode(b"asdf", "base64_codec")
codecs.encode(b"asdf", "base64_codec")

rawDescription: Python 3: How do I use bytes-to-bytes and string-to-string encodings


code:
import pygame

WHITE = (255,255,255)

class init_window(object):

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.gameDisplay = pygame.display.set_mode((self.width, self.height))
        pygame.display.set_caption('Snake')

    def draw_snake(self, startx, starty, width, height):

        pygame.draw.rect(self.gameDisplay, WHITE, [startx, starty, width, height])
        pygame.display.update()
        init_window.move_snake(self, startx, starty, (width, height))

    def move_snake(self, x, y, rectsize):

        FPS = 60
        clock = pygame.time.Clock()
        rectheight, rectwidth = rectsize

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    quit()

                if event.type == pygame.KEYDOWN:

                    x_change = 0
                    y_change = 0

                    if event.key == pygame.K_LEFT:
                        x_change = -5
                    if event.key == pygame.K_RIGHT:
                        x_change = 5
                    if event.key == pygame.K_UP:
                        y_change = -5
                    if event.key == pygame.K_DOWN:
                        y_change = 5

                    x += x_change
                    y += y_change

                    self.gameDisplay.fill((0,0,0))

                    pygame.draw.rect(self.gameDisplay, WHITE, [x, y, rectheight, rectwidth])
                    pygame.display.update()

                    clock.tick(FPS)

if __name__ == '__main__':

    width, height = 800, 600
    pygame.init()

    window = init_window(width, height)
    window.draw_snake(width//2, height//2, 50,50)

rawDescription: pygame OOP moving a rectangle

description: Pygame OOP moving a rectangle


code:
import pexpect
child = pexpect.spawn('myprocess')
child.expect('>')
child.sendline(password_var)
child.expect('>')
child.sendline(password_var)

rawDescription: Execute linux command which requires additional input using Python


rawDescription: Variable expansion in subprocess.Popen

description: Variable expansion in subprocess.Popen


code:
import Image
import ImageDraw

im = Image.new('RGB',(500,500),(255,255,255))
draw = ImageDraw.Draw(im)
draw.line(points, fill=(255,0,0))
del draw
im.save('output.jpg')

rawDescription: Interpolation and image drawing

description: Interpolation and image drawing


code:
tag_list = request.GET.get('q').split(',')

# Generate a query with all species
all_species = Species.objects.all()
# Generate a list with the separately filtered species
filtered_species = [all_species.filter(tags__description=c) for c in tag_list]
# Join the filtered species together using the same method :)
species = reduce(and_, filtered_species, all_species)

rawDescription: Django Filter deduce ManyToMany

description: Django Filter deduce ManyToMany


code:
#!/usr/bin/env python

def main():
    with open('50gb_file', 'rb') as file, open('output', 'wb') as output_file:
        for line in file:
            number, sep, rest = line.partition(b',')
            try:
                number = int(number)*2 #XXX replace number here
            except ValueError:
                pass # don't replace the number
            else:
                line = bytes(number) + sep + rest
            output_file.write(line)

main()

rawDescription: Replace value from CSV with Python

description: Replace value from CSV with Python


code:
seen = {}   # Key prefixes already processed
while True:
    k0 = None  # Current prefix
    for L in all_the_data:
        k = L[0][:2]
        if k not in seen:
            if k0 is None:
                k0 = k
            if k0 == k:
                store_into_database(L)
    if k0 is None:
        break
    seen.append(k0)

rawDescription: What's the best way to insert over a hundred million rows into a SQLite database?


code:
from tkinter import *
def createbutton():
    global secondbut
    secondbut.append(Button(root,text="button"))
    secondbut[-1].pack()
def eliminatebutton():
    secondbut[-1].destroy()
    secondbut.pop()
if __name__=='__main__':
    root=Tk()
    global create
    global delete
    global secondbut
    secondbut = []
    create= Button(root,text="create",command=createbutton)
    delete=Button(root,text="delete",command=eliminatebutton)
    create.pack()
    delete.pack()
    root.mainloop()

rawDescription: Create-Delete Buttons

description: Create-Delete Buttons


code: assert (callable(dist_fun))

rawDescription: Asserting something is a valid function in Python


code:
import sys
import re
import math
from scipy.integrate import dblquad
def f(x,y,*args):
  V=0
  for v in args:
    a,b=v
    V=V+a*x+b*y
  return (V)

def integral(x_max, y_max, variables):
  return dblquad(f, 0, y_max, lambda x: 0, lambda x: x_max, args=variables)

def main():
  variables=((1,2),(3,4),(5,6)) #example variables. The length of this list can change with the code I am running.
  x_max=y_max=1
  integral(x_max,y_max,variables)

if __name__ == '__main__':
  main()

rawDescription: Numerical double integration of a function in python with a list of fixed variables


rawDescription: How to send emoji with Twitter Python lib

description: Send emoji with Twitter Python lib


code:
import wx

class SketchFrame(wx.Frame):
    def __init__(self, parent):

        wx.Frame.__init__(self, parent, -1, "Sketch Frame",size=(350,350))
        self.sketch = SketchWindow(self, -1)

class SketchWindow(wx.Window):

    def __init__ (self, parent,ID):

        wx.Window.__init__(self, parent, ID)
        self.Buffer = None

        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBack)

    def InitBuffer(self):
        size=self.GetClientSize()
        # if buffer exists and size hasn't changed do nothing
        if self.Buffer is not None and self.Buffer.GetWidth() == size.width and self.Buffer.GetHeight() == size.height:
            return False

        self.Buffer=wx.EmptyBitmap(size.width,size.height)
        dc=wx.MemoryDC()
        dc.SelectObject(self.Buffer)
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        dc.Clear()
        self.Drawcircle(dc)
        dc.SelectObject(wx.NullBitmap)
        return True

    def Drawcircle(self,dc):
        size=self.GetClientSize()
        pen=wx.Pen('blue',4)
        dc.SetPen(pen)
        dc.DrawCircle(size.width/2,size.height/2,50)

    def OnEraseBack(self, event):
        pass # do nothing to avoid flicker

    def OnPaint(self, event):
        if self.InitBuffer():
            self.Refresh() # buffer changed paint in next event, this paint event may be old
            return

        dc = wx.PaintDC(self)
        dc.DrawBitmap(self.Buffer, 0, 0)
        self.Drawcircle(dc)

if __name__=='__main__':
    app=wx.PySimpleApp()
    frame=SketchFrame(None)
    frame.Show(True)
    app.MainLoop()

rawDescription: Drawing a circle using wxpython

description: Drawing a circle using wxpython


code:
import pickle

# Saving
data = [1,2,3,4]
pickle.dump(data, open("d:/temp/test.pkl","wb"))

# Loading
load = pickle.load(open("d:/temp/test.pkl","rb"))

rawDescription: What is the best way to store data in Python?


code:
# First make sure we stay in the grid
i1, i2 = max(i-num_dx, 0), min(i+num_dx+1, num_x)
j1, j2 = max(j-num_dy, 0), min(j+num_dy+1, num_y)

# Get the radius in blocks, grid should be homogeneous
radius_i = radius_m / 13000.0

# Calc distances per element by broadcasting
DX = np.arange(i1, i2) - i
DY = np.arange(j1, j2)[:, None] - j
mask = DX*DX + DY*DY <= radius_i*radius_i

# Get block of interest and apply mask
values = myarray[i1:i2, j1:j2][mask]

rawDescription: Fastest way to determine average of gridded values within a given radius of a point


code:
import re
files = ['slide1.xml', 'slide10.xml', 'slide11.xml', 'slide12.xml', 'slide13.xml', 'slide2.xml', 'slide3.xml', 'slide3_COPY.xml', 'slide4.xml', 'slide5.xml', 'slide6.xml', 'slide7.xml', 'slide8.xml', 'slide9.xml']
ordered_files = sorted(files, key=lambda x: (int(re.sub('\D','',x)),x))

rawDescription: Ordered os.listdir() in python

description: Ordered os.listdir() in python


code:
fp = webdriver.FirefoxProfile()
fp.set_preference("browser.download.folderList",2)
fp.set_preference("browser.download.manager.showWhenStarting",False)
fp.set_preference("browser.download.dir","/my/directory")
fp.set_preference("browser.helperApps.neverAsk.saveToDisk","application/forced-download")
self.driver = webdriver.Firefox(firefox_profile=fp)

rawDescription: In selenium python webdriver, I'm not able to download a text file with a .lst extension


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

delta = 0.025

x = y = np.arange(0, 3.01, delta)
X, Y = np.meshgrid(x, y)
Z1 = plt.mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = plt.mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = 10e1 * (Z1*Z2)    # Random function creation
levels = np.array([0,0.2,0.4,0.6,0.8,1,2,3])

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

CF = ax1.contourf(X,Y,Z,
         levels = levels,
         cmap = plt.cm.spectral
        )
CS = ax1.contour(X,Y,Z,
         colors = 'k',    # Black border
         levels = levels
        )

cbar = plt.colorbar(CF, ticks=levels, format='%.2f')
plt.show()

rawDescription: Problems with colorbar range matplotlib python


code:
if settings.DEBUG:
    from django.contrib.staticfiles.urls import staticfiles_urlpatterns
    from django.conf.urls.static import static

    urlpatterns += staticfiles_urlpatterns()
    urlpatterns += static(
        settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rawDescription: Download from MEDIA_ROOT does not work

description: Download from MEDIA_ROOT does not work


code: re.split(r',\t', line)

rawDescription: Splitting a line with different separators in python


code:
from sqlalchemy.orm.session import object_session
# ...

def set_other_object_value(self, value):
    if self.other_object is None:
        value = OtherObject(...)
    self.other_object.value = value
    object_session(self).add(value)

rawDescription: SqlAlchemy: Refer to the bound session from an object?


rawDescription: Find multiple values in a Numpy array

description: Find multiple values in a Numpy array


rawDescription: Python finding patterns within large group of numbers?


code:
s = "< stuff to remove> get this stuff <stuff to remove>"
import re
re.sub(r'<[^<>]*>', '', s)

rawDescription: removing string based on start index and end index

description: Removing string based on start index and end index


code:
import argparse

def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength

parser=argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', nargs='+', action=required_length(2,3))

args=parser.parse_args('-f 1 2 3'.split())
print(args.f)
# ['1', '2', '3']

try:
    args=parser.parse_args('-f 1 2 3 4'.split())
    print(args)
except argparse.ArgumentTypeError as err:
    print(err)
# argument "f" requires between 2 and 3 arguments

rawDescription: Python argparse: Is there a way to specify a range in nargs?


code:
global_var

def on_message(client, userdata, msg):
  global global_var
  print(msg.topic+" "+str(msg.payload))
  global_var = msg.payload

rawDescription: How to use msg.payload globally for MQTT Python client?

description: Use msg.payload globally for MQTT Python client


code:
df
df["weight"].mean()

rawDescription: pandas get column average

description: Pandas get column average


code:
from itertools import product
[np.insert(j,0,i) for i,j in product(a,np.array((b,c)).T)]

rawDescription: Zip uneven numpy arrays

description: Zip uneven numpy arrays


code:
import csv
with open("/tmp/database.txt", 'r') as file:
  reader = csv.reader(file)
  third_where_pineapple = [line[2] for line in reader if line[0] == 'pineapple']
  print (third_where_pineapple)

rawDescription: python csv find text in file and then find a specific column

description: Python csv find text in file and then find a specific column


code:
import importlib

list_of_module_names = ...
for s in list_of_module_names:
    importlib.import_module(s)

rawDescription: Import Numerous Modules

description: Import Numerous Modules


code: np.vstack((b, np.transpose(a[:,2])))

rawDescription: How to add a row into a 1-D array with python-numpy?

description: Add a row into a 1-D array with python-numpy


code:
cj = cookielib.MozillaCookieJar(cookie_filename)
if os.access(cookie_filename, os.F_OK):
    cj.load()
proxy_handler = urllib2.ProxyHandler({'https': 'localhost:8008'})
opener = urllib2.build_opener(
        proxy_handler,
        urllib2.HTTPCookieProcessor(cj)
    )
opener.addheaders = [
        ('User-agent', ('Mozilla/4.0 (compatible; MSIE 6.0; '
                       'Windows NT 5.2; .NET CLR 1.1.4322)'))
    ]
auth = urllib.urlencode({'email':email,'pass':passw})
data = opener.open('https://login.facebook.com/login.php',data=auth)

rawDescription: urllib2 doesn't use proxy (Fiddler2), set using ProxyHandler

description: Urllib2 doesn't use proxy (Fiddler2), set using ProxyHandler


code:
import ntpath
ntpath.split("c:\windows\i\love\you.txt")
ntpath.splitext("c:\windows\i\love\you.txt")
ntpath.basename("c:\windows\i\love\you.txt")

rawDescription: Python - Make Script to Manipulate Windows File Paths but running on Linux


code:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect, render

@login_required
def contactUs(request):
    form = CustomizeRequestForm(data=request.POST or None)

    if request.method == "POST":
        if form.is_valid():
             customize_request = form.save(commit=False)
             customize_request.user = request.user
             customize_request.save()
             return redirect('.')
        else:
             pass # could add a notification here

    context_dict = {'form': form}
    return render(request, 'tour/contactUs.html', context_dict)

rawDescription: How to save a data after user logs in DJANGO

description: Save a data after user logs in DJANGO


code:
from plubum.cmd import openssl

with open('file') as f:
    for ip_code in f:
        (openssl['whatever', 'params'] << ip_code)()

rawDescription: Using subprocess with openssl in a python script


code:
import sys
sys.stdout = sys.stderr

rawDescription: In python, can I redirect the output of print function to stderr?


code:
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
import os

os.environ["CC"]= "/usr/local/Cellar/gcc/5.2.0/bin/g++-5"
os.environ["CXX"]= "/usr/local/Cellar/gcc/5.2.0/bin/g++-5"
os.environ["MACOSX_DEPLOYMENT_TARGET"]= "10.10"
os.environ["ARCHFLAGS"]= "-arch x86_64"
os.environ["CFLAGS"]= (
    '-I/Users/Thomas/Documents/workspace/Quantum/Symengine '
    '-I/Users/Thomas/Documents/workspace/Quantum/Symengine/symengine '
    '-I/Users/Thomas/Documents/workspace/Quantum/Symengine/symengine/teuchos '
    '-I/Users/Thomas/Documents/workspace/Quantum/SymCell '
    '-I/Users/Thomas/googletest/googletest/include '
    '-I/Users/Thomas/Documents/workspace/Quantum/QuantumCell '
    '\"-I/Users/Thomas/Documents/workspace/Quantum/Quantum CPP\" '
)

extensions = [
    Extension("constellation",
        sources=["constellation.pyx"],
        language="c++",
        extra_compile_args=["-std=c++1y","-fopenmp"],
        extra_link_args=["-fopenmp"])]

setup(
    name = "constellation",
    ext_modules = cythonize(extensions)
)

rawDescription: Cython with g++-5 on OSX

description: Cython with g++-5 on OSX


code:
print("UDP target IP:", UDP_IP)
print("UDP target port:", UDP_PORT)
print("message:", MESSAGE)

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP
sock.sendto(bytes(MESSAGE, "utf-8"), (UDP_IP, UDP_PORT))

rawDescription: Python send UDP packet

description: Python send UDP packet


code: call(["depends"] + DEP)

rawDescription: How to convert Python lists into a shell-readable series of strings?

description: Convert Python lists into a shell-readable series of strings


code: os.system("""here some code you use to execute in Terminal""")

rawDescription: Running a bash file with Python

description: Running a bash file with Python


code:
for q in query:
   OutputFile.write(q[0])

rawDescription: Python 2.7 and MySQL: grooming tuple

description: Python 2.7 and MySQL: grooming tuple


code:
def _partial_move_for(self, cr, uid, move):
    partial_move = {
        'product_id' : move.product_id.id,

        # Add product description
        'product_description' : move.name,

        'quantity' : move.product_qty if move.state in ('assigned','draft','confirmed') else 0,
        'product_uom' : move.product_uom.id,
        'prodlot_id' : move.prodlot_id.id,
        'move_id' : move.id,
        'location_id' : move.location_id.id,
        'location_dest_id' : move.location_dest_id.id,
    }
    return partial_move

# Add the product description to the wizard.
# The values get filled in from stock_partial_picking._partial_move_for
class stock_partial_picking_line(osv.TransientModel):
    _inherit = "stock.partial.picking.line"

    _columns = {
        'product_description': fields.char('Description'),
    }

rawDescription: Function field not getting called from within wizard


code:
def times_table(times,factor):
    """takes two positive integers and returns a list of lists

    int, int -> list of lists"""
    table = [[0]*(factor+1)]
    for i in range(1,times+1):
        table.append(list(range(0,i*factor+1,i)))
    return table

def print_table(listx):
    """takes a list of lists of numbers and displays them on the screen

    list of numbers -> numbers"""
    for x in listx:
        for y in x:
            print('{0:<10}'.format(y), end='')
        print()

number1 = int(input("What is the maximum value for the first factor?"))
number2 = int(input("What is the maximun value for the second factor?"))
print("Here is your times table:")
table = times_table(number1, number2)
print_table(table)

rawDescription: Scripts using functions already defined

description: Scripts using functions already defined


code:
from tkinter import *
class Application(Frame, object):
    def __init__(self,  master):
        super(Application, self).\
            __init__(master)
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        self.t1=Text(self,width=10,height=2)
        self.t1.grid(row=1,column=1)
        self.b1=Button(self,text="create",command=self.onClick)
        self.b1.grid(row=2,column=1)

    def onClick(self):
        self.top = Toplevel()
        self.top.title("title")
        self.top.geometry("300x150+30+30")
        self.top.transient(self)
        self.appc=Demo(self.top, self.t1)

class Demo(object):
    def __init__(self, master, t1):
        self.master = master
        self.frame = Frame(self.master)
        self.t1 = t1
        self.widget()

    def widget(self):
        self.e1=Entry(self.master)
        self.e1.grid(row=1,column=1)
        self.b1=Button(self.master,text="submit",command=self.onSubmit)
        self.b1.grid(row=2,column=1)

    def onSubmit(self):
        self.t1.insert(INSERT, self.e1.get())

root=Tk()
app=Application(root)
app.mainloop()

rawDescription: How to display a value from children window to parent window in python tkinter?

description: Display a value from children window to parent window in python tkinter


code:
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from PyQt4 import QtCore, QtGui

class widgetB(QtGui.QWidget):
    procDone = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(widgetB, self).__init__(parent)

        self.lineEdit = QtGui.QLineEdit(self)
        self.button = QtGui.QPushButton("Send Message to A", self)
        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.lineEdit)
        self.layout.addWidget(self.button)

        self.button.clicked.connect(self.on_button_clicked)

    @QtCore.pyqtSlot()
    def on_button_clicked(self):
        self.procDone.emit(self.lineEdit.text())

    @QtCore.pyqtSlot(str)
    def on_procStart(self, message):
        self.lineEdit.setText("From A: " + message)

        self.raise_()

class widgetA(QtGui.QWidget):
    procStart = QtCore.pyqtSignal(str)

    def __init__(self, parent=None):
        super(widgetA, self).__init__(parent)

        self.lineEdit = QtGui.QLineEdit(self)
        self.lineEdit.setText("Hello!")

        self.button = QtGui.QPushButton("Send Message to B", self)
        self.button.clicked.connect(self.on_button_clicked)

        self.layout = QtGui.QHBoxLayout(self)
        self.layout.addWidget(self.lineEdit)
        self.layout.addWidget(self.button)

    @QtCore.pyqtSlot()
    def on_button_clicked(self):
        self.procStart.emit(self.lineEdit.text())

    @QtCore.pyqtSlot(str)
    def on_widgetB_procDone(self, message):
        self.lineEdit.setText("From B: " + message)

        self.raise_()

class mainwindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(mainwindow, self).__init__(parent)

        self.button = QtGui.QPushButton("Click Me", self)
        self.button.clicked.connect(self.on_button_clicked)

        self.setCentralWidget(self.button)

        self.widgetA = widgetA()
        self.widgetB = widgetB()

        self.widgetA.procStart.connect(self.widgetB.on_procStart)
        self.widgetB.procDone.connect(self.widgetA.on_widgetB_procDone)

    @QtCore.pyqtSlot()
    def on_button_clicked(self):
        self.widgetA.show()
        self.widgetB.show()

        self.widgetA.raise_()

if __name__ == "__main__":
    import sys

    app  = QtGui.QApplication(sys.argv)
    main = mainwindow()
    main.show()
    sys.exit(app.exec_())

rawDescription: Sending messages between two widgets using Signals and Slots


code:
foundYear = False

for currentLine, line in enumerate(file):
    if foundYear:
        if line.strip() == "1":
            print("Gold!")
            goldMedals += 1

        else:
            print("Not gold!")

        foundYear = False

    elif line.strip() == year:
        print("Correct year!")
        foundYear = True

    else:
        print("Incorrect year!")

rawDescription: Why is my if statement in Python evaluating to False?


code:
import xlwt

dic = contar_Repetidas("Some Text Here")

wb = xlwt.Workbook()
ws = wb.add_sheet("Your Sheet")

count = 0
for word, num in dic.items():
    count += 1
    ws.write(count, 1, word)
    ws.write(count, 2, num)

wb.save("/Path/To/Save/Example.xls")

rawDescription: Create a xls file from a dict python

description: Create a xls file from a dict python


code:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(2013)
N = 10
x, y = np.random.random((2,N,2))
x.cumsum(axis=0, out=x)
y.cumsum(axis=0, out=y)
fig, ax = plt.subplots()
colors = ['red', 'black']
ax.set_color_cycle(colors)
ax.plot(x,y)
plt.show()

rawDescription: Python Matplotlib: plot with 2-dimensional arguments : how to specify options?


code:
#!/usr/bin/env python3
import sys

def readfile(path):
    with open(path, 'rb') as f:
        return f.read()

contents = [readfile(fname) for fname in sys.argv[1:]]
sys.exit(all(content == contents[0] for content in contents[1:]))

rawDescription: Find files with same name but different content


code: myText = nltk.Text(...)

rawDescription: Using NLTK, how to get a dispersion plot of a list?


code:
d = {}
for path,dirs,fnames in os.walk(top):
    for fname in fnames:
        visit = os.path.join(path,fname)
        with open(visit) as f:
             d[visit] = f.read()

rawDescription: How can I get the file names and contents of a whole directory?

description: Get the file names and contents of a whole directory


code:
import unittest

class linked_list:

    front = rear = None
    current = None #used in iterator

    class node:

        __slots__ = ['value', 'next']

        def __init__(self, value, next):
            self.value = value
            self.next = next

    def empty(self):
        return not self.front

    def push_front(self, value):
        x = self.node(value, self.front)
        self.front = x
        if not self.rear:
            self.rear = x

    def push_back(self, value):
        if self.empty():
            self.front = self.rear = self.node(value, None)
        else:
            x = self.node(value, None)
            self.rear.next = x
            self.rear = x

    def pop_front(self):
        if self.empty():
            raise RuntimeError("Empty List")
        x = self.front.value
        self.front = self.front.next
        if not self.front:
            self.rear = None
        return x

    def pop_back(self):
        if self.empty():
            raise RuntimeError("Empty List")
        y = self.rear.value
        if not self.front.next:
            self.front = self.rear = None
        else:
            x = self.front
            while x.next is not self.rear:
                x = x.next
            x.next = None
            self.rear = x
        return y

class test_linked_list (unittest.TestCase):
    def test_none(self):
        self.assertTrue(linked_list().empty())
    def test_pop_front_empty(self):
        self.assertRaises(RuntimeError, lambda: linked_list().pop_front())
    def test_pop_back_empty(self):
        self.assertRaises(RuntimeError, lambda: linked_list().pop_back())
    def test_push_back_pop_front(self):
        ll = linked_list()
        ll.push_back(1)
        ll.push_back(2)
        ll.push_back(3)
        self.assertFalse(ll.empty())
        self.assertEquals(ll.pop_front(), 1)
        self.assertEquals(ll.pop_front(), 2)
        self.assertEquals(ll.pop_front(), 3)
        self.assertTrue(ll.empty())
    def test_push_front_pop_front(self):
        ll = linked_list()
        ll.push_front(1)
        ll.push_front(2)
        ll.push_front(3)
        self.assertEquals(ll.pop_front(), 3)
        self.assertEquals(ll.pop_front(), 2)
        self.assertEquals(ll.pop_front(), 1)
        self.assertTrue(ll.empty())
    def test_push_front_pop_back(self):
        ll = linked_list()
        ll.push_front(1)
        ll.push_front(2)
        ll.push_front(3)
        self.assertFalse(ll.empty())
        self.assertEquals(ll.pop_back(), 1)
        self.assertEquals(ll.pop_back(), 2)
        self.assertEquals(ll.pop_back(), 3)
        self.assertTrue(ll.empty())
    def test_push_back_pop_back(self):
        ll = linked_list()
        ll.push_back(1)
        ll.push_back("foo")
        ll.push_back([3,2,1])
        self.assertFalse(ll.empty())
        self.assertEquals(ll.pop_back(),[3,2,1])
        self.assertEquals(ll.pop_back(), "foo")
        self.assertEquals(ll.pop_back(), 1)
        self.assertTrue(ll.empty())

if __name__ == '__main__':
    unittest.main()

rawDescription: Creating linked-list in python without using native lists


code:
class CheckableDirModel(QtGui.QFileSystemModel):
   def __init__(self, tView, parent=None):
    QtGui.QFileSystemModel.__init__(self, tView)
    self.tView = tView
    self.checks = {}
    backupstr = fileread(os.path.join(os.path.expanduser("~"), "Desktop"), "saved.txt", "utf-8")

    if backupstr:
        backuplist = backupstr.split('\n')
        for backupitem in backuplist:
            self.checks[backupitem] = QtCore.Qt.Checked

def setData(self, index, value, role):

    if (role == QtCore.Qt.CheckStateRole) and (index.column() == 0):
        self.tView.selectionchanged = True
        if value == QtCore.Qt.Checked:
            self.removesubfolders(index)
            self.checks[str(self.filePath(index))] = QtCore.Qt.Checked
        elif value == QtCore.Qt.Unchecked:
            self.removesubfolders(index)

def removesubfolders(self, index):
    checkedItems = []

    for otherindex, othervalue in self.checks.items():
        if othervalue == QtCore.Qt.Checked:
            checkedItems.append(otherindex)

    uncheckpath = str(self.filePath(index))
    indices = [removeindex for removeindex in checkedItems if self.eligibleIndex(removeindex, uncheckpath)]

    for idx in indices:

        localidx = self.index(idx)
        if str(self.filePath(localidx)) in self.checks:
           self.checks.pop(str(self.filePath(localidx)))

rawDescription: Getting the index in the tree view for the available path


rawDescription: Django templates: create a "back" link?

description: Django templates: create a "back" link


code:
import json
with open('log.txt') as file:
    lines = file.readlines()
try:
    json.loads(lines[-1])
except ValueError:
    with open('log.txt', 'w') as file:
        file.write(''.join(lines[:-1]))

rawDescription: Using Python to remove incomplete line from the end of a JSON formatted log file


code:
i = 0
while True:
    name = str(raw_input())
    # or a try-except statement depending on the kind of input
    if not name.strip():
        break
    if name in phonebook.keys():
        string = name +'='+ str(phonebook[name])
        print(string)
        i += 1
    else:
        print("Not found")
        i += 1

rawDescription: Setting a while loop in python to take unknown number of variables


rawDescription: Python buffer copy speed - why is array slower than string?


code:
def count(head, value):
    seen = 0
    while head is not None:
        if head.data == value:
            seen += 1
        head = head.next
    return seen

#...
print(count(head, "Dog"))

rawDescription: Counter for Specific Occurrences Within A Linked-List


code:
from twisted.internet.endpoints import TCP4ClientEndpoint
from txsocksx.client import SOCKS5ClientEndpoint

if __name__ == "__main__":
    chan = "django-hotclub"
    chain_length = 5

    myID = sys.argv[1]
    counterpartID = sys.argv[2]

    puttyEndPoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 22)
    ircEndpoint = SOCKS5ClientEndpoint('irc.freenode.net', 6667, puttyEndPoint)
    d = ircEndpoint.connect(MomBotFactory('#' + chan, myID, counterpartID, chain_length, chattiness=0.05))
    reactor.run()

rawDescription: How to cause twisted based irc client to connect through socks proxy?

description: Cause twisted based irc client to connect through socks proxy


code:
from flask import render_template, request, flash, session, url_for, redirect
from forms import ContactForm, SignupForm, SigninForm
from flask.ext.mail import Message, Mail
from models import db, User

from flask import Flask

app = Flask(__name__)

app.secret_key = 'development key'

app.config["MAIL_SERVER"] = "smtp.gmail.com"
app.config["MAIL_PORT"] = 465
app.config["MAIL_USE_SSL"] = True
app.config["MAIL_USERNAME"] = 'contact@example.com'
app.config["MAIL_PASSWORD"] = 'your-password'

mail = Mail()

mail.init_app(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://your-username:your-password@localhost/development'

from models import db
db.init_app(app)

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

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

@app.route('/contact', methods=['GET', 'POST'])
def contact():
    form = ContactForm()

    if request.method == 'POST':
        if form.validate() == False:
            flash('All fields are required.')
            return render_template('contact.html', form=form)
        else:
            msg = Message(form.subject.data, sender='contact@example.com', recipients=['your_email@example.com'])
            msg.body = """
            From: %s <%s>
            %s
            """ % (form.name.data, form.email.data, form.message.data)
            mail.send(msg)

            return render_template('contact.html', success=True)

    elif request.method == 'GET':
        return render_template('contact.html', form=form)

@app.route('/signup', methods=['GET', 'POST'])
def signup():
    form = SignupForm()

    if 'email' in session:
        return redirect(url_for('profile'))

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('signup.html', form=form)
        else:
            newuser = User(form.firstname.data, form.lastname.data, form.email.data, form.password.data)
            db.session.add(newuser)
            db.session.commit()

            session['email'] = newuser.email
            return redirect(url_for('profile'))

    elif request.method == 'GET':
        return render_template('signup.html', form=form)

@app.route('/profile')
def profile():
    if 'email' not in session:
        return redirect(url_for('signin'))

    user = User.query.filter_by(email=session['email']).first()

    if user is None:
        return redirect(url_for('signin'))
    else:
        return render_template('profile.html')

@app.route('/signin', methods=['GET', 'POST'])
def signin():
    form = SigninForm()

    if 'email' in session:
        return redirect(url_for('profile'))

    if request.method == 'POST':
        if form.validate() == False:
            return render_template('signin.html', form=form)
        else:
            session['email'] = form.email.data
            return redirect(url_for('profile'))

    elif request.method == 'GET':
        return render_template('signin.html', form=form)

@app.route('/signout')
def signout():
    if 'email' not in session:
        return redirect(url_for('signin'))

    session.pop('email', None)
    return redirect(url_for('home'))

app.run()

rawDescription: AssertionError: View function mapping is overwriting an existing endpoint function: home - flask


code:
[i for i, j in enumerate(input_string) if j == '|'][22]
154

rawDescription: How can I get the position of a recurring character in a string?

description: Get the position of a recurring character in a string


code:
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

rawDescription: Temporarily Disabling Django Caching

description: Temporarily Disabling Django Caching


code:
# vim: tabstop=4 expandtab

import asyncio
import pygame
import logging
from pygame import *
log = logging.getLogger('')

class Client:
    def __init__(self, host, port, loop):
        self.host = host
        self.port = port
        self.loop = loop
        self.send_q = asyncio.Queue()

    async def connect(self):
        self.reader, self.writer = await asyncio.open_connection(self.host,
                                                                 self.port,
                                                                 loop=self.loop)
        self.loop.create_task(self._handle_packets())
        self.loop.create_task(self._send())

    async def _handle_packets(self):
        while True:
            data = await self.reader.read(4096)
            if not data:
                continue
            message = data.decode()
            log.debug("(NET) Received "+message)

    def send(self, data):
        self.send_q.put_nowait(data)

    async def _send(self):
        while True:
            data = await self.send_q.get()
            self.writer.write(data)
            await self.writer.drain()

    def disconnect(self):
        print("DC")
        self.writer.close()

async def main(loop):
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    pygame.display.set_caption("Pyond client")
    bg = Surface((640, 480))
    bg.fill(Color("#004400"))
    client = Client('127.0.0.1', 2508, loop)
    await client.connect()
    while True:
        pygame.event.pump()
        for e in pygame.event.get():
            if e.type == QUIT:
                raise SystemExit
            elif e.type == KEYUP:
                if e.key == K_UP:
                    client.send(b"{'Hello':'World'}")
        screen.blit(bg, (0, 0))
        pygame.display.update()
    client.disconnect()

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

rawDescription: asyncio delayed StreamReader.read

description: Asyncio delayed StreamReader.read


code:
from win32com.client import Dispatch
excel = Dispatch('Excel.Application')
wb = excel.Workbooks.Open(r'c:\path\to\file.xlsx')
ws = wb.Sheets('My Sheet')
# do other stuff, just like VBA
wb.Close()
excel.Quit()

rawDescription: Automation Excel from Python

description: Automation Excel from Python


code:
import random
random.seed()

def run_periodically(start, end, interval, func):
    event_time = start
    while event_time < end:
        s.enterabs(event_time, 0, func, ())
        event_time += interval + random.random(-60, 60)
    s.run()

rawDescription: How to make an automated task, less detectable by randomising the interval (within bounds)

description: Make an automated task, less detectable by randomising the interval (within bounds)


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

def plot_matrix(rm, title='Robot World', cmap=plt.cm.Blues):
    plt.imshow(rm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.tight_layout()
    plt.show()

cmap = colors.ListedColormap(['k','b','y','g','r'])
bounds=[0,1,2,3,4]
norm = colors.BoundaryNorm(bounds, cmap.N)

rm = np.random.randint(0,4,(5,5))
plot_matrix(rm,cmap=cmap)

rawDescription: Difference between cmap and a list of colors


code:
import urllib2

url = 'http://www.google.com'

u = urllib2.urlopen(url)
localFile = open('C:\\file.csv', 'ab')
localFile.write(u.geturl() + ",")

localFile.close()

rawDescription: python csv list by rows instead of columns

description: Python csv list by rows instead of columns


code:
from django.core.cache import cache

...

CACHE_TIMEOUT = 3600      # choose your timeout

def data(request):
    jsonstring = cache.get('elections')

    if jsonstring is None:
        data = [{
                "title": election.title,
                "description": election.description,
                "priority": election.priority,
                "decided": election.decided,
                "candidates": [
                      {
                         "name": candidate.name,
                         "percent": candidate.percent,
                         "totalvotes": candidate.totalvotes,
                         "partyname": candidate.partyname,
                         "partyabbrv": candidate.partyabbrv,
                    } for candidate in election.candidates_set.all()
                  ],
                } for election in race.objects.all()]

        jsonstring = simplejson.dumps(data)
        cache.set('elections', jsonstring, CACHE_TIMEOUT)

    callback = request.GET.get('callback')

    if callback:
        response = HttpResponse("%s(%s)" % (callback, jsonstring),
                                mimetype="application/json")
    else:
        response = HttpResponse('{"races":' + jsonstring + '}',
                                mimetype="application/json")

    return response

rawDescription: How do I render a cached JSONP view in Django

description: Render a cached JSONP view in Django


code:
db = sqlite3.connect('/root/example.db')
db.row_factory = sqlite3.Row
cursor = db.cursor()
cursor.execute('''SELECT id, message,date FROM table''')

results = []
for row in cursor:
    results.append('{0} : {1}, {2}'.format(row['id'], row['message'], row['date']))
db.close()

headers = [
    ('Content-Type', 'text/html; charset=utf-8'),
    ('Content-Length', str(sum(len(line) for line in results)))
]

start_response('200 OK', headers)

return results

rawDescription: How to return value web from sqlite?

description: Return value web from sqlite


rawDescription: Key as Value and Value as Key

description: Key as Value and Value as Key


code:
opt = minimize(sm,x0,args=(a,b),method='nelder-mead', options={'xtol': 1e-8,     'disp': True})
opt

rawDescription: Optimisation using scipy

description: Optimisation using scipy


rawDescription: UnPivot a Pandas Data Set with Merge

description: UnPivot a Pandas Data Set with Merge


code:
def is_recent(version):
    version_as_ints = (int(x) for x in version.split('.'))
    return tuple(version_as_ints) > (1, 18, 10)

rawDescription: Regular expression for version number bigger than 1.18.10


code:
winmesssage = canvas.create_text(440, 550, font=("Bauhaus 93",40), fill = 'white', text='0')

winner = ''
if score1 >= 19:
    winner = '1'
elif score2 >= 19:
    winner = '2'
elif score3 >= 19:
    winner = '3'
elif score4 >= 19:
    winner = '4'

message = 'Player {0} wins!'.format(winner)

canvas.itemconfig(winmessage,text = message)

rawDescription: Finding which of 4 scores reach a certain amount first


code:
class Dog(Structure):
    _fields_ = [('name', c_char_p), ('weight', c_int)]

Dog.name.offset
# 0
Dog.weight.offset
# 4 (on my 32-bit system)

rawDescription: Implementing offsetof() for structures in Python ctypes


code:
with open("file.txt") as inf:
    # divide into tab delimited lines
    split_lines = [l[:-1].split() for l in inf]
    # create 3 lists using zip
    lst1, lst2, lst3 = map(list, zip(*split_lines))

rawDescription: Python file to list

description: Python file to list


code:
def initUI(self):
    self.okButton = QtGui.QPushButton("OK")
    self.okButton.clicked.connect(self.okClicked)
    self.cancelButton = QtGui.QPushButton("Cancel")
    ...

def okClicked(self):
    print(self.cancelButton.text())

rawDescription: PyQT Use Button Widget to Modify Other Widget in Grid


code:
import matplotlib.pyplot as plt

lines=[[array([10,0,0]),array([10,0,101.5]),array([-5,0,250])],[array([9,0,0]), array([9,0,101.5]),array([-4,0,250])]]

fig = plt.figure()
ax = fig.gca(projection='3d')
for line in lines:

    z = []
    for i in [0,1,2]:
        z.append(line[i][2])

    x = []
    for i in [0,1,2]:
        x.append(line[i][0])

    y = []
    for i in [0,1,2]:
        y.append(line[i][1])

    ax.plot(x, y, z, label='path')

plt.show()

rawDescription: Creating a 3D plot of several lines in one figure


code:
lastGoodIndex = 0
for i in range(len(ls) - 1):
    if ls[i] == None:
        if ls[i+1] > ls[lastGoodIndex]*5:
            ls[i+1] = None
    elif ls[i+1] > ls[i]*5:
        ls[i+1] = None
        lastGoodIndex = i

rawDescription: Detect condition between pairs of entries on a Python list


code:
def check_collision_group(most_sprites, screen):
    single = pygame.sprite.GroupSingle()
    for sprite in most_sprites:
        most_sprites.remove(sprite)
        single.add(sprite)

        collided_sprites_dict = pygame.sprite.groupcollide(
            single, most_sprites, False, False)

        most_sprites.add(sprite)

rawDescription: Finding all collisions within 1 group of sprites (efficiently)


code:
query = 'SELECT id,sing_name,bir_yr FROM singers_list WHERE bir_yr = %s'
curs.execute(query, (year, ))

rawDescription: PyMySQL variables in queries

description: PyMySQL variables in queries


code:
textfile=open(filenameOfTextFile, 'w')

rows=sheet.nrows
for row in range(rows):
    textfile.write(sheet.cell(row,0).value + "," + sheet.cell(row,1).value + "," + sheet.cell(row,2).value + "\n")

rawDescription: Working with excel sheets in python 3.4

description: Working with excel sheets in python 3.4


code:
import numpy as np
from enthought.mayavi import mlab

x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
s = np.sin(x*y*z)/(x*y*z)

src = mlab.pipeline.scalar_field(s)
mlab.pipeline.iso_surface(src, contours=[s.min()+0.1*s.ptp(), ], opacity=0.3)
mlab.pipeline.iso_surface(src, contours=[s.max()-0.1*s.ptp(), ],)

mlab.show()

rawDescription: How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar?

description: Display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar


code:
import asd
asd.s
t = asd.s
reload(asd) # I edited asd.py before
asd.s # new module content
t # but this is still old!

rawDescription: Making __import__ get the dynamically added methods


code:
import bs4
soup = bs4.BeautifulSoup(content)
soup.find('td').find('div').text
u'Traceback (most recent call last):  File "./crawler.py", line 381, in <module>      crawler.start()  File "./crawler.py", line 153, in start       raise RemoteTransportException(e)RemoteTransportException:       This socket is already used by another greenlet: <bound method Waiter.      switch of <gevent.hub.Waiter object at 0x7f64d499d6e0>>'

rawDescription: PyQuery find the sub element node text

description: PyQuery find the sub element node text


code:
user = jsonData['user']
user_id = user['id']

rawDescription: getting User_id from tweet using json module in python

description: Getting User_id from tweet using json module in python


code:
from scipy import signal
import matplotlib.pyplot as plt

# Generate a test signal, a 2 Vrms sine wave whose frequency linearly
# changes with time from 1kHz to 2kHz, corrupted by 0.001 V**2/Hz of
# white noise sampled at 10 kHz.

fs = 10e3
N = 1e5
amp = 2 * np.sqrt(2)
noise_power = 0.001 * fs / 2
time = np.arange(N) / fs
freq = np.linspace(1e3, 2e3, N)
x = amp * np.sin(2*np.pi*freq*time)
x += np.random.normal(scale=np.sqrt(noise_power), size=time.shape)

#Compute and plot the spectrogram.

f, t, Sxx = signal.spectrogram(x, fs)
plt.pcolormesh(t, f, Sxx)
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.show()

rawDescription: How to get time/freq from FFT in Python

description: Get time/freq from FFT in Python


code:
import re

sentence = "..."
converted = re.sub(r'ing\b', 'gni', re.sub(r'\bsub', 'bus', sentence))

rawDescription: Replace characters at end of a string

description: Replace characters at end of a string


code:
import sys

def build_index(path):
    index = {}
    for key, pos, data in parse_fastq(path):
        if key not in index:
            # Don't overwrite duplicates- use first occurrence.
            index[key] = pos

    return index

def error(s):
    sys.stderr.write(s + "\n")

def extract_key(s):
    # This much is fairly constant:
    assert(s.startswith('@'))
    (machine_name, rest) = s.split(':', 1)
    # Per wikipedia, this changes in different variants of FASTQ format:
    (key, rest) = rest.split('/', 1)
    return key

def parse_fastq(path):
    """
    Parse the 4-line FASTQ groups in path.
    Validate the contents, somewhat.
    """
    f = open(path)
    i = 0
    # Note: iterating a file is incompatible with fh.tell(). Fake it.
    pos = offset = 0
    for line in f:
        offset += len(line)
        lx = i % 4
        i += 1
        if lx == 0:     # @machine: key
            key = extract_key(line)
            len1 = len2 = 0
            data = [ line ]
        elif lx == 1:
            data.append(line)
            len1 = len(line)
        elif lx == 2:   # +machine: key or something
            assert(line.startswith('+'))
            data.append(line)
        else:           # lx == 3 : quality data
            data.append(line)
            len2 = len(line)

            if len2 != len1:
                error("Data length mismatch at line "
                        + str(i-2)
                        + " (len: " + str(len1) + ") and line "
                        + str(i)
                        + " (len: " + str(len2) + ")\n")
            #print "Yielding @%i: %s" % (pos, key)
            yield key, pos, data
            pos = offset

    if i % 4 != 0:
        error("EOF encountered in mid-record at line " + str(i));

def match_records(path, index):
    results = []
    for key, pos, d in parse_fastq(path):
        if key in index:
            # found a match!
            results.append(key)

    return results

def write_matches(inpath, matches, outpath):
    rf = open(inpath)
    wf = open(outpath, 'w')

    for m in matches:
        rf.seek(m)
        wf.write(rf.readline())
        wf.write(rf.readline())
        wf.write(rf.readline())
        wf.write(rf.readline())

    rf.close()
    wf.close()

#import pdb; pdb.set_trace()
index = build_index('afile.fastq')
matches = match_records('bfile.fastq', index)
posns = [ index[k] for k in matches ]
write_matches('afile.fastq', posns, 'outfile.fastq')

rawDescription: how to create an index to parse big text file

description: Create an index to parse big text file


code:
class postcon:
    def POST(self):
        conn=MySQLdb.connect(host="localhost",user="root",passwd="mysql",db="dang",charset="utf8")
        cursor = conn.cursor()
        n = cursor.execute("insert into d_message (mid,title,content,image) values(2,'xx','ccc','fff')")
        conn.commit() # This right here
        cursor.close()
        conn.close()
        if n:
            raise web.seeother('/')

rawDescription: About MySQLdb conn.autocommit(True)

description: About MySQLdb conn.autocommit(True)


code:
import datetime
from workalendar.europe import France
cal = France()
d = datetime.date(2015, 1, 1)
holiday_map = dict(cal.holidays(d.year))  # list -> dict
holiday_map.get(d, '?')

rawDescription: workalendar.europe library: how to find holidays

description: Workalendar.europe library: how to find holidays


code:
a = np.array([[1, 2, 3], [2, 3, 4] ,[4, 5, 6]])
friedmanchisquare(*(a[i, :] for i in range(a.shape[0])))

rawDescription: What is the correct way of passing parameters to stats.friedmanchisquare based on a DataFrame?


code:
threads = Thread.objects.all()[:30]
threads_by_pk = dict((t.pk, t) for t in threads)
# Extra info about threads that the user have visited
visited_threads = VisitedThread.objects.filter(pk__in=threads_by_pk.keys(), user=request.user)

# I want to loop the visited_threads and add info to thread in threads with new info
for visited_thread in visited_threads:
    thread = threads_by_pk[visited_thread.pk]
    thread.has_unread_post = thread.post_count > visited_thread.post_count

rawDescription: Best way to loop/change some objects in object_list

description: Loop/change some objects in object_list


code: df1['foo'] = pd.merge(df1, df2, on='no', how='left').apply(lambda r: r['foo_y'] if r['foo_y'] == r['foo_y'] else r['foo_x'], axis=1)

rawDescription: Pandas row manipulation

description: Pandas row manipulation


code:
def add_file(request, article_id):
    if request.method == 'POST':
        form = FileForm(request.POST, request.FILES)
        if form.is_valid():
            file = form.save(commit=False)
            article = Article.objects.get(id=article_id)
            file.article = article
            file.save()
            file.title = article.name + ' ' + file.id
            file.save()
            redirect_to = 'redirect to url'
            return HttpResponseRedirect(redirect_to)

rawDescription: django : unique name for object within foreign-key set

description: Django : unique name for object within foreign-key set


code:
FinalList = [(k, [int(i)*v for i in dr[k]]) for k, v in SimList]
TotalList = [sum(x) for x in zip(*(j for i in FinalList for j in i[1:]))]

rawDescription: Python List Appending

description: Python List Appending


rawDescription: How to use a custom predicate sort with Python

description: Use a custom predicate sort with Python


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

d = np.random.rand(100, 100)

fig = plt.figure()
ax = plt.gca()
plt.imshow(d, extent=(0,1,1,0))

ax.set_xticks([0, 0.25, 0.50, 0.75, 1])
ax.set_yticks([0, 0.25, 0.50, 0.75, 1])

fig.show()
raw_input()

rawDescription: Matplotlib imshow: cursor coordinates fail when ticks are specified


code:
# -*- coding: utf-8 -*-

import requests
url = u'https://fr.wikipedia.org/wiki/Nîmes'
response = requests.get(url)
content = response.content
text = response.text
assert type(content) == str
assert type(text) == unicode

rawDescription: How can I avoid explicit decoding of content?

description: Avoid explicit decoding of content


code:
import gtk, gobject, threading, time

gobject.threads_init()

window = gtk.Window()
button = gtk.ToggleButton('Start Thread')

class T(threading.Thread):
    pause = threading.Event()
    stop = False

    def start(self, *args):
        super(T, self).start()

    def run(self):
        while not self.stop:
            self.pause.wait()
            gobject.idle_add(self.rungui)
            time.sleep(0.1)

    def rungui(self):
        pass # all gui interaction should happen here

thread = T()
def toggle_thread(*args):
    if not thread.is_alive():
        thread.start()
        thread.pause.set()
        button.set_label('Pause Thread')
        return

    if thread.pause.is_set():
        thread.pause.clear()
        button.set_label('Resume Thread')
    else:
        thread.pause.set()
        button.set_label('Pause Thread')

button.connect('toggled', toggle_thread, None)

window.add(button)
button.show()
window.show()
gtk.main()

rawDescription: Python&PyGTK: Stop while on button click


rawDescription: Upload a file whose field styling display is None


code:
import urllib2
from xml.etree import cElementTree as etree

def f(url):
    tree = etree.parse(urllib2.urlopen(url))
    el = tree.find('results')
    if el is not None:
       lst = [el.findtext(tag) or '' for tag in "name name_status url".split()]
       return ','.join(lst)

rawDescription: Get text from a single element of the etree in XML


code: done = [(el, x) for el in [a, b, c, d]]

rawDescription: Python turning a list into a list of tuples


code:
import boto
import cStringIO
import urllib
import Image

#Retrieve our source image from a URL
fp = urllib.urlopen('http://example.com/test.png')

#Load the URL data into an image
img = cStringIO.StringIO(fp.read())
im = Image.open(img)

#Resize the image
im2 = im.resize((500, 100), Image.NEAREST)

#NOTE, we're saving the image into a cStringIO object to avoid writing to disk
out_im2 = cStringIO.StringIO()
#You MUST specify the file type because there is no file name to discern it from
im2.save(out_im2, 'PNG')

#Now we connect to our s3 bucket and upload from memory
#credentials stored in environment AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
conn = boto.connect_s3()

#Connect to bucket and create key
b = conn.get_bucket('example')
k = b.new_key('example.png')

#Note we're setting contents from the in-memory string provided by cStringIO
k.set_contents_from_string(out_im2.getvalue())

rawDescription: Upload resized image to S3

description: Upload resized image to S3


code:
df
s = df.apply(lambda x: pd.Series(x['samples']),axis=1).stack().reset_index(level=1, drop=True)
s.name = 'sample'
df.drop('samples', axis=1).join(s)

rawDescription: pandas: When cell contents are lists, create a row for each element in the list

description: Pandas: When cell contents are lists, create a row for each element in the list


code: qs.filter( **{ 'attitudes__%s'%arg:True } )

rawDescription: is it possible to define name of function's arguments dynamically?

description: Is it possible to define name of function's arguments dynamically


rawDescription: Python - open file - readline - list - convert to string


code:
from timeit import timeit
timeit('"abcdefghijklmnopqrstuvwxyz,1".split(",", 1)')
timeit('"abcdefghijklmnopqrstuvwxyz,1".rsplit(",", 1)')

rawDescription: python split() vs rsplit() performance?

description: Python split() vs rsplit() performance


code:
import types

def get_db_connection(request):
    if not hasattr(request, '_db'):
        request._db = my_connect_to_db()
        request.add_finished_callback(close_db_connection)
    return request._db

def new_request_subscriber(event):
    request = event.request
    request.db = types.MethodType(get_db_connection, request)

rawDescription: In Pyramid, how to check if view is static in NewRequest event handler?


code:
statCounter = myData.stats()
results.append(statCounter.sum())
results.append(statCounter.min())
results.append(statCounter.variance())
results.append(statCounter.sampleStdev())
results.append(statCounter.sampleVariance())

rawDescription: PySpark Run Multiple Functions on an RDD


code:
import numpy as np
import pylab as plt

# The example dict/matrix
dict = {}
for x in range(0, 11):
    dict[x] = [0,1,2,3,4,5,6,7,8,9,10]

# Create an empty numpy array with the right dimensions
nparr = np.zeros((len(dict.keys()), len(dict[0])))

# Loop through converting each list into a row of the new array
for ii in xrange(nparr.shape[0]):
    nparr[ii] = dict[ii]

# Plotting as a contour
plt.contour(nparr)
plt.show()

rawDescription: Generating a contour plot based on a matrix of z values using MatPlotLib


code:
def treeview_sort_column(tv, col, reverse):
    l = [(tv.set(k, col), k) for k in tv.get_children('')]
    l.sort(reverse=reverse)

    # rearrange items in sorted positions
    for index, (val, k) in enumerate(l):
        tv.move(k, '', index)

    # reverse sort next time
    tv.heading(col, command=lambda: \
               treeview_sort_column(tv, col, not reverse))

[...]
columns = ('name', 'age')
treeview = ttk.TreeView(root, columns=columns, show='headings')
for col in columns:
    treeview.heading(col, text=col, command=lambda: \
                     treeview_sort_column(treeview, col, False))
[...]

rawDescription: Tk treeview column sort

description: Tk treeview column sort


code:
import rsvg
from gtk import gdk
h = rsvg.Handle('svg-file.svg')
pixbuf = h.get_pixbuf()
pixbuf.save('foobar.png', 'png')

rawDescription: How to convert SVG images for use with Pisa / XHTML2PDF?

description: Convert SVG images for use with Pisa / XHTML2PDF


code:
import time
import threading
import datetime as DT
import logging
logger = logging.getLogger(__name__)

def worker(cond):
    i = 0
    while True:
        with cond:
            cond.wait()
            logger.info(i)
            time.sleep(0.01)
            i += 1

logging.basicConfig(level=logging.DEBUG,
                    format='[%(asctime)s %(threadName)s] %(message)s',
                    datefmt='%H:%M:%S')

cond = threading.Condition()
t = threading.Thread(target=worker, args=(cond, ))
t.daemon = True
t.start()

start = DT.datetime.now()
while True:
    now = DT.datetime.now()
    if (now-start).total_seconds() > 60: break
    if now.second % 2:
        with cond:
            cond.notify()

rawDescription: how to start and stop thread

description: Start and stop thread


rawDescription: mean of elements i and i+1 in a numpy array

description: Mean of elements i and i+1 in a numpy array


code:
from itertools import combinations, product
def canMerge (g, h):
    for i, j in g:
        for x, y in h:
            if abs(i - x) <= 1 and abs(j - y) <= 1:
                return True
    return False

def findGroups (field):
    # initialize one-element groups
    groups = [[(i, j)] for i, j in product(range(len(field)), range(len(field[0]))) if field[i][j] == '#']

    # keep joining until no more joins can be executed
    merged = True
    while merged:
        merged = False
        for g, h in combinations(groups, 2):
            if canMerge(g, h):
                g.extend(h)
                groups.remove(h)
                merged = True
                break

    return groups

# intialize field
field = '''\
..##.#..#
##..####.
.........
###.###..
##...#...'''.splitlines()
groups = findGroups(field)

print(len(groups)) # 3

rawDescription: Python 3.3.2 - 'Grouping' System with Characters


code:
from django.utils import timezone

timezone.now()

rawDescription: Django, queryset, filter today

description: Django, queryset, filter today


code:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'mainwindow.ui'
#
# Created: Wed Aug 13 15:25:22 2014
#      by: PyQt4 UI code generator 4.11.1
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
        def _fromUtf8(s):
            return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(480, 385)
        MainWindow.setWindowOpacity(1.0)
        self.centralWidget = QtGui.QWidget(MainWindow)
        self.centralWidget.setObjectName(_fromUtf8("centralWidget"))
        self.textBrowser = QtGui.QTextBrowser(self.centralWidget)
        self.textBrowser.setGeometry(QtCore.QRect(100, 120, 256, 192))
        self.textBrowser.setObjectName(_fromUtf8("textBrowser"))
        self.widget = QtGui.QWidget(self.centralWidget)
        self.widget.setGeometry(QtCore.QRect(150, 10, 156, 97))
        self.widget.setObjectName(_fromUtf8("widget"))
        self.verticalLayout_2 = QtGui.QVBoxLayout(self.widget)
        self.verticalLayout_2.setMargin(0)
        self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
        self.verticalLayout = QtGui.QVBoxLayout()
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.lineEdit = QtGui.QLineEdit(self.widget)
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))
        self.verticalLayout.addWidget(self.lineEdit)
        self.lineEdit_2 = QtGui.QLineEdit(self.widget)
        self.lineEdit_2.setObjectName(_fromUtf8("lineEdit_2"))
        self.verticalLayout.addWidget(self.lineEdit_2)
        self.verticalLayout_2.addLayout(self.verticalLayout)
        self.pushButton = QtGui.QPushButton(self.widget)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.verticalLayout_2.addWidget(self.pushButton)
        MainWindow.setCentralWidget(self.centralWidget)
        self.menuBar = QtGui.QMenuBar(MainWindow)
        self.menuBar.setGeometry(QtCore.QRect(0, 0, 480, 22))
        self.menuBar.setObjectName(_fromUtf8("menuBar"))
        MainWindow.setMenuBar(self.menuBar)
        self.mainToolBar = QtGui.QToolBar(MainWindow)
        self.mainToolBar.setObjectName(_fromUtf8("mainToolBar"))
        MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar)
        self.statusBar = QtGui.QStatusBar(MainWindow)
        self.statusBar.setObjectName(_fromUtf8("statusBar"))
        MainWindow.setStatusBar(self.statusBar)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.lineEdit, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit.setText)
        QtCore.QObject.connect(self.lineEdit_2, QtCore.SIGNAL(_fromUtf8("textEdited(QString)")), self.lineEdit_2.setText)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.lineEdit.setPlaceholderText(_translate("MainWindow", "Enter Case Number", None))
        self.lineEdit_2.setPlaceholderText(_translate("MainWindow", "Number of cases", None))
        self.pushButton.setText(_translate("MainWindow", "Submit", None))

        # Call a function when the button "Submit" is pressed
        self.pushButton.clicked.connect(self.OnSubmit)

    def OnSubmit(self):

        # On submit do the necessary
        # here I take the text from the LineEdits that you have
        # (ie your Case Number, and number of Cases)
        # and print them to the textbrowser below

        text = self.lineEdit.text() + ' ' + self.lineEdit_2.text()
        self.textBrowser.append(text)

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

rawDescription: PyQT4: getting text from Ui for existing python program


code:
import csv

with open("in.csv", "rb") as in_file:
    header = in_file.readline()
    csv_file_in = csv.reader(in_file, delimiter=" ")
    with open("out.csv","wb") as out_file:
        out_file.write(header)
        csv_file_out = csv.writer(out_file, delimiter=" ")
        for row in csv_file_in:
            csv_file_out.writerow([row[0], 10] + row[1:])

rawDescription: Adding in-between column in csv Python

description: Adding in-between column in csv Python


code:
import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

rawDescription: Python Create unix timestamp five minutes in the future


code:
conf.iface = 'lo'
conf.route.resync()

rawDescription: Reload scapy conf

description: Reload scapy conf