code:
d = dict()

s = 'CPU0Tjmax|90degreesC|ok'
li = s.split("|")

d[li[0]] = (li[1], li[2])
d

rawDescription: Python: Convert a String into a tuple or list with a twist


code:
import string

line = "Hello, world!"

punctuation = set(string.punctuation)
print([c for c in line if c in punctuation])

rawDescription: Using regex, best way to get all punctuations from a line in Python?


code:
import pylab as pl
import numpy as np

d = {'CLOVER':4,'SPADE':6,'DIAMOND':7,'HEART':2}
X = np.arange(len(d))
pl.bar(X, d.values(), align='center', width=0.5)
pl.xticks(X, d.keys())
ymax = max(d.values()) + 1
pl.ylim(0, ymax)
pl.show()

rawDescription: histogram in pylab from a dictionary

description: Histogram in pylab from a dictionary


code:
s = "Arkansas 40\n Washington 83\n North Dakota 49\n New Jersey 24"

sum(int(n) for n in s.split() if n.isdigit())

196

rawDescription: How to add numbers together from a string with words?

description: Add numbers together from a string with words


code:
subforum_id = 1  # some id here by which you need to sort

sql = ''.join((
    'CASE professionalNetwork ',
    'WHEN {} THEN 1 '.format(subforum_id),
    'ELSE -1',
))
q = Group.objects.extra(select={'same_subforum': sql})
q = q.extra(order_by=['same_subforum'])

rawDescription: order by condition Django

description: Order by condition Django


code:
import re
s = 'abc:123,def ghu'
','.join(re.findall(r'\w+', s))

rawDescription: Regular Expression RegEx Parsing

description: Regular Expression RegEx Parsing


code:
"""UWSGI websocket proxy."""
from urllib.parse import urlparse, urlunparse
import logging
import time

import uwsgi
from pyramid import httpexceptions
from ws4py import WS_VERSION
from ws4py.client import WebSocketBaseClient

#: HTTP headers we need to proxy to upstream websocket server when the Connect: upgrade is performed
CAPTURE_CONNECT_HEADERS = ["sec-websocket-extensions", "sec-websocket-key", "origin"]

logger = logging.getLogger(__name__)

class ProxyClient(WebSocketBaseClient):
    """Proxy between upstream WebSocket server and downstream UWSGI."""

    @property
    def handshake_headers(self):
        """
        List of headers appropriate for the upgrade
        handshake.
        """
        headers = [
            ('Host', self.host),
            ('Connection', 'Upgrade'),
            ('Upgrade', 'WebSocket'),
            ('Sec-WebSocket-Key', self.key.decode('utf-8')),
            # Origin is proxyed from the downstream server, don't set it twice
            # ('Origin', self.url),
            ('Sec-WebSocket-Version', str(max(WS_VERSION)))
            ]

        if self.protocols:
            headers.append(('Sec-WebSocket-Protocol', ','.join(self.protocols)))

        if self.extra_headers:
            headers.extend(self.extra_headers)

        logger.info("Handshake headers: %s", headers)
        return headers

    def received_message(self, m):
        """Push upstream messages to downstream."""

        # TODO: No support for binary messages
        m = str(m)
        logger.debug("Incoming upstream WS: %s", m)
        uwsgi.websocket_send(m)
        logger.debug("Send ok")

    def handshake_ok(self):
        """
        Called when the upgrade handshake has completed
        successfully.

        Starts the client's thread.
        """
        self.run()

    def terminate(self):
        super(ProxyClient, self).terminate()

    def run(self):
        """Combine async uwsgi message loop with ws4py message loop.

        TODO: This could do some serious optimizations and behave asynchronously correct instead of just sleep().
        """

        self.sock.setblocking(False)
        try:
            while not self.terminated:
                logger.debug("Doing nothing")
                time.sleep(0.050)

                logger.debug("Asking for downstream msg")
                msg = uwsgi.websocket_recv_nb()
                if msg:
                    logger.debug("Incoming downstream WS: %s", msg)
                    self.send(msg)

                s = self.stream

                self.opened()

                logger.debug("Asking for upstream msg")
                try:
                    bytes = self.sock.recv(self.reading_buffer_size)
                    if bytes:
                        self.process(bytes)
                except BlockingIOError:
                    pass

        except Exception as e:
            logger.exception(e)
        finally:
            logger.info("Terminating WS proxy loop")
            self.terminate()

def serve_websocket(request, port):
    """Start UWSGI websocket loop and proxy."""
    env = request.environ

    # Send HTTP response 101 Switch Protocol downstream
    uwsgi.websocket_handshake(env['HTTP_SEC_WEBSOCKET_KEY'], env.get('HTTP_ORIGIN', ''))

    # Map the websocket URL to the upstream localhost:4000x Notebook instance
    parts = urlparse(request.url)
    parts = parts._replace(scheme="ws", netloc="localhost:{}".format(port))
    url = urlunparse(parts)

    # Proxy initial connection headers
    headers = [(header, value) for header, value in request.headers.items() if header.lower() in CAPTURE_CONNECT_HEADERS]

    logger.info("Connecting to upstream websockets: %s, headers: %s", url, headers)

    ws = ProxyClient(url, headers=headers)
    ws.connect()

    # TODO: Will complain loudly about already send headers - how to abort?
    return httpexceptions.HTTPOk()

rawDescription: Jupyter for WebSocket communication

description: Jupyter for WebSocket communication


rawDescription: touch a directory in python (Linux)

description: Touch a directory in python (Linux)


code:
item = QtGui.QTableWidgetItem("test")
item.setBackground(QtCore.Qt.red)
self.tableWidget.setItem(1,8,item)

rawDescription: PYQT4 Cell color

description: PYQT4 Cell color


code:
from itertools import groupby
from operator import itemgetter
X2 = [list(group) for key, group in groupby(X1, itemgetter(1))]

rawDescription: Using itertools to group consecutive tuples by second value


code:
#!/usr/bin/env python
from subprocess import Popen, PIPE

proc = Popen('./Goldbackup -s -I -U'.split(), stdin=PIPE, stdout=PIPE,
             universal_newlines=True)
output = proc.communicate('yes\n/dir/blabla/\nyes')[0]

rawDescription: How to execute bunch of commands in one pipe using python?

description: Execute bunch of commands in one pipe using python


code:
# An inherited dict maps keys to values.
# The inherited dict provides __getitem__, __len__, __contains__, and get.
# The remaining methods are order-aware.
# Big-O running times for all methods are the same as regular dictionaries.

# The internal self.__map dict maps keys to links in a doubly linked list.
# The circular doubly linked list starts and ends with a sentinel element.
# The sentinel element never gets deleted (this simplifies the algorithm).
# Each link is stored as a list of length three:  [PREV, NEXT, KEY].

rawDescription: How does Python's OrderedDict remember elements inserted?


code:
import parms

parms.foo
parms.bar
parms.baz

rawDescription: Import a bunch of parameters as a dictionary?


code:
firstname = ""
middlename = ""
Surname = ""
title = ""
ppsno = ""
gender = ""
testID = ""
birthDate = ""
address1 = ""
address2 = ""
address3 = ""
address4 = ""
town = ""
county = ""
country = ""
email = ""
mobile = ""

#Default Constructor for the class patient
def __init__(
    self,
    testID,
    firstname = None,
    surname = None,
    gender = None,
    birthDate = None):

    self.testID = testID
    if (firstname is None):
        firstname = "Test"
        self.firstname = firstname
    if (surname is None):
        surname = "Patient"
        self.surname = surname
    if (gender is None):
        gender = "Male"
        self.gender = gender
    if (birthDate is None):
        birthDate = "08081988"
        self.birthDate = birthDatename

#Use this to create a patient with more detailed information

def __init__(
    self,
    testID,
    firstname = None,
    middlename = None,
    surname = None,
    gender = None,
    birthDate = None,
    title = None,
    ppsno = None,
    address1 = None,
    address2 = None,
    address3 = None,
    address4 = None,
    town = None,
    county = None,
    country = None,
    email = None,
    mobile = None):

    self.testID = testID

    if (firstname is None):
        firstname = "Sample"
        self.firstname = firstname
    if (surname is None):
        surname = "Patient"
        self.surname = surname
    if (middlename is None):
        middlename = "Mary"
        self.middlename = middlename
    if (gender is None):
        gender = "Female"
        self.gender = gender
    if (birthDate is None):
        birthDate = "03091959"
        self.birthDate = birthDatename
    if (title is None):
        title = "Mrs"
        self.title = title
    if (ppsno is None):
        ppsno = "7445213P"
        self.ppsno = ppsno
    if (address1 is None):
        address1 = "100"
        self.address1 = address1
    if (address2 is None):
        address2 = "Green Glade"
        self.address1 = address1
    if (address3 is None):
        address3 = "Pleasent Way"
        self.address3 = address3
    if (address4 is None):
        address4 = "Ballybehy"
        self.address4 = address4
    if (town is None):
        town = "Abbeyfeale"
        self.town = town
    if (county is None):
        county = "Limerick"
        self.county = county
    if (country is None):
        country = "Ireland"
        self.country = country
    if (email is None):
        email = "supertest69@freewebmail.ie"
        self.email = email
    if (mobile is None):
        mobile = "0870563229"
        self.mobile = mobile

def getStuff(self):
     return self.stuff

class schemeDetails():
    cardNumber = ""
    scheme = ""
    cardNumber = ""
    month = ""
    year = ""
    setSchemeAsDefault = ""

    def __init__(
        self,
        scheme = None,
        cardNumber = None,
        month = None,
        year = None,
        setSchemeAsDefault = None ):

        if (scheme is None):
            scheme = "GM"
            self.scheme = scheme
        if (cardNumber is None):
            month = "1231456A"
            self.cardNumber = cardNumber
        if (month is None):
            month = "September"
            self.month = month
        if (year is None):
            year = "2015"
            self.year = year
        if (setSchemeAsDefault is None):
            setSchemeAsDefault = "true"
            self.setSchemeAsDefault = setSchemeAsDefault

    def getStuff(self):
        return self.stuff

#Inner class for creating basic dispenses
class basicDispense():
    drug = ""
    packSize = ""
    dosageSystem = ""
    scheme = ""
    #Constructor for the class basicDispense
    def __init__(
        self,
        drug = None,
        packSize = None,
        dosageSystem = None,
        scheme = None):

        if (drug is None):
            drug = "ABBOTT THIN LANCET TYPE C GMS"
            self.drug = drug
        if (packSize is None):
            packSize = "28"
            self.packSize = packSize
        if (dosageSystem is None):
            dosageSystem = "MD"
            self.dosageSystem = dosageSystem
        if (scheme is None):
            scheme = "GM"
            self.scheme = scheme

        def getStuff(self):
            return self.stuff

    #Inner class of basicDispenses for printing Labels
    #Constructor for the class Labels
    class labels():
        def __init__(
            self,
            testID,
            printBagLabel = None,
            printDrugLabel = None):

            self.testID = testID
            if (printBagLabel is None):
                printBagLabel = "false"
                self.drug = drug
            if (printDrugLabel is None):
                printDrugLabel = "false"
                self.printDrugLabel = printDrugLabel

rawDescription: Nested Classes Python and Indentation errors


code:
def render_POST(self, request):
    # some code you may have to run before processing

    d = threads.deferToThread(method_that_does_the_processing, request)

    return ''

rawDescription: python twisted multithreaded tcp proxy

description: Python twisted multithreaded tcp proxy


code:
import ast
x = '''('string','string'), ('string2','string3'), ('string','string'), 'STRING' '''
y = ast.literal_eval(x); print(y)
' '.join( ' '.join(elem) if type(elem) is tuple else '' for elem in y )

