code:
from collections import OrderedDict

# A list of lists can be used as input for an OrderedDict, so don't need to loop
NO_dict = OrderedDict(ISO3166_CountryCodes_NO)
EN_dict = OrderedDict(ISO3166_CountryCodes_EN)

# Assumes you want the result in the same order as the Norwegian list
# Iterate over the English list if it has a preferred order

final_dict = OrderedDict([(k, (NO_dict[k], EN_dict[k])) for k in NO_dict])

rawDescription: Python: Compare lists and combine in common fields


code: "select reltuples from pg_class where relname='%s'" % table_name

rawDescription: Python/Django print loop progress along the way


code:
from itertools import tee
from collections import OrderedDict

d=OrderedDict()
with open('input.txt') as f,open('new','w') as new:
    f2,f3,f=tee(f,3)
    next(f3)
    words={line.split()[0] for line in f if not line.startswith('TOPIC') and line.strip()}

    for line in f2:
        if line.startswith('TOPIC'):
           key=line
           next_line=next(f3)
           try:
               while not next_line.startswith('TOPIC'):
                  d.setdefault(key,[]).append(next_line)
                  next_line=next(f3)
           except:
                pass

    for k,v in d.items():
        block_words={line.split()[0] for line in v if line.strip()}
        insec=words.difference(block_words)
        new.writelines([k]+v+['{} {}\n'.format(i,0) for i in insec])

rawDescription: Assign 0 to certain words when the words are not present


code:
def sort_uniq(alist):
   mod_list = dict(zip(alist,alist)).keys()
   mod_list.sort()
   return mod_list

rawDescription: Dedupe and sort a list in Python 2.2

description: Dedupe and sort a list in Python 2.2


code:
params = {'name': ['val1', 'val2', 'val3', 'val4']}

response = requests.get(url, params=params)

rawDescription: Post request with many params in Python

description: Post request with many params in Python


code: index_2d(myList, 3)

rawDescription: Python: Return 2 ints for index in 2D lists given item


code: self.assertFileMode(my_directory, user="rwx", group="rx", others="rx")

rawDescription: Better assertEqual() for os.stat(myfile).st_mode


code:
from netifaces import interfaces, ifaddresses, AF_INET

def ip4_addresses():
    ip_list = []
    for interface in interfaces():
        for link in ifaddresses(interface)[AF_INET]:
            ip_list.append(link['addr'])
    return ip_list

rawDescription: Why does gethostbyaddr(gethostname()) return my IPv6 IP?


code:
expressions = {}
for left, op, right in list1 + list2:
    expressions.setdefault((left, op), []).append(right)

rawDescription: Combining lists in python with unique elements but changing the third


rawDescription: How to find the top 10 pairs that appear the most in a pandas dataframe in python

description: Find the top 10 pairs that appear the most in a pandas dataframe in python


rawDescription: Python count everytime a string is found in another string


rawDescription: How to Transpose Column Values to Row Values in Python


code:
def poll_data(data_callback):
    def check_new_event():
        if do_something_to_check():
           wx.CallAfter(data_callback) # this will cause the callback to be executed in the main thread (All gui updates *should* be done in the main thread)
    while True:
       check_new_event()
       sleep(1) # force thread to surrender control for a while

def on_callback(*args,**kwargs):
    wx.MessageBox("Some Message","Title")

def my_app():
    a= wx.App(redirect=False)
    f=wx.Frame(None)
    th = threading.Thread(target=poll_data,args=(on_callback,))
    th.start()
    a.MainLoop()

rawDescription: Simultaneous Message Boxes

description: Simultaneous Message Boxes


code:
ip = '192.168.1.1'
ip_as_bytes = ''.join(map(chr,map(int,ip.split('.'))))

rawDescription: Converting IP address into bytes in python


code:
import numpy as np

#initialize the grid with the middle set to one
grid = np.zeros((5,5))
grid[2,2] = 1

rawDescription: 5*5 grid, in every 3*3 square of the grid must be 4 "lights"


code:
df = pd.DataFrame(['yes',np.nan,'no',np.nan], columns=['am'])
df
df['am'] = df.am.map(lambda x: x if pd.isnull(x) else 'new')
df

rawDescription: Relabel levels in pandas

description: Relabel levels in pandas


code:
combos = make_combo_dict([350, 200, 500, 510], 1200)
for total,ways in sorted(combos.items()):
    print("{:>4d}: {}".format(total, ", ".join(ways)))

rawDescription: Generating addition combinations from an int list in python


code:
SomeClass = getattr(baz, 'SomeClass')
obj = SomeClass()

rawDescription: Python dynamic class names

description: Python dynamic class names


code:
attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]

rawDescription: Getting attributes of a class

description: Getting attributes of a class


code: ['Satoshi Dice Change Address', 'Satoshi Dice Change Address', 'SatoshiDICE 50%', 'Satoshi Dice Change Address']

rawDescription: Fetch specific data from JSON

description: Fetch specific data from JSON


code:
from cStringIO import StringIO
from flask import make_response

from somewhere import generate_wav_file  # TODO your code here

@app.route('/path')
def view_method():

    buf = StringIO()

    # generate_wav_file should take a file as parameter and write a wav in it
    generate_wav_file(buf)

    response = make_response(buf.getvalue())
    buf.close()
    response.headers['Content-Type'] = 'audio/wav'
    response.headers['Content-Disposition'] = 'attachment; filename=sound.wav'
    return response

rawDescription: How to send audio wav file generated at the server to client browser?

description: Send audio wav file generated at the server to client browser


code:
input_to_state = None
RNN = None
def main(dataset, n_h, n_y, batch_size, dev_split, n_epochs):
    # Calling 'global' allows you to modify these variables
    global input_to_state
    global RNN
    input_to_state = Linear(name='input_to_state',
                            input_dim=seq_u.shape[-1],
                            output_dim=n_h)
    RNN = SimpleRecurrent(activation=Tanh(),
                          dim=n_h, name="RNN")

def predict(dev_X):
    dev_transform = input_to_state.apply(dev_X)
    dev_h = RNN.apply(dev_transform)

if __name__ == "__main__":
    main(args)
    predict(dev_X)

rawDescription: In Python, can I call the variable from main function - use global variable?


code:
cars = {}
cars['2012'] = ['BMW', ' Fiat']
cars['2013'] = ['Ford', 'Renault']
cars
cars['2012'].append('Toyota')
cars
cars['2012']

rawDescription: Adding value to an existing dict's keys

description: Adding value to an existing dict's keys


code:
stack_1 = stack_2 = input('Value:')
if 1 < stack_1:
    result = False
else:
    result = stack_2 < 10

rawDescription: How do chained comparisons in Python actually work?


code:
key = 117201 * x + y
if key in dictionary_structure:
    print(dictionary_structure[key]["data"])

rawDescription: Fastest data structure for numerically indexed data structure?


code:
class Widget(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)

rawDescription: How to use QtGui in PyQt4 to collect input variables to a python program?

description: Use QtGui in PyQt4 to collect input variables to a python program


code: reduced_d = {k: v for k, v in myDefaultDict.items() if len(v) > 1}

rawDescription: Python filter defaultdict

description: Python filter defaultdict


code:
jdata = json.load('{"uri": "http:", "foo", "bar"}')
'uri' in jdata       # Check if 'uri' is in jdata's keys
jdata['uri']         # Will return the value belonging to the key 'uri'

rawDescription: Parsing json and searching through it

description: Parsing json and searching through it


rawDescription: How to replace multiple overlapping patterns with regex?

description: Replace multiple overlapping patterns with regex


code:
from collections import defaultdict
import re

myarch = 'C:/code/test5.txt'
mydict = defaultdict(int)

with open(myarch) as f:
    for line in f:
        for key in re.findall("\'(\S*)\'", line):
            mydict[key] +=1

out = ["['%s'], %s" % (key, value) for key, value in mydict.iteritems() if value > 1]

#save to a file
with open('C:/code/fileout.txt', 'w') as fo:
    fo.write('\n'.join(out))

rawDescription: Lists in text file

description: Lists in text file


code:
from threading import current_thread
from functools import wraps
from types import MethodType
from collections import defaultdict

def method_decorator(func, cls):
    @wraps(func)
    def wrapper(self, *args, **kw):
        self.__class__.__class__.current_running_class[current_thread()].append(cls)
        result = MethodType(func, self)(*args, **kw)
        self.__class__.__class__.current_running_class[current_thread()].pop()
        return result
    return wrapper

class MetaBase(type):
    definitions = {}
    current_running_class = defaultdict(list)
    def __init__(cls, name, bases, dct):
        for attrname, attr in dct.items():
            cls.__class__.definitions[attr] = cls
            if callable(attr) and attrname != "__setattr__":
                setattr(cls, attrname, method_decorator(attr, cls))

class Base(object, metaclass=MetaBase):
    def __setattr__(self, attr, value):
        if not hasattr(self, "_definitions"):
            super().__setattr__("_definitions", {})
        self._definitions[attr] = self.__class__.current_running_class[current_thread()][-1]
        return super().__setattr__(attr,value)

rawDescription: How can one locate where an inherited variable comes from in Python?


rawDescription: txredisapi subscribe and listen async

description: Txredisapi subscribe and listen async


code:
# ... main operation
self.readycleanup.set() # Still within loop
self.cleanupfinished.wait()
self.cleanupfinished.clear()
# End of loop

rawDescription: Synchronize a cleanup process between threads


code: dict_i_wanted = todos.dict()

rawDescription: How should I do a RedisDict in python?

description: How should I do a RedisDict in python


code: Board = [i+1 for i in xrange(9)]

rawDescription: (Python) adding a list to another without the brackets


code:
from django.utils.six import python_2_unicode_compatible

@python_2_unicode_compatible
class StringConfReference(object):
    def __init__(self, name):
        self.name = name

    def __str__(self):
        return getattr(conf, self.name)

    def deconstruct(self):
        return "%s.%s" % (__name__, self.__class__.__name__), (self.name,), {}

attachment = models.FilePathField(
    path=StringConfReference('ATTACHMENT_DIR'), recursive=True
)

rawDescription: Django migrations and customizable reusable apps


code:
import tkinter
file = tkinter.filedialog.asksaveasfile()
name = file.name

rawDescription: How to save as a file but get its name at the same time?

description: Save as a file but get its name at the same time


code:
#!/usr/bin/env python
import logging
from argparse import ArgumentParser

COMPANY_LOGGER = 'COMPANY.Python.Logger'
CONSL_LEVEL_RANGE = range(0, 51)
LOG_FILE = 'company.log'
FORMAT_STR = '%(asctime)s %(levelname)s %(message)s'

parser = ArgumentParser()
parser.add_argument('-c', '--console-log', metavar='ARG',
                    type=int, choices=range(0, 51),
                    action='store', dest='console_log',
                    default=None,
                    help='Adds a console logger for the level specified in the range 1..50')

args = parser.parse_args()

# Create logger
logger = logging.getLogger(COMPANY_LOGGER)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter(FORMAT_STR)

# Add FileHandler and only log WARNING and higher
fh = logging.FileHandler(LOG_FILE)
fh.name = 'File Logger'
fh.level = logging.WARNING
fh.formatter = formatter
logger.addHandler(fh)

# Add optional ConsoleHandler
if args.console_log:
    ch = logging.StreamHandler()
    ch.name = 'Console Logger'
    ch.level = args.console_log
    ch.formatter = formatter
    logger.addHandler(ch)

logger.debug('DEBUG')
logger.info('INFO')
logger.warning('WARNING')
logger.critical('CRITICAL')

rawDescription: Different levels of logging in python

description: Different levels of logging in python


code: map(lambda x: x["_id"], result)

rawDescription: Conditions in Find, Mongo

