author: Mark Twain

authorFirstName: Mark

authorLastName: Twain

noauthor: error

rawDescription: Python, properly handle Key Errors when parsing JSON object


code:
from mptt.models import MPTTModel, TreeForeignKey

class Item(MPTTModel):
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children')

rawDescription: Django related key of the same model

description: Django related key of the same model


code:
import re
s = 'new Shopify.OptionSelectors("product-select", { product: {"id":185310341,"title":"10. Design | Siyah \u0026 beyaz kalpli",'
re.search('"id":(\d+)', s).group(1)

rawDescription: Scrapy parse javascript

description: Scrapy parse javascript


code: re.compile(r"\.*RESPONSE from[^:]+:\s*TSB[\d] Duration:\s*(\d+) seconds.*?RESPONSE from[^:]+:\s*TSB[\d] Bit Rate:\s*(\d+) kbps", re.DOTALL)

rawDescription: multiline regex pattern match

description: Multiline regex pattern match


code:
#!/usr/bin/python3

#Python script to call the methods of the DBUS Test Server

import dbus

#get the session bus
bus = dbus.SessionBus()
#get the object
the_object = bus.get_object("org.my.test", "/org/my/test")
#get the interface
the_interface = dbus.Interface(the_object, "org.my.test")

#call the methods and print the results
reply = the_interface.hello()
print(reply)

reply = the_interface.string_echo("test 123")
print(reply)

the_interface.Quit()

rawDescription: Use dbus to just send a message in Python


rawDescription: Django foreignkey and tables one to many relationship


code: pd.concat([df[0], df[1]]).merge(pd.concat([df[2], df[3]]), left_index=True, right_index=True)

rawDescription: Merge many sub-dataframes in a big dataframe in a loop in python pandas


code: np.vectorize(f, otypes=[np.int32])(*np.dsplit(arr, 3))[..., 0]

rawDescription: Reducing an axis with numpy

description: Reducing an axis with numpy


code:
def subscribe(request):
    ...
    next = request.POST.get('next', '/some/default/url/here/')
    return redirect(next)

rawDescription: How can I get the path of form, before it produced in view, Django

description: Get the path of form, before it produced in view, Django


rawDescription: Where does Python store the name binding of function closure?


code:
' '.join(hexlify(c) for c in s_utf8.split())
b' '.join(hexlify(c) for c in s_utf8.split())    # Python 3

rawDescription: Convert unicode characters to utf-8 in python


code: ['Broccoli', 'Carrots']

rawDescription: Loop through 3 levels of lists

description: Loop through 3 levels of lists


code:
@app.route("/savedimages/<picture>")
def display_picture(picture):
    return "The picture is: {}".format(picture)

rawDescription: chmod a folder on heroku app

description: Chmod a folder on heroku app


code:
hello

world

utrecht

dafsfffewrtffffffsfsduefwerwe

rawDescription: Writing only lower case letters to file in Python


code: (options, args) = parser.parse_args()

rawDescription: python - beginner - integrating optparse in a program

description: Python - beginner - integrating optparse in a program


rawDescription: Accessing columns after applying the stack function on a pandas dataframe


code: alphabets

rawDescription: Iterating over a list while incrementing another variable at the same time


code:
class MyItem(Item):
    pass

rawDescription: Ruby like DSL in Python

description: Ruby like DSL in Python


code:
class PinochleDeck(Deck):

    def __init__(self):
        Deck.__init__(self)
        x = 0
        for i in range(4):
            for i in range(7):
                self.pop(x)
                x += 1  #NEED TO INCREMENT EVERY TIME THROUGH!!!
            x += 6
        self.extend(self)

rawDescription: Creating two copies of objects in a list


code:
from os import devnull
from subprocess import call

if __name__ == "__main__":
    with open(devnull, 'w') as dn:
        call(['echo', 'hello'], stdout=dn, stderr=dn)

rawDescription: Supressing output with os.system()

description: Supressing output with os.system()


code:
{"684x400":
    {"949520":
        {"_bannerpath": "http://tvdb.com/banners/somepath",
         "rating" : 9.000
         #etc...
        },
     "456520":
        {"_bannerpath": "http://tvdb.com/banners/somepath",
         "rating" : 9.000
         #and so on...
        }
    }
}

rawDescription: Python: comparing nested values - neater method


code:
class Student:
    def __init__(self):
        self.tests = []
        self.quizzes = []
        self.name = ""
        self.homework = []

rawDescription: Using Loops to Simplify Python Dictonaries


code:
currentUser = users.get_current_user()
logoutUrl = users.create_logout_url("/home/example/%s" % currentUser.nickname())

rawDescription: app-engine and python. how to go to subpath

description: App-engine and python. how to go to subpath


code:
def str_to_number(time_str):
    if not isinstance(time_str, str):
        return 0
    entries = [int(x) for x in time_str.split(':')]
    minutes = entries[0]
    sec = entries[1]
    return minutes + sec / 60.0

rawDescription: Pandas: convert column from minutes (type object) to number


code:
import threading
import time

