code:
import pygame
import random
pygame.init()

circles = [
    {
        "width": 2,
        "filled": False,
        "position": [250, 230]
    }, {
        "width": 2,
        "filled": False,
        "position": [250, 260]
    }, {
        "width": 2,
        "filled": False,
        "position": [250, 290]
    }, {
        "width": 2,
        "filled": False,
        "position": [250, 320]
    },
]

size = [720, 575]
screen = pygame.display.set_mode(size)

done = False
clock = pygame.time.Clock()
while not done:
    clock.tick(30)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             done = True

        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            x, y = event.pos

            for circle in circles:
                # Check if mouse was over it
                if circle["bounding box"].collidepoint(x, y):
                    # Lets the circle draw
                    circle["filled"] = True
                    circle["width"] = 0

                    for othercircle in circles:
                        if othercircle is not circle:
                            othercircle["filled"] = False
                            othercircle["width"] = 2

                    if circle["filled"] == True:
                        circle["bounding box"] = pygame.draw.circle(screen, pygame.Color("black"), circle["position"], 7, circle["width"])

    # Cleans the screen and sets the screen background
    screen.fill(pygame.Color(3, 255, 3))
    # Circles
    for circle in circles:
        circle["bounding box"] = pygame.draw.circle(screen, pygame.Color("black"), circle["position"], 7, circle["width"])
    # Update the screen
    pygame.display.flip()

rawDescription: pygame circle not changing

description: Pygame circle not changing


code:
@login_required
def eventcateg_detail(request):
    ca = EventTypeCategory.objects.all()
    return render_to_response('events/categ.html',{
        'objs': ca,
        })

rawDescription: How to view dictionary having foreign key to itself at template level in Django

description: View dictionary having foreign key to itself at template level in Django


rawDescription: Possibility of writing dictionary items in columns


code: np.array(np.where(edge == edge[edge > 0].min())).T

rawDescription: Identify offset of a value in numpy

description: Identify offset of a value in numpy


rawDescription: Fill larger matrix from smaller matrix

description: Fill larger matrix from smaller matrix


code:
g = df.groupby(['SID', 'Trial'])
g.cumcount()

rawDescription: do i want rolling_apply?

description: Do i want rolling_apply


rawDescription: BeautifulSoup counting tags without parsing deep inside them


code:
def check(self, choice1, choice2):
    """ Checks if the chosen words are a pair """
    tries = 0
    if choice1 == choice2:
        pass
    else:
        self.show_word

    tries += 1

rawDescription: Something wrong without any error - Includes Tkinter


code:
def get_all_records(users, dt):
    return [[record for record in user.records if dt <= record.datetime < dt + timedelta(days=7)] for user in users]

records = get_all_records(users, dt)
userInfo   = [(user, record) for user, record in zip(users, records) if len(record)]

rawDescription: Extracting two sets (class + class property) using list comprehension


code:
import itertools
consonants = "bcdfghjklmnpqrstvwxyz"
vowels = "aeiou"
poss = list(itertools.product(consonants, vowels, consonants))
len(poss)
poss[:10]

rawDescription: Python Consonant/Vowel Permutations

description: Python Consonant/Vowel Permutations


code:
src_im = Image.open("test.gif")
im = src_im.rotate(30, expand=True)
im.save("result.gif")

rawDescription: Python Django how to rotate image and remove black color?


code:
from itertools import dropwhile
try:
    item = next(dropwhile(lambda x: x!="the one I'm looking for", items))
    found = True
except:
    found = False

rawDescription: For loops and multiple conditions

description: For loops and multiple conditions


code:
from itertools import combinations, combinations_with_replacement

data = """\
   C1  C2  C3  C4
0   8   0   5   6
1   4   5   3   5
"""
df = pd.read_csv(io.StringIO(data), delim_whitespace=True, index_col=0)

combs = list(combinations_with_replacement(df.columns.tolist(), 2))

df_quad = pd.DataFrame()

for tup in combs:
   df_quad['{0[0]}_{0[1]}'.format(tup)] = df[tup[0]] * df[tup[1]]

rawDescription: generate all quadratic combinations of any 2 columns

description: Generate all quadratic combinations of any 2 columns


rawDescription: max value in Python

description: Max value in Python


rawDescription: Finding largest indices of non-zero elements along each axis


code:
with open("in.csv") as f, open("out.csv","w") as out:
    r = islice(f, 5 ,None)
    out.writelines(r)

rawDescription: Skipping more than one row in Python csv


code:
all_permutations = map(lambda p: ''.join(p), itertools.permutations('123456789'))
permutation_index = dict((perm, index) for index, perm in enumerate(all_permutations))

rawDescription: Best way to hash ordered permutation of [1,9]

description: Hash ordered permutation of [1,9]


code:
import html.parser
parser = html.parser.HTMLParser()
parser.unescape('í')

rawDescription: Decoding html entities in python2

description: Decoding html entities in python2


code: df =_.reset_index()

rawDescription: Need to aggregate count(rowid, colid) on dataframe in pandas


code:
my_expression = r'#.+|[^ ;]+'
f='10-2-2015;10:02;LOCATION;xxx.xxx.xxx.xxx;xxx.xxx.xxx.xxx;somename1 # more alphanumeric text with caps and lower case'
s='10-2-2015;10:02;LOCATION;xxx.xxx.xxx.xxx;xxx.xxx.xxx.xxx;somename1; somename2 somename3 # more,alphanumeric,text,with,caps,and,lower,case'
my_expression = r'#.+|[^ ;]+'
re.findall(my_expression, f)
re.findall(my_expression, s)

rawDescription: How to Split String Using Delimiters

description: Split String Using Delimiters


code:
from collections import defaultdict
def invert(oldDict):
    invertedDict = defaultdict(list)
    while oldDict:
        key, valuelist = oldDict.popitem()
        for value in valuelist:
            invertedDict[value].append(key)
    return invertedDict

rawDescription: In-place dictionary inversion in Python

description: In-place dictionary inversion in Python


code:
import datetime
from scrapy.item import Item, Field
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector

class BillBoardItem(Item):
    date = Field()
    song = Field()
    artist = Field()

BASE_URL = "http://www.billboard.com/charts/%s/hot-100"

class BillBoardSpider(BaseSpider):
    name = "billboard_spider"
    allowed_domains = ["billboard.com"]

    def __init__(self):
        date = datetime.date(year=1958, month=8, day=9)

        self.start_urls = []
        while True:
            if date.year >= 2013:
                break

            self.start_urls.append(BASE_URL % date.strftime('%Y-%m-%d'))
            date += datetime.timedelta(days=7)

    def parse(self, response):
        hxs = HtmlXPathSelector(response)
        date = hxs.select('//span[@class="chart_date"]/text()').extract()[0]

        songs = hxs.select('//div[@class="listing chart_listing"]/article')
        for song in songs:
            item = BillBoardItem()
            item['date'] = date
            try:
                item['song'] = song.select('.//header/h1/text()').extract()[0]
                item['artist'] = song.select('.//header/p[@class="chart_info"]/a/text()').extract()[0]
            except:
                continue

            yield item

rawDescription: How to scrape more efficiently with Urllib2?

description: Scrape more efficiently with Urllib2


code:
def upload_file(request):
    if request.method == 'POST':
        form = UploadForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/success/url/')
    else:
        form = UploadFileForm()
    return render_to_response('upload.html', {'form': form})

rawDescription: Uploading csv file from url using django forms


code:
def wrap_user(instance):
    class wrapped_user(type(instance)):
        __metaclass__ = type
        def __new__(cls):
            pass
        def __init__(self):
            pass
        def __getattribute__(self, attr):
            self_dict = object.__getattribute__(type(self), '__dict__')
            if attr in self_dict:
                return self_dict[attr]
            return getattr(instance, attr)
        def extra_feature(self, foo):
            return instance.username + foo # or whatever
    return wrapped_user()

rawDescription: How to fake type with Python

description: Fake type with Python


code:
D = {}
[D.setdefault(v, []).append(i) for i, v in enumerate(A)]

rawDescription: Dictionary Comprehension for list values


code:
from pylab import *
import numpy.ma as ma

data=np.arange(-50,50).reshape(10,10)
data=np.abs(data)
#create a mask where only values=0 are true:
mask = data == 0
#create a masked array by combining our mask and data:
mx = ma.masked_array(data, mask)
#set masked values in cm.YlOrRd to 'black'
cm.YlOrRd.set_bad(color='black', alpha=None)
# pcolor(data,cmap=cm.YlOrRd)
#we must use pcolormesh instead of pcolor, as pcolor does not draw masked values at all
pcolormesh(mx,cmap=cm.YlOrRd)
show()

rawDescription: Setting arbitrary color in pseudocolor plot with matplotlib


code: dir(s)

rawDescription: Finding letters in a string

description: Finding letters in a string


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

distance=np.array([1000,3000,7000,15000,20000])
elevation=np.array([100,200,350,800,400])

def plot(x, y):
    fig, ax = plt.subplots(figsize=(8, 2))

    # Plot your data and place a marker at the peak location
    maxpoint=x[np.argmax(y)], max(y)
    ax.scatter(maxpoint[0], maxpoint[1], s=10)
    ax.plot(x, y)

    # Reduce the maximum number of ticks and give matplotlib more flexibility
    # in the tick intervals it can choose.
    # Essentially, this will more or less always have two ticks on the y-axis
    # and 4 on the x-axis
    ax.locator_params(axis='y', nbins=3, steps=range(1, 11))
    ax.locator_params(axis='x', nbins=5, steps=range(1, 11))

    # Annotate the peak location. The text will always be 5 points from the
    # data location.
    ax.annotate('Maximum = {:0.0f}'.format(maxpoint[1]), size=8,
                xy=maxpoint, xytext=(5, 5), textcoords='offset points')

    # Give ourselves lots of padding on the y-axis, less on the x
    ax.margins(x=0.01, y=0.3)
    ax.set_ylim(bottom=y.min())

    # Set the aspect of the plot to be equal and add some x/y labels
    ax.set(xlabel='Distance', ylabel='Elevation', aspect=1)
    plt.show()

plot(distance,elevation)

rawDescription: Matplotlib axis limits and text positions independent of dataset units


code:
pw = pg.plot()
while True:
    ...
    pw.plot(x, y, clear=True)
    pg.QtGui.QApplication.processEvents()

rawDescription: What is the easiest way to achieve realtime plotting in pyqtgraph


code: plt.xticks([0, 1, 2], ['hello', 'apple', 'orange'])

rawDescription: Scikit learn confusion matrix

description: Scikit learn confusion matrix


code:
from shlex import shlex
lex = shlex('C:\\test.exe --help')
lex.whitespace_split = True
lex.escape = ''
list(lex)

rawDescription: Python os.path.basename, strip parameters


code:
from collections import Counter
mylist = [20, 30, 25, 20]
[k for k,v in Counter(mylist).items() if v>1]

rawDescription: Identify duplicate values in a list in Python


rawDescription: python - get part of string from query results

description: Python - get part of string from query results


code: wall

rawDescription: How to "embed" a small numpy array into a predefined block of a large numpy array?


rawDescription: Concatanating array by While on Python

description: Concatanating array by While on Python


code:
...
im = numpy.array(img, dtype=int)

packed = im[:,:,0]<<16 | im[:,:,1]<<8 | im[:,:,2]
colors = set(numpy.unique(packed.ravel()))
colors.remove(255<<16 | 255<<8 | 255)

for color in colors:
    py, px = numpy.where(packed == color)
    print(px.min(), py.min(), px.max(), py.max())

rawDescription: Finding bounding boxes of RGB colors in image


code:
class FoodComponentFilter(django_filters.Filter):
    def filter(self, qs, value):
        strs = value.split(',')
        if len(strs) != 2:
            raise Exception
        return qs.filter(
            food_components__in = Component.objects.filter(
                name=strs[0],
                value=float(strs[1])
            )
        )

