code:
import os
import imp
import workbench

def load_wb():
    _cwd = os.getcwd()
    os.chdir(os.path.join(os.getenv('HOME'), 'Skripte'))
    imp.reload(workbench)
    os.chdir(_cwd)

load_wb()

rawDescription: Use PYTHONSTARTUP to interactively test a python file in the interpreter


code: random.normalvariate(25, 4.87340)

rawDescription: Probability function to generate values instead of calling random


rawDescription: Removing specific sequences from a string


code:
import sys
from PyQt4 import QtGui

class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()

        label = QtGui.QLabel('My Label')
        line_edit = QtGui.QLineEdit()

        form_layout = QtGui.QFormLayout()
        form_layout.addRow(label, line_edit)

        close_button = QtGui.QPushButton('Close')
        execute_button = QtGui.QPushButton('Execute')

        button_layout = QtGui.QHBoxLayout()
        button_layout.addWidget(close_button)
        button_layout.addWidget(execute_button)

        main_layout = QtGui.QVBoxLayout()
        main_layout.addLayout(form_layout)
        main_layout.addStretch()
        main_layout.addLayout(button_layout)

        central_widget = QtGui.QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)

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

rawDescription: PyQt: How to stick a widget to the bottom edge of dialog


code:
gap_counts = Counter()
with open(str(sys.argv[1]) + '.out', 'wb') as outfile:
    with open(str(sys.argv[1]), 'rU') as infile:
        for line in infile:
            if line.startswith('>'):
                continue
            else:
                char_groups = groupby(line, lambda char:char == '-')
                line_counts = Counter(len(list(group)) for char, group in char_groups)
                gap_counts = gap_counts + line_counts
    for key, value in sorted(gap_counts.iteritems()):
        t = csv.DictWriter(outfile, gap_counts.keys())
        t.writeheader()
        t.writerow(gap_counts)

rawDescription: Python DictWriter: why won't python quickly return my output file? Using Counter, csv and group-by


rawDescription: Python string list to string

description: Python string list to string


rawDescription: Deleting a Secure Cookie in tornado

description: Deleting a Secure Cookie in tornado


code:
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ss', out_signature='v')
def Get(self, interface, prop):
    ...
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='ssv')
def Set(self, interface, prop, value):
    ...
@dbus.service.method(dbus.PROPERTIES_IFACE, in_signature='s', out_signature='a{sv}')
def GetAll(self, interface):
    ...

rawDescription: How to handle properties of a dbus interface with python?

description: Handle properties of a dbus interface with python


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

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

plt.xkcd(scale=1, length=100, randomness=2)

plt.plot(t, t, 'r', t, t**2, 'b', t, t**3, 'g')
plt.show()

rawDescription: Cartoonish style plots in MATLAB or Python?


code:
a
M = 3
[a[i*M:(i+1)*M,i*M:(i+1)*M] for i in range(a.shape[0]/M)]

rawDescription: Extracting diagonal blocks from a numpy array


code: for e in t.iter(): print(e)

rawDescription: Behavior of ElementTree iterator

description: Behavior of ElementTree iterator


rawDescription: Get foreign key without requesting the whole object


code:
Base = declarative_base()
engine = None
sessionmaker = sessionmaker()
db = scoped_session(sessionmaker)

def configure_engine(url):
    global sessionmaker, engine, db

    engine = create_engine(url)
    db.remove()
    sessionmaker.configure(bind=engine)

def create_app(name=__name__, configuration=None):
    from .modules import admin
    from .modules.admin.models import User

    app = Flask(name, static_path='/static', template_folder=template_dir)
    load_config(app, configuration)
    celery.config_from_object(app.config)
    configure_engine(app.config['SQLALCHEMY_DATABASE_URI'])
    filters.init_app(app)
    register_local_modules(app)
    admin.init_app(app)
    login_manager.init_app(app)
    @login_manager.user_loader
    def load_user(id):
        return db.query(User).get(id)

    # Enable the DebugToolbar
    if app.config['DEBUG_TOOLBAR']:
        toolbar = DebugToolbarExtension(app)

    return app

rawDescription: How do I lazy init SQLAlchemy

description: Lazy init SQLAlchemy


code:
def changeLast(nested, new):
    last = nested[-1]
    if isinstance(last, list):
        changeLast(last, new)
    else:
        nested[-1] = new

a = [3, [4, [5]]]
changeLast(a, 6)
print(a)

[3, [4, [6]]]

rawDescription: How to efficiently change the rightmost value in list of unknown depth?

description: Efficiently change the rightmost value in list of unknown depth


code: THEOPTION = 10

rawDescription: Setting package-wide variables during python setup.py install


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

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)
    ax.scatter(xs, ys, zs, facecolor=(0,0,0,0), s=100, marker=m, edgecolor=c)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

rawDescription: Matplotlib 3D scatter plot no facecolor

description: Matplotlib 3D scatter plot no facecolor


code:
from numpy import linspace , arange , reshape ,zeros
from scipy.fftpack import fft2 , fftfreq
from cmath import pi

# create some arbitrary data
some_data = arange(0.0 , 16384.0 , dtype = complex)

# reshape it to be a 128x128 2d grid
some_data_grid = reshape(some_data , (128 , 128) )

# assign some real spatial co-ordinates to the grid points
# first define the edge values
x_min = -250.0
x_max = 250.0
y_min = -250.0
y_max = 250

# then create some empty 2d arrays to hold the individual cell values
x_array = zeros( (128,128) , dtype = float )
y_array = zeros( (128,128) , dtype = float )

# now fill the arrays with the associated values
for row , y_value in enumerate(linspace (y_min , y_max , num = 128) ):

  for column , x_value in enumerate(linspace (x_min , x_max , num = 128) ):

    x_array[row][column] = x_value
    y_array[row][column] = y_value

# now for any row,column pair the x_array and y_array hold the spatial domain
# co-ordinates of the associated point in some_data_grid

# now use the fft to transform the data to the wavenumber domain
some_data_wavedomain = fft2(some_data_grid)

# now we can use fftfreq to give us a base for the wavenumber co-ords
# this returns [0.0 , 1.0 , 2.0 , ... , 62.0 , 63.0 , -64.0 , -63.0 , ... , -2.0 , -1.0 ]
n_value = fftfreq( 128 , (1.0 / 128.0 ) )

# now we can initialize some arrays to hold the wavenumber co-ordinates of each cell
kx_array = zeros( (128,128) , dtype = float )
ky_array = zeros( (128,128) , dtype = float )

# before we can calculate the wavenumbers we need to know the total length of the spatial
# domain data in x and y. This assumes that the spatial domain units are metres and
# will result in wavenumber domain units of radians / metre.
x_length = x_max - x_min
y_length = y_max - y_min

# now the loops to calculate the wavenumbers
for row in xrange(128):

  for column in xrange(128):

    kx_array[row][column] = ( 2.0 * pi * n_value[column] ) / x_length
    ky_array[row][column] = ( 2.0 * pi * n_value[row] ) / y_length

# now for any row,column pair kx_array , and ky_array will hold the wavedomain coordinates
# of the correspoing point in some_data_wavedomain

rawDescription: How to calculate wavenumber domain coordinates from a 2d FFT

description: Calculate wavenumber domain coordinates from a 2d FFT


rawDescription: Syntax Error with python on module checking


code:
from multiprocessing import Pool
import os

path1 = "some/path"
path2 = "some/other/path"

listing = os.listdir(path1)

p = Pool(5) # process 5 images simultaneously

def process_fpath(path):
    im = Image.open(path1 + path)
    im.resize((50,50))                # need to do some more processing here
    im.save(os.path.join(path2,path), "JPEG")

p.map(process_fpath, listing)

rawDescription: Open images from a folder one by one using python?


rawDescription: Pandas: creating a Series from a tuple generator


code:
import numpy

n = 1000
pairs = [(.3, 'a'), (.3, 'b'), (.4, 'c')]
probabilities = numpy.random.multinomial(n, zip(*pairs)[0])
result = zip(probabilities, zip(*pairs)[1])
# [(299, 'a'), (299, 'b'), (402, 'c')]
[x[0] * x[1] for x in result]
# ['aaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbb', 'cccccccccccccccccccc']

rawDescription: How to do weighted random sample of categories in python

description: Do weighted random sample of categories in python


rawDescription: Python S3 - Work out most recent date

description: Python S3 - Work out most recent date


code:
import HTMLParser
HTMLParser.HTMLParser().unescape(u'a ä b c')

rawDescription: short Unicode \N{} names for Latin-1 characters in Python?

description: Short Unicode \N{} names for Latin-1 characters in Python


code:
import urllib2
from cookielib import CookieJar

cookiejar = CookieJar()
opener = urllib2.build_opener()
cookieproc = urllib2.HTTPCookieProcessor(cookiejar)
opener.add_handler(cookieproc)

rawDescription: Downloading files from the other side of a login


code:
df = pd.DataFrame({"A": ["Hello", "this", "World", "apple"]})
df.A.str.contains("Hello|World")
~df.A.str.contains("Hello|World")
df[~df.A.str.contains("Hello|World")]

rawDescription: Reversal of string.contains In python, pandas


code:
from M2Crypto import EVP
import base64
import time

def aws_url_base64_encode(msg):
    msg_base64 = base64.b64encode(msg)
    msg_base64 = msg_base64.replace('+', '-')
    msg_base64 = msg_base64.replace('=', '_')
    msg_base64 = msg_base64.replace('/', '~')
    return msg_base64

def sign_string(message, priv_key_string):
    key = EVP.load_key_string(priv_key_string)
    key.reset_context(md='sha1')
    key.sign_init()
    key.sign_update(message)
    signature = key.sign_final()
    return signature

def create_url(url, encoded_signature, key_pair_id, expires):
    signed_url = "%(url)s?Expires=%(expires)s&Signature=%(encoded_signature)s&Key-Pair-Id=%(key_pair_id)s" % {
            'url':url,
            'expires':expires,
            'encoded_signature':encoded_signature,
            'key_pair_id':key_pair_id,
            }
    return signed_url

def get_canned_policy_url(url, priv_key_string, key_pair_id, expires):
    #we manually construct this policy string to ensure formatting matches signature
    canned_policy = '{"Statement":[{"Resource":"%(url)s","Condition":{"DateLessThan":{"AWS:EpochTime":%(expires)s}}}]}' % {'url':url, 'expires':expires}

    #sign the non-encoded policy
    signature = sign_string(canned_policy, priv_key_string)
    #now base64 encode the signature (URL safe as well)
    encoded_signature = aws_url_base64_encode(signature)

    #combine these into a full url
    signed_url = create_url(url, encoded_signature, key_pair_id, expires);

    return signed_url

def encode_query_param(resource):
    enc = resource
    enc = enc.replace('?', '%3F')
    enc = enc.replace('=', '%3D')
    enc = enc.replace('&', '%26')
    return enc

#Set parameters for URL
key_pair_id = "APKAIAZVIO4BQ" #from the AWS accounts CloudFront tab
priv_key_file = "cloudfront-pk.pem" #your private keypair file
# Use the FULL URL for non-streaming:
resource = "http://34254534.cloudfront.net/video.mp4"
#resource = 'video.mp4' #your resource (just object name for streaming videos)
expires = int(time.time()) + 300 #5 min

#Create the signed URL
priv_key_string = open(priv_key_file).read()
signed_url = get_canned_policy_url(resource, priv_key_string, key_pair_id, expires)

print(signed_url)

#Flash player doesn't like query params so encode them if you're using a streaming distribution
#enc_url = encode_query_param(signed_url)
#print(enc_url)

rawDescription: Creating Signed URLs for Amazon CloudFront


code:
# setup the jobs and run
result_queue = multiprocessing.Queue()

mcmc1 = MCMC(options, donors, clusters)
mcmc2 = MCMC(options, donors, clusters)
mcmc3 = MCMC(options, donors, clusters)
mcmc4 = MCMC(options, donors, clusters)

