code:
def main():
    phrase = input("Enter a phrase: ")
    print("Number of characters: ",len(phrase))
    count = wordCount(phrase)
    average(phrase,count)
    freqWords(phrase)

def wordCount(phrase):
    words = phrase.split()
    wordCount = len(words)
    print("Number of words: ",wordCount)
    return wordCount

def average(phrase, wordCount):
    avg = len(phrase)/wordCount
    print("The average word length: %.01f" % avg)

def freqWords(phrase):
    freqLetter = phrase[0]
    max = phrase.count(phrase[0])
    for char in phrase:
        if char is not " ":
            if phrase.count(char) > max:
                freqLetter = char
                max = phrase.count(char)

    print("The most frequent letter: ", freqLetter)

main()

rawDescription: Need help assigning parameters to my definitions


code:
with open("filename", 'r') as file:
    current_line = next(file)  # Get 1st line, advance iterator to 2nd line
    for next_line in file:
        do_something(current_line, next_line)
        current_line = next_line

rawDescription: Read lines from a file as a shift register with two cells in Python


code:
import itertools
from pprint import pprint
data = [
    ['07F', '05F', '10F', '06F'],
    ['05T', '05F', '02T'],
    ['03T', '03F']
    ]

# Create a list of the lists of pair-wise combinations
data = [list(itertools.combinations(x,2)) for x in data]

pprint(data)

rawDescription: Creating list that would contain pairs of another list?


code:
tmr = QtCore.QTimer()
tmr.setSingleShot(True)
tmr.timeout.connect(self.SomeFunction)
tmr.start(10000)

rawDescription: PyQt: Is there any Time limit widget?

description: PyQt: Is there any Time limit widget


code:
from functools import reduce
class DerivationRegistry(type):
    def __init__(cls,name,bases,cls_dict):
        type.__init__(cls,name,bases,cls_dict)
        cls._subclasses = set()
        for base in bases:
            if isinstance(base,DerivationRegistry):
                base._subclasses.add(cls)

    def getSubclasses(cls):
        return reduce( set.union,
                       ( succ.getSubclasses() for succ  in cls._subclasses if isinstance(succ,DerivationRegistry)),
                       cls._subclasses)

class Base(object):
    __metaclass__ = DerivationRegistry

class Cls1(object):
    pass

class Cls2(Base):
    pass

class Cls3(Cls2,Cls1):
    pass

class Cls4(Cls3):
    pass

print(Base.getSubclasses())

rawDescription: How can I discover classes in a specific package in python?

description: Discover classes in a specific package in python


code:
#!/usr/bin/env python
import os
import time
import win32com.client
import logging

old_mappings = [
    r'\\192.168.1.100\old',
    ]
new_mapping = r'\\192.168.1.200\new'
LOG_FILENAME = 'status.log'

def main():
    """
    Check to see if Z: is mapped to the old server; if so remove it and
    map the Z: to the new server.

    Then, repeatedly monitor the Z: mapping. If the Z: drive exists,
    report to status.log that we are working. Otherwise, re-map it and
    report errors to the log.
    """
    setupLogging()
    replaceMapping()
    monitorMapping()

def replaceMapping():
    if removeMapping():
        createNewMapping()

def setupLogging():
    format = os.environ['COMPUTERNAME'] + " - %(asctime)s - %(message)s"
    logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG, format=format)

def getCredentials():
    """
    Return one of three things:
    - an empty tuple
    - a tuple containing just a username (if a password is not required)
    - a tuple containing username and password
    """
    return ('someuser', 'somepass')

def createNewMapping():
    network = win32com.client.Dispatch('WScript.Network')
    params = (
        'Z:', # drive letter
        new_mapping, # UNC path
        True, # update profile
        )
    params += getCredentials()
    try:
        network.MapNetworkDrive(*params)
        msg = '{params} - Drive has been mapped'
        logging.getLogger().info(msg.format(**vars()))
    except Exception as e:
        msg = 'error mapping {params}'
        logging.getLogger().exception(msg.format(**vars()))

def monitorMapping():
    while True:
        # only check once a minute
        time.sleep(60)
        checkMapping()

def checkMapping():
    if getDriveMappings()['Z:'] == new_mapping:
        msg = 'Drive is still mapped'
        logging.getLogger().info(msg.format(**vars()))
    else:
        replaceMapping()

# From Python 2.6.4 docs
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

def getDriveMappings():
    """
    Return a dictionary of drive letter to UNC paths as mapped on the
    system.
    """
    network = win32com.client.Dispatch('WScript.Network')
    # http://msdn.microsoft.com/en-us/library/t9zt39at%28VS.85%29.aspx
    drives = network.EnumNetworkDrives()
    # EnumNetworkDrives returns an even-length array of drive/unc pairs.
    # Use grouper to convert this to a dictionary.
    result = dict(grouper(2, drives))
    # Potentially several UNC paths will be connected but not assigned
    # to any drive letter. Since only the last will be in the
    # dictionary, remove it.
    if '' in result: del result['']
    return result

def getUNCForDrive(drive):
    """
    Get the UNC path for a mapped drive.
    Throws a KeyError if no mapping exists.
    """
    return getDriveMappings()[drive.upper()]

def removeMapping():
    """
    Remove the old drive mapping. If it is removed, or was not present,
    return True.
    Otherwise, return False or None.
    """
    mapped_drives = getDriveMappings()
    drive_letter = 'Z:'
    if not drive_letter in mapped_drives:
        return True
    if mapped_drives[drive_letter] in old_mappings:
        network = win32com.client.Dispatch('WScript.Network')
        force = True
        update_profile = True
        network.RemoveNetworkDrive(drive_letter, force, update_profile)
        return True
    # return None

if __name__ == '__main__':
    main()

rawDescription: Python - Check network map

description: Python - Check network map


code:
def process_tree( best_score, node=root ):

    if not node:
        return ["NaN",False]

    node_score = node.evaluate_score()
    if node_score == best_score:
        return [best_score, True]

    score_list = []
    score_list.append(node_score)
    for child in node.children:

        child_score = process_tree(best_score,child)
        if child_score[1]:
            return child_score
        else:
            score_list.append(child_score[0])

    #when no score is equal to the best score
    return [max(score_list),False]

rawDescription: How to use a var to break from all recursive calls?

description: Use a var to break from all recursive calls


code:
def ping(request):
        r = { 'response': 'OK', 'data': 'ping' }
        response = HttpResponse("['ok']", content_type="application/json")
        response['Access-Control-Allow-Origin'] = '*'
        response['Access-Control-Allow-Methods'] = 'GET'

        return response

rawDescription: Django @csrf_exempt decorator not working


code: e = ttk.Entry(master, ..., justify='center')

rawDescription: python ttk.Entry how to center the input

description: Python ttk.Entry how to center the input


code: from sys import argv

rawDescription: What do you call the elements of a module?


code:
def plt_configure(xlabel='', ylabel='', legend=False):
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    if legend:
        if isinstance(legend, dict):
            plt.legend(**legend)
        else:
            plt.legend()

rawDescription: Python & Matplotlib: How to pass dict to functions?


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import random

matplotlib.style.use('ggplot')

taste = ['Sweet','Spicy','Sour','Bitter']
store = ['Asian','Italian','American','Greek','Mexican']

df1 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df2 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df3 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df4 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df5 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df6 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df7 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df8 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df9 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df10 = pd.DataFrame({'Taste':[random.choice(taste) for x in range(10)],
                   'Store':[random.choice(store) for x in range(10)],
                   'Sold':1000+100*np.random.rand(10)})

df1['Year'] = '2010'
df1['City'] = 'MIA'

df2['Year'] = '2011'
df2['City'] = 'MIA'

df3['Year'] = '2012'
df3['City'] = 'MIA'

df4['Year'] = '2010'
df4['City'] = 'ATL'

df5['Year'] = '2011'
df5['City'] = 'ATL'

df6['Year'] = '2012'
df6['City'] = 'ATL'

df7['Year'] = '2013'
df7['City'] = 'ATL'

df8['Year'] = '2014'
df8['City'] = 'ATL'

df9['Year'] = '2013'
df9['City'] = 'CHI'

df10['Year'] = '2014'
df10['City'] = 'CHI'

DF = pd.concat([df1,df2,df3,df4,df5,df6,df7,df8,df9,df10])

DFG = DF.groupby(['Taste', 'Year', 'City'])
DFGSum = DFG.sum().unstack(['Year','City']).sum(axis=1,level=['City','Year'])
#DFGSum is a multilevel DataFrame

import itertools
color_cycle = itertools.cycle( plt.rcParams['axes.color_cycle']  )

plot_colors = [] #Array for a squenece of colors to be plotted

for city in DFGSum.columns.get_level_values('City').unique():
  set_color = color_cycle.next() #Set the color for the city
  for year in DFGSum[city].columns.get_level_values('Year').unique():
    plot_colors.append(set_color)
    #For each unqiue city, all the yearly data belonging to that city will have the same color

DFGSum.plot(kind='bar',color=plot_colors)
# The color pramater of the plot function allows a list of colors sequences to be specified

rawDescription: Plotting multiindex DataFrame bar plot where color is determined by category


code:
class Author(object):
    def __init__(self, id, name, age):
        self._id = id
        self._name = name
        self.age = age      # ages tend to change, so mutable

    id = property(lambda self: self._id)
    name = property(lambda self: self._name)

    def __eq__(self, other):
        return self.id==other.id\
               and self.name==other.name

    def __hash__(self):
        return hash(('id', self.id,
                     'name', self.name))

rawDescription: Explanation needed regarding explanation of hashable objects


code:
sql = ('INSERT INTO table ({}) VALUES ({})'.format(','.join(listOfColumns),
     ','.join('?'*len(listOfColumns))))
cur.execute(sql, listOfValues)

rawDescription: How to programatically set the amount of parameters in python sqlite

description: Programatically set the amount of parameters in python sqlite


code:
import os,sys
sys.stdout = open("./data.out","w")
os.dup2(sys.stdout.fileno(), 1)
os.execv('/usr/bin/python', ['python', './script.py'])

rawDescription: Python get script output with now only the pid of file


code:
from ctypes import c_int

id_type_et = c_int
ID_UNUSED = id_type_et(0)
ID_DEVICE_NAME = id_type_et(1)
ID_SCSI = id_type_et(2)
ID_DEVICE_NUM = id_type_et(3)

rawDescription: How can I convert a C++ enum to ctypes.Structure using Python 2.7.2?

description: Convert a C++ enum to ctypes.Structure using Python 2.7.2


code: label1 = Tkinter.Label( frame, text = '1.0' ).grid( row = 4, column = 5 )

rawDescription: Why is there NoneType when should be Label?


code:
from django.http import HttpResponseRedirect

def myview(request, params):
  # get the URL from the DB...
  #....
  return HttpResponseRedirect(target_url)

rawDescription: django - urlshortener app

description: Django - urlshortener app


code:
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
xlApp = xlApp.Application

rawDescription: Calling an Excel user defined function from Python always returns None


code:
import os

r, w = os.pipe()
r, w = os.fdopen(r, 'rb'), os.fdopen(w, 'wb')

rawDescription: Is there a way to make StringIO reading blocking


code:
for x in boys:
    z = dict(zip(keys,x))
    boyz.append(z)

rawDescription: Making a list of dictionaries from a list of tuples


code:
import socket
from celery.task import task

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('localhost', 9999))

@task
def echo(arg):
    s.send(arg)
    return s.recv()