class Thread1(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        time.sleep(1)
        print("Thread1")

class justAClass(object):
    def do_something(self, pause):
        while True:
            time.sleep(pause)
            print("Thread2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

if __name__ == "__main__":
    total = 0
    thread_limit = 200
    t = threading.Timer(1.0, justAClass().do_something, args=(1.0,))
    t.start()
    while True:
        if threading.activeCount() < thread_limit:
            Thread1().start()

rawDescription: Python running two threads simultaneously


code:
import re
s = "/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nouser,async    1  2"
s2 = "/dev/mapper/ex_s-l_home /home  ext4    rw,exec,auto,nodev,nouser,async    1  2"
re.findall(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', s)
re.findall(r'(?<=\s)(?!.*nodev)(?=\S*,\S*)\S+', s2)

rawDescription: python regex comma separated group

description: Python regex comma separated group


code:
c2 = a[...,np.newaxis, np.newaxis]*b
np.any(c2-c)

rawDescription: Matrix direct product retaining indices in python


rawDescription: Comparing each element between 2 sets?

description: Comparing each element between 2 sets


rawDescription: Populating form field based on query/slug factor


rawDescription: Sort and Merge two list of lists

description: Sort and Merge two list of lists


code:
from dateutil.parser import parse
from datetime import datetime

d = parse('8th April')
if (d - datetime.now()).days <= 0:
    d = datetime.date(d.year+1, d.month, d.day)

rawDescription: Date conversion with strptime()

description: Date conversion with strptime()


code:
d = {}
for i in f.split(','):
    k, v = i.split('=')
    d.setdefault(k, []).append(v)

d

rawDescription: Is there a Python standard library class like collections.Counter() but with with lists as values?


rawDescription: python : reading a datetime from a log file using regex

description: Python : reading a datetime from a log file using regex


rawDescription: How to add items in a list of tuples if the item is the same

description: Add items in a list of tuples if the item is the same


rawDescription: create a column in a pandas dataframe which calculates the difference between two rows

description: Create a column in a pandas dataframe which calculates the difference between two rows


code:
stack = inspect.stack()
the_class = stack[1][0].f_locals["self"].__class__
the_method = stack[1][0].f_code.co_name

print("I was called by {}.{}()".format(str(calling_class), calling_code_name))
# => I was called by A.a()

rawDescription: How to get the caller class name inside a function of another class in python?

description: Get the caller class name inside a function of another class in python


code:
import re
patt = re.compile('See full summary', re.DOTALL | re.IGNORECASE)
patt.findall('text See full summary')

rawDescription: Match href value with a regular expression


code:
h1, h2 = Consts('h1 h2', S)
def fun(h1 , h2):
    # possibly this should be a set() or frozenset()
    # since logically every pair should be unique?
    h1_h2_and_conds = [
        (cl_4712, me_1935),
        (cl_1871, me_1935),
        (cl_1871, me_6745),
        # ...
    ]
    and_conds = (And(h1==a, h2==b) for a,b in h1_h2_and_conds)
    return Or(*and_conds)

rawDescription: How can i have more than 255 arguments in Z3py function?

description: Have more than 255 arguments in Z3py function


code:
import textwrap
lines = textwrap.wrap(text, n, break_long_words=False)

rawDescription: Split a string into pieces of max length X - split only at spaces


rawDescription: How to create a keyframe with Python API for 3D Studio Max

description: Create a keyframe with Python API for 3D Studio Max


code:
df.city = df.city.replace({'Miami': 0, 'Boston': 1})
df

rawDescription: How to replace specific entries of a Numpy array based on its content

description: Replace specific entries of a Numpy array based on its content


rawDescription: How to take out symbols from string with regex

description: Take out symbols from string with regex


code:
figsize(10,5)
plot(range(10))

rawDescription: ipython notebook pylab fig size running twice?

description: Ipython notebook pylab fig size running twice


code:
class Person(models.Model):
    name = models.CharField(max_length=255)
    user = models.ManyToManyField(User)

    def get_transfers(self):
        return self.transfers_set.all()

rawDescription: Get self instance from within model in Django


code:
l = []
for element in list:
    l.append(function(element))
l # returns that list

rawDescription: Special chacacters in python 3.3

description: Special chacacters in python 3.3


code:
from flask import Flask, render_template
from itertools import groupby
from operator import itemgetter

app = Flask(__name__)

@app.route('/')
def main():
    names = ['Atlanta','Calgary','Berlin','Austin']
    sorted_names = sorted(names, key=str.lower)
    grouped = []
    for letter, words in groupby(sorted_names,key=itemgetter(0)):
        grouped.append(letter)
        for word in words:
            grouped.append(word)
    return render_template('index.html', grouped=grouped)

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

rawDescription: Converting Python 3.x code into jinja2 template using groupby and itemgetter()


rawDescription: Find the area between two curves ploted in matplotlib (fill_between area)


code:
app = webapp2.WSGIApplication([('/', 'handlers.MainPage'),
                               ('/sign', 'handlers.Guestbook')],
                              debug=True)

rawDescription: how to organise files with python27 app engine webapp2 framework

description: Organise files with python27 app engine webapp2 framework


code:
for attr in ['__a', '__b', '__c']:
    try:
        var = getattr(self, attr)
        # Do something
    except AttributeError:
        pass # or do something else

rawDescription: Set up a Python list from possibly non-existing variables


code:
class Ui_ClassCode(object):
    def setupUi(self, ClassCode):
        ClassCode.setObjectName("ClassCode")
        # bunch of boiler-plate ui code goes here
        self.retranslateUi(ClassCode)
        QtCore.QMetaObject.connectSlotsByName(ClassCode)

    def retranslateUi(self, ClassCode):
        pass

rawDescription: PyQt4 - Custom widget class structure?

description: PyQt4 - Custom widget class structure


code:
ENABLEPRINTER=n
PRINTERLIST=PRNT1, PRNT2

PRNT1.PORT=9600
PRNT1.BITS=8

rawDescription: Edit configuration file through python

description: Edit configuration file through python


code:
from flask.ext.wtf import Optional

def make_optional(field):
    field.validators.insert(0, Optional())

#Rest of code here...

rawDescription: What's the right way to optionally require a field using Flask-WTForms?


code: sd = sd.reset_index(level="status", drop=True).drop_duplicates()

rawDescription: Yet Another Reshaping Issue

description: Yet Another Reshaping Issue


code:
c = a * b
c = np.sum(c,axis=3)
c = np.sum(c,axis=2)

rawDescription: Numpy product or tensor product question


rawDescription: How to show and hide QtGui.QGridLayout in PySide

description: Show and hide QtGui.QGridLayout in PySide


code:
class Info(QtGui.QWidget):
    def __init__(self,  parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.initUI()
        self.callbacksRegistered = False

    def addCallbacks(self):
        nuke.addOnScriptSave(self.updateInfo)
        if nuke.root().name() == 'Root' and not nuke.modified():
            # No reason to add a scriptLoad callback if opening a
            # script would spawn a new Nuke process.
            nuke.addOnScriptLoad(self.updateInfo)

    def removeCallbacks(self):
        self.removeOnScriptSave(self.updateInfo)
        self.removeOnScriptLoad(self.updateInfo)

    def showEvent(self, event):
        if not (self.callbacksRegistered or event.spontaneous()):
            self.addCallbacks()
            self.callbacksRegistered = True

    def hideEvent(self, event):
        if self.callbacksRegistered and not event.spontaneous():
            # "Spontaneous" hide events are sent when the Nuke
            # window is minimized, which we don't really care
            # about.
            self.removeCallbacks()
            self.callbacksRegistered = False

    # Rest of the class definition omitted for brevity

rawDescription: refresh(update) widget in Nuke (vfx soft)

description: Refresh(update) widget in Nuke (vfx soft)


code:
import re
x = ['\xFF', '\x42', 'A', '\xDE', '@', '\1F']
print([i for i in x if re.search('\w',i)])

rawDescription: Python split list of strings into two containing hex strings and regular


code: [x_o_r(zip(list(a), list(b))) for a in x for b in x]

rawDescription: Python - Result returns generator instead of list (comprehension)


code:
class Listing(Base):
    __tablename__ = 'Listings'
    id = Column(Integer, primary_key=True)
    data = Column(String)
    def __init__(self,**kwargs):
       self.data = json.dumps(kwargs)
       self.data_dict = kwargs

rawDescription: Dynamic Datasets and SQLAlchemy

description: Dynamic Datasets and SQLAlchemy


rawDescription: output a csv structure from a dictionary

description: Output a csv structure from a dictionary


code:
Position: 0
Position: 0
{'name': 'foo', 'value': '1'}
Position: 17
{'name': 'bar', 'value': '2'}
Position: 23

description: Resetting csv.DictReader(StringIO.StringIO(some_string))


code:
from array import array

l = memoryview(array("l", [1, 2, 3, 4,5]))

a = l[:2]

l[0]= 10
print(l.tolist())

print(a.tolist())

rawDescription: Create alias of part of a list in python


code: f.write(struct.pack('%dB' % len(bytes), *bytes))

rawDescription: Python method for storing list of bytes in network (big-endian) byte order to file (little-endian)


code:
@get('/ws/contacts/:uid/:itemid')
def get_user_item(uid, itemid):
    return 'you passed in uid={} and itemid={}'.format(uid, itemid)

rawDescription: Mutiple arguments in bottle's route

description: Mutiple arguments in bottle's route


rawDescription: xor matrix multiplication for AES mix column stage

description: Xor matrix multiplication for AES mix column stage


code:
from bs4 import BeautifulSoup as BS4 # Version 4
from BeautifulSoup import BeautifulSoup as BS3 # Version 3
bs3soup = BS3("""

stuff

""")
bs4soup = BS4("""

stuff

""")
bs3soup.find('table', cellpadding = 4, cellspacing = 0) # None
bs4soup.find('table', cellpadding = 4, cellspacing = 0)

rawDescription: Parse table with BeautifulSoup Python

description: Parse table with BeautifulSoup Python


rawDescription: How do you "concatenate" two 32 bits int to get a 64 bits long in Python?


code: group1 = models.ForeignKey(Group1, blank=True, null=True)

rawDescription: Design ideas for a webapp in Django

description: Design ideas for a webapp in Django


code:
l_succ = stores.objects.filter(
                       order__success = True
                  ).annotate(
                       last_success=Max('order__date')
                  ).value_list (
                       'id', 'last_success'
                  )
#l_succ = [ (1, '1/1/2011'), (2, '31/12/2010'), ... ] <-l_succ result

l_last = stores.objects.annotate(
                       last_date=Max('order__date')
                  ).value_list (
                       'id', 'last_date'
                  )
#l_last = [ (1, '1/1/2011'), (2, '3/1/2011'), ... ]   <-l_last result

rawDescription: Filtering a model in Django based on a condition upon the latest child record


code:
abutton = self.mybuttons[arow][acolumn]
text_at_row_col = abutton["text"]

rawDescription: finding widgets on a grid (tkinter module)

description: Finding widgets on a grid (tkinter module)


code:
for f in foo_list:
    f.bar

rawDescription: How can I get all of the django foreignkey objects in one shot?

description: Get all of the django foreignkey objects in one shot


rawDescription: Cassandra pagination: How to use get_slice to query a Cassandra 1.2 database from Python using the cql library


code: next == "left" or next == "Left"

rawDescription: The CLI seems to ignore my function and go to another! (Python)


rawDescription: dictionary of dictionaries(nested dicts)

description: Dictionary of dictionaries(nested dicts)


code:
df['DATE']= pd.to_datetime(df['DATE'])
df.dtypes
df

rawDescription: Python Pandas: Groupby date, and accessing each group by timestamp


code:
s1 = set(input1.split('\n'))
s2 = set(input2.split('\n'))
adresses_in_only_one_file = (s1 | s2) - (s1 & s2)

rawDescription: Python - Converting long list of addresses into list of strings and intersection of lists


code:
a = [1, 2, 3]
b = a           # b is now the same list as a
a[0] = 10       # so changing that list is visible to b
b
a = [1, 2, 3]
b = a[:]        # b is now a new list, with a copy of a
a[0] = 10       # so changing the original list doesn't affect b
b
a = [1, 2, 3]
b = a           # b is now the same list as a
a = [4, 5]      # but now a is a different list
a[0] = 10
b
a = [1, 2, 3]
b = a           # b is now the same list as a
a[:] = [4, 5]   # and we've replaced the contents
b

rawDescription: python [:] notation and range

description: Python [:] notation and range


code:
class UserProfileForm(forms.ModelForm):
    ...
    category = forms.ModelChoiceField(queryset=ProgrammingCategory.objects.all(), required=False)

rawDescription: Django options field with categories

description: Django options field with categories


rawDescription: numpy array multiplication slower than for loop with vector multiplication?

description: Numpy array multiplication slower than for loop with vector multiplication


code:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('yourapplication', 'templates'))

rawDescription: How do I access session data in Jinja2 templates (Bottle framework on app engine)?

description: Access session data in Jinja2 templates (Bottle framework on app engine)


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

# Enthought library imports
from traits.api import HasTraits, Int, Instance
from traits.api import *
from traitsui.api import Item, View, Group, HGroup, VGroup
from enable.api import Component
from enable.component_editor import ComponentEditor
from traitsui.menu import OKButton, CancelButton
# Chaco imports
from chaco.tools.api import RangeSelection, RangeSelectionOverlay
from chaco.chaco_plot_editor import ChacoPlotEditor, ChacoPlotItem
from chaco.api import Plot, ArrayPlotData, OverlayPlotContainer, create_line_plot, create_scatter_plot, add_default_axes, add_default_grids, PlotAxis, PlotLabel
from chaco.tools.api import PanTool, BroadcasterTool, ZoomTool
# Numpy imports
from numpy import linspace, pi, sin, tan

def main():
    # normally this function gets its values out of other files
    x1 = -2*pi
    x2 = pi
    y1 = 0
    y2 = 2
    uebergabe = {"xlim":[x1,x2], "ylim":[y1,y2], "ranges":[x1,x2]}
    return uebergabe

class Trait(HasTraits):
    plot = Instance(Component)

    #creates the container
    container = OverlayPlotContainer(padding = 50, fill_padding = True,
                        bgcolor = "lightgray", use_backbuffer=True)
    container2 = OverlayPlotContainer(padding = 50, fill_padding = True,
                        bgcolor = "lightgray", use_backbuffer=True)

    # Traits
    xmin = Float
    xmax = Float
    ymin = Float
    ymax = Float
    rangeXMin = Float
    rangeXMax = Float

    # TraitsUI view
    traits_view = View(Group(
        HGroup(
            VGroup(Item("container", editor = ComponentEditor(), show_label = False)),
            VGroup(Item("container2", editor = ComponentEditor(), show_label = False))),
        HGroup(Item("xmin"), Item("xmax"), Item("ymin"), Item("ymax"), show_border = True, label = "Plotborders"),
        HGroup(Item("rangeXMin", label="x_min"), Item("rangeXMax", label="x_max"), show_border = True, label="Range of right plot")),
        buttons = [OKButton, CancelButton], resizable = True, width = 1000, height = 500)

    # Constructor
    def __init__(self):
        super(Trait, self).__init__()

        uebergabe = main()

        # initialize traits
        self.xmin = uebergabe["xlim"][0]
        self.xmax = uebergabe["xlim"][1]
        self.ymin = uebergabe["ylim"][0]
        self.ymax = uebergabe["ylim"][1]
        self.rangeXMin = uebergabe["ranges"][0]
        self.rangeXMin = uebergabe["ranges"][1]

        self._create_Container()

    def _create_Container(self):

        #creating dict of plots and the broadcaster
        plots = {}
        broadcaster = BroadcasterTool()

        #=====================first container===========================

        #first plot
        index = linspace(-2*pi,2*pi,1000)
        plot = create_line_plot((index, sin(index)+0.5), color = "blue", index_bounds=(self.xmin, self.xmax), value_bounds = (self.ymin, self.ymax))
        plot.bgcolor = "white"
        plot.border_visible = True
        value_mapper = plot.value_mapper
        index_mapper = plot.index_mapper
        add_default_grids(plot)
        add_default_axes(plot)

        self.sync_trait("xmin", index_mapper.range, "_low_value")
        self.sync_trait("xmax", index_mapper.range, "_high_value")
        self.sync_trait("ymin", value_mapper.range, "_low_value")
        self.sync_trait("ymax", value_mapper.range, "_high_value")

        # range selection
        self.rangeselect = RangeSelection(plot, left_button_selects = False, auto_handle_event = False)
        plot.active_tool = self.rangeselect
        plot.overlays.append(RangeSelectionOverlay(component=plot))
        self.rangeselect.on_trait_change(self.on_selection_changed, "selection")

        #adds plot to the container
        self.container.add(plot)

        # second plot
        index2 = linspace(-5*pi,4*pi,1000)
        plot = create_line_plot((index2, tan(index2)), color = "black", index_bounds=(self.xmin, self.xmax), value_bounds = (self.ymin, self.ymax))
        plot.value_mapper = value_mapper
        value_mapper.range.add(plot.value)
        plot.index_mapper = index_mapper
        index_mapper.range.add(plot.index)

        # Create a pan tool and give it a reference to the plot
        pan = PanTool(plot, drag_button="left")
        broadcaster.tools.append(pan)

        # allows to zoom
        zoom = ZoomTool(plot, tool_mode="box", always_on = False, visible = True)
        plot.overlays.append(zoom)

        #adds plot to the container
        self.container.add(plot)

        # appends broadcaster to the container
        self.container.tools.append(broadcaster)

        # title of the container
        self.container.overlays.append(PlotLabel("left plot", component=self.container, overlay_position = "top"))

        #==============end of first container===========================

        #====================second container===========================

        #first plot2
        index3 = linspace(-10*pi,10*pi,500)
        plot2 = create_scatter_plot((index3, sin(index3)), color = "blue", index_bounds=(self.rangeXMin, self.rangeXMax), value_bounds = (self.ymin, self.ymax))
        plot2.bgcolor = "white"
        plot2.border_visible = True
        plot2.value_mapper = value_mapper # the plot uses the same index and
        #plot2.index_mapper = index_mapper # value like the plots of container1
        self.sync_trait("rangeXMin", plot2.index_mapper.range, "low", False)
        self.sync_trait("rangeXMax", plot2.index_mapper.range, "high", False)

        plot2.index_mapper.range.low = 0
        plot2.index_mapper.range.high = 2
        #value_mapper.range.add(plot2.value)
        #index_mapper.range.add(plot2.index)
        add_default_grids(plot2)
        add_default_axes(plot2)

        #adds plot to the container
        self.container2.add(plot2)

        # title of the container
        self.container2.overlays.append(PlotLabel("right plot", component=self.container, overlay_position = "top"))

        index_mapper.on_trait_change(self.on_mapper_updated, "updated")

        #=============end of second container===========================

    def on_mapper_updated(self, mapper, name, value):
        if not self.rangeselect.selection:
            self.rangeXMin = mapper.range.low
            self.rangeXMax = mapper.range.high

    def on_selection_changed(self, selection):
        if selection != None:
            self.rangeXMin, self.rangeXMax = selection

gui = Trait()
gui.configure_traits()

rawDescription: Chaco: Get Index and Value out of a chaco plot


code: range_with_holes = itertools.chain(xrange(1, 6), xrange(7, 31))

rawDescription: How can I combine range() functions

description: Combine range() functions


code:
def getName():
    tempName = ""
    while True:
        tempName = raw_input("What is you name? ")
        if not len(tempName):
            continue
        if yesOrNo("Is {0} your name?".format(tempName)):
            return tempName
        else:
            continue

rawDescription: Python skipping a step

description: Python skipping a step


code:
import numpy as np
x = np.zeros(1, dtype=np.dtype([('field', '<f8', 2)]))
y = x[0]['field'].copy()
y[0] = 3
y[1] = 4
x[0]['field'] = y
x
y

rawDescription: Assigning values to a NumPy array

description: Assigning values to a NumPy array


rawDescription: how can I get the position of the nonzero values in a numpy array?

description: Get the position of the nonzero values in a numpy array


code:
def main():

    n = int(input("how many?"))
    if (n>0):
        counter=0
        total=0
        f_v = l_v = s_v = total =int (input("enter first value"))  #first value
        while counter<(n-1):
            x = int(input("enter next number"))
            total=total+x
            counter=counter+1
            if x<s_v:    #find minimum
                s_v=x
            elif x>l_v:  #find maximum
                l_v=x

        print ("the smallest value is {0}".format(s_v))
        print ("the largest value is {0}".format(l_v))
        print("the average is ", total/n)
    else:
        print("What? it is not possible to find the average, sorry ")

main()

rawDescription: smallest, largest, and average value of n numbers input by the user

description: Smallest, largest, and average value of n numbers input by the user


code:
numbers = [len(part)-1 for part in partition2d]

numbers
#>>> [2, 3, 4]

rawDescription: Count number of elements in each row in 2D list


code: [f for f in dir(np.lib.financial) if not f[0] == '_']

rawDescription: Basic Financial Library for Python

description: Basic Financial Library for Python


code:
from collections import Counter
[k for k,v in Counter("<text xx will xx be xx pasted xx here>").items() if v<8]
"".join(k for k,v in Counter("<text xx will xx be xx pasted xx here>").items() if v<8)

rawDescription: what is a way to match any char that appears less than a given number of times with regex python?

description: What is a way to match any char that appears less than a given number of times with regex python


code:
dictObj = {'foo': 'bar'}
any(isinstance(v, dict) for v in dictObj.itervalues())
dictObj = {'foo': {'spam': 'eggs'}}
any(isinstance(v, dict) for v in dictObj.itervalues())

rawDescription: How can I check if a dictionary contains a dictionary?

description: Check if a dictionary contains a dictionary


code:
if x == 0:
    somestuff_A
if not x == 0 or y == 0:
    somestuff_B

rawDescription: Python Pythonic way to organize/design if statements


code:
import pandas as pd, numpy as np

df2 = pd.DataFrame({'a':['yes','yes','no','yes','no','yes'],
                    'b':['no','yes','no','yes','no','no'],
                    'c':['yes','yes','yes','no','no', np.nan]})

data = df2.groupby('a').describe().transpose()

data['no','freq/total_count']=np.nan
data['yes','freq/total_count']=np.nan

for ind in data.index:
    data['no','freq/total_count'][ind] = data['no']['freq'][ind]/(data['no']['count'][ind]+data['yes']['count'][ind])*100
    data['yes','freq/total_count'][ind] = data['yes']['freq'][ind]/(data['no']['count'][ind]+data['yes']['count'][ind])*100

data['no','freq/total_count'] = data['no','freq/total_count'].map('{0:.0f}%'.format)
data['yes','freq/total_count'] = data['yes','freq/total_count'].map('{0:.0f}%'.format)

rawDescription: Modify describe function to remove and add columns


rawDescription: Pandas, Python. How to filter out days depending on number of observations?


code:
import numpy as np

def map_bitarray(f, b, rate):
    '''
    maps function f on a random subset of b
    :param f: the function, should take a binary array of size <= len(b)
    :param b: the binary array
    :param rate: the fraction of elements that will be replaced
    :return: the modified binary array
    '''
    c = np.copy(b)
    num_elem = len(c)
    idx = np.random.choice(range(num_elem), num_elem*rate, replace=False)
    c[idx] = f(c[idx])
    return c

f = lambda x: True
b = np.array([0,0,1,0,1], dtype='bool')
map_bitarray(f, b, 0.2)
# This will output array b with exactly 20% of the elements changed to "1"

rawDescription: Randomize part of an array

description: Randomize part of an array


code:
with open('some_file.dat', 'w') as f:
    for x in xrange(10):  # assume 10 cycles
        line = []
        # ... (here is your code, appending data to line) ...
        f.write('%r\n' % line)  # here you write representation to separate line

rawDescription: How can I append to the new line of a file while using write()?

description: Append to the new line of a file while using write()


code:
j = jinja2.Jinja2(app)
j.environment.filters.update({
        'is_list': is_list,
})

rawDescription: Testing for a List in Jinja2

description: Testing for a List in Jinja2


rawDescription: What defines Scapy send / receive?

description: What defines Scapy send / receive


code:
from operator import itemgetter
from itertools import groupby
myList = [1, 1, 1, 1, 2, 2, 2, 3, 3, 3]

[next(group) for key, group in groupby(enumerate(myList), key=itemgetter(1))]
# [(0, 1), (4, 2), (7, 3)]

rawDescription: Get index from a list where the key changes, groupby


code:
def is_transparent(colour):
    return colour[3] == 0

rawDescription: Pygame cross platform color inconsistency


code:
from functools import lru_cache

# lookup table for `choose(n, k)` for n up to 16 and k up to 4
ncr = {}
for n in range(17):
    nn   = n
    ntok = 1
    ktok = 1
    ncr[n, 0] = 1
    for k in range(1, min(n, 4) + 1):
        ntok *= nn
        nn -= 1
        ktok *= k
        ncr[n, k] = ntok // ktok

@lru_cache(maxsize=None)
def team_combos(zeros, ones, twos, threes, fours):
    """
    Calculate the number of unique second-round 4-person
      team combinations such that no team has members from
      the same first-round team.
    """
    if ones or twos or threes or fours:
        total_ways = 0
        # number of members to take from teams having one person remaining
        for b in range(min(ones, 4) + 1):
            zeros_ = zeros + b
            b_ways = ncr[ones, b]
            b_rem = 4 - b   # number of members yet to be chosen
            # number of members to take from teams having two persons remaining
            for c in range(min(twos, b_rem) + 1):
                ones_ = ones - b + c
                bc_ways = b_ways * ncr[twos, c]
                bc_rem = b_rem - c  # number of members yet to be chosen
                # number of members to take from teams having three persons remaining
                for d in range(min(threes, bc_rem) + 1):
                    e = bc_rem - d  # number of members yet to be chosen
                    # ... all of which _must_ now come from
                    #   teams having four persons remaining
                    if e <= fours:
                        bcde_ways = bc_ways * ncr[threes, d] * ncr[fours, e]
                        total_ways += bcde_ways * team_combos(zeros_, ones_, twos - c + d, threes - d + e, fours - e)
        return total_ways
    else:
        return 1

rawDescription: How to find the following desired probability using computational method (e.g. using Python)?

description: Find the following desired probability using computational method (e.g. using Python)


rawDescription: How to create an integer array in Python?

description: Create an integer array in Python


code:
import lxml.etree

root = lxml.etree.fromstring(document_string)
for elem in root.xpath('.//elem[contains(@class, "class")]'):
    print(elem.tag)
    print(elem.get('src'))

rawDescription: How to getElementsByClassName by using python xml.dom.minidom?

description: GetElementsByClassName by using python xml.dom.minidom


code:
import re

time_pattern = re.compile(r'(\d+)hr\s*(\d+)min')

hours, minutes = time_pattern.search(soup.span.get_text()).groups()

rawDescription: Regular expression for data scraping?

description: Regular expression for data scraping


code:
try:
    del array[array.index("b"):]
except ValueError:
    # "b" was not in array
    pass

rawDescription: Delete array values in python

description: Delete array values in python


code:
lists = function2(value)
if len(lists) == 4:
    list1, list2, list3, list4 = lists
    # do stuff will all 4 lists
else:
    list1, list2 = lists
    # do stuff with just 2 lists—or, if you needed the others, complain

rawDescription: Returning function values based on argument?


code:
def fifo(it, n):
    buffer = [None] * n  # preallocate buffer
    i = 0
    full = False
    for item in it:  # leaves last n items in buffer when iterator is exhausted
        if full:
            yield buffer[i]  # yield old item before storing new item
        buffer[i] = item
        i = (i + 1) % n
        if i == 0:  # wrapped around at least once
            full = True

rawDescription: Simple Way of NOT reading last N lines of a file in Python


code: [x for x, in promotion]  # works only if all items are single-item sequences.

rawDescription: how do i get rid of extra array in python?

description: Get rid of extra array in python


code:
X[7] = np.nan
my_dist = pdist(X, "euclidean")

rawDescription: specifying missing values to pdist in scipy

description: Specifying missing values to pdist in scipy


rawDescription: Image embossing in Python with PIL -- adding depth, azimuth, etc


code:
data = [np.random.random((2, 3)) for _ in range(5)]

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

axes[0].set(title='Simple Plot', ylabel='Y-label')
plot_verts(data, marker='o', ax=axes[0])

axes[1].set(title='More complex', xlabel='X-label')
plot_polygons(data, ax=axes[1], alpha=0.5, color='gray')
plot_verts(data, ax=axes[1], color='red', marker='s', s=200)

plt.show()

rawDescription: What is the best way of combining two independent plots with matplotlib?


rawDescription: Whats the best way to iterate over multidimensional array and tracking/doing operations on iteration index


code:
Max = Zombie()
Max.hit(17)
Max.upgrade(2)
Max.hp
Max.defense

rawDescription: Passing on the parameters of a function into another one?


code:
score = 0
 # already a str in python3 use raw_input in python2
word = input("Input a word: ")

for letter in word:
        if letter == "a":
            score += 5 # augmented assignment same as score = score + 5
        elif letter == "e":
            score += 4
        elif letter == "i":
            score += 3
        elif letter == "o":
            score += 2
        elif letter == "u":
            score += 1

rawDescription: Shortening down this specific code

description: Shortening down this specific code


rawDescription: Python Timenow Without Milliseconds?

description: Python Timenow Without Milliseconds


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

last_login = User.objects.get(username='bob').last_login

rawDescription: Get last_login for all users?

description: Get last_login for all users


rawDescription: Find all indices of maximum in Pandas DataFrame


code:
import itertools as it
keys = ['audio', 'video', 'sensor', 'backup']

SETTINGS_LIST = (
    ('mode_1', it.repeat(True)),
    ('mode_2', it.repeat(False)),
    ('mode_3', [True, False, False, True]),
)

SETTINGS = {mode: dict(zip(keys, values)) for mode, values in SETTINGS_LIST}

rawDescription: DRYly represent a list of settings objects


code:
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.spinner import Spinner
from kivy.base import runTouchApp
from kivy.properties import ObjectProperty

Builder.load_string('''
<MyButton>:
    size_hint: None, None
    size: 20, 20

<MyWidget>:
    MySpinner:
        id:some_id
        text:"some text"
        values:("1","2","3")
        size_hint:(None,None)
        size: root.width/4,root.height/12
''')

class MyButton(Button):
    pass

class MySpinner(Spinner):
    option_cls = ObjectProperty(MyButton) # setting this property inside kv doesn't seem to work

class MyWidget(BoxLayout):
    pass

runTouchApp(MyWidget())

rawDescription: how to set the buttons size inside a spinner in kivy?

description: Set the buttons size inside a spinner in kivy


rawDescription: Points, Vectors, Dot Product & Cross Product of python


code: context['js_paths'] = webapp.settings.template['js_paths'] + ['/static/path/to/js/file.js']

rawDescription: Python list append adding element twice

description: Python list append adding element twice


code:
# this module becomes the _lib module for one platform of either 1 or 2
if platform == 1:
    from .platform_1._lib import * # python 3 import
if platform == 2:
    from .platform_2._lib import *

rawDescription: Build python wheels for different platforms


code:
import multiprocessing, signal, os

p = multiprocessing.Process(target=library_function, args=())
p.start()

# stop the job
os.kill(p.pid, signal.SIGINT)
p.join()

rawDescription: Terminate asynchronous multiprocessing thread from gunicorn-based web session


code:
numbers_list = []

while True:
    try:
        n = int(input("Enter an integer (press ENTER to end the program): "))
    except ValueError:
        break
    else: numbers_list.append(n)

print(any(len(str(i))>2 for i in numbers_list))

rawDescription: Struggling with 'for' statement in Python


code:
import logging, logging.handlers
from custom_handlers import BufferingSocketHandler

rootLogger = logging.getLogger('')
rootLogger.setLevel(logging.DEBUG)
socketHandler = BufferingSocketHandler('localhost',
                    logging.handlers.DEFAULT_TCP_LOGGING_PORT,
                    'logging-buffer.bin')
# don't bother with a formatter, since a socket handler sends
# the event as an unformatted pickle
rootLogger.addHandler(socketHandler)

rawDescription: How to send unsent logs to python logging server when it comes back online?

description: Send unsent logs to python logging server when it comes back online


code:
foreign_string = u'6905\u897f\u963f\u79d1\u8857\uff0c\u5927\u53a6\uff03\u5927'
P = MultiFontParagraph(foreign_string, styles["Normal"],
                     [  ("Bauhaus", "C:\Windows\Fonts\\BAUHS93.TTF"),
                        ("Arial", "C:\Windows\Fonts\\arial.ttf"),
                        ("HanaMinA", 'C:\Windows\Fonts\HanaMinA.ttf')])

rawDescription: ReportLab: working with Chinese/Unicode characters


code:
from django.db.models import Q

q1 = Q(param1=a_param1, param2=a_param2)
q2 = Q(param1=b_param1, param2=b_param2)
result = MyModel.objects.filter(Q1|Q2)

rawDescription: Django filter where multiple params match one of multiple sets


code: [list(t) for t in zip(*2*[iter(x)])]

rawDescription: Getting two-tuples out of a list

description: Getting two-tuples out of a list


code:
def __iter__(self):
    for item in self._iterable:
        yield item

rawDescription: python make class iterable by returning embedded iterable

description: Python make class iterable by returning embedded iterable


code: parts = re.split('[,Xac:YZ#?*]', line)

rawDescription: Delete unusable characters or data in archive with python


code: list(sliding_range('test.txt', 10))

rawDescription: Counting the number of points in a sliding range


code:
stock_dict = dict(stock)
urls = [stock_dict.get(file, "Not found") for file in dirs]

rawDescription: Iterate two lists in python

description: Iterate two lists in python


code:
for entry in mylist:
    if 'string_to_remove' in entry:
        mylist.remove(entry)

rawDescription: reading a file that follows pattern into array

description: Reading a file that follows pattern into array


code:
result = Differ().compare(s1, s2)
foo = list(result) # foo is now ['  one', '+ tow', '- three', '?  -\n', '+ tree', '- twoo']
list(result)

rawDescription: Result of Differ.compare() vanishes after using once


code: def typecheck(obj): return hasattr(myObj, '__iter__')

rawDescription: Type checking: an iterable type that is not a string


code: thing in x

rawDescription: How does __contains__ work for ndarrays?

description: How does __contains__ work for ndarrays


rawDescription: standard python library to construct matrix

description: Standard python library to construct matrix


code: new = ''.join('\\u{:04x}'.format(ord(c)) for c in u)

rawDescription: Python: Replace character by its Unicode-representation


code:
def in_out_repsplit(inf, outf1, outf2):
    outf1 = csv.writer(open(outf1, 'wb'), delimiter=',', lineterminator='\n')
    outf2 = csv.writer(open(outf2, 'wb'), delimiter=',', lineterminator='\n')
    inf1 = csv.reader(open(inf, 'rbU'), delimiter=',')
    inf1.next()
    checklist = set()
    for row in inf1:
        id_num = str(row[7])
        if id_num not in checklist:
            outf1.writerow(row)
            checklist.add(id_num)
        else:
            outf2.writerow(row)

rawDescription: Splitting a CSV into two files by repeated cells Python


code:
from google.appengine.ext import testbed
import webtest
# ...
def setUp(self):
    tb = testbed.Testbed()
    tb.setup_env(current_version_id='testbed.version') #needed because endpoints expects a . in this value
    tb.activate()
    tb.init_all_stubs()
    self.testbed = tb

def tearDown(self):
    self.testbed.deactivate()

def test_endpoint_insert(self):
    app = endpoints.api_server([TestEndpoint], restricted=False)
    testapp = webtest.TestApp(app)
    msg = {...} # a dict representing the message object expected by insert
                # To be serialised to JSON by webtest
    resp = testapp.post_json('/_ah/spi/TestEndpoint.insert', msg)

    self.assertEqual(resp.json, {'expected': 'json response msg as dict'})

rawDescription: How to unit test Google Cloud Endpoints

description: Unit test Google Cloud Endpoints


rawDescription: And and Or confusion

description: And and Or confusion


code:
import win32com.client
from win32com.client import constants as c

xl = win32com.client.gencache.EnsureDispatch('Excel.Application')
xl.Visible = True
wb = xl.Workbooks.Add()
ws = xl.ActiveSheet
ws.Range('A1').FormulaR1C1 = 'X'
ws.Range('B1').FormulaR1C1 = 'Y'
ws.Range('A2').FormulaR1C1 = 1
ws.Range('A3').FormulaR1C1 = 2
ws.Range('A4').FormulaR1C1 = 3
ws.Range('B2').FormulaR1C1 = 4
ws.Range('B3').FormulaR1C1 = 5
ws.Range('B4').FormulaR1C1 = 6
ws.Range('A1:B4').Select()
ch = ws.Shapes.AddChart().Select()
xl.ActiveChart.ChartType = c.xlXYScatterLines
xl.ActiveChart.SetSourceData(Source=ws.Range("A1:B4"))

rawDescription: How to generate Excel spreadsheets with embedded graphs?

description: Generate Excel spreadsheets with embedded graphs


code:
class LevelListModel(QAbstractListModel):
    # [skipped]
    def addLevel(self,level):
        self.beginInsertRows(QModelIndex(), len(self.levelList), len(self.levelList))
        self.levelList.append(level)
        self.endInsertRows()
        return self.index(len(self.levelList)-1)

rawDescription: PyQt: How to change currentIndex in QComboBox when custom QAbstractListModel data changed


code:
def f(string,wrap1,wrap2):
    wrapped = False
    inner = 0
    count = 0
    holds = ['']
    for i,c in enumerate(string):
        if c == wrap1 and not wrapped:
            count += 2
            wrapped = True
            holds.append(wrap1)
            holds.append('')
        elif c == wrap1 and wrapped:
            inner += 1
            holds[count] += c
        elif c == wrap2 and wrapped and inner > 0:
            inner -= 1
            holds[count] += c
        elif c == wrap2 and wrapped and inner == 0:
            wrapped = False
            count += 2
            holds.append(wrap2)
            holds.append('')
        else:
            holds[count] += c
    return holds

rawDescription: regex split on wrapping patterns

description: Regex split on wrapping patterns


code:
def blink(rect, canvas):
    current_color = canvas.itemcget(rect, "fill")
    new_color = "red" if current_color == "white" else "white"
    canvas.itemconfigure(rect, fill=new_color)

rawDescription: Tkinter, executing functions over time

description: Tkinter, executing functions over time


rawDescription: How Accelerate factor function from SAGE


code:
import numpy as np
np.ndarray((2, 5), buffer=np.array(multi_array), dtype=int)

rawDescription: How can I implement a multi dimensional array or array of records in Python?

description: Implement a multi dimensional array or array of records in Python


code:
import numpy.ma as ma

mask1 = ma.where(y1>=y2)
mask2 = ma.where(y2>=y1)

p1 = plt.bar(x1[mask1], y1[mask1], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)
p2 = plt.bar(x2, y2, color='b', alpha=1, edgecolor='none', linewidth=0,width=0.5, log=False)
p3 = plt.bar(x1[mask2], y1[mask2], color='r', alpha=1, edgecolor='none',linewidth=0,width=0.5, log=False)

rawDescription: How do I keep the smaller value in a bar chart in front (when I cannot place the bars side by side)?

description: Keep the smaller value in a bar chart in front (when I cannot place the bars side by side)


code:
def desktop_active():
    MAX_WINDOWS = []  # Use this to store if any windows are maximised
    def foreach_window(hwnd, lParam):  #Callback function for Enumwindows etc
        if IsWindowVisible(hwnd):
            MAX_WINDOWS.append(IsZoomed(hwnd))
    EnumWindows(EnumWindowsProc(foreach_window), 0)
    if any(MAX_WINDOWS):
        return False
    if GetShellWindow() == GetForegroundWindow():
        return True  # If we have no windows max'd and the forground is the desktop

rawDescription: Python: simple 'if' statement to tell you if the user has no windows maximized


rawDescription: Date labels intersecting

description: Date labels intersecting


code:
from operator import add

dfs = (tfs
    .values()
    .flatMap(lambda kv: ((k, 1) for k in kv.keys()))
    .reduceByKey(add))

dfs.sortBy(lambda x: -x[1]).take(5)

## [('ipsum', 2),
##  ('dolor', 2),
##  ('consectetur', 1),
##  ('finibus', 1),
##  ('fringilla', 1)]

rawDescription: spark, small issue about reduceByKey

description: Spark, small issue about reduceByKey


code:
class Package(Base):
    __tablename__ = 'db_package'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    def __init__(self, name):
        self.name = name

class Deb(Base):
    __tablename__ = 'db_deb'
    id = Column(Integer, primary_key=True)
    package_id = Column(Integer, ForeignKey('db_package.id'))
    name = Column(String)
    last_time = Column(DateTime)
    def __init__(self, name, last_time):
        self.name = name
        self.last_time = last_time

    packages = relationship(Package, backref="debs")

rawDescription: how to generate this sql in sqlalchemy,i am trying hard but didn't know what to do

description: Generate this sql in sqlalchemy,i am trying hard but didn't know what to do


code:
for model in get_models(app):
    new_object = model() # Create an instance of that model
    model.objects.filter(...) # Query the objects of that model
    model._meta.db_table # Get the name of the model in the database
    model._meta.verbose_name # Get a verbose name of the model
    # ...

rawDescription: Django get list of models in application


rawDescription: XOR on two lists in Python

description: XOR on two lists in Python


code: nr = [int(i) for i in linetemp.split()]

rawDescription: How to get three integers from a specific line in a file with Python?

description: Get three integers from a specific line in a file with Python


code: parameters(my_get_params)  # should not raise an exception

rawDescription: How to validate URL parameters in Flask app?

description: Validate URL parameters in Flask app


code:
from collections import Counter
inputdict = {'B': ['J', 'K', 'L'], 'C': ['K', 'J', 'L'], 'A': ['L', 'K', 'J'], 'D': ['J', 'L', 'K'], 'E': ['L', 'J', 'K']}
site_counts = Counter(value[0] for value in inputdict.values())
site_counts

rawDescription: Counting first element in python and printing?


code:
def __init__(self, master):
    self.start=0.0
    self.end=0.0
    self.total_time=0.0
    ...

rawDescription: Binding multiple events on Tkinter Entry?


code: monthly_rainfall = daily_rainfall.resample('D', how=np.sum)

rawDescription: Calculating a cumulative deviation from mean monthly value in pandas series


rawDescription: How to merge panda dataframe based on column?

description: Merge panda dataframe based on column


rawDescription: Sort bidimentional numpy array

description: Sort bidimentional numpy array


rawDescription: How to find a open reading frame in Python

description: Find a open reading frame in Python


code:
def mongoengine_agg_doc():
    return list(MyModel.objects.aggregate({"$limit":1}))[0]

rawDescription: Mongoengine is very slow on large documents comapred to native pymongo usage


code:
RcParams({u'axes.axisbelow': True,
          u'axes.edgecolor': u'white',
          u'axes.facecolor': u'#E5E5E5',
          u'axes.grid': True,
          u'axes.labelcolor': u'#555555',
          u'axes.labelsize': u'large',
          u'axes.linewidth': 1.0,
          u'axes.prop_cycle': cycler(u'color', [u'#E24A33', u'#348ABD', u'#988ED5', u'#777777', u'#FBC15E', u'#8EBA42', u'#FFB5B8']),
          u'axes.titlesize': u'x-large',
          u'figure.edgecolor': u'0.50',
          u'figure.facecolor': u'white',
          u'font.size': 10.0,
          u'grid.color': u'white',
          u'grid.linestyle': u'-',
          u'patch.antialiased': True,
          u'patch.edgecolor': u'#EEEEEE',
          u'patch.facecolor': u'#348ABD',
          u'patch.linewidth': 0.5,
          u'xtick.color': u'#555555',
          u'xtick.direction': u'out',
          u'ytick.color': u'#555555',
          u'ytick.direction': u'out'})

rawDescription: In Jupyter, how can I use the matplotlib ggplot style by default?


code:
a, b, c = None, None, None
print(zip((a,b,c), [1,2,3]))

rawDescription: Python Variables Referecing - unexpected behavior with zip


code: set(rt) - set(dp)

rawDescription: Most pythonic means to find out if an element from one list is not a member of another list


rawDescription: Get records for multiple months in django query


code:
p = pexpect.spawn(cmd,args,timeout=None,logfile=sys.stdout)
line = p.readline()
while line:
    # DO OTHER STUFF
    line = p.readline()

rawDescription: Printing output in realtime from subprocess


code:
def someFunction():
    global pingchk
    pcName = raw_input("Please enter a pc name: ")
    pingchk = pinger(pcName, pingchk)

rawDescription: Passing variable from one funtion to another


code:
now = datetime.datetime.now(pytz.utc)
now.tzinfo == pytz.utc # returns True

now = now.astimezone(pytz.timezone('America/Los_Angeles'))
now.tzinfo == pytz.utc # returns False

rawDescription: Checking if date is in UTC format

description: Checking if date is in UTC format


code: RDD.takeOrdered(5, key = lambda x: x[1])

rawDescription: takeOrdered descending Pyspark

description: TakeOrdered descending Pyspark


code:
# SummaryInformation attributes
vm_attrs = {
    'Name': 0,
    'ElementName': 1,
    'CreationTime': 2,
    'Notes': 3,
    'NumberOfProcessors': 4,
    'ThumbnailImage': 5,
    'ThumbnailImage': 6,
    'ThumbnailImage': 7,
    'AllocatedGPU': 8,
    'EnabledState': 100,
    'ProcessorLoad': 101,
    'ProcessorLoadHistory': 102,
    'MemoryUsage': 103,
    'Heartbeat': 104,
    'UpTime': 105,
    'GuestOperatingSystem': 106,
    'Snapshots': 107,
    'AsynchronousTasks': 108,
    'HealthState': 109,
    'OperationalStatus': 110,
    'StatusDescriptions': 111,
    'MemoryAvailable': 112,
    'AvailableMemoryBuffer': 113
}

vms = client.query("select * from Msvm_ComputerSystem where Caption=\"Virtual Machine\"")
management_service = client.Msvm_VirtualSystemManagementService()[0]

for vm in vms:
    settings = vm.associators(wmi_result_class='Msvm_VirtualSystemSettingData')

    vm_original = filter(lambda x: 'Realized' in x.VirtualSystemType, settings)
    vm_snapshots = filter(lambda x: 'Snapshot' in x.VirtualSystemType, settings)

    # skipped retrieving snapshots to make it shorter, but is exactly the same
    vm_data = {'snapshots': len(vm_snapshots)}
    paths = [vm_original[0].path_()]
    summary_info = management_service.GetSummaryInformation(vm_attrs.values(), paths)
    if summary_info[0] != 0:
        raise Exception("Error retrieving information from vm '%s'" % vm.Name)

    # Note, if you do dir() on the COMObject from the summary info list, you wont find any attribute from the docs, but, trust me, if you do summary[1][0].NumberOfProcessors or any other attribute, it will work.
    vm_data.update({attr: getattr(summary_info[1][0], attr) for attr in vm_attrs.keys()})

    vms_data[vm.Name] = vm_data

rawDescription: Python WMI Hyper-v GetSummaryInformation result


code: C = pd.merge(C, A, on=['Canal', 'Gerencia'])

rawDescription: Efficient calculation on a pandas dataframe


code:
for item,nextitem in zip(values, values[1:]):
    diffs.append(nextitem-item)

rawDescription: Read other items in a python list while iterating through it


code:
s = ""
for i in range(n):
    s+=str(n)

rawDescription: Good way to append to a string

description: Good way to append to a string


rawDescription: How do i make a list a list of list?

description: Make a list a list of list


code: json.dumps({ k: self.get_argument(k) for k in self.request.arguments })

rawDescription: tornado maps GET and POST arguments to lists. How can I disable this "feature"?

description: Tornado maps GET and POST arguments to lists. How can I disable this "feature"


code:
x = 1
list(range(2, 11))
for i in range(2, 11):
    x *= i
    print(x)

rawDescription: Repeat an action a specified amount of times


rawDescription: Pythonic way to insert every 2 elements in a string


code: driver.find_element_by_xpath("//span[@title='Go To ALT+G ']").click()

rawDescription: How to select particular element in Selenium with IE Webdriver

description: Select particular element in Selenium with IE Webdriver


rawDescription: reading comma separated value from string object in python

description: Reading comma separated value from string object in python


code:
added = []
deleted = []
changed = []
for  sub_l1, sub_l2 in zip(l1, l2):
    for i in range(min(len(sub_l1), len(sub_l2))):
        if sub_l1[i] != sub_l2[i]:
            changed.append(sub_l2[i])
    if len(sub_l2) > len(sub_l1):
        added.append(sub_l2[len(sub_l1):len(sub_l2)])
    elif len(sub_l1) > len(sub_l2):
        deleted.append(sub_l1[len(sub_l2):len(sub_l1)])

rawDescription: Differences in lists of lists using Python


code: toolbar: None

rawDescription: Remove Matplotlib Toolbar from the Graph


code: f.write ("P1 skill is {0}\n".format( PlayerOneSkill + P1SkillMod))  # New line added.

rawDescription: '0' characters appering within string values when writing to a text file


rawDescription: How do I slice a Multindex timeseries dataframe on Pandas?

description: Slice a Multindex timeseries dataframe on Pandas


rawDescription: Running external program through python terminal


code: s.split('&')[1].split('=')[1].split('|') # Notice the [1] in the first split

rawDescription: Python extract text data in dynamic text format


code:
def unpack_dict(d, field, unpack):
    packed = d.pop(field)
    for item in unpack(packed):
        result = d.copy()
        result[field] = item
        yield result

lst = [
    {'item':'321,121,343','name':'abby','amount':'400'},
    {'item':'111,222,333','name':'chris','amount':'500'}
]

new_lst = [
    ud
    for d in lst
    for ud in unpack_dict(d, "item", lambda item: item.split(","))
]

rawDescription: How to split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary?

description: Split string values across a list of dictionaries, so that each part of the split string is in it's own dictionary


code:
class Foo(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.x = 0
        self.id = self.after(1000, self.callback)

    def callback(self):
        self.x += 1
        print(self.x)
        #You can cancel the call by doing "self.after_cancel(self.id)"
        self.id = self.after(1000, self.callback)

gui = Foo()
gui.mainloop()

rawDescription: Run an infinite loop in the backgroung in Tkinter


code:
self.save_model(request, new_object, form, change=False)
form.save_m2m()
for formset in formsets:
    self.save_formset(request, form, formset, change=False)

rawDescription: Django : Foreign key set not found after saving object


code:
result = {}
for key, value in theDict.items():
    if len(value) > 0:
        result[key] = value

rawDescription: How to avoid using tuples and what will this look like without list comprehension

description: Avoid using tuples and what will this look like without list comprehension


code:
from bs4 import BeautifulSoup

doc = BeautifulSoup("", "html5lib")
body = BeautifulSoup("

1

2

", "html5lib")

doc.html.body.append(body)
print(doc.html.body.ol)

rawDescription: Accessing Appended item with Beautiful Soup


code:
import imp
imp.new_module('name')

rawDescription: Python importlib's analogue for imp.new_module()


code: s = 'first - second - third'

rawDescription: Python 3 String Method?

description: Python 3 String Method


code:
from django.conf.urls.defaults import *
from django.views.generic.create_update import create_object

from my_products_app.models import Product

urlpatterns = patterns('',
    url(r'^admin/products/add/$', create_object, {'model': Product}))

rawDescription: How do I add data to an existing model in Django?

description: Add data to an existing model in Django


code:
a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
a
a[2] = 'bananas'
a

rawDescription: python numpy array of arbitrary length strings

description: Python numpy array of arbitrary length strings


code:
def run_program():
    # consoleprocess is the second module that
    # has to be able to do a callback.
    # A new Instance of the ProcessRunner class is created.

    self.progrunner = consoleprocess.ConsoleProcessRunner()
    self.progrunner.cout.connect(self.cb_update_prog_output)
    self.progrunner.quit.connect(self.cb_prog_terminated)

@QtCore.Slot(int)
@QtCore.Slot(str)
def cb_update_tv(self, data):
    # your code goes here
    pass

rawDescription: How to call a function in pyside MainWindow from another python script

description: Call a function in pyside MainWindow from another python script


code:
class Task(object):
    def __init__(self, data):
        self.cancelled = False
        self.data = data

    def cancel(self):
        self.cancelled = True

q = Queue.Queue()
t = Task("some data to put in the queue")
q.put(t)

# Later
t.cancel()

rawDescription: Cancel a task execution in a thread and remove a task from a queue


code:
#!/usr/bin/python3
# -*- coding: utf-8 -*-
##
# a python script to run a libreoffice python macro externally
#
import uno
from com.sun.star.connection import NoConnectException
from com.sun.star.uno  import RuntimeException
from com.sun.star.uno  import Exception
from com.sun.star.lang import IllegalArgumentException
def test2(*args):
    localContext = uno.getComponentContext()
    localsmgr = localContext.ServiceManager
    resolver =  localsmgr.createInstanceWithContext("com.sun.star.bridge.UnoUrlResolver", localContext )
    try:
        ctx = resolver.resolve("uno:socket,host=localhost,port=2002;urp;StarOffice.ComponentContext")
    except NoConnectException as e:
        print ("LibreOffice is not running or not listening on the port given - ("+e.Message+")")
        return
    msp = ctx.getValueByName("/singletons/com.sun.star.script.provider.theMasterScriptProviderFactory")
    sp = msp.createScriptProvider("")
    scriptx = sp.getScript('vnd.sun.star.script:fs2TimeStamp.py$fs2_TimeStamp?language=Python&location=user')
    try:
        scriptx.invoke((), (), ())
    except IllegalArgumentException as e:
        print ("The command given is invalid ( "+ e.Message+ ")")
        return
    except RuntimeException as e:
        print("An unknown error occurred: " + e.Message)
        return
    except Exception as e:
        print ("Script error ( "+ e.Message+ ")")

return(None)

test2()

rawDescription: How to call an existing LibreOffice python macro from a python script

description: Call an existing LibreOffice python macro from a python script


code:
s = pd.Series(l)
s.unique()

rawDescription: Reducing pandas series with multiple nan values to a set gives multiple nan values


code:
import csv

short = {'New York':'NY', 'NY':'NY', 'Ohio':'OH'}
entries = []

with open('data.txt', 'rb') as f_input:
    for cols in csv.reader(f_input):
        cols[2] = short[cols[2]]
        entries.append(cols)

with open('data.txt', 'wb') as f_output:
    csv.writer(f_output).writerows(entries)

rawDescription: Fixing values in columns of a csv file with python


code:
with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

rawDescription: Python 2.7 - Write and read a list from file


code:
imgobj = Image.open('x.png')
pixels = imgobj.convert('RGBA')
data = imgobj.getdata()
counts = collections.Counter(data)
print(counts[(0, 0, 0, 255)])  # or some other value

rawDescription: List all RGBA values of an image with PIL


code:
lst = [1, 3, 4, 5, 6, 7, 8]
for i in range(2, len(lst)):
    val = lst[i]
    print(val)

rawDescription: For count from 2

description: For count from 2


code: from a import A

rawDescription: module holding variables, mutable vs immutable

description: Module holding variables, mutable vs immutable


code: rline = "".join(line.findall(result))

rawDescription: Python Regex to find last occurence of digit


code:
def compareFiles():
    for eachLine in range(len(rsef)):
        if rsef[eachLine] != rssf[eachLine]:
            print("Sorry! Try Again!")
            secMenu()
            return 0 #exit the function, use this if you need it.

        print("Congratulations! Puzzle Solved!")

rawDescription: Python Basics - Comparing 2 Arrays

description: Python Basics - Comparing 2 Arrays


code:
l = ['a']
l.__contains__('a')
'a' in l

rawDescription: find the docs page for function "in"

description: Find the docs page for function "in"


code:
if q is None:
  a = "without query"
  #custQuery = Customer.all()
elif q is '':
  a = "with blank"
elif q!=None:
  a = "with query"

rawDescription: Receiving the requests and using If else statements on Queries with None in Python GAE


code:
import b

class A:
    def bar(self):
        return b.B()

rawDescription: How to avoid circular imports in Python?

description: Avoid circular imports in Python


code:
class PrefetchedGenerator(object):
    def __init__(self, generator):
         self._data = generator.next()
         self._generator = generator
         self._ready = True

    def next(self):
        if not self._ready:
            self.prefetch()
        self._ready = False
        return self._data

    def prefetch(self):
        if not self._ready:
            self._data = self._generator.next()
            self._ready = True

rawDescription: Python generator pre-fetch?

description: Python generator pre-fetch


code:
server_list, good_list, bad_list = ("gmail.com", "yahoo.com"), [], []
...
...
if email_address.endswith(server_list):
    bad_list.append(email_address)
else:
    good_list.append(email_address)

rawDescription: Python: check if string is in any items in a list?


code:
def findLogData(log_Files, searchForData, folderPath, resultsFile, span = (3,2)):
    nbrOfLinesOver, nbrOfLinesUnder = span
    with open(resultsFile, 'w') as resultFile:
        for filename in log_Files:

            #filename = folderPath + "\\" + file
            with open(filename,'r', encoding='UTF-8') as f:
                log = f.readlines()

            for lineCounter, line in enumerate(log):
                for stringToFind in searchForData:
                    if stringToFind in line:
                        slinceStart = min(0, lineCounter - nbrOfLinesUnder)
                        slinceEnd = max(len(log), lineCounter + nbrOfLinesOver + 1)
                        resultFile.writelines(log[slinceStart:slinceEnd])

rawDescription: Searching logs, outputting lines before and after match


rawDescription: Plotting sort of a heatmap whose colors are a result of a function x,y -> r,g,b


code:
import numpy as np

# set up values
keys = np.array(['key1', 'key2', 'key3'])
values = np.array([
    [1.1, 1.2, 1.3, 1.4],    # values1_x
    [2.1, 2.2, 2.3, 2.4],    # values2_x
    [3.1, 3.2, 3.3, 3.4]     # values3_x
])
weights = np.array([10., 20., 30., 40.])

# crunch the numbers
res = np.dot(values, -weights)   # negative of weights!

order = res.argsort(axis=0)  # sorting on negative value gives
                             # same order as reverse-sort; there does
                             # not seem to be any way to reverse-sort
                             # directly
sortedkeys = keys[order].tolist()

rawDescription: Fastest way to rank items with multiple values and weightings


code:
obj_1 = cs.segmentTrace(0., mat_a, mat_b)
obj_3 = cs.segInsert(obj)

rawDescription: C to Python interface - Trying to pass structs


code:
stringA = 'John'
stringB = 'Tim'
regex = re.compile(r'(%s)(.*)(%s)' % (stringA, stringB))
regex.sub(r'\3\2\1', "I told John to give the bag to Tim.")
regex.sub(r'\3\2\1', "John said hello to Tim.")
regex.sub(r'\3\2\1', "John!h9aghagTim")

rawDescription: Using Python to substitute or swap substrings in a file


code: counts[counts.index(min(counts))] += 15 - sum(counts[1:]) # from user1654936

rawDescription: Taking proportional samples, no bad sampling


code: foo( val1, val2, mydict.get("SomeKey") )

rawDescription: Let default value for parameter take precedence if test fails


code:
latPxSz = (maxy - miny) / row_numbers
lonPxSz = (maxx - minx) / column_numbers

rawDescription: calculate latitude and longitude from a geotiff image

description: Calculate latitude and longitude from a geotiff image


code:
def get_perform_and_pause_deferred(seconds, fn, *args, **kwargs):
    d = Deferred()
    d.addCallback(fn, *args, **kwargs)
    d.addCallback(pause, seconds=seconds)
    return d

rawDescription: Scrapy: non-blocking pause

description: Scrapy: non-blocking pause


code: C = np.einsum('ia,jb->abij', M.conj(), M)

rawDescription: Efficient way to fill up a 4d array from entries of a product of two matrices


rawDescription: python functions, math between csv files

description: Python functions, math between csv files


code: filter(None, iterable)

rawDescription: Regarding the use of filter()

description: Regarding the use of filter()


code:
l = [u'\xf9', u'!']
print(l)
l[0]
print(l[0])
l2 = [u.encode('utf-8') for u in l]
l2
print(l2)
print(l2[0])

rawDescription: Unicode list to String list Python 2

description: Unicode list to String list Python 2


rawDescription: Checking QValidator's state

description: Checking QValidator's state


code:
for char in word: # don't use 'letter' again
    if char == letter:
        position.append(char)
    else:
        position.append('_')

rawDescription: How to get my program to check for more than one letter in a word

description: Get my program to check for more than one letter in a word


code:
max_year = df.groupby(['JOB', 'NAME'])[['YEAR']].max()
max_year = max_year.set_index('YEAR', drop=False, append=True)

#                   YEAR
# JOB    NAME YEAR
# Employ Mary 2014  2014
# Worker Bob  2014  2014

rawDescription: Pandas multiple index with multiple aggregate functions


code:
from django.conf import settings
from django.conf.urls.static import static
...
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

rawDescription: Show an image from models in Django

description: Show an image from models in Django


code:
def readMatrix(infilepath, width):
    answer = []
    with open(infilepath) as infile:
        for line in infile:
            row = [None]*width
            for i in set(int(i) for i in line.split()):
                row[i] = 1
            answer.append(row)
    return answer

rawDescription: Writing the content of a list on a text file


rawDescription: Provide remote shell for Python script

description: Provide remote shell for Python script


code:
'''
Created on May 5, 2016

@author: billal begueradj
'''
import Tkinter as Tk
import PIL.Image
import PIL.ImageTk

class App(object):
    def __init__(self):
        self.root = Tk.Tk()
        self.root.grid_rowconfigure(0, weight=1)
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_columnconfigure(1, weight=1)
        # Get width and height of the screen
        self.h= self.root.winfo_screenheight()
        self.w= self.root.winfo_screenwidth()
        # Set the GUI's dimensions to the screen size
        self.root.geometry(str(self.w) + "x" + str(self.h))
        # Set the  width of the frame 'f1' to the half of the screen width
        self.f1 = Tk.Frame(self.root, bd=1, bg="green", width= self.w/2)
        self.f1.grid(row=0, column=0, sticky="nsew")
        # Load the image
        self.image = PIL.Image.open("/home/Begueradj/mahomet_pedophile.jpg")
        # Resize the image to fit self.label width
        self.photo = PIL.ImageTk.PhotoImage(self.image)
        self.label = Tk.Label(self.root, image=self.photo,  width= self.w/2)
        self.label.grid(row=0, column=1, sticky="nsew")

# Launch the main program
if __name__ == '__main__':
   app = App()
   app.root.mainloop()

rawDescription: python Tkinter occupy image equally to other widget

description: Python Tkinter occupy image equally to other widget


code:
# define an is_needed(row) predicate for a row
needed_rows = filter(is_needed, iterator)

rawDescription: Python Iterators from CSV module...help me understand how to use this, please?


code: ['Steve\xb6\xa9', 'Rob spring', 'Car Daniel', 'Done daniel']

rawDescription: How can I use regex to search inside sentence -not a case sensitive

description: Use regex to search inside sentence -not a case sensitive


code: l = cPickle.loads(s2)

rawDescription: Python - specifying lengths of strings, mostly


code:
def finder(df, row):
    for col in df:
        df = df.loc[(df[col] == row[col]) | (df[col].isnull() & pd.isnull(row[col]))]
    return df

rawDescription: Efficiently find matching rows (based on content) in a pandas DataFrame


code:
import logging

#
# your other flask code here
#

@app.after_request
def log_the_status_code(response):
    status_as_string = response.status
    status_as_integer = response.status_code
    logging.warning("status as string %s" % status_as_string)
    logging.warning("status as integer %s" % status_as_integer)
    return response

rawDescription: Flask - How to get status code when using after_request?


code: data = [[] for i in range(number_of_needed_lists)]

rawDescription: Dynamically size list of lists

description: Dynamically size list of lists


code:
from yahoo_finance import Share
import csv

def run():
    yahoo = Share('YHOO')

    with open('scripts/hisdata.csv', 'wb') as file1:
        csv_output = csv.writer(file1)
        heading = ['Adj_Close', 'Close', 'Date', 'High', 'Low', 'Open', 'Symbol', 'Volume']
        csv_output.writerow(heading)

        for row in yahoo.get_historical('2014-04-25', '2014-04-29'):
            csv_output.writerow([row[value] for value in heading])

run()

rawDescription: Unknown characters fetching stock data from yahoo in csv format


code:
import re
regex = re.compile(r'%s' % '|'.join(keywords))
bits = [bool(regex.search(x)) for x in items]

rawDescription: Comparing the items of two lists in Python


code:
bool(input(''))
bool(input(''))  # Hitting enter results in an empty string

rawDescription: if statement somehow always true

description: If statement somehow always true


code:
import NaiveBayes

model = NaiveBayes.NaiveBayes()

model.set_real(['Height'])
model.set_real(['Weight'])
model.add_instances({'attributes':
                         {'Height': 239,
                          'Weight': 231,
                          },
                     'cases': 32,
                     'label':  'Sex=M'})

model.add_instances({'attributes':
                         {'Height': 233,
                          'Weight': 234,
                          },
                     'cases': 32,
                     'label':  'Sex=M'})
model.add_instances({'attributes':
                         {'Height': 190,
                          'Weight': 152
                          },
                     'cases': 58,
                     'label': 'Sex=F'
                     })
model.add_instances({'attributes':
                         {'Height': 191,
                          'Weight': 153
                          },
                     'cases': 58,
                     'label': 'Sex=F'
                     })

model.train()
result = model.predict({'attributes': {'Height': 212, 'Weight': 200}})

print ("The result is %s" % (result))

rawDescription: Python NaiveBayes: Why am I getting a ZeroDivisionError


rawDescription: Python string, find specific word, then copy the word after it


code:
import asyncio

async def msg(text):
    await asyncio.sleep(0.1)
    print(text)

async def long_operation():
    print('long_operation started')
    await asyncio.sleep(3)
    print('long_operation finished')

async def main():
    await msg('first')

    # Now you want to start long_operation, but you don't want to wait it finised:
    # long_operation should be started, but second msg should be printed immediately.
    # Create task to do so:
    task = asyncio.ensure_future(long_operation())

    await msg('second')

    # Now, when you want, you can await task finised:
    await task

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

rawDescription: asyncio.ensure_future vs. BaseEventLoop.create_task vs. simple coroutine?

description: Asyncio.ensure_future vs. BaseEventLoop.create_task vs. simple coroutine


rawDescription: Which Python Conditional Return Statement Is The Most Pythonic?


code: my_list = my_string.split(',')

rawDescription: python: unpacking a string to a list

description: Python: unpacking a string to a list


code:
sys.path.append('<path to root of source>')
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'

rawDescription: Sphinx autodoc with Django 1.4

description: Sphinx autodoc with Django 1.4


code:
class Test_PwsAddEntryDialog(TestCase):
    """Tests the class PwsAddEntryDialog."""

    def test_password_strength_checking_works(self):
        """Tests if password strength checking works, if the corresponding check
        box is checked.
        """
        d = PwsAddEntryDialog()
        # test default of internal flag
        self.assertFalse(d.testPasswordStrength)
        # type something
        QTest.keyClicks(d.editSecret, "weak", 0, 10)
        # make sure that entered text is not treated as a password
        self.assertEqual(d.labelPasswordStrength.text(), "")
        # click 'is password' checkbox
        QTest.mouseClick(d.checkIsPassword, Qt.LeftButton)
        # test internal flag changed
        self.assertTrue(d.testPasswordStrength)
        # test that label now contains a warning
        self.assertTrue(d.labelPasswordStrength.text().find("too short") > 0)
        # click checkbox again
        QTest.mouseClick(d.checkIsPassword, Qt.LeftButton)
        # check that internal flag once again changed
        self.assertFalse(d.testPasswordStrength)
        # make sure warning disappeared again
        self.assertEqual(d.labelPasswordStrength.text(), "")

rawDescription: Unit and functional testing a PySide-based application?


rawDescription: python argparse, how to refer args by their name

description: Python argparse, how to refer args by their name


code:
import math
def my_round(n, ndigits):
    part = n * 10 ** ndigits
    delta = part - int(part)
    # always round "away from 0"
    if delta >= 0.5 or -0.5 < delta <= 0:
        part = math.ceil(part)
    else:
        part = math.floor(part)
    return part / (10 ** ndigits)

rawDescription: python incorrect rounding with decimals

description: Python incorrect rounding with decimals


rawDescription: How to assert a dict contains another dict without assertDictContainsSubset in python?

description: Assert a dict contains another dict without assertDictContainsSubset in python


code:
from itertools import product
letters = 'ABCDEFGH'
all_combos = (
    ''.join([digit if i == pos else c for i, c in enumerate(letters)])
    for digit, pos in product('1234', range(len(letters))))

next(all_combos)
next(all_combos)
next(all_combos)
next(all_combos)
from itertools import islice
print(list(islice(all_combos, 10)))

rawDescription: Change one character at a time in a string, don't change the string?


code:
def test_db_access(self):
    input = Element(title = 'foo')
    input.save()

    output = Element.objects.get(title='foo')

    self.assertEquals(input, output)

rawDescription: How do I use TDD to create a database representation of existing objects?

description: Use TDD to create a database representation of existing objects


code:
for i in range(10):
    def f(x):
        return x*2
    y = f(i)

rawDescription: In Python, are function-level assignments evaluated at each function call?


code: [[{'name': name} for name in items[key]] for key in sorted(items.keys())]

rawDescription: Python: Split a list into smaller jsons based on another list


rawDescription: Scraping data only after beginning of a certain text


code:
import subprocess

p = subprocess.Popen(['a.out'], stdin=subprocess.PIPE)
p.communicate('1 \n 3 \n 2 \n 5 \n 2...\n')

rawDescription: How to pipe parameter string to excutable in python?

description: Pipe parameter string to excutable in python


code:
class ChileObject(object):

    def __init__(self, request, name, parent):
        self.__parent__ = parent
        self.__name__ = name
        # Do some stuff, for example loading object from DB
        # and populate other attributes of the object.
        # Then add permission for the object's owner
        self.__acl__ = [(Allow, self.owner_id, ALL_PERMISSIONS)]

rawDescription: Having trouble with "fine-grained" Pyramid ACL


code:
def choice(self, seq):
        """Choose a random element from a non-empty sequence."""
        return seq[int(self.random() * len(seq))]

rawDescription: Changing Python's Random Sampling Algorithm


code:
[
(item['path'], prev_item['path']),
(prev_item['path'], item['path']),
]

rawDescription: Double assignment in python

description: Double assignment in python


code:
seq1 = 'asdfasdfasdf'
seq2 = 'asdfasdfasdf'

mymatrix = [[0 for y in range(len(seq1)+1)]for x in range(len(seq2)+1)]
#              ^^^^^^^^^^^^^^^^^^^^^^^^^^ reuse this

d = {'score' : 0, 'pointer' : 'none'}

for y in range(len(seq1)+1):
    mymatrix[0][y] = d.copy()

# The first one is already covered, just leave it off using slice
for x in range(len(seq2)+1)[1:]:
    mymatrix[x][0] = d.copy()

for line in mymatrix:
    print(line)

rawDescription: Trying to iterate over specific column in python array


code: on_press=lambda instance, text=t1.txt: self.SAVE_EDIT(instance, TEXT=text)

rawDescription: Give/get arguments in popup from "on_press"


code:
a=(name)
b=(score)

rawDescription: How to sort contents of a file.txt in python numerically

description: Sort contents of a file.txt in python numerically


code: print(string, end="")

rawDescription: Methods for printing without adding control characters in python


code:
dr_area.realize()
self.gc = dr_area.get_style().fg_gc[gtk.STATE_NORMAL]
img = gtk.gdk.pixbuf_new_from_file("image.png")
self.image = gtk.gdk.Pixmap(dr_area.window, img.get_width(), img.get_height())
self.image.draw_pixbuf(self.gc, img, 0, 0, 0, 0)

rawDescription: What is the fastest way to draw an image in Gtk+?


code: Y = APIWrapper(Y)

rawDescription: Partially Evaluating Python Classmethod Based on Where It's Accessed From


code:
keys = ('a', 'b', 'c', 'e')
dicts = (x, y, z)
f = {k: [d.get(k, 0) for d in dicts] for k in keys}

rawDescription: Merge python Dictionaries

description: Merge python Dictionaries


code:
import requests
content = requests.get(URL, auth=('user', 'pass'))

rawDescription: Get content of protected web pages using Python


code:
for sub in l:
    sub[:] = map(float,(s[:s.rfind("(")] for s in sub))

rawDescription: How to remove parenthesis from elements in a list (Python)

description: Remove parenthesis from elements in a list (Python)


code:
for i in range(len(col_one)):
    holder = number
    for j in range(4):
        holder.remove(col_one[i][j])
    col_two.append(holder)

rawDescription: Randomizing an array into two arrays

description: Randomizing an array into two arrays


code:
print(json.dumps(data, indent=4, sort_keys=True))

[
    {
        "ADRNR": 2692629,
        "AlertID": "",
        "AlertTimestamp": "14-12-2015 14:44:14",
        "BANKL": null,
        "BANKN": null,
        "BANKS": "nan",
        "BEGRU": "NPIV",
        "BUKRS": "2646",
        "C_Block": "No",
        "KOINH": null,
        "LAND1": "US",
        "LOEVM_x": null,
        "LOEVM_y": null,
        "MasterDataID": "10099",
        "MasterDataType": "Vendor",
        "NAME1": "LEGAL",
        "NODEL_x": null,
        "NODEL_y": null,
        "ORT01": null,
        "OtherData": null,
        "PSTLZ": null,
        "RuleID": "Rule3",
        "RuleName": "Vendor and Bank Country is Different",
        "STCD1": null,
        "STCD2": null,
        "STCEG": null,
        "STRAS": null,
        "TELF1": null
    }
]

rawDescription: How to convert few columns of pandas dataframe into JSON record within another record?

description: Convert few columns of pandas dataframe into JSON record within another record


code:
li=[]
for x in 'cat':
   for y in 'pot':
      li.append(x+y)

rawDescription: Python list comprehension for loops

description: Python list comprehension for loops


code:
new_frame = all_data_frame.rx((dataframe.rx2('input_type').ro == 'VALUE1').ro
                               & (dataframe.rx2('data_type').ro == 'VALUE2'),
                              True)

rawDescription: RPy2, subset data frame with multiple conditions


rawDescription: If I have a string "4 2 66" how can i get the ints 4, 2, 66 in python?


code:
# time in minutes
# 60min*24hours*365days*100years
AUTO_LOGOUT = 52560000

rawDescription: How can I set session never expire in django

description: Set session never expire in django


code:
def alphabetize(s, delimiter=","):
    values = s.split(delimiter)  # convert to a list
    result = []
    while values:
        # this is effectively select-sort - which is O(n**2) -
        # but even worse because deleting a list item is also
        # O(n), making it O(n**3) overall
        smallest = min(range(len(values)), key=values.__getitem__)
        result.append(values[smallest])
        del values[smallest]
    # rejoin the sorted items to a string
    return delimiter.join(result)

rawDescription: Smallest ASCII Value in a List

description: Smallest ASCII Value in a List


rawDescription: Parenthesized repetitions in Python regular expressions


code:
for context, label in zip(contexts, labels):
    by_context[context].append(label)

rawDescription: Improve performance of this python function


rawDescription: Numpy/Python performing terribly vs. Matlab


code:
diff = iter(set(a).difference(b))
n = 3
sli = [next(diff) for _ in range(n)]
print(sli)

rawDescription: How to get n elements of a list not contained in another one?

description: Get n elements of a list not contained in another one


code:
import threading

def _get_input(msg, func):
    """Get input and run the function."""
    value = input(msg)
    if func is not None:
        func(value)
    return value
# end _get_input

def thread_input(msg="", func=None):
    """Collect input from the user without blocking. Call the given function when the input has been received.

    Args:
        msg (str): Message to tell the user.
        func (function): Callback function that will be called when the user gives input.
    """
    th = threading.Thread(target=_get_input, args=(msg, func))
    th.daemon = True
    th.start()
# end thread_input

def return_input(msg=""):
    """Run the input method in a separate thread, and return the input."""
    results = []
    th = threading.Thread(target=_store_input, args=(msg, results))
    th.daemon = True
    th.start()
    while len(results) == 0:
        QtGui.qApp.processEvents()
        time.sleep(0.1)

    return results[0]
# end return_input

if __name__ == "__main__":

    stop = [False]
    def stop_print(value):
        print(repr(value))
        if value == "q":
            stop[0] = True
            return
        thread_input("Enter value:", stop_print)

    thread_input("Enter value:", stop_print)
    add = 0
    while True:
        add += 1
        if stop[0]:
            break

    print("Total value:", add)

rawDescription: Matplotlib Freezes When input() used in Spyder


code:
if not a or (a and b):
    print('foo')

rawDescription: Python: Check second variable if first variable is True?


code:
from pyspark.sql import Row

def f(v):
    m, i = zip(*sorted(zip(v.values, v.indices), reverse=True))
    m = [ float(j) for j in m]
    i = [ int(j) for j in i]
    return Row(indices=i, values=m)

rawDescription: rdd.toDF() changes float to None

description: Rdd.toDF() changes float to None


code:
import time
import multiprocessing

def exchange1(q):
    while True:
        time.sleep(2)
        q.put([1, 2, 3, 4, 5])

def exchange2(q):
    while True:
        time.sleep(4)
        q.put([4, 5, 6, 7, 8])

if __name__ == "__main__":
    q = multiprocessing.Queue()
    p1 = multiprocessing.Process(target=exchange1, args=(q,))
    p2 = multiprocessing.Process(target=exchange2, args=(q,))
    p1.start()
    p2.start()
    while True:
        out = q.get()
        print("out is {}".format(out))

rawDescription: How would I handle the event of a thread finishing in python?


code:
x_ax.set_label('x')
y_ax.set_label('y')

rawDescription: 2 pick events 2 colorbars

description: 2 pick events 2 colorbars


code: set([('wilds', 'tony'), ('jones', 'steven')])

rawDescription: Python Fuzzy Matches in two text files

description: Python Fuzzy Matches in two text files


code: grid = defaultdict(lambda: defaultdict(int))

rawDescription: python: representing square grid that wraps on itself (cylinder)

description: Python: representing square grid that wraps on itself (cylinder)


code:
list1 = 'it is, a good,day'
' ouf '.join(map(str.strip,list1.split(',')))

rawDescription: Python3 how to seperate items in truple

description: Python3 how to seperate items in truple


code:
# sample filter
def todollars(value):
    val = int(value)
    return "%.2f" % val/100.0

rawDescription: How to add a character in Django template

description: Add a character in Django template


code:
# This format string is take from the util file in the protorpc folder in Google App Engine source code
format_string = '%Y-%m-%dT%H:%M:%S.%f'

params = {}
for field in request.all_fields():
  value = getattr(request, field.name)
  if (isinstance(value, datetime.datetime)):
    value = value.strftime(format_string)
  params[field.name] = value

taskqueue.add(url='/api/workers.save_to_db', payload=json.dumps(params), headers={'content-type':'application/json'})

rawDescription: Google App Engine Python - Protorpc && Taskqueue


code: items = line.split('|')

rawDescription: Aggregate text keys-values python defaultdict


code:
def to_pygame(coords, height):
    """Convert coordinates into pygame coordinates (lower-left => top left)."""
    return (coords[0], height - coords[1])

rawDescription: Change the position of the origin in PyGame coordinate system


rawDescription: Cannot connect multiple widgets to the same slot


code:
list(find_near_matches('bde', 'abcdefg', 0))
list(find_near_matches('bde', 'abcdefg', 1))
list(find_near_matches('cde', 'abcdefg', 0))
list(find_near_matches('cde', 'abcdefg', 1))
match = _[0]
'abcdefg'[match.start:match.end]

rawDescription: Get position of subsequence using Levenshtein-Distance


code:
for index, item in enumerate(vect):
    results = do_stuff_with(item)
    if index % 100 == 0 and should_we_stop(results):
        break

rawDescription: Single Vs. Multiple For Loops In Python?

description: Single Vs. Multiple For Loops In Python


rawDescription: Django filter many-to-many with contains


code:
import re
data = '''
12345678 foo
bar
baz
12345678 foo
'''
data = re.sub(r'\n(?!\d{8})', '', data)

print(data)

rawDescription: Python re.sub - replacing character when context does not match


code: np.array([mk_row(d[0]) for d in dd])

rawDescription: python: unpacking an array of dictionaries in a matrix

description: Python: unpacking an array of dictionaries in a matrix


code:
gsrc2.props.start          = 2 * gst.SECOND
gsrc2.props.duration       = 4 * gst.SECOND
gsrc2.props.media_start    = 0
gsrc2.props.media_duration = 4 * gst.SECOND
gsrc2.props.priority       = 2

rawDescription: Video Transitions with GStreamer & GNonLin not working


code:
class Damage:

    @staticmethod
    def shortsword():
        return randint(2, 7)

damage = Damage.shortsword()

rawDescription: Storing the value of a randomly generated integer


code:
df2 = df.pivot(index="time", columns="machine", values="status")
df2

rawDescription: Detection of concurrent event appearances - pandas and DataFrame, but possibly pure-python related


rawDescription: reordering list of dicts arbitrarily in python

description: Reordering list of dicts arbitrarily in python


rawDescription: Is there a way to explode a string using a 'pattern'


code:
from itertools import islice, imap
import csv

with open("in.txt") as f, open("numbers.txt") as nums:
    nums = set(imap(str.rstrip, nums))
    r = csv.reader(f)
    for row in r:
        for n in islice(row, 1, None):
            if n in nums:
                print("{} is in row {}".format(n, row[0]))
        print("")

rawDescription: Comparing two CSV files in Python when rows have multiple values


code:
def __init__(self, num_of_lists):
    self._num_of_lists = num_of_lists
    self.nested_list = []
    for i in range(num_of_lists):
        self.nested_list.append([])

rawDescription: Python - Adding to a nested list

description: Python - Adding to a nested list


code:
foo = 'green eggs and ham'
bar = 'green eggs and ham'
foo is bar
False
foo == bar
True

rawDescription: Why does string equality not working in this Python code as expected?


code:
def makeF():
    d = {}
    "sayA = lambda: print('Aah')"
    exec("sayA = lambda: print('Aah')",d)
    return d["sayA"]

from ext import makeF

f = makeF()
f()

rawDescription: Defining a function with exec from inside a function in global environment


rawDescription: Method that applies to instance of a class in python // Apply a method to an instance of a class in python


code:
import email.utils
import operator
def sort_key(received_header):
    received_date = email.utils.parsedate_tz(received_header)
    return received_date

received_header_list.sort(key=sort_key)

rawDescription: extracting email Received: headers with Python email package

description: Extracting email Received: headers with Python email package


code:
class shade:
    def __init__(self, light):
        self.light=light

    @property
    def darkness(self):
        return 100 - self.light

    def __str__(self):
        return (str(self.light) +  ',' + str(self.darkness))

rawDescription: How do you change the value of one attribute by changing the value of another? (dependent attributes)

description: Change the value of one attribute by changing the value of another? (dependent attributes)


code:
class A(object):
    def __init__(self):
        self.version = "1.0"

        self.login = "logged in"
        self.login_message = "hello logger"

    @property
    def logout(self):
        return {"1.0": "logged out", "2.0": "logged out 2.0"}[self.version]

    @property
    def logout_message(self):
        return {"1.0": "goodbye logger", "2.0": "goodbye logger 2.0"}[self.version]

rawDescription: python global decorator for class attributes

description: Python global decorator for class attributes


code:
# get image rect
image_rect = images[current_image].get_rect()

# center image rect on the screen
image_rect.center = screen_rect.center

# draw image using `image_rect`
screen.blit(images[current_image], image_rect)

rawDescription: Sequential image presentation in Pygame

description: Sequential image presentation in Pygame


code:
import json
d = [ { 'city_id': x, 'city_name': y, 'city_capital': z }
      for x, y, z in zip(city_id, city_name, city_capital) ]
pretty_json = json.dumps(d, sort_keys=True, indent=4)

rawDescription: How to create JSON formatted string from multiple lists in python?

description: Create JSON formatted string from multiple lists in python


code:
line = '   P t\xe2\x82\xac         \xc5\x92  \xc3\x98p\xe2\x82\xac Q~\xc3\x80t\xc3\xb406-23423230xx06-34893646xx secure_encryptedsecure_encrypted\xe2\x82\xac  -\xe2\x82\xac  -\xe2\x82\xac  \n'
re.findall("\d{2}-\d{8}", line)

rawDescription: Python Regex And encode

description: Python Regex And encode


code:
from collections import defaultdict

review_object = Review.objects.all()
results = defaultdict(int)
for ro in review_object:
    results[ro.property_id] += ro.star_rating

rawDescription: Accessing and performing operations on queryset data in Django


code: somefunction_mock.side_effect = [10, None, 10]

rawDescription: UnitTest Python mock only one function multiple call


code: re.findall(r'[A-Z][a-z]{2,}', 'ctl00_PD_lblProductTitle')  # also works for 'RatingScore'

rawDescription: How to extract meaningful words from messy strings?

description: Extract meaningful words from messy strings


code:
Solution
stacked = df.stack()
stacked = stacked[stacked.groupby(level=1).idxmax()]

rawDescription: pandas: finding maximum for each series in dataframe

description: Pandas: finding maximum for each series in dataframe


code:
url(r'/blah/create/', 'myview'),
url(r'/blah/edit/(?P<id>[\d+])/', 'myview')

rawDescription: How to use Django AutoField to edit a modelForm?

description: Use Django AutoField to edit a modelForm


code: sorted(nice.items(), key=lambda v: (int(v[1]),int(v[0])),reverse=True)

rawDescription: Python : Displaying a sorted dictionary by more than one condition


code:
while True:
    t1 = time.time()
    for i in range(burstsize):
        sock.write(1460)
    t2 = time.time()
    if t2 - t1 < 1.0:
        tout = 1.0 - (t2-t1)
        select.select([], [], [], tout) #

rawDescription: Configuring client throughput in simple TCP server


code: increment.a = 1

rawDescription: Passing Python function with no argument


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
Builder.load_string('''
<Box>:
    orientation: 'vertical'
    FloatLayout:
        ScrollView:
            Label:
                id: lab
                size_hint_y: None
                text_size: self.width, None
                text: 'l or emi psum '*100
                height:self.texture_size[1]
    Button:
        size_hint_y: None
        height: 100
        on_release: root.ids.lab.text+='lo rem '*100
''')
class Box(BoxLayout): pass
class My(App):
    def build(self):
        return Box()
My().run()

rawDescription: Change the label size depending on the text


rawDescription: How to convert a string to "04x" hex in little endian format?

description: Convert a string to "04x" hex in little endian format


code:
def playerMoveO(board):

    validMove = False
    while not validMove:
        col = input("You are the O player. What column would you like to play? :")
        for row in range (6,0,-1):
            if (1 <= int(row) <= 6) and (1 <= int(col) <= 7) and (board[int(row)-1][int(col)-1] == " "):
                board[int(row)-1][int(col)-1] = "O"
                validMove = True
                break
        else:
            print ("Invalid input. Please try again!\n")

rawDescription: Edit: Python - Going from 1 Player to Two Player Game Using Functions


code:
starting_number = 5

def modify_starting_num(starting_num):
    starting_num = starting_num * 2
    return starting_num

starting_number = modify_starting_num(starting_number) # Calling the function
print (starting_number)

rawDescription: counting number with 3 csvs python

description: Counting number with 3 csvs python


code:
import re
s = "I will kill you today"
[i for i in re.findall(r'\b(?:[kw]ill)\b|\b(\w+)\b', s) if i]

rawDescription: Negative pipe matching with regular expressions


code: set([os.path.dirname(p) for p in glob.glob("/path/to/parent/*/*")])

rawDescription: Check if a given directory contains any directory in python