p1 = Process(result_queue, mcmc1)
p2 = Process(result_queue, mcmc2)
p3 = Process(result_queue, mcmc3)
p4 = Process(result_queue, mcmc4)

jobs = [p1, p2, p3, p4]

for job in jobs:
    #job.debug_level = 1
    job.start()

results = [result_queue.get() for job in jobs]

#for res in results: res.traceplot(show=False)
p5 = Process(result_queue, results[0])
p6 = Process(result_queue, results[1])
p7 = Process(result_queue, results[2])
p8 = Process(result_queue, results[3])

jobs2 = [p5, p6, p7, p8]

for j in jobs2:
    j.start()

results2 = [result_queue.get() for job in jobs2]

rawDescription: Python Multiprocessing.Process how to reuse a process?


rawDescription: python string join performance

description: Python string join performance


rawDescription: sum of dictionary values in python 3

description: Sum of dictionary values in python 3


code:
#coding=utf-8
import codecs
import sys
# import imp
# imp.reload(sys)
# sys.setdefaultencoding('utf8')
dictFileName = 'abstract.dict'
print(sys.getdefaultencoding())
print(sys.stdout.encoding)

def readDict():
    print("start reading dict...")
    #dictObject = codecs.open(dictFileName,'rb', encoding = 'utf-8')#, encoding = 'utf-8')
    dictObject = open(dictFileName, 'rb')
    try:
        print('open file success!')
        #dictObject.seek(0x1852c)
        chunk = dictObject.read(0x5f0) #0x5f0
        print(len(chunk))
        #chunk = dictObject.read(0x1)
        print('read success')
        #print(chunk.decode("utf-8"))
        #print(chunk.encode('utf-8').decode('gb18030'))
        #sys.stdout.buffer.write(chunk.encode('gb18030'))
        sys.stdout.buffer.write(chunk.decode('utf-8').encode('gb18030'))
    finally:
        dictObject.close()
readDict()
input()

rawDescription: How to print out encoded Asian characters(gb2312) on command prompt?

description: Print out encoded Asian characters(gb2312) on command prompt


code:
with open('Path/to/file', 'r') as content_file:
    content = content_file.read()
    urls = content.split()
    for url in urls:
         webbrowser.open(url)

rawDescription: How can i read a file for urls and then launch all the urls in browser using python

description: Read a file for urls and then launch all the urls in browser using python


code:
def put_data(name=hash_name, key=hash_key, value=hash_data):
    import redis
    r = Redis.get_connection()
    ttl = datetime.today() + timedelta(hours=72)
    r.hset(name=name, key=hash_key, value=hash_data)
    r.expire(name=hash_name, time=ttl)

rawDescription: Expiration of HashMap in Redis python?

description: Expiration of HashMap in Redis python


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

class TestWindow(QtGui.QWidget):

    def __init__(self):
        super(TestWindow, self).__init__()

        self.setGeometry(200,200,800,600)
        self.setWindowTitle('TA Switch Tab')
        self.lbl = QtGui.QTextBrowser(self)
        self.lbl.resize(760,40) # Typically you create a layout and put the widget in the layout.
        self.lbl.move(20,440)

        self._update_timer = QtCore.QTimer()
        self._update_timer.timeout.connect(self.update_label)
        self._update_timer.start(10000) # milliseconds

    def update_label(self):
        with open ("/tmp/py.state.test", "r") as myfile:
            data=myfile.read().replace('\n', '')
        self.lbl.append(data)

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    win = TestWindow()
    win.show()
    sys.exit(app.exec_())

rawDescription: How can I use threading to update a text field in PyQt while the gui is open?

description: Use threading to update a text field in PyQt while the gui is open


code:
for directory in dirList:
    w.writerow([directory])

rawDescription: Python csv write module, need output into different rows instead of columns


rawDescription: Using the class sklearn.cluster.SpectralClustering with parameter affinity='precomputed'


code:
tupa = map(tuple, lsta)
tupb = map(tuple, lstb)
set(tupa).intersection(tupb)
set(tupa).difference(tupb)

rawDescription: How do you find common sublists between two lists?

description: Find common sublists between two lists


code:
class Selector(QtGui.QRubberBand):
    def __init__(self,*arg,**kwargs):
        super().__init__(*arg,**kwargs)
        self.setStyle(QtGui.QStyleFactory.create('windowsvista'))

rawDescription: Customizing QRubberBand look while using cleanlooks style


code:
with open('/tmp/test.txt') as f:
    title=f.next()       # strip title line
    data=''.join(line.rstrip() for line in f)

rawDescription: Multiple line file into one string

description: Multiple line file into one string


code:
setup(
    name='your.module',
    version = '1.0',
    description='This is your awesome module',
    author='You',
    author_email='your@email',
    package_dir = {'': 'src'},
    packages = ['your', 'your.module'],
    test_suite = 'your.module.tests',
    use_2to3 = True,
    convert_2to3_doctests = ['src/your/module/README.txt'],
    use_2to3_fixers = ['your.fixers'],
    use_2to3_exclude_fixers = ['lib2to3.fixes.fix_import'],
)

rawDescription: Is there a way to run 2to3 with pip install?


code:
class A(object):
    def f(self):
        pass

class B(A):
    # this declaration is redundant since exact same behaviour is already inherited.
    def f(self):
        pass

rawDescription: Why a subclass would override a base class method but make it identical (and not use it)?


code:
n = int(raw_input())
numbers = map(int, raw_input().split())[:n]

rawDescription: How to read a specific number of integers and store it in a list in python?

description: Read a specific number of integers and store it in a list in python


code:
def makeInverseIndex(s):
    dic={}
    for index, line in enumerate(s):  #use enumerate() for getting index as well as item
        words = line.split()
        for palabra in words:
            dic.setdefault(palabra,set()).add(index)

rawDescription: Python change list to set in code

description: Python change list to set in code


code:
import datetime
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
now = datetime.datetime.strptime("20:18", "%H:%M")
min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M")))

rawDescription: Find the closest hour

description: Find the closest hour


code:
from django.db.models import Q
import operator

def dynamic_search(queryset):
    search_fields = ["search_field1", "search_field2", "search_field3"]
    search_text = "dummy_text"
    queryset.filter(reduce(operator.or_, [Q(**{'{0}__contains'.format(search_field): search_text}) for search_field in search_fields]))

rawDescription: dynamic search with django orm

description: Dynamic search with django orm


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

url = 'http://www.scb.se/sv_/Hitta-statistik/Statistik-efter-amne/Befolkning/Befolkningens-sammansattning/Befolkningsstatistik/25788/25795/Helarsstatistik---Riket/26046/'

table = pd.read_html(url,thousands=' ', header=0, index_col=0)[0]
table["Folkmängd"].plot(color='k')
plt.show()

rawDescription: Pandas - Reading HTML

description: Pandas - Reading HTML


code:
MAX_SIZE = 5 * 1024 * 1024
BUF_SIZE = 8192

data_blocks = []
byte_count = 0

buf = f.read(BUF_SIZE)
while buf:
    byte_count += len(buf)

    if byte_count > MAX_SIZE:
        # if you want to just truncate at (approximately) MAX_SIZE bytes:
        break
        # or, if you want to abort the call
        raise bottle.HTTPError(413, 'Request entity too large (max: {} bytes)'.format(MAX_SIZE))

    data_blocks.append(buf)
    buf = f.read(BUF_SIZE)

data = ''.join(data_blocks)

rawDescription: Limit uploaded file size in bottle

description: Limit uploaded file size in bottle


code:
from tg.decorators import Decoration
from tg.paginate import Page
from tg.util import Bunch, partial
from tg import request

class paginate(object):
    def __init__(self, name, use_prefix=False,
        items_per_page=10, max_items_per_page=0):
        self.name = name
        prefix = use_prefix and name + '_' or ''
        self.page_param = prefix + 'page'
        self.items_per_page_param = prefix + 'items_per_page'
        self.items_per_page = items_per_page
        self.max_items_per_page = max_items_per_page

    def __call__(self, func):
        decoration = Decoration.get_decoration(func)
        decoration.register_hook('before_validate', self.before_validate)
        decoration.register_hook('before_render', self.before_render)
        return func

    def before_validate(self, remainder, params):
        page_param = params.pop(self.page_param, None)
        if page_param:
            try:
                page = int(page_param)
                if page < 1:
                    raise ValueError
            except ValueError:
                page = 1
        else:
            page = 1

        try:
            paginators_data = request.paginators
        except:
            paginators_data = request.paginators = {'_tg_paginators_params':{}}

        paginators_data['_tg_paginators_params'][self.page_param] = page_param
        paginators_data[self.name] = paginator = Bunch()

        paginator.paginate_page = page or 1
        items_per_page = params.pop(self.items_per_page_param, None)
        if items_per_page:
            try:
                items_per_page = min(
                    int(items_per_page), self.max_items_per_page)
                if items_per_page < 1:
                    raise ValueError
            except ValueError:
                items_per_page = self.items_per_page
        else:
            items_per_page = self.items_per_page
        paginator.paginate_items_per_page = items_per_page
        paginator.paginate_params = params.copy()
        paginator.paginate_params.update(paginators_data['_tg_paginators_params'])
        if items_per_page != self.items_per_page:
            paginator.paginate_params[self.items_per_page_param] = items_per_page

    def before_render(self, remainder, params, output):
        if not isinstance(output, dict) or not self.name in output:
            return

        paginator = request.paginators[self.name]
        collection = output[self.name]
        page = Page(collection, paginator.paginate_page,
            paginator.paginate_items_per_page, controller='/')
        page.kwargs = paginator.paginate_params
        if self.page_param != 'name':
            page.pager = partial(page.pager, page_param=self.page_param)
        if not getattr(tmpl_context, 'paginators', None):
            tmpl_context.paginators = Bunch()
        tmpl_context.paginators[self.name] = output[self.name] = page

rawDescription: How to place multiple @paginate turbogears 2?

description: Place multiple @paginate turbogears 2


code:
class myPanel(wx.Panel):
    def __init__(self, parent, *args, **kwargs):
        wx.Panel.__init__(self, parent, *args, **kwargs)
        bitmap = wx.EmptyBitmap(15,15)
        self.button = wx.BitmapButton(self, -1, bitmap=bitmap, size=(15,15), style=wx.NO_BORDER)
        self.Bind(wx.EVT_BUTTON, self.onClick, self.button)

def onClick(self, event):
    self.Hide()

rawDescription: Is it possible to bind an on click event on a wx.StaticText?


code:
ax = plt.gca()
ax.grid(True)

rawDescription: Getting vertical gridlines to appear in line plot in matplotlib


code:
def make_str(s):
    return s.strip("'").strip('"')

a = 'USA'
b = '"USA"'

c = "UN"
d = "'UN'"

if make_str(a) == make_str(b):
     print(make_str(a))

if make_str(c) == make_str(d):
     print(make_str(c))

rawDescription: How can I treat double quoted data and single quoted data same in Python 2.x?

description: Treat double quoted data and single quoted data same in Python 2.x


code:
import random
import matplotlib.pyplot as plt
import networkx as nx
G=nx.Graph()
G.add_edges_from([('a','b'),('b','d'),('c','e'),('b','e')])
pos=nx.spring_layout(G)
nodes=G.nodes()
random.shuffle(nodes)
blue=nodes.pop()
nx.draw_networkx_nodes(G,pos,nodelist=[blue],node_color='b')
nx.draw_networkx_nodes(G,pos,nodelist=nodes,node_color='r')
nx.draw_networkx_edges(G,pos)
plt.show()

rawDescription: Change color of nodes when in a spring layout+ networkx


code:
from subprocess import check_output

output = check_output(["upower", "-d"], universal_newlines=True)
print(output.split())

rawDescription: using split() with subprocess.check_output()

description: Using split() with subprocess.check_output()


code:
import itertools as it
data = ['IND', 'MIA', '06:37 AM', '103', 'LA', 'SUN', '06:49 AM', '-150', '120']
g = it.groupby(data, str.isalpha)
[tuple(v)+tuple(next(g)[1]) for _, v in g]