rawDescription: Shared XMPP connection between Celery workers


code:
a = 1
b = 1

a is b # not guaranteed to be true

rawDescription: Is the data in xlsx cells string?

description: Is the data in xlsx cells string


rawDescription: matplotlib custom colorbar unintended discrete colors

description: Matplotlib custom colorbar unintended discrete colors


rawDescription: How to get a list from query in sqlalchemy

description: Get a list from query in sqlalchemy


code:
figure = Figure()
canvas = FigureCanvasWxAgg(self, wx.ID_ANY, figure)
axes = figure.add_subplot(111, projection="3d")
plotSizer = wx.BoxSizer(wx.VERTICAL)
plotSizer.Add(self, canvas, proportion=1, flag=wx.EXPAND)
plotPanel = wx.Panel(self, wx.ID_ANY, size=DEFAULT_PLOT_SIZE)
plotPanel.SetSizer(plotSizer)

rawDescription: How to use mouse to rotate matplotlib 3D plots in wxPython?

description: Use mouse to rotate matplotlib 3D plots in wxPython


code:
with open('A') as file1, open('B') as file2:
     L = file1.read().splitlines()
     L.extend(file2.read().splitlines())
L.sort(key=lambda line: int(line.partition(' ')[0])) # sort by 1st column
print("\n".join(L)) # print result

rawDescription: Losing lines from two text files over iteration


code: myWidget.place(rely=1.0, relx=1.0, x=0, y=0, anchor=SE)

rawDescription: Tkinter; Put a widget in the lower-right corner using place()


rawDescription: BeautifulSoup4: how to find a HTML element whose text contains an accented character?


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

from os import pardir, rename, listdir, getcwd
from os.path import join

class MyOpener(urllib.FancyURLopener):
     version = 'QuickTime/7.6.2 (verqt=7.6.2;cpu=IA32;so=Mac 10.5.8)'

# This line tells urllib.urlretrieve and urllib.urlopen to use your MyOpener
# instead of the default urllib.FancyOpener
urllib._urlopener = MyOpener()

def main():
    # lots of stuff
    for title, url in downloads.iteritems():
        fpath = join(data_dir, title.strip().replace('\t',"").replace(" ", "_"))
        fpath += ".mov"
        urllib.urlretrieve(url, fpath)

rawDescription: How to set useragent as QuickTime in Python script?

description: Set useragent as QuickTime in Python script


rawDescription: Make lists between two unique charecters [python]


rawDescription: Datetime collection needs to parse out date and only keep time


code:
pipe = subprocess.Popen(
     ["metaflac", "--show-tag=title", filename], stdout=subprocess.PIPE)
title, error = pipe.communicate()

rawDescription: Python: AttributeError: 'int' object has no attribute 'replace'


code:
with tempfile.TemporaryDirectory() as dir:
   do_stuff_with(dir)

rawDescription: Python: differences between tempfile.mkdtemp and tempfile.TemporaryDirectory


code:
def delete_eof(fin, fout):
    BUFSIZE = 2**15
    EOFCHAR = chr(26)
    data = fin.read(BUFSIZE)
    while data:
        fout.write(data.translate(None, EOFCHAR))
        data = fin.read(BUFSIZE)

import sys
ipath = sys.argv[1]
opath = ipath + ".new"
with open(ipath, "rb") as fin, open(opath, "wb") as fout:
    delete_eof(fin, fout)

rawDescription: How to process huge text files that contain EOF / Ctrl-Z characters using Python on Windows?

description: Process huge text files that contain EOF / Ctrl-Z characters using Python on Windows


code:
class Mixin(object):
    def get_fields(self):
        return[(field.name, field.value_to_string(self)) for field in self.__class__._meta.fields]

class A(models.Model, Mixin):
    ...

class B(models.Model, Mixin):
    ...

rawDescription: Making a function available to all models


code:
class Preprocessor(object):
    # hard code the stopwords for now
    stopwords = nltk.corpus.stopwords.words()

    def __init__(self, stemmer_cls, vectorizer_cls):
        self.stemmer_cls = stemmer_cls
        self.vectorizer_cls = vectorizer_cls

    def _build_analyzer(self, stemmer, vectorizer_cls):
        # analyzer tokenizes and lowercases
        analyzer = super(vectorizer_cls, self).build_analyzer()
        return lambda doc: (stemmer.stem(w) for w in analyzer(doc))

    def fit(self, **kwargs):
        analyzer = self._build_analyzer(self.stemmer_cls(), vectorizer_cls)
        self.vectorizer_cls = vectorizer_cls(stopwords=stopwords,
                                         analyzer=analyzer,
                                         decode_error='ignore')

        return self.vectorizer_cls.fit(kwargs)

    def transform(self, **kwargs):
        return self.vectorizer_cls.transform(kwargs)

    def fit_transform(self, **kwargs):
        return self.vectorizer_cls.fit_transform(kwargs)

rawDescription: Override method for a collection of classes implementing an interface


code:
import os, sys, shutil, re

def readFile():
    from queue import PriorityQueue
    str1 = 'ID_IS'
    str2 = 'NUM_IS'
    q = PriorityQueue()
    #try block will execute if the text file is found
    try:
        fileName= open("Real_format.txt",'r')
        for line in fileName:
                # from the sample text, the split is pointless but harmless
                for string in line.strip().split(','):
                    if string.upper().startswith(str1): #if str1 is found
                        q.put(string[-4:]) #store it in PQ
                    elif string.upper().startswith(str2):#if str2 is found
                        q.put(string[-8:]) #store it in PQ

        fileName.close() #close the file after reading
        print("Displaying Sorted Data")
        #print("ID TYPE       Type")
        while not q.empty():
            print(q.get())

            #catch block will execute if no text file is found
    except IOError:
                print("Error: FileNotFoundException")
                return

readFile()

rawDescription: Else statement did not get executed

description: Else statement did not get executed


code:
import sys
import os

PYVER = sys.version_info
PATH = os.path.join(os.environ["HOME"], ".local", "lib", "python%d.%d" % (PYVER.major, PYVER.minor))

sys.path.insert(0, PATH)

rawDescription: Load user python package in preference to system


code:
def start_requests(self):
    for url in self.start_urls:
        yield scrapy.Request(url, callback=self.parse_details, headers={"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 5_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B179 Safari/7534.48.3"})

rawDescription: How can I download json Response with Scrapy?

description: Download json Response with Scrapy


rawDescription: How to append/concat a number in re.sub

description: Append/concat a number in re.sub


code:
import json
import urllib2
data = json.loads(urllib2.urlopen(url).read())

rawDescription: HTTPS GET request & read JSON reply

description: HTTPS GET request & read JSON reply


code: (foobar(x) for x in S)

rawDescription: How to apply a function to a collection of elements

description: Apply a function to a collection of elements


rawDescription: find key with a value among multiple value

description: Find key with a value among multiple value


code: [Tuple_list[i-1] for i in order]

rawDescription: Python re-ordering a list of tuples by pre-defined sequence


code:
query =  {'fowl': [{'cateogry': 'Space'}, {'cateogry': 'Movie'}, {'cateogry': 'six'}], u'Year of the Monkey': {'score': 40, 'match': [{'category': u'Movie'}, {'category': 'heaven'}, {'category': 'released'}]}}
query['fowl'] # 'fowl'
[d['cateogry'] for d in query['fowl']] # 'fowl' categories
[d['cateogry'] for d in query['fowl']][0] # 'fowl' 'Space' category

rawDescription: Extracting value from nested dictionary

description: Extracting value from nested dictionary


code:
import convrt

ratings = convrt.RottenTomatoesRating("Movie Title Here")
tomatometer = ratings.tomatometer
audience = ratings.audience

rawDescription: How to return a value (tuple) using the following Class script?

description: Return a value (tuple) using the following Class script


code:
with open('my.csv', 'r') as my_file:
    lines = my_file.readlines()
if all((line.isspace() for line in lines)):
    print("Empty file!")
else:
    reader = csv.reader(lines)
    # do stuff

rawDescription: check CSV file contains no characters but only empty space and tab

description: Check CSV file contains no characters but only empty space and tab


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

primary_regex = "set<array<(char|float|int), .*>>"
struct_regex = (
    "set<array<struct{((int|char|float)\s+.*,)*\s+((int|char|float) .*)}, .*>>"
)

def extract(define_str):
    m = re.match(primary_regex, define_str)
    result = {
        'base_type': 'array',
    }

    if m is None:
        m = re.match(struct_regex, define_str)

        if m is None:
            # Invalid define_str, return None
            return None

        # Result of m.groups() is a tuple alike
        # ('int foo,', 'int', 'char bar', 'char')
        sub_type = m.groups()[1::2]
        result['type'] = 'struct'
        result['sub_type'] = sub_type
    else:
        primary_type = m.group(1)
        result['type'] = primary_type

    return result

rawDescription: Python regex to split string by different brackets


code:
li = {}
for j in range(10):
    li[j] = []

rawDescription: Python: incorporating index from for loop as part of a list name


code:
import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()

rawDescription: How to rotate x-axis label in Pandas barplot

description: Rotate x-axis label in Pandas barplot


code:
session.query(User).join(User.addresses) \
                   .filter(User.name == "jack",
                           Address.email.like("%@google.com")) \
                   .options(contains_eager(User.addresses))

rawDescription: Selectively loading backrefs in SQLAlchemy


code:
from itertools import product
list(product([1, 2], repeat=2))

rawDescription: Get all combinations of list elements not ignoring position in Python


code:
import tornado.httpserver
import tornado.ioloop
import tornado.netutil
import tornado.web

app = tornado.web.Application()
sockets = tornado.netutil.bind_sockets(0, '')
server = tornado.httpserver.HTTPServer(app)
server.add_sockets(sockets)

for s in sockets:
    print('Listening on %s, port %d' % s.getsockname()[:2])
tornado.ioloop.IOLoop.instance().start()

rawDescription: Bind Tornado Webserver on random port

description: Bind Tornado Webserver on random port


code:
def features_deepcopy (f):
    return [cv2.KeyPoint(x = k.pt[0], y = k.pt[1],
            _size = k.size, _angle = k.angle,
            _response = k.response, _octave = k.octave,
            _class_id = k.class_id) for k in f]

f2 = features_deepcopy(f1)

rawDescription: Deep copy of an opencv2 ORB data structure in Python


code:
dict1 = {"Harry": 18, "Mary": 27, "Tim": 7}
dict2 = {"Harry": 22, "Mary": 27, "Frank": 40}
dict1.update(dict2)
dict1

rawDescription: Combining two lists of objects based on an attribute


code:
Example = namedtuple('Example', ['list', 'tuple', 'property'])
e.list
e.tuple
e.property

rawDescription: Reasons to rename property to _property

description: Reasons to rename property to _property


code:
with os.popen('fusermount -V') as p:
    versiontext = p.read()
#do something with version text

rawDescription: Get fuse version installed on current OS


code:
req = mechanize.Request("http://www.google.com")
req.set_proxy("localhost:8888","http")
mechanize.urlopen(req)

rawDescription: Python's mechanize proxy support

description: Python's mechanize proxy support


code:
for result in events:
    my_instance = SomeClass(result[0], result[1])
    # Do whatever you want to do with the instances, which looks like
    # it may be appending to data
    data.append(my_instance) # Or data.append(SomeClass(result[0], result[1]))

rawDescription: Create an instance of a class from SQL query


code:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', nargs='+')
parser.parse_args('-i input1.txt input2.txt input3.txt'.split())