rawDescription: How to parse a string given the following?

description: Parse a string given the following


code:
from sqlalchemy.sql import table, column, select, update, insert

# define meta information
metadata = MetaData(bind=engine)
mytable = Table('mytable', metadata, autoload=True)

# select
s = mytable.select() # or:
#s = select([mytable]) # or (if only certain columns):
#s = select([mytable.c.field1, mytable.c.field2, mytable.c.field3])
s = s.where(mytable.c.field1 == 'abc')
result = session.execute(s)
out = result.fetchall()
print(out)

# insert
i = insert(mytable)
i = i.values({"field1": "value1", "field2": "value2"})
session.execute(i)

# update
u = update(mytable)
u = u.values({"field3": "new_value"})
u = u.where(mytable.c.id == 33)
session.execute(u)

rawDescription: Insert and update with core SQLAlchemy

description: Insert and update with core SQLAlchemy


code:
myconnection = pyodbc.connect(myconnectionstring, autocommit=False)
# your commands here
myconnection.commit()

rawDescription: Execute sql-server transaction using python


rawDescription: Slice Pandas DataFrame by Row

description: Slice Pandas DataFrame by Row


code:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([command] + args, startupinfo=startupinfo).wait()

rawDescription: Disable cmd opening from GUI (PyQt)

description: Disable cmd opening from GUI (PyQt)


rawDescription: I am trying to iterate over multiple ranges to create a multidimensional ndarray from another


code:
class BaseModel(object):

    @classmethod
    def _get_keys(cls):
        return sa.orm.class_mapper(cls).c.keys()

    def get_dict(self):
        d = {}
        for k in self._get_keys():
            d[k] = getattr(self, k)
        return d

rawDescription: SQLAlchemy: Knowing the field names and values of a model object?


code:
class D(C, B):
    a = A.a

rawDescription: Python multiple inheritance name clashes


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

n=10

X = np.random.rand(28**2,n)

fig, ax = plt.subplots(1,n)

plt.ion()
plt.show()

for i in range(n):
    wi = X[:,1].reshape(28,28)
    ax[i].imshow(wi)

    #fig.canvas.draw()  # May be necessary, wasn't for me.

plt.ioff()  # Make sure to make plt.show() blocking again, otherwise it'll run
plt.show()  #   right through this and immediately close the window (if program exits)

rawDescription: pyplot draw method for subplots

description: Pyplot draw method for subplots


code:
p = None #This initializes the variables globally.

def message_handler(connect_object, message_node):
    R = (message_node.getBody())
    if R== "video" :
        movie_path= '/home/pi/Desktop/media/video.mp4'
        p = subprocess.Popen(['omxplayer', movie_path],stdin=subprocess.PIPE)
    elif R== "pause":
        p.stdin.write('\x20') #Much cleaner alternative to named pipes...
    else:
        pass

rawDescription: Python, pausing a subprocess based on the received messages


code:
with open('sample.txt') as sample:
    num_testcases = int(sample.readline())
    assert 1 <= num_testcases <= 5
    for testcase in range(num_testcases):
        num_elems = int(sample.readline())
        assert 1 <= num_elems <= 10000
        elems = map(int, sample.readline().split())
        assert len(elems) == num_elems
        assert all(1 <= elem <= 100000 for elem in elems)
        method_test(elems)

rawDescription: What is the best way to write a code in python to read some sample input from a "txt" files?


code:
inFile = open("data.txt")
outFile = open("result.txt", "w")
buffer = []
keepCurrentSet = True
for line in inFile:
    buffer.append(line)
    if line.startswith("----"):
        #---- starts a new data set
        if keepCurrentSet:
            outFile.write("".join(buffer))
        #now reset our state
        keepCurrentSet = False
        buffer = []
    elif line.startswith("extractme"):
        keepCurrentSet = True
inFile.close()
outFile.close()

rawDescription: Python to extract data from a file

description: Python to extract data from a file


code:
colNums = [0, 2, 6]
to_write = [ col for i, col in enumerate(zip(*my_reader)) if i in colNums ]

rawDescription: how to copy some csv file colums into another csv file with python?

description: Copy some csv file colums into another csv file with python


code:
def foo():pass
foo.bar="text"
foo.bar

rawDescription: In python, What does it mean if I assign a variable to a method?


code:
words = ['proper','organization','done']
pd.DataFrame([[wrd, df['comment'].str.contains(wrd).sum()] for wrd in words])

rawDescription: Pandas Dataframe: count number of IDs based on occurence of words in a text column


code:
def compatible_pred(obj_types, fun_signature):
  if len(obj_types) != len(fun_signature): return False
  return all(issubclass(of, ft) for of, ft in zip(obj_types, fun_signature))

def is_compatible(obj_types, fun_signatures=(t1, t2)):
  return [t for t in fun_signatures if compatible_pred(obj_types, t)]

rawDescription: Python Type Checking & Inheritance Issue


code:
fm = urllib.parse.parse_qs(request_body['family'].encode().decode(),True) # return a dictionary
familyvalue = str([k for k in fm.keys()][0]) # access to first item

rawDescription: read wsgi post data with unicode encoding

description: Read wsgi post data with unicode encoding


code:
from pyparsing import ParseBaseException, ParserElement

def parseConsumeString(self, instring, parseAll=True, yieldLoc=False):
    '''Generator version of parseString which does not try to parse
    the whole string at once.

    Should be called with a top-level parser that could parse the
    entire string if called repeatedly on the remaining pieces.
    Instead of:

        ZeroOrMore(TopLevel)).parseString(s ...)

    Use:

        TopLevel.parseConsumeString(s ...)

    If yieldLoc==True, it will yield a tuple of (tokens, startloc, endloc).
    If False, it will yield only tokens (like parseString).

    If parseAll==True, it will raise an error as soon as a parse
    error is encountered. If False, it will return as soon as a parse
    error is encountered (possibly before yielding any tokens).'''

    if not self.streamlined:
        self.streamline()
        #~ self.saveAsList = True
    for e in self.ignoreExprs:
        e.streamline()
    if not self.keepTabs:
        instring = instring.expandtabs()
    try:
        sloc = loc = 0
        while loc<len(instring):
            # keeping the cache (if in use) across loop iterations wastes memory (can't backtrack outside of loop)
            ParserElement.resetCache()
            loc, tokens = self._parse(instring, loc)
            if yieldLoc:
                yield tokens, sloc, loc
            else:
                yield tokens
            sloc = loc = self.preParse(instring, loc)
    except ParseBaseException as exc:
        if not parseAll:
            return
        elif ParserElement.verbose_stacktrace:
            raise
        else:
            # catch and re-raise exception from here, clears out pyparsing internal stack trace
            raise exc

def monkey_patch():
    ParserElement.parseConsumeString = parseConsumeString

rawDescription: Incremental but complete parsing with PyParsing?


code:
if __name__ == '__main__':
    io_loop = tornado.ioloop.IOLoop.instance()

    loop = msgpackrpc.Loop(io_loop)
    rpc = msgpackrpc.Server(RPCServer(), loop=loop)

    # ... sockjs-tornado initialisation. No need to call rpc.start()

    io_loop.start()

rawDescription: Sockjs-tornado and rpc

description: Sockjs-tornado and rpc


code:
import forms

form = getattr(forms, category + "Form")()

rawDescription: Python: how to use value stored in a variable to decide which class instance to initiate?


rawDescription: How do I find out what Python implementation I am using?

description: Find out what Python implementation I am using


code:
import scipy as sp
import Image
import ImageDraw
import ImageFont

font_fname = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'
font_size = 200
font = ImageFont.truetype(font_fname, font_size)

h,w = 1080, 1920
bg_colour = (255, 255, 255)
bg_image = sp.dot(sp.ones((h,w,3), dtype='uint8'), sp.diag(sp.asarray((bg_colour), dtype='uint8')))
image0 = Image.fromarray(bg_image)
draw = ImageDraw.Draw(image0)
draw.text((530, 160), "hello world", font=font, fill='rgb(0, 0, 0)')

rawDescription: python: any tutorial to overlay text on a picture?

description: Python: any tutorial to overlay text on a picture


code:
df.sort( 'status', inplace=True)
df['change'] = df['median'].pct_change()
#   median quarter status  change
#0     240  2014-1     BV     NaN
#1     300  2014-2     BV    0.25
#2     300  2014-1   CORR    0.00
#3     240  2014-2   CORR   -0.20

df.query( 'quarter=="2014-2"')
#   median quarter status  change
#1     300  2014-2     BV    0.25
#3     240  2014-2   CORR   -0.20

rawDescription: Percentage change with pandas

description: Percentage change with pandas


code:
import winsound
Freq = 2500 # Set Frequency To 2500 Hertz
Dur = 1000 # Set Duration To 1000 ms == 1 second
winsound.Beep(Freq,Dur)

rawDescription: Python: Making a beep noise

description: Python: Making a beep noise


code:
import tkinter as tk
from tkinter import ttk

class App:
    def __init__(self):
        self.root = tk.Tk()
        self.tree = ttk.Treeview()
        self.tree.pack(side="top", fill="both")
        self.tree.bind("<<TreeviewSelect>>", self.on_tree_select)

        for i in range(10):
            self.tree.insert("", "end", text="Item %s" % i)

        self.root.mainloop()

    def on_tree_select(self, event):
        print("selected items:")
        for item in self.tree.selection():
            item_text = self.tree.item(item,"text")
            print(item_text)

if __name__ == "__main__":
    app = App()

rawDescription: How to get the value of a selected treeview item?

description: Get the value of a selected treeview item


code:
def function():
    print("Hello World")

d = {
    'hello': function  # NOTE: we are not calling the function here - just keeping the reference
}
d['hello']()

rawDescription: Calling a function from within a dictionary


code:
import re

def number_to_string(num, n=3):
    num_str = str(num)
    if len(num_str) < n:
        num_str = '0' * (n-len(num_str)) + num_str
    elif len(num_str) % n != 0:
        num_str = '0'*(n-len(num_str)%n) + num_str
    print(num_str)

    chars = re.findall('.'*n, num_str)
    l = [chr(int(i)) for i in chars]
    return ''.join(l)

rawDescription: Convert an integer into a string of its ascii values


code: getattr(rpc, function_name)(*params)

rawDescription: Dynamic function calls in Python using XMLRPC


code:
from django.conf.urls.defaults import *
from wkhtmltopdf.views import PDFTemplateView

urlpatterns = patterns('',
    # ...
    url(r'^pdf/$', PDFTemplateView.as_view(template_name='my_template.html',
                                           filename='my_pdf.pdf'), name='pdf'),
    # ...
)

rawDescription: HTML to PDF with python and wkhtmltopdf

description: HTML to PDF with python and wkhtmltopdf


code:
with open("curve.dat", "w") as outFile:
    for t,p in zip(timeList,parameterList):
        outFile.write('{t}\t{p}\n'.format(t=t,p=p))

rawDescription: writing values generated from different functions in a single file

description: Writing values generated from different functions in a single file