rawDescription: Grouping values inside a list

description: Grouping values inside a list


code:
import numpy as np

wtf = ['"442116.503118","442116.251106"',
     '"442141.502863","442141.247462"']

to_list = []

for nest1 in wtf:
    nest2 = nest1.split(',')
    for each in nest2:
        to_list.append(float(each.strip('"')))

to_array = np.asarray(to_list)

rawDescription: Python - convert a list in an array

description: Python - convert a list in an array


code:
import seaborn as sns
tips = sns.load_dataset("tips")
sns.set(style="ticks", palette="colorblind")
g = sns.FacetGrid(tips, col="time", size=4, aspect=.75)
g = g.map(sns.violinplot, "sex", "total_bill", "smoker", palette={"No": "b", "Yes": "w"}, inner=None, linewidth=1, scale="area", split=True, width=0.75).despine(left=True)
g.fig.get_axes()[0].legend(title= 'smoker',loc='upper left')
g.set_axis_labels('lunch','total bill')
sns.plt.show()

rawDescription: seaborn violinplots: change violin color, axes names, legend

description: Seaborn violinplots: change violin color, axes names, legend


code: map(lambda x: min(map(min, x)), zip(*a))

rawDescription: Find global min values from sub-sub-lists of different lengths


code:
import subprocess

app = subprocess.Popen(["/path/to/app", "-and", "args"], stdin=subprocess.PIPE)
app.stdin.write("python command\n")

rawDescription: Launch Application and execute script lines from python


code:
def strip_tags(value):
    """Returns the given HTML with all tags stripped."""
    return re.sub(r'<[^>]*?>', '', force_unicode(value))

rawDescription: How to strip entire HTML, CSS and JS code or tags from HTML page in python

description: Strip entire HTML, CSS and JS code or tags from HTML page in python


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

def cut_array2d(array, shape):
    arr_shape = np.shape(array)
    xcut = np.linspace(0,arr_shape[0],shape[0]+1).astype(np.int)
    ycut = np.linspace(0,arr_shape[1],shape[1]+1).astype(np.int)
    blocks = [];    xextent = [];    yextent = []
    for i in range(shape[0]):
        for j in range(shape[1]):
            blocks.append(array[xcut[i]:xcut[i+1],ycut[j]:ycut[j+1]])
            xextent.append([xcut[i],xcut[i+1]])
            yextent.append([ycut[j],ycut[j+1]])
    return xextent,yextent,blocks

nx = 900; ny = 650
X, Y = np.meshgrid(np.linspace(-5,5,nx), np.linspace(-5,5,ny))
arr = X**2+Y**2

x,y,blocks = cut_array2d(arr,(10,10))

n = 0

for x,y,block in zip(x,y,blocks):
    n += 1
    plt.imshow(block,extent=[y[0],y[1],x[0],x[1]],
               interpolation='nearest',origin='lower',
               vmin = arr.min(), vmax=arr.max(),
               cmap=plt.cm.Blues_r)
    plt.text(0.5*(y[0]+y[1]),0.5*(x[0]+x[1]),str(n),
             horizontalalignment='center',
             verticalalignment='center')

plt.xlim([0,900])
plt.ylim([0,650])
plt.savefig("blocks.png",dpi=72)
plt.show()

rawDescription: Splitting numpy array into blocks

description: Splitting numpy array into blocks


code:
__author__ = 'Girish'

import logging
import sys
import traceback
import logging.handlers

class StreamToLogger(object):
    def __init__(self, logger, log_level, std):

        self.logger = logger
        self.log_level = log_level
        self.linebuf = ''
        self.std = std

    def write(self, buf):
        for line in buf.rstrip().splitlines():
            # ^^STACK OVERFLOW^^
            self.logger.log(self.log_level, line.rstrip())
            self.std.write(line + "\n")
    def flush(self):
        self.std.flush()

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',
    filename="history.log",
    filemode='a'
)
hand = logging.handlers.TimedRotatingFileHandler("bot.log", when="S", interval=20)
# my attempt at handling

stdout_logger = logging.getLogger('STDOUT')

sl = StreamToLogger(stdout_logger, logging.INFO, sys.__stdout__)

stderr_logger = logging.getLogger('STDERR')
stderr_logger.addHandler(hand) #here

sl = StreamToLogger(stderr_logger, logging.ERROR, sys.__stderr__)
sys.stdout = sl
for i in range(2):
    sl.write("is this working")

rawDescription: Stack overflow on logging python module

description: Stack overflow on logging python module


code:
from datetime import datetime

string = '1856-00-00 00:00:00'

try:
    date = datetime.strptime(string, '%Y-%m-%d %H:%M:%S')
except ValueError:
    date = datetime(1960, 1, 1, 0, 0, 0)

print(date)

rawDescription: Python DateTime Issues

description: Python DateTime Issues


code:
def set_property(cls, name, attr, docstring):
    def getter(self):
        return getattr(self, attr)
    prop = property(getter, None, None, docstring)
    setattr(cls, name, prop)

for name in attributes:
    attr = '_' + name
    docstring = "str: This class' {}".format(name)
    set_property(SomeClass, name, attr, docstring)

rawDescription: Python object properties with docstrings from a dict


code:
import bs4 as bs

content = '''5
xxx10'''

soup = bs.BeautifulSoup(content)
print(soup('span', {'class': 'b'})[0].next_sibling)
# 10

print(soup('span', {'class': 'b'})[0].next_sibling.string)
# 10

rawDescription: Getting tag after tag?

description: Getting tag after tag


code:
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates

times = pd.date_range('2015-10-06', periods=500, freq='10min')

fig, ax = plt.subplots(1)
fig.autofmt_xdate()
plt.plot(times, range(times.size))

xfmt = mdates.DateFormatter('%d-%m-%y %H:%M')
ax.xaxis.set_major_formatter(xfmt)

plt.show()

rawDescription: How to show date and time on x axis in matplotlib

description: Show date and time on x axis in matplotlib


code:
line = next(inf, '') # a file is an iterator over lines
ignoreLines = all((s == '0') for s in line.split()) # ignore if all zeros

rawDescription: Removing code from a vrml (wrl) file, selectively


code:
import curses
import time

mywindow = curses.initscr()

matrix = [[3,2,3],[1,2,1],[2,8,6]]

def updateMatrix(m):
    m[1][1] = m[1][1] * 2
    return m

def getMarixString(m):
    x = ''
    for row in m:
        x += ' '.join(str(item) for item in row)
        x += "\n"
    return x

z = 10
while z > 1:
    matrix = updateMatrix(matrix)
    mywindow.addstr(0,0, getMarixString(matrix))
    mywindow.refresh()
    z -= 1
    time.sleep(3)

curses.endwin()
quit()

rawDescription: Print and update a matrix in-place

description: Print and update a matrix in-place


code:
data = "Name:James Score:12---Name:Alex Score:5---Name:Marley Score:8---Name:Dean Score:16"
stuff1 = filter(lambda _: ":" in _, data.split('---'))
stuff2 = dict(map(lambda x: (x.split(' ')[0].split(":")[1], x.split(' ')[1].split(":")[1]), stuff1))
for name, score in sorted(stuff2.items()):
    print("{}: {}".format(name, score))

for name, score in sorted(stuff2.items(), key=lambda x: x[1]):
    print("{} - {}".format(score, name))

rawDescription: Sorting files alphabetically and by highest to lowest


code:
import numpy as np
import scipy.optimize as opt

# y1 = interpolated values for one of the spectra
# y2 = interpolated values for the other spectra, normalise this one

def errfunc(p, a1, a2):
    return np.sum(a1 - a2 * p)

p0 = 1.  # initial guess
norm_factor = opt.fmin(errfunc, p0, args=(y1, y2))

rawDescription: Create composite spectrum from two unnormalized spectra


code:
s = select([orders.c.user_id, func.count(orders.c.id)]).\
    group_by(orders.c.user_id).having(func.count(orders.c.id) > 2)

rawDescription: sqlalchemy filter by count column

description: Sqlalchemy filter by count column


code:
from google.appengine.ext import db
#...
obj_key = db.Key.from_path('EntityClass', id_or_name)
obj = db.get(obj_key)

rawDescription: Serialize an entity key to a string in Python for GAE


rawDescription: Spider for parsing JSON in scrapy

description: Spider for parsing JSON in scrapy


rawDescription: extract columns from matrix

description: Extract columns from matrix


code:
from timeit import Timer
t = Timer('[x for x in l[::-1]]', 'l = list(range(100000))')
t.timeit(number=1000)
t = Timer('l.reverse(); [x for x in l]', 'l = list(range(100000))')
t.timeit(number=1000)
t = Timer('[x for x in reversed(l)]', 'l = list(range(100000))')
t.timeit(number=1000)

rawDescription: Need to iterate over a Python list in reverse as fast as possible


rawDescription: Conforming dataframe dtypes between read_excel() and to_excel()


code:
import datetime
now = datetime.datetime.now()
isinstance(now, datetime.datetime)

rawDescription: detect if a variable is a datetime object

description: Detect if a variable is a datetime object


rawDescription: How to access dictionary of dictionary in the interactive shell

description: Access dictionary of dictionary in the interactive shell


code:
l = "G O S J A J E K R A L J"
l.split()
''.join(l.split())

rawDescription: Python nice print

description: Python nice print


rawDescription: execute an specific method of the instances in a list in python

description: Execute an specific method of the instances in a list in python


code:
import time

consumption = "300"
spend = "5000"

def create_report(consumption, spend):
    # '/' is used for path like `C:/Program Files/bla bla` so you can't use it as a file name
    date = time.strftime("%d_%m_%Y")
    date = date + ".txt"
    file = open(date, "w")
    # NameError: name 'pastdate' is not defined
    # file.write("Since: ", pastdate)

    # The method `write()` was implemented to take only one string argument. So ',' is replaced by '+'
    file.write("\n Consumption in £: " + consumption)
    file.write("\n Overall spend in £: " + spend)
    file.close()

create_report(consumption, spend)

rawDescription: How do I create a text file through python?

description: Create a text file through python


code:
new_list = set()
outfile = open("final_downloads/malicious_ips", "w")
for line in open("final_downloads/ip_list_clean", "r"):
        if line in open("/var/www/botwatch.txt", "r"):
                outfile.write(line)
                new_list.add(line)
outfile.close()

rawDescription: python compare and output to new file

description: Python compare and output to new file


code:
#nums_list is a 2_d list of the Entry widget id tags
#check_list are the 0's and digits of the seed values
def check_conf(self):
    # iterate over rows
    for widgets, check_values in zip(self.nums_list, self.check_list):
        #iterate over columns
        for widget, check_value in zip(widgets, check_values):
            if widget.get().isdigit():
                if widget.get() == check_value:
                    widget.config(background = 'red')

rawDescription: Checking specific list entry and the rest of the list entries


code:
fig = plt.figure()
ax = fig.add_axes()
ax.invert_xaxis()

rawDescription: loglog plots with inverted x_axis in python

description: Loglog plots with inverted x_axis in python


code:
try:
    # Python 3
    from configparser import ConfigParser
except ImportError:
    # Python 2
    from ConfigParser import ConfigParser

config = ConfigParser()
config.readfp( open( 'desiredFile' ) )

somevar = config.get( 'label2', 'variable1' )

rawDescription: Read file with "variable=value" (Windows INI) format?


code:
plt.rcParams['figure.figsize'] = (20,5) # width, height

plt.subplot( 151 ) # a fig with 1 row, 5 columns, 1st graph
plt.plot( x,y )
plt.subplot( 152 ) # 2nd graph
plt.plot( ... )
# and similarly for the next ones

plt.show()

rawDescription: How to make a row of square graphs in matplotlib

description: Make a row of square graphs in matplotlib


code:
import pygame
import math
pygame.init()
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock()

# some helpful vector math functions
def normalize(v):
    vmag = magnitude(v)
    return [v[i]/vmag  for i in range(len(v))]