rawDescription: Django FilterSet AND(?) condition

description: Django FilterSet AND(?) condition


code: dictionary2 = {key:value*number for key,value in dictionary.items()}

rawDescription: Changing all the values of a dictionary

description: Changing all the values of a dictionary


code:
import difflib
difflib.get_close_matches('hello', words)

rawDescription: find a list of keywords from a text string and find inexact matches

description: Find a list of keywords from a text string and find inexact matches


code:
df = pd.DataFrame([["A"], ["A"], ["A"]], columns=["category"])
df
res = df.groupby("category").size()
res

rawDescription: Dont drop non present indexes on group_by - Pandas


code: stretch = Linear.linear_stretch()

rawDescription: multiprocessing.Process - Variable as function

description: Multiprocessing.Process - Variable as function


code:
f = gzip.open('foo.bin.gz', 'wb')
foo.tofile(f)
f.close()

rawDescription: Create a zipfile directly from numpy array without an intermediary file


code:
def minimal(iterable, func):
    'Return a list of minimal values according to a weighting function'
    it = iter(iterable)
    try:
        x = next(it)
    except StopIteration:
        return []
    lowest_values = [x]
    lowest_weight = func(x)
    for x in it:
        weight = func(x)
        if weight == lowest_weight:
            lowest_values.append(x)
        elif weight < lowest_weight:
            lowest_values = []
            lowest_weight = weight
    return lowest_values

rawDescription: Find all minimal elements in a list or set as weighted by a function


code:
mylist = ["some static text common to all files",st,"more static content"]
f.writelines(mylist)

rawDescription: Python - Parse large list into separate text files by name and content


code:
from plotly.offline.offline import _plot_html
data_or_figure = [{"x": [1, 2, 3], "y": [3, 1, 6]}]
plot_html, plotdivid, width, height = _plot_html(
    data_or_figure, False, "", True, '100%', 525)
print(plot_html)

rawDescription: python save plotly plot to local file and insert into html

description: Python save plotly plot to local file and insert into html


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:
def __init__(self, fileName):
    self.name = self.loadData(fileName)

rawDescription: Defining a class property within __init__ as opposed to within another class method -- python


code:
def foo(num):
    """Convert a string implementation to
       Python Object"""
    try: #First check if its an Integer
        return int(num)
    except ValueError:
        #Well not an Integer
        pass
    try: #Check if its a float
        return float(num)
    except ValueError:
        pass
    #Invalid Number
    raise TypeError("Invalid Number Specified")

rawDescription: Pythonic way of writing a library function which accepts multiple types?


code:
res = res.stack()
res

rawDescription: Python Pandas merge two data frames based on multiple values field


code:
times, charges = numpy.loadtxt("mdat.txt", skiprows=2, unpack=True)
times
charges

rawDescription: Reading Data in Columns Python 2.7.3

description: Reading Data in Columns Python 2.7.3


code:
response = urllib2.urlopen('http://example.com')
response_encoding = response.headers.getparam('charset')
# or in Python 3: response.headers.get_content_charset(default)

rawDescription: A good way to get the charset/encoding of an HTTP response in Python


code:
for seta in (set([x for x in l if len(x) > 0]) for l in a):
    setb = set([x for x in next(b) if len(x) > 0])
    print(len(seta^setb)==0)

rawDescription: Compare lines in 2 text files with different number of columns


rawDescription: How to I check that a string contains only digits and / in python?


code:
from itertools import islice
print(sorted(([ele[0],sum(islice(ele,1,None)) / len(l) - 1] for ele in l),key=itemgetter(1),reverse=True))

rawDescription: Sort tuple by averages

description: Sort tuple by averages


code:
def __getitem__(self, key):
    if key not in self:
        dict.__setitem__(self, key, dotdictify())
    return dict.__getitem__(self, key)

rawDescription: Python: Easily access deeply nested dict (get and set)


code:
import numpy as np

class truncarray(np.ndarray):
    def __new__( cls, array ):
        obj = np.asarray(array).view(cls)
        return obj
    def __add__( a, b ):
        s = slice(0, min(len(a),len(b)))
        return np.add(a[s],b[s])
    __radd__ = __add__

a = truncarray([1,2,3])
b = truncarray([4,5,6,7])
a_array = np.array([1,2,3])
b_array = np.array([4,5,6,7])

rawDescription: Automatically truncate numpy arrays

description: Automatically truncate numpy arrays


code:
import numpy as np
classes = np.unique(["ham", "spam", "eggs"])

for xs, ys in minibatches:
    lr.partial_fit(xs, ys, classes=classes)

rawDescription: Batch gradient descent with scikit learn (sklearn)


code: simple_page = Blueprint('simple_page')

rawDescription: Flask Blueprint Initialization - Initializing some global variables


code:
#!/usr/bin/python

import unittest
import sys
sys.path.insert(0, 'lib.zip')

if __name__ == "__main__":
    all_tests = unittest.TestLoader().discover('.')
    unittest.TextTestRunner().run(all_tests)

rawDescription: Bootstrapping tests and using Python test discovery


code:
class UserView(AdminView):
    form_excluded_columns = ('password')

class RoleView(AdminView):
    pass

class PostView(AdminView):
    pass

rawDescription: flask-admin is_accessible usage

description: Flask-admin is_accessible usage


rawDescription: Get files created before x days, y hours and z minutes in python?


code:
if y % 100:
    somevar = y % 100

rawDescription: Slicing and if statements (Python)

description: Slicing and if statements (Python)


rawDescription: Why doesn't Beautifulsoup find this input by name?


code:
import base64
import struct
struct.unpack('>I', base64.b64decode('vHI6Bw=='))

rawDescription: Difficulty comparing generated and google cloud storage provided CRC32c checksums


code:
class Json(TypeDecorator):

    impl = String

    def process_bind_param(self, value, dialect):
        return json.dumps(value)

    def process_result_value(self, value, dialect):
        return json.loads(value)

class Word(Base):
    __tablename__ = "words"

    eng = Column(String(32), primary_key=True)
    chinese = Column(Json(128))

rawDescription: python using sqlalchemy store a list into sql database

description: Python using sqlalchemy store a list into sql database


code:
0.131*trees + 0.121*graph + 0.119*system + 0.115*user + 0.098*survey + 0.082*interface + 0.080*eps + 0.064*minors + 0.056*response + 0.056*computer
0.171*time + 0.171*user + 0.170*response + 0.082*survey + 0.080*computer + 0.079*system + 0.050*trees + 0.042*graph + 0.040*minors + 0.040*human
0.155*system + 0.150*human + 0.110*graph + 0.107*minors + 0.094*trees + 0.090*eps + 0.088*computer + 0.087*interface + 0.040*survey + 0.028*user

0.333333333333

['The EPS user interface management system', 'The generation of random binary unordered trees', 'The intersection graph of paths in trees', 'Graph minors A survey']
['A survey of user opinion of computer system response time', 'Relation of user perceived response time to error measurement']
['Human machine interface for lab abc computer applications', 'System and human system engineering testing of EPS', 'Graph minors IV Widths of trees and well quasi ordering']

rawDescription: Topic distribution: How do we see which document belong to which topic after doing LDA in python


code:
from timeit import Timer
Timer("mydict = {'a' : 1, 'b' : 2, 'c' : 'three'}").timeit()
Timer("mydict = dict(a=1, b=2, c='three')").timeit()

rawDescription: In Python, use "dict" with keywords or anonymous dictionaries?


code: import numpy as np

rawDescription: Efficiently Removing Very-Near-Duplicates From Python List


code:
class TabBar(QTabBar):
    middleClicked = pyqtSignal(int)

    def __init__(self):
        super(QTabBar, self).__init__()
        self.previousMiddleIndex = -1

    def mousePressEvent(self, mouseEvent):
        if mouseEvent.button() == Qt.MidButton:
            self.previousIndex = self.tabAt(mouseEvent.pos())
        QTabBar.mousePressEvent(self, mouseEvent)

    def mouseReleaseEvent(self, mouseEvent):
        if mouseEvent.button() == Qt.MidButton and \
            self.previousIndex == self.tabAt(mouseEvent.pos()):
            self.middleClicked.emit(self.previousIndex)
        self.previousIndex = -1
        QTabBar.mouseReleaseEvent(self, mouseEvent)

class MainWindow(QMainWindow):
    def __init__(self):
        super(QMainWindow,self).__init__()
        self.tabWidget = QTabWidget(self)
        self.setCentralWidget(self.tabWidget)

        self.tabBar = TabBar()
        self.tabWidget.setTabBar(self.tabBar)
        self.tabBar.middleClicked.connect(self.onTabMiddleClick)

    # function called with the index of the clicked Tab
    def onTabMiddleClick(self, index):
        pass

rawDescription: PyQt mouse events for QTabWidget

description: PyQt mouse events for QTabWidget


code:
class MusicLink(object):
    #...
    def searchSong(self,search):
        musicObject = self.loadData(dataFile)
        """
        The following code-line is a list-comprehension. (http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)
        try to read it like a sentence
        Create a list of song(s) by taking every song in musicObject["LinkCollection"]
        but only if the lowercase search-string is within the song 's lowercase title
        """
        return [song for song in musicObject["LinkCollection"] if search.lower() in song["title"].lower() ]
    #…

rawDescription: How should I write my method to get the 'link' value from the result I get after searching through JSON?


code:
with open('somefile') as fp:
    for line in fp:
        a, *b, c, d, e, f = line.strip().split('|')
        b = '|'.join(b)
        # do something

rawDescription: Chopping A Line From A Text Document Into Different Strings


code:
if mylist:
    mylist.sort()
    last = mylist[-1]
    for i in range(len(mylist)-2, -1, -1):
        if last == mylist[i]:
            del mylist[i]
        else:
            last = mylist[i]

rawDescription: Deleting repeats in a list python

description: Deleting repeats in a list python


rawDescription: Python: Printing dataframe to csv

description: Python: Printing dataframe to csv


code:
import argparse

def output_version():
    print('Version 1.0!')

parser = argparse.ArgumentParser(description="A program to do something.")
parser.add_argument('-v', help='Output version number.', action='store_true')

args = parser.parse_args()
if args.v:
    output_version()

rawDescription: Storing code inside a dictionary

description: Storing code inside a dictionary


code:
words = { 'ArabicWord' : { 'POS1' : 'EnglishTranslation1' } }
words['ArabicWord']['POS2'] = 'EnglishTranslation2'
words

rawDescription: Python: Dictionary with 3 items

description: Python: Dictionary with 3 items


code: cb = Bunch(config)

rawDescription: Accesing dictionary with class attribute


code:
# folder0/__init__.py
from . import folder1
from . import folder2

rawDescription: Python - Import from deeper subfolder

description: Python - Import from deeper subfolder


rawDescription: Limiting print output

description: Limiting print output


rawDescription: Is there a more Pythonic way to pad a string to a variable length using string.format?


rawDescription: Django Group By Weekday?

description: Django Group By Weekday


code:
def isLink(a, b):
    return os.path.islink(a) and os.path.abspath(os.readlink(a)) == os.path.abspath(b)

rawDescription: If path is symlink to another path

description: If path is symlink to another path


code:
order = np.argsort(-z1) # for desc
x = np.take(x, order)
y = np.take(y, order)
z1 = np.take(z1, order)
z2 = np.take(z2, order)

rawDescription: Plot larger points on bottom and smaller on top


code:
import sys
if sys.platform == "win32":
    import os, msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)

rawDescription: Problems outputting an image over http using Python


code:
## main.py ##
try:
   import swigpackagefoo.swigsubpackagebar as swigClass
except ImportError:
   import swigMock.swigsubpackagebar as swigClass

aClass = swigClass()

rawDescription: how do I create a in-line module