rawDescription: Python script accepting optional multiple inputs


code:
import subprocess

cmd = "xterm -hold -e scipt.sh"
# no block, it start a sub process.
p = subprocess.Popen(cmd , shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# and you can block util the cmd execute finish
p.wait()
# or stdout, stderr = p.communicate()

rawDescription: Running a bash script from Python

description: Running a bash script from Python


rawDescription: Python read() automatically converts hex to char?


code:
import subprocess
op = subprocess.check_output(["ls","-lrt"])
print(op)

rawDescription: Python: How to store output of ls -lrt

description: Python: How to store output of ls -lrt


code:
TESTING_BROWSERS = "[{'platform': 'Windows 7', 'browserName': 'firefox', 'version': '24.0'}, \
{'platform': 'OS X 10.10', 'browserName': 'chrome', 'version': '45.0'}, \
{'platform': 'Windows XP', 'browserName': 'chrome', 'version': '40.0'}, \
{'platform': 'OS X 10.10', 'browserName': 'safari', 'version': '8.0'},  ]"

import ast
my_dict = ast.literal_eval(TESTING_BROWSERS)

rawDescription: Reading a python dictionary from an environment variable


code:
import multiprocessing
p = multiprocessing.Pool()
a = p.apply_async(None) # Replace None with the function to execute.
help(a.__class__)

rawDescription: Make a blocking function timeout in Python


code: l = [item for item in my_list if not do_I_suppress(item)]

rawDescription: Explore all object of a list and delete some of them


code:
from unidecode import unidecode
unidecode(u'ıöüç')

rawDescription: Python and character normalization

description: Python and character normalization


code:
def recursive_dict_sum_helper(v1, v2):
    # "add" two values: if they can be added with '+', then do so,
    # otherwise expect dictionaries and treat them appropriately.
    try: return v1 + v2
    except: return recursive_dict_sum(v1, v2)

def recursive_dict_sum(d1, d2):
    # Recursively produce the new key-value pair for each
    # original key-value pair, and make a dict with the results.
    return dict(
        (k, recursive_dict_sum_helper(v, d2[k]))
        for (k, v) in d1.items()
    )

mainDict = recursive_dict_sum(mainDict, b)

rawDescription: How to add elements from one dictionary into other? Python

description: Add elements from one dictionary into other? Python


code:
def quiz(question,answer, score):
    import time
    a = raw_input(question)
    if a.lower() == answer.lower():
        score = score + 1
        if score == 1:
            print("correct! So far your score is an awesome " + str(score) + "     point")
            time.sleep(0.5)
        else:
            print("correct! So far your score is an awesome " + str(score) + " points")
            time.sleep(0.5)
    else:
        print("wrong, dumbass! The correct answer was " + answer + "! So far your score is an abysmal " + str(score) + " points")
        time.sleep(0.5)

    return score

actual_score = 0
new_score = quiz("what is my favourite colour? ", "green", actual_score)
new_score = quiz("What is my favourite game? ", "cards against humanity", new_score)
new_score = quiz("Who's better: Gandalf or Dumbledore? ", "Gandalf", new_score)

rawDescription: My quiz() method won't update its score, how can i fix this?


code:
def longestrun(myList):
    prev = None
    size = 0
    max_size = 0
    curr_pos = 0
    max_pos = 0

    for (index, i) in enumerate(myList):
        if i == prev:
            size += 1
            if size > max_size:
                max_size = size
                max_pos = curr_pos
        else:
            size = 0
            curr_pos = index
        prev = i
    return max_pos

rawDescription: Function that finds the zero-based index of the longest run in a string in Python


code:
import sys
class MyNameSpace(object):
    def __init__(self,ns):
        self.ns = ns
    def __enter__(self):
        globals().update(self.ns)
    def __exit__(self, exc_type,exc_value,traceback):
        self.ns.update(sys._getframe(1).f_locals)

my_dict = {'a':3, 'b':2}
with MyNameSpace(my_dict) as ns:
    print(a) # Should print 3
    x = 5 # When the block finishes, my_dict['x'] should now be 5

print(my_dict['x'])

rawDescription: Getting the block of commands that are to be executed in the with statement


code:
def __init__(self):
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    for name in dir(self):
        if not name.startswith("_"):
            p = subparsers.add_parser(name)
            method = getattr(self, name)
            argnames = inspect.getargspec(method).args[1:]
            for argname in argnames:
                p.add_argument(argname)
            p.set_defaults(func=method, argnames=argnames)
    self.args = parser.parse_args()

def __call__(self):
    a = self.args
    callargs = [getattr(a, name) for name in a.argnames]
    return self.args.func(*callargs)

rawDescription: Argparse functions Python

description: Argparse functions Python


rawDescription: PIL fromarray function is giving wierd colormap


code:
import requests
from bs4 import BeautifulSoup

r = requests.get("http://www.elitebetkenya.com/coupon.php")
soup = BeautifulSoup(r.content, "html.parser")

for league in soup.find_all("tr", class_="league"):
    # get basic league and fixture data
    league_name = league.get_text(strip=True)

    fixture = league.find_next_sibling("tr", class_="fixture")
    home = fixture.find("span", class_="home").get_text(strip=True)
    away = fixture.find("span", class_="away").get_text(strip=True)

    date = fixture.br.find_next_sibling(text=True).strip()

    print(league_name, home, away, date)

    # iterate over odds rows
    for odd in fixture.find_next_siblings("tr"):
        # stop once the next league is met
        if "league" in odd.get("class", []):
            break

        # skipping header rows
        if not odd.td.get_text(strip=True):
            continue

        cells = [td.get_text(strip=True) for td in odd.find_all("td")]
        print(cells)

rawDescription: Beautiful Soup scraping poorly built table


code:
import sys

print(n, file=sys.stderr)

rawDescription: Is there the redirect operator >> in Python 3?


code:
[easy_install]

# i don't like having zipped files.
zip_ok = 0

rawDescription: How do I forbid easy_install from zipping eggs?

description: Forbid easy_install from zipping eggs


code:
# plot projection of density onto z-axis
plotdat = np.sum(density, axis=2)
plotdat = plotdat / np.max(plotdat)
plotx, ploty = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotx, ploty, plotdat, offset=-4, zdir='z')

#This is new
#plot projection of density onto y-axis
plotdat = np.sum(density, axis=1) #summing up density along y-axis
plotdat = plotdat / np.max(plotdat)
plotx, plotz = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotx, plotdat, plotz, offset=4, zdir='y')

#plot projection of density onto x-axis
plotdat = np.sum(density, axis=0) #summing up density along z-axis
plotdat = plotdat / np.max(plotdat)
ploty, plotz = np.mgrid[-4:4:100j, -4:4:100j]
ax.contour(plotdat, ploty, plotz, offset=-4, zdir='x')
#continue with your code

rawDescription: Plot contours of distribution on all three axes in 3D plot


code:
# HTTP POST variables
request.POST['section'] # => [39]
request.POST['MAINS'] # => [137]

# HTTP GET variables
request.GET['section'] # => [39]
request.GET['MAINS'] # => [137]

# HTTP POST and HTTP GET variables (Deprecated since Django 1.7)
request.REQUEST['section'] # => [39]
request.REQUEST['MAINS'] # => [137]

rawDescription: Django request get parameters

description: Django request get parameters


code:
chrDict = {}
with open('file.txt','rb') as fmaps:
    while True:
        pos = fmaps.tell()
        ln = fmaps.readline()
        if not ln:
            break
        key = ln.split()[0]
        if key not in chrDict:
            chrDict[key] = pos

rawDescription: Indexing a file using f.tell() in python


code:
pydoc_process = launch_pydoc()
browser_process = launch_browser()
browser_process.wait()
pydoc_process.terminate()

rawDescription: How do I setup a portable pydoc server that closes when portable browsers have been shut down?

description: Setup a portable pydoc server that closes when portable browsers have been shut down


code:
def function(number_of_items):
     n = number_of_items
     # do some stuff. . .
     n -= 1
     # now the variable number_of_items was changed in the enclosing scope!

rawDescription: Why is mutability determined by the type in Python?


code:
import flask
import time

app = flask.Flask(__name__)

@app.route('/yield')
def index():
    def inner():
        for x in range(100):
            time.sleep(1)
            yield '%s<br/>\n' % x
    return flask.Response(inner(), mimetype='text/html')  # text/html is required for most browsers to show the partial page immediately

app.run(debug=True)

rawDescription: How to continuously display python output in a webpage?

description: Continuously display python output in a webpage


code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import AxesGrid

# Some random data
values1 = np.random.rand(10,10)
values2 = np.random.rand(10,10)
values3 = np.random.rand(10,10)
values4 = np.random.rand(10,10)
vals = [values1,values2,values3,values4]

fig = plt.figure()

grid = AxesGrid(fig, 111,
                nrows_ncols=(2, 2),
                axes_pad=0.05,
                share_all=True,
                label_mode="L",
                cbar_location="right",
                cbar_mode="single",
                )

for val, ax in zip(vals,grid):
    im = ax.imshow(val)

grid.cbar_axes[0].colorbar(im)

for cax in grid.cbar_axes:
    cax.toggle_label(False)

plt.show()

rawDescription: Multiple Heatmap Subplots: Same Heatbar

description: Multiple Heatmap Subplots: Same Heatbar


code:
class Tag:
    def __init__(self, name, parent=None):
        self.name = name
        self.children = []
        self.has_root = True
        self.parent = parent

    def __str__(self):
        """ compose string for this tag (recursivly) """
        if not self.children:
            return self.name
        children_str = ' '.join([str(child) for child in self.children])
        if not self.parent:
            return children_str
        return '<%s>%s</%s>' % (self.name, children_str, self.name)

    @classmethod
    def from_file(cls, file):
        """ create root tag from file """
        obj = cls('root')
        columns = []
        with open(file) as in_file:
            for line in in_file:
                value, tag = line.strip().split(' ')
                obj.add_tag(tag, value)
        return obj

    def search_tag(self, tag):
        """ search for a tag in the children """
        if self.name == tag:
            return self
        for i, c in enumerate(self.children):
            if isinstance(c, Tag) and c.name == tag:
                return c
            elif isinstance(c, str):
                if c.strip() == tag.strip():
                    self.children[i] = Tag(tag, self)
                    return self.children[i]
            else:
                result = c.search_tag(tag)
                if result:
                    return result

    def add_tag(self, tag, value):
         """
         add a value, tag pair to the children

         Firstly this searches if the value is an child. If this is the
         case it moves the children to the new location

         Afterwards it searches the tag in the children. When found
         the value is added to this tag. If not a new tag object
         is created and added to this Tag. The flag has_root
         is set to False so the element can be moved later.
         """
         value_tag = self.search_tag(value)
         if value_tag and not value_tag.has_root:
             print("Found value: %s" % value)
             if value_tag.parent:
                 i = value_tag.parent.children.index(value_tag)
                 value = value_tag.parent.children.pop(i)
                 value.has_root = True
             else:
                 print("not %s" % value)

         found = self.search_tag(tag)
         if found:
             found.children.append(value)
         else:
             # no root
             tag_obj = Tag(tag, self)
             self.children.append(tag_obj)
             tag_obj.add_tag(tag, value)
             tag_obj.has_root = False

tags = Tag.from_file('final')
print(tags)

rawDescription: Python - Formatting strings

description: Python - Formatting strings


