code:
class TicTacToeGame:
    """
    A class that implements a tic tac toe game
    """

    # This is a class variable that contains
    # a list of all the winning combos
    winningCombos = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 9],
        [1, 4, 7],
        [2, 5, 8],
        [3, 6, 9],
        [1, 5, 9],
        [3, 5, 7]
    ]

    def __init__(self):
        """
        Init method. This gets called when you create a new game object
        We simply use this method to initialize all our instance variables
        """

        # The current player. Either X or O
        self.currentPlayer = 'X'

        # List of player x moves
        self.playerXMoves = []

        # List of player o moves
        self.playerOMoves = []

        # Whether or not the game has been won
        self.isWon = False

        # Whether or not the game is over
        self.isOver = False

        # The winning player
        self.winningPlayer = None

        # The number of moves played
        self.numberOfMovesPlayed = 0

    def doMakeAMoveAtPos(self, pos):
        """
        Makes a move in the game at the specified position
        1 is the first position, 5 is the center position, etc

        @param pos: The position (1 through 9)
        @type pos: int
        @rtype: None
        """

        # If the game has already been won
        if self.isWon:
            raise ValueError('The game has been won')

        # If the game is over, nobody won
        if self.isOver:
            raise ValueError('The game is a tie')

        # Make sure that the position is within range
        if pos < 1 or pos > 9:
            raise ValueError('Invalid position. Should be between 1 and 9')

        # Make sure the position isn't already taken
        if pos in self.playerXMoves or pos in self.playerOMoves:
            raise ValueError('The position: ' + str(pos) + ' is already taken')

        # Get the current player
        currentPlayer = self.currentPlayer

        # If the current player is X
        if currentPlayer == 'X':

            # Add the move and switch to player O
            currentPlayerMoves = self.playerXMoves
            currentPlayerMoves.append(pos)
            self.currentPlayer = 'O'

        # Otherwise, the current player is O
        else:

            # Add the move and switch to player X
            currentPlayerMoves = self.playerOMoves
            currentPlayerMoves.append(pos)
            self.currentPlayer = 'X'

        # Increment the number of plays.. You could just check the length of
        # playerXMoves and playerOMoves to get the total number of moves, but
        # we are going to keep track to avoid more code later
        self.numberOfMovesPlayed += 1

        # If the number of plays is 9, the game is over
        if self.numberOfMovesPlayed == 9:
            self.isOver = True

        # See if the game has been won

        # If there hasn't been enough moves to win yet, no winner
        if len(currentPlayerMoves) < 3:
            return

        # Iterate through each winning combo
        for winningCombo in self.winningCombos:

            # If each number is in the player's moves, the game has been won
            if set(winningCombo) <= set(currentPlayerMoves):

                self.isWon = True
                self.winningPlayer = currentPlayer
                return

# OK... Our Class has been defined.
# Now it's time to play tic tac toe.

# Define an input string. How you get this is up to you
# Change this to different numbers to see what you get.
inputString = '3 7 5 4 1 9 2 8 3 6 5 1 3 7 6 4 2 9 8 5 1 2 8 6 4 7 3 9'

# Parse the input string into a list of integers
moves = [int(move) for move in inputString.split()]

# Create the initial game
game = TicTacToeGame()

# Set the number of games to 1 (This is the first game after all)
numberOfGames = 1

# Go through all the moves 1 by 1
for pos in moves:

    # Try to make a move in the current game
    try:
        game.doMakeAMoveAtPos(pos)

    # But, since the input is unpredictable, we need to catch errors
    # What's to stop the input from being '1 1 1 1 1 1 1 1 1', etc
    # You can't keep playing position number 1 over and over
    except ValueError as exc:

        # Do what you want with the exception.
        # For this example, I'm just gonna print it
        # and move on the the next move
        print(exc)
        continue

    # If the game has been won
    if game.isWon:
        print('Game ' + str(numberOfGames) + ' Won On Move: ' + str(game.numberOfMovesPlayed) + ' Winning Player: ' + str(game.winningPlayer))

        # Since the game was won, create a new game
        game = TicTacToeGame()

        # And increment the game number
        numberOfGames += 1

    # If the game is a tie
    elif game.isOver:
        print('Game ' + str(numberOfGames) + ' Tie')

        # Since the game was a tie, create a new game
        game = TicTacToeGame()

        # And increment the game number
        numberOfGames += 1

# If there is an unfinished game, we can report this as well
if game.numberOfMovesPlayed > 0:
    print('Game ' + str(numberOfGames) + ' was not finished')

rawDescription: How can I check an array with a list of array values?

description: Check an array with a list of array values


code:
from oauth2client.appengine import StorageByKeyName
from model import Credentials

self.mirror_service = create_service(
        'mirror', 'v1',
        StorageByKeyName(Credentials, MY_USER_ID, 'credentials').get())
timeline_item = {'text': 'Test10'}
self.mirror_service.timeline().insert(body=timeline_item).execute()

rawDescription: Push a Timeline Card to a given User ID

description: Push a Timeline Card to a given User ID


code: from myspecialpackage import json as special_json

rawDescription: Module and package with same name

description: Module and package with same name


code: soup.find_all(lambda e: e.name == 'span' and e.attrs.get('id') == '')

rawDescription: Get content of tags with empty id in BeautifulSoup


code: (offsetx, offsety) = (-meanx + cenx, -meany + ceny)

rawDescription: Extracting polygon given coordinates from an image using OpenCV


code:
def gen_range(start, stop, step):
    current = start
    while current < stop:
        next_current = current + step
        if next_current < stop:
            yield (current, next_current)
        else:
            yield (current, stop)
        current = next_current

rawDescription: Generate list of range tuples with given boundaries in python


code:
from tkinter import *  # Use this if use python 3.xx
#from Tkinter import *   # Use this if use python 2.xx
a = Button(text="Center Button")
b = Button(text="Top Left Button")
c = Button(text="Bottom Right Button")

a.place(relx=0.5, rely=0.5, anchor=CENTER)
b.place(relx=0.0, rely=0.0, anchor=NW)
c.place(relx=1.0, rely=1.0, anchor=SE)
mainloop

rawDescription: Tkinter: How to make a button center itself?


code: yag.send('recipient@email.com', "this is the subject", str(w))

rawDescription: Storing return data of print Whois in Python


rawDescription: Replace character in HTML tag with REGEX


code:
def process_x(x):
    #================  Get title ==================#
    out_string = ""
    campaign = parseCampaign(x)
    out_string += ';' + str(campaign.getTitle())

    #================ Get Profile ==================#
    if campaign.getTitle() != 'NA':
        creator = parseCreator(campaign.getCreatorUrl())
        out_string += ';' + str(creator.getCreatorProfileLinkUrl())
    else:
        pass
    #================ Write ==================#
    out_string += '\n'
    return out_string

rawDescription: MultiThreading with a python loop

description: MultiThreading with a python loop


rawDescription: Different way to create an instance method object in Python


code:
import multiprocessing as mp

class Consumer(mp.Process):
    def __init__(self, task_queue, result_queue, arr, lock):
            mp.Process.__init__(self)
            self.task_queue = task_queue
            self.result_queue = result_queue
            self.arr = arr
            self.lock = lock

    def run(self):
            proc_name = self.name
            while True:
                next_task = self.task_queue.get()
                if next_task is None:
                    self.task_queue.task_done()
                    break
                answer = next_task(arr = self.arr, lock = self.lock)
                self.task_queue.task_done()
                self.result_queue.put(answer)
            return

class Task(object):
    def __init__(self, i):
        self.i = i

    def __call__(self, arr, lock):
        with lock:
            arr[self.i].value = "test {}".format(self.i)
            print([a.value for a in arr])

if __name__ == '__main__':
   tasks = mp.JoinableQueue()
   results = mp.Queue()
   arr = [mp.Array('c', 10) for i in range(3)]

   lock = mp.Lock()
   num_consumers = mp.cpu_count() * 2
   consumers = [Consumer(tasks, results, arr, lock) for i in xrange(num_consumers)]

   for w in consumers:
      w.start()

   for i in xrange(3):
      tasks.put(Task(i))

   for i in xrange(num_consumers):
      tasks.put(None)

   tasks.join()

rawDescription: Python : multiprocessing and Array of c_char_p


code:
sql = 'INSERT INTO table_name ({fields}) VALUES ({values})'
fields = ', '.join(query_data.keys())
values = ', '.join(['"{0}"'.format(value) for value in query_data.values()])
composed_sql = sql.format(fields=fields, values=values)

rawDescription: Python sql query insert data in columns

description: Python sql query insert data in columns


code:
class c:

    x=2
    y=5

    @classmethod
    def attrs(cls):
        return vars(cls)

rawDescription: how to get a dict of instance fields with in a class definition in python?

description: Get a dict of instance fields with in a class definition in python


code:
def run(init, description, cache=True, part=False, hashp=False,
    npart=16, n=6):
    times = []

    for i in range(n):
        start = datetime.datetime.now()

        init2 = procRDD(
                init.map(lambda n: (n, n*3)),
                cache, part, hashp, npart)
        init3 = procRDD(
                init.map(lambda n: (n, n*2)),
                cache, part, hashp, npart)

        # If part set to True limit number of the output partitions
        init4 = init2.join(init3, npart) if part else init2.join(init3)
        init = init4.map(lambda n: n[0])

        if cache:
            init4.cache()
            init.cache()

        init.count() # Force computations to get time
        end = datetime.datetime.now()

        times.append(get_stats(
            i, init, init2, init3, init4,
            start, end, description,
            cache, part, hashp
        ))

    return times

rawDescription: Spark iteration time increasing exponentially when using join


rawDescription: How to convert list to tuple and search for max and min

description: Convert list to tuple and search for max and min


code:
for product, product_id in data:
    hdd.update({'_id': product_id},
               {'$set': {'Speed': products['Speed'],
                         'capacity': products['capacity'],
                         'format': products['format']}})

rawDescription: PyMongo update multiple records with multiple data


code:
import time
inputstring = "Tue 24 Dec 2013  5:53 AM UTC"
timetup = time.strptime(inputstring, '%a %d %b %Y %I:%M %p %Z')
time.mktime(timetup) * 1000

rawDescription: Is there a built-in function or library that converts UTC time to milliseconds in Python?


code:
s = "STRING"
str.lower(s) # unbound method
s.lower()    # bound method

rawDescription: FTP_ASCII in Python

description: FTP_ASCII in Python


rawDescription: column max with list of matrices

description: Column max with list of matrices


code:
lst = [1, 2, 3, 4, 5, 6]
list(itertools.islice(lst, 0, None, 2))
list(itertools.islice(lst, 0, None, 2))

rawDescription: Python: How to transform a 'flat' sequence into a sequence of tuples?


code:
import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-t', nargs='+', type=str)

# If no argument is given to parse_args() then the argument strings of
# the program are taken from sys.argv. And be sure not to pass in
# sys.argv[0] if you specify them instead supply sys.argv[1:].
args = parser.parse_args()

print(args.t)

rawDescription: python argparse with time format

description: Python argparse with time format


rawDescription: Query current directory in Python (the one the script is running from)


code: {'bananas apples ': ['y'], 'apples oranges ': ['x', 'z']}

rawDescription: Extract partial duplicates from a list of lists; return single match with record of origin of each duplicate; Python


code:
class Room:
    registry = {}
    def __init__(self, name):
        if name in self.registry:
            raise ValueError('room named "{}" already exists'.format(name))
        self.registry[name] = self

rawDescription: How to reference an existing class object with no defined variable?

description: Reference an existing class object with no defined variable


code:
stringA = 'This is a'
stringB = 'test'
print(stringA + stringB)
print(stringA + ' ' + stringB)