code:
class gameWindow(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.setGeometry(300,300,1280,800)

        self.frame = QtGui.QFrame()
        self.frame.resize(300,300)
        self.frame.setStyleSheet("background-color: rgb(200, 255, 255)")

        layout=QtGui.QVBoxLayout()
        layout.addWidget(self.frame)
        self.setLayout(layout)

rawDescription: Adding a Qframe in PYQT and set size

description: Adding a Qframe in PYQT and set size


code:
def funct(x, y):
    x = x[x!=0]
    y = y[y!=0]
    # do something here
    return x,y
a, b = funct(a, b)  #assign the returned value back to the global variables

rawDescription: remove the zeros from an array with a function Python

description: Remove the zeros from an array with a function Python


code:
from django.db.models import Max
objs = Obj.objects.annotate(latest_data=Max('objdata__datum')).order_by('latest_data')

rawDescription: Django order query by foreign key (reverse direction)


code:
d =  {'translation 1': 'dilligent', 'pinyin 1': 'ren4wei2', 'character 1': '\xe8\xaa\x8d\xe7\x88\xb2'}
key = "translation %s" % 1
d[key]

rawDescription: python2.7 - taking a value from a dictionary, where the key is a variable

description: Python2.7 - taking a value from a dictionary, where the key is a variable


code:
x='a'
lis=[]
id(lis)
lis=lis+[x]
lis
id(lis)

rawDescription: Python [ ] notation in list

description: Python [ ] notation in list


code: match = re.findall(r'([^ ]*)\/PERSON', string)

rawDescription: Regexp Word within a word with a fullstop


code:
f.seek(-1, os.SEEK_CUR)
f.write(";")

rawDescription: "Backspace" over last character written to file


code:
groups = relationship(
    Group, GroupMemeber.__table__,
    primaryjoin=lambda: and_(not_(Group.deleted), GroupMemeber.user_id == User.id)
)

rawDescription: Permanently filter a SQLAlchemy relationship


code:
class AnotherWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="GCT")
        self.connect("destroy", self.on_destroy)

        self.add(Gtk.Label("This is another window"))
        self.show_all()

    def on_destroy(self, widget):
        widget.hide()

rawDescription: close sub-window without closing main window PyGTK in python

description: Close sub-window without closing main window PyGTK in python


code:
from django.conf import settings
from django.core.mail import EmailMessage

def send_message_to_admin(subject,message):
    EmailMessage(subject,message,to=[settings.ADMIN_CONTACT['email']]).send()

rawDescription: Where to store global data in Django

description: Where to store global data in Django


code:
#!/usr/bin/python3

import numpy as np
from sympy.parsing.sympy_parser import parse_expr
from sympy.utilities.lambdify import lambdify, implemented_function
from sympy import S, Symbol
from sympy.utilities.autowrap import ufuncify

def CreateMagneticFieldsListOpt(dataToSave,equationString,DSList):

    expression  = S(equationString)
    numOfElements = len(dataToSave["MagneticFields"])

    #initialize the magnetic field output array
    magFieldsArray    = np.empty(numOfElements)
    magFieldsArray[:] = np.NaN

    lam_f = lambdify(tuple(DSList),expression,modules='numpy')
    replacementList = [None]*len(DSList)

    for j in range(len(DSList)):
        replacementList[j] = np.array(dataToSave[DSList[j]])
    print(replacementList)

    magFieldsArray = np.double(lam_f(*replacementList))

    return magFieldsArray

list={"MagneticFields":[1,2,3,4,5],"ChX":[2,4,6,8,10]}

out=CreateMagneticFieldsListOpt(list,"MagneticFields*5+ChX",["MagneticFields","ChX"])

print(out)

rawDescription: Python 3: Sympy: Include list information to optimize lambdify


rawDescription: Python: Is it possible to make a tkinter program on top of all windows?


rawDescription: Numpy array - change the next element based on a change on previous


code:
tidy_catalog = collections.defaultdict(dict)
for val in catalog:
    tidy_catalog[val['item_id']][val['property_name']] = val['property_value']
pp(tidy_catalog)

rawDescription: Aggregating / grouping lists into a dictionary


code:
def func(dct):
   dct.clear()
   dct.update({'a': 5})

rawDescription: Replace the content of dictionary with another dictionary in a function - Python


code: df1.merge(df2, how='outer')

rawDescription: Python: Pandas merge 2 dataframes using a common columm


code:
from copy import deepcopy
class CopyingMock(MagicMock):
    def __call__(self, *args, **kwargs):
        args = deepcopy(args)
        kwargs = deepcopy(kwargs)
        return super(CopyingMock, self).__call__(*args, **kwargs)
c = CopyingMock(return_value=None)
arg = set()
c(arg)
arg.add(1)
c.assert_called_with(set())
c.assert_called_with(arg)
c.foo

rawDescription: How can i check call arguments if they will change with unittest.mock

description: Check call arguments if they will change with unittest.mock


code:
word=['a', 'sdfs', 'sdfsdfsfs']
join_word = ' '.join(word)
len_join_word = len(join_word)
print(len_join_word)

rawDescription: How to get len of join word?

description: Get len of join word


code:
import requests

response = requests.post('http://httpbin.org/post', files={'file': open('filename','rb')})
print(response.content)

rawDescription: Multipart form encoding file upload in Python 3


code:
step = str(StepNumber)  # StepNumber is an int

if flag:
    color = "green"
    sv = "[S]"
else:
    color = "red"
    sv = "[V]"

P = Paragraph('{step} {sv}'.format(color=color, sv=sv, step=step)
    , style)

rawDescription: How to have multiple text colors within the same paragraph in ReportLab?

description: Have multiple text colors within the same paragraph in ReportLab


code:
x = np.array([2,8,3,4,7,6,1])
lix = x > 4
x = x[lix] # this "drops" everything 4 or less
x
[dropped] = np.where(~lix) # find the indices that weren't dropped
dropped

rawDescription: Keeping track of dropped indices when dropping elements from numpy array


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

number_of_items_sold_per_store = [10, 6, 90, 5, 102, 10, 6, 50, 85, 1, 2, 3, 6]

ar = sorted(number_of_items_sold_per_store,reverse=True)
y = np.cumsum(ar).astype("float32")

#normalise to a percentage
y/=y.max()
y*=100.

#prepend a 0 to y as zero stores have zero items
y = np.hstack((0,y))

#get cumulative percentage of stores
x = np.linspace(0,100,y.size)

#plot
plt.plot(x,y)
plt.show()

rawDescription: Sorted cumulative plots

description: Sorted cumulative plots


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

def sinespace(m=90, n=10):
    x = np.linspace(0, m, n)
    s = np.sin(np.deg2rad(x))
    return (s/s[-1])*m

s = sinespace()
print(s)

plt.plot(s, np.ones_like(s), 'ro')
plt.show()

rawDescription: Python : creating an array, weighed by sine function


code:
def parse(self, response):
    revenue = response.xpath('//td[@align="right"]/strong/text()')
    items = []
    for rev in revenue:
        item = DozenItem()
        item["Revenue"] = rev.re('\d*,\d*')
        items.append(item)
    return items[:3]

rawDescription: Python: Scrapy exports raw data instead of text() only?


code:
with open(infilename) as infile:
    nucStart=69
    nucStop=497
    nucleotides=[]
    for line in infile:
        if line.startswith(">"):
            # process the previous list if populated
            if len(nucleotides) > 0:
                nucleotides = ''.join(nucleotides)  # make a single string
                # write out the accession information and the nucleotides we want
                outfile.write("%s %s" % (accession_line,
                                         nucleotides[nucStart-start-1:nucStop-start]))
                nucleotides=[]   # clear it for the next run
            # this is the start of the next sequence
            accession_line = line
            start = int(line.split('.')[1])
        else:
            # this is a line containing a partial nucleotide sequence, so add it
            nucleotides.append(line)

rawDescription: Combine strings, extract substrings

description: Combine strings, extract substrings


code:
def sendCookie(self):
    cookies = cherrypy.response.cookie

    cookies['cookie1'] = 'Chips Ahoy!'
    cookies['cookie1']['path'] = '/the/red/bag/'
    cookies['cookie1']['comment'] = 'round'

    cookies['cookie2'] = 'Chocolate Chips'
    cookies['cookie2']['path'] = '/the/yellow/bag/'
    cookies['cookie2']['comment'] = 'thousands'

    return 'Cookies are now in your hands.'
setCookie.exposed = True

rawDescription: How do I set multiple cookies with CherryPy

description: Set multiple cookies with CherryPy


code:
def config(**kwargs):
    for key, value in kwargs.items():
        if key not in AllowedKeys:
            raise KeyError("{} is not allowed in config".format(key))

        if not value_is_correct_for_key(key, value):
            raise ValueError("{} is not allowed for {} in config".format(value, key))

        # ... more tests here depending on your use case

    # Everything is OK,  just return the dictionary
    return kwargs

# Usage:
print(config(A="1", B="2"))

rawDescription: config dict construction pattern, using a helper class?

description: Config dict construction pattern, using a helper class


code:
import subprocess
import sys

command = 'python -c \'print raw_input("Please make a selection: ")\''
sp = subprocess.Popen(command, shell = True, stdin = sys.stdin)
sp.wait()

rawDescription: Python calling raw_input from a subprocess


code:
Line = "A[0x04] Va   [0xf]"
[x.partition(']')[0] for x in Line.split('[') if ']' in x]

rawDescription: Elegant way to strip values in brackets in Python


code:
def skip_modules_docstring(app, what, name, obj, options, lines):
    if what == 'module':
        del lines[:]

def setup(app):
    app.connect('autodoc-process-docstring', skip_modules_docstring)

rawDescription: Get "flat" member output for sphinx automodule


code:
from collections import OrderedDict
list1 = ['r', '8', 'w', 'm', 'f', 'c', 'd']
list2 = ['AA', 'AB', 'AC', 'AD', 'AE', 'AF']
OrderedDict(zip(list1, list2))

rawDescription: 2 Lists to Dictionary Issue

description: 2 Lists to Dictionary Issue


code: result = [MyClass(a.data1, a.data2, b.data6, static_var) for a, b in zip(list_a, list_b)]

rawDescription: iterating through 2 lists containing class instances

description: Iterating through 2 lists containing class instances


code:
def some_func(a):
  L = []

  def append():
    L.append(a)  # for the sake of example
    #...

  if a == 100:
    append()
    #...
  elif a == 200:
    append()
    #...

rawDescription: Where do I put common code for if and elif?


rawDescription: Getting rid of "count" column by replicating rows


code:
import bson
class Example(object):
    def __init__(self):
            self.a = 'a'
            self.b = 'b'
    def set_c(self, c):
            self.c = c

e = Example()
e
e.__dict__
e.set_c(123)
e.__dict__
bson.BSON.encode(e.__dict__)
bson.BSON.encode(e)

rawDescription: Converting Python class object instance to mongodb BSON string


code:
# Open the pdf before looping to add pages
with PdfPages(r'C:\test\Delete.pdf') as pdf:
    for f in os.listdir(pth):
        if not os.path.isfile(os.path.join(pth,f)):
            continue
        # ignore the pdf file that just got created
        if 'pdf' in f:
            continue
        #read each file
        df = pd.read_csv(os.path.join(pth, f))
        #add column names
        df.columns=['Count', 'Bins']
        #create pdf file to save graphs to
        #plot the graph
        df2=df.plot(title=str(f))
        #set x-label
        df2.set_xlabel("Bins")
        #set y-label
        df2.set_ylabel("Count")
        #save the figure
        fig = plt.gcf()
        pdf.savefig(fig)
        #close the figure
        plt.close(fig)

rawDescription: Plotting graphs within a loop

description: Plotting graphs within a loop


code:
@decorator
class myClass(unittest.TestCase):
    def __init__(self, *args, **kwargs):
        unittest.TestCase.__init__(self, *args, **kwargs)
        self.test = 'test'

rawDescription: Python decorator for class

description: Python decorator for class