code:
cmd_args = ['osascript', '-e', 'tell application "Google Chrome" to set source to execute front window\'s active tab javascript "document.documentElement.outerHTML"']
proc = subprocess.Popen(cmd_args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
source, err = proc.communicate()

rawDescription: Python osascript using extra quotation marks


Why `0.4/2` equals to `0.2` meanwhile `0.6/3` equals to `0.19999999999999998` in python


code:
buffer = win32gui.PyMakeBuffer(255)
length = win32gui.SendMessage(control, win32con.WM_GETTEXT, 255, buffer)

rawDescription: Python: How to get the text label from another program window?


code:
from collections import OrderedDict
LINES_PER_CYCLE = 1000

with open('output.txt', 'wb') as output, open('test_2.txt', 'rb') as fin:
    fin_line = ''

    # Loop until fin reaches EOF.
    while True:
        cache = OrderedDict()

        # Fill the cache with up to LINES_PER_CYCLE entries.
        for _ in xrange(LINES_PER_CYCLE):
            fin_line = fin.readline()
            if not fin_line:
                break

            key, rest = fin_line.strip().split(' ', 1)
            cache[key] = ['', rest]

        # Loop over the file_1.txt to find tags with given id.
        with open('test_1.txt', 'rb') as fout:
            for line in fout:
                tag, _ = line.split(' ', 1)
                _, idx = tag.rsplit('_', 1)
                if idx in cache:
                    cache[idx][0] = tag

        # Write matched lines to the output file, in the same order
        # as the lines were inserted into the cache.
        for _, (tag, rest) in cache.iteritems():
            output.write('{} {}\n'.format(tag, rest))

        # If fin has reached EOF, break.
        if not fin_line:
            break

rawDescription: Match file names and replace with new name


code:
# Example to remove all root logger handlers and reconfigure. (UNTESTED)
import logging

# Remove all handlers associated with the root logger object.
for handler in logging.root.handlers[:]:
    logging.root.removeHandler(handler)

# Reconfigure logging again, this time with a file.
logging.basicConfig(filename = 'myfile.log', level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s')

rawDescription: Changing logging's 'basicConfig' which is already set


code:
var = 'insert text here'
"hello {}".format(var)

rawDescription: Calling variables in a send_email call in Python


code:
import logging
fh = logging.FileHandler('/Users/defuz/test.txt')
fh.baseFilename
fh.stream.name

rawDescription: How to get file name of logging.FileHandler in Python?

description: Get file name of logging.FileHandler in Python


code:
def skit(*lines, **kwargs):
    for line in lines:
        line(**{key: value for key, value in kwargs.iteritems()
                if key in line.func_code.co_varnames})

rawDescription: Separating **kwargs for different functions


code:
with open(ima) as file:
    file_list = f.readlines() # You will have a list with size/28=the number of digits
    # Divide file_list by size 28

rawDescription: Python: Read File and append a lot of list of 28 lines


code:
class ProjectGroupMembershipInlineForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ProjectGroupMembershipInlineForm, self).__init__(*args, **kwargs)
        self.fields['group'].queryset = Group.objects.filter(some_filtering_here=self.instance)

rawDescription: django admin inlines: get object from formfield_for_foreignkey

description: Django admin inlines: get object from formfield_for_foreignkey


code:
import unittest

def create_suite():
    test_suite = unittest.TestSuite()
    test_suite.addTest(fooTest())
    test_suite.addTest(barTest())
    return test_suite

if __name__ == '__main__':
   suite = create_suite()

   runner=unittest.TextTestRunner()
   runner.run(suite)

rawDescription: Is it possible to run all unit test?

description: Is it possible to run all unit test


code:
import os
fileToRead = os.path.join(os.path.dirname(__file__), "somefile.txt")

rawDescription: Having a relative path in a module relative to the file calling the module


code:
class equalToAllStrings(str):
    def __eq__(self, other):
        return type(other) is str
x = equalToAllStrings("a")
x == 'b'

rawDescription: How can i override the exactly equal function for a specific string in Python?

description: Override the exactly equal function for a specific string in Python


rawDescription: Change the widget of just one field in django-crispy-forms with the layout object AppendedText


code:
roles = _Money.objects.raw("""SELECT
                                  *
                              FROM
                                  _Money m
                                  INNER JOIN _Pay p
                                  ON m.date = p.date""")

rawDescription: inner join between tables no related django

description: Inner join between tables no related django


code:
import urllib2
import re
page = urllib2.urlopen("http://www.samair.ru/proxy/ip-address-01.htm").read()
re.findall('\d+\.\d+\.\d+\.\d+', page)

rawDescription: How do I use regular expressions in python to parse a web page for all IP addresses?

description: Use regular expressions in python to parse a web page for all IP addresses


code:
from django.contrib.auth.decorators import login_required

@login_required(redirect_field_name='redirect_to')
def my_view(request):
    ...

rawDescription: URL updating on login using django

description: URL updating on login using django


code:
"""
Show how to use a lasso to select a set of points and get the indices
of the selected points.  A callback is used to change the color of the
selected points

This is currently a proof-of-concept implementation (though it is
usable as is).  There will be some refinement of the API.
"""
from matplotlib.widgets import Lasso
from matplotlib.colors import colorConverter
from matplotlib.collections import RegularPolyCollection
from matplotlib import path

import matplotlib.pyplot as plt
from numpy import nonzero
from numpy.random import rand

class Datum(object):
    colorin = colorConverter.to_rgba('red')
    colorout = colorConverter.to_rgba('blue')
    def __init__(self, x, y, include=False):
        self.x = x
        self.y = y
        if include: self.color = self.colorin
        else: self.color = self.colorout

class LassoManager(object):
    def __init__(self, ax, data):
        self.axes = [ax]
        self.canvas = ax.figure.canvas
        self.data = [data]

        self.Nxy = [ len(data) ]

        facecolors = [d.color for d in data]
        self.xys = [ [(d.x, d.y) for d in data] ]
        fig = ax.figure
        self.collection = [ RegularPolyCollection(
            fig.dpi, 6, sizes=(100,),
            facecolors=facecolors,
            offsets = self.xys[0],
            transOffset = ax.transData)]

        ax.add_collection(self.collection[0])

        self.cid = self.canvas.mpl_connect('button_press_event', self.onpress)

    def callback(self, verts):

        axind = self.axes.index(self.current_axes)
        facecolors = self.collection[axind].get_facecolors()
        p = path.Path(verts)
        ind = p.contains_points(self.xys[axind])
        for i in range(len(self.xys[axind])):
            if ind[i]:
                facecolors[i] = Datum.colorin
            else:
                facecolors[i] = Datum.colorout

        self.canvas.draw_idle()
        self.canvas.widgetlock.release(self.lasso)
        del self.lasso

    def onpress(self, event):
        if self.canvas.widgetlock.locked(): return
        if event.inaxes is None: return
        self.current_axes = event.inaxes

        self.lasso = Lasso(event.inaxes, (event.xdata, event.ydata), self.callback)
        # acquire a lock on the widget drawing
        self.canvas.widgetlock(self.lasso)

    def add_axis(self, ax,  data):
        self.axes.append(ax)
        self.data.append(data)

        self.Nxy.append( len(data) )

        facecolors = [d.color for d in data]
        self.xys.append( [(d.x, d.y) for d in data] )
        fig = ax.figure
        self.collection.append( RegularPolyCollection(
            fig.dpi, 6, sizes=(100,),
            facecolors=facecolors,
            offsets = self.xys[-1],
            transOffset = ax.transData))

        ax.add_collection(self.collection[-1])

if __name__ == '__main__':

    data = [Datum(*xy) for xy in rand(100, 2)]
    data2 = [Datum(*xy) for xy in rand(100, 2)]

    ax = plt.subplot(1,2,1)
    lman = LassoManager(ax, data)
    ax2 = plt.subplot(1,2,2)
    lman.add_axis(ax2, data2)
    plt.show()

rawDescription: Getting Lasso to work correctly on subplots in matplotlib


rawDescription: python logging basic how to use

description: Python logging basic how to use


code:
logger = logging.getLogger('my-logger')
logger.propagate = False
# now if you use logger it will not log to console.

rawDescription: How to I disable and re-enable console logging in Python?


code:
b = a.astype(complex)
b
b.dtype

rawDescription: Converting np-array from float to complex


code:
def clean_high(dict_name,key_string,limit):
    '''clean all the keys to eliminate the bad values from the arrays'''
    new_dict = {}
    for key in dict_name:
        new_dict[key] = dict_name[key][dict_name[key_string]<limit]
    return new_dict

rawDescription: python: badly behaving dict inside a function- erroneous TypeError

description: Python: badly behaving dict inside a function- erroneous TypeError


code:
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, Rectangle

rect = Rectangle((-2,-2),4,2, facecolor="none", edgecolor="none")
circle = Circle((0,0),1)

plt.axes().add_artist(rect)
plt.axes().add_artist(circle)

circle.set_clip_path(rect)

plt.axis('equal')
plt.axis((-2,2,-2,2))
plt.show()

rawDescription: Clipping in Matplotlib. Why doesn't this work?


code:
ax2 = ax1.twinx()
p1 = ax2.plot(ind, total_facilities, '--bo')
p2 = ax1.bar(ind, pdb_facilities, width, color='gray',edgecolor = "none")
plt.xlim([-1,len(total_facilities)])
ax2.set_yscale('symlog')
ax1.yaxis.tick_right()
ax2.yaxis.tick_left()
plt.show()

rawDescription: Arrange line in front of bars in Matplotlib plot with double y axes


code: t = Thread(target = do_something, args = arguments + (the_queue, ))

rawDescription: Python how to initialize thread with unknown number of arguments?


code:
import sys
sys.path.insert(3, '<path_to_your_NumPy_1.10_install>')

rawDescription: How can I stop numpy_1.8 from masking numpy_1.10?

description: Stop numpy_1.8 from masking numpy_1.10


code:
class SurveyForm(forms.ModelForm):
    class Meta:
        model = Survey
        fields = ('field_one', 'field_two', ...)

    def __init__(self, *args, **kwargs):
        super(SurveyForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            if isinstance(field.widget, forms.Select):
                field.widget = forms.RadioSelect()

rawDescription: Django - use Radio Buttons instead of Select for form component


code:
import csv

def lazy(csvfile):
    with open(csvfile) as f:
        r = csv.reader(f)
        for row in r:
            yield row

rawDescription: Can csv data be made lazy?

description: Can csv data be made lazy


code:
import matplotlib.pyplot as plt
x=[1,2,3,4,5]
y=[1,2,3,4,5]
plt.plot(x,y)
plt.xticks(rotation='vertical')

fig = plt.gcf()
fig.subplots_adjust(bottom=0.2)

plt.show()

rawDescription: Python/Matplotlib - Adjusting the spacing between the edge of the plot and the x-axis


code:
import clr
clr.AddReference('System.Drawing')
clr.AddReference('System.Windows.Forms')

### importing our assembly
clr.AddReference('ClassLibrary1ForPython')

from System.Drawing import *
from System.Windows.Forms import *

from ClassLibrary1ForPython import *

class MyForm(Form):
    def __init__(self):
        # Create child controls and initialize form
        pass

### your class instantiating
classInstance = candleStim()

Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)

form = MyForm()
### setting the window title from the value of a property of your class (standard string)
form.Text = classInstance.simulationID

Application.Run(form)

rawDescription: How does Iron Python play (mean or nice) with a C# class?


code:
"""Module to log to a file."""

import Queue
import threading

_name = None
_lt = None
_q = None
_stop = False

def _run():
    while not _stop:
        txt = _q.get()
        with open(_name, 'a+') as logfile:
            logfile.write(txt)

def start(name):
    global _lt, _q, _name
    if _name:
        raise RuntimeError('Logging already initialized')
    _name = name
    _q = Queue.Queue()
    _lt = threading.Thread(target=_run)
    _lt.start()

def stop():
    global _stop
    _stop = True
    _lt.join()

def write(txt):
    _q.put(txt, block=False)

rawDescription: Python multithreading for writing log

description: Python multithreading for writing log


code:
data['Autopass(cb)%'] = data['Autopass(cb)'] / data['TotalCB'] * 100
data['Qd(cb)%'] = data['Qd(cb)'] / data['TotalCB'] * 100

rawDescription: Add calculated column to a pandas pivot table


rawDescription: pandas - groupby and select variable amount of random values according to column

description: Pandas - groupby and select variable amount of random values according to column


code:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 *y1

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

rawDescription: Adding a y-axis label to secondary y-axis in matplotlib


rawDescription: Get cell color from .xlsx

description: Get cell color from .xlsx


rawDescription: Reading from files in python

description: Reading from files in python


code:
import os, os.path, re

path = "/Users/mypath/testData"
myfiles = os.listdir(path)
# its much faster if you compile your regexes before you
# actually use them in a loop
REGEXES = [(re.compile(r'dog'), 'cat'),
           (re.compile(r'123'), '789')]
for f in myfiles:
    # split the filename and file extension for use in
    # renaming the output file
    file_name, file_extension = os.path.splitext(f)
    generated_output_file = file_name + "_regex" + file_extension

    # As l4mpi said ... if odt is zipped, you'd need to unzip it first
    # re.search is slower than a simple if statement
    if file_extension in ('.txt', '.doc', '.odt', '.htm', '.html'):

        # Declare input and output files, open them,
        # and start working on each line.
        input_file = os.path.join(path, f)
        output_file = os.path.join(path, generated_output_file)

        with open(input_file, "r") as fi, open(output_file, "w") as fo:
            for line in fi:
                for search, replace in REGEXES:
                    line = search.sub(replace, line)
                fo.write(line)
        # both the input and output files are closed automatically
        # after the with statement closes

rawDescription: multiple regex substitution in multiple files using python

description: Multiple regex substitution in multiple files using python


code:
def find_recursive(needle, haystack):
    for index, item in enumerate(haystack):
        if not isinstance(item, str):
            try:
                path = find_recursive(needle, item)
                if path is not None:
                    return (index, ) + path
            except TypeError:
                pass
        if needle == item:
            return index,
    return None

rawDescription: Index of item in a list of lists of lists (Python)


rawDescription: Using a second app in Django

description: Using a second app in Django


code:
m, m1, m2 = 10, 5, 7

# tag each index with equal probabilities to True & False
# note: p = m1 / ( m1 + m2 ) can make more sense depending
# on desired distribution
tag = np.random.binomial(n=1, p=.5, size=m) == 1

# assign True indices to idx1 and False indices to index 2
idx = np.array( range( m ) )
idx1, idx2 = idx[ tag ], idx[ np.logical_not( tag ) ]

# sample from idx1 and idx2
i1, i2 = np.random.choice( idx1, size=m1 ), np.random.choice( idx2, size=m2 )

rawDescription: Create two set of mutually exclusive random samples in python


code:
import os
import StringIO

from google.appengine.api import conversion
from google.appengine.api import files
from google.appengine.ext import blobstore
from google.appengine.ext import webapp
from google.appengine.ext.webapp import blobstore_handlers

import jinja2

template_dir = os.path.join(os.path.dirname(__file__), 'templates')

jinja2_env = jinja2.Environment(
    loader=jinja2.FileSystemLoader(template_dir))

class MainHandler(webapp.RequestHandler):
    def get(self):
        tmpl = jinja2_env.get_template('index.jinja2')
        self.response.out.write(tmpl.render())

class PostHandler(blobstore_handlers.BlobstoreDownloadHandler):
    def post(self):
        data = self.request.get('file')
        asset = conversion.Asset('text/plain', data, 'test.txt')
        conversion_obj = conversion.Conversion(asset, 'application/pdf')
        result = conversion.convert(conversion_obj)
        buf = StringIO.StringIO()
        if result.assets:
            for asset in result.assets:
                buf.write(asset.data)
        else:
            raise Exception('Conversion failed.')
        u_file = files.blobstore.create(mime_type='application/pdf',
                                        _blobinfo_uploaded_filename='test.pdf')
        with files.open(u_file, 'a') as f:
            f.write(buf.getvalue())
        files.finalize(u_file)
        blob_key = files.blobstore.get_blob_key(u_file)
        blob_info = blobstore.get(blob_key)
        self.send_blob(blob_info)

app = webapp.WSGIApplication([
    ('/', MainHandler),
    ('/post_file', PostHandler),
],
debug=True)

rawDescription: How to convert from text to PDF using conversion API in GAE?

description: Convert from text to PDF using conversion API in GAE


code:
def my_function(source_path, dest_path, start_text, stop_text):
    # pre-format start and end to save time in loop (for case insensitive match)
    lower_start = start_text.lower()
    lower_stop = stop_text.lower()
    # safely open input and output files
    with open(source_path, 'r') as source, open(dest_path, 'w') as dest:
        # this variable controls if we're writing to the destination file or not
        writing = False
        # go through each line of the source file
        for line in source:
            # test if it's a starting or ending line
            if line.lower().startswith(lower_start): writing = True
            elif line.lower().startswith(lower_stop): writing = False
            # write line to destination file if needed
            if writing: dest.write(line)

rawDescription: How to get all the words between two specific words from a text file and write it in a new text file using python

description: Get all the words between two specific words from a text file and write it in a new text file using python


code:
class myHandsomeReconnectingClientFactory(protocol.ReconnectingClientFactory):

    def __init_(self, hosts):
        # hosts should be a list of tuples (host, port)
        self._hosts = hosts

    def clientConnectionFailed(self, connector, reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def clientConnectionLost(self, connector, unused_reason):
        if self.continueTrying:
            self._try_next_host(connector)

    def _try_next_host(self, connector):
        # round robing of servers
        to_try = self._hosts.pop(0)
        self._hosts.append(to_try)
        connector.host, connector.port = to_try
        self.connector = connector
        self.retry()

rawDescription: Twisted: ReconnectingClientFactory connection to different servers


code:
def mark_right(answer_id):
  try:
    answer = Answer.objects.get(pk=answer_id)
  except Answer.DoesNotExist:
    raise Http404
  answer.is_right = True
  answer.save()

rawDescription: Conrtoller for "right answer"

description: Conrtoller for "right answer"


code:
date_format = xlwt.easyxf(num_format_str='dd/mm/yyyy')
time_format = xlwt.easyxf(num_format_str='hh:mm')
datetime_format = xlwt.easyxf(num_format_str='dd/mm/yyyy hh:mm')

def format(value):
    if value is None:
        return ("null",)
    if isinstance(value, datetime.datetime):
        return value, datetime_format
    if isinstance(value, datetime.date):
        return value, date_format
    if isinstance(value, datetime.time):
        return value, time_format
    return (value,)

# Create workbook
wb = xlwt.Workbook()
ws = wb.add_sheet("Sheet 1")

# Write header
headers = data[0].keys()
for column, header in enumerate(headers):
    ws.write(0, column, header)

# Write data
for row, row_data in enumerate(data, start=1):
    for column, key in enumerate(headers):
        ws.write(row, column, *format(row_data[key]))

# Save file
wb.save("test.xls")

rawDescription: Convert list of dictionnaries to EXCEL with Python


code:
import somemodule

somemodule.someclass = debug_signals(somemodule.someclass)

rawDescription: Dynamically add a decorator to class

description: Dynamically add a decorator to class


rawDescription: Combining NumPy arrays

description: Combining NumPy arrays


code:
##Continued from above
###Now as three separate arrays
x1 = mu + sigma*np.random.randn(990,1)
x2 = mu + sigma*np.random.randn(980,1)
x3 = mu + sigma*np.random.randn(1000,1)

#Stack the data
plt.figure()
plt.hist([x1,x2,x3], bins, stacked=True, normed = True)
plt.show()

rawDescription: Matplotlib, creating stacked histogram from three unequal length arrays


code:
import random

a = np.array(range(300)).reshape(10,10,3)

def crop(X):
    x = random.randint(0,3)
    y = random.randint(0,3)
    return X[x:3+x, y:3+y]

# we can loop over each component of the matrix by first splitting it
# off the last dimension:
b = [np.squeeze(x) for x in np.dsplit(a, a.shape[-1])]

# this will recreate the original matrix
c = np.dstack(b)

# so putting it together with the crop function
get_rand_matrix = [crop(np.squeeze(x)) for x in np.dsplit(a, a.shape[-1])]
desired_result = np.dstack(get_rand_matrix)

rawDescription: How do you apply a function incorporating random numbers to rows of a numpy array in python?

description: Apply a function incorporating random numbers to rows of a numpy array in python


code:
mask = stamps[((stamps.dayofweek == 6) & (stamps.hour < 17))  # Sunday before 17:00
              | (stamps.dayofweek == 5)   # All of Saturday
              | ((stamps.dayofweek == 4)  # Friday after 16:00
                 & (stamps.hour >= 16)
                 & ~((stamps.hour == 16) & (stamps.minute == 0)))]  # Exclude 16:00

stamps[~stamps.isin(mask)]

rawDescription: How do I extract a subset of a time series according to a custom interval using pandas?

description: Extract a subset of a time series according to a custom interval using pandas


code: newList = [x[: 2] + y + x[-1:] for x, y in zip(l1, l2)]

rawDescription: Concatenate a list of lists

description: Concatenate a list of lists


code:
[''.join(x) for x in itertools.product(*L1)]
[''.join(x) for x in itertools.product(*L2)]

rawDescription: Python: How to get every combination in list


code:
from twisted.internet.ssl import AcceptableCiphers

cipherListString = "KRB5-IDEA-CBC-SHA,SEED-SHA".replace(",", ":")

acceptableCiphers = AcceptableCiphers.fromOpenSSLCipherString(cipherListString)

options = CertificateOptions(..., acceptableCiphers=acceptableCiphers)

rawDescription: Twisted Python - How to create list of acceptableCiphers for CertificateOptions?


code:
# Line graph subplot
lineGraph = lineGraph.plot(xs,ys,'-')
lineGraph.set_xlabel('x')
lineGraph.set_ylabel('y')

# Bar graph subplot
barChart = barChart.bar(xs,ys,width=1.0,facecolor='g')
barChart.set_xlabel('x')
barChart.set_ylabel('y')

rawDescription: plotting 2 graph in same window using matplotlib in python

description: Plotting 2 graph in same window using matplotlib in python


code:
a = "Hello, World!"
def generate_tuples(string, n):
    return [string[i:i+n] for i in range(len(string)-n+1)]

generate_tuples(a, 3)

rawDescription: Generating all n-tuples from a string

description: Generating all n-tuples from a string


code:
import shutil
import os
from tkinter import *
import tkinter.filedialog as fdialog

class MainClass():

    def __init__(self,master):
        self.parent=master
        self.gui()

    def gui(self):
        self.Source=StringVar()
        self.Destination=StringVar()

        MySource=Entry(myGUI, textvariable=self.Source).grid(row=9, column=2)
        browse=Button(myGUI,text="Browse",command=lambda:self.Source.set(fdialog.askopenfilename(filetypes=[("JPEG File",'.jpg')]))).grid(row=9, column=3)
        MyDestination=Entry(myGUI, textvariable=self.Destination).grid(row=10, column=2)
        browse1=Button(myGUI,text="Browse",command=lambda:self.Destination.set(fdialog.askdirectory())).grid(row=10, column=3)

        label1=Label(myGUI, text='Welcome to the copy utility', fg='Blue').grid(row=0,column=2)
        label2=Label(myGUI, text='Ultimate JPG mover', fg='Black').grid(row=1,column=0)
        label3=Label(myGUI, text='(Thing\'s actually pretty useless)',   fg='Black').grid(row=2,column=0)

        button1=Button(myGUI, text="  Copy  ", command=self.copyy).grid(row=3, column=0)
        button2=Button(myGUI, text="  Move  ", command=self.movee).grid(row=5, column=0)

    def copyy(self):
        source_file=self.Source.get()
        if source_file.endswith(".jpg"):
            shutil.copy(source_file, self.Destination.get())

    def movee(self):
        source_file=self.Source.get()
        if source_file.endswith(".jpg"):
            shutil.move(source_file, self.Destination.get())

if __name__ == '__main__':
    myGUI=Tk()
    app=MainClass(myGUI)
    myGUI.geometry("400x200+100+200")
    myGUI.title('Copy dat')
    myGUI.mainloop()

rawDescription: Python 3.2 Tkinter - typed in directory to be source for file copying


code: numpy.histogram(my_values, bins=numpy.r_[-numpy.inf, my_bins, numpy.inf])

rawDescription: Numpy: use bins with infinite range

description: Numpy: use bins with infinite range


code:
import numpy as np
numBins = 10  # number of bins in each dimension
data = np.random.randn(100000, 3)  # generate 100000 3-d random data points
jointProbs, edges = np.histogramdd(data, bins=numBins)
jointProbs /= jointProbs.sum()

rawDescription: Python Joint Distribution of N Variables


code:
to_directed()
to_undirected()

rawDescription: Convert to directed graph to undirected graph in Python igraph


code:
if email not in self.emails and not email.endswith("png"):  # if not a duplicate
        self.csvwriter.writerow([page.title.encode('utf8'), page.url.encode("utf8"), email])
        self.emails.append(email)

rawDescription: How do I exclude a string from re.findall?

description: Exclude a string from re.findall


code:
from collections import defaultdict
def group_by(iterable, f):
    results = defaultdict(list)
    for x in iterable:
        results[f(x)].append(x)
    return results

rawDescription: Python equivalent to Scala groupby

description: Python equivalent to Scala groupby


rawDescription: Alembic migration to convert serial field to integer


code:
import glob

fastafiles = sorted(glob.glob("*.fasta"))

for fastafile in fastafiles:
    number = fastafile.split(".")[0]
    space_file = glob.glob(number + ".fasta *")
    with open(fastafile, "a+") as fasta:
        with open(space_file[0], "r") as fasta_space:
            fasta.write("\n")
            fasta.writelines(fasta_space.readlines())

rawDescription: how can I cat two files with a matching string in the filename?

description: Cat two files with a matching string in the filename


code:
cls = globals()[someClass]
instance = cls()
for f in cls._meta.fields:
    previous_value = getattr(instance, f)
    setattr(instance, f, previous_value + 'some new value')

rawDescription: Add values to dynamically created object


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

from time import strftime, gmtime
import csv
from urllib2 import urlopen
from simplejson import loads
c = csv.writer(open('FB_Monitoring.csv', "a"), delimiter=';')
First = ['Name', 'Likes', 'Talking About']
c.writerow(First)

source = open("FBPAGES.txt", "r")
FacebookPages = source.readlines()

for Page in FacebookPages:
    Page = Page.replace('facebook.com','graph.facebook.com')
    content = loads(urlopen(Page).read())
    liste = [content['name'],content['likes'],content['talking_about_count']]
    c.writerow(liste)

rawDescription: Monitoring a Facebook page

description: Monitoring a Facebook page


code:
if self._getters:
    assert not self._queue, (
        'queue non-empty, why are getters waiting?')

    getter = self._getters.popleft()
    self.__put_internal(item)

    # getter cannot be cancelled, we just removed done getters
    getter.set_result(self._get())

rawDescription: asyncio.queue strange behaviour

description: Asyncio.queue strange behaviour


code:
query = {'$match': {'symbol': 'AAPL'}}
sort = {'$sort': {'ts_minute': 1}}
unwind = {'$unwind': '$ticks'}
projection = {
    '$project': {
        'symbol':       1,
        'ts_minute':    1,
        'volume' : { '$cond' : [
        {"$eq" : ["$ticks.t",null]},
        "$ticks.v",
        0
    ] },
    "price" : { "$cond" : [
        {"$eq" : ["$ticks.t",null] },
        null,
        "$ticks.v"
    ] }
    }
}

group = {
    '$group': {
        '_id': {
            'symbol':   '$symbol',
            'minute':   '$ts_minute'
        },
        'open':     {'$first':  '$price'},
        'high':     {'$max':    '$price'},
        'low':      {'$min':    '$price'},
        'close':    {'$last':   '$price'},
        'volume':   {'$sum':    '$volume'}
    }
}
bars = tick_collection.aggregate([query, sort, unwind, projection, group])

rawDescription: MongoDB: Aggregation of stock tick data

description: MongoDB: Aggregation of stock tick data


code:
with open('big1.csv') as i, open('big2.csv') as j:
   a = csv.reader(i)
   b = csv.reader(j)
   for linea in a:
      lineb = next(b)
      if sorted(map(str.lower, linea)) != sorted(map(str.lower, lineb)):
          print('{} does not match {}'.format(linea, lineb))

rawDescription: Compare lines in 2 text files

description: Compare lines in 2 text files


code:
x = 0
while x < 10:
    if condition:
        x += 1

rawDescription: Setting Variable as Integer Once

description: Setting Variable as Integer Once


rawDescription: How to get Python interactive console in current namespace?

description: Get Python interactive console in current namespace


code:
def isWordIn(word, string):
    return not(string.find(word) == -1)

rawDescription: Check whether a string contains a specific word


code:
class Department(models.Model):
    name = models.CharField(max_length=100)
    abbreviation = models.CharField(max_length=4)

    class Meta:
        ordering = ["name"]

rawDescription: Controlling Django ModelForm output

description: Controlling Django ModelForm output


code:
lines = defaultdict(dict)
with open("file_parse.txt") as f:
    for line in f:
        parts = line.split()
        key = tuple(parts[1:3]) # unique key with servername and datetime
        lines[key][parts[0]] = parts[3]
        lines[key]["servername"] = parts[1]
        lines[key]["datetime"] = parts[3]
res = list(lines.values())
print(res)
# [
#    {'cpudile': 'NaN', 'cpunice': '0.0', 'cpunumber': '40.0', 'cpusystem': '0.0', 'cpuuser': '0.0', 'cpuwait': '0.0', 'datetime': 'NaN', 'servername': '1438084445'},
#    {'cpudile': 'NaN', 'cpunice': '0.0', 'cpunumber': '40.0', 'cpusystem': '0.0', 'cpuuser': '0.0', 'cpuwait': '0.0', 'datetime': 'NaN', 'servername': '1438084440'},
#    {'cpudile': 'NaN', 'cpunice': '0.0', 'cpunumber': '40.0', 'cpusystem': '0.0', 'cpuuser': '0.0', 'cpuwait': '0.0', 'datetime': 'NaN', 'servername': '1438084450'}
# ]

rawDescription: Python script to read data from a file and store it in mysql table


code:
for new_product in new_products_list:
    # use different variable names, otherwise you won't be able to access
    # the item from new_product_list here
    product, created = Products.objects.get_or_create(article=new_product.article)

    if not created:
       for field in new_product._meta.get_all_field_names():
           setattr(product, field, getattr(new_product, field))
       product.save()

rawDescription: How to update object with another object in get_or_create?

description: Update object with another object in get_or_create


code:
import time

while True:
  do_task()
  time.sleep(4 * 60 * 60) # 4 hours * 60 minutes * 60 seconds

rawDescription: Scheduling a task on python

description: Scheduling a task on python


code:
import glob
import os

files = glob.glob("*cycle*.log")
files.sort(key=os.path.getmtime)
print("\n".join(files))

rawDescription: Glob search files in date order?

description: Glob search files in date order


rawDescription: How to Use Boolean Array to Replace Specific Indices in Python


code:
a,b = raw_input().split()
a = int(a)
b = float(b)

rawDescription: How to read two inputs separated by space in a single line?

description: Read two inputs separated by space in a single line


code:
from collections import OrderedDict
od = OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])
od