def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))
def add(u, v):
    return [ u[i]+v[i] for i in range(len(u)) ]

class Paddle(pygame.sprite.Sprite):
    def __init__(self, start_pos, up_key, down_key):
        pygame.sprite.Sprite.__init__(self)
        # the image is just a white rect
        self.image = pygame.surface.Surface((20, 100))
        self.image.fill(pygame.color.Color('White'))
        self.image.set_colorkey(pygame.color.Color('Black'))
        self.rect = self.image.get_rect(topleft=start_pos)
        # using a mask so we can use pixel perfect collision
        self.mask = pygame.mask.from_surface(self.image)
        self.up_key, self.down_key = up_key, down_key
    def update(self, pressed):
        if pressed[self.up_key]:   self.rect.move_ip(0, -3)
        if pressed[self.down_key]: self.rect.move_ip(0,  3)
        # keep the paddle inside the screen
        self.rect.clamp_ip(pygame.display.get_surface().get_rect())

class Ball(pygame.sprite.Sprite):
    def __init__(self, start_pos):
        pygame.sprite.Sprite.__init__(self)
        # the image is just a white ball
        self.image = pygame.surface.Surface((20, 20))
        self.rect = self.image.get_rect(center=start_pos)
        pygame.draw.circle(self.image, pygame.color.Color('White'), self.image.get_rect().center, 10)
        self.image.set_colorkey(pygame.color.Color('Black'))
        # using a mask so we can use pixel perfect collision
        self.mask = pygame.mask.from_surface(self.image)
        # the vector we use to move the ball
        self.move_v = (1, 0.7)
        # store the absolute position in self.pos
        # because a rect can only use integers
        self.pos = self.rect.center
    def update(self, pressed):
        # check if the ball collides with any other sprite
        collide = [s for s in pygame.sprite.spritecollide(self, self.groups()[0], False, pygame.sprite.collide_mask) if s != self]
        if collide:
            # warning: this does not handle the case of the ball hits
            # the top or bottom of the paddle, only the sides.
            self.move_v = [-self.move_v[0], self.move_v[1]]

        # check if the ball would go out of screen
        display = pygame.display.get_surface().get_rect()
        if self.rect.top < display.top and self.move_v[1] < 0 or \
           self.rect.bottom > display.bottom and self.move_v[1] > 0:
            self.move_v = [self.move_v[0], -self.move_v[1]]

        # apply a constant speed and update the position
        move_vector = [c * 4 for c in normalize(self.move_v)]
        self.pos = add(self.rect.center, move_vector)
        self.rect.center = map(int, self.pos)

player1 = Paddle((30,  190), pygame.K_w , pygame.K_s)
player2 = Paddle((590, 190), pygame.K_UP, pygame.K_DOWN)
ball = Ball(screen.get_rect().center)
sprites = pygame.sprite.Group(player1, player2, ball)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT: break
    else:
        pressed = pygame.key.get_pressed()
        sprites.update(pressed)
        screen.fill(pygame.color.Color('black'))
        sprites.draw(screen)
        pygame.display.flip()
        clock.tick(60)
        continue
    break
pygame.quit()

rawDescription: How can I implement pygame.sprite.spritecollide to my pygame

description: Implement pygame.sprite.spritecollide to my pygame


code:
class DummyClient:
   def __init__(self):
      def callback_get_login(realm, username, may_save):
         name = raw_input("Enter your svn login : ")
         password = getpass.getpass("Enter your svn password :")
         return True, name, password, False
      self.client.callback_get_login = callback_get_login

rawDescription: Python callback inside class

description: Python callback inside class


rawDescription: python - split string with dynamic delimeter

description: Python - split string with dynamic delimeter


code:
import sqlalchemy as sa

q = (
    session
    .query(sa.func.max(Table1.date))
    .select_from(Table1, Table2)  # or any other `.join(Table2)` would do
    .filter(...)
    .order_by(Table1.c.Date.desc())
)

rawDescription: SQLAlchemy: How to select max from several tables


code:
def update_profile(message):
    list_of_updates = message['profile_updates']
    user_update_id = message['user_id']

    for update in list_of_updates['custom_permissions']:
        User.objects.filter(id=user_update_id).update(**update)

rawDescription: Django Update Model Field with Variable User Input... .update(key=value)


code:
#IMPORTS
try:
    import tkinter as tk
    import os
    from PIL import Image, ImageTk
    print("[OK] Imports")
except ValueError as error:
    print(error)
    quit()

imagesFiles = []
atualFrame = 0

#GET IMAGES FROM FOLDER
def getImageList():

    global imagesFiles

    for files in os.listdir("./images"):
        imagesFiles.append(files.split(".")[0])

    imagesFiles = sorted(imagesFiles, key = int)

#CHANGE FRAMES
def changeFrames(self):

    global atualFrame

    self.img = ImageTk.PhotoImage(Image.open("./images/" + imagesFiles[atualFrame] + ".gif"))
    self.label["image"] = self.img

    if atualFrame == len(imagesFiles) - 1:
        atualFrame = 0

    atualFrame += 1

    self.after(100, lambda: changeFrames(self))