code:
import wx
class MyForm(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Toggle")
        self.panel = wx.Panel(self, wx.ID_ANY)
        self.dummy = wx.StaticText(self.panel, -1, "")
        self.cb1 = wx.CheckBox(self.panel, -1,"Choice 1", pos=(10,10))
        self.cb2 = wx.CheckBox(self.panel, -1,"Choice 2", pos=(10,40))
        self.cb1.Bind(wx.EVT_CHECKBOX, self.onToggle1)
        self.cb2.Bind(wx.EVT_CHECKBOX, self.onToggle2)
        self.cb1.SetToolTipString(wx.EmptyString)
        self.cb2.SetToolTipString(wx.EmptyString)
    #----------------------------------------------------------------------
    def onToggle1(self, event):
        if self.cb1.GetValue() == True:
            self.cb1.SetToolTipString("Check Box 1 is Checked")
        else:
            self.cb1.SetToolTip(None)

    def onToggle2(self, event):
        if self.cb2.GetValue() == True:
            self.cb2.SetToolTipString("Check Box 2 Is Checked")
        else:
            self.cb2.SetToolTip(None)

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = MyForm()
    frame.Show()
    app.MainLoop()

rawDescription: How to turn off tooltips in wxpython

description: Turn off tooltips in wxpython


code:
engine = create_engine('postgresql+psycopg2://postgres:postgres@localhost:5432/cm', convert_unicode=True)
metadata = MetaData(bind=engine)
db = engine.connect()
hosts = Table('hosts', metadata, autoload=True)
results = db.execute(select({hosts}))

hosts_dict = {}
for x in results:
    host_name = x[hosts.c.host_name]
    hosts_dict[host_name] = {column: value for column, value in x.items()}

rawDescription: nested dictionary returns set()?

description: Nested dictionary returns set()


code:
def mlock(f):
    def inner(*args, **kwargs):
        with Coloring.lock:
            return f(*args, **kwargs)
    return inner

rawDescription: mutex decorator in python

description: Mutex decorator in python


code:
import Tkinter as tk

class MyApp(object):
    def __init__(self, master):
        self.text = tk.Text(master)
        self.text.bind('<Key>', self.callback)
        self.text.pack()
        self.text.focus()

    def callback(self, event):
        print('{k!r}'.format(k = event.char))

root = tk.Tk()
app = MyApp(root)
root.mainloop()

rawDescription: simple key pressed event in python tkinter app

description: Simple key pressed event in python tkinter app


code:
def closest(data, num, n):
    return sorted(data, key=lambda x: abs(x - num))[:n]

rawDescription: A loop issue and how to select closest values from given values


code:
argv_string = ' '.join(sys.argv)
if ('gunicorn' in argv_string) or ('runserver' in argv_string):
    import all_my_stuff

rawDescription: Make Django not lazy-load module, for development convenience


code:
import polib
po = polib.pofile('path/your_language.po')
text == 'Your text'
is_translated = any(e for e in po if e.msgid == text and (not e.translated() or 'fuzzy' in e.flags) and not e.obsolete)

rawDescription: In Django, how to determine if translation for a given text is available?


code:
s = set(x[0] for x in amm)
amv = [x for x in data if x[4] in s]

rawDescription: Comparing lists of lists and writing certain elements into a new list


code: has_key = lambda a, d: any(k in a for k in d)

rawDescription: Python check if string contains dictionary key


code:
#!/usr/bin/env python

# Starting point for this script:
# http://stackoverflow.com/a/5839291

import os
import pip
import subprocess

homedir = os.getenv('HOME')
homepkg = []

for dist in pip.get_installed_distributions():
  if not dist.location.startswith(homedir):
    continue
  homepkg.append(dist.project_name)

if len(homepkg) == 0:
  print('No locally-installed packages, nothing to update.')
  raise SystemExit

# --no-deps is required because --upgrade by default is recursive and would try
# to update packages that are not from homedir (e.g. from /usr).

subprocess.call(['pip', 'install', '--user', '--upgrade', '--no-deps'] + homepkg)

rawDescription: update user installed packages with pip

description: Update user installed packages with pip


code:
import inspect
import pkgutil
import sys

def whereis_in_globals(fname):
    return [m for m in sys.modules.itervalues()
            if module_has_function(m, fname)]

def whereis_in_locals(fname):
    modules = (__import__(module_name, globals(), locals(), [fname], -1)
               for _, module_name, _ in pkgutil.walk_packages(path="."))
    return [m for m in modules if module_has_function(m, fname)]

def module_has_function(m, fname):
    return hasattr(m, fname) and inspect.isfunction(getattr(m, fname))

if __name__ == "__main__":
    # these should never raise AttributeError
    for m in whereis_in_locals('walk'):
        m.walk
    for m in whereis_in_globals('walk'):
        m.walk

rawDescription: In Python, given a function name, how to get all the modules containing the function?


code: print ("{} + {} is equal to {}.".format(num1, num2, add(num1, num2)))

rawDescription: Period at the end of print()

description: Period at the end of print()


rawDescription: Is there a way to find an element by attributes in Python Selenium?


rawDescription: Selecting dates from Pandas Panel without looping over items


code:
a = """
text
text
text
"""

print(a)

rawDescription: How to print multiple lines of text with python

description: Print multiple lines of text with python


rawDescription: Creating a method to read both positive and negative numbers from a file


code:
from collections import deque
from glob import iglob
import ast

def get_lists(pattern):
    for filename in iglob(pattern):
        with open(filename) as fin:
            penultimate = deque(fin, 2)[0]
            yield ast.literal_eval(penultimate)

data = list(get_lists('chr*.txt'))

rawDescription: How to read an output line containing a list of integers produced by python

description: Read an output line containing a list of integers produced by python


code:
import threading

class Server(threading.Thread):
    # some code

    # This is the top level function called by other objects
    def reboot(self):
        # perhaps add a lock
        if not hasattr(self, "_down"):
            self._down = threading.Thread(target=self.__powerDown)
            self._down.start()
            up = threading.Thread(target=self.__powerUp)
            up.start()

    def __powerUp(self):
        if not hasattr(self, "_down"):
            return
        self._down.join()
        # do something
        del self._down

rawDescription: How to spawn a thread inside another thread in the same object in python?

description: Spawn a thread inside another thread in the same object in python


rawDescription: Regex for string starting with $ followed by integer and contains brackets


rawDescription: eclipse pydev - how to install python modules

description: Eclipse pydev - how to install python modules


code:
from http.server import HTTPServer, SimpleHTTPRequestHandler

class LowerCaseRequestHandler(SimpleHTTPRequestHandler):

    def translate_path(self, path):
        # calls the original implementation and returns the result
        # converted to lower case
        return super().translate_path(path).lower()

if __name__ == '__main__':
    server = HTTPServer(('', 8080), LowerCaseRequestHandler)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.server_close()

rawDescription: Disable Case sensitivity on Python's Webserver


code:
[build-system]
# Minimum requirements for the build system to execute.
requires = ["setuptools", "wheel"]  # PEP 508 specifications.

rawDescription: Python best way to document imported module version in scripts


code:
output = {}

in_list = False
current_name = None

for line in open('actors.list'):
    if in_list:
        if line.startswith('-'):
            break
        if '\t' not in line:
            continue
        name, title = line.split('\t', 1)
        name = name.strip()
        title = title.strip()
        if name:
            if ',' in name:
                name = name.split(',', 1)
                name[0] = name[0].rstrip()
                name[1] = name[1].lstrip()
                name.reverse()
                name = ' '.join(name)
            current_name = name
        if title:
            output.setdefault(
                current_name, []).append(title)
    else:
        if line.startswith('-'):
            in_list = True

rawDescription: Parsing through a file from database and adding info to dictionary


code:
from bokeh.plotting import show,figure
from bokeh.io import output_notebook
from bokeh.models import Range1d
import calendar

output_notebook()

order = range(1,8)
values=[2,3,4,5,6,7,8]
days = [calendar.day_name[i-1] for i in order]
yr = Range1d(0,max(values))
p = figure(x_range=days, y_range=yr)
p.rect(order, [val/2.0 for val in values] , width=0.5, height=values, color = "#ff1200")

show(p)

rawDescription: Choosing order of bars in Bokeh bar chart


code:
import unittest

def weight(tdag, path):
    return sum([level[p] for p, level in zip(path,tdag)])

def search_max(tdag):
    if len(tdag) == 1:
        return (0,)
    if len(tdag) > 1:
        # recursive call to search_max with some new tdag
        # when choosing first node at depth 2
        path1 = (0,) + search_max(...)
        # recursive call to search_max with some new tdag
        # when choosing second node at depth 2
        # the result path should also be slightly changed
        # to get the expected result in path2
        path2 = (0,) + ...
        if weigth(tdag, path1) > weigth(tdag, path2):
            return path1
        else:
            return path2

class Testweight(unittest.TestCase):
    def test1(self):
        self.assertEquals(1, weight([[1]],(0,)))

    def test2(self):
        self.assertEquals(3, weight([[1], [2, 3]],(0, 0)))

    def test3(self):
        self.assertEquals(4, weight([[1], [2, 3]],(0, 1)))

class TestSearchMax(unittest.TestCase):

    def test_max_one_node(self):
        self.assertEquals((0,), search_max([[1]]))

    def test_max_two_nodes(self):
        self.assertEquals((0, 1), search_max([[1], [2, 3]]))

    def test_max_two_nodes_alternative(self):
        self.assertEquals((0, 0), search_max([[1], [3, 2]]))

    def test_max_3_nodes_1(self):
        self.assertEquals((0, 0, 0), search_max([[1], [3, 2], [6, 4, 5]]))

    def test_max_3_nodes_2(self):
        self.assertEquals((0, 0, 1), search_max([[1], [3, 2], [4, 6, 5]]))

    def test_max_3_nodes_3(self):
        self.assertEquals((0, 1, 1), search_max([[1], [2, 3], [4, 6, 5]]))

    def test_max_3_nodes_4(self):
        self.assertEquals((0, 1, 2), search_max([[1], [2, 3], [4, 5, 6]]))

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

rawDescription: all path in a DAG (a kind of connected binary tree)

description: All path in a DAG (a kind of connected binary tree)


code:
filename = url[url.rfind("/")+1:]
filename_small = filename.replace(".", "_small.")

rawDescription: How to extract a filename from a URL & append a word to it?

description: Extract a filename from a URL & append a word to it


code:
for key, value in Contigs.items():
    value.sort(key=lambda element: int(element[0]))

rawDescription: How to sort a list as a value in a dictionary by the first value in each list?

description: Sort a list as a value in a dictionary by the first value in each list


code:
all_first_names = set(['dan', 'bob', 'danny'])

username = 'dannysmith123'

# Get "extra" parts of the username if they exist
m = re.match(r'^([a-zA-Z]+)(.*)$', username)
name, extra = m.group(1), m.group(2)

# Get a list of possible first/last name splits
# [('d', 'annysmith'), ('da', 'nnysmith'), ...]
name_splits = [(name[:i], name[i:]) for i in range(1, len(name)+1)]

# Check each one of these splits to see if the first name
# is present in the master first name list, if so, add it to
# the list of valid matches.
match_list = []
for ns in name_splits:
    if ns[0] in all_first_names:
        match_list.extend(ns)
        if extra:
            match_list.append(extra)
            extra = None

rawDescription: Finding names inside a string

description: Finding names inside a string


code:
import numpy as np
from scipy.spatial import Delaunay

points = np.random.rand(30, 2) # 30 points in 2-d
tri = Delaunay(points)

# Make a list of line segments:
# edge_points = [ ((x1_1, y1_1), (x2_1, y2_1)),
#                 ((x1_2, y1_2), (x2_2, y2_2)),
#                 ... ]
edge_points = []
edges = set()

def add_edge(i, j):
    """Add a line between the i-th and j-th points, if not in the list already"""
    if (i, j) in edges or (j, i) in edges:
        # already added
        return
    edges.add( (i, j) )
    edge_points.append(points[ [i, j] ])

# loop over triangles:
# ia, ib, ic = indices of corner points of the triangle
for ia, ib, ic in tri.vertices:
    add_edge(ia, ib)
    add_edge(ib, ic)
    add_edge(ic, ia)

# plot it: the LineCollection is just a (maybe) faster way to plot lots of
# lines at once
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection

lines = LineCollection(edge_points)
plt.figure()
plt.title('Delaunay triangulation')
plt.gca().add_collection(lines)
plt.plot(points[:,0], points[:,1], 'o', hold=1)
plt.xlim(-1, 2)
plt.ylim(-1, 2)

# -- the same stuff for the convex hull

edges = set()
edge_points = []

for ia, ib in tri.convex_hull:
    add_edge(ia, ib)

lines = LineCollection(edge_points)
plt.figure()
plt.title('Convex hull')
plt.gca().add_collection(lines)
plt.plot(points[:,0], points[:,1], 'o', hold=1)
plt.xlim(-1, 2)
plt.ylim(-1, 2)
plt.show()

rawDescription: python scipy Delaunay plotting point cloud

description: Python scipy Delaunay plotting point cloud


code:
from queue import Empty, Queue
from threading import Lock, Thread
from time import perf_counter

def drill_folder_loop(folder_list, project_id, directory, jsession_id):
    while True:
        next_folder_list = []
        for folder in folder_list:
            f_name, f_id = folder.popitem()
            f_dict = list_folders_files(f_id, jsession_id)
            f_list = process_folder_files(f_dict, directory, jsession_id)
            recipient_process(f_dict, 'no', f_id, directory, project_id)
            next_folder_list.extend(f_list)
        if not next_folder_list:
            break
        folder_list = next_folder_list
    return log_info('Folder loop complete')

###############################################################################

class ThreadPool:

    def __init__(self, count, timeout, daemonic):
        self.__busy = 0
        self.__idle = perf_counter()
        self.__jobs = Queue()
        self.__lock = Lock()
        self.__pool = []
        self.__timeout = timeout
        for _ in range(count):
            thread = Thread(target=self.__worker)
            thread.daemon = daemonic
            thread.start()
            self.__pool.append(thread)

    def __worker(self):
        while True:
            try:
                function, args, kwargs = self.__jobs.get(True, 0.1)
            except Empty:
                with self.__lock:
                    if self.__busy:
                        continue
                    if perf_counter() - self.__idle < self.__timeout:
                        continue
                    break
            else:
                with self.__lock:
                    self.__busy += 1
                try:
                    function(*args, **kwargs)
                except:
                    pass
                with self.__lock:
                    self.__busy -= 1
                    self.__idle = perf_counter()

    def apply(self, function, *args, **kwargs):
        self.__pool = list(filter(Thread.is_alive, self.__pool))
        if not self.__pool:
            raise RuntimeError('ThreadPool has no running Threads')
        self.__jobs.put((function, args, kwargs))

    def join(self):
        for thread in self.__pool:
            thread.join()

def drill_folder_loop(folder_list, project_id, directory, jsession_id):
    tp = ThreadPool(25, 1, False)
    tp.apply(dfl_worker, tp, folder_list, project_id, directory, jsession_id)
    tp.join()

def dfl_worker(tp, folder_list, project_id, directory, jsession_id):
    for folder in folder_list:
        f_name, f_id = folder.popitem()
        f_dict = list_folders_files(f_id, jsession_id)
        f_list = process_folder_files(f_dict, directory, jsession_id)
        tp.apply(dfl_worker, tp, f_list, project_id, directory, jsession_id)
        recipient_process(f_dict, 'no', f_id, directory, project_id)
    log_info('One folder processed')

rawDescription: Python - How do I make the below function threaded?


code:
def check(matrix):
    # flatten up the matrix into one single list
    # and set on the list it should be [0,1] if it
    # contains only 0 and 1. Then do sum on that will
    # return 1
    if sum(set(sum(matrix,[]))) > 1:
        return False
    return True
check([[1,0,1], [1,1,0], [0,0,0]])
check([[1,0,1], [1,1,0], [0,0,2]])
check([[1,0,1], [1,1,0], [0,0,3]])

rawDescription: How does one test if a matrix in Python has only 1's and 0's?

description: Test if a matrix in Python has only 1's and 0's


rawDescription: Why is calling float() on a number slower than adding 0.0 in Python?


code:
"""
tkentrycomplete.py

A Tkinter widget that features autocompletion.

Created by Mitja Martini on 2008-11-29.
Updated by Russell Adams, 2011/01/24 to support Python 3 and Combobox.
Updated by Dominic Kexel to use Tkinter and ttk instead of tkinter and tkinter.ttk
   Licensed same as original (not specified?), or public domain, whichever is less restrictive.
"""
import sys
import os
import Tkinter
import ttk

__version__ = "1.1"

# I may have broken the unicode...
Tkinter_umlauts=['odiaeresis', 'adiaeresis', 'udiaeresis', 'Odiaeresis', 'Adiaeresis', 'Udiaeresis', 'ssharp']

class AutocompleteEntry(Tkinter.Entry):
        """
        Subclass of Tkinter.Entry that features autocompletion.

        To enable autocompletion use set_completion_list(list) to define
        a list of possible strings to hit.
        To cycle through hits use down and up arrow keys.
        """
        def set_completion_list(self, completion_list):
                self._completion_list = sorted(completion_list, key=str.lower) # Work with a sorted list
                self._hits = []
                self._hit_index = 0
                self.position = 0
                self.bind('<KeyRelease>', self.handle_keyrelease)

        def autocomplete(self, delta=0):
                """autocomplete the Entry, delta may be 0/1/-1 to cycle through possible hits"""
                if delta: # need to delete selection otherwise we would fix the current position
                        self.delete(self.position, Tkinter.END)
                else: # set position to end so selection starts where textentry ended
                        self.position = len(self.get())
                # collect hits
                _hits = []
                for element in self._completion_list:
                        if element.lower().startswith(self.get().lower()):  # Match case-insensitively
                                _hits.append(element)
                # if we have a new hit list, keep this in mind
                if _hits != self._hits:
                        self._hit_index = 0
                        self._hits=_hits
                # only allow cycling if we are in a known hit list
                if _hits == self._hits and self._hits:
                        self._hit_index = (self._hit_index + delta) % len(self._hits)
                # now finally perform the auto completion
                if self._hits:
                        self.delete(0,Tkinter.END)
                        self.insert(0,self._hits[self._hit_index])
                        self.select_range(self.position,Tkinter.END)

        def handle_keyrelease(self, event):
                """event handler for the keyrelease event on this widget"""
                if event.keysym == "BackSpace":
                        self.delete(self.index(Tkinter.INSERT), Tkinter.END)
                        self.position = self.index(Tkinter.END)
                if event.keysym == "Left":
                        if self.position < self.index(Tkinter.END): # delete the selection
                                self.delete(self.position, Tkinter.END)
                        else:
                                self.position = self.position-1 # delete one character
                                self.delete(self.position, Tkinter.END)
                if event.keysym == "Right":
                        self.position = self.index(Tkinter.END) # go to end (no selection)
                if event.keysym == "Down":
                        self.autocomplete(1) # cycle to next hit
                if event.keysym == "Up":
                        self.autocomplete(-1) # cycle to previous hit
                if len(event.keysym) == 1 or event.keysym in Tkinter_umlauts:
                        self.autocomplete()

class AutocompleteCombobox(ttk.Combobox):

        def set_completion_list(self, completion_list):
                """Use our completion list as our drop down selection menu, arrows move through menu."""
                self._completion_list = sorted(completion_list, key=str.lower) # Work with a sorted list
                self._hits = []
                self._hit_index = 0
                self.position = 0
                self.bind('<KeyRelease>', self.handle_keyrelease)
                self['values'] = self._completion_list  # Setup our popup menu

        def autocomplete(self, delta=0):
                """autocomplete the Combobox, delta may be 0/1/-1 to cycle through possible hits"""
                if delta: # need to delete selection otherwise we would fix the current position
                        self.delete(self.position, Tkinter.END)
                else: # set position to end so selection starts where textentry ended
                        self.position = len(self.get())
                # collect hits
                _hits = []
                for element in self._completion_list:
                        if element.lower().startswith(self.get().lower()): # Match case insensitively
                                _hits.append(element)
                # if we have a new hit list, keep this in mind
                if _hits != self._hits:
                        self._hit_index = 0
                        self._hits=_hits
                # only allow cycling if we are in a known hit list
                if _hits == self._hits and self._hits:
                        self._hit_index = (self._hit_index + delta) % len(self._hits)
                # now finally perform the auto completion
                if self._hits:
                        self.delete(0,Tkinter.END)
                        self.insert(0,self._hits[self._hit_index])
                        self.select_range(self.position,Tkinter.END)

        def handle_keyrelease(self, event):
                """event handler for the keyrelease event on this widget"""
                if event.keysym == "BackSpace":
                        self.delete(self.index(Tkinter.INSERT), Tkinter.END)
                        self.position = self.index(Tkinter.END)
                if event.keysym == "Left":
                        if self.position < self.index(Tkinter.END): # delete the selection
                                self.delete(self.position, Tkinter.END)
                        else:
                                self.position = self.position-1 # delete one character
                                self.delete(self.position, Tkinter.END)
                if event.keysym == "Right":
                        self.position = self.index(Tkinter.END) # go to end (no selection)
                if len(event.keysym) == 1:
                        self.autocomplete()
                # No need for up/down, we'll jump to the popup
                # list at the position of the autocompletion

def test(test_list):
        """Run a mini application to test the AutocompleteEntry Widget."""
        root = Tkinter.Tk(className=' AutocompleteEntry demo')
        entry = AutocompleteEntry(root)
        entry.set_completion_list(test_list)
        entry.pack()
        entry.focus_set()
        combo = AutocompleteCombobox(root)
        combo.set_completion_list(test_list)
        combo.pack()
        combo.focus_set()
        # I used a tiling WM with no controls, added a shortcut to quit
        root.bind('<Control-Q>', lambda event=None: root.destroy())
        root.bind('<Control-q>', lambda event=None: root.destroy())
        root.mainloop()

if __name__ == '__main__':
        test_list = ('apple', 'banana', 'CranBerry', 'dogwood', 'alpha', 'Acorn', 'Anise' )
        test(test_list)

rawDescription: Tkinter - How to create a combo box with autocompletion


code:
lst = [1, 2, 3]
print('\n'.join('{}: {}'.format(*k) for k in enumerate(lst)))

rawDescription: In Python, is there an elegant way to print a list in a custom format without explicit looping?


code:
import unicodedata
foo = u'１２３４５６７８９０'
unicodedata.normalize('NFKC', foo)

rawDescription: Python: How can I replace full-width characters with half-width characters?


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()
url = 'https://www.aircanada.com/en/'
browser.get(url)

input_field = browser.find_element_by_id('departure1')

browser.execute_script("arguments[0].value = ''", input_field)
input_field.send_keys('12/04/2014')
input_field.send_keys(Keys.RETURN)

rawDescription: How to replace default values in the text field using selenium python?

description: Replace default values in the text field using selenium python


code:
import re
re.escape('escape this. /')

re.escape('www.stackoverflow.com')

rawDescription: What is best practice for escaping special characters from a python string?


code:
import csv

headers = None
records = {}

reader = csv.reader(open(csvFile))

# So we can have lists as entries by default
from collections import defaultdict
index = {}

for row in reader:
    if reader.line_num == 1:
        headers = row
        # We'll set up rows to be a dictionary with one defaultdict
        # for each of the headers, mapping the unique values to the
        # rows that match
        index = dict((header, defaultdict(list)) for header in headers)
    else:
        for header, value in zip(headers, row):
            index[header][value].append(reader.line_num)

# Now, you can find out which rows have, say, 'Location' set to a given value
index['Location']['201682']

# Or all the rows with 'Time' set to '1:00:00 AM'
index['Time']['1:00:00 AM']

rawDescription: Efficiently creating a dictionary of dictionaries from very large csv data


code:
import boto.ses
from boto.regioninfo import RegionInfo
region = RegionInfo(None, "eu-west-1", "email.eu-west-1.amazonaws.com")
conn = boto.ses.SESConnection(region=region,aws_access_key_id='<key_id>', aws_secret_access_key='<secret_key>')

rawDescription: EU region not available when connecting SES using boto


rawDescription: pandas pivot dataframe structure

description: Pandas pivot dataframe structure


code:
df  = read_csv(filename, index_col = 0,header = 0)
self.datatable = QtGui.QTableWidget(parent=self)
self.datatable.setColumnCount(len(df.columns))
self.datatable.setRowCount(len(df.index))
for i in range(len(df.index)):
    for j in range(len(df.columns)):
        self.datatable.setItem(i,j,QtGui.QTableWidgetItem(str(df.iget_value(i, j))))

rawDescription: Python / Pandas - GUI for viewing a DataFrame or Matrix


code:
with open('data.txt') as fin, open('outfile.txt','w') as fout:
    for line in fin:
        if line.startswith("#"):
            fout.write(line)
            continue
        fields = line.split()
        fields[1] = "0" if float(fields[-1]) < 8 else "1"
        fout.write(" ".join(fields) + "\n")

rawDescription: how to read a data txt file and change a value under specific condition in python

description: Read a data txt file and change a value under specific condition in python


code: ['cplusplus' if i in b else i for i in a]

rawDescription: Python: Replace occurrences of items in multiple lists?


code:
from sqlalchemy import literal

a = session.query(literal(1).label('x')).cte('a')
b = session.query(a.c.x.label('y')).cte('b')
res = session.query(b).all()

assert res[0].y == 1

rawDescription: Dependent CTEs in SQLAlchemy? (example inside)


code:
from simplecrypt import encrypt, decrypt
ciphertext = encrypt('password', plaintext)
plaintext = decrypt('password', ciphertext)

rawDescription: Encrypting strings in python with no knowledge of cryptography


code:
import datetime
import time

datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")

rawDescription: How to convert `ctime` to `datetime` in Python?

description: Convert `ctime` to `datetime` in Python


code:
#!/usr/bin/env python3

import time
import random
from datetime import datetime

"""
1) Trying to use 'input' from like 20 thread simultaneously is probably
   not a great idea.
2) You should read the PEP8
3) Good thing you're using Python 3 :-)
4) You should write shorter methods, aroudn 25 lines max
5) Why do you need background tasks ?

If you think you need background tasks to increment a variable each
second, that's probably not the easier way to start. A good may may
probably better to "simulated" this, like storing the last time the
player have seen its credits, computing the number of seconds since
then, and adding it just before printing again.

Don't forget to drop a line or two of doc to explain what you're
doing.
"""

class Shop():
    def __init__(self):
        """Initial stock, as an example about the class Shop managing its own rules
        """
        self.scavs = 100

    def player_enters(self, player):
        print("Welcome to the shop!")
        time.sleep(1)
        print("Here you can buy items which will produce caps, making your "
              "job easier!")
        time.sleep(1)
        shop_option = input("Would you like to (buy) or (exit)? \n")
        time.sleep(0.4)
        while shop_option == "buy":
            print("(S)cavenger (10 caps per second) : 500 caps")
            print("(C)ap magnet (20 caps per second) : 1000 caps")
            print("(F)actory cap press (100 caps per second) : 5000 caps")

            buy_option = input()

            if buy_option == "S":
                if self.scavs < 1:
                    print("Sorry, no moar scavs here")
                elif player.value < 500:
                    print("Sorry, you don't have enough caps. Get more!")
                elif player.value >= 500:
                    player.give(500)
                    player.scav += 1
                    print("Thank you for purchasing a Scavenger, "
                          "you now have ", player.scav, "Scavengers!")
                    shop_option = input("Please enter anything to exit "
                                        "the shop. \n")

class Player():
    """That's not completly necessary, but a good example, you can use a
    class to store information about something, and how to modify it.
    """
    def __init__(self):
        self._value = 0
        self.scav = 0
        self.magnet = 0
        self.press = 0
        self.last_checked = datetime.now()

    def give(self, value):
        self._value -= value

    def receive(self, value):
        self._value += value

    @property
    def value(self):
        now = datetime.now()
        seconds = (now - self.last_checked).total_seconds()
        self.last_checked = now
        self._value += int((self.scav * 10 +
                            self.magnet * 20 +
                            self.press * 100) * seconds)
        return self._value

    def will_find_some_caps(self, rand_min, rand_max):
        """Here you should find a better name for this method. Naming is
        important (and complicated).
        """
        cap_chance = random.randint(rand_min, rand_max)
        print("You have found {} caps!".format(cap_chance))
        self._value += cap_chance
        print("\nYou now have {} caps!\n".format(self.value))

    def search(self):
        """Here, your succession of if/elsif is wrong, the first one is >= 50,
        which completly hide the second one, being >= 85.  I also
        doubt about using random to choose a range for random, you're
        not adding randomness to randomness, that's useless, what
        about a single, simple, self.will_find_some_caps(0, 250) ?
        """
        progress("Searching for caps.")
        search_chance = random.randint(0, 100)
        if search_chance >= 50:
            self.will_find_some_caps(10, 50)
        elif search_chance >= 85:
            self.will_find_some_caps(5, 10)
        elif search_chance >= 40:
            self.will_find_some_caps(25, 75)
        elif search_chance >= 25:
            self.will_find_some_caps(40, 120)
        elif search_chance <= 10:
            self.will_find_some_caps(60, 250)
        else:
            print("You haven't found any caps.")
            print("You now have {} caps!".format(self.value))

    def goto_shop(self, shop):
        shop.player_enters(self)

    def check(self):
        print("You have ", self.value, "caps!")
        print("You have ", self.scav, "Scavengers!")
        print("You have ", self.magnet, "Cap magnets!")
        print("You have ", self.press, "Factory cap presses!")

def progress(text):
    """Print text twice, with little sleeps in between
    """
    print(text + '.')
    time.sleep(.5)
    print(text + '..')
    time.sleep(.5)
    print(text + '...')
    time.sleep(1)

def cap_scavengerJob(player, shop):
    print("\nWelcome to Cap Scavenger!\n")
    time.sleep(1)
    progress("Searching for caps")

    start_chance = random.randint(65, 125)
    print("You have found ", start_chance, "caps!")
    player.receive(start_chance)
    print("Your goal is to find as many caps as you can!")
    while True:
        decision_search_1 = input(
            "Would you like to (search) for more caps, "
            "(check) how many caps you have or go to the (shop)? \n")
        if decision_search_1 == "search":
            player.search()
        elif decision_search_1 == "shop":
            player.goto_shop(shop)
        elif decision_search_1 == "check":
            player.check()
        elif decision_search_1 == "debug_mode":
            print("Debug Mode activated!")
            player.receive(10000)

player1 = Player()
main_shop = Shop()

while True:
    cap_scavengerJob(player1, main_shop)

rawDescription: I need help creating a background loop in python


code:
def get_version():
    """Extract version string from PEX-INFO file"""
    my_pex_name = os.path.dirname(__file__)
    zip = zipfile.ZipFile(my_pex_name)
    with zip.open("PEX-INFO") as pex_info:
        return json.load(pex_info)['build_properties']['tag']

rawDescription: --version support in a Python program built with Pants


code: result = a or b or c or default

rawDescription: Pythonic way to select first variable that evaluates to True


code:
from crontab import CronTab

tab = CronTab()
cron = tab.new(command='/foo/bar')
cron.every_reboot()
tab.write()

rawDescription: Is there any Python wrapper around cron?

description: Is there any Python wrapper around cron


code:
def exponential(beta):
    return -beta * math.log(1.0 - random.random())

rawDescription: Does Python's random module have a substitute for numpy.random.exponential?


code: combo = {k: {i: eval(i)[k] for i in dicts} for k in eval(dicts[0]).keys()}

rawDescription: Merge dictionaries by key with dictionary names as subkeys


code:
for k in myDict:
    myDict[k] /= 2

rawDescription: For each value in dict?

description: For each value in dict


code:
import sys, pygame
window_size = ( 400, 400 )

white = ( 255, 255, 255 )

class Player():
  image = pygame.image.load( 'snikebodydraw.png')
  rect = image.get_rect()

player = Player()

screen = pygame.display.set_mode( window_size )

move = (0,0) # init movement

done = False

while not done:
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      sys.exit()

    if event.type == pygame.KEYDOWN:

      if event.key == pygame.K_LEFT:
        move = (-10, 0 )
      if event.key == pygame.K_RIGHT:
        move = ( 10, 0 )
      if event.key == pygame.K_UP:
        move = ( 0,-10 )
      if event.key == pygame.K_DOWN:
        move = ( 0, 10 )

  player.rect = player.rect.move(move)

  screen.fill( white )
  screen.blit( player.image, player.rect )

  pygame.display.flip()

rawDescription: Constant movement in snake game

description: Constant movement in snake game


code:
import types

class A(object):
    class B(object):
        pass

    class C(object):
        pass

def enumerate_nested_classes(_class):
    return [getattr(_class, n) for n in dir(_class) if not n.startswith('__')
            and isinstance(getattr(_class, n), (type, types.ClassType))]

assert enumerate_nested_classes(A) == [A.B, A.C]

rawDescription: How to enumerate nested classes in python?

description: Enumerate nested classes in python


code:
import numpy as np
import skimage.io as io
import skimage.filter as filter
import matplotlib.pyplot as plt

img = io.imread('62.jpg')
gray = np.sum(img, axis=2) # summed up over red, green, blue
#threshold = filter.threshold_otsu(gray) # delivers very high threshold
threshold = filter.threshold_isodata(gray) # works extremely well
#threshold = filter.threshold_yen(gray) # delivers even higher threshold
print(threshold)

plt.imshow(gray > threshold)
plt.show()

rawDescription: Extracting foreground image as mask by thresholding


code:
x = [['republikán']]
print(x)
print(x[0])
print(x[0][0])

rawDescription: n-gram generation for words of non english languages

description: N-gram generation for words of non english languages


code:
import scipy as sp
from scipy.misc import imread
from scipy.signal.signaltools import correlate2d as c2d
def get(i):
    # get JPG image as Scipy array, RGB (3 layer)
    data = imread('im%s.jpg' % i)
    # convert to grey-scale using W3C luminance calc
    data = sp.inner(data, [299, 587, 114]) / 1000.0
    # normalize per http://en.wikipedia.org/wiki/Cross-correlation
    return (data - data.mean()) / data.std()
im1 = get(1)
im2 = get(2)
im3 = get(3)
im1.shape
im2.shape
im3.shape
c11 = c2d(im1, im1, mode='same')  # baseline
c12 = c2d(im1, im2, mode='same')
c13 = c2d(im1, im3, mode='same')
c23 = c2d(im2, im3, mode='same')
c11.max(), c12.max(), c13.max(), c23.max()

rawDescription: Image comparison algorithm

description: Image comparison algorithm


code:
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class ToolBox(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        btn = [QPushButton('B', self) for i in range(6)]
        for Btn in btn:
            Btn.resize(30, 30)
        self.resize(60, 90)
        k = 0
        for i in range(6):
            btn[i].move((i%2)*30, k*30)
            k += 1 if i % 2 == 1 else 0

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.resize(300, 200)
        self.statusBar().showMessage('Ready!')

        exitAction = QAction(QIcon('idea.png'), 'Exit', self)
        exitAction.setStatusTip('Exit application')
        exitAction.setShortcut('Ctrl+Q')
        exitAction.triggered.connect(qApp.quit)

        menuBar = self.menuBar()
        fileMenu = menuBar.addMenu('File')
        fileMenu.addAction(exitAction)

        t = ToolBox()
        self.setCentralWidget(t)

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

rawDescription: QWidget cannot display on QMainWindow instance PyQt5


code:
def online_variance(data):
    n = 0
    mean = 0
    M2 = 0

    for x in data:
        n = n + 1
        delta = x - mean
        mean = mean + delta/n
        M2 = M2 + delta*(x - mean)

    variance = M2/(n - 1)
    return variance

rawDescription: calculating mean and standard deviation of the data which does not fit in memory using python

description: Calculating mean and standard deviation of the data which does not fit in memory using python


code:
sentence = "ASK NOT WHAT YOUR COUNTRY CAN DO FOR YOU ASK WHAT YOU CAN DO FOR YOUR COUNTRY"
keyword = input("Input a keyword from the sentence")
words = sentence.split(" ")
for (i, subword) in enumerate(words):
    if subword.lower() == keyword.lower():
        print (1+1)

rawDescription: I need to make this not case sensitive

description: I need to make this not case sensitive


code:
from collections import defaultdict

d = defaultdict(str)

with open('file') as file1:
    for line in file1:
        if line[0] == '>': #I'm assuming header/idnumber starts with '>'
            key = line.strip('\n')
        else:
            d[key] += line.strip('\n')

rawDescription: How do I make a dictionary out of a collection of FASTA?

description: Make a dictionary out of a collection of FASTA


code: a[np.arange(4)[:,None], idxs]

rawDescription: is it possible to use numpy.take to pick a list of indices?

description: Is it possible to use numpy.take to pick a list of indices


code:
i = 1
def cwprint(t,labels,color='black'):
    global i
    text = '{} {}'.format(i, t)
    labels.append (Label(cw,text=text,fg=color).grid(row=i))
    i += 1

labels = []
cwprint ('Hello', labels)
cwprint ('World', labels)

rawDescription: Python quotation mark canceler algorithm


code:
graph = facebook.GraphAPI(oauth_access_token)
tags = json.dumps([{'x':50, 'y':50, tag_uid:12345},
                    {'x':10, 'y':60, tag_text:'a turtle'}])
graph.put_photo(open('img.jpg'), 'Look at this cool photo!',
                    album_id_or_None, tags=tags)

rawDescription: How to implement a "send file to facebook" button in a native python gtk program?

description: Implement a "send file to facebook" button in a native python gtk program


code:
import datetime
date = datetime.date.today()
start_week = date - datetime.timedelta(date.weekday())
end_week = start_week + datetime.timedelta(7)
entries = Entry.objects.filter(created_at__range=[start_week, end_week])

rawDescription: Django/Python - Check a date is in current week


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

# generate data
x = np.arange(0, 360, 1.5)
y = np.arange(-90, 90, 1.5)
lon, lat = np.meshgrid(x, y)
noise = np.random.random(lon.shape)

# specify levels from vmim to vmax
levels = np.arange(-1, 2.1, 0.2)

# plot
fig = plt.figure()
ax = fig.add_subplot(111)
plt.contourf(lon, lat, noise, levels=levels)
plt.colorbar(ticks=levels)
plt.show()

rawDescription: Setting colorbar to show values outside of data range in matplotlib


rawDescription: paint several x,y series of values in one with matplotlib in python

description: Paint several x,y series of values in one with matplotlib in python


code:
from twill.commands import go, showforms, formclear, fv, submit

go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()

formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()

submit('0')

rawDescription: Python WWW macro

description: Python WWW macro


code:
def c_to_nex(self, event):#Hitting 'Return' on 'c' calls this, setting focus back to 'dirdisplay' treeview, giving focus to child immediately below what was originally clicked.
    #Do whatever with data in c
    print('Focus acknowledged')
    print(self.nextID)#Feedback to show me the nextID actually exists when I hit 'Return'
    self.dirdisplay.focus_set()
    self.dirdisplay.selection_set((self.nextID, self.nextID))
    self.dirdisplay.focus(self.nextID)

rawDescription: How to set focus to a specific child in a ttk.Treeview similar to clicking on it?

description: Set focus to a specific child in a ttk.Treeview similar to clicking on it


code:
def check_time(self):
        for game in self.games:
            if self.games[game]['state'] == 'GAME':
                game_start_time = self.games[game]['starttime']
                if game_start_time is None:
                    continue
                elif game_start_time + 300 > time.time():
                    #300 seconds = 5 minutes.
                    continue
                else:
                    self.end_game(game)
def __init__(self):
    self.timecheck = task.LoopingCall(self.check_time)
    self.timecheck.start(1)

rawDescription: Run a function each tick in Twisted

description: Run a function each tick in Twisted


code:
import numpy as np
import mpmath as mpm
x = np.array(mpm.arange(0,4))

sin = np.vectorize(mpm.sin)
y = sin(x)

rawDescription: Element-wise operations in mpmath

description: Element-wise operations in mpmath


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

rawDescription: python - read whole file at once

description: Python - read whole file at once


code: api.add_resource(File, '/<path:fname>')

rawDescription: How to pass file path in a REST API ala Dropbox using Flask-RESTful?

description: Pass file path in a REST API ala Dropbox using Flask-RESTful


rawDescription: Metro-like full-screen browser using PyQT/PySide


code:
class testone(object):
    def __init__(self):
        self.attone = None
        self.atttwo = None
        self.attthree = None

class testtwo(testone):
    def __init__(self):
        self.attfour = None
        super(testtwo, self).__init__()  # on python3 just use super()

rawDescription: Is it possible to implicitly assign attributes to a class, from an inherited class?


code:
def adjust_endpoint(length, endpoint, step):
     if endpoint < 0:
         endpoint += length
         if endpoint < 0:
             endpoint = -1 if step < 0 else 0
     elif endpoint >= length:
         endpoint = length - 1 if step < 0 else length
     return endpoint

def adjust_slice(length, start, stop, step):
     if step is None:
         step = 1
     elif step == 0:
         raise ValueError("step cannot be 0")

     if start is None:
         start = length - 1 if step < 0 else 0
     else:
         start = adjust_endpoint(length, start, step)

     if stop is None:
         stop = -1 if step < 0 else length
     else:
         stop = adjust_endpoint(length, stop, step)

     return start, stop, step

def slice_indices(length, start, stop, step):
     start, stop, step = adjust_slice(length, start, stop, step)
     i = start
     while (i > stop) if step < 0 else (i < stop):
         yield i
         i += step

def mySlice(L, start=None, stop=None, step=None):
     return [L[i] for i in slice_indices(len(L), start, stop, step)]

rawDescription: Implementing python slice notation

description: Implementing python slice notation


code:
path1 = "c:/fold1/fold2"
list_of_paths = ["c:\\fold1\\fold2","c:\\temp\\temp123"]
os.path.normpath(path1)
os.path.normpath(path1) in list_of_paths
os.path.normpath(path1) in (os.path.normpath(p) for p in list_of_paths)

rawDescription: Comparing two paths in python

description: Comparing two paths in python


code:
clicked = []
foo = Button(root, text='bar', command=lambda self:clicked.append(self))

rawDescription: basic question about tkinter buttons

description: Basic question about tkinter buttons


code:
from urlparse import urljoin
...
url = post.xpath('./a/@href').extract_first()
new_url = urljoin(response.url, url) # someurl.com/leave.php?...
yield Request(new_url, ...)
...

rawDescription: Adding string to scraped url (scrapy)

description: Adding string to scraped url (scrapy)


code:
x = (1,)
y = (x, x)
z = ((1,), (1,))
y == z
pickle.dumps(y) == pickle.dumps(z)

rawDescription: Is there some way to test whether two pkl files have the same data in python?


code:
data = sc.textFile("textfile_location")
data = data.map(lambda line: (line.split(":")[0], line.split(":")[1].split()))
data = data.flatMap(lambda key, values: [(key, value) for value in values])

rawDescription: How to map each line to get multiline output rdd

description: Map each line to get multiline output rdd


code:
#!/usr/bin/env python
# http://stackoverflow.com/questions/22869427/how-to-print-hello-world-to-console
import SOAPpy
import logging
logging.getLogger().setLevel(logging.DEBUG)

item_str='<?xml version="1.0" encoding="utf-8"?>\
         <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" \
            xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" \
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">\
            <soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\
                <Item xsi:type="Dp_Data">\
                    <UCPTname>Net/MB485/MAIN POWER/Fb/PowerSum</UCPTname>\
                    <UCPTlastUpdate>2014-04-04T13:34:17.441-04:00</UCPTlastUpdate>\
                    <UCPTformatDescription>#0000000000000000[0].SNVT_power_f#SI</UCPTformatDescription>\
                    <UCPTvalue LonFormat="#0000000000000000[0].SNVT_power_f#SI">9330.949</UCPTvalue>\
                    <UCPTpointStatus>AL_OFFLINE</UCPTpointStatus>\
                    <UCPTpriority>255</UCPTpriority>\
                    <UCPTpropagate>0</UCPTpropagate>\
                </Item>\
            </soap:Body>\
        </soap:Envelope>'
expected = { 'Item': {
    'UCPTname': (SOAPpy.NS.XSD, "string"),
    'UCPTlastUpdate': (SOAPpy.NS.XSD, "dateTime"),
    'UCPTpriority': (SOAPpy.NS.XSD, "unsignedByte"),
    'UCPTpropagate': (SOAPpy.NS.XSD, "boolean"),
}}

item = SOAPpy.parseSOAPRPC(item_str, rules=expected)
logging.debug("Name: %s" % item['UCPTname'])
logging.debug("Last update: %s" % (item['UCPTlastUpdate'],))
logging.debug("Priority: %s" % item['UCPTpriority'])
logging.debug("Should this be propagated? %s" % ('Yeep' if item['UCPTpropagate'] else 'Nopes'))

rawDescription: How to print "hello world" to console

description: Print "hello world" to console


code:
def avg(lsts):
    for lst in lsts:
        print(sum(lst)/len(lst))

rawDescription: Print out the averages of each list, within the list, one per line in Python


code:
import scipy.interpolate
data_locations = np.vstack(datalon.ravel(), datalat.ravel()).T
grid_locations = np.vstack(gridlon.ravel(), gridlat.ravel()).T
grid_data      = scipy.interpolate.griddata(data_locations, val.ravel(),
                                            grid_locations, method='nearest')

rawDescription: matplotlib.mlab.griddata very slow and returns array of nan when valid data is input

description: Matplotlib.mlab.griddata very slow and returns array of nan when valid data is input


rawDescription: Max and one-to-many and one-to-one relationship


code: res = list(set(a)^set(b))

rawDescription: Removing the common elements between two lists


code:
class A(QObject):
    def __init__(self):
        self.counter = 0
        Timer.singleShot(100, self.domath())

    Slot()
    def domath(self):
        # do the computation
        self.counter += 1
        if self.counter != 10:
            Timer.singleShot(100, self.domath())
        else:
            self.counter = 0;

rawDescription: Proper use of PyQt timer/sleep

description: Proper use of PyQt timer/sleep


code:
from google.appengine.api import users
import urllib
url = users.create_login_url()
url_dict = dict((p.split('=') for p in url.split('&')))
urllib.unquote_plus(url_dict['ahname'])

rawDescription: How do I get the application title of a Google AppEngine app from within that app

description: Get the application title of a Google AppEngine app from within that app


code:
r, w = os.pipe()
if os.fork() == 0:
    # Child process
    os.dup2(r, sys.stdin.fileno())
    os.close(r)
    os.close(w)
    os.execvp(...)
else:
    # Parent process
    os.close(r)
    os.write(w, 'yo')
    ...
    os.close(w)  # When done writing
    os.wait()

rawDescription: How to pipe to stdin of os.execv'd process in Python

description: Pipe to stdin of os.execv'd process in Python


code:
from zipfile import ZipFile
from io import StringIO
zname,zipextfile = 'zipcontainer.zip', 'file_in_archive'
istream = ZipFile(zname).open(zipextfile)
ostream = StringIO(istream.read())

rawDescription: ZipExtFile to Django File

description: ZipExtFile to Django File


code:
l1 = ['E', 'A', None, 'D', 'B', None, None, 'C']
l2 = ['B', None, None, 'C', 'E', 'A', None, 'D']

if len(l1) == len(l2) and set(l1) == set(l2):
    sep = ' '  # choose something that won't be in the data
    str_2l1 = sep.join(repr(x) for x in l1 + l1)
    str_l2 = sep.join(repr(x) for x in l2)
    return str_l2 in str_2l1
else:
    return False

rawDescription: Checking if two list have the same elements in it, in the same order, but with other starting points in Python


code: thread = threading.Thread(target=win.player.get_midi_in, args=(test,))

rawDescription: unable to release GIL with Cython when using callback-based C libraries

description: Unable to release GIL with Cython when using callback-based C libraries


code:
import urllib, urllib2
from django.http import HttpResponse
from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):
    def __init__(self, *args, **kwargs):
        self.capture_data = False
        self.data_list = []
        HTMLParser.__init__(self, *args, **kwargs)

    def handle_starttag(self, tag, attrs):
        if tag == 'td':
            self.capture_data = True

    def handle_endtag(self, tag):
        if tag == 'td':
            self.capture_data = False

    def handle_data(self, data):
        if self.capture_data and data and not data.isspace():
            self.data_list.append(data)

def parse_url(request):
    p = MyHTMLParser()
    url = 'http://www.mysite.com/lists.asp'
    content = urllib.urlopen(url).read()
    p.feed(content)
    return HttpResponse(str(p.data_list))

rawDescription: python - How to parse an HTML table

description: Python - How to parse an HTML table


code:
now = pygame.time.get_ticks()
if pressed(K_A) and now - when_moved > 10:
    when_moved = now
    move_left()
if pressed(K_SPACE) and now - when_shot > 1000:
    when_shot = now
    shoot()

rawDescription: How can I handle two keys, each with their own intervals, in pygame

description: Handle two keys, each with their own intervals, in pygame


code:
class StdoutRedirector(IORedirector):
   '''A class for redirecting stdout to this Text widget.'''
   def write(self,message):
      self.text_area.config(state = "normal")
      self.text_area.insert("insert", message)
      self.text_area.config(state = "disabled")

rawDescription: Tkinter: Redirect stdout to read-only Text


code:
data_files = [('Images', glob('Images/*.*')),
                            ]

includes = ['win32com.decimal_23', 'datetime']

excludes = ['_gtkagg', '_tkagg', 'bsddb', 'curses',  'pywin.debugger',
            'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl',
            'Tkconstants', 'Tkinter', 'unittest']
packages = []

dll_excludes = ['libgdk-win32-2.0-0.dll', 'libgobject-2.0-0.dll', 'tcl84.dll',
                'tk84.dll','MSVCP90.dll']

setup(
    data_files = data_files,
    options = {"py2exe": {"compressed": 2,
                          "optimize": 2,
                          "includes": includes,
                          "excludes": excludes,
                          "packages": packages,
                          "dll_excludes": dll_excludes,
                          "bundle_files": 1,
                          "dist_dir": "dist",
                          "xref": False,
                          "skip_archive": False,
                          "ascii": False,
                          "custom_boot_script": '',
                         }
              },
    zipfile = None,
    windows = [filename]
    )

rawDescription: Creating a Python .exe file: py2exe invalid image error


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

x_ra,y_ra = np.arange(0,10,1),np.arange(0,10,1)
x_rb,y_rb = np.arange(0,10,1),np.arange(1,11,1)
x_rc,y_rc = np.arange(0,10,1),np.arange(2,12,1)
x_rd,y_rd = np.arange(0,10,1),np.arange(3,13,1)
x_re,y_re = np.arange(0,10,1),np.arange(4,14,1)
x_rf,y_rf = np.arange(0,10,1),np.arange(5,15,1)

fig,ax = plt.subplots(1)
mylines = ax.plot(
            x_ra,y_ra,'g^-',
            x_rb,y_rb,'b-',
            x_rc,y_rc,'y^--',
            x_rd,y_rd,'^-',
            x_re,y_re,'b^-.',
            x_rf,y_rf,'--'
            )

ax.legend(mylines,['A','B','C','D','E','F'],loc=0)
plt.show()

rawDescription: getting custom legend on canvas on matplotlib

description: Getting custom legend on canvas on matplotlib


code:
def getPrime(num):
    count = 0
    i = 1
    highPrime = None
    while count < num:
        if isPrime(i):
            count += 1
            highPrime = i
        i += 1
    return highPrime

rawDescription: While loop not working properly in Python


code:
def __copy__(self):
    return SomeClass(self.somefield, self.otherfield, self.somethingelse)

rawDescription: Assign class to variable without dependencies in Python


code:
collection.find({"$and": [{"foo": {'$ne': 'bar'}},
                          {"foo": {'$exists': True}}]})

rawDescription: MongoDB/PyMongo: Querying multiple criteria - unexpected results


code:
import sys
from cx_Freeze import setup, Executable

# Dependencies are automatically detected, but it might need fine tuning. This example will include the os package, and omit the tkinter package
build_exe_options = {"packages": ["os"], "excludes": ["tkinter"]}

# GUI applications require a different base on Windows (the default is for a
# console application).
base = None
if sys.platform == "win32":
    base = "Win32GUI"

setup(  name = "test",
        version = "0.1",
        description = "My GUI application!",
        options = {"build_exe": build_exe_options},
        executables = [Executable("test.py", base=base)])

rawDescription: Python 3.5 App to .exe or copy libraries to another PC


code:
from PyQt4 import QtGui, QtCore
point = QtCore.QPointF(100.2, 144.23)
QtGui.QCursor.pos(), QtGui.QCursor.setPos(point.toPoint()), QtGui.QCursor.pos()
# (PyQt4.QtCore.QPoint(1335, 691), None, PyQt4.QtCore.QPoint(100, 144))

rawDescription: How to convert QPointf to QPoint in PyQt

description: Convert QPointf to QPoint in PyQt


rawDescription: can sprite group in pygame contain subgroups containing sprites apart from the normal sprites ?

description: Can sprite group in pygame contain subgroups containing sprites apart from the normal sprites


code:
aScanListNames = ["AIN0", "AIN1", "AIN2", "AIN3"]
suffixes = ["_NEGATIVE_CH", "_RANGE", "_RESOLUTION_INDEX", "_EF_CONFIG_D", "_EF_CONFIG_E"]
result = [name+suffix for name in aScanListNames for suffix in suffixes]

rawDescription: simplify expression in list comprehension

description: Simplify expression in list comprehension


code:
bytestr = struct.pack('>Q', 2592701575664680400)
bytestr
[ord(b) for b in bytestr]

rawDescription: Convert a 64 bit integer into 8 separate 1 byte integers in python


code:
import csv

infile = open('input.csv', "rb")
reader = csv.reader(infile)

outfile = open('output.csv', "wb")
writer = csv.writer(outfile)

found_keys = {}
for rows in reader:
    k, v = rows[18], rows[19]
    if k in found_keys and found_keys[k] != v:
        print("found duplicate key {} with different values {} , {}".format(k, v, found_keys[k]))
    else:
        found_keys[k] = v
        writer.writerow([k, v])

infile.close()
outfile.close()

rawDescription: Printing a dictionary to a CSV file when some keys have more than one value


code:
class SomeClass:
  x=6  # class variable

  def __init__(self):
    self.y = 666  # instance variable

rawDescription: Differences between static and instance variables in python. Do they even exist?


code: {{ form.question(value=q.question) }}

rawDescription: Passing a value to WTForms field with Jinja2


rawDescription: reversing the tuples in a list

description: Reversing the tuples in a list


code:
import re

def openFind():
    with open("test.txt", "r") as in_file:
        data = in_file.read()

    def sub(m):
        l = [s.strip() for s in m.group(1).split(",")]
        l.sort()
        return "{%s}" % (", ".join(l),)

    replacement = re.sub(r'{(.*?)}', sub, data)
    with open("out.txt", "w") as out_file:
        out_file.write(replacement)

rawDescription: Python arranging a list and writing it back to file


code:
class MyModel(mongoengine.Document):
    creation_date = mongo.DateTimeField()
    modified_date = mongo.DateTimeField(default=datetime.datetime.now)

    def save(self, *args, **kwargs):
        if not self.creation_date:
            self.creation_date = datetime.datetime.now()
        self.modified_date = datetime.datetime.now()
        return super(MyModel, self).save(*args, **kwargs)

rawDescription: Mongoengine creation_time attribute in Document


code:
data = [[1,2,3],[3,4],[5,6,7],[1,8,9,10]]

result = []

for d in data:
    d = set(d)

    matched = [d]
    unmatched = []
    # first divide into matching and non-matching groups
    for g in result:
        if d & g:
            matched.append(g)
        else:
            unmatched.append(g)
    # then combine all matching groups into one group
    # while leaving unmatched groups intact
    result = unmatched + [set().union(*matched)]

print(result)
# [set([5, 6, 7]), set([1, 2, 3, 4, 8, 9, 10])]

rawDescription: Collapse list of lists to eliminate redundancy


code:
# Store indexes
rdicts = [{'index': i, 'rectangle': r} for i, r in enumerate(rectangles)]
# Sort by width
rdicts.sort(key=lambda d: d['rectangle'][0], reverse=True)

placement = []
for rdict in rdicts:
    rectangle = rdict['rectangle']
    ... # do the rest of your algorithm
    # Add the calculated coordinate, along with the original index
    placement.append({'index': rdict['index'], 'coordinate': coordinate})

# Sort by the original index
placement.sort(key=lambda p: p['index'])
# Return the coordinates without the indexes.
ordered_placement = [p['coordinate'] for p in placement]

rawDescription: How to sort a collection based on another collection in Python?

description: Sort a collection based on another collection in Python


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

t = np.linspace(0, 10, 101)
y1, y2 = np.random.rand(2, 101)

fig, ax1 = plt.subplots()
ax2 = ax1.twiny()

fig.subplots_adjust(bottom=0.25)

ax1_pos = fig.add_axes([0.2, 0.1, 0.65, 0.03])
ax2_pos = fig.add_axes([0.2, 0.05, 0.65, 0.03])

s1 = Slider(ax1_pos, 'Pos1', 0.1, len(x))
s2 = Slider(ax2_pos, 'Pos2', 0.1, len(x))

def update1(v):
    pos = s1.val
    ax1.axis([pos,pos+2,0,1])
    fig.canvas.draw_idle()

def update2(v):
    pos = s2.val
    ax2.axis([pos,pos+2,0,1])
    fig.canvas.draw_idle()

s1.on_changed(update1)
s2.on_changed(update2)

ax1.plot(t, y1, 'b-')
ax2.plot(t, y2, 'r-')
plt.show()

rawDescription: Overlay plots and scroll independently matplotlib