rawDescription: Ordered Dict, preserve initial Order

description: Ordered Dict, preserve initial Order


code:
with open(csv_file_name, 'rb') as source:
    consec_empty_lines = 0
    for line in source:
        if line == '\r\n':
            consec_empty_lines += 1
            if consec_empty_lines == 2:
                break
        else:
            consec_empty_lines = 0
    df = pd.read_csv(source)

rawDescription: Read pandas dataframe from csv beginning with non-fix header


code:
# the smallest element of myArr greater than myNumber
myArr[myArr > myNumber].min()
# the largest element of myArr less than myNumber
myArr[myArr < myNumber].max()

rawDescription: find the closest 2 numbers in a list to a given number in python

description: Find the closest 2 numbers in a list to a given number in python


rawDescription: Reference where a python script is located if being run from another location


code:
import re
pattern = re.compile('^\t')  # match a tab in the beginning of the line
pattern.sub('', '\tline1\t')
pattern.sub('', '\t\tline2\t')
pattern.sub('', 'line3\t')

rawDescription: python replace remove one tab from each line

description: Python replace remove one tab from each line


code:
arr = np.empty((len(m), len(n)), dtype=str)
arr.fill('')
arr[0] = list(n)
arr[:,0] = list(m)
arr

rawDescription: len(n) x len(m) array in NumPy