class mainPage(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        getImageList()

        self.label = tk.Label(self)
        self.label.pack()

        changeFrames(self)

app = mainPage()
#app.geometry("600x600")
#app.config(cursor = "none")
#SET FULLSCREEN
#app.attributes("-fullscreen", True)
app.mainloop()

rawDescription: How to put a moving gif image in Canvas using Class in Python 3.x

description: Put a moving gif image in Canvas using Class in Python 3.x


code:
...
res = req.read().decode('utf-8')
res = "".join(filter(str.strip, res.split('\n'))) # remove blank lines
response_file = open(response_file_path, 'w')
response_file.write(res)
...

rawDescription: Python urllib response returns file with added blank lines


code: sum([f.subs(dict(k=k)) for k in u])

rawDescription: Sum SymPy expression over NumPy array

description: Sum SymPy expression over NumPy array


rawDescription: Get parents objects using field of Child model in Django


code:
def get_focus(request):
    return {'focus': request.GET.get('focus', '')}

rawDescription: Mimic Stack Overflow's focus/jump to a section and fade from yellow highlight effect using Django


code:
import json

data_file = '/path/to/file'
# Load current state from file
contents = json.load(data_file)
# Do something
# ....
# ....
# Change values
contents['firstarg'] = firstarg
# Save to file
json.dump(contents, data_file)

rawDescription: Python Shelve like requirement

description: Python Shelve like requirement


code:
inv_c = defaultdict(list)
for k, v in c.iteritems():
    inv_c[v].append(k)

rawDescription: Iterate over items in a Counter by counts


rawDescription: Plotting Two Solutions with the Same Drive Strength on One Graph


code:
...
import cPickle

rf = RandomForestRegresor()
rf.fit(X, y)

with open('path/to/file', 'wb') as f:
    cPickle.dump(rf, f)

# in your prediction file

with open('path/to/file', 'rb') as f:
    rf = cPickle.load(f)

preds = rf.predict(new_X)

rawDescription: Save python random forest model to file

description: Save python random forest model to file


rawDescription: How do I call the parent method of a class inside completely non-related class?

description: Call the parent method of a class inside completely non-related class


code:
import shutil
from contextlib import closing

with closing(opener.open(request)) as src, open(filename, "wb") as dest:
    shutil.copyfileobj(src, dest)

rawDescription: Python 3 FancyURLopener cookie handling

description: Python 3 FancyURLopener cookie handling


code:
class Migration(SchemaMigration):
    def forwards(self, orm):
        for manufacturer in orm.Manufacturer.objects.all():
             for car in manufacturer.car.all():
                  car.manufacturer = manufacturer
                  car.save()

rawDescription: Django: convert ManyToManyField to ForeignKey


code:
import matplotlib.pyplot as plt
f,a = plt.subplots(1,1)
a.plot([1,2])
ticks = a.xaxis.get_ticklabels()
for tick in ticks[::2]:
    tpos = tick.get_position()
    tick.set_position((tpos[0],tpos[1]-0.05))

rawDescription: matplotlib x label placement

description: Matplotlib x label placement


code:
# sudo apt-get install apache2 apache2.2-common apache2-mpm-prefork apache2-utils libexpat1 ssl-cert

# sudo apt-get install libapache2-mod-wsgi

# sudo service apache2 restart

rawDescription: Install WSGI in my apache localhost Ubuntu 12.04


code:
import numpy as np
from scipy.ndimage.filters import gaussian_filter as gaussian

# Test data parameters
w = 800
h = 1200
npts = 250

# generate data
xvals = np.random.randint(w, size=npts)
yvals = np.random.randint(h, size=npts)

# Heatmap parameters
gaussianSize = 250
nbreaks = 25

# Preliminary function definitions
def populateMat(w, h, xvals, yvals):
    container = np.zeros((w,h))

    for idx in range(0,xvals.size):
        x = xvals[idx]
        y = yvals[idx]
        container[x,y] += 1

    return container

# Create the data matrix
dmat = populateMat(w,h,xvals,yvals)

# Convolve
dmat2 = gaussian(dmat, gaussianSize/7)

# Scaling etc
dmat2 = dmat2 / dmat2.max()
dmat2 = np.round(nbreaks*dmat2)/nbreaks

# Show
imshow(dmat2)

rawDescription: Matlab vs Python 2D convolution performance


code:
import os

counter_file = open(r'./counter_file.txt', 'r+')
content_lines = []

for line in counter_file:
        if 'counter=' in line:
                line_components = line.split('=')
                int_value = int(line_components[1]) + 1
                line_components[1] = str(int_value)
                updated_line= "=".join(line_components)
                content_lines.append(updated_line)
        else:
                content_lines.append(line)

counter_file.seek(0)
counter_file.truncate()
counter_file.writelines(content_lines)
counter_file.close()

rawDescription: how to update a variable in a text file

description: Update a variable in a text file


code:
import tkinter
import tkinter.messagebox as messagebox

class Creator(object):

    def __init__(self):

        root = self.root = tkinter.Tk()

        # Main Frame
        f_main = tkinter.Frame(root, borderwidth=6, relief='flat')
        f_main.grid(row=0, column=0, sticky='nsew')

        # Text widget and frame
        f_txt = tkinter.Frame(f_main, borderwidth=2, relief="sunken")
        f_txt.config(width=768, height=768)
        f_txt.pack(padx=4, pady=4, side="bottom", fill="both", expand=True)

        my_txt = self.text = tkinter.Text(f_txt)
        my_txt.config(undo=True, wrap='word')
        my_txt.grid(row=0, column=0, sticky="nsew")
        my_txt.bind("<ButtonRelease-3>", self.test)
        my_txt.focus_set()

    def test(self, event=None):
        txt = str(self.text)
        a = "::tk::TextPrevPos {} current tcl_wordBreakBefore".format(txt)
        b = "::tk::TextNextPos {} current tcl_wordBreakAfter".format(txt)
        ind1 = self.root.tk.eval(a)
        ind2 = self.root.tk.eval(b)
        x = self.text.get(ind1, ind2)
        messagebox.showinfo('info', x)

GUI = Creator()
GUI.root.mainloop()

rawDescription: wordend doesn't consider an apostrophe

description: Wordend doesn't consider an apostrophe


code:
username = selenium.find_element_by_id("username")
password = selenium.find_element_by_id("password")

username.send_keys("YourUsername")
password.send_keys("Pa55worD")

selenium.find_element_by_name("submit").click()

rawDescription: Fill username and password using selenium in python


code:
import plotly.plotly as py
from plotly.graph_objs import *
py.sign_in('', '')
data = Data([
    Bar(
        x=['Sivaranjani S', 'Vijayalakshmi C', 'Rajeshwari S', 'Shanthi Priscilla', 'Pandiyaraj G', 'Kamatchi S', 'MohanaPriya', 'Madhumitha G', 'Franklin Alphones Raj J', 'Akfaris Almaas', 'Biswajit Champati', 'Priya R', 'Rekha Rajasekaran', 'Sarath Kumar B', 'Jegan L', 'Karthick A', 'Mahalakshmi S', 'Ragunathan V', 'Anu S', 'Ramkumar KS', 'Uthra R'],
        y=[1640, 1394, 1390, 1313, 2166, 1521, 1078, 1543, 780, 1202, 1505, 2028, 2032, 1769, 1238, 1491, 1477, 1329, 2038, 1339, 1458],
        text=['Scuti', 'Scuti', 'Cygni', 'Scorpii', 'Scuti', 'Pollux', 'Scorpii', 'Pollux', 'Scuti', 'Pollux', 'Scorpii', 'Scorpii', 'Scuti', 'Cygni', 'Scorpii', 'Scuti', 'Scuti', 'Pollux', 'Scuti', 'Pollux', 'Pollux']
    )
])

layout = Layout(
    paper_bgcolor='rgba(0,0,0,0)',
    plot_bgcolor='rgba(0,0,0,0)'
)

fig = Figure(data=data, layout=layout)

plot_url = py.plot(fig, filename='transparent-background')

rawDescription: Python -- Setting Background color to transparent in Plotly plots


code:
plotdate = []
for idx, val in enumerate(date):
    if idx%5 == 0:
        plotdate.append(val)
    else:
        plotdate.append('')

rawDescription: Matplotlib tick frequency

description: Matplotlib tick frequency


code:
#!usr/bin/python
import os

os.chdir('./P574/J0998-1034')
os.system('vap -c freq *.SFTC > 1400list.txt')

rawDescription: How to write the output of my programme to a file or list

description: Write the output of my programme to a file or list


code:
class HoursOnDay(models.Model):
    is_open = models.BooleanField()
    open = models.TimeField(null=True)
    closed = models.TimeField(null=True)

class Day(models.Model):
    hours = models.ManyToManyField(HoursOnDay)

class Business(models.Model):
    days = models.ManyToManyField(Day)

rawDescription: Array of foreign keys in Django Model

description: Array of foreign keys in Django Model


code:
f = open('UserDetails','a')
name = input("Name? ")
f.write ("{} ".format(name))
age = input("Age? ")
f.write ("{}\n".format(age))
f.close ()

rawDescription: How to format the file output Python 3

description: Format the file output Python 3


code:
from flask import Flask, request, make_response
import csv
import StringIO

app = Flask(__name__)

@app.route('/')
def landing():
    return """<form action="data" method="post">
            <input type="submit" name="submit" value="Get Data">
         </form>"""

@app.route('/data', methods=['POST'])
def data():
    if request.method == 'POST':
        if request.form['submit'] == 'Get Data':
            csvlist = [['item 1', 'item2'], ['box1', 'box2']]

            si = StringIO.StringIO()
            cw = csv.writer(si)
            cw.writerows(csvlist)
            output = make_response(si.getvalue())
            output.headers["Content-Disposition"] = "attachment; filename=export.csv"
            output.headers["Content-type"] = "text/csv"
            return output

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

rawDescription: Using Flask button to download list of lists to CSV file


code:
class SomeClass:
    def __init__(self):
        from Smith import John
        self.imp=John
    def run(self, args):
        self.imp.dosmth()

rawDescription: Importing an object to a class

description: Importing an object to a class


code:
from py4j.java_gateway import JavaGateway
gateway = JavaGateway()                        # connect to the JVM
java_object = gateway.jvm.mypackage.MyClass()  # invoke constructor
other_object = java_object.doThat()
other_object.doThis(1,'abc')
gateway.jvm.java.lang.System.out.println('Hello World!') # call a static method

rawDescription: Using a java library from python

description: Using a java library from python


code:
def combiner(itemkey, methodname, *a, **k):
  def keyextractor(container):
    item = container[itemkey]
    method = getattr(item, methodname)
    return method(*a, **k)
  return keyextractor

rawDescription: python: combine sort-key-functions itemgetter and str.lower

description: Python: combine sort-key-functions itemgetter and str.lower


rawDescription: Python matrix in matrix in matrix

description: Python matrix in matrix in matrix


code:
totalRent_dict = {}

for d in data:
    accountLabelType = None
    for (date, details) in d['nightlyDetails'].items():
        for (key, value) in details.items():
            if key == 'accountLabelType':
                accountLabelType = value
    if accountLabelType:
        try:
            totalRent_dict[accountLabelType] += d['totalRent']
        except KeyError:
            totalRent_dict[accountLabelType] = d['totalRent']

rawDescription: Make a dictionary out of values on a json file


code:
import os
import shutil

for root, dirs, files in os.walk('.'):  # replace the . with your starting directory
   for file in files:
      path_file = os.path.join(root,file)
      shutil.copy2(path_file,'destination_directory') # change you destination dir

rawDescription: How to copy all files from a folder (including sub-folder) while not copying the folder structure in python

description: Copy all files from a folder (including sub-folder) while not copying the folder structure in python


code:
from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://test.com")

driver.save_screenshot("screenshot.png")

driver.close()

rawDescription: Open website and save as image

description: Open website and save as image


code:
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        print(os.path.join(root, name))

rawDescription: Read structure in files python

description: Read structure in files python


code: dct[id(lst)] = lst

rawDescription: How to store a hashtable of lists in Python (hashed by identity)?

description: Store a hashtable of lists in Python (hashed by identity)


code:
auth.settings.allow_basic_login = True

@service.xmlrpc
def example(temp):
    return ...

@auth.requires_login()
def call(): return service()

rawDescription: Using xmlrpc in web2py for command line interface for a web application


rawDescription: Getting just the current directory without the full path in python


code:
python = sys.executable
os.execl(python, python, * sys.argv)

rawDescription: Python - How can I essentially "Restart" my program?


code:
class MyModel(models.Model):
    my_field = models.DecimalField(max_digits=15, decimal_places=6)

rawDescription: Django model field for PostgreSQL NUMERIC data type


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

fig, axes = plt.subplots(nrows=2,
                         ncols=1,
                         sharex=True)

df1 = pd.DataFrame(
    data = np.random.rand(25, 1),
    index=pd.date_range('2015-05-05', periods=25),
    columns=['DF1']
)

df2 = pd.DataFrame(
    data = np.random.rand(25, 1),
    index=pd.date_range('2015-04-10', periods=25),
    columns=['DF2']
)

df3 = pd.DataFrame(
    data = np.random.rand(50, 1),
    index=pd.date_range('2015-03-20', periods=50),
    columns=['DF3']
)

df3 = df3.reindex(index=df3.index.union(df2.index).union(df1.index))

df1.plot(ax=axes[0], linewidth=2, color='b', linestyle='solid')
df2.plot(ax=axes[0], linewidth=2, color='b', linestyle='dashed')
df3.plot(ax=axes[1])

plt.show()

rawDescription: Shared x axes in Pandas Python

description: Shared x axes in Pandas Python


code:
df["genes"] = df["genes"].str.split().str[0]
df

rawDescription: Remove characters after whitespace for every row in a Pandas column


code:
def build_tree(nodes):
    # create empty tree to fill
    tree = {}

    # fill in tree starting with roots (those with no parent)
    build_tree_recursive(tree, None, nodes)

    return tree

def build_tree_recursive(tree, parent, nodes):
    # find children
    children  = [n for n in nodes if n.parent == parent]

    # build a subtree for each child
    for child in children:
    	# start new subtree
    	tree[child.name] = {}

    	# call recursively to build a subtree for current node
    	build_tree_recursive(tree[child.name], child, nodes)

rawDescription: Converting tree list to hierarchy dict

description: Converting tree list to hierarchy dict


code:
from PIL import Image

image_samples = []

im = Image.open("input.tif")
sample_dimensions = (16,16)

for box in get_all_corner_combinations(im, sample_dimensions):

    image_samples.append(im.crop(box))

classifier = YourClassifier()

classifications = []

for sample in image_samples:
    classifications.append (classifier (sample))

label = fuse_classifications (classifications)

rawDescription: Recognize images in Python

description: Recognize images in Python


code:
class Vector3D:
    def __init__(self, x, y, z):
        self._x = x
        self._y = y
        self._z = z
    def __mul__(self, other):
        return Vector3D(self._x*other._x, self._y*other._y, self._z*other._z)
    def mag(self):
        return sqrt((self._x)^2 + (self._y)^2 + (self._z)^2)
    def dot(self, other):
        temp = self * other
        return temp._x + temp._y + temp._z
    def cos_theta(self):
        #vector's cos(angle) with the z-axis
        return self.dot(Vector3D(0,0,1)) / self.mag() #(0,0,1) is the z-axis unit vector
    def phi(self):
        #vector's
        return asin( self.dot(Vector3D(0,0,1)) / self.mag() )
    def __repr__(self):
        return "({x}, {y}, {z})".format(x=self._x, y=self._y, z=self._z)
if __name__ == "__main__":
    samplevector = Vector3D(1,1,1)
    print(samplevector)
    print(samplevector.mag())
    print(samplevector*Vector3D(1,1,1))
    print(samplevector.cos_theta())
    print(samplevector.phi())

rawDescription: class vector3D member functions in python

description: Class vector3D member functions in python


code:
@require_basic_auth
class UploadFile(tornado.web.RequestHandler):
    def put(self, params):
        path = calculate_path(params)
        with open(path, 'wb') as out:
            body = self.request.get_argument('data')
            out.write(bytes(body, 'utf8'))

rawDescription: File upload with Tornado

description: File upload with Tornado


rawDescription: Creating a bigger List of Lists using a pattern


rawDescription: How can I open a Python shell at a network path in Windows?

description: Open a Python shell at a network path in Windows


code:
import cv2
import numpy as np

image = cv2.imread("ellipse.jpg", 0)

bimage = cv2.GaussianBlur(image, (3, 3), 0)
edge_image = cv2.Canny(bimage, 107, 208,
    apertureSize=3, L2gradient=False)

img2 = cv2.dilate(edge_image, np.ones((3, 3)), iterations=3)
dis_image = cv2.cvtColor(img2, cv2.COLOR_GRAY2BGR)

import scipy.ndimage as ndimage
labels, count = ndimage.label(img2)

for lab, idx in enumerate(ndimage.find_objects(labels.astype(int)), 1):
    sy = idx[0].start
    sx = idx[1].start
    y, x = np.where(labels[idx] == lab)
    ellp = cv2.fitEllipse(np.column_stack((x+sx, y+sy)))
    cv2.ellipse(dis_image, ellp, (0, 0, 255))

rawDescription: Improving my Ellipse Fitting Algorithm

description: Improving my Ellipse Fitting Algorithm


code:
df['intCode'] = pd.Categorical.from_array(df.group).labels
df

rawDescription: Recode catagorical variable as integers in Pandas


code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

element = WebDriverWait(driver, 10).until(
EC.element_to_be_clickable((By.XPATH, "/html/body/main/div/article[1]/div[4]/header/div[2]/div/div/a")));

element.click();

rawDescription: Python selenium WebdriverWait

description: Python selenium WebdriverWait


code:
inlay = img.crop((x1,y1,x2,y2)).rotate(90)
img.paste(inlay, (x1,y1,x2,y2))

rawDescription: rotating only a part of the image in python

description: Rotating only a part of the image in python


code:
# The addinfourl classes depend on fp being a valid file
# object.  In some cases, the HTTPError may not have a valid
# file object.  If this happens, the simplest workaround is to
# not initialize the base classes.
if fp is not None:
    self.__super_init(fp, hdrs, url, code)

rawDescription: How to raise HTTPError

description: Raise HTTPError


code:
class Point():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        if isinstance(other, Point):
            return Point(self.x + other.x, self.y + other.y)
        elif isinstance(other, tuple):
            return Point(self.x + other[0], self.y + other[1])
        else:
            raise TypeError("unsupported operand type(s) for +: 'Point' and '{0}'".format(type(other)))

    def __repr__(self):
        return u'Point ({0}, {1})'.format(self.x, self.y) #Remove the u if you're using Python 3

rawDescription: Add method that works with either a Point Object or a tuple


code:
import glob
import os

last_file = None
time=0
for i in glob.glob("Hello.txt_*"):
    if os.path.getctime(i) > time:
        last_file = i

rawDescription: Reading files based on file name and not data type


code:
if not index.isValid() or not index.parent().isValid():
    return

rawDescription: Context menu only for QTreeWidget children


code:
from django.db import models
from django.conf import settings
from django.core.files.storage import Storage
from azure.storage.blob import BlobService
accountName = 'accountName'
accountKey = 'accountKey'

class OverwriteStorage(Storage):
    def __init__(self,option=None):
        if not option:
            pass
    def _save(self,name,content):
        blob_service = BlobService(account_name=accountName, account_key=accountKey)
        import mimetypes

        content.open()

        content_type = None

        if hasattr(content.file, 'content_type'):
            content_type = content.file.content_type
        else:
            content_type = mimetypes.guess_type(name)[0]

        content_str = content.read()

        blob_service.put_blob(
            'mycontainer',
            name,
            content_str,
            x_ms_blob_type='BlockBlob',
            x_ms_blob_content_type=content_type
        )

        content.close()

        return name
    def get_available_name(self,name):
        return name

def upload_path(instance, filename):
    return 'uploads-from-custom-storage-{}'.format(filename)

class Photo(models.Model):
   image_file = models.ImageField(upload_to=upload_path, storage=OverwriteStorage(), null=True, blank=True )

rawDescription: How to use Azure's BlobService object to upload a file associated to a Django model

description: Use Azure's BlobService object to upload a file associated to a Django model


code:
soup = BeautifulSoup(webContent)
a = soup.find('a', href=True, text=re.compile("Next"))
if a:
    link = a["href"]

rawDescription: Going to the next page using Python 3 and BeautifulSoup 4


rawDescription: How to check unicode string to be letters, spaces and dashes only

description: Check unicode string to be letters, spaces and dashes only


rawDescription: Accessing key of MultiIndexed groupby

description: Accessing key of MultiIndexed groupby


code: grid1 = '\n'.join(' '.join(row) for row in grid)

rawDescription: How to get changing variable values into one fixed variable out of for loop?

description: Get changing variable values into one fixed variable out of for loop


rawDescription: Joining elements of a list - Python

description: Joining elements of a list - Python


code: file = io.TextIOWrapper(filearg.file, 'utf-8')

rawDescription: Uploading file as utf-8 in Python3.x

description: Uploading file as utf-8 in Python3.x


code:
from sys import argv
with open(argv[1]) as f:
    addresses = {i.split(" : ")[0] : i.split(" : ")[1] for i in f}
print(addresses[argv[2]])

rawDescription: python : read text file, extract data

description: Python : read text file, extract data


code:
import importlib

website_modules = {'Website A': 'website_a', 'Website B': 'website_b'}

# ...

website = importlib.import_module(website_modules[source_website])

# use with website.function_name

rawDescription: Using conditional imports as a way to utilize different functions with the same namespace


code:
import ctypes
libglib = ctypes.CDLL('libglib-2.0.so')
libglib.g_set_application_name("Hello World")

rawDescription: Grouped windows show script name instead of title in window list


code:
fig, ax = plt.subplots()
ax = sns.barplot(data = data, x = 'var1', color = '#007b7f')
plt.setp(ax.patches, linewidth=0)

rawDescription: Seaborn: how to set bar borders' line width or color?


code:
from django.core.management import call_command
from django.test import TestCase
from model_mommy import mommy

class IntegrationTestCase(TestCase):
    def rebuild_index(self):
        call_command('rebuild_index', verbosity=0, interactive=False)

class IntegrationTestUsers(IntegrationTestCase):
    def test_search_users_in_elasticsearch(self):
        user = mommy.make(User, first_name='John', last_name='Smith')
        user = mommy.make(User, first_name='Andy', last_name='Smith')
        user = mommy.make(User, first_name='Jane', last_name='Smith')
        self.rebuild_index()

        # Search api and verify results e.g. /api/users/?last_name=smith

rawDescription: Unit testing elastic search inside Django app


code:
import pyexiv2

# read image
metadata = pyexiv2.ImageMetadata(path_to_image)
metadata.read()

# now the metadata has been parsed and is ready to be extracted
title = metadata[Iptc.Application2.Caption][0]
imageDescription = metadata[Iptc.Application2.ImageDescription][0]

rawDescription: image title tag missing in PIL and pyexiv2 after Lightroom export

description: Image title tag missing in PIL and pyexiv2 after Lightroom export


code: new_list = [str(output[0]), str(''.join(output[1:]))]

rawDescription: Using Selenium and Python to push text to Array


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

def main():
    x = np.arange(10)
    fig, ax = plt.subplots()
    for i in range(1, 31):
        ax.plot(x, i * x, label=r'$y={}x$'.format(i))

    ax.legend(loc='upper left', bbox_to_anchor=(1.05, 1),
              ncol=2, borderaxespad=0)
    fig.subplots_adjust(right=0.55)
    fig.suptitle('Right-click to hide all\nMiddle-click to show all',
                 va='top', size='large')

    interactive_legend().show()

def interactive_legend(ax=None):
    if ax is None:
        ax = plt.gca()
    if ax.legend_ is None:
        ax.legend()

    return InteractiveLegend(ax.legend_)

class InteractiveLegend(object):
    def __init__(self, legend):
        self.legend = legend
        self.fig = legend.axes.figure

        self.lookup_artist, self.lookup_handle = self._build_lookups(legend)
        self._setup_connections()

        self.update()

    def _setup_connections(self):
        for artist in self.legend.texts + self.legend.legendHandles:
            artist.set_picker(10) # 10 points tolerance

        self.fig.canvas.mpl_connect('pick_event', self.on_pick)
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)

    def _build_lookups(self, legend):
        labels = [t.get_text() for t in legend.texts]
        handles = legend.legendHandles
        label2handle = dict(zip(labels, handles))
        handle2text = dict(zip(handles, legend.texts))

        lookup_artist = {}
        lookup_handle = {}
        for artist in legend.axes.get_children():
            if artist.get_label() in labels:
                handle = label2handle[artist.get_label()]
                lookup_handle[artist] = handle
                lookup_artist[handle] = artist
                lookup_artist[handle2text[handle]] = artist

        lookup_handle.update(zip(handles, handles))
        lookup_handle.update(zip(legend.texts, handles))

        return lookup_artist, lookup_handle

    def on_pick(self, event):
        handle = event.artist
        if handle in self.lookup_artist:
            artist = self.lookup_artist[handle]
            artist.set_visible(not artist.get_visible())
            self.update()

    def on_click(self, event):
        if event.button == 3:
            visible = False
        elif event.button == 2:
            visible = True
        else:
            return

        for artist in self.lookup_artist.values():
            artist.set_visible(visible)
        self.update()

    def update(self):
        for artist in self.lookup_artist.values():
            handle = self.lookup_handle[artist]
            if artist.get_visible():
                handle.set_visible(True)
            else:
                handle.set_visible(False)
        self.fig.canvas.draw()

    def show(self):
        plt.show()