description: Create a in-line module


code:
import sys
from threading import Event, Thread
from tkinter import Tk, ttk
from urllib.request import urlretrieve

def download(url, filename):
    root = progressbar = quit_id = None
    ready = Event()
    def reporthook(blocknum, blocksize, totalsize):
        nonlocal quit_id
        if blocknum == 0: # started downloading
            def guiloop():
                nonlocal root, progressbar
                root = Tk()
                root.withdraw() # hide
                progressbar = ttk.Progressbar(root, length=400)
                progressbar.grid()
                # show progress bar if the download takes more than .5 seconds
                root.after(500, root.deiconify)
                ready.set() # gui is ready
                root.mainloop()
            Thread(target=guiloop).start()
        ready.wait(1) # wait until gui is ready
        percent = blocknum * blocksize * 1e2 / totalsize # assume totalsize > 0
        if quit_id is None:
            root.title('%%%.0f %s' % (percent, filename,))
            progressbar['value'] = percent # report progress
            if percent >= 100:  # finishing download
                quit_id = root.after(0, root.destroy) # close GUI

    return urlretrieve(url, filename, reporthook)

download(url, 'downloaded_file.py')

rawDescription: Download progressbar for Python 3

description: Download progressbar for Python 3


rawDescription: Python table titles into dictionary

description: Python table titles into dictionary


code:
['any string', '\x13\x00\x00\x00', 'any string', '\xfe\x9b<P\xd2\t\xc2\x02',
 '\x9a\x99\x19?', 'any string', 'any string']

rawDescription: How to convert a list with multiple types to binary in Python?

description: Convert a list with multiple types to binary in Python


code: newvalue = {"name": "Eric", "weight": 225, "nextname": None, "nextweight": None}

rawDescription: Doubly Linked list in Python

description: Doubly Linked list in Python


code:
def raw_dispatch_command(function, *args, **kwargs):
    ...
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
    set_default_command(parser, function)
    dispatch(parser, *args, **kwargs)

rawDescription: Python’s argh library: preserve docstring formatting in help message


code:
import re
re.search(r'[^f]', 'ffffooooooooo').start()

rawDescription: Python: Find first non-matching character


code:
def getSubs(cls):
    for sub in cls.__subclasses__():
        if not sub.__dict__.get('ignore_me', False):
            yield sub
        for desc in getSubs(sub):
            yield desc

rawDescription: Static attribute that is True only for a concrete class, and False for its children in Python


code:
graph = sps.rand(5, 5, density=0.2, format='csr')
graph.toarray()
non_empty_rows
sorted_out

rawDescription: How to read a sparse directed graph in scipy

description: Read a sparse directed graph in scipy


code: extra_context['iva'] = fact.importe_sin_iva * 0.21

rawDescription: How to make equations in views.py with a model field (beginner)

description: Make equations in views.py with a model field (beginner)


rawDescription: Using python requests on a simple form

description: Using python requests on a simple form


code:
def print_entries(date):
    """Prints all the entries that match with date"""
    with open('a.txt', 'r') as f:
        flag = False
        content = f.readlines()
        content = [line.strip('\n').split(',') for line in content]
        for row in content:
            if row[0] == date:
                flag = True
                print(*row, sep='\t')
        if not flag:
            print('Try again')
        return flag

while not print_entries(input("Enter date :")):
    pass

rawDescription: Search a data.txt file for information based on user input and print it(Python 3.5.1)


code:
from io import StringIO
def parts(r, sec_len, skip):
    consume(r, skip)
    for sli in iter(lambda: list(islice(r, sec_len)), []):
        yield "".join(sli)
        consume(r, skip)

with open("test.txt")as f:
    so = StringIO()
    so.writelines(parts(f, 4, 2))
    so.seek(0)
    print(pd.read_csv(so, header=None))

rawDescription: Skip every specified line before importing to pandas


rawDescription: Isolating divs in Beautiful Soup

description: Isolating divs in Beautiful Soup


code:
singleton = ThesaurusSingleton()
thesaurus = Thesaurus(singleton)

rawDescription: Python2.7: infinite loop when super __init__ creates an instance of it's own subclass


code:
#!/usr/bin/env python
import logging
from multiprocessing.dummy import Pool

debug = logging.getLogger(__name__).debug

def work(x_y):
    try:
        x, y = x_y # do some work here
        debug('got %r', x_y)
        return x / y, None
    except Exception as e:
        logging.getLogger(__name__).exception('work%r failed', x_y)
        return None, e

def main():
    logging.basicConfig(level=logging.DEBUG,
        format="%(levelname)s:%(threadName)s:%(asctime)s %(message)s")

    inputlist = [ (5,5),(10,4),(78,5),(87,2),(65,4),(10,10), (1,0), (0,1) ]
    pool = Pool(3)
    s = 0.
    for result, error in pool.imap_unordered(work, inputlist):
        if error is None:
           s += result
    print("sum=%s" % (s,))
    pool.close()
    pool.join()

if __name__ == "__main__":
   main()

rawDescription: Terminating a thread : Python

description: Terminating a thread : Python


code:
from itertools import chain, repeat, islice

def window(seq, size=2, fill=0, fill_left=True, fill_right=False):
    """ Returns a sliding window (of width n) over data from the iterable:
      s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...
    """
    ssize = size - 1
    it = chain(
      repeat(fill, ssize * fill_left),
      iter(seq),
      repeat(fill, ssize * fill_right))
    result = tuple(islice(it, size))
    if len(result) == size:  # `<=` if okay to return seq if len(seq) < size
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

rawDescription: Iterate over a ‘window’ of adjacent elements in Python


code:
from pandas.tseries.offsets import (as_datetime, as_timestamp, apply_nat,
                               DateOffset, relativedelta, datetime)
class MonthAnchor(DateOffset):
    """DateOffset Anchored to day in month

        Arguments:
        day_anchor: day to be anchored to
    """

    def __init__(self, n=1, **kwds):
        super(MonthAnchor, self).__init__(n)

        self.kwds = kwds
        self._dayanchor = self.kwds['day_anchor']

    @apply_nat
    def apply(self, other):
        n = self.n

        if other.day > self._dayanchor and n <= 0:  # then roll forward if n<=0
            n += 1
        elif other.day < self._dayanchor and n > 0:
            n -= 1

        other = as_datetime(other) + relativedelta(months=n)
        other = datetime(other.year, other.month, self._dayanchor)
        return as_timestamp(other)

    def onOffset(self, dt):
        return dt.day == self._dayanchor

    _prefix = ''

rawDescription: pandas timeseries resampling ending a given day

description: Pandas timeseries resampling ending a given day


rawDescription: Why does python 2.6 not update my numpy array?


code: writer.writerow([ID] + wordList)

rawDescription: write two values to csv row in python

description: Write two values to csv row in python


code:
import mechanize
import pprint
import lxml.etree as ET
import lxml.html as lh
import urllib
import urllib2

browser=mechanize.Browser()
browser.open("http://www.cbs.gov.il/ts/ID40d250e0710c2f/databank/series_func_e_v1.html?level_1=31&level_2=1&level_3=7")
browser.select_form(nr=0)

rawDescription: How can I scrape data from the Israeli Bureau of Statistics web query tool?

description: Scrape data from the Israeli Bureau of Statistics web query tool


code:
captcha_count = CaptchaStore.objects.count()
self.failUnlessEqual(captcha_count, 0)

rawDescription: How to unit test a form with a captcha field in django?

description: Unit test a form with a captcha field in django


code: #!/usr/bin/python

rawDescription: Run python script without the "python" keyword


code:
sps.coo_matrix(A)
m = sps.coo_matrix(A)
sps.issparse(m)

rawDescription: Scipy.sparse test for sparse matrix returns False for a diagonal matrix. Why?


code:
len.__class__
np.vdot.__class__

rawDescription: Determine whether a Python function is already implemented in C extension


code:
DEFAULTS = {
    'param1': 1,
    'param2': 'something',
}
meta = Meta()
for name, value in DEFAULTS.items():
    setattr(meta, name, param.get(name, value))

rawDescription: Dealing with a high volume of query params in python


code: sum([d[i] for i in d.keys() if 'item' in  i])

rawDescription: regex match item in python Counter

description: Regex match item in python Counter


code: numpy.savetxt(filename, a, newline=" ")

rawDescription: Saving numpy array to txt file row wise

description: Saving numpy array to txt file row wise


code:
from itertools import product
def get_chunks(items, number=3):
    for i in range(len(items) - number + 1):
        yield items[i: i + number]

rawDescription: Cartesian product that returns outputs of varied lengths


rawDescription: Add some characters at the beginning of each line


rawDescription: Splat operators in JavaScript, equivalent to *args and **kwargs in Python?


code:
M
import scipy.linalg as la
evals, lvecs = la.eig(M, right=False, left=True)
tol = 1e-15
mask = abs(evals - 1) < tol
evals = evals[mask]
evals
lvecs = lvecs[:, mask]
lvecs
u = lvecs/lvecs.sum(axis=0, keepdims=True)
u
np.dot(u.T, M).T

rawDescription: find Markov steady state with left eigenvalues (using numpy or scipy)

description: Find Markov steady state with left eigenvalues (using numpy or scipy)


code:
for i in obj_dates:
    dates_list.append(i.info)

rawDescription: iterating through a Django model field produces unwanted format

description: Iterating through a Django model field produces unwanted format


rawDescription: Exponential not working in Python

description: Exponential not working in Python


code:
text = r'ab\fx*abcdfansab\fasdafdab\f664s'
for m in re.finditer( r'ab\\f', text ):
   print( 'll found', m.start(), m.end() )

rawDescription: Recognize \ literally in Python strings

description: Recognize \ literally in Python strings


code:
self.controls = []
for i in range(100):
    control = wx.TextCtrl(self, -1, '')
    self.controls.append(control)
    sizer.Add(control)

...

self.controls[12].SetFocus()

rawDescription: wxPython .SetFocus() on ID

description: WxPython .SetFocus() on ID


code: [(nm, var) for nm, var in nc.variables.iteritems() if var.ndim > 1]

rawDescription: How can I find all the variables 2D or higher in a netcdf file using python?

description: Find all the variables 2D or higher in a netcdf file using python


code:
tmp=np.arange(6.).reshape(2,3)
lol=lambda first, second: np.sum(first)/second

rawDescription: argument order in numpy.apply_along_axis

description: Argument order in numpy.apply_along_axis


code:
def check_name(x):
   names_to_check = ('Jenson','Amra','McCay','Spinner','Jones')
   for i in names_to_check:
       if i == x:
          return True
   return False

rawDescription: Python - function to do string comparison


code:
def test(value):
    # will return False if value is either 3 5 or 7
    if value in [3, 5, 7]:
        return False
    return True

rawDescription: How to prevent a function from continuing after a return statement in Python

description: Prevent a function from continuing after a return statement in Python


rawDescription: How to save pictures with lower resolution in python?

description: Save pictures with lower resolution in python


code:
def double(n):
    return n * 2

def halve(n):
    return n // 2

def mult(m, n):

    def loop(m, n, a = 0):

        if n % 2 != 0:
            a = a + m
            m = double(m)
            n = halve(n)
        if n % 2 == 0:
            m = double(m)
            n = halve(n)
        if n != 0:
            return loop(m, n, a)
        return a
    return loop(m, n)

print(mult(57, 86))

rawDescription: Russian Peasant Multiplication Python using recursive-tail


code:
def roundrobin(*iterables):
    "roundrobin('ABC', 'D', 'EF') --> A D E B F C"
    # Recipe credited to George Sakkis
    pending = len(iterables)
    nexts = cycle(iter(it).__next__ for it in iterables)
    while pending:
        try:
            for next in nexts:
                yield next()
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

rawDescription: Breadth-first version of itertools.chain()