description: Len(n) x len(m) array in NumPy


code:
import sys
sys.path.append('/path/to/directory')
import your_module

rawDescription: Python module not working (not able to import) even after including it in PATH variable


code:
# ...append all line edits to this list:
line_edits = []

for le in line_edits:
  le.textChanged.connect(self.mySumFunction)

rawDescription: Connect the same signal from several widgets to the same function in PyQt?


code:
A = np.subtract.outer(Img2, Img2)
A = np.abs(A)

rawDescription: Affinity Matrix Calculation using Numpy

description: Affinity Matrix Calculation using Numpy


code:
# in the init code...
self.runThread = threading.Event()

# when starting thread...
self.runThread.set()
self.monThread.start()

# in the thread...
while self.runThread.isSet():
    pass # do stuff

# killing the thread...
self.runThread.clear()
self.monThread.join()

rawDescription: On-Demand Python Thread Start/Join Freezing Up from wxPython GUI


code:
MyModelForm(instance=myInstanceModel)
MyModelForm(initial={ "my": "initial-data" })

rawDescription: Load Django Form Object with data from Model instance already "loaded"


code: pylab.imshow(z, interpolation="gaussian", extent = [.3,.9,0.,3.5], aspect='auto')

rawDescription: Rescaling axis in Matplotlib imshow under unique function call


code:
# Assuming list and detail URLs like:
#   /v1/objects/<parent_pk>/subobjects/
#   /v1/objects/<parent_pk>/subobjects/<pk>/
def pre_save(self, obj):
    parent = models.MainObject.objects.get(pk=self.kwargs['parent_pk'])
    obj.parent = parent