rawDescription: Simple adding spaces between variables in python3


rawDescription: Facebook login with Django

description: Facebook login with Django


rawDescription: Evaluating and removing duplicate dicts from a Python list


code:
import json

@app.route('/mv')
def my_view():

    pq = my_object()

    # put all of the data into a list
    data = [p._data for p in pq]

    # render the template with our data
    return render_template('my_view.html', page_title = 'nothing yet', data=data)

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

rawDescription: Passing data to a view with flask

description: Passing data to a view with flask


rawDescription: How do I fit a quadratic surface to some points in Python?

description: Fit a quadratic surface to some points in Python


code:
#file commandline.py
from base import *

i1 = input() # in 3.X, raw_input in 2.X
r1 = f1(i1)

i2 = input() # in 3.X, raw_input in 2.X
r2 = f2(r1, i2)
r3 = f3(r2)

rawDescription: How to create a light GUI with TkInter

description: Create a light GUI with TkInter


code:
from werkzeug.routing import BaseConverter

class IntListConverter(BaseConverter):
    regex = r'\d+(?:,\d+)*,?'

    def to_python(self, value):
        return [int(x) for x in value.split(',')]

    def to_url(self, value):
        return ','.join(str(x) for x in value)

rawDescription: Capture a list of integers with a Flask route


rawDescription: Python List Variable - Is it using the memory location or something?


code:
while True:
    data = read_sensors()
    command = process(data)
    motor_do(command)
    time.sleep(delay)

rawDescription: How to multithread/multiprocess just one instance of a particular function in Python?

description: Multithread/multiprocess just one instance of a particular function in Python


code:
import numpy as np

# create an empty array (NaNs will be drawn transparent)
data = np.empty((50,50))
data[:,:] = np.nan

# ptlist is a list of (x, y, intensity) triplets
ptlist = np.array(ptlist)
data[ptlist[:,1].astype('int'), ptlist[:,0].astype('int')] = ptlist[:,2]

rawDescription: Python real time varying heat map plotting


rawDescription: including a negative number in the log sum of exponents, in python

description: Including a negative number in the log sum of exponents, in python


code: soup.find("p", class_=False, id=False)

rawDescription: Scraping elements without an id or class from a web page using Python BeautifulSoup


rawDescription: Sum of values across all nested dictionaries in python


code:
true
1

rawDescription: Python lxml - find tag block ammend

description: Python lxml - find tag block ammend


rawDescription: Is "norm" equivalent to "Euclidean distance"?


code:
if not b.endswith('s'):
    b += 's'

rawDescription: Most Pythonic and efficient way to insert character at end of string if not already there


code:
def reset_var():
    global var1
    global var2
    var1 = 0
    var2 = 0

rawDescription: How to make process to do some action upon user request in Python?

description: Make process to do some action upon user request in Python


rawDescription: How to cross 2 two-dimensional arrays in python?

description: Cross 2 two-dimensional arrays in python


code: sorted(DATABASE, key=lambda x: len(x['SPECIAL_KEY']), reverse=True)

rawDescription: Python3: Make itemgetter sort by string length


code:
@mock.path('code.OriginalClass')
def test_connection(self, mocked_conn):
    code.make_connection()
    mocked_conn.assert_called_with(host, port)
    mocked_instance = mocked_conn.return_value
    mocked_instance.connect.assert_called_once()
    mocked_instance.send.assert_called_with(param)

rawDescription: Python Mock not asserting calls

description: Python Mock not asserting calls


rawDescription: Converting integers to bytes

description: Converting integers to bytes


code:
from itertools import combinations

[(i, j, i[0] == j[0]) for i, j in combinations(l, 2)]

rawDescription: Python cross matching

description: Python cross matching


code:
def my_formatter(x, pos):
    """Format 1 as 1, 0 as 0, and all values whose absolute values is between
    0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
    formatted as -.4)."""
    val_str = '{:g}'.format(x)
    if np.abs(x) > 0 and np.abs(x) < 1:
        return val_str.replace("0", "", 1)
    else:
        return val_str

rawDescription: removing leading 0 from matplotlib tick label formatting

description: Removing leading 0 from matplotlib tick label formatting


code:
formattime(7480)
formattime(0)

rawDescription: Format duration in minutes as weeks, days, hours, minutes


rawDescription: Specific data conversion in python

description: Specific data conversion in python


code:
from ctypes import *
from ctypes.wintypes import *

kernel32 = WinDLL('kernel32')
LPDWORD = POINTER(DWORD)
UCHAR = c_ubyte

GetFileAttributesW = kernel32.GetFileAttributesW
GetFileAttributesW.restype = DWORD
GetFileAttributesW.argtypes = (LPCWSTR,) #lpFileName In

INVALID_FILE_ATTRIBUTES = 0xFFFFFFFF
FILE_ATTRIBUTE_REPARSE_POINT = 0x00400

CreateFileW = kernel32.CreateFileW
CreateFileW.restype = HANDLE
CreateFileW.argtypes = (LPCWSTR, #lpFileName In
                        DWORD,   #dwDesiredAccess In
                        DWORD,   #dwShareMode In
                        LPVOID,  #lpSecurityAttributes In_opt
                        DWORD,   #dwCreationDisposition In
                        DWORD,   #dwFlagsAndAttributes In
                        HANDLE)  #hTemplateFile In_opt

CloseHandle = kernel32.CloseHandle
CloseHandle.restype = BOOL
CloseHandle.argtypes = (HANDLE,) #hObject In

INVALID_HANDLE_VALUE = HANDLE(-1).value
OPEN_EXISTING = 3
FILE_FLAG_BACKUP_SEMANTICS = 0x02000000
FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000

DeviceIoControl = kernel32.DeviceIoControl
DeviceIoControl.restype = BOOL
DeviceIoControl.argtypes = (HANDLE,  #hDevice In
                            DWORD,   #dwIoControlCode In
                            LPVOID,  #lpInBuffer In_opt
                            DWORD,   #nInBufferSize In
                            LPVOID,  #lpOutBuffer Out_opt
                            DWORD,   #nOutBufferSize In
                            LPDWORD, #lpBytesReturned Out_opt
                            LPVOID)  #lpOverlapped Inout_opt

FSCTL_GET_REPARSE_POINT = 0x000900A8
IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003
IO_REPARSE_TAG_SYMLINK = 0xA000000C
MAXIMUM_REPARSE_DATA_BUFFER_SIZE = 0x4000

class GENERIC_REPARSE_BUFFER(Structure):
    _fields_ = (('DataBuffer', UCHAR * 1),)