code:
dict((covar_type,GMM(n_components=num,
                covariance_type=covar_type, init_params='wmc',n_init=1, n_iter=10)) for covar_type in covs for num in num_comp)

rawDescription: Python: list iteration only returns last value


code:
import numpy as np
xaxis = yaxis = np.arange(0, 2000, 10)
x, y = np.meshgrid(xaxis, yaxis)
z = np.maximum(40 * np.sin(np.hypot(x, y) / 350), 0)

rawDescription: Algorithm for finding approximate area of the ground via elevation grid?


code:
def auth(request):
    """
    Returns context variables required by apps that use Django's authentication
    system.

    If there is no 'user' attribute in the request, uses AnonymousUser (from
    django.contrib.auth).
    """
    # If we access request.user, request.session is accessed, which results in
    # 'Vary: Cookie' being sent in every request that uses this context
    # processor, which can easily be every request on a site if
    # TEMPLATE_CONTEXT_PROCESSORS has this context processor added.  This kills
    # the ability to cache.  So, we carefully ensure these attributes are lazy.
    # We don't use django.utils.functional.lazy() for User, because that
    # requires knowing the class of the object we want to proxy, which could
    # break with custom auth backends.  LazyObject is a less complete but more
    # flexible solution that is a good enough wrapper for 'User'.
    def get_user():
        if hasattr(request, 'user'):
            return request.user
        else:
            from django.contrib.auth.models import AnonymousUser
            return AnonymousUser()

    return {
        'user': SimpleLazyObject(get_user),
        'messages': messages.get_messages(request),
        'perms':  lazy(lambda: PermWrapper(get_user()), PermWrapper)(),
    }

rawDescription: How to do a DetailView of Users in Django?

description: Do a DetailView of Users in Django


code:
def methodA(self):
    if doc['flag']:
        self.anotherMethod()

def anotherMethod(self):
    self.method1()
    self.method2()

rawDescription: Reusing code from a method which performs a flag check


code:
my_client_context.setsockopt( zmq.LINGER, 0 ) # do not wait for anything
my_client_socket.close()                      # statefull close
my_client_context.term()                      # gracefull termination / release of resources ( no MEM leaks )

rawDescription: ZeroMQ - how to make a CLIENT to give up and try at a later time if the SERVER doesn't respond?


code: lines[3] # as lines is a list

rawDescription: Ways to read/edit multiple lines in python


code:
session = mapi.MAPILogonEx(0, MAPIProfile, None, mapi.MAPI_EXTENDED |
                           mapi.MAPI_LOGON_UI | mapi.MAPI_NEW_SESSION)

rawDescription: Python - Sending Outlook email from different address using pywin32


code:
def __getitem__(self, key):
    if key not in self.traits.keys():
        raise KeyError
    ...
    return traits[key]

def __setitem__(self, key, value):
    if key not in self.traits.keys():
        raise KeyError
    ...
    traits[key] = value

rawDescription: Correct useage of getter/setter for dictionary values


code:
reformat_authors(r'John Bar \and Tom Foo \and Sam Foobar \and Ron Barfoo')
reformat_authors(r'John Bar \and Tom Foo \and Sam Foobar')
reformat_authors(r'John Bar \and Tom Foo')
reformat_authors(r'John Bar')

rawDescription: Join author names with python: first ones by comma and last one by and


rawDescription: regEx: To match two groups of chars

description: RegEx: To match two groups of chars


code: a = retry(stop_max_attempt_number=3)(a)

rawDescription: How to use @retry with keyword arguments AND pass a function

description: Use @retry with keyword arguments AND pass a function


code:
def cga_quantize(image):
    pal_image= Image.new("P", (1,1))
    pal_image.putpalette( (0,0,0, 0,255,0, 255,0,0, 255,255,0) + (0,0,0)*252)
    return image.convert("RGB").quantize(palette=pal_image)

rawDescription: How do I convert any image to a 4-color paletted image using the Python Imaging Library?

description: Convert any image to a 4-color paletted image using the Python Imaging Library


code:
class TimedButton(Button):
    """A simple ``Button`` subclass that produces an event at regular intervals
    when pressed.

    This class, when long-pressed, emits an ``on_time_slice`` event every
    ``time_slice`` milliseconds.

    :param long_press_interval: Defines the minimum time required to consider
                                the press a long-press.
    :type long_press_interval: int
    :param time_slice: The number of milliseconds of each slice.
    :type time_slice: int
    """

    def __init__(self, long_press_interval=550, time_slice=225, **kwargs):
        super(TimedButton, self).__init__(**kwargs)

        self.long_press_interval = long_press_interval
        self.time_slice = time_slice

        self._touch_start = None
        self._long_press_callback = None
        self._slice_callback = None

        self.register_event_type('on_time_slice')
        self.register_event_type('on_long_press')

    def on_state(self, instance, value):
        if value == 'down':
            start_time = time.time()
            self._touch_start = start_time

            def callback(dt):
                self._check_long_press(dt)

            Clock.schedule_once(callback, self.long_press_interval / 1000.0)
            self._long_press_callback = callback
        else:
            end_time = time.time()
            delta = (end_time - (self._touch_start or 0)) * 1000
            Clock.unschedule(self._slice_callback)
            # Fixes the bug of multiple presses causing fast increase
            Clock.unschedule(self._long_press_callback)
            if (self._long_press_callback is not None and
                delta > self.long_press_interval):
                self.dispatch('on_long_press')
            self._touch_start = None
            self._long_press_callback = self._slice_callback = None

    def _check_long_press(self, dt):
        delta = dt * 1000
        if delta > self.long_press_interval and self.state == 'down':
            self.dispatch('on_long_press')
            self._long_press_callback = None

            def slice_callback(dt):
                self.dispatch('on_time_slice')
                return self.state == 'down'

            Clock.schedule_interval(slice_callback, self.time_slice / 1000.0)

            self._slice_callback = slice_callback

    def on_long_press(self):
        pass

    def on_time_slice(self):
        pass

rawDescription: How to allow infinite integer values in a spinner?

description: Allow infinite integer values in a spinner


rawDescription: Removing every other element in NumPy

description: Removing every other element in NumPy


code:
def get_obj_ajax(request):
   import json
   data={"issuccess": 'no'}
   if request.method == "GET":
     obj= MyModel.objects.get(id=int(request.GET.get('id')))
     data = {"issuccess": 'yes',"title":obj.title ,"content": obj.content}
   return HttpResponse(json.dumps(data), content_type="application/json")

rawDescription: AJAX - Django - better approach?

description: AJAX - Django - better approach


code:
review_list = ['I like this book.', 'I do not like this novel, no, I do not.']
results = [twoeachside(s, 'not') for s in review_list]
assert results == [[], ['I do not like this I do not']]

rawDescription: Python: finding the two words following a key word


code:
import struct

def toU32(bits):
    return struct.unpack_from(">I", bits)[0]

def toS32(bits):
    return struct.unpack_from(">i", bits)[0]

rawDescription: Read 32-bit signed value from an "unsigned" bytestream


code:
{'Sasha Levchenko': 8.0, 'Charlie Watson': 8.0, 'Marie Curie': 10.0,
 'Margo Kazinsky': 9.5, 'Alice Brown': 8.5, 'Stephanie Hoover': 9.0,
 'Rosalind Samuelson': 6.5, 'Gordon Rogers': 8.5, 'Anastasia Melnyk': 8.5,
 'Evelyn Stewart': 10.0, 'Francine Walters': 9.0, 'Leonard Runka': 8.0,
 'Robert Wilson': 7.0, 'Roger Brosnan': 8.7, 'Francine Williamson': 9.0}

rawDescription: Creating a dictionary from csv

description: Creating a dictionary from csv


rawDescription: Can't extract text from html using SoupStrainer


code:
def foo(x, k=None):
    k = k or len(x)

rawDescription: How do I change an argument in a python function?

description: Change an argument in a python function


code:
from collections import Counter
s1cnt = Counter(s1w)
s2cnt = Counter(s2w)

rawDescription: Python: how many similar words in string?


code: [lst for lst in list_of_lists if lst.count(x) <= 1]

rawDescription: excluding lists that have more than one x

description: Excluding lists that have more than one x


code:
f=open('/path_to_file/list_2_array.dat', 'r')
l = []
for line in f.readlines():
    l.append(int(line.strip().split()[-1]))
array=np.array(l)

rawDescription: Assigning list to an array in python

description: Assigning list to an array in python


code:
df_list = [Home, Work, Park]
for df in df_list:
    name = [k for k, v in globals().items() if id(v) == id(df) and k[0] != '_'][0]
    df.columns = [col_name+'_{}'.format(name) for col_name in df.columns]

rawDescription: Renaming pandas data frame columns using a for loop


code:
for patname, pat in mypats:
    for m in pat.finditer(text):
        matches.append([m.start(), m.end(), patname, m.group()])

rawDescription: More compact and/or elegent way to run multiple regex matches


rawDescription: Python Unit Test: Mimic a command line argument for test purposes


code: (ngram_freq - (w1_freq * w2_freq) / total_num_words) / sqrt(ngram_freq + 1e-20)

rawDescription: What is the total bigram count returned for NLTK BigramCollocationFinder?


code:
def cross_product(A, B):
    """Returns a list of the cross product of A and B."""
    return [a+b for a in A for b in B]

square_letter = {c: e for e in ['ABC','DEF','GHI'] for c in e}
square_number = {n: e for e in ['123','456','789'] for n in e}
def find_peers(square, _letter=square_letter, _number=square_number):
    """
    Returns list of strings of shared squares in the unit.
    Example: find_peers('A2') -> ['A1', 'A2', 'A3', 'B1' , ..., 'C3']
    """
    return cross_product(_letter[square[0]], _number[square[1]])

find_peers('A2')
find_peers('E8')

rawDescription: Pythonic way of returning an element of a list if a certain char is found in that element


rawDescription: Iterating over an unknown number of lists referenced by dictionary key to allow comparison of values within each list


code:
linear_layout = lock.parent.parent
check_box = linear_layout.children[2].children[0]

rawDescription: How can i get the status of check box

description: Get the status of check box


rawDescription: how to access values of nested dictionary keys in python?

description: Access values of nested dictionary keys in python


code:
def is_prime(n):
    for x in range(2, n):
        if n % x == 0:
            return False
    return True

rawDescription: Finding a pair of prime numbers with a given arithmetic average using Python


code:
import os
os.getcwd()
os.chdir('c:')    # does not assume root directory
os.getcwd()
os.chdir('d:')
os.getcwd()
os.chdir('l:')
os.getcwd()
os.chdir('l:\\letter')
os.getcwd()
os.chdir('z:')
os.getcwd()
os.chdir('l:\\')
os.getcwd()

rawDescription: os.getcwd() for a different drive in Windows

description: Os.getcwd() for a different drive in Windows


code: plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.Paired)

rawDescription: Multilayer-perceptron, visualizing decision boundaries (2D) in Python


rawDescription: When __repr__() is called?

description: When __repr__() is called


rawDescription: Rearranging a (list of lists) matrix using list comprehensions only


code: outfile = raw_input("Please name your output file")

rawDescription: Writing Array to txt file with requested name


code:
class SomeObject:
    def __init__(self):
         self.reference_=None

    def connect(self, reference):
        self.reference_=reference
    #code to access parents MyVar
    def call(self):
        self.reference_.MyVar=5

class MyClass:
    MyVar = 3
    MyObject = SomeObject()
    def connect(self):
        self.MyObject.connect(self)

if __name__ == '__main__':
    myclass = MyClass()
    myclass.connect()
    myclass.MyObject.call()
    print(myclass.MyVar)

rawDescription: Access parents variables in Python

description: Access parents variables in Python


code:
given_list = ["e.x.a", "m.p.l.e", "ex.am.ple"]
sorted(given_list, key=lambda x: (x.count("."), len(x)))
sorted(given_list, key=lambda x: (x.count("."), len(x)), reverse=True)