if __name__ == '__main__':
    main()

rawDescription: Hiding lines after showing a pyplot figure


code:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
       sys.exit()
    elif event.type == KEYDOWN and event.key == K_ESCAPE:
       sys.exit()
    elif event.type == MOUSEBUTTONDOWN:
        click_position = event.pos
        if rock.point_collide(click_position):
            print('Clicked within the rock')
            clicks += 1
            # Any other events that have to happen
            #   when the rock is clicked

rawDescription: How to make a mouse event for clicks on a masked image [Pygame]

description: Make a mouse event for clicks on a masked image [Pygame]


rawDescription: numpy - how to add a value to every element in the first column of an array?

description: Numpy - how to add a value to every element in the first column of an array


code:
import inspect
from numpy import percentile
inspect.getfile(percentile)

rawDescription: Where to find source code for numpy's percentile


code:
from datetime import datetime, timedelta
import random

# Generate some random datetime objects.
d = [datetime.today() + timedelta(seconds=i*600) for i in range(10)]

def dt_to_seconds(dt):
    return 3600*dt.hour + 60*dt.minute + dt.second

s = tuple([dt_to_seconds(i) for i in d])

print(s)
# (35545, 36145, 36745, 37345, 37945, 38545, 39145, 39745, 40345, 40945)

rawDescription: Datetime tuple to seconds tuple

description: Datetime tuple to seconds tuple


code:
def writetoafile(fname):
    with open(fname, 'w') as fp:
        fp.write('Hello\n')

def test_writetofile(tmpdir):
    file = tmpdir.join('output.txt')
    writetoafile(file.strpath)  # or use str(file)
    assert file.read() == 'Hello\n'

rawDescription: writing a pytest function to check outputting to a file in python?

description: Writing a pytest function to check outputting to a file in python


rawDescription: What is the most practical python data structure for a time series of grid data?


code:
def main():
    csv_file = open('DataRecorded.csv', 'wb')
    writer = csv.writer(csv_file)
    writer.writerow(['Time', 'Current[mA]', 'Voltage[V]', 'Position',
    'Period', 'CurrentAct[mA]', 'VoltageAct[V]' ])
    tester = Tester(5) #Change number to
    timer = PeriodicTimer(0.05, tester.onTimer)
    timer.start()
    raw_input('Monitoring Current and Voltage') # Use input() in Python 3
    IPCON.disconnect()
    csv_file.close()

if __name__ == "__main__":
    main()

rawDescription: How to perform different tasks from different classes in every cycle iteration?

description: Perform different tasks from different classes in every cycle iteration


code:
ndf = merge(left=df1,right=df1,on=('c','d'),how='inner')
out = ndf[(ndf.a_x == (-1)*ndf.a_y) & (ndf.b_x == (-1)*ndf.b_y)]

rawDescription: How to find matching rows in Pandas DataFrame with identical values with same/opposite signs in certain columns?

description: Find matching rows in Pandas DataFrame with identical values with same/opposite signs in certain columns


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

def init():
    l1, = plt.plot([], [], 'r*-')
    l2, = plt.plot([], [], 'b*-')
    l3, = plt.plot([], [], 'g*-')

    return l1, l2, l3

def update_line(num):
    #Setup some dummy data based on num
    x = np.linspace(0, 2, 100)

    #Some if then else condition to decide which line to update
    if num%3:
        y1 = np.sin(2 * np.pi * (x - 0.01 * num))
        l1.set_data(x, y1)
    elif num%2:
        y2 = np.sin(2 * np.pi * (x - 0.01 * num*0.2))
        l2.set_data(x, y2)
    else:
        y3 = np.sin(2 * np.pi * (x - 0.01 * num*0.3))
        l3.set_data(x,y3)

    return l1, l2, l3

#setup figure
fig1 = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))

#Setup three different line objects
l1, = plt.plot([], [], 'r*-')
l2, = plt.plot([], [], 'b*-')
l3, = plt.plot([], [], 'g*-')

#Animate calls update line with num incremented by one each time
line_ani = animation.FuncAnimation(fig1, update_line, init_func=init,
                                    interval=50, blit=True)

plt.show()

rawDescription: Python matplotlib Plot Line2D object with animation package


code: round(random.uniform(0.1, 1.0), 10)

rawDescription: Generate random number between 0.1 and 1.0. Python


code: lambda i=i: self.onClick(i)

rawDescription: Checkbuttons and buttons: using lambda

description: Checkbuttons and buttons: using lambda


code:
center=(100,200) #Store pos by center

#In loop:
rCar=pygame.transform.rotate(car,r) #Do the rotation
size=rCar.get_size() #Store size
hSize=[n/2 for n in size] #Half the size
pos=(center[0]-hSize[0],center[1]-hSize[1])  #Substract half the size
#from the center
screen.blit(rCar,pos) #Draw

rawDescription: Pygame Image Rotation

description: Pygame Image Rotation