description: Conditions in Find, Mongo


rawDescription: building a parser in python

description: Building a parser in python


code:
list1, list2 = (list(t) for t in zip(*sorted(zip(list1, list2))))
list1
list2

rawDescription: Is it possible to sort two lists(which reference each other) in the exact same way?


code: passive=true

rawDescription: Have user sign up with Google and get redirected back to the site afterwards?


code:
main_c = Counter() # keep all results here
urls = ["http://www.nerdwallet.com/the-best-credit-cards","http://stackoverflow.com/questions/tagged/python"]
for url in urls:
    website = requests.get(url)
    soup = BeautifulSoup(website.content)
    texts = soup.findAll(text=True)
    a = Counter([x.lower() for y in texts for x in y.split()])
    b = (a.most_common())
    main_c.update(b)
make_a_frame = pd.DataFrame(main_c.most_common())
make_a_frame.columns = ['Words', 'Frequency']
print(make_a_frame)

rawDescription: How to Crawl Multiple Websites to find common Words (BeautifulSoup,Requests,Python3)


code:
def write(self, fp):
    """Write an .ini-format representation of the configuration state."""
    if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
    for section in self._sections:
        fp.write("[%s]\n" % section)
        for (key, value) in self._sections[section].items():
            if key != "__name__":
                fp.write("%s = %s\n" %
                         (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")

rawDescription: How to remove spaces while writing in INI file- Python

description: Remove spaces while writing in INI file- Python


code:
binNum = input('Input your number: \n')
binNum = binNum[::-1]

rawDescription: 'str' object is not callable - Converter


code:
import requests
requests.post('http://test.com/upload', files={'data': ('readme.txt', 'Readme file content or pointer', 'text/plain')})

rawDescription: Mime type for Requests post file

description: Mime type for Requests post file


code:
import time
import data as shared

shared.var = "002"
time.sleep(5.0)
shared.print_vars()

# It prints:
# list_vars = []
# var = 002

rawDescription: Static variables in Python that are shared across files


code:
class Handle:
    # Both pid and procname may be specified at the same time.
    def __init__(self, pid=-1, procname=None):
        self.procname = procname
        self.pid = pid

rawDescription: Python overload __init__

description: Python overload __init__


code:
import matplotlib.pyplot as plt

plt.annotate('Testing\nThis\nOut', xy=(0.5, 0.5))

plt.show()

rawDescription: Python : Matplotlib annotate line break (with and without latex)


code:
class IsInRange5(object):
    def __init__(self, r=("8X5000", "8X5099")):
        ((self.minr0, self.minr1), (self.maxr0, self.maxr1)) = [[int(i) for i in l.split('X')] for l in r]
        pos = len(r[0]) - r[0].find('X')
        self.basel = 10**(pos-1)
        self.baseh = self.basel*10
        self.ir = range(2)

    def __contains__(self, n):
        return self.minr0 <= n // self.baseh <= self.maxr0 and \
            self.minr1 <= n % self.basel <= self.maxr1

rawDescription: How to check if a number is within a group of non-consecutive ranges?

description: Check if a number is within a group of non-consecutive ranges


code:
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

# Pagina principal
class MainPage(webapp.RequestHandler):
    def get(self):
        if users.get_current_user():
            url = users.create_logout_url(self.request.uri)
            url_linktext = "Bem Vindo: "+ str(users.get_current_user()) + ".  Logout "
        else:
            url = users.create_login_url(self.request.uri)
            url_linktext = ' Entrar '
        values = {
                  'url': url,
                  'url_linktext': url_linktext,
                  }
        self.response.out.write(template.render('templates/index.html', values))

application = webapp.WSGIApplication([
                                      ('/', MainPage),
                                      ],debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

rawDescription: GAE simple app question

description: GAE simple app question


code: colors = hsv(np.linspace(0, 1.0, len(kinds)))

rawDescription: matplotlib large set of colors for plots

description: Matplotlib large set of colors for plots


code: d

rawDescription: How to not print the last line

description: Not print the last line


code:
c1 = pandas.Series([1, 2], index=['A', 'B'], name='c1')
c2 = pandas.Series([3, 4, 5], index=['A', 'B', 'C'], name='c2')
c2[~c2.index.isin(c1.index)]

rawDescription: Get elements of Series B not in A

description: Get elements of Series B not in A


code: new=zip(l,p)

rawDescription: How can I generate a list like this with python

description: Generate a list like this with python


rawDescription: Merging CSV data and counting cell values in python pandas


code:
def traverse(val):
    if isinstance(val, list):
        for v in val:
            yield from traverse(v)
    else:
        yield val

rawDescription: Counting integer in a nested list

description: Counting integer in a nested list


code:
DOWNLOADER_MIDDLEWARES = {
    'splashtest.middleware.splash.SplashMiddleware': 725,
}

rawDescription: Python/Scrapy: Scraping Nasdaq's data?

description: Python/Scrapy: Scraping Nasdaq's data


code: df1[['depth', 'attr1']].join(df1.apply(lambda x: get_depth_group(x['name'], x['depth']), axis=1))

rawDescription: In Pandas, merge two dataframs with complex multi-indexing


rawDescription: solving for a compound interest between PV and "summation" FV?

description: Solving for a compound interest between PV and "summation" FV


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

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
import threading

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200)
        self.end_headers()
        message =  threading.currentThread().getName()
        self.wfile.write(message)
        self.wfile.write('\n')
        return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
    """Handle requests in a separate thread."""

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!\n')

if __name__ == '__main__':
    # create Tornado Server
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)

    # create BaseHTTPServer
    server = ThreadedHTTPServer(('localhost', 8080), Handler)
    server.timeout = 0.01

    tornado.ioloop.PeriodicCallback(server.handle_request, 100).start() # every 100 milliseconds
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Python BaseHTTPServer and Tornado

description: Python BaseHTTPServer and Tornado


code:
root = TK.Tk()

frame = TK.Frame(root)
canvas = TK.Canvas(frame, width=1000, height=1000)
frame.grid()
canvas.grid()

# create a bunch of isoceles triangles in different places:
shapes = []
for dx, dy in zip(range(0,1000, 30), range(0,1000, 30)):
    shapes.append(Shape(canvas, [0+dx, 0+dy, 10+dx, 10+dy, 20+dx, 0+dy], 5))

# draw (or redraw) the shapes:
for shape in shapes:
    shape.updateShape()

# move one of the shapes and change it to a square
shapes[10].vertexCoords = [50, 10, 60, 10, 60, 20, 50, 20]
shapes[10].updateShape()

# delete all the odd-numbered shapes, just for fun:
for k in range(len(shapes)):
    if k%2 == 1:
        shape.deleteShape()

root.mainloop()

rawDescription: Finding and Connecting Multiple Canvas Items in Python


rawDescription: Store NumPy Row and Column Headers

description: Store NumPy Row and Column Headers


rawDescription: Why is a `for` over a Python list faster than over a Numpy array?


code: sum(map(lambda x:[int(c) for c in str(x)], somedata), [])

rawDescription: python map/reduce: emit multiple keys values from single map lambda

description: Python map/reduce: emit multiple keys values from single map lambda


code:
selenium_jar = '/full/path/to/selenium-server-standalone-2.0b3.jar'
path_to_fifo_profile = '...'

# start external process
p = subprocess.Popen(['java', '-jar', selenium_jar,
                              '-firefoxProfileTemplate', path_to_fifo_profile,
                     ])
# wait for it to finish before exiting
p.wait()

rawDescription: Sending stdin to subprocess in python script


code:
s = 'Something M123'
'M' in s and s[s.rfind('M') + 1:].isdigit()

rawDescription: Find index of string + integer in python


code:
internal_apis = patterns('',
                     url(r'^/api/jobs/status/',...),
                     url(r'^/api/jobs/parameters/',...),
                     )

urlpatterns = urlpatterns + patterns('',
              url(r'^', include(internal_apis, namespace="internal_apis")),
              ...
              )

rawDescription: Exclude URLs from Django REST Swagger

description: Exclude URLs from Django REST Swagger


code:
import speech

while True:
    phrase = speech.input()
    speech.say("You said %s" % phrase)
    if phrase == "turn off":
        break

rawDescription: which module to automating Voice/Speech using python

description: Which module to automating Voice/Speech using python


code:
def pixel(surface, color, pos):
    surface.fill(color, (pos, (1, 1)))

rawDescription: Pygame: Draw single pixel

description: Pygame: Draw single pixel


rawDescription: Difference between dictionary and ordereddict in python


code: ['this Is a TEST\n', 'and this is another line']

rawDescription: Reading multiple lines from an external text file in Python


code:
max_len=max(l)
new = [[0 for _ in range(max_len)] for _ in range(max_len)]
for i,v in enumerate(l):
    new[i][v-1] = v

new

rawDescription: How to place numbers in a python list at the index of their magnitude

description: Place numbers in a python list at the index of their magnitude


code:
def link_emit(self, node):
    target = node.content
    if node.children:
        inside = self.emit_children(node)
    else:
        inside = self.html_escape(target)

    return '%s' % (
        self.attr_escape(target), inside)

rawDescription: Change internal links rendering using python-creole


code:
import timeit
text = "gw3AQEFGh8NFgoqDwYsAQALDVFPVltYVkNGXldCRFUbNRk=----------:jhawrewre:--\r\n"
timeit.timeit('test(text)', 'from __main__ import with_takewhile as test, text')
timeit.timeit('test(text)', 'from __main__ import with_re as test, text')

rawDescription: How to extract valid string from beginning to the first no base64 valid character?

description: Extract valid string from beginning to the first no base64 valid character


code:
import inspect
def class_for_method(cls, method):
    return next((c for c in inspect.getmro(cls)
                 if method.__func__ in vars(c).values()), None)

class Base1(object):
    def foo(self): pass

class Base2(object):
    pass

class ClassA(Base1, Base2):
    pass

class_for_method(ClassA, ClassA.foo)

rawDescription: In Python, class from which a given instance is inheriting a particular method


code:
from collections import defaultdict

week_to_items = defaultdict(list)
for item in data:
    week_to_items[item['week']].append(item)

rawDescription: Get matching values from dictionaries in a list then add and average


code:
class EmployeeOrderAdmin(admin.ModelAdmin):
    list_display = ('employee_order_date', 'employee_placed')
    raw_id_fields = ('order',)

rawDescription: Displaying "info" by selecting foreign key in django admin


code: params = [('title', 'file1'), ('title', 'file2'), ('title', 'file3')]

rawDescription: how to POST multipart list of JSON/xml files using python requests


rawDescription: Boto3 uses old credentials

description: Boto3 uses old credentials


code: df['End_Time'] += df['Diff']

rawDescription: How to convert the time from 00:00 to 24:00 in python

description: Convert the time from 00:00 to 24:00 in python


code:
# logic

def get_geo(full_address):
    " Dummy function which fakes `full_address` and get lat/lng using hash(). "
    hs = hash(full_address)
    return (hs >> 8) & 0xff, hs & 0xff

def add_test_data(addresses):
    with session.begin():
        for fa in addresses:
            session.add(RawAddress(full_address=fa))

def add_geo_info():
    with session.begin():
        q = (session
             .query(RawAddress)
             .filter(~RawAddress.geocoded_address.has())
             )
        for ra in q.all():
            print("Computing geo for: {}".format(ra))
            lat, lng = get_geo(ra.full_address)
            ra.geocoded_address = GeocodedAddress(
                full_address=ra.full_address, lat=lat, lng=lng)

rawDescription: SQL alchemy - specifying relationships when foreign key may not exist


code:
def get_upload_path(instance, filename):
    return '{0}/{1}'.format(instance.gallery.folder, filename)

rawDescription: Django-models: use field from foreign key


code:
library_path=r"c:\Program Files (x86)\Graphviz 2.28\bin"
include_path=r"c:\Program Files (x86)\Graphviz 2.28\include\graphviz"

rawDescription: Installing PygraphViz on Windows, Python 2.6


rawDescription: How can I select n items and skip m from ndarray in python?

description: Select n items and skip m from ndarray in python


rawDescription: Regex to capture numbers up to 2 digits and coma if followed by another word and number


code: print("Thanks", StudentName, "for participating in the quiz.")

rawDescription: Text after variable print command

description: Text after variable print command


rawDescription: Having quotation marks as a character in a python list


code: timestamp, base64_data = ba_object[:4], ba_object[4:]

rawDescription: Python 3 Struct unpack int and bytearray


code:
def get_cnt(lVals):
    d = dict(zip(lVals, [0]*len(lVals)))
    for x in lVals:
        d[x] += 1
    return d

rawDescription: count each element in list without .count

description: Count each element in list without .count


code:
import Queue
output_queue = Queue.Queue()

def get_links():
    #gather urls
    urls = ['www.google.com'] * 25
    threaded(urls, write_csv, num_threads=5)

def write_csv(url):
    data = {'cat':1,'dog':2}
    output_queue.put(data)

if __name__ == '__main__':

    get_links() # thready blocks until internal input queue is cleared

    csv_out = csv.writer(file('output.csv','wb'))

    while not output_queue.empty():
        d = output_queue.get()
        csv_out.writerow(d.keys())
        csv_out.writerow(d.values())

rawDescription: csv writer not printing rows properly

description: Csv writer not printing rows properly


code:
import itertools
def day_generator():
    days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
    for day in itertools.cycle(days):
        yield day

rawDescription: Infinite generator in Python for days of week


rawDescription: __repr__ for an attribute that can be a string or None?


code:
field_names = data[0].split(",")
list_of_dicts = [dict(zip(field_names, row.split(','))) for row in data[1:]]

rawDescription: Storing data into namedtuples with empty fields to add other stuff


code: dct = dict((tuple(map(int, key)), value) for key, value in str_dict.iteritems())

rawDescription: Loop through dictionary with a math function


code:
# initializing here for reproducibility
pids = ['01','02']
prices = [10, [u'10', u'20', u'30']]
names = ['Orange','Banana']
df = pd.DataFrame({"product_id": pids, "prices": prices, "item_name": names})

rawDescription: Pandas write variable number of new rows from list in Series


code:
import re

INDENT_RE = re.compile(r'^\s*$')

def matching_indent(line, pattern):
    """
    Returns indent if line matches pattern, else returns None.
    """
    if line.endswith(pattern):
        indent = line[:-len(pattern)]
        if INDENT_RE.match(indent):
            return indent
    return None

def replace_line(lines, pattern, replacements):
    for line in lines:
        indent = matching_indent(line, pattern)
        if indent is None:
            yield line
        else:
            for replacement in replacements:
                yield indent + replacement

rawDescription: How can I keep the indentation between lines?

description: Keep the indentation between lines


code:
def print_tree(tree):
    result = ['
']
    for t in tree:
        result.append("
" + t['name'])
        if 'children' in t:
            result.append(print_tree(t['children']))
        result.append("
")
    result.append("
")
    return '\n'.join(result)

rawDescription: How to use a function with jinja2

description: Use a function with jinja2


rawDescription: Convert hex to BCD in python

description: Convert hex to BCD in python


code:
class c(object):
    def __init__(self, fun):
        self.fun = fun
        self.fun()

rawDescription: function as constructor parameter in python

description: Function as constructor parameter in python


rawDescription: Different Column values not displayed in PYGTK TreeView


code:
myString="['ASK', 'NOT', 'WHAT', 'YOUR', 'COUNTRY', 'CAN', 'DO', 'FOR', 'YOU']"
list(map(lambda x:x.strip("'"), myString.strip('"[]').split(", ")))

rawDescription: How do I convert this string to an array with all the proper formatting?

description: Convert this string to an array with all the proper formatting


code:
from itertools import chain

def lookup(entry):
    if isinstance(entry, str):
        entries = chain(index_on_1.get(entry, []), index_on_2.get(entry, []))
        return [yourstructure[i] for i in entries]
    else:
        return [yourstructure[i] for i in index_on_3.get(entry, [])]

rawDescription: How to assign a collection of 3 pieces of data

description: Assign a collection of 3 pieces of data


rawDescription: Partitioning a file for parallel download


code: h = lookup_escape('h')

rawDescription: Lookup escape filter method

description: Lookup escape filter method


code: port.write(hex("page 1"));

rawDescription: Send byte (0xFF) with Node.js through SerialPort


code:
p1 = tDict['Example']['points'][0]
p2 = tDict['Example']['points'][1]

rawDescription: Splitting one dictionary item into 2 variables


code:
import difflib

def show_diffs(limit):
    characters = 'abcdefghijklmnopqrstuvwxyz'
    differ = difflib.Differ()
    for length in range(1, limit + 1):
        for pos in range(0, length + 1):
            line_a = characters[:length]
            line_b = line_a[:pos] + 'A' + line_a[pos:]
            diff = list(differ.compare([line_a], [line_b]))
            if len(diff) == 2 and diff[0][0] == '-' and diff[1][0] == '+':
                marker = 'N'  # Insertion not detected
            elif len(diff) == 3 and diff[0][0] == '-' and diff[1][0] == '+' and diff[2][0] == '?':
                marker = 'Y'  # Insertion detected
            else:
                print('ERROR: unexpected diff for %r -> %r:\n%r' % (line_a, line_b, diff))
                return
            print('%s %r -> %r' % (marker, line_a, line_b))

show_diffs(limit=3)

rawDescription: Python difflib: not detecting changes

description: Python difflib: not detecting changes


code:
#!/usr/bin/env python

import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('127.0.0.1', 12345))

while True:
    dummy, addr = sock.recvfrom(1024)
    # work on files until done

rawDescription: Wait for signal to start generating data from another process in python


rawDescription: python regexp matching one or more characters in a group, except for particular alternatives

description: Python regexp matching one or more characters in a group, except for particular alternatives


code:
import numpy as np

a = np.random.rand(4, 4, 4)
ind = np.random.randint(0, 4, size=(4, 4, 4))

i0, i1, i2 = np.indices(a.shape)

b = a[ind, i1, i2]

rawDescription: Numpy fancy indexing suggestion needed

description: Numpy fancy indexing suggestion needed


rawDescription: Collecting results from a loop that returns NumPy Arrays


code:
@register.simple_tag(takes_context=True)
def include_fallback(context, *template_choices):
    t = django.template.loader.select_template(template_choices)
    return t.render(context)

rawDescription: Catching TemplateDoesNotExist in Django

description: Catching TemplateDoesNotExist in Django


code:
np.all(np.diff(base)==1)
np.sum(values)

rawDescription: numpy histogram cumulative density does not sum to 1

description: Numpy histogram cumulative density does not sum to 1


rawDescription: Finding minimum value element-wise in three 2d submatrices


rawDescription: Coverting a string to an array in python


code: keywords = itertools.product(alphabets, repeat = 3)

rawDescription: What is the best way to generate all possible three letter strings?


code:
if answerb == 'Call of duty' or answerb == 'call of duty' or answerb == 'Call Of Duty' or answerb == 'Call of Duty' or answerb == 'a' or answerb == 'a)':
    print("You are correct!")
    points = points + maxGuesses-guessesTaken

rawDescription: Python using variables and if statements


code:
from __future__ import print_function
print (1,2)

rawDescription: Should I use the print statement or function in Python 2.7?


code:
lecturers[lec_id] = Lecturer(lec_id, lec_name)
if lec_id in lecturers.keys():
    lecturers[lec_id].offered_proj.add(proj_id)

rawDescription: How do I create a list or set object in a class in Python?

description: Create a list or set object in a class in Python


code:
dm = pd.get_dummies(df.index.month).set_index(df.index)
dm

rawDescription: Pandas Dataframe - How To Convert Date to Boolean Columns?


code:
def __init__(self, queue, callb):
        super(Task2, self).__init__()
        self.queue = queue
        self.callb = callb

rawDescription: Python Process completion

description: Python Process completion


code:
def get_scores(x, kind):
    if x > 0:
        xp = int(input("What percentage are "+ kind + " weighted?"))
        return xp

rawDescription: Python - Get a function to use argument as string and int


code:
totaluniqueimp = db.alpha2.map_reduce(map, reduce, {
    out: "myresults",
    query: {'ts': {'$gt': 1345840456, '$lt': 2345762454}, 'cid': '2636518'}
}).count();

rawDescription: map_reduce() *and* find() in same query

description: Map_reduce() *and* find() in same query


code:
def add_bar_chrt(slide, tbl, size=10, color='pink'):
    return 'Created a {} barchart, with bars size {}'.format(size, color)

def add_column_chrt(slide, tbl, style='corinthyan', material='marble'):
    return 'Created a {} column chart, with {}-style plinths'.format(material, style)

chart_types = {
    'bar': add_bar_chrt,
    'column': add_column_chrt,
}
def chart_selector(slide, df_table, chart_type, *args, **kwargs):
    return chart_types[chart_type](slide, df_table, *args, **kwargs)

chart_selector('spam', 'eggs', 'bar')
chart_selector('spam', 'eggs', 'column', material='gold')

rawDescription: Python: setting a parameter for a function within a function


code: re.sub( "(?<=--out=)(.+)(?=\s)", "something", "--bass_cut_off=0 --out=sys_alg_oar_all_beds_IN10B0O_SP10F2H.wav" )

rawDescription: How to replace a words near the specific word in a text file using python

description: Replace a words near the specific word in a text file using python


code: ''.join([random.choice(y) for _ in xrange(x)])

rawDescription: "for in" with unused variable

description: "for in" with unused variable


code:
data = {}
data["people 1"] = {}
data["people 1"]["criteria a"] = "bla"
data["people 1"]["criteria b"] = "ble"
data["people 2"] = {}

rawDescription: Help for arrays: converting php code to python


code: next(e in lestring for e in lelist if e in lestring)

rawDescription: Python - Fastest way to check if a string contains specific characters in any of the items in a list


code:
from Selenium2Library import Selenium2Library

# create new class that inherits from Selenium2Library
class CustomSeleniumLibrary(Selenium2Library):
    # create a new keyword called "get webdriver instance"
    def get_webdriver_instance(self):
        return self._current_browser()

rawDescription: Pass existing Webdriver object to custom Python library for Robot Framework


code: ["fastq_quality_trimmer", "-Q", "33" "-v", "-t", "50", "-l", "20", "-i", leftInitial, "-o", leftTrimmed]

rawDescription: Problems capturing Python subprocess output on Mac OS X


rawDescription: cPickle.load() doesnt accept non-.gz files, what can I use for .pkl files?

description: CPickle.load() doesnt accept non-.gz files, what can I use for .pkl files


code:
from django.contrib import admin
class RelationAdmin(admin.ModelAdmin):
    form = RelationForm
    model = Relation

rawDescription: Django admin change form load quite slow


code:
binary(1)
binary(0.32)

rawDescription: Binary representation of float in Python (bits not hex)


code: x

rawDescription: Generating random numbers given required distribution and empirical sampling


code:
import cv2
import numpy

opencv_haystack =cv2.imread('haystack.jpg')
opencv_needle =cv2.imread('needle.jpg')

ngrey = cv2.cvtColor(opencv_needle, cv2.COLOR_BGR2GRAY)
hgrey = cv2.cvtColor(opencv_haystack, cv2.COLOR_BGR2GRAY)

# build feature detector and descriptor extractor
hessian_threshold = 5000
detector = cv2.SURF(hessian_threshold)
hkeypoints,hdescriptors = detector.detectAndCompute(hgrey,None)
nkeypoints,ndescriptors = detector.detectAndCompute(ngrey,None)

# extract vectors of size 64 from raw descriptors numpy arrays
rowsize = len(hdescriptors) / len(hkeypoints)
if rowsize > 1:
    hrows = numpy.array(hdescriptors, dtype = numpy.float32).reshape((-1, rowsize))
    nrows = numpy.array(ndescriptors, dtype = numpy.float32).reshape((-1, rowsize))
    #print hrows.shape, nrows.shape
else:
    hrows = numpy.array(hdescriptors, dtype = numpy.float32)
    nrows = numpy.array(ndescriptors, dtype = numpy.float32)
    rowsize = len(hrows[0])

# kNN training - learn mapping from hrow to hkeypoints index
samples = hrows
responses = numpy.arange(len(hkeypoints), dtype = numpy.float32)
#print len(samples), len(responses)
knn = cv2.KNearest()
knn.train(samples,responses)

# retrieve index and value through enumeration
for i, descriptor in enumerate(nrows):
    descriptor = numpy.array(descriptor, dtype = numpy.float32).reshape((1, rowsize))
    #print i, descriptor.shape, samples[0].shape
    retval, results, neigh_resp, dists = knn.find_nearest(descriptor, 1)
    res, dist =  int(results[0][0]), dists[0][0]
    #print res, dist

    if dist < 0.1:
        # draw matched keypoints in red color
        color = (0, 0, 255)
    else:
        # draw unmatched in blue color
        color = (255, 0, 0)
    # draw matched key points on haystack image
    x,y = hkeypoints[res].pt
    center = (int(x),int(y))
    cv2.circle(opencv_haystack,center,2,color,-1)
    # draw matched key points on needle image
    x,y = nkeypoints[i].pt
    center = (int(x),int(y))
    cv2.circle(opencv_needle,center,2,color,-1)

cv2.imshow('haystack',opencv_haystack)
cv2.imshow('needle',opencv_needle)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: SURF descriptors with opencv 2.4.6.1 and Python


code:
import csv

headers = ['some', 'column', 'headers', 'go', 'here']
with open('path/to/outfile.csv', 'w') as outf:
    writer = csv.writer(outf)
    writer.writerows(headers + all_data)

rawDescription: Print lots of info on a single line

description: Print lots of info on a single line


rawDescription: How can I convert a SHA256 hash from integer to string and back?

description: Convert a SHA256 hash from integer to string and back


code:
a = 5
p = np.random.randint(5, size=(a, 3))

rawDescription: Translating Matlab (Octave) group coloring code into python (numpy, pyplot)


code:
def splitWithAny(string, delimiters):
    "Splits the string with any of the strings of delimiters"
    return reduce(
        lambda iterable, delim: reduce(
            lambda lst,chunk: lst + chunk.split(delim),
            iterable,
            []),
        delimiters,
        [string])

def splitName(fileName):
    "Splits the fileName into smaller and hopefully significant chunks"
    delimiters = [" ", ".", "_", "-"]
    return filter(None, splitWithAny(fileName, delimiters))

rawDescription: My first Python program! Anyone care to review it an help me improve?


rawDescription: Python webcrawling BeautifulSoup: getting both text and links


code:
df
s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()
s.index = s.index.droplevel(-1) # to line up with df's index
s.name = 'Seatblocks' # needs a name to join
s
del df['Seatblocks']
df.join(s)

rawDescription: pandas: How do I split text in a column into multiple rows?

description: Pandas: How do I split text in a column into multiple rows


rawDescription: change the positions and the labels for clabel

description: Change the positions and the labels for clabel


code:
def quadratic_intersections(p, q):
    """Given two quadratics p and q, determines the points of intersection"""
    x = np.roots(np.asarray(p) - np.asarray(q))
    y = np.polyval(p, x)
    return x, y

rawDescription: How to find the points of intersection of a line and multiple curves in Python?

description: Find the points of intersection of a line and multiple curves in Python


code:
from itertools import cycle
myIterator = cycle(range(2))

myIterator.next()   # or next(myIterator) which works in Python 3.x. Yields 0
myIterator.next()   # or next(myIterator) which works in Python 3.x. Yields 1
# etc.

rawDescription: Python: How to toggle between two values


code:
from copy import deepcopy
cpy = deepcopy(instance)
cPickle.dump(cpy, open(filename, 'wb'), HIGHEST_PROTOCOL)
cpy = None

rawDescription: serialize class instance for comparison

description: Serialize class instance for comparison


code:
breaks=np.asarray(np.percentile(df.MAT,[25,50,75,100]))
df['Class']=(df.MAT.values>breaks[..., np.newaxis]).sum(0)
ax=df.boxplot(column='N0_YLDF',by='Class')
ax.xaxis.set_ticklabels(['%s'%val for val in breaks])

rawDescription: Boxplot stratified by column in python pandas


code:
"Hello, {foo}".format(**{'foo': 'bar'})
"Hello, %(foo)s!" % {'foo': 'bar'}

rawDescription: Better Method in Python to Call Changed Dict Values Than This?


code:
from mrjob.job import MRJob
import mrjob

class MRWordFrequencyCount(MRJob):
    INPUT_PROTOCOL = mrjob.protocol.RawProtocol

    def mapper(self, key, line):
        yield "constant", key
        yield "chars", len(line)
        yield "words", len(line.split())
        yield "lines", 1

    def reducer(self, key, values):
        if str(key) != "constant":
            yield key, sum(values)
        else:
            yield "constant",list(values)

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

rawDescription: Declare mrjob mapper without ignoring key


rawDescription: How do I create a dictionary mapping strings to sets given a list and a tuple of tuples?

description: Create a dictionary mapping strings to sets given a list and a tuple of tuples


code: p, success = optimize.leastsq(errorfunction, params, args=(x, y, data))

rawDescription: Python 2D Gaussian Fit with NaN Values in Data


rawDescription: How to append a file and take out a specific line python 3

description: Append a file and take out a specific line python 3


rawDescription: Generating cyclic permutations / reduced Latin Squares in Python


rawDescription: read the code from another python script

description: Read the code from another python script


code: diff = [right-left for left, right in zip(angles, angles[1:]+angles[:1])]

rawDescription: How to compare the last index to the first in a list whilst iterating, or looping

description: Compare the last index to the first in a list whilst iterating, or looping


code: [[Slot(self.world,i,j) for j in range(NUMROWS)] for i in range(NUMCOLS)]

rawDescription: What does this nested for-loops compacted into a single line mean? - python


code:
class WebSvc(models.Model):
    ...
    def __init__(*args, **kwargs):
        super(WebSvc, self).__init__(*args,**kwargs)
        self.state = self.caste().get_state()

rawDescription: "Annotating" querysets with model function returns


code:
my_cmap = plt.get_cmap('jet')
#my_nom = # you will need to scale your read data between [0, 1]
new_color = my_cmap(data2.T.ravel())
pc.update({'facecolors':new_color})

draw()

rawDescription: How to update pcolor in matplotlib?

description: Update pcolor in matplotlib


rawDescription: Summation of every row, column and diagonal in a 3x3 matrix numpy


code: numbers.findall("It took between 2.3 and 42.31 seconds")

rawDescription: Python: Strip Everything but Numbers

description: Python: Strip Everything but Numbers


rawDescription: Create a new array from numpy array based on the conditions from a list


code:
def groupings(lst, min_size):
    results = [tuple(lst)]
    for i in range(min_size, len(lst)):
        results.extend(combinations(lst, i))
    return results

rawDescription: How to get all combinations of list groupings of at least a certain size?

description: Get all combinations of list groupings of at least a certain size


code: [sum(tups, ()) for tups in product(*[(permutations(grp.index)) for (name, grp) in age])]

rawDescription: Quick way to find all permutations of a pandas DataFrame that preserves a sort?


rawDescription: apt like column output - python library

description: Apt like column output - python library


code:
# http://stackoverflow.com/q/3844948/
def checkEqualIvo(lst):
    return not lst or lst.count(lst[0]) == len(lst)

# http://stackoverflow.com/q/3844931/
def checkEqual6502(lst):
    return not lst or [lst[0]]*len(lst) == lst

rawDescription: check if all elements in a list are identical

description: Check if all elements in a list are identical


code:
class ModelByMakerList(generics.ListAPIView):
    serializer_class = ModelSerializer

    def get_queryset(self):
        """
        This view should return a list of all models by
        the maker passed in the URL
        """
        maker = self.kwargs['make']
        return Model.objects.filter(make=maker)

rawDescription: Django REST framework foreign keys and filtering


rawDescription: Similarity of lists in Python - comparing customers according to their features


code:
class Base(object):

    def sayHello(self, other=None):
        print("hello from {self} to {other}".format(self=self, other=other))
        return other
    def __str__(self):
        return type(self).__name__

class C1(Base):
    '''C1!'''

class C2(Base):
    '''C2!'''

c1 = C1()
c2 = C2()

c1.sayHello(c2).sayHello(c1)

rawDescription: Python - Method Chaining with instances from different Classes


rawDescription: Numpy.argmax() on certain axis in 2D matrix


code:
def cartesian_exponent(li, e=1):
    if e == 1:
        return [[x] for x in li]
    else:
        return [[x]+y for x in li for y in cartesian_exponent(li, e=e-1)]

rawDescription: how to permute n elements from list recursively in python?

description: Permute n elements from list recursively in python


code: allList = [x for x in itertools.chain(list1, list2, list3)]

rawDescription: how do I concatenate 3 lists using a list comprehension?

description: Concatenate 3 lists using a list comprehension


code:
mask = '001001'
num=12345678
"".join(x if y!='1' else '0' for x,y in izip_longest(str(num),mask,fillvalue="#"))

rawDescription: How to apply a mask to a number or string in Python?

description: Apply a mask to a number or string in Python


code:
from StringIO import StringIO

# Read each line of the PDF
pdfContent = StringIO(getPDFContent("test.pdf").encode("ascii", "ignore"))
for line in pdfContent:
    doSomething(line.strip())

rawDescription: How to read line by line in pdf file using PyPdf?

description: Read line by line in pdf file using PyPdf


code:
import sys
import win32com.client

shell = win32com.client.Dispatch("WScript.Shell")
shortcut = shell.CreateShortCut("t:\\test.lnk")
print(shortcut.Targetpath)

rawDescription: Reading the target of a .lnk file in Python?


rawDescription: Pandas long to wide reshape

description: Pandas long to wide reshape


rawDescription: Python3 & Tkinter, list.sort list of objects made of StringVar


code: type(data)

rawDescription: What is recommended way to store dictionaries and json file type in python


code: question = str(a) + b + str(c)

rawDescription: Python 3.5 Bracket and Speech Mark Removal from Lists


code:
import math
math.frexp(24.54883)  # significand and exponent
math.frexp(24.54883)[0]  # just the significand
int(math.frexp(24.54883)[0] * 2**4)  # most significant 4 bits

rawDescription: How can I get first n bits of floating point number as integer in python

description: Get first n bits of floating point number as integer in python


code: array = cursor.fetchall()

rawDescription: Improve loop efficiency

description: Improve loop efficiency


rawDescription: Spectrogram - Whitening out specific areas


code:
from matplotlib.pyplot import stem

stem(y, linefmt='b-', markerfmt='bo', basefmt='r-')
stem(x, y, linefmt='b-', markerfmt='bo', basefmt='r-')

rawDescription: Plotting PMF neatly in python

description: Plotting PMF neatly in python


rawDescription: Natural Join Implementation Python

description: Natural Join Implementation Python


code:
import pandas
my_file = 'example.csv'
df = pandas.read_csv(my_file)

rawDescription: Append String Split to Pandas DataFrame

description: Append String Split to Pandas DataFrame


code:
import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

rawDescription: Converting JSON String to Dictionary, Not List (Python)


code:
def localx(choice):
    if choice== 1:
        riddle()
    if choice== 2:
        mathschallenge()
    if choice== 3:
        tenquestions()

rawDescription: Passing a variable between functions

description: Passing a variable between functions


code:
class Maybe():
    def __init__(v):
        self.val = v
        self.isNothing = False
Nothing = Maybe(None)
Nothing.isNothing = True

def bind(val, func):
    if val.isNothing:
        return Nothing
    else:
        return(func(val.val))

rawDescription: simplifying maybe Monad

description: Simplifying maybe Monad


code:
from tkinter import *
from PIL import Image
from PIL import Image, ImageTk
import time, sys

def col():
    global count1,count,pix,x,root,img
    count1+=1
    print("("+str(count1)+")")
    count=-1
    for i in pix:
        count+=1
        #print(i)
        i+=10
        pix[count]=i

    #update the data in img and then paste it into photo
    img.putdata(pix)
    photo.paste(img)
    root.update()
    root.after(100, col)

root=Tk()

#load the image before making PhotoImage
img = Image.open("AI.gif")
pix=list(img.getdata())
width=img.size[0]
height=img.size[1]
#img.close() #don't close the image as you won't be able to modify it after closing

# do this part after defining img
photo = ImageTk.PhotoImage(img)
        # ^ use PIL's PhotoImage to use PIL operations on it
x=Label(root, compound="top", image=photo)
x.pack(side="right")

root.geometry((str(width)+"x"+str(height))+"-0+0")
root.update()

count1=0
col()

root.mainloop()

rawDescription: How do I save an image in python 3 using PIL?

description: Save an image in python 3 using PIL


code:
class EventManager(models.Manager):
    def bookings_today(self, location_id):
        # Construction of today_end / today_start as above, omitted for brevity
        return self.filter(location=location_id, start__lte=today_end, end__gte=today_start)

rawDescription: Django filter events occurring today

description: Django filter events occurring today


code:
import numpy as np
import pandas as pd

index = ['x', 'y']
columns = ['a','b','c']

# Option 1: Set the column names in the structured array's dtype
dtype = [('a','int32'), ('b','float32'), ('c','float32')]
values = np.zeros(2, dtype=dtype)
df = pd.DataFrame(values, index=index)

# Option 2: Alter the structured array's column names after it has been created
values = np.zeros(2, dtype='int32, float32, float32')
values.dtype.names = columns
df2 = pd.DataFrame(values, index=index, columns=columns)

# Option 3: Alter the DataFrame's column names after it has been created
values = np.zeros(2, dtype='int32, float32, float32')
df3 = pd.DataFrame(values, index=index)
df3.columns = columns

# Option 4: Use a dict of arrays, each of the right dtype:
df4 = pd.DataFrame(
    {'a': np.zeros(2, dtype='int32'),
     'b': np.zeros(2, dtype='float32'),
     'c': np.zeros(2, dtype='float32')}, index=index, columns=columns)

# Option 5: Concatenate DataFrames of the simple dtypes:
df5 = pd.concat([
    pd.DataFrame(np.zeros((2,), dtype='int32'), columns=['a']),
    pd.DataFrame(np.zeros((2,2), dtype='float32'), columns=['b','c'])], axis=1)

# Option 6: Alter the dtypes after the DataFrame has been formed. (This is not very efficient)
values2 = np.zeros((2, 3))
df6 = pd.DataFrame(values2, index=index, columns=columns)
for col, dtype in zip(df6.columns, 'int32 float32 float32'.split()):
    df6[col] = df6[col].astype(dtype)

rawDescription: Creating a Pandas DataFrame with a numpy array containing multiple types


code: df.loc[pos] = row

rawDescription: Creating a DataFrame using .loc to set with enlargement


rawDescription: Pandas Correlation Groupby

description: Pandas Correlation Groupby


rawDescription: iPython: Create variables that depend on the loop index

description: IPython: Create variables that depend on the loop index


code:
import numpy as np

mat = np.arange(12).reshape(2,6)

result = np.c_[(np.array(list(np.ndindex(mat.shape))), mat.ravel())]
print(result)

rawDescription: Vector (positionx,positiony,value) of a matrix python


rawDescription: tf-idf feature weights using sklearn.feature_extraction.text.TfidfVectorizer

description: Tf-idf feature weights using sklearn.feature_extraction.text.TfidfVectorizer


code:
import numpy as np
x = 1e9 * np.random.random(5)
x
np.set_printoptions(formatter={'float_kind':'{:f}'.format})
x

rawDescription: convert elements of an array from scientific notation to decimal notation in python

description: Convert elements of an array from scientific notation to decimal notation in python


code: set(['food', 'drink', 'vege'])

rawDescription: How to create a list while avoiding duplicate?

description: Create a list while avoiding duplicate


code: [[sum([x[1] for x in i])] for i in data]

rawDescription: Summing 2nd list items in a list of lists of lists


code:
img=imread(name)
f=figure(1)
imshow(img)
f.show()

img2=imread(name)
g=figure(2)
imshow(img2)
g.show()

rawDescription: Python, Pyplot - How to move two plots at the same time?


code:
class toy(object):
    pass

a = toy()
a.key1 = "hello world"
dir(a)

rawDescription: An approach to address html contents in a python class


code: sorted(ss, key= lambda x: x[0].time)

rawDescription: Sorting a list of UUID v1 in python

description: Sorting a list of UUID v1 in python


code:
# file: myspider.py
import json

from scrapy.http import Request
from scrapy.spider import BaseSpider

class MySpider(BaseSpider):
    name = 'myspider'
    start_urls = (
        # Add here more urls. Alternatively, make the start urls dynamic
        # reading them from a file, db or an external url.
        'https://www.facebook.com/TiltedKiltEsplanade',
    )

    graph_url = 'https://graph.facebook.com/{name}'
    feed_url = 'https://www.facebook.com/feeds/page.php?id={id}&format=rss20'

    def start_requests(self):
        for url in self.start_urls:
            # This assumes there is no trailing slash
            name = url.rpartition('/')[2]
            yield Request(self.graph_url.format(name=name), self.parse_graph)

    def parse_graph(self, response):
        data = json.loads(response.body)
        return Request(self.feed_url.format(id=data['id']), self.parse_feed)

    def parse_feed(self, response):
        # You can use the xml spider, xml selector or the feedparser module
        # to extract information from the feed.
        self.log('Got feed: %s' % response.body[:100])

rawDescription: Quickly mass scrape Facebook fan pages' numeric IDs


code:
def sum_col(filename, colnum):
    with open(filename) as inf:
        columns = zip(*[line.strip() for line in inf])
        return sum([int(num) for num in list(columns)[colnum]])

rawDescription: Converting string to float

description: Converting string to float


code: " ".join(s[i: i + 3] for i in range(0, len(s), 3))

rawDescription: Regex insert space every third character, except at end of line


code:
result = gb['Value'].unique()
type(result)
#pandas.core.series.Series

result = result.reset_index()
type(result)
#pandas.core.frame.DataFrame

rawDescription: Pandas DataFrame - Combining one column's values with same index into list


code:
x = np.random.randint(1, 63, 10)
y = np.random.randint(1, 63, 10)

dy, dx = [grid.astype(int) for grid in np.mgrid[-1:1:3j, -1:1:3j]]
Y = dy[None, :, :] + y[:, None, None]
X = dx[None, :, :] + x[:, None, None]

rawDescription: Slice subarray from numpy array by list of indices


code:
files = list_of_files
fd = nltk.FreqDist()
for file in files:
    with open(file) as f:
        for sent in nltk.sent_tokenize(f.lower()):
            for word in nltk.word_tokenize(sent):
                fd.inc(word)

rawDescription: How do I count words in an nltk plaintextcorpus faster?

description: Count words in an nltk plaintextcorpus faster


code:
import itertools

def process(lst):
    # Guard clause against empty lists
    if len(lst) < 1:
        return lst

    # use an object here to work around closure limitations
    state = type('State', (object,), dict(prev=lst[0], n=0))

    def grouper(x):
        if x < state.prev:
            state.n += 1

        state.prev = x
        return state.n

    return [ list(g) for k, g in itertools.groupby(lst, grouper) ]

data = [45,78,120,47,58,50,32,34]
print (list(process(data)))

rawDescription: Python: Find monotonic sequences in a list


rawDescription: What can I do with a closed file object?

description: What can I do with a closed file object


code:
import string
s="This char -- or that one -- It's a Space."
for k in [string.uppercase, string.lowercase, string.whitespace, string.punctuation]:
    len(filter(lambda x: x in k, s))

rawDescription: Writing a counting program in python

description: Writing a counting program in python


code: newfoo = foo.preprocess(Resize(100, 100), Cutoff(55))

rawDescription: Handling arguments in order for preprocessing in Python, when order matters


code: sess.run(weights['h1'][j, i])

rawDescription: How to quickly print Tensorflow results to TXT?

description: Quickly print Tensorflow results to TXT


code:
class BinFormatter(object):
    def __init__(self, v):
        self.v = v
    def __repr__(self):
        return '{:04b}'.format(self.v)

print([BinFormatter(v) for v in (10, 2)])

rawDescription: Inserting binary notation of numbers in python list


code:
from flask.ext.login import current_user

@lm.user_loader   # you should have same function
def load_user(user_id):
   return User.get_user(user_id)

@flask_app.before_request
def before_request():
    g.user = current_user # save current user in request context.

rawDescription: how can test u=g.user in Flask

description: How can test u=g.user in Flask


code: farglocker = ArgLocker() # for function `f()`

rawDescription: Garbage-collect a lock once no threads are asking for it


code: import pythonFunction

rawDescription: how to call a function from another file?

description: Call a function from another file


rawDescription: Cleanup A String from Most Simply

description: Cleanup A String from Most Simply


code:
samples_to_average = np.arange(5, 25, 5)

sample_average = mc.Lambda('sample_average', lambda x=list_of_samples, n=samples_to_average: [np.mean(x[:t]) for t in n])

rawDescription: Passing parameters to deterministic variables, pymc


rawDescription: Create a json tree from csv list in python


code:
idx = pd.IndexSlice
criterion = criterion['value']['count']
df2 = df.loc[idx[:,'2015-10-01':'2015-12-01'],:].groupby(level=0).sum()
df2[criterion].append(df3, ignore_index=False)

rawDescription: pandas, slice multi-index df with multiple conditions

description: Pandas, slice multi-index df with multiple conditions


code:
from threading import Event, Thread

def call_repeatedly(interval, func, *args):
    stopped = Event()
    def loop():
        while not stopped.wait(interval): # the first call is in `interval` secs
            func(*args)
    Thread(target=loop).start()
    return stopped.set

rawDescription: Improve current implementation of a setInterval python


code:
@login_required
def home(request):
    dishes = Dishes.objects.all()
    return_list = []
    for dish in dishes:
        return_list.append((dish,
                            Likes.objects.filter(user=request.user, dish=dish)))
    return render(request, 'dish_list.html', {'dishes': return_list})

rawDescription: How to show whether user already liked object instance in Django

description: Show whether user already liked object instance in Django


code:
a = fixedint.UInt32(14)
a
a << 2

rawDescription: Fixed width integer types (e.g. uint32) in Python


rawDescription: From Matlab to Python - Solve function

description: From Matlab to Python - Solve function


code:
import subprocess
subprocess.check_output('ps -eo pcpu,pid,user,args | sort -k 1 -r | head -3',
                        shell=True)

rawDescription: piping in shell via Python subprocess module

description: Piping in shell via Python subprocess module


code:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage'

rawDescription: How can I use django-storages for both media and static files?

description: Use django-storages for both media and static files


code:
dic = {'list_1':[3, 'green', 'yellow', 'black'], 'list_2':[2, 'green', 'blue']}
set().union(*(x[1:] for x in dic.itervalues()))

rawDescription: Iterating over a dictionary of list elements


code:
m["Top 5"]= l
k = json.dumps(m)

rawDescription: convert a dict to sorted dict in python

description: Convert a dict to sorted dict in python


code:
df["IndepFlag"] = df.Independent.where((df.Independent == 0) | (df.Independent == 1)).notnull().astype(int)
df

rawDescription: Pandas if statements

description: Pandas if statements


rawDescription: Finding and uninstalling PIL on Mac

description: Finding and uninstalling PIL on Mac


rawDescription: Keep QTableView scrolling to the last row when the model is growing


code: dct = {name: classthing(inputs) for name in listofstuff}

rawDescription: Convert list of strings into objects

description: Convert list of strings into objects


code:
def as_float_array(a):
    "View the quaternion array as an array of floats with one extra dimension of size 4"
    return a.view(np.float).reshape(a.shape+(4,))

rawDescription: Creating new numpy scalar through C API and implementing a custom view


code:
def parse(infile):
    returning = False
    trial = None
    for line in infile:
        line = line.rstrip()
        if not line:
            continue

        if line.startswith('handle:'):
            trial = line[len('handle:'):]

        if line.startswith('goaly:'):
            returning = True
        elif line.startswith('pauseTimes:'):
            returning = False

        if returning:
            yield trial, line

rawDescription: Extracting information between strings in a text file


rawDescription: Efficient way of appending / extracting list elements


code:
# newcert.py
from twisted.python.filepath import FilePath
from twisted.internet.ssl import PrivateCertificate, KeyPair, DN

def getCAPrivateCert():
    privatePath = FilePath(b"ca-private-cert.pem")
    if privatePath.exists():
        return PrivateCertificate.loadPEM(privatePath.getContent())
    else:
        caKey = KeyPair.generate(size=4096)
        caCert = caKey.selfSignedCert(1, CN="the-authority")
        privatePath.setContent(caCert.dumpPEM())
        return caCert

def clientCertFor(name):
    signingCert = getCAPrivateCert()
    clientKey = KeyPair.generate(size=4096)
    csr = clientKey.requestObject(DN(CN=name), "sha1")
    clientCert = signingCert.signRequestObject(
        csr, serialNumber=1, digestAlgorithm="sha1")
    return PrivateCertificate.fromCertificateAndKeyPair(clientCert, clientKey)

if __name__ == '__main__':
    import sys
    name = sys.argv[1]
    pem = clientCertFor(name.encode("utf-8")).dumpPEM()
    FilePath(name.encode("utf-8") + b".client.private.pem").setContent(pem)

rawDescription: Use TLS and Python for authentication

description: Use TLS and Python for authentication


code:
with open("test.txt") as f:
    r = re.compile("(\d+)")
    for line in f:
        a, b = line.lstrip("0123456789. ").split(">> ")
        a_keys = [int(i.group()) for i in r.finditer(a)]
        b_keys = [int(i.group()) for i in r.finditer(b)]
        a = a.strip("()\n").split(",")
        b = b.strip("()\n").split(",")
        for ele, k in zip(a, a_keys):
            ind = bisect(b_keys, k, hi=len(b) - 1)
            ind -= k - b_keys[ind] < b_keys[ind-1] - k
            print("{} -> {}".format(ele, b[ind] if abs(b_keys[ind] - k) < 5 else "NULL"))

rawDescription: Using bisect for combing items with a distance condition


code:
with api.app.test_client() as client:
    rv = client.get('/api/v1.0/worker/bbc-stage-0')

# assert something about the response, such as 'expected string' in rv.data

rawDescription: How to unit test view_func in url rule?

description: Unit test view_func in url rule


code:
def fs(x, p):
     p = re.sub('\s+', '', p) # get rid of spaces ...
     if re.search('[0-9]+'+x, p): # exp = (n digits) + (tag 'x')
         return int( re.search('[0-9]+'+x, p).group()[:-len(x)] )
     else: return 0

rawDescription: Python convert time duration in words to seconds


code:
def foo(a, b):
    return str(a) + ", " + str(b)

rawDescription: Need an easy way to embedd IronPython with C++ CLI


code:
class Comment(object):
    all_comments = []

    def __init__(self, message, parent):
        self.message = message
        self.parent = parent
        self.all_comments.append(self)

    def __iter__(self):
        """
        Yields tuples of (indentation level, comments), with this comment first
        and child comments later.
        """
        # what goes here?

rawDescription: A complex ordering algorithm for a Python list?


code:
df['new'] = drop_rows(df.date,df.Subject)
df = df[ df['new'].notnull() ]

rawDescription: drop values on datetime difference, with revision

description: Drop values on datetime difference, with revision


code:
for (item, value) in config.items(section):
    # the function returns at the end of the 1st iteration
    # hence you get only 1 tuple.
    # You may also consider using a generator & 'yield'ing the tuples
    return (item, value)

rawDescription: Python - Return values from a function

description: Python - Return values from a function


code:
import subprocess
for i in range(len(operations)):
    command = ['python','myScript.py','arg1','arg2']
    subprocess.call(command)

rawDescription: Launch a single python script as different processes differing by command line arguments


rawDescription: Python: find difference in dicts

description: Python: find difference in dicts


code:
import random # import once

def genDigit():
    digit = random.randint(0, 9)
    return digit # return the digit

def genNumber():
    numList = list() # add missing ()
    for counter in range(0,4):
        numList.append(genDigit()) # add digits to list
    return numList # return the list

print(genNumber()) # now print the entire list

rawDescription: Appending result of function into a list


code: newJSONObject = json.dumps(zenJSONObj, sort_keys=True, indent=4)

rawDescription: Getting Deeper Level JSON Values in Python


rawDescription: Python generate from list instead of Genfromtext


code: sizer_2.Add(self.panel_1, 1, wx.EXPAND, 0)

rawDescription: Error with wxpython sizers

description: Error with wxpython sizers


code:
from plotly.offline import iplot, init_notebook_mode
from plotly.graph_objs import Mesh3d
from numpy import sin, cos, pi

# some math: generate points on the surface of ellipsoid

phi = np.linspace(0, 2*pi)
theta = np.linspace(-pi/2, pi/2)
phi, theta=np.meshgrid(phi, theta)

x = cos(theta) * sin(phi) * 3
y = cos(theta) * cos(phi) * 2
z = sin(theta)

# to use with Jupyter notebook

init_notebook_mode()

iplot([Mesh3d({
                'x': x.flatten(),
                'y': y.flatten(),
                'z': z.flatten(),
                'alphahull': 0
})])

rawDescription: How to draw ellipsoid with plotly

description: Draw ellipsoid with plotly


code: re.sub(r'\ba\b', 'an', "a bridge")

rawDescription: Replacing regex with new regex

description: Replacing regex with new regex


rawDescription: To fill the missing data lines with pandas reindex function


rawDescription: Python reading X and Y values and assigning to Z specific X Y pairs


code:
import urllib2

word_site = "http://www.freebsd.org/cgi/cvsweb.cgi/src/share/dict/web2?rev=1.12;content-type=text%2Fplain"

response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()

rawDescription: Random word generator- Python

description: Random word generator- Python


code:
import numpy as np
deltas=np.diff(data)
deltas[deltas<0]=0
deltas[deltas>100]=0

rawDescription: Can I cleanse a numpy array without a loop?

description: Cleanse a numpy array without a loop


rawDescription: Obfuscated mandlebrot function - can someone deobfuscate it?


code:
from os import system
...
system("xdotool windowunmap --sync " + str(client.window.id))
system("xdotool windowmap   --sync " + str(client.window.id))

rawDescription: How to move or resize X11 windows (even if they are maximized)?

description: Move or resize X11 windows (even if they are maximized)


code:
np.in1d(a,b)
a[np.in1d(a,b)] = 0
a

rawDescription: change value in numpy array based on presence in another array

description: Change value in numpy array based on presence in another array


code: sum(1 for c1, c2 in itertools.izip(s1, s2) if c1 == c2)

rawDescription: How do I count the number of identical characters in a string by position using python?

description: Count the number of identical characters in a string by position using python


code:
import numpy as np
import pandas as pd

# arbitrary hourly time series data (from 11/9/2014 to 1/17/15)
time = pd.date_range(start='20141109', end='20150117', freq='H')[:-1]

# sinusoidal "pressure" data with minor noise added
x = np.linspace(-2*np.pi, 2*np.pi, num=time.size)
pressure = np.sin(x) + 100
noise = np.random.normal(0, 0.1, pressure.size)
noisy_pressure = pressure + noise

rawDescription: Plotting colormap graph for each day side by side


code:
def is_enabled(info, request):
    return True if route_should_be_enabled else False

config.add_route('my_plugin_head', '/foo/{bar}', custom_predicates=[is_enabled])

rawDescription: Adding routes dynamically to pyramid

description: Adding routes dynamically to pyramid


code:
import copy

class Dict(dict):

  def __add__(self, other):
    ret = copy.copy(self)
    ret.update(other)
    return ret

d1 = Dict({1: 2, 3: 4})
d2 = Dict({3: 10, 4: 20})
print(d1 + d2)

rawDescription: Override operator of built-in object

description: Override operator of built-in object


code:
cols = ['var' + str(n) for n in range(1, 3 + 1)]
cols
Out[9]: ['var1', 'var2', 'var3']

df[cols].sum(axis='columns')

rawDescription: Elegantly summing named DataFrame columns in python


code: intensitiesshaped = np.reshape(intensities, (len(unique_x),len(unique_y),-1))

rawDescription: Loading .txt data into 10x256 3d numpy array


code:
def wow(amount):
    if amount <= 0:
        return
    else:
        print("Wow! \n")
        return wow(amount - 1)

rawDescription: Recursive function without return - Python 2.7


rawDescription: Appending a value to a key in Python?

description: Appending a value to a key in Python


code:
from lxml import etree
xmldoc = etree.parse("tweets.xml")

tweets = xmldoc.xpath("/tweets/tweet/content/text()")

rawDescription: How to dynamicaly create a variable in a for?

description: Dynamicaly create a variable in a for


code:
from tkinter import Tk, Entry, END    # Python3. For Python2.x, import Tkinter.

# Use this as a flag to indicate if the box was clicked.
global clicked
clicked = False

# Delete the contents of the Entry widget. Use the flag
# so that this only happens the first time.
def callback(event):
    global clicked
    if (clicked == False):
        box[0].delete(0, END)         #
        box[0].config(fg = "black")   # Change the colour of the text here.
        clicked = True

root = Tk()
box = []                              # Declare a list for the Entry widgets.

box.append(Entry(fg = "gray"))        # Create an Entry box with gray text.
box[0].bind("<Button-1>", callback)   # Bind a mouse-click to the callback function.
box[0].insert(0, "Value 1")           # Set default text at cursor position 0.

box.append(Entry(fg = "gray"))        # Make a 2nd Entry; store a reference to it in box.
box[1].insert(0, "Value 2")

box[0].pack()                         #
box[1].pack()

if __name__ == "__main__":
    root.mainloop()

rawDescription: Default text as well as list textvariable Entry widget Tkinter


code:
class RequiredIf(Required):
    # a validator which makes a field required if
    # another field is set and has a truthy value

    def __init__(self, other_field_name, *args, **kwargs):
        self.other_field_name = other_field_name
        super(RequiredIf, self).__init__(*args, **kwargs)

    def __call__(self, form, field):
        other_field = form._fields.get(self.other_field_name)
        if other_field is None:
            raise Exception('no field named "%s" in form' % self.other_field_name)
        if bool(other_field.data):
            super(RequiredIf, self).__call__(form, field)

rawDescription: How to make a field conditionally optional in WTForms?

description: Make a field conditionally optional in WTForms


code: size = fields.IntegerRangeField(min_value=-100, max_value=100)

rawDescription: How to limit the maximum value of a numeric field in a Django model?

description: Limit the maximum value of a numeric field in a Django model


code:
class Country(object):

# ...

    def get_density(self):
        return self.population / self.area

rawDescription: reading file into a dictionary

description: Reading file into a dictionary


code: plt.plot(nth_value_plot, "o")

rawDescription: matplotlib plotting a dot every nth x

description: Matplotlib plotting a dot every nth x


code: id(np.nan) == id(np.nan)

rawDescription: NaNs comparing equal in Numpy

description: NaNs comparing equal in Numpy


code:
from itertools import dropwhile

def get_links(s):
    without_paren = r'<a href="(?P<WITHOUT_PAREN>[^"]+)">'
    with_paren = r'\(.*?<a href="(?P<WITH_PAREN>[^"]+)">.*?\)'
    master_pattern = with_paren + '|' + without_paren  # try with_paren first
    it = re.finditer(master_pattern, s)
    # Drop matches in `it` until we hit the first without_paren match
    # and yield every match from there onwards
    for mo in dropwhile(lambda mo: mo.lastgroup == 'WITH_PAREN', it):
        yield mo.group(mo.lastgroup)

rawDescription: Matching all links, except the ones at the beginning in parentheses


rawDescription: Prevent OS X from going to sleep with Python?


code:
output_vals = (l.split(None, 2) for l in path_output)
d = dict((var, rest) for var, equals, rest in output_vals)

rawDescription: Using Python2.6 to Parse Bash Output

description: Using Python2.6 to Parse Bash Output


code:
with open("AllText.txt") as fp:
    whole_file_text = fp.read()

rawDescription: Read text file as a whole

description: Read text file as a whole


rawDescription: Ignoring zero by division instances in script


code: {'networks': {'prod': 'value'}, 'services': {'web': {'name': 'new'}}}

rawDescription: Use list of indices to manipulate a nested dictionary


code:
c = dict(a,**b)
type(c)  #returns a dict

rawDescription: update method of python dictionary did not work

description: Update method of python dictionary did not work


code:
class A():  my_attr = 'foo'
class B(A): pass

rawDescription: python - class instance variable inherence and class variable inherence

description: Python - class instance variable inherence and class variable inherence


code:
import math
import multiprocessing

def prime_list2(arg):
    start, num = arg # Unpack the tuple.
    if num < 3:
        raise ValueError('this function only accepts arguments > 2')
    if start < 3:
       start = 3
    candidates = range(start, num+1, 2)
    L = [c for c in candidates if all(c % p != 0 for p in
         range(3, int(math.sqrt(c))+1, 2))]
    if start < 3:
        L = [2] + L
    return L

data = [(n*100000+1, (n+1)*100000+1) for n in range(0,10)]
p = multiprocessing.Pool()
rv = p.map(prime_list2, data)
print('len(rv)=', len(rv))
for i, v in enumerate(rv):
    print('rv[{}][:10] ='.format(i), v[:10])

rawDescription: Python 3 multiprocessing only using one core with 4 threads open


rawDescription: Reduce array over ranges

description: Reduce array over ranges


code:
name = 'Albus Percival Wulfric Brian, Dumbledore'
', '.join(reversed(name.split(', ')))

rawDescription: Swapping first and last name positions

description: Swapping first and last name positions


code:
help
help(zip)

rawDescription: Python: Function Documentation

description: Python: Function Documentation


code:
response = [
    {'country': 'KR', 'values': ['Server1']},
    {'country': 'IE', 'values': ['Server1', 'Server3', 'Server2']},
    {'country': 'IE', 'values': ['Server1', 'Server3']},
    {'country': 'DE', 'values': ['Server1']},
    {'country': 'DE', 'values': ['Server2']},
]

rawDescription: How to carry out this aggregation in python

description: Carry out this aggregation in python


code: splitted

rawDescription: Trying to create a list of users in AD

description: Trying to create a list of users in AD


code:
{'alice': trueskill.Rating(mu=23.967, sigma=4.088),
 'bob': trueskill.Rating(mu=36.119, sigma=5.434),
 'carol': trueskill.Rating(mu=29.226, sigma=5.342),
 'eve': trueskill.Rating(mu=16.740, sigma=4.438),
 'ted': trueskill.Rating(mu=21.013, sigma=5.150)}

rawDescription: Python Trueskill - Using Dictionaries

description: Python Trueskill - Using Dictionaries


code:
ListenerBase = win32com.client.getevents("SAPI.SpInProcRecoContext")
class Listener(ListenerBase):
    def OnRecognition(self, _1, _2, _3, Result):
        """Callback whenever something is recognized."""
        # Work with Result

    def OnHypothesis(self, _1, _2, Result):
        """Callback whenever we have a potential match."""
        # Work with Result

rawDescription: Consuming COM events in Python

description: Consuming COM events in Python


code: ",".join(["{" + e + "}" for e in myList])

rawDescription: Mapping and joining a python list

description: Mapping and joining a python list


code:
import matplotlib.pyplot as plt

plt.figure()
for i in range(0,19):
    plt.plot((-0.1, 0.6),(i, i), color=((20-i)/20., 0, i/20.))
plt.ylim([0,20])
plt.xlim([-0.1,0.6])
plt.xlabel('Posicion [m]')
plt.ylabel('Velocidad [m/s]')
plt.show()

rawDescription: Graphic with color gradient in python

description: Graphic with color gradient in python


code:
import SendKeys
SendKeys.SendKeys("Hello world")

rawDescription: How can I paste some string to the active window in Python?

description: Paste some string to the active window in Python


code: not None

rawDescription: does adding element to a set return true if it is successful in python?

description: Does adding element to a set return true if it is successful in python


code:
import numpy as np

def magic_add(*args):
    n = max(a.ndim for a in args)
    args = [a.reshape((n - a.ndim)*(1,) + a.shape) for a in args]
    shape = np.max([a.shape for a in args], 0)
    result = np.zeros(shape)

    for a in args:
        idx = tuple(slice(i) for i in a.shape)
        result[idx] += a
    return result

rawDescription: adding numpy arrays of differing shapes

description: Adding numpy arrays of differing shapes


code:
def read_lines_with_duplicate_replace_v1(path,replace_char="X"):
    """Generator that read the lines in the file contained in path
       and for each line that start as some previous line replace each
       part that is similar with replace_char. Yield a list with the result"""
    #assume that each line has the same number of elements
    record=dict()
    with open(path) as file:
        for line in file:
            result  = line.split()
            temp = tuple(result)
            if temp[0] in record:
                key = result[0]
                result[0] = replace_char
                for i in range(1,len(result)):
                    if result[i] == record[key][i-1]:
                        result[i] = replace_char
                    else:
                        break
            record[temp[0]] = temp[1:]
            yield result

rawDescription: Python-Replacing Duplicatte information in a Text file


code: data='{"username": "jackripper@example.com", "password": "crm114"}',

rawDescription: Bad Request when posting JSON to Flask endpoint in unit test


rawDescription: How do I disable log messages from the Requests library?

description: Disable log messages from the Requests library


code:
wordsCount = {}
words = []  # list of words
for word in words:
  if word not in wordsCount:
    wordsCount[word] = 0
  wordsCount[word] += 1

rawDescription: python dictionary counting how many times a word occurs and linking to the word in a dictionary

description: Python dictionary counting how many times a word occurs and linking to the word in a dictionary


code: output = input[np.where(index)[0]]

rawDescription: Get a subarray from a numpy array based on index


rawDescription: Can't return the list I want

description: Can't return the list I want


rawDescription: Returning python object in httpresponse

description: Returning python object in httpresponse


code:
a = np.array([1,2,3])
b = np.array([1,2,3])
np.dot(a, b)
np.inner(a, b)

rawDescription: numpy: 1D array with various shape

description: Numpy: 1D array with various shape


rawDescription: Curency Rate Conversion Wrong Base Currency


code:
import numpy as np
df = pd.DataFrame({'a': [1, 2, 3], 'b': ['a', 'b', 'c']}, index=[10, 2, 7])

np.where( df.a>=2)

rawDescription: Get DataFrame selection's row posititions


code:
def cmp_tasks(a,b):
    a = a.split('.')
    b = b.split('.')
    if len(a) == len(b):
        ret = cmp(int(a[0]),int(b[0]))
        if not ret:
            return cmp(int(a[1]),int(b[1]))
        return ret
    else:
        return cmp(int(a[0]),int(b[0]))

rawDescription: Python way of getting max of list containing integers and floats


code:
class ConfigurationSerializer(serializers.ModelSerializer):
    parameters = ParametersField(source="parameter_set")

    class Meta:
        model = Configuration
        fields = ('id', 'version', 'resource', 'option', 'name', 'parameters')

rawDescription: How to serializer/deserialize Django models

description: Serializer/deserialize Django models


code:
m.submit_form(form_find_b)
m.url
m.parsed.findAll('div', id='PhoneListsControl_phoneListMembersText')
m.parsed.findAll('input', id='PhoneListsControl_phoneListDetail__ctl2_number')

rawDescription: Python - Requests/RoboBrowser - ASPX POST JavaScript


code:
if not madeSwap:
                return

rawDescription: List sorting with bubble sort (list of list)


code: p2 = pd.Panel(newd)

rawDescription: Python - Add a column to each dataframe of a Pandas Panel


code:
def sine_example():
    net = Neuralnet([1, 6, 1])
    for step in range(100000):
        x = np.random.normal()
        net.feedforward([x])
        net.backpropagate([np.tanh(np.sin(x))])
    net.feedforward([3])
    print(net.outputs[-1])

rawDescription: Neural network backpropagation algorithm not working in Python


code:
# iterate over each sublist
for sub in myList:
    # check every element in each sublist for "RND"
    # if we find a match print the next element in the list
    for ind, ele in enumerate(sub,1):
        if ele == "RND":
            print(sub[ind])

rawDescription: Getting more than one number after specific string


rawDescription: Removing double quotes after json

description: Removing double quotes after json


code:
g = df.groupby(["WEEK_END_DATE", "TITLE_SHORT"]).sum().reset_index()
g

rawDescription: Pandas Shaping Data for Covariance

description: Pandas Shaping Data for Covariance


code:
def groupIt(lst, out=None):
    if out is None:
        out = set()
    out.add(int("".join(map(str, sorted(lst)))))
    if len(lst) > 1:
        for i in range(len(lst)-1):
            n = lst[i] * lst[i+1]
            if n < 10:
                groups(lst[:i] + [n] + lst[i+2:], out)
    return min(out)

rawDescription: Python For Loop includes the end of the range


code:
POST /demo/doc/1
{
    "title": "testing123"
}

rawDescription: Elasticsearch - Not require an exact match


rawDescription: How do I get rid of dotted line on x axis of Pandas/Matplotlib bar plot?

description: Get rid of dotted line on x axis of Pandas/Matplotlib bar plot


code:
'   spacious   '.lstrip()
'www.example.com'.lstrip('cmowz.')

rawDescription: Equivalent of str.lstrip(char) in jython < 2.1


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

while True:
    line = sys.stdin.readline()
    if not line:
        break
    sys.stdout.write(line) # or print, doesn't matter.

rawDescription: immediate piping with python

description: Immediate piping with python


rawDescription: Python convert a bytearray to hex array

description: Python convert a bytearray to hex array


rawDescription: Scanning two integers separated by an unknown character


code:
import tkinter as tk

s = '\U0001d412\U0001d413\U0001d400\U0001d402\U0001d40a\U0001d40e\U0001d415\U0001d404\U0001d411\U0001d405\U0001d40b\U0001d40e\U0001d416.\U0001d402\U0001d40e\U0001d40c'

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = s
        self.hi_there["command"] = self.say_hi
        self.hi_there.pack(side="top")

        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="bottom")

    def say_hi(self):
        print("hi there, everyone!")

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

rawDescription: How do I get tkinter to display these unicode characters?

description: Get tkinter to display these unicode characters


rawDescription: I cannot print the final value of a variable


code: {{ myvariable|safe }}

rawDescription: How to render formatted data to html in Python Flask Framwork?

description: Render formatted data to html in Python Flask Framwork


code:
cities = getCities()

for c in cities :
    c.retrieveTemps()
    print(c.name,c.high0,c.low0,c.high1,c.low1,c.weather0,c.weather1,c.wind0,c.wind1)

rawDescription: Writing a method that I can call in a separate script in python


rawDescription: Getting method calls and their arguments from method object


rawDescription: python : generate sublists depending on the elements values

description: Python : generate sublists depending on the elements values


code: from OpenGL.GL import *

rawDescription: NameError when running pyOpenGL

description: NameError when running pyOpenGL


code: [(x,y) for x in lista for y in listb]

rawDescription: python: combining lists and strings

description: Python: combining lists and strings


code:
import base64

with open(img_input, "rb") as f:
    with open(img_output_b64, "wb") as f2:
        f2.write(base64.b64encode(f.read()))

rawDescription: How can I pack images? -Pygame -PyInstaller

description: Pack images? -Pygame -PyInstaller


code:
TEMPLATE_CONTEXT_PROCESSORS = (
"django.contrib.auth.context_processors.auth",
"django.core.context_processors.debug",
"django.core.context_processors.i18n",
"django.core.context_processors.media",
"django.core.context_processors.static",
"django.core.context_processors.request",
"django.contrib.messages.context_processors.messages",
"main_app.context_processor.NavbarContext",)

rawDescription: Empty {{ MEDIA_URL }} tag, caused by transitioning from Django 1.7.2 to 1.8


code:
df
df.loc[df.E == "test", "C"] = -1
df

rawDescription: Pandas Multiple Conditions Function based on Column


code:
dict1 = {
        'medic1' : {'date' : '02/02/2015', 'no' : '123' },
        'medic2' : {'date' : '02/03/2015', 'no' : '456' },
        'testkey1': 'testvalue1',
        'testkey2': 'testvalue2',
        'testkey3':{ "level2_1":"value2_1",
            "level2_2":{
                        "level3_1": "value3_1_change",
                        "level3_2": "value3_2",
                    }
        }
}

dict2 = {
        'medic1' : {'date' : '02/02/2015', 'no' : '456' },
        'medic2' : {'date' : '02/03/2015', 'no' : '456' },
        'testkey1': 'testvalue1',
        'testkey2': 'testvalue22',
        'testkey3':{ "level2_1":"value2_1",
                    "level2_2":{
                                "level3_1": "value3_1",
                                "level3_2": "value3_2",
                            }
                }

}

import copy

def compareDict(dict1, dict2):

    d1_keys = dict1.keys()
    d2_keys = dict2.keys()
    intersect_keys = set(d1_keys).intersection(set(d2_keys))
    modified = {}
    for i in intersect_keys:
        if dict1[i] != dict2[i] :
            if isinstance(dict1[i], dict) and isinstance(dict1[i], dict):
                modified[i]=compareDict(dict1[i], dict2[i])
            else:
                modified.update({i : (dict1[i], dict2[i])})

    return copy.deepcopy(modified)

modified = compareDict(dict1, dict2)
import pprint
pprint.pprint(modified)

rawDescription: compare two dictionaries in python

description: Compare two dictionaries in python


code: re.findall(r'{[^}]*}|\b\w+\b', '{Łatwe|Proste} szukanie mieszkania {Sprawdź|Wypróbuj juz dziś}, znalezienie {wcale|w ogóle}')

rawDescription: Python string split using regex

description: Python string split using regex


code:
import re
grps = re.compile(r'CN=(\w+)').findall

def anyof(short_group_list, adu):
  all_groups_of_user = set(g for gs in adu.get('memberOf',()) for g in grps(gs))
  return sorted(all_groups_of_user.intersection(short_group_list))

rawDescription: Finding partial strings in a list of strings - python


code: func()

rawDescription: Python append function as dot notation

description: Python append function as dot notation


code:
s1=set(x for x in string.printable)
s2=set(chr(x) for x in range(32,127))
s1-s2

rawDescription: Python: How to import ascii characters

description: Python: How to import ascii characters


code:
[{u'isChecked': False,
  u'isClosed': False,
  u'offerDetails': [{u'basePrice': 980,
                     u'conditionalPrice': 980,
                     u'contractLength': [u'None'],
                     u'contractLengthCount': 1,
                     u'coolingOffPeriod': 10,
                     u'estimatedSolarCredit': 0,
                     u'exitFee': [0],
                     u'exitFeeCount': 1,
                     u'fullDiscountedPrice': 660,
                     u'greenPower': 0,
                     u'greenpowerAmount': 0,
                     u'greenpowerChargeType': None,
                     u'hasIncentive': False,
                     u'hasPayOnTimeDiscount': True,
                     u'intrinsicGreenpowerPercentage': u'0.0000',
                     u'isDirectDebitOnly': False,
                     u'isPartDual': False,
                     u'isTouOffer': False,
                     u'offerId': u'GLO40961MR',
                     u'offerKey': u'7636',
                     u'offerName': u'GLO SWITCH',
                     u'offerType': u'Market offer',
                     u'retailerId': u'31206',
                     u'retailerImageUrl': u'img/retailers/big/globird.jpg',
                     u'retailerName': u'GloBird Energy',
                     u'retailerPhone': u'(03) 8560 4199',
                     u'retailerUrl': u'http://www.globirdenergy.com.au/switchon/',
                     u'solarType': None,
                     u'tariffDetails': {},
                     u'tariffType': u'Single rate',
                     u'timeDefinition': u'Local time'}],
  u'offerFuelType': 0},
 {u'isChecked': False,
  u'isClosed': False,
  u'offerDetails': [{u'basePrice': 1080,
                     u'conditionalPrice': 1080,
                     u'contractLength': [u'None'],
                     u'contractLengthCount': 1,
                     u'coolingOffPeriod': 10,
                     u'estimatedSolarCredit': 0,
                     u'exitFee': [0],
                     u'exitFeeCount': 1,
                     u'fullDiscountedPrice': 720,
                     u'greenPower': 0,
                     u'greenpowerAmount': 0,
                     u'greenpowerChargeType': None,
                     u'hasIncentive': False,
                     u'hasPayOnTimeDiscount': True,
                     u'intrinsicGreenpowerPercentage': u'0.0000',
                     u'isDirectDebitOnly': False,
                     u'isPartDual': False,
                     u'isTouOffer': True,
                     u'offerId': u'GLO41009MR',
                     u'offerKey': u'7642',
                     u'offerName': u'GLO SWITCH',
                     u'offerType': u'Market offer',
                     u'retailerId': u'31206',
                     u'retailerImageUrl': u'img/retailers/big/globird.jpg',
                     u'retailerName': u'GloBird Energy',
                     u'retailerPhone': u'(03) 8560 4199',
                     u'retailerUrl': u'http://www.globirdenergy.com.au/switchon/',
                     u'solarType': None,
                     u'tariffDetails': {},
                     u'tariffType': u'Time of use',
                     u'timeDefinition': u'Local time'}],
  u'offerFuelType': 0}]

rawDescription: Multi POST query (session mode)

description: Multi POST query (session mode)


code:
li = [("I'm", 'using'), ('using', 'python')]
[set(el) for el in li]

rawDescription: adding elements to different sets from a list in python

description: Adding elements to different sets from a list in python


code: [np.outer(x[i],y[i]) for i in xrange(x.shape[0])]

rawDescription: Is there a more vectorized way to perform numpy.outer along an axis?


rawDescription: Django urlpattern with infinite number of parameters


code:
import web
import json
from mimerender import mimerender

render_xml = lambda message: '<message>%s</message>'%message
render_json = lambda **args: json.dumps(args)
render_html = lambda message: '%s'%message
render_txt = lambda message: message

urls = (
    '/(.*)', 'greet'
)
app = web.application(urls, globals())

class greet:
    @mimerender(
        default = 'html',
        html = render_html,
        xml  = render_xml,
        json = render_json,
        txt  = render_txt
    )
    def GET(self, name):
        if not name:
            name = 'world'
        return {'message': 'Hello, ' + name + '!'}

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

rawDescription: Recommendations of Python REST (web services) framework?


rawDescription: Removing rows in NumPy efficiently

description: Removing rows in NumPy efficiently


code:
def numCol(n):
    firstline  = []
    secondline = []

    for i in range(1, n+1):
        i %= 100
        tens, ones = i // 10, i % 10
        if ones:        # ones != 0
            firstline.append(" ")
        if not ones:    # ones == 0    # <= 'else:'
            firstline.append(str(tens))
        secondline.append(str(ones))

    print(''.join(firstline))
    print(''.join(secondline))

rawDescription: Slicing strings of a sentence with a scale


rawDescription: Python matching regex multiple times in a row (not the findall way)


code:
def make_index(num_dimension, slice_pos):
    zeros = [0] * num_dimension
    zeros[slice_pos] = slice(None)
    return tuple(zeros)

rawDescription: Python: Index an array using the colon operator in an arbitrary dimension


code: query = self.request.query

rawDescription: Is it possible to get values from query string with same name?


code:
ordered_keys = [t[0] for t in t1]
a = {t[0]:t[1:] for t in t1} # {'a': (3, 4), 'c': (4, 5), 'b': (3, 4)}
b = {t[0]:t[1:] for t in t1} # {'a': (4, 6), 'c': (3, 4), 'b': (3, 6), 'd': (4, 5)}
l = list()
for key in sorted(ordered_keys):
    try:
        l.append(diff_unique(a[key][1],b[key][1]))
    except KeyError:
        l.append(0) # default value
return l

rawDescription: comparing list of tuple elements python

description: Comparing list of tuple elements python


code: df['dummy_numeric'] = 1

rawDescription: Count repeating events in pandas timeseries


code:
dic1 = {'a':'a','b':'c','c':'d'}
dic2 = {'b':'a','a':'c','c':'d'}
dic1.viewkeys() == dic2.viewkeys()
dic1.viewkeys() - dic2.viewkeys()
dic1.viewkeys() | dic2.viewkeys()

rawDescription: Python: How to know if two dictionary have the same keys


code: df = df.set_index(['STATE_PROV_CODE', 'COUNTY'])

rawDescription: Pandas join on 2 columns

description: Pandas join on 2 columns


code:
import time
from joblib import Parallel, delayed

def long_function():
    time.sleep(1)

REPETITIONS = 4
Parallel(n_jobs=REPETITIONS)(
    delayed(long_function)() for _ in range(REPETITIONS))

rawDescription: Parallelize for-loop in python

description: Parallelize for-loop in python


code:
1,  # a tuple with one element
a, = 1,  # assigning one value to the left-hand targets.
a
a, b = 1,  # not enough elements
a, b = 1, 2, 3  # the syntax requires an exact match, 3 is too many
a, b = 1, 2   # two values assigned
a
b

rawDescription: The ,= operator

description: The ,= operator