rawDescription: Django REST Framework: creating hierarchical objects using URL arguments


code:
from itertools import combinations
xyPositions = [[474, 318], [543, 432], [633, 328], [548, 514]]
[dotOverlap(*items) for items in combinations(xyPositions, r=2)]

rawDescription: Multiple Comparisons for 2D list

description: Multiple Comparisons for 2D list


code:
class rpartial(partial):
    def __init__(self, *args):
        self.result = args[-1]
    def __repr__(self):
        return self.result

rpartial(function, arg1, arg2, undoredo)

rawDescription: Python: Need the result of functools.partial(function) to be known as something else


code: results += [each for each in os.listdir(folder) if each.endswith('.c')]

rawDescription: Python: How can I find all files with a particular extension?


code:
df['counter'] = df.groupby(['Product','SubProd']).cumcount()+1
df

rawDescription: Grouping and auto increment based on columns in pandas


code:
#!/usr/bin/env python

from osgeo import gdal, gdalconst

# Source
src_filename = 'MENHMAgome01_8301/mllw.gtx'
src = gdal.Open(src_filename, gdalconst.GA_ReadOnly)
src_proj = src.GetProjection()
src_geotrans = src.GetGeoTransform()

# We want a section of source that matches this:
match_filename = 'F00574_MB_2m_MLLW_2of3.bag'
match_ds = gdal.Open(match_filename, gdalconst.GA_ReadOnly)
match_proj = match_ds.GetProjection()
match_geotrans = match_ds.GetGeoTransform()
wide = match_ds.RasterXSize
high = match_ds.RasterYSize

# Output / destination
dst_filename = 'F00574_MB_2m_MLLW_2of3_mllw_offset.tif'
dst = gdal.GetDriverByName('GTiff').Create(dst_filename, wide, high, 1, gdalconst.GDT_Float32)
dst.SetGeoTransform( match_geotrans )
dst.SetProjection( match_proj)

# Do the work
gdal.ReprojectImage(src, dst, src_proj, match_proj, gdalconst.GRA_Bilinear)

del dst # Flush

rawDescription: How to project and resample a grid to match another grid with GDAL python?

description: Project and resample a grid to match another grid with GDAL python


code:
import numpy as np
orig_color = (0, 0, 0)
replacement_color = (r, g, b)

data[(data == orig_color).all(axis = -1)] = replacement_color

rawDescription: Replace vectors in 2d numpy array

description: Replace vectors in 2d numpy array


code: f, ax = plt.subplots(num='My Window Title')

rawDescription: assigning name to matplotlib subplot figure that can be used to make figure current

description: Assigning name to matplotlib subplot figure that can be used to make figure current


code:
from io import TextIOWrapper

with open('/path/to/file', 'rb') as f:
  wf = TextIOWrapper(f, 'utf-8')
  wf._CHUNK_SIZE = 1  # Implementation detail, may not work everywhere

  wf.read(1) # gives next utf-8 encoded character
  f.read(1)  # gives next byte

rawDescription: Read utf-8 character from byte stream

description: Read utf-8 character from byte stream


code:
...
def anim_3(gifID = 0):                              # Something to track on what GIF we are currently
    if gifID >= len(giflist_2): return              # No more gifs to display
    L2.config(image=giflist_2[gifID])
    L2.update()
    side.after(100, lambda: anim_3(gifID+1))        # Going to next GIF

def anim_2(gifID = 0):
    if gifID >= len(giflist_1): return
    L1.config(image=giflist_1[gifID])
    L1.update()
    side.after(100, lambda: anim_2(gifID+1))        # Number 100 means 100 milliseconds. It's equal to 0.1 seconds.

if __name__ == '__main__':
    anim(a1)
    anim_1(a2)

    side.after(100, anim_2)
    side.after(100, anim_3)

side.mainloop()

rawDescription: How do I make two image loops run at the same time in Tkinter

description: Make two image loops run at the same time in Tkinter


code:
import matplotlib.pyplot as plt

nx = 3
ny = 1

dxs = 8.0
dys = 6.0

fig, ax = plt.subplots(ny, nx, sharey = True, figsize=(dxs*nx, dys*ny) )
for i in range(nx):
    ax[i].plot([1, 2], [1, 2])

rawDescription: matplotlib pyplot: subplot size

description: Matplotlib pyplot: subplot size


rawDescription: Mark the shortest overlapping match using regular expressions


code:
import json
title, data = ('Marks_Subjects ', "[['Time', 'maths', 'Science', 'english'], ['2013-08-31-16', 100, 50, 65]]")
title, sub_title = title.split('_')  # Split 'Mark' and 'Subjects'
data = json.loads(data.replace("'", '"'))  # Deserialize the data list
data = dict(zip(*data))  # make a dict of the two lists
date = data.pop('Time')  # Extract the date
# Create a dict using a comprehension.
{title: {subject: {date: {sub_title: mark}}
 for subject, mark in data.iteritems()}}

rawDescription: how to create Dictionary within a dictionary in python

description: Create Dictionary within a dictionary in python


code:
from PyQt4 import QtGui, QtCore
import sys, os

class CheckableComboBox(QtGui.QComboBox):
    def __init__(self):
        super(CheckableComboBox, self).__init__()
        self.view().pressed.connect(self.handleItemPressed)
        self.setModel(QtGui.QStandardItemModel(self))

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)

class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()
        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)
        self.ComboBox = CheckableComboBox()
        for i in range(3):
            self.ComboBox.addItem("Combobox Item " + str(i))
            item = self.ComboBox.model().item(i, 0)
            item.setCheckState(QtCore.Qt.Unchecked)
        self.toolbutton = QtGui.QToolButton(self)
        self.toolbutton.setText('Select Categories ')
        self.toolmenu = QtGui.QMenu(self)
        for i in range(3):
            action = self.toolmenu.addAction("Category " + str(i))
            action.setCheckable(True)
        self.toolbutton.setMenu(self.toolmenu)
        self.toolbutton.setPopupMode(QtGui.QToolButton.InstantPopup)
        myBoxLayout.addWidget(self.toolbutton)
        myBoxLayout.addWidget(self.ComboBox)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(480,320)
    sys.exit(app.exec_())

rawDescription: PyQt: How to set Combobox Items be Checkable?


code:
class myObject(QObject):
  somethingChanged= pyqtSignal(str)

  def __init__(self):
    super(myObject).__init__(self)
    # Here we indicate we will try and catch the signal.
    self.somethingChanged.connect(self.updateText)

  def processData(self):
    for i in data:
      ...
      # Inside the loop you can fire off a signal.
      object.emit("somethingChanged")
      ...

  def updateText(self,text):
      textedit.setText(text)

rawDescription: Qt Pyside displaying results in widgets

description: Qt Pyside displaying results in widgets


code:
pixels = img.load() # create the pixel map

for i in range(img.size[0]):    # for every pixel:
    for j in range(img.size[1]):
        pixels[i,j] = (i, j, 100) # set the colour accordingly

rawDescription: Python equivalent for TurboPascal's plot (x , y, colour)?


code:
from PyQt4 import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        QtGui.QWidget.__init__(self)
        self.tree1 = QtGui.QTreeWidget(self)
        self.tree2 = QtGui.QTreeWidget(self)
        layout = QtGui.QHBoxLayout(self)
        for tree in (self.tree1, self.tree2):
            tree.header().hide()
            tree.itemExpanded.connect(self.handleExpanded)
            tree.itemCollapsed.connect(self.handleCollapsed)
            for text in 'one two three four'.split():
                item = QtGui.QTreeWidgetItem(tree, [text])
                for text in 'red blue green'.split():
                    child = QtGui.QTreeWidgetItem(item, [text])
            layout.addWidget(tree)

    def handleExpanded(self, item):
        self.syncExpansion(item, True)

    def handleCollapsed(self, item):
        self.syncExpansion(item, False)

    def syncExpansion(self, item, expand=True):
        if item is not None:
            tree = item.treeWidget()
            if tree is self.tree1:
                tree = self.tree2
            else:
                tree = self.tree1
            text = item.text(0)
            for other in tree.findItems(text, QtCore.Qt.MatchFixedString):
                other.setExpanded(expand)

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(300, 500, 300, 300)
    window.show()
    sys.exit(app.exec_())

rawDescription: Get the place in one Qtreewidget and expand another to the same place


code:
import copy

def InsertionSort(A):
    A = copy.deepcopy(A) # or A = A[:] might work as well in this case
    ...
    return A

rawDescription: Insertion sort algorithm modifying output


code: s = set()

rawDescription: Python newbie: creating an empty set

description: Python newbie: creating an empty set


code:
from random import shuffle
# Given list1 and list2
list1_shuf = []
list2_shuf = []
index_shuf = range(len(list1))
shuffle(index_shuf)
for i in index_shuf:
    list1_shuf.append(list1[i])
    list2_shuf.append(list2[i])

rawDescription: Better way to shuffle two related lists

description: Better way to shuffle two related lists


code: positionsList.sort(key=lambda p: howCentric(p, boardLength))

rawDescription: how to sort using key function which takes more than one argument

description: Sort using key function which takes more than one argument


rawDescription: Change the numbers of a list to another number python


rawDescription: How to save an image by selecting "save image as..." in a context menu using Selenium Webdriver (Python)

description: Save an image by selecting "save image as..." in a context menu using Selenium Webdriver (Python)


code: [x for x in listobj if any(y is not None for y in x)]

rawDescription: how to Skip None holding tuple in list?

description: Skip None holding tuple in list


code:
from pylab import *

# some random values
xdata = arange(0.0, 2.0, 0.01)
ydata1 = sin(2*pi*xdata)
ydata2 = 5*cos(2*pi*xdata) + randn(len(xdata))

# number of ticks on the y-axis
numSteps = 9;

# plot
figure()

subplot(121)
plot(xdata, ydata1, 'b')
yticks( linspace(ylim()[0],ylim()[1],numSteps) )
grid()

subplot(122)
plot(xdata, ydata2, 'g')
yticks( linspace(ylim()[0],ylim()[1],numSteps) )
grid()

show()

rawDescription: Matplotlib: multiple y axes, grid lines applied to both?


code:
import sys
sys.stdout.flush()

rawDescription: How to flush output of Python print?

description: Flush output of Python print


code:
class CreateNetwork(View):  # Extend from the view you need

    c = {}
    r = []

    def get(self, request, *args, **kwargs):

        # This code will be executen in a GET request

        # here you can access c or r with self
        self.c.update(csrf(request))  # this is just an example
        ...

    def post(self, request, *args, **kwargs):

        # This code will be executed in a POST request

        self.r.append(...)

rawDescription: Use POST and GET in the same view django


code:
import sys
module_name = "web1.%s.models" % app
__import__(module_name)
models = sys.modules[module_name]
models.modelname

rawDescription: Django / Python, using variablized object names


code:
@app.before_request
def func():
  session.modified = True

rawDescription: Resetting the expiration time for a cookie in Flask


code:
import subprocess
ret = subprocess.call(['python', 'manage.py', 'test'])
if ret == 0:
    print("Tests Passed Successfully")
else:
    print("Tests failed")

rawDescription: How to send an email on successful test completion in django

description: Send an email on successful test completion in django


code:
import sys
sys.path.append("/path/to/your/tweepy/directory")

import tweepy

rawDescription: (Python) Use a library locally instead of installing it