code:
for item in data:
    if item["parentId"] != 0:
        parents.setdefault(item["parentId"], []).append(item['id'])

rawDescription: Is there an elegant way to create a dictionary of arrays?


rawDescription: Plotting in python with rows

description: Plotting in python with rows


code:
import SimpleITK as sitk
import cv2
import numpy as np

def downsample_large_volume(img_path_list, input_voxel_size, output_voxel_size):

    scale = input_voxel_size / output_voxel_size
    resampled_zs = []

    #Resample z slices
    for img_path in img_path_list:
        z_slice_arr = cv2.imread(img_path, cv2.CV_LOAD_IMAGE_GRAYSCALE)
        z_slice_resized = cv2.resize(z_slice_arr, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
        resampled_zs.append(z_slice_resized) # Or save to disk to save RAM and use np.memmap for xz scaling

    temp_arr = np.dstack(resampled_zs)  # We seem to be in yxz space now
    final_scaled_slices = []

    # Resample xz plane at each y
    for y in range(temp_arr.shape[0]):
        xz_pane = temp_arr[y, :, :]
        scaled_xz = cv2.resize(xz_pane, (0, 0), fx=scale, fy=1, interpolation=cv2.INTER_AREA)
        final_scaled_slices.append(scaled_xz)

    final_array = np.dstack(final_scaled_slices)

    img = sitk.GetImageFromArray(np.swapaxes(np.swapaxes(final_array, 0, 1), 1, 2))
    sitk.WriteImage(img, 'scaled_by_pixel.nrrd')

rawDescription: Downsampling large 3D image in numpy

description: Downsampling large 3D image in numpy


code:
import logging
logger = logging.getLogger('myapp')
hdlr = logging.FileHandler('var/myapp.log')
hdlr2 = logging.FileHandler('var/myapp2.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
hdlr2.setFormatter(formatter)
logger.addHandler(hdlr)
logger.addHandler(hdlr2)
logger.setLevel(logging.INFO)
logger.info('a log message')

rawDescription: python logging into file as well as wxpython txt ctrl

description: Python logging into file as well as wxpython txt ctrl


code:
import tempfile
import os

class Sandbox(): # uppercase - see "PEP 8 -- Style Guide for Python Code"

    def start_tmp_dir(self): # self
        self.temp_dir = tempfile.TemporaryDirectory() # self.temp_dir
        print('tmp dir available in start_tmp_dir: ' + str(os.path.isdir(self.temp_dir.name))) # self.temp_dir
        return self.temp_dir.name # self.temp_dir

    def use_tmp_dir(self, dir_name):
        print('tmp dir available in use_tmp_dir: ' + str(os.path.isdir(dir_name)))

if __name__ == "__main__":
    sandbox = Sandbox() # uppercase and ()
    dir_name = sandbox.start_tmp_dir()
    sandbox.use_tmp_dir(dir_name)

rawDescription: How can I expand context to an entire script?

description: Expand context to an entire script


code:
class MyWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)
        self.menu=QtGui.QMenuBar()
        self.menu.addAction("do something")
        layout=QtGui.QVBoxLayout()
        layout.addWidget(self.menu)

rawDescription: Menus and toolbar

description: Menus and toolbar


code:
dest = cv.createMat(r, c, cv.CV_32FC1)
src = cv.fromarray(your_np_array)
cv.Convert(src, dest)

rawDescription: Set type for fromarray() in opencv for python


code:
def extract(dict_in, dict_out):
    for key, value in dict_in.iteritems():
        if isinstance(value, dict): # If value itself is dictionary
            extract(value, dict_out)
        elif isinstance(value, unicode):
            # Write to dict_out
            dict_out[key] = value
    return dict_out

rawDescription: how to get all keys&values in nested dict of list-of-dicts and dicts?

description: Get all keys&values in nested dict of list-of-dicts and dicts


code:
class TreeWidget(QtGui.QTreeWidget):
    def sizeHint(self):
        return QtCore.QSize(150, 75)

mw.dockWdg2 = QtGui.QDockWidget(mw)
mw.content2 = TreeWidget()
mw.dockWdg2.setWidget(mw.content2)

rawDescription: How to set QDockWidget initial (default) size in the app with no central widget (PyQt4)?

description: Set QDockWidget initial (default) size in the app with no central widget (PyQt4)


code:
class MyWidget(QWidget):
    def __init__(self, parent=None):
        super(MyWidget, self).__init__(parent)   #always provide parent!
        self.initUI()
    def initUI(self):
        self.btn = QPushButton('dia', self)
        self.le = QLineEdit(self)
        layout = QHBoxLayout()  #whatever layout you want
        layout.addWidget(self.btn)
        layout.addWidget(self.le)
        self.setLayout(layout)

class Example(QWidget):
    def __init__(self, parent=None):
        super(Example, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.mw = MyWidget(self)   # remember the parent!
        layout = QHBoxLayout()
        layout.addWidget(self.mw)
        self.setLayout(layout)

        self.resize(250, 300)
        self.center()
        self.setWindowTitle('Custom Widget Example')
        self.show()

rawDescription: PyQt - PySide Custom Widget Won't Show

description: PyQt - PySide Custom Widget Won't Show


rawDescription: Date Ordinal Output?

description: Date Ordinal Output


code:
firstNumber  = int(input("Please enter the first number: "))
secondNumber = int(input("Please enter the second number: "))

# Print twelve spaces in order to format the columns correctly, but don't
# place a newline after the print statement
print(" "*12, end="")

# Loop through all of the column header values in the first row
columnCounter = 0
while columnCounter < 10:
    # Print a single incremented column value, with a space separating each
    print("{:5}".format(firstNumber + columnCounter), end=" ")
    columnCounter = columnCounter + 1

# Add a newline to go to the next row
print("")

# Print the dashes separating the first row from the rest
print("{:5} {:}".format(" ", "-"*65))

# Print the remainder of the rows in the table
rowCounter = 0
while(rowCounter < 10):
    # Print the left-hand side value
    print("{:5} {:5}".format(secondNumber, "|"), end=" ")

    downSolution = firstNumber * secondNumber

    # Loop through the values for all columns for this row
    columnCounter = 0
    while(columnCounter < 10):
        print("{:5}".format(downSolution + secondNumber*columnCounter), end= " ")
        columnCounter = columnCounter + 1

    secondNumber = secondNumber + 1
    print("")
    rowCounter = rowCounter + 1

rawDescription: while loop multiplication table python

description: While loop multiplication table python


code:
from django.contrib.auth.models import Group, User

class FamilyManager(models.Manager):
    """
    Lets us do querysets limited to families that have
    currently enrolled students, e.g.:
        Family.has_students.all()
    """
    def get_query_set(self):
        return super(FamilyManager, self).get_query_set().filter(student__enrolled=True).distinct()

class Family(Group):
    notes = models.TextField(blank=True)

    # Two managers for this model - the first is default
    # (so all families appear in the admin).
    # The second is only invoked when we call
    # Family.has_students.all()
    objects = models.Manager()
    has_students = FamilyManager()

    class Meta:
        verbose_name_plural = "Families"
        ordering = ['name']

    def __unicode__(self):
        return u'%s' % (self.name)

rawDescription: How do I extend the Django Group model?

description: Extend the Django Group model


code:
def find_index(name,l=sav) :
    for i,j in enumerate(l) :
         if name in j :
              return ('index is : {}'.format(i))

find_index('Harvey',sav)

rawDescription: Finding an array subsection index from one string within it (python 3.4.2)


code:
try:
    from functools import wraps
except ImportError:
    from django.utils.functional import wraps
from django.http import HttpRedirectResponse
from django.contrib import messages
from django.views.generic import *

def add_message(success_message=None):
    def decorator(func):
        def inner(request, *args, **kwargs):
            resp = func(request, *args, **kwargs)
            if isinstance(resp, HttpRedirectResponse):
                messages.success(request, message)
            return resp
        return wraps(func)(inner)
    return decorator

student_info_edit = {
  'template_name': 'myapp/student/form.html',
  'template_object_name': 'student',
  'form_class':  studentForm,
}

student_info_new = {
  'template_name': 'myapp/student/form.html',
  'form_class':  studentForm,
  'post_save_redirect': '/myapp/students/',
}

urlpatterns += patterns('',
  url(r'^students/$', list_detail.object_list, { 'queryset': Student.objects.all() }, name="students"),
  url(r'^students/(?P<object_id>\d+)/$', add_message("Student record updated successfully")(create_update.update_object), student_info_edit, name="student_detail"),
  url(r'^students/new$', add_message("The student was added successfully.")(create_update.create_object), student_info_new, name="student_new"),
)

rawDescription: how to send success message if we use django generic views

description: Send success message if we use django generic views


code:
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User
from perfil.models import *

class Command(BaseCommand):

    help = 'What does this do? '

    def handle(self, *args, **options):
        for user in usuarios:
            profiles = Perfil.objects.filter(user=user)
            create_task = Task.objects.create(user=user)

rawDescription: Execute Django shell command as cron

description: Execute Django shell command as cron


code:
fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

rawDescription: Change values on matplotlib imshow() graph axis


rawDescription: lxml - get attribute of child based on parent class

description: Lxml - get attribute of child based on parent class


rawDescription: Union python dictioniaries with function on collision


code:
from scipy.io.wavfile import read
from pydub import AudioSegment

rate, signal = read("./test/data/test1.wav")
channel1 = signal[:,0]

audio_segment = pydub.AudioSegment(
    channel1.tobytes(),
    frame_rate=rate,
    sample_width=channel1.dtype.itemsize,
    channels=1
)

# test that it sounds right (requires ffplay, or pyaudio):
from pydub.playback import play
play(audio_segment)

rawDescription: How to create a pydub AudioSegment using an numpy array?

description: Create a pydub AudioSegment using an numpy array


code:
import gtk

def set_sticky(frame):
    gdkwin = gtk.gdk.window_lookup(frame.GetHandle())
    win = gdkwin.get_user_data() # http://library.gnome.org/devel/gdk/unstable/gdk-Windows.html#gdk-window-get-user-data
    while not isinstance(win, gtk.Window):
        win = win.get_parent()
    win.stick()

rawDescription: Marking a frame as sticky with wxPython

description: Marking a frame as sticky with wxPython


code:
class MyForm(forms.ModelForm):
    accept_terms = forms.BooleanField()

    class Meta:
       model = YourModel

rawDescription: Add a simple field to django form without updating the model


rawDescription: Delete duplicates in list structure (python)


code:
def group(lst, n):
    for i in range(0, len(lst), n):
        val = lst[i:i+n]
        if len(val) == n:
            yield tuple(val)

a = 'Moscow|city|London|city|Royston Vasey|vilage'
list(group(a.split('|'), 2))

rawDescription: split string into list of tuples?

description: Split string into list of tuples


code:
import sys
from PyQt4 import QtCore, QtGui

class ElidedLabel(QtGui.QLabel):
    _width = _text = _elided = None

    def __init__(self, text='', width=40, parent=None):
        super(ElidedLabel, self).__init__(text, parent)
        self.setMinimumWidth(width if width > 0 else 1)

    def elidedText(self):
        return self._elided or ''

    def paintEvent(self, event):
        painter = QtGui.QPainter(self)
        self.drawFrame(painter)
        margin = self.margin()
        rect = self.contentsRect()
        rect.adjust(margin, margin, -margin, -margin)
        text = self.text()
        width = rect.width()
        if text != self._text or width != self._width:
            self._text = text
            self._width = width
            self._elided = self.fontMetrics().elidedText(
                text, QtCore.Qt.ElideRight, width)
        option = QtGui.QStyleOption()
        option.initFrom(self)
        self.style().drawItemText(
            painter, rect, self.alignment(), option.palette,
            self.isEnabled(), self._elided, self.foregroundRole())

class MyMainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow, self).__init__()

        self.setCentralWidget(QtGui.QLabel("main widget"))

        statusBar = QtGui.QStatusBar()
        self.setStatusBar(statusBar)

        statusBar.addWidget(ElidedLabel("first message"))
        statusBar.addWidget(ElidedLabel("second message"))
        statusBar.addWidget(ElidedLabel("a third long long long long long message"))

app = QtGui.QApplication(sys.argv)
window = MyMainWindow()
window.show()
sys.exit(app.exec_())

rawDescription: How to hide or cut a Qwidget() text when I change main window size

description: Hide or cut a Qwidget() text when I change main window size


code: print (" ".join([strlist[2]] + [strlist[0]] + strlist[4:]))

rawDescription: Print Variable/Dynamic List of String

description: Print Variable/Dynamic List of String


code:
if os.path.isfile('number.txt'):
    print('ESISTE')
    f = open('number.txt', 'r')
    data = f.read()
    f.close()
    listOfNumber = data[0:12]
    if jid[0:12] in listOfNumber:
        print("PRESENTE")
    else:
        print("DA INSERIRE")
        numberAndMessage = jid[0:12] + " " + messageContent
        listNumberAndMessage.append(data)
        listNumberAndMessage.append(numberAndMessage)

        f = open('number.txt', 'w')
        for item in listNumberAndMessage:
            f.write("%s\n" % item)
        f.close()
else: #line with error
    print('NON ESISTE')

rawDescription: Invalid syntax python else:

description: Invalid syntax python else:


code:
import numpy as np
import pylab
from PIL import Image, ImageDraw, ImageFont

#-- your data array
xs = np.zeros((20,20))

#-- prepare the text drawing
img = Image.fromarray(xs)
d = ImageDraw.Draw(img)
d.text( (2,2), "4", fill=255)

#-- back to array
ys = np.asarray(img)

#-- just show
pylab.imshow(ys)

rawDescription: Easy way to add a number as an image in a matrix?


code: self.helper.add_input(Button('cancel', "Cancel", css_class='btn', onclick="javascript:location.href = '/customeroverview';"))

rawDescription: Django crispy-forms - Custom button

description: Django crispy-forms - Custom button


rawDescription: Regex matching string python

description: Regex matching string python


code:
pattern= r"\b%s\b" % text
Product.objects.filter(name__regex = pattern)

rawDescription: Django search in the database

description: Django search in the database


code:
episodes = Episode.query.subquery()
userseries = UserSerie.query.subquery()
# Get the min air time for each of the favorite series.
min_air_times = db.session.query(
        Serie.id.label('serie_id'),
        db.func.min(episodes.c.id).label('id')
    ).filter(
        Serie.id.in_(x.id for x in u1.favorite_series)
    ).outerjoin(
        userseries,
        Serie.id == userseries.c.serie_id
    ).outerjoin(
        episodes,
        Serie.id == episodes.c.serie_id
    ).filter(
        ~episodes.c.id.in_(x.id for x in u1.watched_episodes)
    ).filter(
        episodes.c.seas_num != 0
    ).order_by(
        desc(userseries.c.last_watched)
    ).group_by(
        Serie.id
    ).subquery()
# Select the serie and episode.
shows = db.session.query(
        Serie,
        Episode
    ).join(
        Episode,
        Episode.serie_id == Serie.id
    ).join(
        min_air_times,
        db.and_(
            min_air_times.c.serie_id == Serie.id,
            min_air_times.c.id == Episode.id
        )
    ).all()

rawDescription: Flask-SQLAlchemy - First unwatched episode from series sorted by last watched


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

x=np.linspace(0,1,201)
y1=x**2
y2=np.sin(x)

fig = plt.figure()

a = fig.add_subplot(211)

a.plot(x,y1, label='y1')

lgd1 = a.legend(bbox_to_anchor = (1.27,1), borderaxespad=0.)

a = fig.add_subplot(212)
a.plot(x,y2)

fig.savefig('fig',bbox_extra_artists=(lgd1,),bbox_inches='tight')

rawDescription: Save figure with clip box from another figure


code:
from file import Card

...
card1 = Card(10, "Diamond")
# Do something with it

rawDescription: How to pass a class/module definition into another file

description: Pass a class/module definition into another file


code: SeasonIdentifier =  ['Summer' if x in Summer else 'Winter' if x in Winter else 'Other' for x in GivenMonths]

rawDescription: Python: generate a string array based on indexing


code: list_out = [x for x in list_in if list_in.count(x) > 1]

rawDescription: Add duplicted list objects to list

description: Add duplicted list objects to list


code:
from pathlib import Path
Path('a/b/c/d').parts
Path('a/b/c/d').parts[0]

rawDescription: How do you find the first element of a path?

description: Find the first element of a path


code:
# Create DB
dbpath = './test.db'
db = sqlite3.connect(dbpath)
cursor=db.cursor()
cursor.execute("""
    CREATE TABLE IF NOT EXISTS trials (
    timestamp INTEGER PRIMARY KEY, emg BLOB) """)
cursor.execute ('DELETE FROM trials')
# Define vars
now = datetime.datetime.now()
timestamp = time.mktime(now.timetuple())
emg = list(range(200))
s = pickle.dumps(emg, pickle.HIGHEST_PROTOCOL)

# Store vars
cursor.execute("""
    INSERT INTO trials VALUES (?,?)""", (timestamp,s))
db.commit()

# Fetch vars
cursor.execute("""
    SELECT * FROM trials WHERE timestamp = ?""", (timestamp,))
out = cursor.fetchone()
s1 = out[1]
emg1 = pickle.loads(s1)

# Test equality
print(emg1 == emg)

rawDescription: Store sequences of data in sqllite3 (blob)


code:
import pygame
import sys

from pygame.locals import *

bif="bg.jpg"
mif="pkmn.png"

pygame.init()
FPS = 30  # changed for FPS
FPSCLOCK = pygame.time.Clock()  # changed for FPS

screen = pygame.display.set_mode ((600,375),0,32)
background = pygame.image.load(bif).convert()
mouse_c = pygame.image.load(mif).convert_alpha()

move_speed = 5  # changed for FPS
x, y = 0, 0

while True:

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pressed = pygame.key.get_pressed()
    if pressed[K_LEFT]:
        x -= move_speed
    if pressed[K_RIGHT]:
        x += move_speed
    if pressed[K_UP]:
        y -= move_speed
    if pressed[K_DOWN]:
        y += move_speed

    screen.blit(background,(0,0))
    screen.blit(mouse_c,(x,y))

    pygame.display.update()
    FPSCLOCK.tick(FPS)  # changed for FPS

rawDescription: INDEPENDENT sprite movement in "x" and "y" in pygame


code:
import re

s = open('test.sh', 'r').read()

s = re.sub(r"^export HOME=.*$", "export HOME=/new/path", s, 0, re.M)
s = re.sub(r"^export VERSION=.*$", "export VERSION=new_version", s, 0, re.M)
s = re.sub(r"^export CONNECTION=.*$", "export CONNECTION=new_connection", s, 0, re.M)

open('test.sh', 'w').write(s)

rawDescription: Replace multiple values in file in python


code:
items = ['Item1','Item2']
p1 = Panel({ 'Item1' : DataFrame(randn(4, 3)) }).reindex(items=items)
p2 = Panel({ 'Item2' : DataFrame(randn(4, 2)) }).reindex(items=items)
p4d = pd.Panel4D({ 'Label1' : p1, 'Label2' : p2 })
p4d.ix['Label1','Item1']
p4d.ix['Label1','Item2']

rawDescription: Why are the items in panel4d copied?

description: Why are the items in panel4d copied


code:
import numpy as np
x = np.array([5, -1, 3, -11, -9, 2, -10])
x[x.argmin():]

rawDescription: Obtaining highest negative value to end of data


code:
import shutil
shutil.copyfile("testcopy.txt", "testcopy.md")

rawDescription: Writing from .txt to .md in python

description: Writing from .txt to .md in python


code:
def exe(a,b):
    if a == b:
        print(1)
        return 1

rawDescription: How can i print and return a value from a function in python?

description: Print and return a value from a function in python


code:
class X:

    def some_method(self):
        print("X.some_method called on", self)

class Y:

    def some_method(self):
        print("Y.some_method called on", self)

class Foo(X,Y):

    def some_method(self):
        X().some_method()
        Y().some_method()
        print("Foo.some_method called on", self)

class Bar(X,Y):

    def some_method(self):
        X.some_method(self)
        Y.some_method(self)
        print("Bar.some_method called on", self)
Foo().some_method()
Bar().some_method()

rawDescription: Python - calling ancestor methods when multiple inheritance is involved


rawDescription: isinstance(foo, types.GeneratorType) or inspect.isgenerator(foo)?

description: Isinstance(foo, types.GeneratorType) or inspect.isgenerator(foo)


code:
class Location(models.Model):
    location_name = models.CharField()

    def __unicode__(self): #or __str__ for python 3.x
        return u'%s' % self.location_name #Or whatever field

class Person(models.Model):
    location = models.ForeignKey(Location)
    name = models.CharField()

    def __unicode__(self): #or __str__ for python 3.x
        return u'%s' % self.name #or whatever field

rawDescription: Django one-to-many form issue with form

description: Django one-to-many form issue with form


rawDescription: Finding closest values in a list of dictionary keys Python


code:
class ExampleLibrary:

    ROBOT_LIBRARY_SCOPE = 'TEST SUITE'

rawDescription: How to force Robot Framework to initialize my custom library only once

description: Force Robot Framework to initialize my custom library only once


code:
rows =int(math.ceil(len(pd.Series.unique(conversionRate['State']))/2))
fig, axes = plt.subplots(nrows=rows, ncols=2, figsize=(10,
10),sharex=True, sharey=False)
columnCounter = itertools.cycle([0,1])
rowCounter1    = 0
for element in pd.Series.unique(conversionRate['State']):
    rowCounter  = (rowCounter1)//2
    rowCounter1 = (rowCounter1+1)
    subSample = conversionRate[conversionRate['State']==element]
    axis=axes[rowCounter,next(columnCounter)]
    #ax2 = axis.twinx()
    subSample.plot(secondary_y=['conversionratio'], ax=axis)

rawDescription: Subplot secondary axis - Python, matplotlib


code:
def content_file_name(instance, filename):
    return os.path.join('media', instance.user.username, filename)

class Image(models.Model):
    ...
    content = models.FileField(upload_to=content_file_name)

rawDescription: Django: grab username of auth user foreignkey


code:
#!/usr/bin/env python
import msvcrt
from Queue import Empty, Queue
from threading import Thread

def read_keys(queue):
    for key in iter(msvcrt.getch, 'q'): # until `q`
        queue.put(key)
    queue.put(None) # signal the end

q = Queue()
t = Thread(target=read_keys, args=[q])
t.daemon = True # die if the program exits
t.start()

while True:
    try:
        key = q.get_nowait() # doesn't block
    except Empty:
        key = Empty
    else:
        if key is None: # end
            break
    # do stuff

rawDescription: Python event loop -- multithreading -- How to run two bits of code simultaneously?


code: tsr = sum(x * i for i, x in enumerate(L, 1)) / len(L)

rawDescription: Calculate a discrete mean in python

description: Calculate a discrete mean in python


code:
s
r = '<br />'
s.replace('\r\n',r).replace('\n\r',r).replace('\r',r).replace('\n',r)

rawDescription: Rendering newlines in user-submitted content (Python web app)


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

foo_proc = Popen(['foo', 'bar'], stdin=PIPE, stdout=PIPE)
yes_proc = Popen(['yes', 'y'], stdout=foo_proc.stdin)
foo_output = foo_proc.communicate()[0]
yes_proc.wait() # avoid zombies

rawDescription: How to pass the same answer to subprocess.Popen automatically?

description: Pass the same answer to subprocess.Popen automatically


code:
def fruit(food_type):
    return [k for k, v in food_type.items() if v == 'fruit']

rawDescription: Dictionaries- narrowing down a value and printing which keys belong to it - Python


code: my_list.extend(y for y in (list(x) for x in (a_objs, b_objs)) if y)

rawDescription: how to extend the list in python without empty items

description: Extend the list in python without empty items