class SYMBOLIC_LINK_REPARSE_BUFFER(Structure):
    _fields_ = (('SubstituteNameOffset', USHORT),
                ('SubstituteNameLength', USHORT),
                ('PrintNameOffset', USHORT),
                ('PrintNameLength', USHORT),
                ('Flags', ULONG),
                ('PathBuffer', WCHAR * 1))
    @property
    def PrintName(self):
        arrayt = WCHAR * (self.PrintNameLength // 2)
        offset = type(self).PathBuffer.offset + self.PrintNameOffset
        return arrayt.from_address(addressof(self) + offset).value

class MOUNT_POINT_REPARSE_BUFFER(Structure):
    _fields_ = (('SubstituteNameOffset', USHORT),
                ('SubstituteNameLength', USHORT),
                ('PrintNameOffset', USHORT),
                ('PrintNameLength', USHORT),
                ('PathBuffer', WCHAR * 1))
    @property
    def PrintName(self):
        arrayt = WCHAR * (self.PrintNameLength // 2)
        offset = type(self).PathBuffer.offset + self.PrintNameOffset
        return arrayt.from_address(addressof(self) + offset).value

class REPARSE_DATA_BUFFER(Structure):
    class REPARSE_BUFFER(Union):
        _fields_ = (('SymbolicLinkReparseBuffer',
                        SYMBOLIC_LINK_REPARSE_BUFFER),
                    ('MountPointReparseBuffer',
                        MOUNT_POINT_REPARSE_BUFFER),
                    ('GenericReparseBuffer',
                        GENERIC_REPARSE_BUFFER))
    _fields_ = (('ReparseTag', ULONG),
                ('ReparseDataLength', USHORT),
                ('Reserved', USHORT),
                ('ReparseBuffer', REPARSE_BUFFER))
    _anonymous_ = ('ReparseBuffer',)

def islink(path):
    result = GetFileAttributesW(path)
    if result == INVALID_FILE_ATTRIBUTES:
        raise WinError()
    return bool(result & FILE_ATTRIBUTE_REPARSE_POINT)

def readlink(path):
    reparse_point_handle = CreateFileW(path,
                                       0,
                                       0,
                                       None,
                                       OPEN_EXISTING,
                                       FILE_FLAG_OPEN_REPARSE_POINT |
                                       FILE_FLAG_BACKUP_SEMANTICS,
                                       None)
    if reparse_point_handle == INVALID_HANDLE_VALUE:
        raise WinError()
    target_buffer = c_buffer(MAXIMUM_REPARSE_DATA_BUFFER_SIZE)
    n_bytes_returned = DWORD()
    io_result = DeviceIoControl(reparse_point_handle,
                                FSCTL_GET_REPARSE_POINT,
                                None, 0,
                                target_buffer, len(target_buffer),
                                byref(n_bytes_returned),
                                None)
    CloseHandle(reparse_point_handle)
    if not io_result:
        raise WinError()
    rdb = REPARSE_DATA_BUFFER.from_buffer(target_buffer)
    if rdb.ReparseTag == IO_REPARSE_TAG_SYMLINK:
        return rdb.SymbolicLinkReparseBuffer.PrintName
    elif rdb.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT:
        return rdb.MountPointReparseBuffer.PrintName
    raise ValueError("not a link")

rawDescription: Having trouble implementing a readlink() function


code:
def plus_minus(s):
    if len(s) <= 1:
        yield s
        return
    for x in ["", "+", "-"]:
        for y in plus_minus(s[1:]):
            yield s[0] + x + y

rawDescription: Taking a string of numbers and inserting + and - operators


code:
from django.http import HttpResponse
from my_project.models import *

def index(request):
    f = open('myfile.zip')
    contents = f.read()
    f.close()

    record = TestModel(name = 'My File', zip_file = contents)
    record.save()

    result = SkinDetails.objects(name='Metro Skin')

    zip_contents = result[0].zip_file

    response = HttpResponse(zip_contents, content_type='application/zip')
    response['Content-Disposition'] = 'attachment; filename="My_File.zip"'
    return response

rawDescription: Saving and retrieving Blob data from MongoDB


code:
for letter in keyString:
    cipherVariables.append(getattr(cipher, letter))

rawDescription: Using a variable with module functions

description: Using a variable with module functions


code:
def main():
    states1 = ["AL", "AK", "AR", "AZ", "CA", "CO", "CT", "DE", "FL", "GA"]
    for words in states1:
        print(words, end=" ")
    states2 = states1[3:7]
    states2 = list_func(states2)
    # don't forget to print here

def list_func(states2):
    states2.pop(1)
    states2.insert(1, 'TX')
    state_variable = input("Enter the abbreviation of another state of your choice: ")
    states2.append(state_variable)
    states2.reverse(states2)
    returned_states = list_func(states2)
    print(returned_states)
    return states2

main()

rawDescription: Loops/Functions and State abbreviations

description: Loops/Functions and State abbreviations


code:
with doing_xy():
    print('do_something')
    print('do_other_thing')

with doing_xy():
    print('do_third_thing')
    print('do_fourth_thing')

rawDescription: Run some common code before and after a block


rawDescription: Vectorized version of for-loop + numpy.where


code: y = line.split()

rawDescription: Python: How to separate string with comma


code:
mutable_post = request.POST.copy()
mutable_post['foo'] = 'bar'

form = MyForm(mutable_post)

rawDescription: Additional field in django form

description: Additional field in django form


code:
UPLOADS_DEFAULT_DEST = '/var/uploads/'
UPLOADS_DEFAULT_URL = 'http://localhost:5000/'

rawDescription: What does UPLOADS_DEFAULT_URL configuration value in flask uploads mean?


rawDescription: DataFrame balancing by using reindex

description: DataFrame balancing by using reindex


rawDescription: Support QtCore library path in PyInstaller


code:
class Article(model.Model):
    ...
    author = models.ForeignKey(Author, related_name='articles')

rawDescription: Reverse ForeignKey lookup

description: Reverse ForeignKey lookup


code:
df.select(df.columns
  .drop(1)
  .map(col)
  .reduce(_ + _)
  .divide(df.columns.size - 1)
  .alias("mean"))

rawDescription: Spark DataFrame: Computing row-wise mean (or any aggregate operation)


code:
d = {'abc': 1, 'def': 2}
repr(d)
repr(repr(d))

rawDescription: Interesting Behavior with Dictionary and ast.literal_eval


code:
import Tkinter as tk
import ttk

root = tk.Tk()

frame = ttk.Frame(root)
frame.pack(fill=tk.BOTH, expand=True)
frame.columnconfigure(index=0, weight=1)
frame.columnconfigure(index=2, weight=1)
frame.rowconfigure(index=0, weight=1)
frame.rowconfigure(index=2, weight=1)

rawDescription: Tkinter button distance from window edges


code:
from flask import Flask
from flask.ext.cache import Cache
application = Flask(__name__)
cache = Cache(application, config={'CACHE_TYPE': 'simple'})

rawDescription: Generate a static page from a Jinja template and serve it with Flask


code:
from itertools import chain

nature = "cow"
creator = ""
minor = ""
item = "hammer"
NAMEPROPERTIES = [nature, creator, minor]
propertiestrue = filter(None, NAMEPROPERTIES)

print(*chain(propertiestrue , [item]))

rawDescription: Printing variable after filter objects python 3.3


code: cell_list = [{'num':1, 'state':0} for j in range(2)]

rawDescription: problem with a 2 dimensional array(list of list of dict)

description: Problem with a 2 dimensional array(list of list of dict)


code:
def __init__(self, **kwargs):
    for kw,arg in kwargs.iteritems():
        setattr(self, kw, arg)

rawDescription: Improving __init__ where args are assigned directly to members


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

a = 1
theta = np.linspace(0, 2*np.pi, 100)

# We could replace the next three lines with:
# y, x = np.mgrid[-3*a:3*a:1000j, -3*a:3*a:1000j]
x = np.linspace(-3*a, 3*a, 1000)
y = np.linspace(-3*a, 3*a, 1000)
x, y = np.meshgrid(x, y)

# Now let's make something similar to your V for this example..
r = np.hypot(x, y)
V = np.cos(3*np.arctan2(y, x)) + np.sin(r) + np.cos(x)*1j * np.cos(r)

def plot(ax, data):
    ax.plot(a*np.cos(theta), a*np.sin(theta), color='black')
    im = ax.imshow(data, extent=[x.min(), x.max(), y.max(), y.min()])
    fig.colorbar(im, ax=ax, shrink=0.5)

fig, (ax1, ax2) = plt.subplots(ncols=2)

ax1.set(title='Real Portion')
plot(ax1, V.real)

ax2.set(title='Imaginary Portion')
plot(ax2, V.imag)

plt.show()

rawDescription: adding line plot to imshow and changing axis marker

description: Adding line plot to imshow and changing axis marker


code: op = str_ops.get(my_operator, lambda x,y: None) #fallback: do-nothing operator

rawDescription: Using a string as an operator?

description: Using a string as an operator


rawDescription: How can I change the view of my list?

description: Change the view of my list


code:
import itertools
list(itertools.takewhile(lambda i: i != "Bad", list_str))

rawDescription: Python - Looping through a list of strings to form new strings


code:
import numpy as np
np.random.seed(1)

def update(V, W, H, WH, V_over_WH):
    # equation (5)
    H *= (np.dot(V_over_WH.T, W) / W.sum(axis=0)).T

    WH = W.dot(H)
    V_over_WH = V / WH
    W *= np.dot(V_over_WH, H.T) / H.sum(axis=1)

    WH = W.dot(H)
    V_over_WH = V / WH
    return W, H, WH, V_over_WH

def factor(V, r, iterations=100):
    n, m = V.shape
    avg_V = V.mean()
    W = np.random.random(n * r).reshape(n, r) * avg_V
    H = np.random.random(r * m).reshape(r, m) * avg_V
    WH = W.dot(H)
    V_over_WH = V / WH

    for i in range(iterations):
        W, H, WH, V_over_WH = update(V, W, H, WH, V_over_WH)
        # equation (3)
        divergence = ((V * np.log(V_over_WH)) - V + WH).sum()
        print("At iteration {i}, the Kullback-Liebler divergence is {d}".format(
            i=i, d=divergence))
    return W, H

V = np.arange(0.01, 1.01, 0.01).reshape(10, 10)
# V = np.arange(1,101).reshape(10,10).astype('float')
W, H = factor(V, 6)

rawDescription: non-negative matrix factorization failing to converge

description: Non-negative matrix factorization failing to converge


code:
def _h(x, a):
   xx = np.mod(x, a)
   return np.minimum(xx, np.abs(a - xx))

rawDescription: How to test for closeness in angular quantities

description: Test for closeness in angular quantities


code: csv1 - csv2

rawDescription: Converting set of string values to numeric values


code:
t = (2,5)
a,b = t #valid!

def random_int():
    return random.randint(1, 100)
#valid: unpack a 2-tuple to a 2-tuple of variables
a, b = random_int(), random_int()
#invalid: tries to unpack an int as a 2-tuple
a, b = random_int()

#valid: you can also use comprehensions
a, b = (random_int() for i in range(2))

rawDescription: Multiple assignment from a function

description: Multiple assignment from a function


code:
root = LH.fromstring('FOO BAR <c>QUX</c>  BAZ')
root.xpath('//a//text()')
[a.text_content() for a in root.xpath('//a')]

rawDescription: What am I doing wrong? Parsing HTML using lxml


code: x = np.loadtxt('test.dat', dtype = np.float64)

rawDescription: Numpy loadtxt rounding off numbers

description: Numpy loadtxt rounding off numbers


code:
df = pd.DataFrame([100, 200, 300, 400, 500, 600, 700, 800, 900, 1000], columns=['PRICE'])
horizon = 3

df['FORECAST'] = df.apply(lambda x: [df['PRICE'][x.name+1:x.name+horizon+1]], axis=1)

rawDescription: Apply function to pandas dataframe row using values in other rows


rawDescription: Extending Django User model with django-allauth


rawDescription: Matching parts of two csv files to return certain elements


code:
def segment(value, numsplits):
    return ["{}-{}".format(max(0,i + value*i//numsplits), min(value,i + value*i//numsplits + value//numsplits)) for i in range(numsplits)]

rawDescription: splitting a list dynamically with range and value to split

description: Splitting a list dynamically with range and value to split


code:
def column_add(a,b):
     return  a.__add__(b)

newdf = df.withColumn('total_col',
         reduce(column_add, ( df[col] for col in df.columns ) ))

rawDescription: Add column sum as new column in PySpark dataframe


code:
for item in list(set(rowon + colon)):  # remove duplicates
    if not (item == 0) and (item in possibles):
        del possibles[possibles.index(item)]

rawDescription: Numbers in a Matrix

description: Numbers in a Matrix


code: call(differenciate([1, 2, 3, 4]), 4)

rawDescription: Horner's method to return P(x) and its derivative


code:
def _validate_valueschema(self, schema, field, value):
    if isinstance(value, Mapping):
        for key, document in value.items():
            validator = self._Validator__get_child_validator()
            validator.validate(
                {key: document}, {key: schema}, context=self.document, update=self.update)
            if len(validator.errors):
                self._error(field, validator.errors)

rawDescription: In Cerberus can you use 'valueschema' with a type of 'dict'?


code:
import pandas as pd
df = pd.read_table('data', sep='\s+').set_index(['repositoryid', 'date'])
repository = pd.read_table('data2', sep='\s+').set_index(['repositoryid'])
timewindow = 100

rawDescription: Dropping rows fast from a multi-indexed data frame conditional on the level 1 index


code:
class A:
    def func():
        pass
    func = some_decorator(func)

    _decorator = func.some_decorator
    def func():
        pass
    func = _decorator(func)

rawDescription: How is this called and how can be done ( `function_name.decorator` )?


code:
class ConfigGroup(object):
    def __init__(self, config):
        self.config = config

    def __getattribute__(self, name):
        v = object.__getattribute__(self, name)
        if hasattr(v, '__get__'):
            return v.__get__(self, ConfigGroup)
        return v

class Config(object):
    def __init__(self):
        self.a = 10
        self.group = ConfigGroup(self)
        self.group.a = property(lambda group: group.config.a*2)

rawDescription: Python: Idiomatic properties for structured data?


code:
extract_times(start,true) == [(1,0,true),(8,1,true),(15,2,true),(30,3,true)]
extract_times(end,false) == [(7,0,false),(16,1,false),(20,2,false),(40,3,false)]

rawDescription: python find intersection timeranges in array

description: Python find intersection timeranges in array


code:
import requests
import pprint
r = requests.get('http://httpbin.org/get')
pprint.pprint(r.json)

rawDescription: Remove HTTP "Connection" header, Python urllib2


code:
with open('c:/HashFiles/Part1.txt') as inf, open('c:/HashFiles/hashes.txt','w') as outf:
    for line in inf:
        if not line.startswith('#'):
            data = line.split(',')
            hash = data[4]
            outf.write(hash + '\n')

rawDescription: parsing/extracting data from a text file. Unable to make it work

description: Parsing/extracting data from a text file. Unable to make it work


rawDescription: python sum of primes

description: Python sum of primes


rawDescription: Position of maximum value in column in pandas


code: data_files = [ 'COPYING', 'COPYING.LESSER'],

rawDescription: distutils: how to include test files in source distribution and not in build?

description: Distutils: how to include test files in source distribution and not in build


code:
class Singleton(object):
    __instance = None
    def __new__(cls):
        if cls.__instance is None:
            cls.__instance = super(Singleton,cls).__new__(cls)
            cls.__instance.__initialized = False
        return cls.__instance

    def __init__(self):
        if(self.__initialized): return
        self.__initialized = True
        print ("INIT")

a = Singleton()
b = Singleton()
print (a is b)

rawDescription: issue with singleton python call two times __init__

description: Issue with singleton python call two times __init__


code: entry.tag_add('sel', '1.0', 'end')

rawDescription: In tkinter 8.5, how do I highlight (select) text in Text widget with a button click?


code: tchnls

rawDescription: grouping table elements according to grouping column values

description: Grouping table elements according to grouping column values


code:
import subprocess
subprocess.call(["./tg.sh", "user#****", "message here"])

rawDescription: Sending messages with Telegram - APIs or CLI?


code:
#! python
import sys; print(sys.version_info)

rawDescription: The Python Windows launcher isn't reading `py.ini`


rawDescription: Input into tuple that goes into list

description: Input into tuple that goes into list


code:
import pandas as pd
import matplotlib.pyplot as plt
import datetime as dt
import numpy as np
import math

# the sample data provided in the question was made into a csv and read in using pandas
data = pd.read_csv('Workbook1.csv', sep=',')
# get just the 'Date' column
dates = data['Date']

"""
datetime is a python module to work with dates, time, timezones, time differences

strptime(date_string, format) method is used to read in a string (which we know is
a date) and return a datetime. e.g.

>>> s = '2015-05-11'
>>> dt.datetime.strptime(s, '%Y-%m-%d')
datetime.datetime(2015, 5, 11, 0, 0)

>>> print dt.datetime.strptime(s, '%Y-%m-%d')
2015-05-11 00:00:00

>>> print dt.datetime.strptime(s, '%Y-%m-%d').date()
2015-05-11

list comprehension: a way to create a list

create a list of integers from 0 to 9:
>>> [x for x in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

create a list of 1/n! for n from 0 to 99 and sum the values:
>>> sum( [1.0/math.factorial(n) for n in xrange(100)] )
2.7182818284590455

below we use list comprehension to map date strings to datetimes in the
specified format YYYY-MM-DD
"""
dates = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in dates]

rawDescription: Matplotlib - adjusting date spacing on the x-axis


first name: Jack

last name: Dawson

first name: Roger

last name: Federer

rawDescription: Creating json from lists using zip

description: Creating json from lists using zip


rawDescription: Apache Spark -- Assign the result of UDF to multiple dataframe columns


code:
con = sqlite3.connect(":memory:")
with con:
    cursor = con.cursor()
    # or use the connection directly
    con.execute(...)

rawDescription: Is __enter__ and __exit__ behaviour for connection objects specified in the Python database API?


rawDescription: Delete an element from peewee Query select


rawDescription: Comparing elements in the value at two keys


code:
from itertools import takewhile
i = sum(1 for _ in takewhile(lambda elem: elem == 'XX', list3))

list3[i:i+3] = list2[i-1:i+2]

rawDescription: How can i move more than one item from one list to another in Python

description: Move more than one item from one list to another in Python


code:
x = [1,2,3]
id(x)
y = x
id(y)
z = list(x)
id(z)
x.append(10)
x
y
z

rawDescription: Using list.reverse() on a copy changes the original


code:
all_amounts = lambda x: (int(x['date']), float(x['amount']))
stock.sort(key=all_amounts)

rawDescription: Numeric sort of list of dictionary objects


code: result

rawDescription: re string position list builder

description: Re string position list builder


code:
def create_dict_walk(path):
    h = {}
    for dirname, subdirs, files in os.walk(path):
        for filename in files:
            a = extract(os.path.join(dirname, filename))
            if a:
                h[filename] = a
    return h

rawDescription: Python: extract strings between defined characters and store into a disctionary with lists


code:
content = '''
<feed>
    <entry>
        <id>uuid:asdfadsfasdf123123</id>
        <title type="text"></title>
        <content type="application/xml">
            <NamespaceDescription xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <Name>instancename</Name>
                <Region>US</Region>
                <Status>Active</Status>
            </NamespaceDescription>
        </content>
    </entry>
    <entry>
        <id>uuid:asdfadsfasdf234234</id>
        <title type="text"></title>
        <content type="application/xml">
            <NamespaceDescription xmlns="http://schemas.microsoft.com/netservices/2010/10/servicebus/connect" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <Name>instancename2</Name>
                <Region>US2</Region>
                <Status>Active</Status>
            </NamespaceDescription>
        </content>
    </entry>
</feed>'''

from lxml import etree

tree = etree.XML(content)
ns = {'default': 'http://schemas.microsoft.com/netservices/2010/10/servicebus/connect'}

names = tree.xpath('//default:Name/text()', namespaces=ns)
regions = tree.xpath('//default:Region/text()', namespaces=ns)
statuses = tree.xpath('//default:Status/text()', namespaces=ns)

print(names)
print(regions)
print(statuses)

rawDescription: Parsing nested XML with ElementTree

description: Parsing nested XML with ElementTree


code:
class CombinedIter(object):
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        self.index = -1
        return self

    def next(self):
        self.index += 1
        try:
            return self.data[self.index]
        except IndexError:
            raise StopIteration

rawDescription: Python: the mechanism behind list comprehension


code:
def clean_string_to_list(s):
    return [c for c in s if c not in '[,]']  # you might need to catch errors

df['data'] = df['data'].apply(clean_string_to_list)

rawDescription: How to duplicate rows in pandas, based on items in a list

description: Duplicate rows in pandas, based on items in a list


code:
import numpy as np
newimage = np.where(np.logical_and(91<=oldimage, oldimage<=151), 0, oldimage)

rawDescription: NumPy - Image (matrix) thresholding using an intensity value matrix.


code:
class Player:
    def __init__(self):
        self.x = 200
        self.y = 300
        self.speed_init = 6
        self.images = [pygame.image.load(img) for img in glob.glob("walk\Pinks_w*.png")]
        self.index = 0
        self.max_index = len(self.images)-1
        self.speed = 0
        self.img = self.images[self.index]

    def update(self, pos):
        if pos != 0:
            self.speed -= 1
            self.x += pos
            if not self.speed:
                self.speed = self.speed_init
                if self.index < self.max_index:
                    self.index += 1
                else:
                    self.index = 0
            self.img = self.images[self.index]
        # change True to False if needed, or change the operator.
        if pos > 0:
            self.img = pygame.transform.flip(self.img,True,False)
        screen.blit(self.img,(self.x,self.y))

rawDescription: How to flip an img in Pygame, having trouble in my code?

description: Flip an img in Pygame, having trouble in my code


code:
dt=[('E', '<i4'), ('M', '<i4'), ('S', '<i4'), ('T', '<i4'), ('N', '|O4')]
arr = numpy.loadtxt('data.txt', dtype=dt)  # Correctly reads the first 4 columns

with open('data.txt') as input_file:
    for (line_num, line) in enumerate(input_file):
        arr[line_num]['N'] = tuple(int(x) for x in line.split()[4:])  # Manual setting of the tuple column

rawDescription: NumPy: using loadtxt or genfromtxt to read a ragged structure


code:
someList = ['foo', 'bar', 'baz']
someList += ['spam'] * 5
someList

rawDescription: Pythonic way to add several identical values to a list


code:
def bisection(a,b,TOL):
    c = (a+b)/2.0
    while (b-a)/2.0 > TOL:
        if f(c)==0:
            return c
        elif f(a)*f(c)<0:
            b = c
        else:
            a = c
        c = (a+b)/2.0 # put inside the while
    return c

rawDescription: My bisection code in python doesnt return the root


code:
l=[random.randrange(0,10) for i in range(100)]
l
from itertools import count
dict([(i,l.count(i)) for i in l])

rawDescription: How do you tally the amount of times a item in appears from a randomly list?

description: Tally the amount of times a item in appears from a randomly list


code:
def combinations(my_string, n):
    result = []
    for i in range(0,len(my_string)-n+1):
        result.append(my_string[i:i+n])
    result.append(my_string[-1]+my_string[0:n-1])
    return result

rawDescription: Searching for a function similar to combinations() or how could i create one, given some 'rules'


code: foo(*iterable)

rawDescription: Python: Unpack individual strings from tuple using Unpacking asterisk argument


code:
for s in list[:]:
    if s=='b' or s=='c':
        list.remove(s)

rawDescription: how to correctly modify the iterator of a loop in python from within the loop

description: Correctly modify the iterator of a loop in python from within the loop


code:
from operator import attrgetter
smallest_rectangle = min(list_of_rectangles,key=attrgetter('area'))

rawDescription: Putting a pointer as a value in a method call [python]


code:
from itertools import product

def filler(word, from_char, to_char):
    options = [(c,) if c != from_char else (from_char, to_char) for c in word]
    return (''.join(o) for o in product(*options))

rawDescription: String Replacement Combinations

description: String Replacement Combinations


code:
def max_draw_down_relative(p, b):
    p = p.add(1).cumprod()
    b = b.add(1).cumprod()
    pmb = p - b
    cam = pmb.expanding(min_periods=1).apply(lambda x: x.argmax())
    p0 = pd.Series(p.ix[cam.values.astype(int)].values, index=p.index)
    b0 = pd.Series(b.ix[cam.values.astype(int)].values, index=b.index)
    dd = (p * b0 - b * p0) / (p0 * b0)
    mdd = dd.min()
    end = dd.argmin()
    start = cam.ix[end]
    return mdd, start, end

rawDescription: Maximum Active Drawdown in python

description: Maximum Active Drawdown in python


code:
def parseData(input):
    data = input.split('_')
    d = {'sku': data[0],
         'country': data[1].capitalize(),
         'material': data[2].capitalize(),
         'size': data[3],
         'retail_price': data[4],
         'sale_price': data[5]}
    return d

rawDescription: Referencing a variable after seperating it from a list


code:
import string
a = bytearray(b'ABCDEF_')
uppercase = string.ascii_uppercase.encode()
a[::3] = [b | 0b0100000 if b in uppercase else b
          for b in a[::3]]
a

rawDescription: Python - How can I change bytes in a file


code:
from itertools import groupby

key = lambda i: i[0][0].upper()
out = {key: sum(v for k, v in group) for key, group in groupby(sorted(original.items(), key=key), key=key)}

rawDescription: How to add in a dictionary the values that have similar keys?

description: Add in a dictionary the values that have similar keys


rawDescription: How to make a function that detects a character in a string and returns it's position in the string? Python 3.2

description: Make a function that detects a character in a string and returns it's position in the string? Python 3.2


rawDescription: How to make the anaconda plugin use a custom interpreter (virtualenv)?

description: Make the anaconda plugin use a custom interpreter (virtualenv)


rawDescription: NumPy check if 2D array is subset of 2D array


code:
df['count'] = df.groupby(['Col A', 'Col B', 'Col C'])['Col D'].transform(lambda x: (x==0).sum())
df['share'] = df.groupby(['Col A', 'Col B', 'Col C'])['Col D'].transform(lambda x: '{:.2f}%'.format((x==0).sum()/len(x)*100))

rawDescription: How to calculate percentage of missing values

description: Calculate percentage of missing values


code:
with open('C:\\Python33\\text file.txt', 'r') as f:
    for c in iter(lambda: f.read(1), '\n'):
        print(c)

rawDescription: Returning yield of lambda within iter

description: Returning yield of lambda within iter


code:
c = ['nan'] * len(a)
c

rawDescription: Python : creating an array from list with given indices


rawDescription: Add front slash to python regex

description: Add front slash to python regex


code:
from subprocess import check_output as qx

cmd = r'C:\Tools\Dvb_pid_3_0.exe'
output = qx(cmd)

rawDescription: How do I get all of the output from my .exe using subprocess and Popen?

description: Get all of the output from my .exe using subprocess and Popen


code:
# assume worksheet is an xlwt worksheet object
lst = [['a','b','c'],['aa1','bb1','cc1'],['aaa2','bbb2','ccc2']]
for (rownum, rowlist) in enumerate(lst):
    for (colnum, value) in enumerate(rowlist):
        worksheet.write(rownum, colnum, value)

rawDescription: How to create a tabular data structure from a list of sublists with Gpread or XLWT?

description: Create a tabular data structure from a list of sublists with Gpread or XLWT


rawDescription: Python for loop overwriting

description: Python for loop overwriting


code:
import re

def find_by_label(soup, label):
    return soup.find("div", text=re.compile(label)).next_sibling

rawDescription: Extracting text outside of a <div> tag BeautifulSoup


code: sums = dict((k, sum(i for i in v if isinstance(i, int))) for k, v in d.items())

rawDescription: Python how to get sum of numbers in a list that has strings in it as well


code:
adjust_text(xs, ys, texts, precision=3, text_from_points=False, lim=1000,
            arrowprops=dict(arrowstyle="-", color='black', lw=0.5),
            bbox={'pad':0, 'alpha':0})
plt.show()

rawDescription: "Repel" annotations in matplotlib?

description: "Repel" annotations in matplotlib


rawDescription: Python: max depth in binary tree

description: Python: max depth in binary tree


code:
arr = df.values
arr
arr / (np.diag(arr) + np.diag(arr)[:,np.newaxis] - arr)

rawDescription: How to perform arithmetic operations involving row and column in dataframe?

description: Perform arithmetic operations involving row and column in dataframe


code:
o = [1, 2, 4, 6]
f = {1: 10, 2: 5, 3: 1, 4: 3, 5: 7, 6: 9}
min(f.viewkeys() & o, key=f.get)
set_o = set(o)
min(f, key=lambda k: f[k] if k in set_o else float('inf'))

rawDescription: Most efficient way to find the key of the smallest value in a dictionary from a subset of the dictionary


rawDescription: How to categorize and count imported data

description: Categorize and count imported data


code:
from django.forms import Form, fields
def UploadForm(Form):
 someField = fields.CharField()
 uploadedFile.name = fields.CharField()

rawDescription: How to use non valid identifiers as django form field names

description: Use non valid identifiers as django form field names


code:
class A(object):
    def __init__(self, val, *args, **kwargs):
        super(A, self).__init__(*args, **kwargs)
        self.x = val
        self.y = 42

class B(object):
    def __init__(self, *args, **kwargs):
        super(B, self).__init__(*args, **kwargs)
        self.a = 22

rawDescription: Override a field in parent class with property in child class


code: multiplier = 1 + U/100.0

rawDescription: How to compute a percentage increase/decrease multiplier in python without if statements

description: Compute a percentage increase/decrease multiplier in python without if statements


code: df.apply(you_function, axis=1)

rawDescription: Efficiently processing DataFrame rows with a Python function?


code: print(next(c))

rawDescription: return constantly changing variable python

description: Return constantly changing variable python


code:
rows = {1: 'qwertyuiop', 0: 'asdfghjkl;', 2: 'zxcvbnm,.'}
keys = {c:k for k,row in rows.iteritems() for c in row}

rawDescription: What's the most pythonic way to build this dictionary?


code:
import maxtest

x = max(1, 2, 3)
y = max(4, 5, 6)

rawDescription: Function that replaces itself with builtin after first execution


code:
from Tkinter import *
import pickle

class Launch(object):
    def __init__(self, root):
        self.load()  # <-- load
        root.title("Choose Client")
        self.row = 3
        for key in self.dic:
            Label(root, text=key).grid(row=self.row, column=0)
            self.row += 1
        l3 = Label(root, text="Client Name")
        l3.grid(row=0, column=0)
        self.e1 = Entry(root)
        self.e1.grid(row=0, column=1)
        l4 = Label(root, text="Client age")
        l4.grid(row=1, column=0)
        self.e2 = Entry(root)
        self.e2.grid(row=1, column=1)
        b3 = Button(root, text="Create client", command=self.add)
        b3.grid(row=2)

    def add(self):
        client = self.e1.get()
        age = self.e2.get()
        self.dic[client] = age
        Label(root, text=client).grid(row=self.row)
        self.row += 1  # <--- increase row count
        with open("data", "wb") as f:
            pickle.dump(self.dic, f)

    def load(self):
        try:
            self.dic = pickle.load(open("data", "rb"))
        except IOError:
            self.dic = {}

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

rawDescription: Pickling dictionary data then loading it doesn't work


code:
from requests import get
r = get("http://www.google.com/")
type(r.content)

rawDescription: Remove boilerplate content from HTML page


rawDescription: Multiply lengths of all sub-lists in list


code: x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")

rawDescription: converting string 'yyyy-mm-dd' into datetime python

description: Converting string 'yyyy-mm-dd' into datetime python


code:
temp_dict = dict(zip(["dept", "sku"], key))
temp_list = [item["qty"] for item in grp]
temp_dict["avg"] = sum(temp_list) / len(temp_list)
result.append(temp_dict)

rawDescription: Group by multiple keys and summarize/average values of a list of dictionaries


code:
sum_of_numbers = sum(number*count for number, count in counter)
count = sum(count for n, count in counter)
mean = sum_of_numbers / count

rawDescription: Calculate mean on values in python collections.Counter


rawDescription: Counting occurences of words that appear in a list using Python


rawDescription: How can I get number of rows and columns selected by excel COM interface?

description: Get number of rows and columns selected by excel COM interface


code:
@my_decorator
def function():
    pass

rawDescription: Set django.contrib.auth.views.login as csrf_exempt


rawDescription: python BeautifulSoup finding certain things in a table

description: Python BeautifulSoup finding certain things in a table


code: import numpy as np

rawDescription: Storing these vectors but which data structure to use in Python


code:
a = 7
b = 5
n = len(aList)
for i in range(n):
    a *= i ** n # `a` is multiplicated `n` times by (constant) `i`
    b = (n - 1) ** 2 # at the end of the loop, `j` is `(n - 1)`
    v = i + (i * b) # at the end of the loop, `w` is `i * b`
    x = v * v
    w = a * (n - 1) + 23 # at the end of the loop, `k` is `(n - 1)`
    v = b ** 2 # `b` (and as such `v`) is never changed in the loop
    a = w + v

rawDescription: Trying to find the T(n) function and complexity in this bit of Python


code:
from matplotlib import rcParams
rcParams['xtick.direction'] = 'out'
rcParams['ytick.direction'] = 'out'

rawDescription: In matplotlib, how do you draw R-style axis ticks that point outward from the axes?


rawDescription: Python reduce a list by order

description: Python reduce a list by order


code:
lst = list(data.items())
lst
lst1 = list(zip(*[i[1] for i in lst]))
lst1
newlist = []
for x in lst1:
    d = {}
    for i,y in enumerate(lst):
            d[y[0]] = x[i]
    newlist.append(d)
newlist

rawDescription: Iterate over list of values dictionary

description: Iterate over list of values dictionary


code:
cell = table.getCellByName(cellName)
cell.WritingMode = 2

rawDescription: How do you set the text direction for a TextTable Cell in OpenOffice?

description: Set the text direction for a TextTable Cell in OpenOffice


rawDescription: Making Python display .txt files from directories


code:
import re
re.split(r'^\n\n', 'Cool\n\n\nNew paragraph\nruns here\n\n\nAnother paragraph?', flags=re.MULTILINE)

rawDescription: Splitting paragraphs that begin as indents


code: re.search(r'my.*Alex', s).group()

rawDescription: Grep a range of words from a text file python


code:
[(elem, num, '{:.1%}'.format(num/final_sum)) for elem, num in final_dict.items()]
from operator import itemgetter
sorted([(elem, num, '{:.1%}'.format(num/final_sum)) for elem, num in final_dict.items()], key = itemgetter(1), reverse=True)

rawDescription: Grouping and totaling a pipe separated list


rawDescription: python change str to hex, NOT CONVERTING

description: Python change str to hex, NOT CONVERTING


code:
instance = printclass()
instance.dotheprint()

rawDescription: Call a function inside a class when calling the class in python


code: proc = subprocess.Popen(mayapy + ' -u ' + job.pyFile)

description: Multiprocessing.Process subprocess.Popen completed


code:
class studentList(APIView):
    def get(self, request, pk, pk2, format=None):
        student_detail = Student.objects.all()
        if pk:
            student_detail = student_detail.filter(last_name=pk)
        if pk2:
            student_detail = student_detail.filter(campus_id__name=pk2)

        serialized_student_detail = studentSerializer(student_detail, many=True)
        return Response(serialized_student_detail.data)

rawDescription: Django urls with empty values

description: Django urls with empty values


rawDescription: adding two consecutive numbers in a list

description: Adding two consecutive numbers in a list


code:
import operator

res = operator.mul(*map(int, s.split('x')))

rawDescription: Resolve variables from a string

description: Resolve variables from a string


code:
def replace_in_file(filename, oldtext, newtext):
    with open(filename, 'r+') as file:
        lines = file.read()
        new_lines = lines.replace(oldtext, newtext)
        file.seek(0)
        file.write(new_lines)

rawDescription: How should I replace parts from a text file through Python?


rawDescription: difficulty with search url in django

description: Difficulty with search url in django


rawDescription: Find Largest Number From Selected List Elements In Python


rawDescription: Extracting individual frames from an image


code:
def start(list_of_entries):
    for x in list_of_entries: func(x.name, x.age)

rawDescription: Map/Iterating through List of Python Object


code:
class DLLAPI:
  def __init__(self, path=None):
    ...

rawDescription: Parameterising an import statement

description: Parameterising an import statement


code:
def waitForNonStaleElement(driver, type, element):
    strategy = {
            "id":           driver.find_element_by_id,
            "link_text":    driver.find_element_by_link_text,
            "name":         driver.find_element_by_name,
            "xpath":        driver.find_element_by_xpath
            }
    lhsType, rhsType = type.split(".", 1)
    find_element = strategy.get(rhsType.lower())

    try:
        find_element(element)
    except StaleElementReferenceException:
        waitForNonStaleElement(driver, type, element)
    except TypeError:
        raise TypeError("ERROR : CODE TO HANDLE \""+element+"\" TYPE NEEDS TO BE CREATED")

def waitForNonStaleElementClick(driver, type, element):
    strategy = {
            "id":           driver.find_element_by_id,
            "link_text":    driver.find_element_by_link_text,
            "name":         driver.find_element_by_name,
            "xpath":        driver.find_element_by_xpath
            }
    lhsType, rhsType = type.split(".", 1)
    find_element = strategy.get(rhsType.lower())

    try:
        waitForNonStaleElement(driver, type, element)
        find_element(element).click()
    except StaleElementReferenceException:
        waitForNonStaleElementClick(driver, type, element)
    except TypeError:
        raise TypeError("ERROR : CODE TO HANDLE \""+element+"\" TYPE NEEDS TO BE CREATED")

def waitForNonStaleElementText(driver, type, element):
    strategy = {
            "id":           driver.find_element_by_id,
            "link_text":    driver.find_element_by_link_text,
            "name":         driver.find_element_by_name,
            "xpath":        driver.find_element_by_xpath
            }
    lhsType, rhsType = type.split(".", 1)
    find_element = strategy.get(rhsType.lower())

    try:
        return find_element(element).text
    except StaleElementReferenceException:
        waitForNonStaleElementText(driver, type, element)
    except TypeError:
        raise TypeError("ERROR : CODE TO HANDLE \""+element+"\" TYPE NEEDS TO BE CREATED")

rawDescription: StaleElementReferenceException occurs when clicking on the buttons of a changed table (Python > Selenium Webdriver)


rawDescription: column matrix representation in python

description: Column matrix representation in python


code: import MySQLdb as mysql

rawDescription: How to import multiple files with same name in python

description: Import multiple files with same name in python


code: tempDF['date'] = tempDF['date'].apply(lambda x:x.replace(hour=12,minute=0))

rawDescription: Changing time components of pandas datetime64 column


code:
def create():
    author_parse = argparse.ArgumentParser()
    author_parse.add_argument('name', type=str, nargs=2)
    name = raw_input("Provide your first and last name: ")
    auth_args = auth_parse.parse_args(name.split())

rawDescription: How to use argparse during runtime to conditionally get further input?

description: Use argparse during runtime to conditionally get further input


code:
s = "text with    triple spaces and other \n sorts \t of strange ,.-#+ stuff and 123 numbers"
cleanUpWords(s)

rawDescription: Trying to use output of one function to influence the next function to count words in text file


code:
A
sortpts_clockwise(A)

rawDescription: (4,1,2) Numpy Array Sort Clockwise

description: (4,1,2) Numpy Array Sort Clockwise


rawDescription: Bottle framework: how to return datetime in JSON response


code:
import requests
from lxml.html import fromstring
r = requests.get('http://www.imdb.com/title/tt0108778/')
tree = fromstring(r.content)
tree.findtext('.//title')

rawDescription: How to get page title in requests

description: Get page title in requests


code:
def myfunc(*args):
    """Takes three arguments: name, age and height, returns a growth rate."""
    name, age, height = args
    return height / age

rawDescription: Python helptip change text

description: Python helptip change text


code:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

X = np.arange(0.25, 5, 0.25)
Y = np.arange(0.25, 5, 0.25)
X, Y = np.meshgrid(X, Y)
Z = 1/(X*Y)

surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
        linewidth=0, antialiased=False)
ax.set_zlim(0, 10)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()

rawDescription: Plotting surface of implicitly defined volume


code:
from bitstring import ConstBitStream
def unpack_bitstream(raw):
    num_bytes, remainder = divmod(len(raw) * 8 - 1, 7)
    bitstream = ConstBitStream(bytes=raw, offset=1) # use offset to ignore leading bit
    msg = b''
    for _ in range(num_bytes):
        byte = bitstream.read("uint:7")
        if not byte:
            msg += b'\n'
        elif 32 <= byte <= 126:
            msg += bytes((byte,))
            # msg += chr(byte) # python 2
    return msg

rawDescription: Ascii string of bytes packed into bitmap/bitstring back to string?


code:
counter = Counter(['a', 'b', 'c', 'a', 'b', 'a', 'd'])
sorted(counter.elements(), key=counter.get, reverse=True)

rawDescription: Sorting Lists by Repetitions in Python

description: Sorting Lists by Repetitions in Python


code: url = reverse('pay', kwargs={'payment_id': plan.payment_id})

rawDescription: Django urlresolvers reverse for dynamically generated ids


code:
cmd = "commands"
output = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in output.stdout:
    print(line)

rawDescription: How to print the output of shell instantly by python script

description: Print the output of shell instantly by python script


code: all_urls = [''.join(top, name) for top, names in url_dict.items() for name in names]

rawDescription: Loop to append a list of strings to the strings in another list


code:
cpt = 0 # Counter representing the ID of your code.
for row in cursor:
   # I suppose the first column of your table is ID
   tree.insert('', 'end', text=str(cpt), values=(row[1], row[2], row[3]))
   cpt += 1 # increment the ID

rawDescription: how can i display data in Tkinter treeview fetched from Mysql table using python

description: Display data in Tkinter treeview fetched from Mysql table using python


code:
lis=[1,2,3,4,5]
zip(lis, xrange(len(lis))) # Call list() on this in Python 3

rawDescription: creating a list of tuples using for loop

description: Creating a list of tuples using for loop


code:
# Returns value of is_user_like key from user's session if it's available, or False
request.session.get('is_user_like', False)
# Sets value of is_user_like in user's session to True
request.session['is_user_like'] = True

rawDescription: prevent user from submitting likes or dislikes multiple times

description: Prevent user from submitting likes or dislikes multiple times


code:
a_rownames == b_rownames[:, numpy.newaxis]
#>>> array([[ True, False, False],
#>>>        [False,  True, False],
#>>>        [ True, False, False],
#>>>        [False, False,  True],
#>>>        [False,  True, False]], dtype=bool)

rawDescription: Manipulation with arrays in numpy

description: Manipulation with arrays in numpy


rawDescription: Interpolation in SciPy: Finding X that produces Y


rawDescription: Read each entire Column of CSV file using python (preferably by help of pandas )


rawDescription: How to plot contours from multidimensional data in MatPlotLib (NumPy)?

description: Plot contours from multidimensional data in MatPlotLib (NumPy)


code:
ax=plt.gca()
im=ax.images[-1]
im.colorbar.remove()
#in real code, color range is updated here
plt.colorbar()

rawDescription: updating colorbar without resetting zoom history in matplotlib user interface

description: Updating colorbar without resetting zoom history in matplotlib user interface


code:
['bar', 'baz']

['blah', 'bleh']

['foo', 'romeo', 'isn']

rawDescription: negative lookbehind regex assertion in python

description: Negative lookbehind regex assertion in python


code:
import operator
Edges = {(1,2):8.3 , (2,3): 4, (3,1):6}
Edges_list = [(k1,k2,v) for (k1,k2),v in Edges.items() ]
Edges_list
Edges_list.sort(key=operator.itemgetter(2))
Edges_list

rawDescription: Sorting dictionary-represented graph edges by value/weight


code:
from scipy.spatial import cKDTree

# the indices of the non-zero locations and their corresponding values
nonzero_idx = np.vstack(np.where(mask)).T
nonzero_vals = A[mask]

# build a k-D tree
tree = cKDTree(nonzero_idx)

# use it to find the indices of all non-zero values that are at most 1 pixel
# away from each edge pixel
edge_idx = np.vstack(np.where(edges)).T
neighbours = tree.query_ball_point(edge_idx, r=1, p=np.inf)

# take the average value for each set of neighbours
new_vals = np.hstack(np.mean(nonzero_vals[n]) for n in neighbours)

# use these to replace the values of the edge pixels
A_new = A.astype(np.double, copy=True)
A_new[edges] = new_vals

rawDescription: border/edge operations on numpy arrays

description: Border/edge operations on numpy arrays


code:
df['week_beginning'] = df.index.to_period('W').to_timestamp()
df['week_time'] = df.index.to_series() - df['week_beginning']

rawDescription: Plotting Weekly Tick Data From A Year Time Series


code:
def sum_until_found(lst, num):
    index = 0
    res = 0
    found = False
    if num in lst:
        while not found:
            res += lst[index]
            index += 1
            if lst[index] == num:
                found = True
    else:
        return "The number is not in the list!"
    return res

rawDescription: Sum a list of numbers until a number X is found


code: data["year_month"] = year_month

rawDescription: Isolating/manipulating data in a pandas Dataframe


code: newImg.save(path, 'PNG', dpi=[300,300])

rawDescription: How does Python PIL and PILLOW compress pictures?


code:
print(sorted(signature_seq((2, 3, 11), 10)))
print(sorted(signature_seq((5, 7, 13), 30)))

rawDescription: Enumeration of all factor products less than a maximum


code:
from django.forms import inlineformset_factory

InlineOtherFormSet = inlineformset_factory(Base, Other)
formset = InlineOtherFormSet(instance=Base.objects.get(pk=1))

rawDescription: django form twice on same template

description: Django form twice on same template


code:
from scipy import sparse

tree_dist = tree.sparse_distance_matrix(tree, max_distance=10000, p=2)
udist = sparse.tril(tree_dist, k=-1)    # zero the main diagonal
ridx = udist.row    # row indices
cidx = udist.col    # column indices
dist = udist.data   # distance values

rawDescription: Python calculate lots of distances quickly


code: assert out.rstrip() == 'expected result'

rawDescription: Parametrize set of tests using PyTest

description: Parametrize set of tests using PyTest


code:
id = self.request.get('id') or 'default'
config = Configuration.get_by_id(id) or Configuration(id = id)
config.displayName = self.request.get('newDisplayName')
config.starting = self.request.get('newStartingDate')
config.put()

rawDescription: How to store and update a configuration in Google App Engine (Python)

description: Store and update a configuration in Google App Engine (Python)


code:
...
self.create_button(" 0 ", self.user_input, [x,y])
...

def create_button(self, info, boom, posit):
    ...
    cmd = lambda row=posit[1], column=posit[0]: boom(row, column)
    self.button.config(command=boom)

rawDescription: How to determine which button is pressed on a single tkinter object?

description: Determine which button is pressed on a single tkinter object


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

fig=plt.figure()

N=20
M=10

x = np.random.random((M,N))
mask=np.random.random_integers(0,1,N*M).reshape((M,N))
x = np.ma.array(x,mask=mask)
ax1=fig.add_subplot(2,1,1)
ax1.boxplot(x)

z = [[y for y in row if y] for row in x.T]
ax2=fig.add_subplot(2,1,2)
ax2.boxplot(z)
plt.show()

rawDescription: Boxplotting Masked Arrays

description: Boxplotting Masked Arrays


rawDescription: Do Python regular expressions have an equivalent to Ruby's atomic grouping?


code:
instance = clazz()
instance.method()

rawDescription: How to make from var_str import var_str in python

description: Make from var_str import var_str in python


code:
Foo.bar.im_class
Foo.bar.__func__  # new name, old name im_self still works too

rawDescription: Not sure what the Python documentation says about user-defined method objects here


code:
def prettyprint_namedtuple(namedtuple,field_spaces):
    assert len(field_spaces) == len(namedtuple._fields)
    string = "{0.__name__}( ".format(type(namedtuple))
    for f_n,f_v,f_s in zip(namedtuple._fields,namedtuple,field_spaces):
        string+= "{f_n}={f_v!r:<{f_s}}".format(f_n=f_n,f_v=f_v,f_s=f_s)
    return string+")"

rawDescription: Namedtuple formatted/pretty print in Python


rawDescription: How to read a text file with mixed data_types automatically in Python?

description: Read a text file with mixed data_types automatically in Python


code:
from itertools import combinations
nums = [[0,25], [1,54], [2,76], [3,13], [4,79]]
list(combinations(nums, r=2))

rawDescription: Combinations in of nested lists in python based on a one key attribute


code:
def unique_hashable(seq):
    # Not order preserving. Use this if the items in seq are hashable,
    # and you don't care about preserving order.
    return list(set(seq))

def unique_hashable_order_preserving(seq):
    # http://www.peterbe.com/plog/uniqifiers-benchmark (Dave Kirby)
    # Use this if the items in seq are hashable and you want to preserve the
    # order in which unique items in seq appear.
    seen = set()
    return [x for x in seq if x not in seen and not seen.add(x)]

def unique_unhashable_orderable(seq):
    # Author: Tim Peters
    # http://code.activestate.com/recipes/52560-remove-duplicates-from-a-sequence/
    # Use this if the items in seq are unhashable, but seq is sortable
    # (i.e. orderable). Note the result does not preserve order because of
    # the sort.
    #
    # We can't hash all the elements.  Second fastest is to sort,
    # which brings the equal elements together; then duplicates are
    # easy to weed out in a single pass.
    # NOTE:  Python's list.sort() was designed to be efficient in the
    # presence of many duplicate elements.  This isn't true of all
    # sort functions in all languages or libraries, so this approach
    # is more effective in Python than it may be elsewhere.
    try:
        t = list(seq)
        t.sort()
    except TypeError:
        del t
    else:
        last = t[0]
        lasti = i = 1
        while i < len(seq):
            if t[i] != last:
                t[lasti] = last = t[i]
                lasti += 1
            i += 1
    return t[:lasti]

def unique_unhashable_nonorderable(seq):
    # Use this (your Method1) if the items in seq are unhashable and unorderable.
    # This method is order preserving.
    u = []
    for x in seq:
        if x not in u:
            u.append(x)
    return u

rawDescription: Proper Usage of list.append in Python

description: Proper Usage of list.append in Python


code:
import mock
import unittest

class ClassToPatch():
   def __init__(self, *args):
       pass

   def some_func(self):
       return id(self)

class UUT():
    def __init__(self, *args):
        resource_1 = ClassToPatch()
        resource_2 = ClassToPatch()
        self.test_property = (resource_1.some_func(), resource_2.some_func())

class TestCase1(unittest.TestCase):
    @mock.patch('__main__.ClassToPatch', autospec = True)
    def test_1(self, mock1):
        ctpMocks = [mock.Mock(), mock.Mock()]
        ctpMocks[0].some_func.return_value = "funky"
        ctpMocks[1].some_func.return_value = "monkey"
        mock1.side_effect = ctpMocks

        u = UUT()
        self.assertEqual(u.test_property, ("funky", "monkey"))

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

rawDescription: Python patch a class and get a new Mock object for each instanciation


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

# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

from page2 import Ui_page2

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

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

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(707, 563)
        MainWindow.setMinimumSize(QtCore.QSize(707, 563))
        MainWindow.setMaximumSize(QtCore.QSize(707, 563))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8("../../Documents/Icon/2.0/TheBat.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        MainWindow.setWindowIcon(icon)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.label_start = QtGui.QLabel(self.centralwidget)
        self.label_start.setGeometry(QtCore.QRect(0, 0, 731, 501))
        self.label_start.setText(_fromUtf8(""))
        self.label_start.setPixmap(QtGui.QPixmap(_fromUtf8("../../Downloads/Workout routine program.jpg")))
        self.label_start.setObjectName(_fromUtf8("label_start"))
        self.horizontalLayoutWidget = QtGui.QWidget(self.centralwidget)
        self.horizontalLayoutWidget.setGeometry(QtCore.QRect(0, 500, 721, 51))
        self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
        self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))

        # initialize the qwidget as an attribute of the class and set a listener on the button
        self.page2 = QtGui.QWidget()
        ui = Ui_page2()
        ui.setupUi(self.page2)

        self.enter = QtGui.QPushButton(self.horizontalLayoutWidget)
        self.enter.clicked.connect(self.page2.show)

        font = QtGui.QFont()
        font.setFamily(_fromUtf8("Corbel"))
        font.setPointSize(10)
        font.setBold(True)
        font.setItalic(False)
        font.setUnderline(False)
        font.setWeight(75)
        font.setStrikeOut(False)
        font.setStyleStrategy(QtGui.QFont.PreferAntialias)
        self.enter.setFont(font)
        self.enter.setAutoFillBackground(False)
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap(_fromUtf8("../../Documents/Icon/2.0/install.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.enter.setIcon(icon1)
        self.enter.setCheckable(False)
        self.enter.setAutoDefault(False)
        self.enter.setObjectName(_fromUtf8("enter"))
        self.horizontalLayout.addWidget(self.enter)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "Welcome to Workout Routine Program", None))
        self.enter.setText(_translate("MainWindow", "Enter", None))

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

    sys.exit(app.exec_())

rawDescription: How do i connect from main window to next window in pyqt?

description: Connect from main window to next window in pyqt


rawDescription: Insert 0s into 2d array

description: Insert 0s into 2d array


code: total = recAnswer({}, x, y, z, 1)

rawDescription: Permutation of phone numbers starting at button x, ending at button y, and z numbers long


code: numIn = int(input("Enter a number: ")) == firstArray[i]

rawDescription: Trying to call range in Array (Lists) in Python 3


code:
def get(self):
    template_page = "expense.html"
    expenses = Expense.query().fetch()
    ndb.get_multi([e.vendor for e in expenses])
    template_values = {'expense':expenses}

    self.renderTemplatePage(template_page, template_values)

rawDescription: Google App Engine Datastore modeling issue


code:
class conditional_decorator(object):
    def __init__(self, dec, condition):
        self.decorator = dec
        self.condition = condition

    def __call__(self, func):
        if not self.condition:
            # Return the function unchanged, not decorated.
            return func
        return self.decorator(func)

rawDescription: how to do a conditional decorator in python 2.6

description: Do a conditional decorator in python 2.6


code:
from math import sqrt
map(sqrt, [1,2,9])

rawDescription: How do you subtract list a from list b in Python?

description: Subtract list a from list b in Python


code:
from sqlalchemy.sql import cast, func
from sqlalchemy.dialects.postgresql import INET

session.query(func.host(cast('0.0.0.0', INET) + SomeTable.ip_dec)).scalar()

rawDescription: Sqlalchemy change decimal IP address to dotted


code: [type(dat) for dat,type in zip(match.groups(), CITY_TYPES)]

rawDescription: Regular Expressions in data parsing Python


rawDescription: How to increase the performance for estimating `Pi`in Python

description: Increase the performance for estimating `Pi`in Python


rawDescription: will the memory overflow if python processing too many bigtext

description: Will the memory overflow if python processing too many bigtext


code:
from pylab import *
import matplotlib.pyplot as plt
import numpy

def update(val):
    A = sA.val
    B = sB.val
    C = sC.val
    y_data = A*x_data*x_data + B*x_data + C
    par_plot.set_ydata(y_data)
    draw()

x_data = numpy.arange(-100,100,0.1);

fig = plt.figure(figsize=plt.figaspect(0.75))
ax = fig.add_subplot(1, 1, 1)
subplots_adjust(top=0.8)

ax.set_xlim(-100, 100);
ax.set_ylim(-100, 100);
ax.set_xlabel('X')
ax.set_ylabel('Y')

axsliderA = axes([0.12, 0.85, 0.16, 0.075])
sA = Slider(axsliderA, 'A', -1, 1.0, valinit=0.5)
sA.on_changed(update)

axsliderB = axes([0.43, 0.85, 0.16, 0.075])
sB = Slider(axsliderB, 'B', -30, 30.0, valinit=2)
sB.on_changed(update)

axsliderC = axes([0.74, 0.85, 0.16, 0.075])
sC = Slider(axsliderC, 'C', -30, 30.0, valinit=1)
sC.on_changed(update)

axes(ax)
A = 1;
B = 2;
C = 1;
y_data = A*x_data*x_data + B*x_data + C;

par_plot, = plot(x_data,y_data, lw=2, color='red')

show()

rawDescription: Closing pyplot windows

description: Closing pyplot windows


code:
from matplotlib import path

...
p = path.Path(poly_verts)
grid = p.contains_points(points)
...

rawDescription: How to "draw" a geometric shape on a 2-D meshgrid?


rawDescription: Pandas: Change dates in dataframe to same date format


code: lines_are_equal = all(a == b for a, b in itertools.zip_longest(lines1, lines2))

rawDescription: How to detect that two Python iterators yield the same items?

description: Detect that two Python iterators yield the same items


code:
import requests
session = requests.Session()
response = session.get('https://domain.com/auth?name=USERNAME&pw=PASSWORD')

rawDescription: Python httplib2: HTTPS login fails

description: Python httplib2: HTTPS login fails


rawDescription: How to use collections.defaultdict, to ensure a straightforward comparison of values in Python

description: Use collections.defaultdict, to ensure a straightforward comparison of values in Python


code:
my_instance = session.query(MyTable).filter(MyTable.name == some_value).first()
session.delete(my_instance)  # !!!
# ...
session.commit()

rawDescription: One-to-one delete for SQLAlchemy classes with inheritance


code: df = df.dropna()

rawDescription: replacing quotes inside a pandas df to count unique terms

description: Replacing quotes inside a pandas df to count unique terms


rawDescription: Numpy indexing multidimensional arrays with array and slice


code:
import urllib
urllib.encode({"access_token": example, "attachment": json_encoded})
# produces a long string in the form "access_token=...&attachment=..."

rawDescription: urllib's urlencode returning weird encoded results

description: Urllib's urlencode returning weird encoded results


code: json_obj = json.loads(model.json_text)

rawDescription: django-rest-framework: How Do I Serialize a Field That Already Contains JSON?

description: Django-rest-framework: How Do I Serialize a Field That Already Contains JSON


code: A[rows, columns] += 1

rawDescription: Composite Index updates for Numpy Matrices


code:
def test(n):
    for i in range(n):
        1 + 1

import dis
dis.dis(test)

rawDescription: How many CPU cycles one addition take?

description: How many CPU cycles one addition take


code:
a = np.array([0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1])
a_orig = a.copy()
how_many_flip = 4  # you'll have to make sure it's less than a.sum()
b = np.hstack((np.zeros(how_many_flip, dtype=int), np.ones(a.sum()-how_many_flip, dtype=int)))
np.random.shuffle(b)
b
a[a!=0] = b
a
a_orig

rawDescription: How to randomly convert some 1's to 0's in an array

description: Randomly convert some 1's to 0's in an array


code:
nestedList = [[0],[0,1,2,3,4,6,7,8,9],[0,1,2,3,4,6,7,8,9],[1,2,3]]
lengthList = [[1],[5,4],[5,4],[3]]

answer = []
for lens,sub in zip(lengthList, nestedList):
    answer.append([])
    top = 0
    for l in lens:
        answer[-1].append(sub[top:top+l])
        top += l

rawDescription: split list into nested lists by values in a loop (iterating values)

description: Split list into nested lists by values in a loop (iterating values)


code:
MI = BitVecSort(32)
MV = BitVecSort(8)
Mem = Array('Mem', MI, MV)

pmt = BitVec('pmt', 32)
pmt2 = BitVec('pmt2', 8)

def Select4(M, I):
  return Concat(Select(M, I + 3), Select(M, I + 2), Select(M, I+1), Select(M, I))

g = True
g = And(g, pmt2 == Select(Mem, pmt))
t3 = BitVec('t3', 32)
g = And(g, t3 == Select4(Mem, pmt))

solve(g, pmt2 > 10)

rawDescription: Z3: How to select 4 bytes from array of 8-bits?


code:
from itertools import groupby
rooms = [1,'John','Mike','Simona',2,'Peter','Mark',3,'Olivia']
grouped = groupby(rooms, type)
rooms = {}
for key, grp in grouped:
    roomname = 'room{}'.format(next(grp))
    rooms[roomname] = list(next(grouped)[1])

rooms

rawDescription: Construct dictionary from mixed type list


code:
class BookFormStep1(models.ModelForm):
    class Meta:
        model = Files
        fields = ('file',)

class BookFormStep2(models.ModelForm):
    class Meta:
        model = Books
        fields = ('book_title',)

rawDescription: How can I create a two step form or wizard, where the model has a foreign key, but the foreign key is selected at the second step?

description: Create a two step form or wizard, where the model has a foreign key, but the foreign key is selected at the second step


rawDescription: resize borderless window with vpaned in python+gtk3

description: Resize borderless window with vpaned in python+gtk3


code: image = images_dict['fox']

rawDescription: Loading pygame images as a module

description: Loading pygame images as a module


code: fns_to_delete = chain(*[find_files_to_delete_for_group(g) for k, g in fn_groups])

rawDescription: python deleting older files that match an unknown pattern (tricky)

description: Python deleting older files that match an unknown pattern (tricky)


code: [city.rstrip(' 0123456789(*)') for city in cities]

rawDescription: How to strip noisy pattern at the end of string?

description: Strip noisy pattern at the end of string


code:
import operator
sorted(a, key=operator.itemgetter(1, 0))  # order by column 1 first, then 0.

rawDescription: Python - order list of lists by multiple column indexes


code:
with open("phonebookCOMPK-Directory.csv") as f:
    lineno = 0

    for line in f:
        lineno += 1

        try:
            business = deserialize_business(line)

        except:
            # Bad line formatting?
            log.exception(u"Failed to deserialize line #%s!", lineno)

        else:
            # All is well
            store_business(business)

rawDescription: Reformat csv file using python?

description: Reformat csv file using python


rawDescription: Finding cosine similarity between 2 numbered datasets using Python


rawDescription: Sorting panda DataFrames based on criteria


code:
keywords = ['a', 'b', 'c']
N = len(keywords)
ids = range(5)

for i, idd in enumerate(ids):
    counter = Counter({'a': random.randint(0, 10),
                      'b': random.randint(0, 10),
                      'c': random.randint(0, 10),})
    for j, key in enumerate(keywords):
        a.loc[i*N+j] = [idd, key, counter[key]]

rawDescription: Inserting counter objects into Dataframe python


code:
bignum = 2**50 - 1
only_8_lsb = bignum & 0xFF
only_16_lsb = bignum & 0xFFFF
only_48_lsb = bignum & (2**49 - 1)

rawDescription: U8,U16,U32 representation in python

description: U8,U16,U32 representation in python


code:
def shift_char(ch,shift):
    if not ch.isalpha():
        return ch   # return non-alphabetic characters as is
    if ch.isupper():
        base_a = 'A'
    else:
        base_a = 'a'
    return chr(ord(base_a) + (ord(ch)-ord(base_a)+shift)%26)

def encode_string(s,shift):
    return ''.join(shift_char(i,r) for i in s), shift  # NOTE EXTRA return value

def decode_string(s,shift):
    return ''.join(shift_char(i,-shift) for i in s)

# usage
s = 'Hello, StackOverflow!'
enc_s,shift = encode_string(s)
dec_s = decode_string(enc_s,shift)

rawDescription: How to change random letter using number in Python

description: Change random letter using number in Python


code:
pd.set_option("display.float_format",lambda x: "{:,}".format(x).replace(",","'"))
pd.DataFrame([[12345.3,12345.4]])

rawDescription: set thousands separators in iPython without string formatting

description: Set thousands separators in iPython without string formatting


rawDescription: Advice on a simple algebra solver(python)


code:
d = {c: [] for c in colors}
for x in g16.nodes(data=True):
    k = x[1]['color']
    if k in d:
        d[k].append(x[0])

rawDescription: creating dictionary containing list values using a comprehension

description: Creating dictionary containing list values using a comprehension


code:
for n, coolfunc in inspect.getmembers(this_module, function_that_has_site):
   result = coolfunc(blabla, yada)
   if result: return result

rawDescription: Go through a number of functions in Python


code:
def shortStringsByWordLengths(sentences):
    return [' '.join(sorted(sentence.split(), key=len)) for sentence in sentences]

rawDescription: sorting a list of strings by their length not working

description: Sorting a list of strings by their length not working


code: final_assets = [item for item in similar_assets if item.id in exact_assets_ids]

rawDescription: Iterate through two lists simultaneously and remove from one if exists in the other


code:
strs = 'bacarat,baccarat\r'
strs.replace('\r','').split(',')

rawDescription: string split() in python 2.6

description: String split() in python 2.6


code:
from multiprocessing import Pool, Lock
from time import sleep

lock = Lock()

def do_job(i):
    "The greater i is, the shorter the function waits before returning."
    with lock:
        sleep(1-(i/10.))
        return i

def main():
    poolsize = 4
    with Pool(poolsize) as pool:
        results = pool.imap_unordered(do_job, range(poolsize))
        print(list(results))

if __name__ == "__main__":
    main()

rawDescription: How to create global lock/semaphore with multiprocessing.pool in Python?

description: Create global lock/semaphore with multiprocessing.pool in Python


rawDescription: Python: "Try" inside shortened for...loop


rawDescription: Twitter/ general categorisation training corpus


code:
HEIGHT = 3
for b in range(1, HEIGHT+1):
    for a in range(1, b + 1):
        print("*", end='')
    for a in range(0, 2*(HEIGHT-b)):
        print(" ", end='')
    for a in range(1, b + 1):
        print("*", end='')
    print()

rawDescription: For/While Loops to make *-triangles

description: For/While Loops to make *-triangles


code: dict((k,len(v)) for k, v in myDict.iteritems())

rawDescription: Dictionary that counts occurrences of its items


rawDescription: Python - Create an array from columns in file


rawDescription: Plotting a graph in python

description: Plotting a graph in python


code:
from django.db.models.signals import post_save

#####SIGNALS######
def after_save_instance_handler(sender, **kwargs):
    #get the saved instance
    instance_object = kwargs['instance']

    #get the needed data
    the_date = ...
    the_user = ...
    the_object_id = ...

    #create the relation to the audit object
    instance_object.audit_obj.create(operation="op963",operation_at=the_date,operation_by=the_user,object_id=the_object_id)

#connect the handler with the post save signal - django 1.1 + 1.2
post_save.connect(after_save_instance_handler, sender=Instances)

rawDescription: Django signals, implementing on save listner


rawDescription: Python 3 String Method?

description: Python 3 String Method


rawDescription: Python - Iteration over nested lists

description: Python - Iteration over nested lists


code:
def paths(filename):
    return [os.path.join(s, filename) for s in ('c:\\', 'y:\\', 'z:\\')]

rawDescription: Utilizing objects in another class in Python


code:
result = []
start = 0
while start < len(lst):
    try:
        end = lst.index(item, start + 1)
    except ValueError:
        end = len(lst)
    result.extend(lst[x+start:x+start+size] for x in range(end - start - size + 1))
    start = end + 1

rawDescription: Find all possible sublists of a list

description: Find all possible sublists of a list


rawDescription: In python curly braces with numbers from range() inside


rawDescription: Converting 32-bit integer into array of four 8-bit integers in Python


rawDescription: Do you change variables AFTER you run a function in python?


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        wx.Frame.__init__(self, *args, style=wx.DEFAULT_FRAME_STYLE)
        self.button = wx.Button(self, -1, "Change")
        self.Bind(wx.EVT_BUTTON, self.ButtonPress, self.button)

        self.tc = wx.TextCtrl(self, -1)
        self.lb = wx.ListBox(self, -1, choices = ('One', 'Two'))

        box = wx.BoxSizer(wx.VERTICAL)
        box.Add(self.lb, 0, wx.EXPAND, 0)
        box.Add(self.tc, 0, wx.EXPAND, 0)
        box.Add(self.button, 0, wx.ADJUST_MINSIZE, 0)
        self.SetSizer(box)
        box.Fit(self)
        self.Layout()

    def ButtonPress(self, evt):
        txt = self.tc.GetValue()
        pos = self.lb.GetSelection()
        self.lb.Delete(pos)
        self.lb.Insert(txt, pos)

if __name__ == "__main__":
    app = wx.PySimpleApp(0)
    frame = MyFrame(None, -1, "")
    frame.Show()
    app.MainLoop()

rawDescription: Set String of the Current Selected Item with wxListbox


rawDescription: How to pivot data in a csv file?

description: Pivot data in a csv file


code:
X = np.arange(0,n,0.1).astype(int)[None,None,:,None]
a,b,c,d = np.ogrid[:n,:n,:100,:n]
argmaxD = F[a,b,c,d,X].argmax(axis=3)

rawDescription: Evaluate array at specific subarray

description: Evaluate array at specific subarray


code:
twobytes = b'\x13\x24'
byte1, byte2 = twobytes[:2]
bytes([((byte1 & 0x0F) << 4) | (byte2 & 0x0F)])

rawDescription: how to join two bites together (the last 4 bits of each) for a whole file

description: Join two bites together (the last 4 bits of each) for a whole file


rawDescription: Create a Tuple from text file

description: Create a Tuple from text file


code:
import numpy as np
lon=np.arange(0,360,1)
lat=np.arange(0,90,1)
longitude, latitude = np.meshgrid(lon,lat)

rawDescription: Select gridded data from input array python


code:
import numpy as np

# I'll use numbers instead of words,
# but same exact concept
points_list = [[0,1,2],
               [0,3],
               [1,4],
               [0,2]]

scores = np.zeros((5,5))

for points in points_list:
    temp = np.array(points)[:, np.newaxis]
    scores[temp, points] += 1

rawDescription: Recognition of elements in a list - machine learning


code:
def build_insert_statement(table_name, col_names, values, where_clause):
    return ''.join(['insert into ',
                    table_name,
                    ' ( ',
                    ', '.join(col_names),
                    ' ) values ( ',
                    ', '.join(values),
                    ' ) where ',
                    where_clause,
                    ';'])

rawDescription: string_builder decorator in python 2.7 - how to do it and should I?

description: String_builder decorator in python 2.7 - how to do it and should I


code:
from matplotlib import pyplot
import numpy

rawDescription: How to set limits to specific components of an equation when plotting them?

description: Set limits to specific components of an equation when plotting them


code: re.findall(r'\b\d{3}\b', inputtext)

rawDescription: Searching for a 3 digit number in a text line in python


code:
def trans_function(df):
    return df[df.Primary == min(df.Primary)]

rawDescription: pandas groupby - return min() along with time where min() occurs

description: Pandas groupby - return min() along with time where min() occurs


code:
def func(kv):
    return '-'.join(kv)

rawDescription: Spark: how to generate several elements in map (python)?


code: app = MyFlask( ... )

rawDescription: How to process URLs in Flask before Rules are mapped to endpoints?

description: Process URLs in Flask before Rules are mapped to endpoints


code:
import time
week = 6
year = 2014
atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))
atime