rawDescription: Sorting a list using two keys

description: Sorting a list using two keys


code: [(t[1], t[0]) for t in mylist]

rawDescription: swap values in a tuple/list inside a list in python?

description: Swap values in a tuple/list inside a list in python


code:
time_elapsed = 0
for func in function_queue_generator:
    if time_elapsed > time_limit:
        yield
        time_elapsed = 0
    func()

rawDescription: Python: How to do break up array processing (using multiple queued functions) in timed chunks (600ms)


code:
v1fColor = np.array(map(int,value1.split(',')))
v2fColor =  np.array(map(int,value2.split(',')))

rawDescription: Python numpy: Convert string in to numpy array


code:
# create mask from surface
mask = pygame.mask.from_surface(building.surface)

# translate the position of the missile,
# since the top left coordinate of the mask is always (0, 0)
rel_point = sub(missile.position, building.position)
try:
    if mask.get_at(rel_point):
        # point in mask
        do_something()
except IndexError:
    pass

rawDescription: Check if a point collides with a surface (pixel perfect) in pygame


code:
class ModelUtils(object):
    def to_dict(self):
        result = super(ModelUtils,self).to_dict()
        result['key'] = self.key.id() #get the key as a string
        return result

rawDescription: ndb to_dict method does not include object's key

description: Ndb to_dict method does not include object's key


code:
line = 'a   b  c  d,e,f    g   h  i,j,k,l   m   n q,w,e,r  f o   o'
items = [x[0].split(',') for x in re.findall(r'((\w+,)+\w)',line)]
strs = re.sub(r'((\w+,)+\w+)','{}',line)

rawDescription: Python: Split a mixed String

description: Python: Split a mixed String


code: stri = ''.join(str(ord(c)) for c in text)

rawDescription: I have string of characters that i need to turn to string of ASCII numbers, how to convert it?


code:
from functools import partial
import maya.cmds as cmds

def createUI(windowTitle):

    windowID = 'myWindoWID'

    if cmds.window(windowID, exists = True):
        cmds.deleteUI(windowID)

    cmds.window( windowID, title = windowTitle, sizeable = False, resizeToFitChildren = True)

    cmds.rowColumnLayout(numberOfColumns = 3, columnWidth = [(1,120), (2,120), (3,120)])

    my_float_field = cmds.floatField(enable = False)
    cmds.button(label = 'enable the float field', command = partial(enableFloatField, my_float_field))
    cmds.button(label = 'disable the float field', command = partial(disableFloatField, my_float_field))

    cmds.showWindow()

def enableFloatField(float_field, *args):
    #enable the float field
    cmds.floatField(float_field, edit=True, enable=True)

def disableFloatField(float_field, *args):
    #disable the float field
    cmds.floatField(float_field, edit=True, enable=False)

createUI('my window')

rawDescription: enable or disable a field in maya ui with python

description: Enable or disable a field in maya ui with python


code:
with open('path-to-file.txt') as infile:
  for line in infile:
    if condition:
      # skip a line
      next(infile)

rawDescription: Reading specific data from a text file

description: Reading specific data from a text file


code:
from django import forms

from models import Team, Game

class GameUpdateForm(forms.ModelForm):
    home_team_name = forms.CharField(max_length=20)
    away_team_name = forms.CharField(max_length=20)

    def save(self):
        obj = super(GameForm, self).save()

        if not obj.home_team_id:
            obj.home_team = Team()
        obj.home_team.name = self.cleaned_data.get('home_team_name')
        obj.home_team.save()

        if not obj.away_team_id:
            obj.away_team = Team()
        obj.away_team.name = self.cleaned_data.get('away_team_name')
        obj.away_team.save()

        return obj
    class Meta:
        model = Game
        exclude = ('home_team', 'away_team')

rawDescription: How can I have a modelformset with inline modelform?

description: Have a modelformset with inline modelform


code:
class proto(parentProtocol):
    def stringReceived(self, data):
        self.handle_server_response(data)
        next_command = self.command_queue.pop()
        # do stuff

rawDescription: How to properly trigger a python twisted transport?

description: Properly trigger a python twisted transport


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

# sample data
x = y = np.logspace(-3,3)

# create a figure
fig,ax = plt.subplots(1)

# plot sample data
ax.loglog(x,y)

# this is the function the FuncFormatter will use
def mylogfmt(x,pos):
    logx = np.log10(x) # to get the exponent
    if logx < 0:
        # negative sign is added automatically
        return u"$10^{{{:.0f}}}$".format(logx)
    else:
        # we need to explicitly add the positive sign
        return u"$10^{{+{:.0f}}}$".format(logx)

# Define the formatter
formatter = ticker.FuncFormatter(mylogfmt)

# Set the major_formatter on x and/or y axes here
ax.xaxis.set_major_formatter(formatter)
ax.yaxis.set_major_formatter(formatter)

plt.show()

rawDescription: Adding + sign to exponent in matplotlib axes


rawDescription: Sort numeric lines with thousand separators


rawDescription: Check list of tuples where first element of tuple is specified by defined string


code: keys = reduce(set.union, map(set, dct.values()))

rawDescription: In Python, how do I write the contents of nested dictionaries to a file in a certain format?


code: (total-free-cached)/total

rawDescription: Python system resources enumeration

description: Python system resources enumeration


code:
import numpy as np
from scipy.sparse.csgraph import minimum_spanning_tree, connected_components
from scipy.sparse import csr_matrix

# Create a random "distance" matrix.
# Select only the upper triangle since the distance matrix array would be symmetrical.
a = np.random.rand(5,5)
a = np.triu(a)

# Create the minimum spanning tree.
mst = minimum_spanning_tree(csr_matrix(a))
mst = mst.toarray()

# Get the index of the maximum value.
# `argmax` returns the index of the _flattened_ array;
# `unravel_index` converts it back.
idx = np.unravel_index(mst.argmax(), mst.shape)

# Clear out the maximum value to split the tree.
mst[idx] = 0

# Label connected components.
num_graphs, labels = connected_components(mst, directed=False)

# We should have two trees.
assert(num_graphs == 2)

# Use indices as node ids and group them according to their graph.
results = [[] for i in range(max(labels) + 1)]
for idx, label in enumerate(labels):
    results[label].append(idx)

print(results)

rawDescription: Method to split a SciPy minimum spanning tree based on greatest edge weight?


code:
if mazeList[x][y] == 'E':
        return True

rawDescription: Python Maze solving program: how to mark correct path


code: clear_buffer = time.time() + 60

rawDescription: Timeout after X second in Python

description: Timeout after X second in Python


rawDescription: python split function -avoids last empy space

description: Python split function -avoids last empy space


code: self.RobotMap[x][y] += Val

rawDescription: python script speed improvements

description: Python script speed improvements