code:
import curses
curses.ACS_ULCORNER
curses.initscr()
curses.ACS_ULCORNER
4194412

rawDescription: How do I use extended characters in Python's curses library?

description: Use extended characters in Python's curses library


code:
from subprocess import Popen
Popen(["sleep", "100"])
exit()

rawDescription: Python multiprocessing and independence of children processes


code:
from ilogue import fexpect

prompt = ['Password', 'mypassword']  # ('prompt', 'answer') Case sensitive

def test():
    with fexpect.expecting(prompt):
        fexpect.local("su -")

rawDescription: fabric -- cant run commands after user is switched

description: Fabric -- cant run commands after user is switched


rawDescription: python daemon thread is exiting when process is killed

description: Python daemon thread is exiting when process is killed


code:
class Thing(object):
    """Generic game object with interpolation"""
    def __init__(self, x=0, y=0):
        self._x = self.x = x
        self._y = self.y = y

    def imprint(self):
        """call before changing x and y"""
        self._x = self.x
        self._y = self.y

    def __iter__(self):
        """handy to unpack like a tuple"""
        yield self.x
        yield self.y

Ship = Thing
Bullet = Thing

class Star(Thing):
    """docstring for Star"""
    def __init__(self, x, y, r):
        super(Star, self).__init__(x, y)
        self.r = r

    def __iter__(self):
        yield self.x
        yield self.y
        yield self.r

def lerp_things(things, alpha, threshold=100):
    """Expects iterables of Things"""
    for t in things:
        if sqrt((t._x - t.x) ** 2 + (t._y - t.y) ** 2) > threshold:
            yield (t.x, t.y)
        else:
            yield (lerp(t._x, t.x, alpha), lerp(t._y, t.y, alpha))

rawDescription: How would you handle interpolation in a python game?


code:
with open(infile) as open_file:
    with open(outfile, 'w') as write_file:
        for line in open_file:
            write_file.write(" ".join(line))

rawDescription: How to add a whitespace between all characters in a .txt file

description: Add a whitespace between all characters in a .txt file


code:
def calculate():
    # we only want the user to input numbers
    while True:
        try:
            currency_input = float(input('Insert value: '))  # input always returns a str, we need to type cast
            break  # if input is valid we break out of the loop and move on
        except TypeError:  # handle the error when the input is not a number
            print('Please enter a number.')

    # use a dictionary because it is easier to read
    currency_dict = {
        'dollar': 34,
        'euro': 36,
        'pound': 52}

    # get the type of currency and do the math
    while True:
        select_currency = input('Insert currency(dollar,euro or pound): ').lower()
        if select_currency not in currency_dict:  # if the users enter something that is not in the dict
            print('Invalid currency')  # oops, try again
        else:
            money = currency_input * currency_dict[select_currency]  # we do the math
            return money  # return allows us to further manipulate that variable if we so desire

print(calculate())

rawDescription: Python program not working, input == string not working


code:
class mainFrame(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Aminozuurtoets V.1.0", size=(900,600))

        top_panel = wx.Panel(self)
        self.vraag = 1
        m_tekst = wx.StaticText(top_panel, -1, "Vraag " + str(self.vraag),(400,50), (100, -1), wx.ALIGN_CENTER)
        m_font = wx.Font(20, wx.DECORATIVE, wx.ITALIC, wx.NORMAL)
        m_tekst.SetFont(m_font)

        cijfer = random.randint(1,100)

        ### Make an attribute to access from buttonClick1 method.
        self.test2 = wx.StaticText(top_panel, -1, str(cijfer), (325,300))

        res_but = wx.Button(top_panel, label = "Resultaten", pos=(650, 400), size=(150, 200))
        ga_naar = wx.Button(top_panel, label = "Ga naar vraag", pos=(100, 400), size=(150, 200))
        ga_button = wx.Button(top_panel, label = "Volgende vraag", pos=(380, 400), size=(150, 200))
        self.Bind(wx.EVT_BUTTON, self.buttonClick1, ga_button)

    def buttonClick1(self, event):
        ### Change label of static text.
        self.test2.Label = str(random.randint(1,100))

    def closebutton(self, event):
        self.Close(True)

rawDescription: wxpython frame update with a button click

description: Wxpython frame update with a button click


code:
import Tkinter as Tk
import pygame

root = Tk.Tk()
root.title('Intro')

playButton = Tk.Button(root, text='Play', command=root.destroy)
playButton.pack()

root.mainloop() # Rest of the script won't execute until playButton pressed

# Initialize pygame window

rawDescription: how to combine pygame and tkinter?

description: Combine pygame and tkinter


code:
import tkinter as tk

root = tk.Tk() # create a Tk root window

w = 800 # width for the Tk root
h = 650 # height for the Tk root

# get screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)

# set the dimensions of the screen
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.mainloop() # starts the mainloop

rawDescription: How to specify where a Tkinter window opens?

description: Specify where a Tkinter window opens


code:
import operator
ops = {"+": operator.add,
       "-": operator.sub,
       "*": operator.mul,
       "/": operator.div}
op_char = raw_input('enter a operand')
op_func = ops[op_char]
result = op_func(a, b)

rawDescription: assign operator to variable in python?

description: Assign operator to variable in python


code:
def cmdlineCall(name, args):
    child = pexpect.spawn(name, args)
    # Wait for the end of the output
    child.expect(pexpect.EOF)
    out = child.before # we get all the data before the EOF (stderr and stdout)
    child.close() # that will set the return code for us
    # signalstatus and existstatus read as the same (for my purpose only)
    if child.exitstatus is None:
        returncode = child.signalstatus
    else:
        returncode=child.exitstatus
    return (out,returncode)

rawDescription: Capture "Segmentation fault" message for a crashed subprocess: no out and err after a call to communicate()


code:
class Role(db.Model):
    # snip
    def __str__(self):
        return self.name

rawDescription: How to tell flask-admin to use alternative representation when displaying Foreign Key Fields?

description: Tell flask-admin to use alternative representation when displaying Foreign Key Fields


code:
def pro(temp_line):
    test = 0
    temp_line = temp_line.strip().split()
    test = test + 1
    return test, len(temp_line)

if __name__ == "__main__":
    with open("somefile.txt") as lines:
        pool = mp.Pool(processes = 10)
        tests_and_t = pool.map(pro,lines.readlines())
        tests, t = zip(*test_and_t)
        test = sum(tests)

rawDescription: changing global variable when multiprocessing in python

description: Changing global variable when multiprocessing in python


code:
import sys
from PySide import QtGui, QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.grid = QtGui.QGridLayout()
        big_one = QtGui.QPushButton('Big one')
        big_one.setSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
        self.grid.addWidget(big_one, 0, 0, 2, 2)
        self.grid.addWidget(QtGui.QPushButton('Ajouter'), 0, 2, 1, 1)
        self.grid.addWidget(QtGui.QPushButton('Enlever'), 1, 2, 1, 1)
        self.grid.addWidget(QtGui.QLabel("Chemin du lecteur :"), 2, 0, 1, 1)
        self.grid.addWidget(QtGui.QLineEdit(), 2, 1, 1, 1)
        self.grid.addWidget(QtGui.QPushButton("Selectionner"), 2, 2, 1, 1)
        self.grid.addWidget(QtGui.QCheckBox("Some long text in french"), 3, 0, 1, 3)
        self.grid.addWidget(QtGui.QCheckBox("An even longer text in french than the first one"), 4, 0, 1, 3)
        self.grid.addWidget(QtGui.QLabel("Something, something, something"), 5, 0, 1, 2)
        self.grid.addWidget(QtGui.QSpinBox(), 5, 2, 1, 1)
        self.setLayout(self.grid)

app = QtGui.QApplication(sys.argv)
w = Window()
w.show()
sys.exit(app.exec_())

rawDescription: QGridLayout, expand widget on the line

description: QGridLayout, expand widget on the line


code:
bar_width = .2

fig, axs = plt.subplots(1,2, figsize=(12,6))
fig.subplots_adjust(wspace=0, top=1, right=1, left=0, bottom=0)

axs[1].barh(y_pos[::-1], num_tickets[::-1], bar_width,  align='center', alpha=0.4, color='r')
axs[1].barh(y_pos_2[::-1], num_tickets_2[::-1], bar_width,  align='center', alpha=0.4, color='b')
axs[1].barh(y_pos_3[::-1], num_tickets_3[::-1], bar_width,  align='center', alpha=0.4, color='y')
axs[1].barh(y_pos_4[::-1], num_tickets_4[::-1], bar_width,  align='center', alpha=0.4, color='g')

axs[1].set_yticks([])
axs[1].set_xlabel('Numbers')
axs[1].set_title('Horizontal Bar Chart with table')
axs[1].set_ylim(0 - .4, (len(appsol)) + .4)

cell_text = list(zip(num_tickets, num_tickets_2, num_tickets_3, num_tickets_4))

row_lables = appsol
column_labels = ['So Huge\nMice', 'Elephants', 'Reptiles', 'Germs']

axs[0].axis('off')

the_table = axs[0].table(cellText=cell_text,
                     rowLabels=row_lables,
                     colLabels=column_labels,
                     bbox=[0.4, 0.0, 0.6, 1.0])

the_table.set_fontsize(15)

plt.savefig('barh_graph.png')
plt.close('all')

rawDescription: Move graph position within plot (matplotlib)


code:
newlist = []

for i in filter_words:
    if i not in skip_words:
        newlist.append(i)

rawDescription: Comparing 2 lists to remove unwanted words


code:
import collections
def distance(s1, s2):
    cnt = collections.Counter()
    for c in s1:
        cnt[c] += 1
    for c in s2:
        cnt[c] -= 1
    return sum(abs(diff) for diff in cnt.values()) // 2 + \
        (abs(sum(cnt.values())) + 1) // 2   # can be omitted if len(s1) == len(s2)

rawDescription: Modify Levenshtein-Distance to ignore order


code: sqlPrefix = "select x,y in myTable where myVar in ('%s', '%s')" % (var1, var2)

rawDescription: Converting to sql style string

description: Converting to sql style string


code:
PDRAlias = PDR.alias()
subq = (PDRAlias
        .select(fn.MAX(PDRAlias.id).alias('max_id'), PDRAlias.property, PDRAlias.requesting_user)
        .where(PDRAlias.property == 7)
        .group_by(PDRAlias.requesting_user)
        .alias('subq'))
query = (PDR
         .select()
         .join(subq, on=(subq.c.max_id == PDR.id)))

rawDescription: How to convert this query to the Peewee ORM?

description: Convert this query to the Peewee ORM


code:
from PyQt4 import QtGui, QtWebKit
from PyQt4.QtCore import Qt, QSize

class RoundWindow(QtWebKit.QWebView):
    def __init__(self):
        super(RoundWindow, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setAttribute(Qt.WA_TranslucentBackground)

    def sizeHint(self):
        return QSize(300,300)

    def paintEvent(self, event):
        qp = QtGui.QPainter()
        qp.begin(self)
        qp.setRenderHint(QtGui.QPainter.Antialiasing);
        qp.setPen(Qt.NoPen);
        qp.setBrush(QtGui.QColor(255, 0, 0, 127));
        qp.drawEllipse(0, 0, 300, 300);
        qp.end()

a = QtGui.QApplication([])
rw = RoundWindow()
rw.show()
a.exec_()

rawDescription: PyQt Irregularly Shaped Windows (e.g. A circular without a border/decorations)


rawDescription: Injecting variable before/during import

description: Injecting variable before/during import