rawDescription: Converting week numbers to dates

description: Converting week numbers to dates


code:
def switch(lst, i):
  newlst = list(lst)
  newlst[0], newlst[i] = newlst[i], newlst[0]
  return newlst

rawDescription: How to switch nodes at an index with the head of a list?

description: Switch nodes at an index with the head of a list


code:
for t in range(10):
    print("The falling distance in %d seconds is %s" %(t, fallingDistance(t)))

rawDescription: Python using the numbers 1 through 10 in a functions equation


rawDescription: multi-parameter 'in' in python

description: Multi-parameter 'in' in python


code:
from operator import itemgetter
s = sorted(d, key=itemgetter(0))

rawDescription: Is there a "get first item" function, for use in higher-ordered functions?


code:
x = df.loc[:,idx[:,:,'x']]
z = df.loc[:,idx[:,:,'z']]
x.sub(z)

#     A                       B
#     a       b       c       a       b       c
#     x   z   x   z   x   z   x   z   x   z   x   z
# 0 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 1 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 2 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 3 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 4 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 5 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
# 6 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN

rawDescription: Subtract same column multi index for each level


rawDescription: Reading excel column 1 into Python dictionary key, column 2 into value


code:
seen = set()
temp = set()

with open(infile, 'rt') as f:
    reader = csv.reader(f,delimiter=",")
    next(reader)
    prev = None
    for row in reader:
        # found new name and it is not the first
        if row[0] not in seen and temp:
            # set should only hav  and 1 if all columns only contain 0,1
            if temp == {"0", "1"}:
                print(prev)  # print previous row
            # reset temp
            temp = set()
        seen.add(row[0])
        temp.update(row[2:])
        # need to keep track of previous row
        prev = row

rawDescription: How do I remove a dictionary from a list depending on a value being present in a list in Python?

description: Remove a dictionary from a list depending on a value being present in a list in Python


code:
import heapq
top10=[]
for i in range(2000000):
    heapq.heappush(top10, funcx())
    top10 = top10[:10]

rawDescription: How do you iterate and keep the top 10 max? Python

description: Iterate and keep the top 10 max? Python


code:
if __name__ == '__main__':
    dataReadEvent = threading.Event()
    Thread(target = SerialRead, args=(dataReadEvent,) ).start()
    Thread(target = main, args=(dataReadEvent,) ).start()

rawDescription: Have textbox update every 5 seconds PyQt


code:
cls_inst = Cls()
cls_inst.func1()
# 13
cls_inst.func2()
# 15

rawDescription: Attach a method to a class while the class is being created


code:
def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

rawDescription: Does Python have a cleaner way to express "if x contains a|b|c|d..."?


code:
import os

fileobj.seek(0, os.SEEK_END)
size = fileobj.tell()
fileobj.seek(0, os.SEEK_SET)

rawDescription: What exactly does tell() return, and how do I use it to calculate percent of file read?