code: train_end = (int(len(instances)*TRAINING_END) // CHANNELS) * CHANNELS

rawDescription: Whats the most pythonic way to do this?

description: Whats the most pythonic way to do this


code: new_list = [ mutable_object_factory() for _ in range(nbr) ]

rawDescription: Generate a list of a given length with fake elements. Django


code: d.attribute_unique_to_this_instance = "some value"

rawDescription: Giving attributes to an object in Python


code:
def merge (tgt, letter):
    for i in range (len (tgt) + 1):
        yield tgt [:i] + letter + tgt [i:]

rawDescription: Create new set of subsets out of set of subsets (python)


code:
bp = plt.boxplot(data, whis=[5, 95], showfliers=False)
sc = plt.scatter([1, 1], [data.min(), data.max()])

rawDescription: Matplotlib boxplot show only max and min fliers


code:
def a_add(self, other):
    cls = type(self)  # cls will be set to the class
    return cls.a + other

rawDescription: Are python object functions singletons?

description: Are python object functions singletons


rawDescription: Python coding style on function call with multiple parameters


code: df1 = df1.sort(['a', 'b'], ascending=[True, False])

rawDescription: How to sort a dataFrame in python pandas by two or more columns?

description: Sort a dataFrame in python pandas by two or more columns


code: board[6] in playerSym  # and not board[6] == playerSym

rawDescription: Tic Tac Cover up!! Can't get the program to work correctly


rawDescription: Simulating ajax request with python using the requests lib


code:
def is_iterable(x):
    return type(x) in [list, tuple] # or just isinstance(x, list)

rawDescription: Pythonic way of looping over variable that is either an element or a list


code:
# Debug with pdb.  Follow every step of the process to ensure that you are
# setting valeus as you thought, and that the code you thought would be
# called is actually being called.  I've had many problems like this where
# the error was in procedure, not in the actual code at hand.
import pdb; pdb.set_trace()

# check to see if id(Manager) is the same as id(self.__class__)

# in the set_domain() function:
# check to see what attributes you can see on Manager,
# and if they match the attributes on Manager and self.__class__ in __init__

rawDescription: How do python classes work?

description: How do python classes work


rawDescription: Dictionary value sorting

description: Dictionary value sorting


code:
LOGIN_REQUIRED_URLS = (
    r'/private_stuff/(.*)$',
    r'/login_required/(.*)$',
)

rawDescription: Best way to make Django's login_required the default

description: Make Django's login_required the default


code: names = pd.concat((df.plA, df.plB)).unique()

rawDescription: Calculating expanding mean on 2 columns simultaneously


code:
import numpy as np

up_bound = 1
low_bound = 0
dim = 4
j = 6
m = 2**j - 1

space = np.asarray(np.meshgrid(*[np.linspace(low_bound, up_bound, m)]*dim))

rawDescription: Creating variables in loop for dynamicly creating griddata()


code: pdb.set_trace = lambda : 0

rawDescription: How to tell the Python debugger to finish the program?

description: Tell the Python debugger to finish the program


code:
def OpenPage(self, event):
    import time
    # With that, we get the row and column where we clicked in
    grid_info=event.widget.grid_info()

    # week or weekend?
    if grid_info["row"] > 5: #may depend on amount of headers
        _timearray=self.weekendtimes
    else:
        _timearray=self.weektimes

    # get the column
    col=grid_info["column"]

    # get the startTime
    stime=_timearray[col]

    # end time is +30 minutes
    etime="%s"%(time.strptime("%s"%stime, "%H:%M")+time.struct_time(tm_min=30))

    # now call the handler...

rawDescription: Python timetable pass start and finish time that pressed button relevant to position


rawDescription: How to Reload a Python3 C extension module?

description: Reload a Python3 C extension module


rawDescription: python and mechanize.open()

description: Python and mechanize.open()


code:
df.idxmax(1)
df.idxmin(1)

rawDescription: Get min and max elements for 2 corresponding series in pandas


rawDescription: Processing two CSV files in parallel

description: Processing two CSV files in parallel


code:
import iso8601
utciso8601 = dt.astimezone(iso8601.iso8601.UTC).isoformat(' ')[:19]

rawDescription: Android Python MySQL Datetime Parsing

description: Android Python MySQL Datetime Parsing


rawDescription: list of dicts to/from dict of lists

description: List of dicts to/from dict of lists


code:
useful = []
with open ("Report.txt", "r") as myfile:
    for line in myfile:
        if "===" in line:
            break
    for line in myfile:
        useful.append(line)
a_string = "".join(useful)

rawDescription: How can I read a file to a string starting at a given word without knowing the line number?

description: Read a file to a string starting at a given word without knowing the line number


code:
#! /usr/bin/python3.2

import re

a = '524946(46|58){4}434452[22:33]367672736E'
patterns = [ ('([0-9a-fA-F]+)', 'Sequence '),
    ('(\\([0-9a-fA-F]+\\|[0-9a-fA-F]+\\))', 'Option '),
    ('({[0-9a-fA-F]+})', 'Curly '),
    ('(\\[[0-9a-fA-F]+:[0-9a-fA-F]+\\])', 'Slice ') ]

while a:
    found = False
    for pattern, name in patterns:
        m = re.match (pattern, a)
        if m:
            m = m.groups () [0]
            print (name + m)
            a = a [len (m):]
            found = True
            break
    if not found: raise Exception ('Unrecognized sequence')

rawDescription: Python - filter char based on type into a structure


code: cds_score[score] = id

rawDescription: Multiple hash assignments in perl - translated to python? Why equal 1 always?


code:
class BlockLabel(Label):
    scale_factor = .9
    factor = dimension = None

    def on_texture_size(self, *args):
        if not self.factor:
            self.factor = [self.font_size / self.texture_size[0], self.font_size / self.texture_size[1]]
        if not self.dimension:
            self.dimension = 1 if self.texture_size[0] * self.size[1] < self.texture_size[1] * self.size[0] else 0
        self.font_size = self.size[self.dimension] * self.scale_factor * self.factor[self.dimension]

rawDescription: How can I fit text in label in Kivy?

description: Fit text in label in Kivy


rawDescription: for information retrieval course using python, accessing given tf-idf weight

description: For information retrieval course using python, accessing given tf-idf weight


code:
Xpl = numpy.arange(xmin, xmax, 0.1).tolist()
Ypl = numpy.arange(ymin, ymax, 0.01).tolist()
Xpl, Ypl = numpy.meshgrid(Xpl, Ypl)

Z=[]
for j in range(len(Xpl)):
   for i in range(len(Xpl[0])):
        # your loop order was backwards
        Z.append(funcPower3([Xpl[j][i],Ypl[j][i]]))

# reshape Z
Z = numpy.array(Z).reshape(Xpl.shape)

fig = plt.figure('Power 3')
ax = fig.gca(projection='3d')
surf=ax.plot_surface(Xpl, Ypl, Z, rstride=8, cstride=8, alpha=0.3,cmap=cm.jet)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
plt.show()

rawDescription: Python matplotlib - formatting with meshgrid for user-defined function


rawDescription: Python: How do I find the complement of a list?


code:
from itertools import count, takewhile
for n in takewhile(lambda _: x0 < xmin, count(0)):
    xy.createSomeCube(x0,y0,z0,x1,y1,z1)
    xy.someCube(n).setSomeParameters(dx,dy,dz)

    ...

    x0 -= someDecrement(someArgument)

rawDescription: Python: get the index in a while loop

description: Python: get the index in a while loop


code:
Words = ['A','B','C']
for i,word in enumerate(Words):
    pyplot.text(x_coordinate[i],y_coordinate[i], word, fontsize=20)

rawDescription: How to use pyplot.text() in a cycle to print different string on plot after each cycle

description: Use pyplot.text() in a cycle to print different string on plot after each cycle


code: functions = [getattr(some_module, name) for name in names]

rawDescription: Executing a function in reverse in Python


code:
print(dat[6])
print(dat[18])
print(dat[7])
print(dat[8])
print(dat[3])

rawDescription: Python 2D array with same values

description: Python 2D array with same values


rawDescription: nested Python numpy arrays dimension confusion

description: Nested Python numpy arrays dimension confusion


code:
def sin(x, terms=4):
    return sum(
            (-1.)**n / math.factorial(2*n + 1) * math.pow(x, 2*n + 1)
        for n in range(terms))

rawDescription: Not Getting Correct Answer for sine & cosine in Python


code: unique = {frozenset(d.items()): d for d in dictlist}.values()

rawDescription: Is there a python builtin to extract the 'set' of unhashable objects from a list, using 'is' comparison?


code:
level = int(raw_input('Please input nth level: '))

N = level*2 + 5
for x in range(level+1):
    d = ' '.join(str(11**x))
    print('{d:^{N}} {x:>}'.format(N=N, d=d, x=x))

rawDescription: Creating a non-right Pascal's triangle (centered) in python


rawDescription: How to label the x axis in fraction numbers?

description: Label the x axis in fraction numbers


rawDescription: Python print on same line after sleep

description: Python print on same line after sleep


code:
def avg_grams(some_list):
    """ Returns the average grams of parameter list """
    return sum(some_list) / float(len(some_list))

a = [2, 3, 4]
b = [3, 4, 5]

print('overall sum: {}'.format(avg_grams(a+b)))

rawDescription: Combining averages of two lists

description: Combining averages of two lists


code:
import regex # say "yeah!" for Matthew Barnett
pattern = r'\[(?:[^[\]]++|(?R))*\]'
myregex = regex.compile(pattern)

# this outputs [EEE]
matches = myregex.findall('AAA [BBB [CCC]] [EEE]')
print (matches[-1])

# this outputs [C[D[E]F]] (simple nesting)
matches = myregex.findall('AAA [BBB] [C[D[E]F]]')
print (matches[-1])

# this outputs [B[C] [D] [E[F][G]]] (family-style nesting)
matches = myregex.findall('AAA [AAA] [B[]B[B]] [B[C] [D] [E[F][G]]]')
print (matches[-1])

rawDescription: Match the last group of (potentially) nested brackets


code:
(r"/login/google/", GoogleAuthHandler),
(r"/login/facebook/", FacebookAuthHandler),

rawDescription: Multiple authentication options with Tornado


code:
re.search(r'(?<=//).+(?= \" target)',
          'http://domain.com.uy " target').group(0)

rawDescription: Regex to return all characters until "/" searching backwards


code:
import pickle
def update():
  lis = pickle.load( open( "lis.pkl", "rb" ) ) # Load the list
  #do something with lis                     #modify it
  pickle.dump( lis, open( "lis.pkl", "wb" ) )  #save it again

rawDescription: how to update global variable in python

description: Update global variable in python


code:
conn = sqlite3.connect('/path/to/database.db')
cursor=conn.cursor()
t=(value,)
rowCount = cursor.execute("select field from table where other_field = ?", t)
if rowCount > 0:
   returnObject = cursor.fetchone()[0]

rawDescription: SQLite no return type in Python

description: SQLite no return type in Python


rawDescription: Index into dataframe by column value

description: Index into dataframe by column value


code:
r1 = resource_wrapper(UserResource())
r1.test(test=True)
# True

rawDescription: Decorate all class methods without redecorating each time


code:
result = reduce(operator.and_, [False] * 1000)
result = reduce(operator.or_, [True] * 1000)

rawDescription: Does Python's reduce() short circuit?

description: Does Python's reduce() short circuit


code:
#!/usr/bin/env python
import matplotlib

from pylab import *
from matplotlib.colors import colorConverter

#Some simple functions to generate colours.
def pastel(colour, weight=2.4):
    """ Convert colour into a nice pastel shade"""
    rgb = asarray(colorConverter.to_rgb(colour))
    # scale colour
    maxc = max(rgb)
    if maxc < 1.0 and maxc > 0:
        # scale colour
        scale = 1.0 / maxc
        rgb = rgb * scale
    # now decrease saturation
    total = sum(rgb)
    slack = 0
    for x in rgb:
        slack += 1.0 - x

    # want to increase weight from total to weight
    # pick x s.t.  slack * x == weight - total
    # x = (weight - total) / slack
    x = (weight - total) / slack

    rgb = [c + (x * (1.0-c)) for c in rgb]

    return rgb

def get_colours(n):
    """ Return n pastel colours. """
    base = asarray([[1,0,0], [0,1,0], [0,0,1]])

    if n <= 3:
        return base[0:n]

    # how many new colours to we need to insert between
    # red and green and between green and blue?
    needed = (((n - 3) + 1) / 2, (n - 3) / 2)

    colours = []
    for start in (0, 1):
        for x in linspace(0, 1, needed[start]+2):
            colours.append((base[start] * (1.0 - x)) +
                           (base[start+1] * x))

    return [pastel(c) for c in colours[0:n]]

axes([0.2, 0.2, 0.7, 0.6])   # leave room below the axes for the table

data = [[  66386,  174296,   75131,  577908,   32015],
        [  58230,  381139,   78045,   99308,  160454],
        [  89135,   80552,  152558,  497981,  603535],
        [  78415,   81858,  150656,  193263,   69638],
        [ 139361,  331509,  343164,  781380,   52269]]

colLabels = ('Freeze', 'Wind', 'Flood', 'Quake', 'Hail')
rowLabels = ['%d year' % x for x in (100, 50, 20, 10, 5)]

# Get some pastel shades for the colours
colours = get_colours(len(colLabels))
colours.reverse()
rows = len(data)

ind = arange(len(colLabels)) + 0.3  # the x locations for the groups
cellText = []
width = 0.4     # the width of the bars
yoff = array([0.0] * len(colLabels)) # the bottom values for stacked bar chart
for row in xrange(rows):
    bar(ind, data[row], width, bottom=yoff, color=colours[row])
    yoff = yoff + data[row]
    cellText.append(['%1.1f' % (x/1000.0) for x in yoff])

# Add a table at the bottom of the axes
colours.reverse()
cellText.reverse()
the_table = table(cellText=cellText,
                  rowLabels=rowLabels, rowColours=colours,
                  colLabels=colLabels,
                  loc='bottom')
ylabel("Loss $1000's")
vals = arange(0, 2500, 500)
yticks(vals*1000, ['%d' % val for val in vals])
xticks([])
title('Loss by Disaster')

show()

rawDescription: python - matplotlib - Create a multiline graph with results summary underneath

description: Python - matplotlib - Create a multiline graph with results summary underneath


rawDescription: Efficient matricization of a pandas dataframe


code: import simplecv

rawDescription: Python No module named, even though the module does appear


code: line1 = "Built By : " + raw_input("Built By : ")

rawDescription: create a input and create a file python script

description: Create a input and create a file python script


code:
from itertools import product
d = {'a':[1,2], 'b':[3,4,5]}
list(product(*d.values()))
[dict(zip(d.keys(), combo)) for combo in product(*d.values())]
from pprint import pprint
pprint(_)

rawDescription: Get list of all possible dict configs in Python


code:
# One approach is to find pythonhome by an environment variable
# Another is to use the windows registry but beware of different
# issue regarding 64 and 32 bit windows as shown in the link below:

rawDescription: Python: Sharing python site-packages libraries between two python installations


code:
import json

r = client.post("http://api.imgur.com/2/account/albums.json", json.dumps(payload))

rawDescription: requests post to imgur

description: Requests post to imgur


code:
f = open( 'file.py', 'w' )
f.write( 'dict = ' + repr(dict) + '\n' )
f.close()

rawDescription: Write variable to file, including name

description: Write variable to file, including name


code:
def toggleConsole():
    toggleConsole.show = not getattr(toggleConsole, "show", True)
    console = win32console.GetConsoleWindow()
    win32gui.ShowWindow(console, int(toggleConsole.show))

rawDescription: How can I set a true/false variable with if?

description: Set a true/false variable with if


code:
from collections import defaultdict
d1 = {'eggs':3, 'ham':2, 'toast':1}
d2 = {'eggs':2,'ham':1}
d = defaultdict(int)
dresult.update(d1)
for k,v in d2.items():
   dresult[k] += v

rawDescription: Merge dictionaries without overwriting, rather an addition of value if key equality


code:
if(singlePlayerCard == [1,2,3,4,5,6,7,8,9,10]):
    singlePlayerCardValue = singlePlayerCard

rawDescription: Python Blackjack game - referenced before assignment


code:
[k for k,v in d.items() if v['class'] == '2b']
Out[17]: ['c', 'b']

rawDescription: Recalling information from dictionaries within dictionaries


code:
from tempfile import NamedTemporaryFile
from shutil import copyfileobj
from os import remove

tempFileObj = NamedTemporaryFile(mode='w+b',suffix='jpg')
pilImage = open('/tmp/myfile.jpg','rb')
copyfileobj(pilImage,tempFileObj)
pilImage.close()
remove('/tmp/myfile.jpg')
tempFileObj.seek(0,0)

rawDescription: How to send image generated by PIL to browser?

description: Send image generated by PIL to browser


rawDescription: Where is the sqlite database file created by Django?


code: item_labels.sort(key=lambda t : len([x[1] for x in item_labels if x[1]==t[1] ]))

rawDescription: Python list sort by size of group

description: Python list sort by size of group


code: subprocess.call(["ls",  "-lrt"], stdout=open("foo.txt",'w'))

rawDescription: calling linux shell in python with writing output in a text file

description: Calling linux shell in python with writing output in a text file


code:
rowcount = select(p for p in Product if p.price > 100).count()  # approach 1
rowcount = Product.select(lambda p: p.price > 100).count()  # approach 2
rowcount = count(p for p in Product if p.price > 100)  # approach 3

rawDescription: how to make a rowcount in ponyorm? Python

description: Make a rowcount in ponyorm? Python


code:
def get_file(file):
    input_file = open(file, 'r')
    source_string = input_file.read().lower()
    input_file.close()
    return set(re.findall('[a-zA-Z]+', source_string))

rawDescription: How to avoid repetion with my code

description: Avoid repetion with my code


code:
import numpy as np

# some data
A = np.random.random((250000, 30))

# some random indices
x = np.random.randint(0, 250000, 150000)
y = np.random.randint(0, 30, 10)

def method1(A, x, y):
    return A[x[:, np.newaxis], y]

def method2(A, x, y):
    return A[np.ix_(x,y)]

def method3(A, x, y):
    return A[x][:,y]

def method4(A, x, y):
    return A[:,y][x]

rawDescription: Numpy: Efficient Way To Extract Subarray


rawDescription: How can i query for objects in current year , current month in django

description: Query for objects in current year , current month in django


code:
def eventFilter(self, watched, event):
    if event.type() == QEvent.KeyPress and \
       event.matches(QKeySequence.InsertParagraphSeparator):
       i = self.list.currentRow()
       # process enter key on row i

rawDescription: PyQt4 - Enter key pressed on item in QListView


code:
# use writelines
f = open(filename, 'w')
f.writelines((datum + os.linesep) for datum in data)
f.close()

rawDescription: How to write a memory efficient Python program?

description: Write a memory efficient Python program


code:
import os
import sys
import argparse
import csv
import indent
from xml.etree.ElementTree import ElementTree, Element, SubElement, Comment, tostring

def get_args(args):
    parser=argparse.ArgumentParser(description='Convert wordlist text files to various formats.', prog='Text Converter')
    parser.add_argument('-v','--verbose',action='store_true',dest='verbose',help='Increases messages being printed to stdout')
    parser.add_argument('-c','--csv',action='store_true',dest='readcsv',help='Reads CSV file and converts to XML file with same name')
    parser.add_argument('-x','--xml',action='store_true',dest='toxml',help='Convert CSV to XML with different name')
    #parser.add_argument('-i','--inputfile',type=str,help='Name of file to be imported',required=True)
    #parser.add_argument('-o','--outputfile',help='Output file name')
    parser.add_argument('inputfile',type=str,help='Name of file to be imported')
    parser.add_argument('outputfile',help='(optional) Output file name',nargs='?')
    args = parser.parse_args()
    if not (args.toxml or args.readcsv):
        parser.error('No action requested')
        return None
    if args.outputfile is None:
        args.outputfile = os.path.splitext(args.inputfile)[0] + '.xml'
    return args

def main(argv):
    args = get_args(argv[1:])
    if args is None:
        return 1
    inputfile = open(args.inputfile, 'r')
    outputfile = open(args.outputfile, 'w')
    reader = read_csv(inputfile)
    if args.verbose:
        print ('Verbose Selected')
    if args.toxml:
        if args.verbose:
            print ('Convert to XML Selected')
        generate_xml(reader, outputfile)
    if args.readcsv:
        if args.verbose:
            print ('Reading CSV file')
    return 1 # you probably want to return 0 on success

def read_csv(inputfile):
      return list(csv.reader(inputfile))

def generate_xml(reader,outfile):
    root = Element('Solution')
    root.set('version','1.0')
    tree = ElementTree(root)

    head = SubElement(root, 'DrillHoles')
    head.set('total_holes', '238')

    description = SubElement(head,'description')
    current_group = None
    i = 0
    for row in reader:
        if i > 0:
            x1,y1,z1,x2,y2,z2,cost = row
            if current_group is None or i != current_group.text:
                current_group = SubElement(description, 'hole',{'hole_id':"%s"%i})

                collar = SubElement (current_group, 'collar',{'':', '.join((x1,y1,z1))}),
                toe = SubElement (current_group, 'toe',{'':', '.join((x2,y2,z2))})
                cost = SubElement(current_group, 'cost',{'':cost})
        i+=1
    indent.indent(root)
    tree.write(outfile)

if (__name__ == "__main__"):
    sys.exit(main(sys.argv))

rawDescription: Using argparse to convert csv to xml in python


code:
import pandas

df1 = pandas.DataFrame({'A':[1,4,0,8,3,4,5,3,3,3,9,9],
                        'B':[5,5,7,4,2,0,0,0,0,0,0,0]})
print(df1)
cln = df1.unstack().drop_duplicates()
cln.drop(['A'], inplace=True)
print(cln)
cln = cln.reset_index(drop=True)
print(cln)

rawDescription: python pandas drop value from column 'B' if that value appears in column 'A'

description: Python pandas drop value from column 'B' if that value appears in column 'A'


rawDescription: Histogram which do not use bin intervals but concrete values


code:
df.loc[df.filename == 'test2.dat', 'n'] = df2[df2.filename == 'test2.dat'].loc[0]['n']
df

rawDescription: How to update values in a specific row in a Python Pandas DataFrame?

description: Update values in a specific row in a Python Pandas DataFrame


code:
a1
a2
np.in1d(a1[:,0],a2) # Intersecting rows mask for a1
a1[np.in1d(a1[:,0],a2)]

rawDescription: Python Numpy intersect1d on 1D array with 2D array


rawDescription: Python And Date Formats

description: Python And Date Formats


code: [fullList.index(i) for i in fullList if 'c' in i]

rawDescription: Python find the index of a multi value List?


code:
...
def create_a_person():
    global person
    person = Person(name_ent.get(), age_ent.get(), title_ent.get())

Button(root, text="Confirm", command=create_a_person).grid(row=3, columnspan=2)
Button(root, text="Print", command=lambda: print(person.print_person())).grid(row=4, columnspan=2)
...

rawDescription: Tkinter: Instatiate Object with Button

description: Tkinter: Instatiate Object with Button


code:
letters = ['L','K']
final_result = sorted(l, key=lambda x: (letters.index(x.split('_')[1]), months.index(x.split('_')[0])))

rawDescription: Sort list according given text of months


code:
def InsertionSort(l):
    """ sorts l in place using an insertion sort """
    for j in range(1, len(l)):
        key = l[j]
        i = j - 1
        while (i >=0) and (l[i] > key):
            l[i+1] = l[i]
            i = i - 1

        l[i+1] = key

rawDescription: Sorting 5 elements with minimum element comparison


code:
template = "{a}{b}-{c}{d}"
a = 1
b = 2
c = 3
d = 4
template.format(**{'a':a,'b':b,'c':c,'d':d})
template.format(a=a,b=b,c=c,d=d)

rawDescription: Python: split method call into multiple lines


code:
def nested(x, ys):
    return any(x in nested for nested in ys)

rawDescription: How to check if an element is in a nested list?

description: Check if an element is in a nested list


rawDescription: Functional assignment in numpy

description: Functional assignment in numpy


code:
taxonomy = {
    'Animalia': {
        'Chordata': {
            'Mammalia': {
                'Carnivora': {
                    'Canidae': {
                        'Canis': {
                            'coyote': {},
                            'dog': {}
                        }
                    },
                    'Felidae': {
                        'Felis': {
                            'cat': {}
                        },
                        'Panthera': {
                            'lion': {}
                        }
                    }
                }
            }
        }
    },
    'Plantae': {
        'Solanales': {
            'Convolvulaceae': {
                'Ipomoea': {
                    'sweet potato': {}
                }
            },
            'Solanaceae': {
                'Solanum': {
                    'potato': {},
                    'tomato': {}
                }
            }
        }
    }
}

rawDescription: From python dictionary to html list

description: From python dictionary to html list


code:
porter = PorterStemmer()
[porter.stem(word) for word in word_tokenize(sent)]

rawDescription: Confused about priority between stemmer and pos tagger


code:
import pandas as pd

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])
df['day_of_week'] = df['my_dates'].dt.dayofweek

days = {0:'Mon',1:'Tues',2:'Weds',3:'Thurs',4:'Fri',5:'Sat',6:'Sun'}

df['day_of_week'] = df['day_of_week'].apply(lambda x: days[x])

rawDescription: Create a day-of-week column in a Pandas dataframe using Python


code:
def sub(self,event):

    for i in self.trying:
        i.Destroy()
    self.trying = [] # remove all StaticText from list

    self.something += 1
    self.trying.append(wx.StaticText(self.frame,-1,str(self.something),pos=(200,200)))
    self.trying.append(wx.StaticText(self.frame,-1,str(self.something),pos=(250,200)))

rawDescription: Why can't I destroy my StaticText in wxPython?


code:
CodeType = type((lambda: 0).func_code)
help(CodeType)

rawDescription: Synthetic functions in python

description: Synthetic functions in python


code:
s1 = 'bana'
s2 = 'ana'
second_index = s1.find(s2, s1.find(s2)+1)
print(second_index)

rawDescription: Substring Occurrences

description: Substring Occurrences


code:
from celery.decorators import task

@task
def publish_post(post_id):
    ''' Sets the status of a post to Published '''
    from blog.models import Post

    Post.objects.filter(pk=post_id).update(status=Post.STATUS_PUBLISHED)

rawDescription: Trouble scheduling and rescheduling posts with Celery


code:
import json

with open('conf.json') as conf:
    # JSON parser will convert it to dictionary
    constants = json.load(conf)

rawDescription: Organizing code for Testing with Constants from a Configuration File


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

os.environ['DJANGO_SETTINGS_MODULE'] = 'sample.settings'
sys.path.append(os.path.join(os.environ['OPENSHIFT_REPO_DIR'],'mysite'))

virtenv = os.path.join(os.environ['OPENSHIFT_PYTHON_DIR'],'virtenv')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:execfile(virtualenv, dict(__file__=virtualenv))
except IOError:pass

from django.core.handlers import wsgi
application = wsgi.WSGIHandler()

rawDescription: Configure Django1.6 with python 27 on openshift Step by step


code:
URL = "www.website.com/users/"

with open('input.txt', 'r') as input_file:
    with open('output.txt', 'w') as output_file:
        for line in input_file:
            output_file.write(URL + line)

rawDescription: Using Python to generate URLs with names from txt


rawDescription: How to map key values using lists?

description: Map key values using lists


rawDescription: Defining variables efficiently according to a parameter that may take several values


code: form = DynamicForm(..., my_arg='value')

rawDescription: passing arguments to a dynamic form in django

description: Passing arguments to a dynamic form in django


code:
df.groupby("Symbol")["Close"].pct_change()
df["Perf1"] = df.groupby("Symbol")["Close"].pct_change()
df["Perf2"] = df.groupby("Symbol")["Close"].pct_change(2)
df

rawDescription: Can I apply a function that uses 'shift' on a grouped data frame, and return a simple data frame from pandas?

description: Apply a function that uses 'shift' on a grouped data frame, and return a simple data frame from pandas


code:
square_list = []
for i in range(1,6):
    square_list.append(i**2)
# square_list = [1, 4, 9, 16, 25]

rawDescription: what do the brackets mean around this python line?

description: What do the brackets mean around this python line


code:
group = pdb.gimp_layer_group_new(img)
group.name = "my group"

rawDescription: GIMP Python-fu nested group layers

description: GIMP Python-fu nested group layers


code:
def parse(tokens):
    """ take iterator of tokens, parse to dictionary or atom """
    dictionary = {}
    # iterate tokens...
    for token in tokens:
        if token == ")" or next(tokens) == ")":
            # token is ')' -> end of dict; next is ')' -> 'leaf'
            break
        # add sub-parse to dictionary
        dictionary[token] = parse(tokens)
    # return dict, if non-empty, else token
    return dictionary or int(token)

rawDescription: Extract data from within parenthesis in python


code:
x = p.Series()
N = 4
for i in xrange(N):
   x = x.set_value(i, i**2)

rawDescription: How to add a single item to a Pandas Series

description: Add a single item to a Pandas Series


code: df.pivot_table(index='id', columns='name', values='value', aggfunc='sum', fill_value=0)

rawDescription: pivot table(?) with a Pandas Dataframe

description: Pivot table(?) with a Pandas Dataframe


code:
i = 0
while i < 20:
    i += 1

    if i == 15:
        i = 5
    print(i)

rawDescription: Make index go back in for loop

description: Make index go back in for loop


rawDescription: Indexing from an ndimensional array - numpy/ python


rawDescription: Decimal to hex in python

description: Decimal to hex in python


code:
with open("input.fasta") as ecoli: # will close your file automatically
    from collections import Counter
    counts = Counter()
    for line in ecoli: # iterate over file object, no need to read all contents onto memory
        if line.startswith(">"): # skip lines that start with >
            continue
        counts.update(line.rstrip())
    total = float(sum(counts.values()))
    for key,val in counts.items():
        print("{}: {}, ({:.1%})".format(key,val, val / total))

rawDescription: Python Dict and Forloop with FASTA file

description: Python Dict and Forloop with FASTA file


code: result = [a <= value <= b for (value, (a, b)) in zip(main_voltages, limit_list)]

rawDescription: Perform check on lists

description: Perform check on lists


code:
import os
os.system("echo 18>import")
exit()

rawDescription: Python equivalent to Bash comand "echo"?

description: Python equivalent to Bash comand "echo"


code: no_match = [el for el in results_a if el not in results_b]

rawDescription: SQLite compare query Python

description: SQLite compare query Python


code:
with open("in.txt") as f:
    lines = f.readlines()
    for ind, line in enumerate(lines):
        if line.startswith("55"):
            lines[ind] = ""
    with open("in.txt","w") as f:
        f.writelines(lines)

rawDescription: to delete records from a file in python

description: To delete records from a file in python


code: print("Hello")

rawDescription: Conda environments and .BAT files

description: Conda environments and .BAT files


rawDescription: Pandas map column in place

description: Pandas map column in place


code:
strs = 'abcdefghijklmnopqrstuvwxyz'
import re
before, after = re.split('jklmnop',strs)
before
after

rawDescription: Regex search find before and after query. Python


code: data

rawDescription: Python Matrix sorting via one column

description: Python Matrix sorting via one column


rawDescription: xaxis numbers not printed on log-scale plot

description: Xaxis numbers not printed on log-scale plot


code: t.reshape(3, 4).T

rawDescription: Stab a 3d array

description: Stab a 3d array


rawDescription: masking the built-in variable with its magic behavior?

description: Masking the built-in variable with its magic behavior


code:
permutation = np.array([0,2,2])
col
df.loc[(df[col] == permutation).all(axis=1)]

rawDescription: Python: given list of columns and list of values, return subset of dataframe that meets all criteria


code:
import pandas as pd

def select(df, *args):
    cols = [x for x in args]
    return df[cols]

def rename(df, **kwargs):
    for name, value in kwargs.items():
        df = df.rename(columns={'%s' % name: '%s' % value})
    return df

class SinkInto(object):
    def __init__(self, function, *args, **kwargs):
        self.args = args
        self.kwargs = kwargs
        self.function = function

    def __rrshift__(self, other):
        return self.function(other, *self.args, **self.kwargs)

    def __repr__(self):
        return "<SinkInto {} args={} kwargs={}>".format(
            self.function,
            self.args,
            self.kwargs
        )

df = pd.DataFrame({'one' : [1., 2., 3., 4., 4.],
                   'two' : [4., 3., 2., 1., 3.]})

rawDescription: "Piping" output from one function to another using Python infix syntax


rawDescription: How to count the number of words in a paragraph and exclude some words (from file)?

description: Count the number of words in a paragraph and exclude some words (from file)


code:
def find_anagrams_in_wordlist(str, str_list):  # You shouldn't name something 'str' because it's a type.
    str_list = get_dictionary_wordlist()  # You are overwriting your incoming list with the same function call.

    for int in range (0, len(str)):  # You're executing your for loop once per letter in the candidate word.
        anagram(str, str_list[int])  # This function executes but isn't doing anything
        if anagram(str, str_list[int]):
            return(str_list[int])  # If you find something you are exiting your for loop AND your function

def anagram(str1, str2):
    str1_list = list(str1)
    str1_list.sort()  # The result of this is the same every time... and it's None
    str2_list = list(str2)
    str2_list.sort()  # Always returns None

    return (str1_list == str2_list)  # This is the only real work being done here.

rawDescription: Anagram Function Returning None

description: Anagram Function Returning None


rawDescription: Compare or match 2 strings and display matched word


code:
import warnings
warnings.simplefilter("ignore", DeprecationWarning)

rawDescription: Passing options to Python executable in non-interactive mode


rawDescription: Slicing a sparse scipy matrix to subsample for every 10th row and column


rawDescription: Binary I/O in Python

description: Binary I/O in Python


code:
import a
import b

rawDescription: Can I import a built-in module twice in both my script and custom module

description: Import a built-in module twice in both my script and custom module


code:
import collections

class D(collections.MutableMapping):
    '''
    Mapping that works like both a dict and a mutable object, i.e.
    d = D(foo='bar')
    and
    d.foo returns 'bar'
    '''
    # ``__init__`` method required to create instance from class.
    def __init__(self, *args, **kwargs):
        '''Use the object dict'''
        self.__dict__.update(*args, **kwargs)
    # The next five methods are requirements of the ABC.
    def __setitem__(self, key, value):
        self.__dict__[key] = value
    def __getitem__(self, key):
        return self.__dict__[key]
    def __delitem__(self, key):
        del self.__dict__[key]
    def __iter__(self):
        return iter(self.__dict__)
    def __len__(self):
        return len(self.__dict__)
    # The final two methods aren't required, but nice for demo purposes:
    def __str__(self):
        '''returns simple dict representation of the mapping'''
        return str(self.__dict__)
    def __repr__(self):
        '''echoes class, id, & reproducible representation in the REPL'''
        return '{}, D({})'.format(super(D, self).__repr__(),
                                  self.__dict__)

rawDescription: How would I implement a dict with Abstract Base Classes in Python?


code:
def mycallback(w):
    for l in w:
        for key, value in l.items():
            ddict[key].update(value)

rawDescription: python map_async, where is the overhead coming from?

description: Python map_async, where is the overhead coming from


code:
l = ['foo', 'bar', 'baz']
i = l.index('bar')
# i is 1, because l[1] == 'bar'

rawDescription: trying to find out places located within list

description: Trying to find out places located within list


code:
def dicty(*bases, **attrs):
    if not bases:
        bases = (object,)
    return type("<from dict>", bases, attrs)

class Foo(dicty(a=1, b=2, c=3)):
    pass

# if you already have the dict, use unpacking

dct = dict(a=1, b=2, c=3)

class Foo(dicty(**dct)):
    pass

rawDescription: python dynamically set non-instance class attributes

description: Python dynamically set non-instance class attributes


code:
if condition:
    return bool(otherCondition)

rawDescription: Python does not allow multiple return() statements in ternary; possible alternative that is also aesthetically pleasing?


rawDescription: Finding a parent key from a dict given an intermediate key using python


code:
def func1():
    def func2():
        print("Hello")
    return func2

innerfunc = func1()
innerfunc()

rawDescription: Call a function defined in another function


code:
for thing in things:
    for otherthing in things:
        add_edge(thing, otherthing)

rawDescription: Follow-up on iterating over a graph using XML minidom


code: np.where((vals == (0, 1)).all(axis=1))

rawDescription: Find matching rows in 2 dimensional numpy array


code:
import _winreg as winreg

INTERNET_SETTINGS = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
    r'Software\Microsoft\Windows\CurrentVersion\Internet Settings',
    0, winreg.KEY_ALL_ACCESS)

def set_key(name, value):
    _, reg_type = winreg.QueryValueEx(INTERNET_SETTINGS, name)
    winreg.SetValueEx(INTERNET_SETTINGS, name, 0, reg_type, value)

set_key('ProxyEnable', 1)
set_key('ProxyOverride', u'*.local;<local>')  # Bypass the proxy for localhost
set_key('ProxyServer', u'X.X.X.X:8080')

rawDescription: Change browser proxy settings from Python?


code:
def rpn_to_ast(rpn):
    stack = []
    for n in rpn:
        num_args = (2 if n.token.ttype == "operator-infix" else
                    1 if n.token.ttype.startswith('operator') else
                    n.num_args if n.token.ttype == 'function' else 0)
        n.args = [stack.pop() for _ in range(num_args)][::-1]
        stack.append(n)
    return stack[0]

rawDescription: parsing excel style formula

description: Parsing excel style formula


code:
class EmailDomainFilterRegistrationForm(RegistrationForm):

    def clean_email(self):
        submitted_data = self.cleaned_data['email']

        if not ALLOWED_DOMAINS: # If we allow any domain
            return submitted_data

        domain = submitted_data.split('@')[1]
        logger.debug(domain)
        if domain not in ALLOWED_DOMAINS:
            raise forms.ValidationError(
                u'You must register using an email address with a valid '
                'domain ({}). You can change your email address later on.'
                .format(', '.join(self.allowed_domains))
            )
        return submitted_data

rawDescription: django-registration email domain whitelist

description: Django-registration email domain whitelist


rawDescription: Apply custom function on text on a pandas dataframe rather than iterating individual element


code:
{'George Bush': 'George W. Bush',
 'Luc van den Bergen': 'Luc Bergen',
 'Billy Idol': 'Billy Idol',
 'J. Payne': 'John Payne',
 'M Stuart': 'M. Stuart'}

rawDescription: Given two python lists of same length. How to return the best matches of similar values?


rawDescription: Django: How to get related objects of a queryset?


code:
for row in reversed(list(reader1)):
    highNAS, lowNAS = row['High'], row['Low']
    dateNAS = row['Date']
    averageNAS[dateNAS] = (float(highNAS) + float(lowNAS)) / 2 # Insertion

rawDescription: Finding the highest value

description: Finding the highest value


code:
def printName():
   print("Enter your name: ")
   n=input()
   if n=='Python':
     ...

rawDescription: I am getting a NameError: name 'n' is not defined


code:
strs
re.findall(r"\w+:\s\w+",strs)

rawDescription: Extract categories from text using regular expression


code:
import re
from functools import partial

def _hexrepl(match):
    return chr(int(match.group(1), 16))
unescape = partial(re.compile(r'#([0-9A-F]{2})').sub, _hexrepl)

def pdfnames(inputtext):
    for match in Name.finditer(inputtext):
        yield unescape(match.group(0))

rawDescription: Translating regex match groups

description: Translating regex match groups


code:
L = [['not', 'D'], ['not', 'C'], 'B', 'A']
L.sort(key=lambda x:(isinstance(x,str) and x) or x[1])
L

rawDescription: Sort alphabetically a list with strings and lists of strings in Python


rawDescription: How to keep certain entities as one word using nltk tokenize in python?

description: Keep certain entities as one word using nltk tokenize in python