code:
import pandas as pd

# game is a unique id (like a combination of date, home_team and away_team)
bet_list = [
    {'playerid': 1, 'game': 1, 'date': 1, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 3, 'away_goals': 5},
    {'playerid': 2, 'game': 1, 'date': 1, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 2, 'away_goals': 1},
    {'playerid': 3, 'game': 1, 'date': 1, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 1, 'away_goals': 0},
    {'playerid': 4, 'game': 1, 'date': 1, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 0, 'away_goals': 0},
    {'playerid': 1, 'game': 2, 'date': 2, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 3, 'away_goals': 5},
    {'playerid': 2, 'game': 2, 'date': 2, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 2, 'away_goals': 1},
    {'playerid': 3, 'game': 2, 'date': 2, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 1, 'away_goals': 0},
    {'playerid': 4, 'game': 2, 'date': 2, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 0, 'away_goals': 0},
    {'playerid': 1, 'game': 3, 'date': 3, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 3, 'away_goals': 5},
    {'playerid': 2, 'game': 3, 'date': 3, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 2, 'away_goals': 1},
    {'playerid': 3, 'game': 3, 'date': 3, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 1, 'away_goals': 0},
    {'playerid': 4, 'game': 3, 'date': 3, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 0, 'away_goals': 0}
]

result_list = [
    {'game': 1, 'date': 1, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 3, 'away_goals': 4},
    {'game': 2, 'date': 2, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 2, 'away_goals': 2},
    {'game': 3, 'date': 3, 'home_team': 'Bayern', 'away_team': 'VfL', 'home_goals': 0, 'away_goals': 0},
]

def calculate_result(input_df):
    input_df['result'] = 0
    # home wins (result 1)
    mask = input_df['home_goals'] > input_df['away_goals']
    input_df['result'][mask] = 1
    # away wins (result 2)
    mask = input_df['home_goals'] < input_df['away_goals']
    input_df['result'][mask] = 2
    # draws (result 3)
    mask = input_df['home_goals'] == input_df['away_goals']
    input_df['result'][mask] = 3
    # goal difference
    input_df['goal_difference'] = input_df['home_goals'] - input_df['away_goals']
    return input_df

# so what where the expectations?
bet_df = pd.DataFrame(bet_list)
bet_df = calculate_result(bet_df)
# if you want to look at the results
bet_df

# what were the actuals
result_df = pd.DataFrame(result_list)
result_df = calculate_result(result_df)
# if you want to look at the results
result_df

# now let's compare them!
# i take a subsetof the result df and link results on the game
combi_df = pd.merge(left=bet_df, right=result_df[['game', 'home_goals', 'away_goals', 'result', 'goal_difference']], left_on='game', right_on='game', how='inner', suffixes=['_bet', '_actual'])
# look at the data
combi_df

def calculate_bet_score(input_df):
    '''
Notice that I'm keeping in extra columns, because those are nice for comparative analytics in the future. Think: "you had this right, just like x% of all the people"

    '''
    input_df['bet_score'] = 0
    # now look at where people have correctly predicted the result
    input_df['result_estimation'] = 0
    mask = input_df['result_bet'] == input_df['result_actual']
    input_df['result_estimation'][mask] = 1 # correct result
    input_df['bet_score'][mask] = 1 # bet score for a correct result
    # now look at where people have correctly predicted the difference in goals when they already predicted the result correctly
    input_df['goal_difference_estimation'] = 0
    bet_mask = input_df['bet_score'] == 1
    score_mask = input_df['goal_difference_bet'] == input_df['goal_difference_actual']
    input_df['goal_difference_estimation'][(bet_mask) & (score_mask)] = 1 # correct result
    input_df['bet_score'][(bet_mask) & (score_mask)] = 2 # bet score for a correct result
    # now look at where people have correctly predicted the exact goals
    input_df['goal_exact_estimation'] = 0
    bet_mask = input_df['bet_score'] == 2
    home_mask = input_df['home_goals_bet'] == input_df['home_goals_actual']
    away_mask = input_df['away_goals_bet'] == input_df['away_goals_actual']
    input_df['goal_exact_estimation'][(bet_mask) & (home_mask) & (away_mask)] = 1 # correct result
    input_df['bet_score'][(bet_mask)  & (home_mask) & (away_mask)] = 3 # bet score for a correct result
    return input_df

combi_df = calculate_bet_score(combi_df)

# now look at the results
combi_df

# and you can do nifty stuff like making a top player list like this:
combi_df.groupby('playerid')['bet_score'].sum().order(ascending=False)
# player 4 is way ahead!
# which game was the best estimated game?
combi_df.groupby('game')['bet_score'].mean().order(ascending=False)
# game 3! though abysmal predictions in general ;)

rawDescription: What is the most elegant way to evaluate sport game estimates in Python?


code:
def some_function():
    return {
        "status": error,
        "location": loc,
        "codes": {
            "code1": 5,
            "code2": 6,
        },
    }

rawDescription: Python return object

description: Python return object


code:
import sys
import serial

port = serial.Serial('COM4', 115200, timeout=0)
data = b''

while(1):
    data = port.read()
    print(data)
    if data != b'':
        fileID = open('output.txt', 'a')
        fileID.write(str(ord(data)))
        fileID.write(',')
        fileID.close()

port.close()

rawDescription: Convert a binary number to human readable text


code:
from selenium import webdriver

driver = webdriver.PhantomJS()
url = "http://www.euronews.com/2015/03/20/uber-taxis-overtake-new-york-yellow-cabs/"
driver.get(url)
for script in driver.find_elements_by_xpath("//script[contains(@src, 'google')]"):
    print(script.get_attribute('src'))

rawDescription: get a src atrribute using xpath

description: Get a src atrribute using xpath


code:
items = ['taylor', 'steven', 'roger']
filenames = ['file1', 'file2', 'file3']

for item, filename in zip(items, filenames):
    with open(filename, 'w') as output:
        output.write(item + '\n')

rawDescription: Printing out elements of list into separate text files in python


code:
class CachedProperty(object):
    '''
    A property that is calculated (a) lazily and (b) only once for an object.

    Usage:

        class MyObject(object):

            # ... Regular definitions here

            def _get_personality(self):
                print('Calculating personality...')
                time.sleep(5) # Time consuming process that creates personality
                return 'Nice person'

            personality = CachedProperty(_get_personality)

    '''
    def __init__(self, getter, name=None):
        '''
        Construct the cached property.

        You may optionally pass in the name that this property has in the
        class; This will save a bit of processing later.
        '''
        self.getter = getter
        self.our_name = name

    def __get__(self, obj, our_type=None):

        if obj is None:
            # We're being accessed from the class itself, not from an object
            return self

        value = self.getter(obj)

        if not self.our_name:
            if not our_type:
                our_type = type(obj)
            (self.our_name,) = (key for (key, value) in
                                vars(our_type).iteritems()
                                if value is self)

        setattr(obj, self.our_name, value)

        return value

rawDescription: Making a LazilyEvaluatedConstantProperty class in Python


code: out = [x[1:3] for x in aa]

rawDescription: extract a substring from an array of strings in python

description: Extract a substring from an array of strings in python


code:
segment_scores = (('A', 'B', 'C', 'D'), .99), (('A', 'B', 'C', 'E'), .77) #, ...

def best_score_for(items, segments, subtotal = 1.0):
    if not items: return subtotal
    if not segments: return 0.0
    segment, score = segments[0]
    best_without = best_score_for(items, segments[1:], subtotal)
    return max(
        best_score_for(items.difference(segment), segments[1:], subtotal * score),
        best_without
    ) if items.issuperset(segment) else best_without

best_score_for(set('ABCDEFGHI'), segment_scores) # .430155

rawDescription: Establishing highest score for a set of combinations


code:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout

Builder.load_string("""
<Calc>:
    # This are attributes of the class Calc now
    a: _a
    b: _b
    result: _result
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'top'
        ScreenManager:
            size_hint: 1, .9
            id: _screen_manager
            Screen:
                name: 'screen1'
                GridLayout:
                    cols:1
                    TextInput:
                        id: _a
                        text: '3'
                    TextInput:
                        id: _b
                        text: '5'
                    Label:
                        id: _result
                    Button:
                        text: 'sum'
                        # You can do the opertion directly
                        on_press: _result.text = str(int(_a.text) + int(_b.text))
                    Button:
                        text: 'product'
                        # Or you can call a method from the root class (instance of calc)
                        on_press: root.product(*args)
            Screen:
                name: 'screen2'
                Label:
                    text: 'The second screen'
    AnchorLayout:
        anchor_x: 'center'
        anchor_y: 'bottom'
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, .1
            Button:
                text: 'Go to Screen 1'
                on_press: _screen_manager.current = 'screen1'
            Button:
                text: 'Go to Screen 2'
                on_press: _screen_manager.current = 'screen2'""")

class Calc(FloatLayout):
    # define the multiplication of a function
    def product(self, instance):
        # self.result, self.a and self.b where defined explicitely in the kv
        self.result.text = str(int(self.a.text) * int(self.b.text))

class TestApp(App):
    def build(self):
        return Calc()

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

rawDescription: Kivy input values for simple calculations


code: result = self.cur.executemany(sql, data)

rawDescription: Insert multiple rows to database without using looping


code:
class BaseDataType(object):
    parent_operation = relationship(Operation, backref="datatype")

class DataTypeA(Base, BaseDataType):
    id = Column(Integer, primary_key=True)

class DataTypeB(Base, BaseDataType):
    id = Column(Integer, primary_key=True)

rawDescription: python class attributes and sql alchemy relationships

description: Python class attributes and sql alchemy relationships


rawDescription: In Python and numpy, how do I remove rows of an array that have a certain condition


code:
walker = iter(os.walk(IMAGE_DIRECTORY))
next(walker)
for path, files, _ in walker:
    list_of_files.extend(os.path.join(path, f) in files)

rawDescription: Better way to list all directories in Python other than self?


code:
import mechanize
import socket
timeout_occurred = False
br = mechanize.Browser()
try:
    br.open("http://python.org/", timeout=0.001)
except mechanize.URLError as exc:
    if isinstance(exc.reason, socket.timeout):
        timeout_occurred = True
if timeout_occurred:
    # retry
    br.open("http://python.org/", timeout=0.001)

rawDescription: Does mechanize have an option to retry a request if it fails?


code:
def whichSlot(x, n):
    return (x - 1) // n

rawDescription: If there are slots consisting of n numbers, which will x fit into?


code:
@route('/file')
def getAFileLink():
    host = bottle.request.get_header('host')
    return {'url': 'http://{}/some/file.abc'.format(host)}

rawDescription: get server address from bottle

description: Get server address from bottle


code:
with open('address1.txt') as fin, open('address2.txt','w') as fout:
  for line in fin:
    fout.write( "\t".join(line.split()) + "\n" )

rawDescription: Parsing tab or space/s delimited file using Python


code:
def reverse(text):
    final_string = ""
    count = len(text) # sets the counter variable to the length of the string variable
    while count > 0: # starts a loop as long as our counter is higher than 0
        final_string += text[len(text)-1] #copies the last letter from text to final string
        text = text[0:len(text)-1] #removes the last letter from text
        count -= 1 #decrements the counter so we step backwards towards 0
    return final_string

rawDescription: What does the following python code snippet do?


code:
x = [(('university', 'NN'), 'nsubj', ('bit', 'NN')), (('university', 'NN'), 'cop', ('is', 'VBZ')), (('university', 'NN'), 'amod', ('good', 'JJ'))]
for arg1, pred, arg2 in x:
    word1, pos1 = arg1
    word2, pos2 = arg2
    if pos1.startswith('NN') and pos2.startswith('JJ') and pred == 'amod':
            print ((arg1, pred, arg2))

rawDescription: How to get JJ and NN (adjective and Noun) from the triples generated StanfordDependencyParser with NLTK?

description: Get JJ and NN (adjective and Noun) from the triples generated StanfordDependencyParser with NLTK


code:
df = pd.read_clipboard(header=None)
df[df[0].str.contains('fb')]

rawDescription: Selecting columns equal to a substring in python


code:
import matplotlib, scipy
fig = matplotlib.figure()
ax = fig.add_axes([0.1,0.1,0.8,0.8])
axicon = fig.add_axes([0.4,0.4,0.1,0.1])
ax.plot(range(5), [4,2,3,5,1])
axicon.imshow(scipy.randn(100,100))
axicon.set_xticks([])
axicon.set_yticks([])
fig.show()

rawDescription: Adding a small photo/image to a large graph in Matplotlib/Python


code: my_set.remove((6, 7))

rawDescription: sets in python problem

description: Sets in python problem


code:
s = open(filename).read()
reports = [x.strip() for x in s.split('=-=-=-=-=-=-=-=-=-=-=\n')]

rawDescription: Extract chunk of text between symbols from file using Python


code:
cv2.imwrite('hue.png', img[:,:,0])
cv2.imwrite('sat.png', img[:,:,1])
cv2.imwrite('val.png', img[:,:,2])

rawDescription: Show HSV Values using open cv

description: Show HSV Values using open cv


code:
import time, datetime

# Create time bounds -- program should run between RUN_LB and RUN_UB
RUN_LB = datetime.time(hour=22)     # 10pm
RUN_UB = datetime.time(hour=3)      #  3am

# Helper function to determine whether we should be currently running
def should_run():
    # Get the current time
    ct = datetime.datetime.now().time()
    # Compare current time to run bounds
    lbok = RUN_LB <= ct
    ubok = RUN_UB >= ct
    # If the bounds wrap the 24-hour day, use a different check logic
    if RUN_LB > RUN_UB:
        return lbok or ubok
    else:
        return lbok and ubok

# Helper function to determine how far from now RUN_LB is
def get_wait_secs():
    # Get the current datetime
    cd = datetime.datetime.now()
    # Create a datetime with *today's* RUN_LB
    ld = datetime.datetime.combine(datetime.date.today(), RUN_LB)
    # Create a timedelta for the time until *today's* RUN_LB
    td = ld - cd
    # Ignore td days (may be negative), return td.seconds (always positive)
    return td.seconds

while True:
    if should_run():
        print("--do something--")
    else:
        wait_secs = get_wait_secs()
        print("Sleeping for %d seconds..." % wait_secs)
        time.sleep(wait_secs)

rawDescription: Scheduling a Python program to sleep within a given time period


rawDescription: how to slice a subset of numpy arrays

description: Slice a subset of numpy arrays


code:
plt.annotate(
    '30.2',
    xy=(3, y),
    xycoords='data',
    xytext=(3, y - 5),
    textcoords='data',
    horizontalalignment='center',
    arrowprops=dict(facecolor='black', arrowstyle="->")
)

rawDescription: Create arrows in matplotlib using annotate


code:
import urllib2
import cookielib

cp = urllib2.HTTPCookieProcessor()
cj = cp.cookiejar

# see cookielib.Cookie documentation for options description
cj.set_cookie(cookielib.Cookie(0, 'a_cookie', 'a_value',
                               '80', False, 'domain', True, False, '/path',
                               True, False, None, False, None, None, None))
opener = urllib2.build_opener(urllib2.HTTPHandler(),
                              cp)
opener.addheaders.append(('User-agent', 'Mozilla/5.0 (compatible)'))
opener.open('http://website.com').read()

rawDescription: Open web page with custom cookies in Python


code:
# ...
a['example']['test'] = 'red'

import tempfile, os
with tempfile.NamedTemporaryFile() as tmp:
    a.write(tmp)

    # or ctypes.windll.kernel32.MoveFileExW(tmp.name, 'data.txt', 2)
    # 2 = MOVEFILE_REPLACE_EXISTING
    # I'll leave wrapping it in a cross-platform manner up to you
    os.rename(tmp.name, 'data.txt')

rawDescription: configparser reading and writing

description: Configparser reading and writing


code:
class UpgradeGateway(Gateway):
    def respond(self):
        h = self.req.inheaders
        if h.get("Connection", "") == "Upgrade":
            # Turn off auto-output of HTTP response headers
            self.req.sent_headers = True
            # Not sure exactly what you want to pass or how, here's a start...
            return protocols[h['Upgrade']].handle(self.req.rfile, self.req.wfile)
        else:
            return old_gateway(self.req).respond()

old_gateway = cherrypy.server.httpserver.gateway
cherrypy.server.httpserver.gateway = UpgradeGateway

rawDescription: Handling HTTP/1.1 Upgrade requests in CherryPy


code:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

class FakeSlider(object):
    def __init__(self, slider, func):
        self.func, self.slider = func, slider
    @property
    def val(self):
        return self.func(self.slider.val)

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.25)

sliderax1 = fig.add_axes([0.15, 0.1, 0.75, 0.03], axisbg='gray')
sliderax2  = fig.add_axes([0.15, 0.15, 0.75, 0.03], axisbg='gray')

slider1 = Slider(sliderax1, 'Value 1', 0.1, 5, valinit=2)
slider2 = Slider(sliderax2, 'Value 2', -4, 0.9, valinit=-3,
                 slidermax=FakeSlider(slider1, lambda x: 1 - x))
plt.show()

rawDescription: Matplotlib dependent sliders

description: Matplotlib dependent sliders


rawDescription: Python Tkinter Text Area set cursor to end


code:
import tarfile
import StringIO

tar = tarfile.TarFile("test.tar","w")

string = StringIO.StringIO()
string.write("hello")
string.seek(0)
info = tarfile.TarInfo(name="foo")
info.size=len(string.buf)
tar.addfile(tarinfo=info, fileobj=string)

tar.close()

rawDescription: python write string directly to tarfile

description: Python write string directly to tarfile


rawDescription: Pandas Data Frame join by grouping

description: Pandas Data Frame join by grouping


code:
import pandas as pd

df = pd.DataFrame([{'a': 'ac', 'b': 'dc'}, {'a': 'ddd', 'b': 'fdf'}])
print(df)

#      a    b
# 0   ac   dc
# 1  ddd  fdf

d = df.to_dict(orient='records')
print(d)

# [{'b': 'dc', 'a': 'ac'}, {'b': 'fdf', 'a': 'ddd'}]

rawDescription: Convert dataframe to dictionary

description: Convert dataframe to dictionary


code:
values = []

def obtainingparams(self, df, tau_1, tau_2, residuals):
    global values

    print('Calculate the yields Matrix and matrix_of_params in this part')

    params = np.linalg.lstsq(matrix_of_params,yields)
    residuals = np.sqrt(((yields - matrix_of_params.dot(params))**2).sum())
    tau_1 = tau_1 + 0.2
    tau_2 = tau_2 + 0.2

    values.append((tau1, tau2, residuals))

    #Checkin how many times the function has been called via a decorator not included in this code
    while self.obtainingparams(self, df, tau_1, tau_2, residuals).called < 5:
        self.obtainingparams(self, df, tau_1, tau_2, residuals)

rawDescription: Storing values from a recursive function call


code:
x = np.arange(256).reshape(-1, 1)
y = np.arange(256)
rng_paraboloid = (x*x + y*y) % 256

import matplotlib.pyplot as plt
plt.imshow(rng_paraboloid, interpolation='nearest')

rawDescription: how to achieve pixelmath in numpy/scipy

description: Achieve pixelmath in numpy/scipy


code: CST = 10

rawDescription: Constant values in Python

description: Constant values in Python


code:
def post_edit(request, pk=None):
    if pk is not None:
        post = get_object_or_404(Post, pk=pk)
    else:
        post = None
    if request.method == "POST":
        form = PostForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.published_date = timezone.now()
            post.save()
            return redirect("post_detail", pk=post.pk)
    else:
        form = PostForm(instance=post)
    return render(request, "blog/post_edit.html", {"form":form})

rawDescription: Possible to make these two django views DRY-er?


code:
from matplotlib import *
plot(xrange(10))
yticks(xrange(10), rotation='vertical')

rawDescription: Barchart with vertical labels in python/matplotlib


rawDescription: Select rows randomly based on condition pandas python


code: SOLID_I18N_USE_REDIRECTS = True

rawDescription: How to display / on django site instead of /en/ using i18n_patterns and set_language at the same time?

description: Display / on django site instead of /en/ using i18n_patterns and set_language at the same time


code:
def my_re_escape(regex):
    regex = re.escape(regex)
    regex = regex.replace('foo', 'bar')
    # etc
    return regex

rawDescription: Adding special characters to Python regex engine


code:
lists = random.sample(x, 2)
# now we swap two random elements between lists[0], lists[1]

rawDescription: Random sample from list of lists

description: Random sample from list of lists


code:
from tkinter import *
import tkinter.messagebox as tm

class LoginFrame(Frame):
    def __init__(self, master):
        super().__init__(master)

        self.label_1 = Label(self, text="Username")
        self.label_2 = Label(self, text="Password")

        self.entry_1 = Entry(self)
        self.entry_2 = Entry(self, show="*")

        self.label_1.grid(row=0, sticky=E)
        self.label_2.grid(row=1, sticky=E)
        self.entry_1.grid(row=0, column=1)
        self.entry_2.grid(row=1, column=1)

        self.checkbox = Checkbutton(self, text="Keep me logged in")
        self.checkbox.grid(columnspan=2)

        self.logbtn = Button(self, text="Login", command = self._login_btn_clickked)
        self.logbtn.grid(columnspan=2)

        self.pack()

    def _login_btn_clickked(self):
        #print("Clicked")
        username = self.entry_1.get()
        password = self.entry_2.get()

        #print(username, password)

        if username == "john" and password == "password":
            tm.showinfo("Login info", "Welcome John")
        else:
            tm.showerror("Login error", "Incorrect username")

root = Tk()
lf = LoginFrame(root)
root.mainloop()

rawDescription: How can I integrate TKinter with Python log in screen?

description: Integrate TKinter with Python log in screen


code:
result = {}
for k, v in my_list + other_list:
    result[k] = result.get(k, 0) + v

rawDescription: Python Easiest Way to Sum List Intersection of List of Tuples


code:
d.name.where(d.name == 'World', np.nan)
d.name.where(d.name == 'World', np.nan).max()

rawDescription: getting string from pandas Series and DataFrames in python?

description: Getting string from pandas Series and DataFrames in python


rawDescription: Python Regular Expressions: Capture lookahead value (capturing text without consuming it)


rawDescription: usleep in Python

description: Usleep in Python


code:
import dis
def f(x, y):
    return not x in y
def g(x, y):
    return x not in y
dis.dis(f)
dis.dis(g)

rawDescription: Effect of the position of 'not' in python statement on performance


code:
g = df.groupby('SITE')['VALUE'].mean()
g[g > 0.1]

rawDescription: Pandas groupby to find percent True and False


code:
for col_name in ['col2','col3']:
    plt = figure() #This gives you a new figure to plot in
    x_min = min(df['col1'].min(), df[col_name].min())
    x_max = max(df['col1'].max(), df[col_name].max())
    plt.xlim([x_min,x_max])
    plt.ylim([x_min,x_max])
    plt.axes().set_aspect('equal')
    plt.scatter(df['col1'], df[col_name])

rawDescription: How to plot more than one image with matplotlib?

description: Plot more than one image with matplotlib


code:
import json

from django.http import HttpResponse
from django.core import serializers

def get_object(request, name):
    name = request.GET.get('name', '')
    if name is not None:
        obj = Company.objects.get(name=name)
        company = serializers.serialize('json', [obj,])
        struct = json.loads(company)
        data = json.dumps(struct[0])
        return HttpResponse(data, content_type='json')

rawDescription: AttributeError '' object has no attribute 'get' on returning an object in Get Request


code:
from copy import deepcopy
y = deepcopy(x)

rawDescription: Multi-Referenced Nested Lists

description: Multi-Referenced Nested Lists


code:
import logging

logpath = "/tmp/log.log"
logger = logging.getLogger('log')
logger.setLevel(logging.INFO)
ch = logging.FileHandler(logpath)
ch.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(ch)

def application(env, start_response):
   logger.info("%s %s".format("hello","world!"))
   start_response('200 OK', [('Content-Type', 'text/html')])
   return ["Hello!"]

rawDescription: Write thread-safe to file in python

description: Write thread-safe to file in python


code:
fiblist = [x]
for _ in range(10):
    z = x + y
    fiblist.append(z)
    x, y = z, x
print(fiblist)

rawDescription: Looping the Fibbonacci Sequence in Python


code: df = pd.merge(df1, df2, on='DateTime', how='left').fillna(method='ffill')

rawDescription: Join/Merge two pandas dataframes and filling


code:
def calc_length(start, end, step):
    return (end - start - 1) // step + 1

for i in range(start, end):
    calculated = calc_length(start, i, step)
    empirical = len(range(start, i, step))

    assert calculated == empirical, "{} {}".format(calculated, empirical)

rawDescription: Python: How to calculate the length of a range without creating the range?


code:
word=""
other_file = open("other_file","w")
with open(some_file) as f:
    for line in f.readlines():
        data = line.split()
        if data[0] == "**":
            data[0] = word
        else:
            word = data[0]
        other_file.write(' '.join(data))
other_file.close()

rawDescription: Compare first word of each line and replace if statement is true (Python)


code:
def perf_measure(y_actual, y_hat):
    TP = 0
    FP = 0
    TN = 0
    FN = 0

    for i in range(len(y_hat)):
        if y_actual[i]==y_hat[i]==1:
           TP += 1
    for i in range(len(y_hat)):
        if y_actual[i]==1 and y_actual!=y_hat[i]:
           FP += 1
    for i in range(len(y_hat)):
        if y_actual[i]==y_hat[i]==0:
           TN += 1
    for i in range(len(y_hat)):
        if y_actual[i]==0 and y_actual!=y_hat[i]:
           FN += 1

return(TP, FP, TN, FN)

rawDescription: Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative


code:
import locale
loc = locale.getlocale() # get current locale
locale.getdefaultlocale() # Tries to determine the default locale settings and returns them as a tuple of the form (language code, encoding); e.g, ('en_US', 'UTF-8').

rawDescription: Python: get OS language

description: Python: get OS language


code:
import watcher
w = watcher.Watcher(dir, callback)
w.flags = watcher.FILE_NOTIFY_CHANGE_FILE_NAME
w.start()

rawDescription: Is it possible to monitor every file creation on a Windows drive?


code:
import pexpect
child = pexpect.spawn ('sudo mod -p -c noresource -u dtt -Q')
child.expect ('First question:')
child.sendline ('Y')
child.expect ('Second question:')
child.sendline ('Yup')

rawDescription: Is it possible to communicate with a sub subprocess with subprocess.Popen?


code:
import re

string = 'CommonSettingsMandatory = #toto,tata#, true'
splitlist = re.split('\s?=\s?#(.*?)#,\s?', string)

rawDescription: Python : How to ignore a delimited part of a sentence?


code:
exts.append( Extension('_socket', ['socketmodule.c'],
                       depends = ['socketmodule.h']) )

rawDescription: Where is the _socket file?

description: Where is the _socket file


code:
self.columnButton = \
    gtk.TreeViewColumn ('Enabled', self.buttonRenderer,
                        active = 0)  # 0 is the tree store column index

rawDescription: trouble setting up GtkTreeViews in PyGtk

description: Trouble setting up GtkTreeViews in PyGtk


code:
loader = QtUiTools.QUiLoader()
ui = loader.load('filename.ui', parent)
my_widget = ui.my_widget_name

rawDescription: Correct way to address Pyside Qt widgets from a .ui file via Python


code:
def parse_grid(grid):
    values = dict((s, digits) for s in squares)
    for s,d in grid_values(grid).items():
        if d in digits and not assign(values, s, d):
            return False ## (Fail if we can't assign d to square s.)
    return values

rawDescription: Python | returning a variable

description: Python | returning a variable


code:
instance = Parent.objects.prefetch_related('children').all()[0]

try:
    instance._prefetched_objects_cache[instance.children.prefetch_cache_name]
    # Ok, it's pefetched
    child_count = len(instance.children.all())
except (AttributeError, KeyError):
    # Not prefetched
    child_count = instance.children.count()

rawDescription: Django: Can you tell if a related field has been prefetched without fetching it?


code:
from PyQt4.QtCore import QCoreApplication
from PyQt4.QtGui import QApplication
a = QApplication([])
a
QApplication.instance()
QCoreApplication.instance()
b = QCoreApplication([])
b
QCoreApplication.instance()
QApplication.instance()

rawDescription: Difference between QtGui.QApplication and QtCore.QCoreApplication


code:
def flip_member(x):
    if x == 1:
        x += 1
    else:
        x -= 1
    return x

rawDescription: Reuse specific lines of code

description: Reuse specific lines of code


code:
import sys
sys.path.insert(0,'path/to/your/folder/containing/file/to/be/imported')
import your_module

rawDescription: How to combine and get a single Python file by resolving the imports

description: Combine and get a single Python file by resolving the imports


code:
@login_required
def user_profile(request):
    success = False
    user = User.objects.get(pk=request.user.id)
    if request.method == 'POST':
        upform = UserProfileForm(request.POST, instance=user.get_profile())
        if upform.is_valid():
            up = upform.save(commit=False)
            up.user = request.user
            up.save()
            success = True
    else:
        upform = UserProfileForm(instance=user.get_profile())

    return render_to_response('profile/index.html',
        locals(), context_instance=RequestContext(request))

rawDescription: Django, updating a user profile with a ModelForm


code:
import subprocess

proc = subprocess.Popen("cat", stdin = subprocess.PIPE, stdout = subprocess.PIPE)

out, err = proc.communicate(input)

rawDescription: Redirect the standard input and output of .net program


rawDescription: Python: Start another python program using parent's python version


rawDescription: pygtk: cannot set parent on toplevel widget

description: Pygtk: cannot set parent on toplevel widget


code:
d1 = {"admin": {"key1": "v2"}}
d2 = {"admin": {"key2": "v3"},
      "user": {"something": "else"}}
keys = list(d1) + list(d2)
d = {k: dict(d1.get(k, {}).items() + d2.get(k, {}).items()) for k in keys}
d

rawDescription: python: combine two nested dictionaries with dictionaries as values of the top level keys

description: Python: combine two nested dictionaries with dictionaries as values of the top level keys


code:
def magicGetSuperClasses(cls):
  return cls.__bases__

rawDescription: Python super class reflection

description: Python super class reflection


code:
mylist = {'apples', 'oranges', 'bananas'}
def part_one () :
    answer_one = raw_input ('>>> ').lower()
    if answer_one in mylist:
        chapter_one()

rawDescription: How to make raw_input accept multiple answers in a simple, fast manner

description: Make raw_input accept multiple answers in a simple, fast manner


code:
def gcd(x, y):
    if y > x:
        x, y = y, x
    r = x % y
    ...

rawDescription: Python - Implementing Functions

description: Python - Implementing Functions


code:
from dateutil.parser import parse
from dateutil.tz import tzoffset
dt = parse('2011-08-24 13:39:00 +0800')
dt.astimezone(tzoffset(None, 3600))

rawDescription: Python pytz Converting a timestamp (string format) from one timezone to another


code:
totalResults = []
totalClasses = []
for key, location in groupby(rows, lambda k: k[0]):
    location = list(location)
    totalResults.append(dict(name=key, data=[x[2] for x in location]))
    totalClasses.append(dict(name=key, data=[x[3] for x in location]))

rawDescription: Python itertools.groupby multiple values


code:
from subprocess import call
call(["adb", "shell", "input", "tap" , "1400" , "800"])

rawDescription: python and (android) adb shell

description: Python and (android) adb shell


code:
from collections import defaultdict

grouped = defaultdict(list)
for position, v in np.ndenumerate(arr):
    grouped[v].append(position)

for v, positions in grouped.items():
    print('{0} is at {1}'.format(v, positions))

rawDescription: python array sorting and indexing

description: Python array sorting and indexing


rawDescription: json object decoding error

description: Json object decoding error


code:
def trace(frame, event, arg_frame):
    print(frame.f_code.co_filename, frame.f_code.co_firstlineno)

sys.settrace(trace)

rawDescription: A list of Python Hooks?

description: A list of Python Hooks


code:
import re, urllib.request

patern = re.compile(r'image/\w*\W*\w*\.jpg', re.I|re.M)

file = open('APODLinks.txt','r')
rf = file.read()
a = rf.split('\n')
file.close()

def lic(li):
    if not li:
        print("No matches found")
    else:
        print('http://apod.nasa.gov/apod/%s' % li[0])
        f.write('http://apod.nasa.gov/apod/%s\n' % li[0])

def main():
    for i in range(len(a)):
        try:
            ur = urllib.request.urlopen(a[i])
        except:
            print('404 not found!')
        mf = re.findall(patern, str(ur.read()))
        lic(mf)

f = open('APODImgs.txt','w')
main()
f.close()

rawDescription: Writing string list to a txt file, but the file is empty why?


code:
def read_file(self, key_name):
    k = Key(self.__bucket)
    k.key = key_name
    if k.exists():
        rawData = k.read()
    else :
        rawData = None
    return rawData

rawDescription: Python Boto Download Questions

description: Python Boto Download Questions


code:
import wx

dc = wx.PaintDC(self)
self.pngimage = wx.Bitmap('image.png', wx.BITMAP_TYPE_PNG)
dc.DrawBitMap(self.pngimage, x, y)

rawDescription: Display a transparent .png in wxpython

description: Display a transparent .png in wxpython


code:
# -*- coding: utf-8 -*-
import datetime
import wx
import wx.lib.sized_controls as SC
import ObjectListView as OLV

class MyData:
    def __init__(self, year, month, day, level, sets, reps):
        self.date = datetime.date(year, month, day)
        self.level = level
        self.sets = sets
        self.reps = reps

    def GetDate(self):
        return self.date

    def GetLevel(self):
        return self.level

    def GetSets(self):
        return self.sets

    def GetRepetitions(self):
        return self.reps

class MyListCtrl(OLV.GroupListView):
    def __init__(self, parent):
        super(MyListCtrl, self).__init__(parent, wx.ID_ANY, style=wx.LC_REPORT)
        self.SetColumns(self._ColumnDefinitions())
        meter_flt = OLV.Filter.TextSearch(self, columns=self.columns[2:3],
                                          text="7")
        self.SetFilter(meter_flt)
        self.SetObjects(self._DataObjects())

    def _DataObjects(self):
        return [MyData(2010,10,8, 1, 2, 3),
                MyData(2005,10,10, 7, 2, 3),
                MyData(2010,10,3, 2, 2, 3),
                MyData(2012,10,10, 1, 2, 3),
                MyData(2014,10,10, 1, 2, 3)
                ]

    def _ColumnDefinitions(self):
        return [OLV.ColumnDefn('Date', valueGetter='GetDate', groupKeyGetter='GetDate'),
                OLV.ColumnDefn('Level', valueGetter='GetLevel', width=150),
                OLV.ColumnDefn('Sets', valueGetter='GetSets', width=100, groupKeyGetter='GetSets'),
                OLV.ColumnDefn('Reps', valueGetter='GetRepetitions', width=200)]

class MyFrame(SC.SizedFrame):
    def __init__(self):
        super(MyFrame, self).__init__(None)
        pane = self.GetContentsPane()

        olv = MyListCtrl(pane)
        olv.SetSizerProps(expand=True, proportion=1)

if __name__ == '__main__':
    import wx.lib.mixins.inspection as WIT
    app = WIT.InspectableApp()
    win = MyFrame()
    win.Show()
    app.MainLoop()

rawDescription: Objectlistview Python: Filtering

description: Objectlistview Python: Filtering


code:
firstline = True
with open("server.txt") as f:
    with open("output.txt", "w") as fw:
        for line in f.readlines(): # For each line in server.txt

            if firstline: # Do not process the header line
                firstline = False
                continue

            if line[-2] == "1": # -2 because -1 is the line return character
                line = line[:-2] + "noissue\n"
            else:
                line = line[:-2] + "issue\n"
            fw.write(line)

rawDescription: Replace word in text file comma separated with word in a specific column with Python


code:
cts_tradefed_script = "./android-cts/tools/cts-tradefed"
process = subprocess.Popen([cts_tradefed_script + " " + serialno], shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

rawDescription: automating android CTS with python

description: Automating android CTS with python


code:
my_string = 'Hello {name}, my name is {my_name}!'

to_replace = {
    "search_for" : "replace_with",
    "name" : "minerz029",
}

for search_str in to_replace:
    my_string = my_string.replace('{' + search_str + '}', to_replace[search_str])

print(my_string)

rawDescription: How can I escape the format string?

description: Escape the format string


code:
from collections import defaultdict
d=defaultdict(list)
for item in a:
 d[(item['latitude'],item['longtitude'])].append(item)

d
d.values()

rawDescription: How do I group elements in a list to be list of lists in python 3

description: Group elements in a list to be list of lists in python 3


code:
from django.db.models import Count
Image.objects.annotate(Count("person")).order_by("person__count")

rawDescription: Django queryset ordering by _set

description: Django queryset ordering by _set


code:
import csv
import random
import string
import sys

UNSORTED_FILENAME = 'unsorted.csv'
SORTED_FILENAME = 'sorted.csv'

def main():
    """This function handles execution of the entire program."""
    # seed = setup_random_sequence(111411468)
    seed = setup_random_sequence()
    write_random_file(UNSORTED_FILENAME, seed)
    header, data = load_and_sort(UNSORTED_FILENAME)
    write_csv_file(SORTED_FILENAME, header, data)
    print('Your files have been generated. Goodbye!')

def setup_random_sequence(seed=None):
    """Seed the random number generator with some specific value."""
    if seed is None:
        seed = get_int('Enter your ID for your random number sequence: ')
    random.seed(seed, 2)
    return seed

def get_int(prompt='>>> '):
    """Get an integer from the user and return it to the function's caller."""
    while True:
        try:
            text = input(prompt)
        except EOFError:
            sys.exit()
        else:
            try:
                return int(text)
            except ValueError:
                print('You must enter an integer.')

def write_random_file(filename, seed):
    """Create random file based on the user data."""
    rows = ((rubbish_string(string.ascii_letters, 5),
             rubbish_string(string.digits, 4))
            for _ in range(random.randint(10, 20)))
    write_csv_file(filename, ('Personal ID', seed), rows)

def write_csv_file(filename, header, data):
    """Write the now sorted list to a file."""
    with open(filename, 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(header)
        writer.writerows(data)

def rubbish_string(selection, length):
    """Create a string of given length built of characters from selection."""
    return ''.join(random.choice(selection) for _ in range(length))

def load_and_sort(filename):
    """Load the file given by filename and sort by user specification."""
    sort_on_column = None
    while True:
        sort_on_column = get_int('Which column should file be sorted on? ')
        if sort_on_column in {1, 2}:
            break
        print('Column number is out of range.')
    with open(filename, newline='') as file:
        reader = csv.reader(file)
        header = next(reader)
        data = list(reader)
    selection_sort(data, sort_on_column)
    return header, data

def selection_sort(array, column):
    """This is a modified function for selection sort from part Q7A."""
    array.sort(key=lambda row: row[column - 1].casefold())

if __name__ == '__main__':
    main()

rawDescription: How to sort a CSV file's column without regard for character casing?

description: Sort a CSV file's column without regard for character casing


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

fig, ax = plt.subplots()

simbh = np.array([5.3,  5.3,  5.5,  5.6,  5.6,  5.8,  5.9,  6.0,   6.2,  6.3,  6.3])
simstel = np.array([10.02, 10.08, 9.64, 9.53, 9.78, 9.65, 10.05, 10.09, 10.08, 10.22, 10.42])
sca2 = ax.scatter(simstel, simbh)
for x, y in zip(simstel, simbh):
    ax.annotate('', xy=(x, y), xytext=(0, 25), textcoords='offset points',
                arrowprops=dict(arrowstyle="<|-"))

rawDescription: Plot vertical arrows for my points

description: Plot vertical arrows for my points


code:
def ray_intersect(A, B, C, D):
   """
   Intersect two line segments defined by A->B and C->D
   Returns the time of intersection along A->B
   """

   # turn C->D into a plane...
   E = D-C
   n = np.array((-E[1], E[0]))
   # ...and do the regular plane vs ray maths
   numerator = np.dot(C-A, n)
   denom = np.dot(B-A, n)

   return numerator / denom;

rawDescription: Could someone help me translate this short code snippet into python?


code: module[name] = type(name, (base_class,), d)

rawDescription: What is a non-deprecated way to do `new.classobj(name, (base_class,), my_dict)`


code:
from collections import defaultdict
# Use a default dict to make our life easier (we already know we are working with lists)
data = defaultdict(list)
# Get each item from each list, the below list-comprehension is efficient.
for item in [item for sublist in biglist for item in sublist if '=' in item]:
    key, value = item.split('=', 1)  # split the items on '=' but only once.
    data[key].append(value)  # add our new value to our dictionary.

pd.DataFrame(data)  # tada!

rawDescription: separate text and numbers and convert to dataframe in python

description: Separate text and numbers and convert to dataframe in python


code: df = pd.read_csv(location, names=names, header=None, delim_whitespace=True)

rawDescription: How to read a large text file in Python?

description: Read a large text file in Python


code:
import numpy as np
x,y=np.meshgrid(np.linspace(0,6,7),np.linspace(0,8,9)) # create x,y grid
z=x**2*y # and z values
# create larger versions with two more columns/rows
xlarge=np.zeros((x.shape[0]+2,x.shape[1]+2))
ylarge=np.zeros((x.shape[0]+2,x.shape[1]+2))
zlarge=np.zeros((x.shape[0]+2,x.shape[1]+2))
xlarge[1:-1,1:-1]=x # copy data on centre
ylarge[1:-1,1:-1]=y
zlarge[1:-1,1:-1]=z
# fill extra columns/rows
xmin,xmax=-50,50
ymin,ymax=-40,40
xlarge[:,0]=xmin;xlarge[:,-1]=xmax # fill first/last column
xlarge[0,:]=xlarge[1,:];xlarge[-1,:]=xlarge[-2,:] # copy first/last row
ylarge[0,:]=ymin;ylarge[-1,:]=ymax
ylarge[:,0]=ylarge[:,1];ylarge[:,-1]=ylarge[:,-2]
# for speed gain: store factor of first/last column/row
first_column_factor=(xlarge[:,0]-xlarge[:,1])/(xlarge[:,1]-xlarge[:,2])
last_column_factor=(xlarge[:,-1]-xlarge[:,-2])/(xlarge[:,-2]-xlarge[:,-3])
first_row_factor=(ylarge[0,:]-ylarge[1,:])/(ylarge[1,:]-ylarge[2,:])
last_row_factor=(ylarge[-1,:]-ylarge[-2,:])/(ylarge[-2,:]-ylarge[-3,:])
# extrapolate z; this operation only needs to be repeated when zlarge[1:-1,1:-1] is updated
zlarge[:,0]=zlarge[:,1]+first_column_factor*(zlarge[:,1]-zlarge[:,2]) # extrapolate first column
zlarge[:,-1]=zlarge[:,-2]+last_column_factor*(zlarge[:,-2]-zlarge[:,-3]) # extrapolate last column
zlarge[0,:]=zlarge[1,:]+first_row_factor*(zlarge[1,:]-zlarge[2,:]) # extrapolate first row
zlarge[-1,:]=zlarge[-2,:]+last_row_factor*(zlarge[-2,:]-zlarge[-3,:]) #extrapolate last row

rawDescription: Extrapolate with LinearNDInterpolator

description: Extrapolate with LinearNDInterpolator


code:
image = np.zeros((20, 20), dtype=np.double)
image[13:17, 13:17] = 1
m = moments(image)
cr = m[0, 1] / m[0, 0]
cc = m[1, 0] / m[0, 0]
moments_central(image, cr, cc)

rawDescription: What to use for the arguments of skimage.measure.moments_central( )?


code:
if event.type == pygame.VIDEORESIZE:
    setGet(event.size)

rawDescription: pygame, how to update the window size when resizing it

description: Pygame, how to update the window size when resizing it


code:
#!/usr/bin/python
import pygame
from pygame.locals import *

pygame.init()
pygame.display.set_caption('End credits')
screen = pygame.display.set_mode((800, 600))
screen_r = screen.get_rect()
font = pygame.font.SysFont("Arial", 40)
clock = pygame.time.Clock()

def main():

    credit_list = ["CREDITS - The Departed"," ","Leonardo DiCaprio - Billy","Matt Damon - Colin Sullivan", "Jack Nicholson - Frank Costello", "Mark Wahlberg - Dignam", "Martin Sheen - Queenan"]

    texts = []
    # we render the text once, since it's easier to work with surfaces
    # also, font rendering is a performance killer
    for i, line in enumerate(credit_list):
        s = font.render(line, 1, (10, 10, 10))
        # we also create a Rect for each Surface.
        # whenever you use rects with surfaces, it may be a good idea to use sprites instead
        # we give each rect the correct starting position
        r = s.get_rect(centerx=screen_r.centerx, y=screen_r.bottom + i * 45)
        texts.append((r, s))

    while True:
        for e in pygame.event.get():
            if e.type == QUIT or e.type == KEYDOWN and e.key == pygame.K_ESCAPE:
                return

        screen.fill((255, 255, 255))

        for r, s in texts:
            # now we just move each rect by one pixel each frame
            r.move_ip(0, -1)
            # and drawing is as simple as this
            screen.blit(s, r)

        # if all rects have left the screen, we exit
        if not screen_r.collidelistall([r for (r, _) in texts]):
            return

        # only call this once so the screen does not flicker
        pygame.display.flip()

        # cap framerate at 60 FPS
        clock.tick(60)

if __name__ == '__main__':
    main()

rawDescription: Python/Pygame - Create "End credits" like the ones at the end of a movie


code:
# German locale
loc= locale.setlocale(locale.LC_TIME,("de","de"))
try:
     date= datetime.date.strptime( input, "%d. %b. %Y" )
except:
     # English locale
     loc= locale.setlocale(locale.LC_TIME,("en","us"))
     date= datetime.date.strptime( input, "%d. %b. %Y" )

rawDescription: Handling international dates in python

description: Handling international dates in python


code:
log = logging.getLogger('my_logger')
memlog = io.StringIO()
log.addHandler(logging.StreamHandler(memlog))

rawDescription: How to enable logging so messages kept internally until get/clear?

description: Enable logging so messages kept internally until get/clear


code:
from twython import Twython, TwythonError
import time

APP_KEY = '##########'  # Customer Key here
APP_SECRET = '#############'  # Customer secret here
OAUTH_TOKEN = '###############'  # Access Token here
OAUTH_TOKEN_SECRET = '################'  # Access Token Secret here

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

try:
    with open('jokes.txt', 'r+') as fp:
        buff = fp.readlines()

    for line in buff[:]:
        if len(line) < 140:
            print("Tweeting...")
            twitter.update_status(status=line)
            time.sleep(3)
            with open('jokes.txt', 'w') as fp:
                buff.remove(line)
                fp.writelines(buff)
        else:
            with open('jokes.txt', 'w') as fp:
                buff.remove(line)
                fp.writelines(buff)
            print("Skipped line - Char Length Violation")
            continue

except TwythonError as e:
    print(e)

rawDescription: Removing and updating lines in a text file - Python


code:
from matplotlib import pyplot as plt
import numpy as np
from matplotlib_venn import venn3

# Create the diagram
plt.figure(figsize=(4,4))
v = venn3(subsets=(1, 2, 3, 4, 5, 6, 7), set_labels = ('A', 'B', 'C'))
plt.title("Sample Venn diagram")

# Make all patches of the diagram pickable
for p in v.patches:
    if p is not None: p.set_picker(True)

# This is the event handler
def on_pick(event):
    p = event.artist
    ec = p.get_edgecolor()
    p.set_edgecolor('black' if ec[-1] == 0.0 else 'none')
    plt.gcf().canvas.draw()   # Redraw plot

# Connect event handler
plt.gcf().canvas.mpl_connect('pick_event', on_pick)

# Show the plot
plt.show()

rawDescription: How i can pick(select) venn diagram area


code:
a = [{u'time': 136.648, u'name': u'machine', u'value': 71.3}]
b = str(a)[1:-1]
c = '{"time": 136.648, "name": "machine", "value":71.3}'
d = json.loads(c)
a
type(a)
a[0]
a[0]['time']
b
type(b)
b[0]
b['time']
c
type(c)
c[0]
c['time']
d
type(d)
d['time']

rawDescription: How to access python dictionary

description: Access python dictionary


rawDescription: convert tuple keys of dict into a new dict

description: Convert tuple keys of dict into a new dict


code:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

rawDescription: python socket send immediately

description: Python socket send immediately


code:
import urllib, urllib2
from BeautifulSoup import BeautifulSoup as bs_parse

data = urllib.urlencode(values)
req  = urllib2.Request(url, data)
res  = urllib2.urlopen(req)
page = bs_parse(res.read())

rawDescription: beautifulsoup and mechanize to get ajax call result

description: Beautifulsoup and mechanize to get ajax call result


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

X = np.random.rand(100, 3)*10
Y = np.random.rand(100, 3)*5

plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
sc = ax.scatter(X[:, 0], X[:, 1], X[:, 2])
fig.show()

for i in range(0, 20):
    plt.pause(1)

    Y = np.random.rand(100, 3)*5

    sc._offsets3d = (Y[:,0], Y[:,1], Y[:,2])
    plt.draw()

rawDescription: Updating a pyplot 3d scatter plot in a loop, grid lines overlap points


code:
l = [('date_published', 'date'), ('headline', 'headline'), ('description', 'description')]
for dict_val, html_val in l:
    try:
        meta_dict[dict_val] = html.find(html_val).text
    except:
        meta_dict[dict_val] = ''

rawDescription: Shorter try except block for many vars

description: Shorter try except block for many vars


rawDescription: Python3 hashing function override

description: Python3 hashing function override


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

driver = webdriver.Firefox()  # could also be headless: webdriver.PhantomJS()
driver.get('http://schoolsite.edu')

# submit a login form
username = driver.find_element_by_name('j_username')
password = driver.find_element_by_name('j_password')

username.send_keys(USERNAME)
password.send_keys(PASSWORD)

username.submit()

# wait for the badge count to appear
badge_count = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "badgeTotalCount")))

print(badge_count.text)

rawDescription: Hidden HTML elements using Mechanize Python


code:
import bpy, mathutils

plane = bpy.data.objects["Plane"]
previous = None

for poly in plane.data.polygons:
  center = mathutils.Vector(poly.center)
  if previous:
    previous -= center
    #print length and center
    print(previous.length, center)
  previous = center

rawDescription: How get length of Navigation Mesh?

description: How get length of Navigation Mesh


rawDescription: min function in numpy array

description: Min function in numpy array


code:
import json

py_dict = {'a': 'b'}
# Convert dict to string
json_obj = json.dumps(py_dict)
# oops need to make a change -> convert from string to dict
py_dict = json.loads(json_obj)
# append to dict
py_dict['hello'] = 'world'
# Convert dict to string
json_obj = json.dumps(py_dict)

rawDescription: Python writing to a json

description: Python writing to a json


code:
from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

x_img = Image.open("lenac.tif")
x_gray = x_img.convert("L")
x = np.array(x_gray)
for i in range(0,4):
    y = x > (2**(7-i))-1
    z = x - y * (2**(7-i))
    x = z

y = y.astype('uint8') * 255        # This scales the pixel values

new_img = Image.fromarray(y ,'L')  # Use y here instead of y.astype(...)
plt.imshow(new_img, cmap='gray')
#plt.show()
new_img.save("lena_4.bmp")

rawDescription: Lenna compression save all black python

description: Lenna compression save all black python


code:
textsurface=font.render('Test', True, (0, 0, 0))
surface=pygame.Surface((100, 30))
surface.fill((255, 255, 255))
surface.blit(textsurface, pygame.Rect(0, 0, 10, 10))
surface.set_alpha(50)
window.blit(surface, pygame.Rect(0, 30, 10, 10))

rawDescription: Python - Pygame - rendering translucent text


code:
local_tz = pytz.timezone('US/Pacific-New')
date = datetime.datetime.fromtimestamp(
    float(data['timeStamp']) / 1000,
    local_tz
)

rawDescription: Format the iCloud Timestamp

description: Format the iCloud Timestamp


code:
result = urlfetch.fetch("http://www.domain.com/",
                        headers={"Authorization":
                                 "Basic %s" % base64.b64encode("username:password")})

rawDescription: Python GAE urlfetch credentials

description: Python GAE urlfetch credentials


code:
def rates_fetcher(url):
    html = urllib.request.urlopen(url).read()
    soup = BeautifulSoup(html)
    return [item.text for item in soup.find_all(class_='rightCol')]

rawDescription: Python: Reading a webpage and extracting text from that page


code:
def runscript():
    answer=raw_input("input")
    if answer == "stop":
        stop()
    elif answer == "login":
        login()
    elif answer == "list":
        list()

rawDescription: Use the return() function and not have a newline


code:
def save(self, *args, **kwargs):
    initialise_skill_links = not self.pk
    super(NWODCharacter, self).save(*args, **kwargs)
    if initialise_skill_links:
        CharacterSkillLink.objects.bulk_create([
            CharacterSkillLink(
                skill=SkillAbility.objects.get_or_create(skill=skill)[0],
                content_object=self
            )
            for skill in SkillAbility.Skills
        ])

rawDescription: Autopopulate a set of generic many to many fields in Django?


rawDescription: Get function's 'namespace path'

description: Get function's 'namespace path'


code:
plt.imshow(X, aspect='auto', interpolation='None')
plt.colorbar()
plt.show()

rawDescription: matplotlib plot a matrix of unbalanced axis

description: Matplotlib plot a matrix of unbalanced axis


code:
import csv
import random

words = dict(csv.reader(open("file.csv")))
randWord = random.choice(words.keys())
correctAnswer = words[randWord]

if answer == correctAnswer:
    ...

rawDescription: Get random line from CSV file in Python and find corresponding word, like a quiz


code:
import os

def dup_structure(src, dst):
    os.makedirs(dst)
    for p, ds, fs in os.walk(src):
        for dn in ds:
            dp = os.path.relpath(os.path.join(p, dn), src)
            os.makedirs(os.path.join(dst, dp))
        #for fn in fs:
        #    fp = os.path.relpath(os.path.join(p, fn), src)
        #    with open(os.path.join(dst, fp), 'wb'): pass

dup_structure('a', 'b')

rawDescription: Simulate database structure

description: Simulate database structure


code: scores = [read_score(f, normalize=True) for f in glob.glob(path)]

rawDescription: Pythonic and concise way to construct this list?


code:
from _collections_abc import list_iterator
list_iterator is type(iter([]))

rawDescription: Importing list_iterator

description: Importing list_iterator


rawDescription: Accesing the output of grouped data in Pandas DataFrame python


code:
# import V
fn = 'cooltemp.dat'
V = loadtxt(fn,unpack=True,usecols=[1])
# print V

@np.vectorize
def result(x):
    def integrand(E):
        del1, del2, R, fE, fEeV = 1.0,2.0,1.0,1.0,1.0
        e = 1.602176565*10**-19
        a = E/( math.sqrt( E**2 - del1**2 ) )
        b = ( E+ e*x )/( math.sqrt( ( E + e*x )**2) - del2**2)
        c = fE-fEeV
        d = 1/(e*R) # integration constant
        return a * b * c
    return quad(integrand, -inf, inf)

I = result(V)

rawDescription: Python/Scipy Integration array

description: Python/Scipy Integration array


rawDescription: Rank values in a 2D array

description: Rank values in a 2D array


code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import LogLocator
x = np.linspace(0, 10, 10)
y = 2**x
f = plt.figure()
ax = f.add_subplot(111)
plt.yscale('log')
ax.yaxis.set_major_locator(LogLocator(base=100))
ax.plot(x, y)
plt.show()

rawDescription: Controlling tick spacing in log-scale

description: Controlling tick spacing in log-scale


code:
d
"{A} then {B} and also {C}".format(**d.iloc[0])

rawDescription: Apply string.format() to row in Pandas DataFrame


code:
def get_non_base_10(s):
    #support for base 2,8,and 16
    if s.startswith("O") and s[1:].isdigit():
       return int(s[1:],8)
    elif s.startswith("0x") and s[2:].isdigit():
       return int(s[2:],16)
    elif s.startswith("0b") and s[2:].isdigit():
         return int(s[2:],2)

def get_number(s,decimal_separator=".",thousands_separator=","):
    if isinstance(s,basestring):
       temp_val = get_non_base_10(s)
       if temp_val is not None:
          return temp_val
       s = s.replace(decimal_separator,".").replace(thousands_separator,"")
    try:
       return float(s)
    except ValueError:
       return "nan"

def is_number(s,decimal_separator=".",thousands_separator=",",return_type="b"):
    numeric = get_number(s,decimal_separator,thousands_separator)
    return numeric if return_type != "b" else numeric != "nan"

rawDescription: Is there a more Pythonic way to test if an object is a number or return its value?


code:
labels, uniques = df.A.factorize()
df.A = labels
df

rawDescription: Turning a column of strings into a column of integers in Pandas


code:
file2 = open("/path/to/file2", "r")
market_names = {}
for line in file2:
  fields = line.split(",")
  market_names[int(fields[0])] = fields[1]
file2.close()

file1 = open("/path/to/file1", "r")
for line in file1:
  fields = line.split(",")
  market_name = market_names[int(fields[1])]
  # do what ever you want with the Market_Name associated with
  # the Market_ID contained in this line
file1.close()

rawDescription: Get value from 2nd list based on ID from 1st list in Python


code:
def pytest_funcarg__api(request):
    api = myclass()
    #do some initialisation...
    mp = request.getfuncargvalue("monkeypatch")
    mp.setattr(api,"get_external_stuff", Mock())
    mp.setattr(api,"morestuff", Mock())
    return api

rawDescription: py.test use monkeypatch in custom funcargs

description: Py.test use monkeypatch in custom funcargs


code:
with open(filename,"r") as infile:
    cursor.execute("insert into mytable (file_contents) values (%s)", (infile.read(), ))

rawDescription: python - need help inserting text files with open() into mysql

description: Python - need help inserting text files with open() into mysql


code:
STATIC_ROOT = os.path.join(os.path.abspath(
    os.path.join(PROJECT_ROOT, 'myproj_public', 'static')), '')

STATIC_URL = '/static/'

rawDescription: Django - referencing static files in templates


rawDescription: Assign two variables from list of tuples in one iteration


code:
# a first
for dimension in particles:
    ...

# b first
for particle in particles:
    ...

# c first
for timestep in particles:
    ...

rawDescription: Order of indexes in a Numpy multidimensional array


code:
from datetime import datetime

def try_parsing_date(text):
    for fmt in ('%Y-%m-%d', '%d.%m.%Y', '%d/%m/%y'):
        try:
            return datetime.strptime(text, fmt)
        except ValueError:
            pass
    raise ValueError('no valid date format found')

rawDescription: How to format date string via multiple formats in python

description: Format date string via multiple formats in python


code:
import subprocess
subprocess.Popen(["python.exe", 'C:/Dokumente und Einstellungen/schnei17/Desktop/python/zeit/1.py'])
subprocess.Popen(["python.exe", 'C:/Dokumente und Einstellungen/schnei17/Desktop/python/zeit/2.py'])

rawDescription: Python: start many scripts at the same time


code:
def send_mail(modeladmin, request, queryset):
    for msg in queryset:
        send_mail('People information', msg.name, msg.price, msg.email,
    [msg.email])
send_mail.short_description = u'Send e-mail to selected objs'

class PeopleAdmin(admin.ModelAdmin):
    list_display = ('name', 'email')
    actions = (send_mail,)

rawDescription: Django. How to create specific function in admin site that send a e-mail?


code:
def readnumbers(filename,number,year):
    strings_number = 'A'+ str(number)
    strings_year = ' ' + str(year)
    STARTER = strings_number + '' + strings_year

    result = []
    with open(filename) as f:
        start_seen = False

        # iterate the file handle
        for line in f:
            # only check the line for STARTER if you haven’t seen it yet
            if not start_seen and line.strip() == STARTER:
                start_seen = True

            # otherwise, check if it’s a stopper which starts with `A`
            elif start_seen and line.startswith('A'):
                break

            # otherwise, if we’ve seen the start line, we need to capture the result
            elif start_seen:
                parts = line.split()

                # append to the result list
                result.append(parts)

    # finally, return the result
    return result

rawDescription: Write text data to array between boundaries


code:
with open('/tmp/in') as input_file:
    with open('/tmp/out', 'w') as output_file:
        input = input_file.read()
        output_file.write(''.join(re.findall(r'(?s)(?<={{).*?(?=}})', input)))

rawDescription: Writing from file to another file in Python from certain set of characters to another one


code:
import random

def decision(probability):
    return random.random() < probability

rawDescription: True or false output based on a probability


code:
s = '1. Good morning 2. Hello 3. Bye'
import re
re.split('\d+\. ', s)

rawDescription: How to split string separated numbers

description: Split string separated numbers


code:
def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None

rawDescription: Test if executable exists in Python?

description: Test if executable exists in Python


rawDescription: Condition checking in two complex multi-dimensional arrays of same shape


code:
trans = {'lw': '100011',
    'sw': '101011',
    'jal': '000011',
    'beq': '000100',
    'andi': '001100',
    'ori': '001101',
    'addi': '00100'}

with open ('output.txt', 'w') as f:
    try: f.write (trans [inst] )
    except KeyError: print ('Operation not supported')

rawDescription: how to implement assembler program

description: Implement assembler program


code:
from operator import itemgetter
from itertools import groupby

[max(items) for key, items in groupby(L,key = itemgetter(1))]

rawDescription: Get tuples with max value from each key from a list


code:
for each in People.objects.all()[:3]:
    item_salary=Salary()
    item_salary.id_of_people_id=each.id
    item_salary.save()

rawDescription: Django loop through all items to save, but it only saves one record


code:
def func(l=None, d=None):
    if l is None:
       l = list()  #or l = []
    if d is None:
       d = dict()  #or d = {}

rawDescription: Correct way to specify default empty list/dict/set/etc as function arg


code:
from sqlalchemy import func
selection = users.filter(coalesce(Users.status, 0) == 1,
                         coalesce(Users.no_reminders, 0) == 0,
                         func.dbo.pplBalance(Users.user_id, datetime.datetime.now()) < -0.01).all()

rawDescription: Is it possible in SQLAlchemy to filter by a database function or stored procedure?


code:
self.request_parser.add_argument(
    name='address',
    required=True,
    type=unicode,
    help="Needs argument: 'address' - The address"
)

rawDescription: Special characters in Python Flask's reqparse.RequestParser()


code:
from __future__ import print_function
import MySQLdb as mdb

conn = mdb.connect("localhost","username","passwd","db")
table = open("table.csv" , 'w')
query = "SELECT NAME FROM mytable WHERE H_ID= 5 ORDER BY NAME;"
cursor = conn.cursor()
cursor.execute(query)
for item in range(cursor.rowcount):
    row = cursor.fetchone()
    print(row[0],file=table)
table.close()

rawDescription: python write to file is breaking

description: Python write to file is breaking


code: dict(p.split('=') for p in input.split('\001'))

rawDescription: what is the best way to unpack a FIX message into a python dictionary?

description: What is the best way to unpack a FIX message into a python dictionary


code:
import os
import socket

if os.name != "nt":
    import fcntl
    import struct

    def get_interface_ip(ifname):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s',
                                ifname[:15]))[20:24])

def get_lan_ip():
    ip = socket.gethostbyname(socket.gethostname())
    if ip.startswith("127.") and os.name != "nt":
        interfaces = [
            "eth0",
            "eth1",
            "eth2",
            "wlan0",
            "wlan1",
            "wifi0",
            "ath0",
            "ath1",
            "ppp0",
            ]
        for ifname in interfaces:
            try:
                ip = get_interface_ip(ifname)
                break
            except IOError:
                pass
    return ip

rawDescription: Python - Get localhost IP

description: Python - Get localhost IP


code:
mylist = [(1,2,3),(6,1,1),(7,8,1),(3,4,5)]
import itertools
set(itertools.chain.from_iterable(mylist))

rawDescription: List of unique items in a list of tuples


code:
def remove_1(tup):
    result = []
    for r in tup:
        r = r[1:]
        result.append(r)
    return tuple(result)

rawDescription: The difference between use print and return in a loop


code:
import urllib
url = driver.find_element_by_link_text("Download").get_attribute("href");
urllib.urlretrieve(url, "saveasfilename")

rawDescription: Avoid download file dialog box in Python/selenium automation


code:
def _set(self, i, obj):
    self._success, self._value = obj
    if self._callback and self._success:  # <-----
        self._callback(self._value)       # <-----
    self._cond.acquire()
    try:
        self._ready = True
        self._cond.notify()
    finally:
        self._cond.release()
    del self._cache[self._job]

rawDescription: python AsyncResult.successful() does not return

description: Python AsyncResult.successful() does not return


code:
import sum2
import numpy as np
x=np.array(1.0,dtype=np.float64)
y=np.array(2.0,dtype=np.float64)
z=np.array(0.0,dtype=np.float64)
sum2.sum2(x,y,z)
z

rawDescription: Unable to change and return value in Fortran subroutine + notebook


code: {' '.join(line.split()[:-2]):' '.join(line.split()[-2:]) for line in lines}

rawDescription: How to read variating data into dictionary?

description: Read variating data into dictionary


code:
class child(pandas.Panel4D):
    def __init__ (self, d=None):
        if isinstance(d, pandas.Panel4D):
            d = d._data
            super(child, self).__init__(d)
        else:
            super(child, self).__init__(d)

rawDescription: Initializing an extended class with an instance when the parent class can't take itself as argument for the constructor


code:
groups = df.groupby(['username', pd.cut(df.views, bins)])
groups.size().unstack()

rawDescription: Pandas groupby with bin counts

description: Pandas groupby with bin counts


code:
def combined(name, value):
    foo(**{name:value})

rawDescription: How to convert a string into an identifier in python?

description: Convert a string into an identifier in python


code:
df
df['dics'].apply(pd.Series)

rawDescription: Sublists in pandas

description: Sublists in pandas


code:
def __add__(self, rhs):
  return getattr(self, 'decimal', self) + getattr(other, 'decimal', other)

rawDescription: Python3 "magic functions" stack trace

description: Python3 "magic functions" stack trace


code:
s = 'acquire Wooden Shield'
s.split(' ', 1)

rawDescription: Split a string in python into only two parts starting from the left


code:
#short hand:
metals.xs('BI', level=0).xs('Arsenic, Dissolved', level=0).xs(1, level=1)

# more verbose
metals.xs('BI', level='bmp_category').xs('Arsenic, Dissolved', level='parameter').xs(1, level='storm')

# two chained `ix` calls:
metals.ix['BI', 'Arsenic, Dissolved'].ix[:, 1]

rawDescription: How do I really use the `ix` method of a pandas DataFrame?

description: Really use the `ix` method of a pandas DataFrame


code:
from pyspark.sql.functions import lit
new_df = df.withColumn('column_name', lit(10))

rawDescription: Replace all values of a column in a dataframe with pyspark


code:
import inspect
import dis

class A(object):
    def __add__(self, other):
        fr = inspect.getouterframes(
            inspect.currentframe(), 1)[1][0]
        opcode = fr.f_code.co_code[fr.f_lasti]
        # opcode = ord(opcode) # Uncomment for Python 2
        is_op = opcode == dis.opmap['BINARY_ADD']
        if is_op:
            print('Called with +')
        else:
            print('Called with __add__')

A() + 1
A().__add__(1)

rawDescription: Know if + or __add__ called on an object


code:
ack_pkt = sniff(offline="../mptcp/mptcpdemo.pcap", count=14)[0]
ack_pkt.show()

rawDescription: Unable to send MPTCP packet with Scapy sendp()


code:
from datetime import datetime

hour = datetime.now().hour
print("The current hour is " + hour + "!")

rawDescription: How do I import specific parts of the time, e.g. hours or minutes in Python?

description: Import specific parts of the time, e.g. hours or minutes in Python


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

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig = plt.figure()
# set height ratios for sublots
gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])

# the fisrt subplot
ax0 = plt.subplot(gs[0])
# log scale for axis Y of the first subplot
ax0.set_yscale("log")
line0, = ax0.plot(x, y, color='r')

#the second subplot
# shared axis X
ax1 = plt.subplot(gs[1], sharex = ax0)
line1, = ax1.plot(x, y, color='b', linestyle='--')
plt.setp(ax0.get_xticklabels(), visible=False)
# remove last tick label for the second subplot
yticks = ax1.yaxis.get_major_ticks()
yticks[-1].label1.set_visible(False)

# put lened on first subplot
ax0.legend((line0, line1), ('red line', 'blue line'), loc='lower left')

# remove vertical gap between subplots
plt.subplots_adjust(hspace=.0)
plt.show()

rawDescription: Python - Subplots merging with shared x-axis, different y-scalings and figures


code:
try:
   gpsp.start()
except SomethingHere:
   print('Oops, GPS failed!')
   sys.exit()

while not gpsp.fix.latitude:
   time.sleep(4) # Pause till the GPS has obtained a fix

lat = gpsp.fix.latitude
lon = gpsp.fix.longitude

payload = {'vehic':"PJ048",'lat':lat,'lon':lon}

r = requests.post("http://my-server.com/Pi/Loc.php",data=payload)
r.raise_for_status()

rawDescription: Retrieve final value returned from while statement


code:
df
df["Rank"].ffill()
df["Rank"] = df["Rank"].ffill()
df

rawDescription: How to update rows for one column based on string value of another? Python Pandas

description: Update rows for one column based on string value of another? Python Pandas


code: [(k,i) for k,m in enumerate(ref, 1) for i,j in enumerate(m, 1) if 'yellow' in j]

rawDescription: finding index in a nested list

description: Finding index in a nested list


code:
def myfn(m):
    return re.sub(r'\s+', ' ', m.group().strip())

pat = re.compile(r"^\w+\s+=\s\(\n.*?\n\)$", re.S | re.M)
mdls_output = pat.sub(myfn, mdls_output)

rawDescription: Efficiently replace multi-line list strings with single_line list string


code:
cmyk_scale = 100

def rgb_to_cmyk(r,g,b):
    if (r == 0) and (g == 0) and (b == 0):
        # black
        return 0, 0, 0, cmyk_scale

    # rgb [0,255] -> cmy [0,1]
    c = 1 - r / 255.
    m = 1 - g / 255.
    y = 1 - b / 255.

    # extract out k [0,1]
    min_cmy = min(c, m, y)
    c = (c - min_cmy) / (1 - min_cmy)
    m = (m - min_cmy) / (1 - min_cmy)
    y = (y - min_cmy) / (1 - min_cmy)
    k = min_cmy

    # rescale to the range [0,cmyk_scale]
    return c*cmyk_scale, m*cmyk_scale, y*cmyk_scale, k*cmyk_scale

rawDescription: How can I convert RGB to CMYK and vice versa in python?

description: Convert RGB to CMYK and vice versa in python


code:
import itertools

def generate(f, x):
  return itertools.accumulate(itertools.repeat(x), lambda v,_:f(v))

for i, val in enumerate(generate(lambda x: 2*x, 3)):
  print(val)
  if i == 10:
    break

rawDescription: python generator endless stream without using yield

description: Python generator endless stream without using yield


code:
import urllib2
from xml.dom import minidom

usock = urllib2.urlopen('http://ws......')
xmldoc = minidom.parse(usock)

staffs = xmldoc.getElementsByTagName("DadosEstoque")
for staff in staffs:
        sku = staff.getElementsByTagName("CodigoProduto")[0]
        protocolo = staff.getElementsByTagName("ProtocoloEstoque")[0]
        print("SKU: %s" % (sku.firstChild.data))
        print("PROTOCOLO: %s" % (protocolo.firstChild.data))

rawDescription: How to parse XML using BeautifulSoap?

description: Parse XML using BeautifulSoap


code:
# Read in the data from the stackoverflow question
df = pd.read_clipboard().iloc[1:]

# Convert it to "long-form" or "tidy" representation
df = pd.melt(df, id_vars=["date"], var_name="condition")

# Plot the average value by condition and date
ax = df.groupby(["condition", "date"]).mean().unstack("condition").plot()

# Get a reference to the x-points corresponding to the dates and the the colors
x = np.arange(len(df.date.unique()))
palette = sns.color_palette()

# Calculate the 25th and 75th percentiles of the data
# and plot a translucent band between them
for cond, cond_df in df.groupby("condition"):
    low = cond_df.groupby("date").value.apply(np.percentile, 25)
    high = cond_df.groupby("date").value.apply(np.percentile, 75)
    ax.fill_between(x, low, high, alpha=.2, color=palette.pop(0))

rawDescription: Plotting time-series data with seaborn

description: Plotting time-series data with seaborn


code: [True if x is None else False for x in metrics]

rawDescription: Numpy array of lil_matrix objects - is empty?


code:
while True:
    x = int(input("What number?: "))
    if x == 1:
        y = str(input("What colour?: "))
        if y == "Red":
            print("ok")
            z = int(input("Do you wanna ask another num+colour? (1/0 is yes/no): "))
            if z == 1:
                continue # to the next iteration
            elif z == 0:
                break # finish loop

rawDescription: Python 3 - How do I return to first input after going a few if statements deep into code?


code:
from collections import defaultdict
d = defaultdict(list)
l = [('admincases', 'test_case_6'), ('admincases', 'test_case_8'),('admincases1', 'test_case_8'),('admincases1', 'test_case_9'),('admincases1', 'test_case_10')]
for k,v in l:
   d[k].append(v)

d['admincases']

rawDescription: How to achieve data search in python list

description: Achieve data search in python list


code:
original = 'a,1,b,2,c,3'
s = original.split(',')
s
alternate = map(''.join, zip(s[::2], s[1::2]))
alternate

rawDescription: string splitting after every other comma in string in python

description: String splitting after every other comma in string in python


code: result = [myFunc(p, additionalArgument) for p in pages]

rawDescription: Python map list item to function with arguments


rawDescription: Python - How to get a function to actually return `None`?


code:
import sys
sys.path.append('PATH_TO/config')
import common

rawDescription: importing from parent directory

description: Importing from parent directory


code:
locs = np.arange(grid_resid.shape[1],step=100) # locations
plt.xticks( locs, xp_int[locs], rotation="vertical" )

rawDescription: Less frequent ticks on the x axis in Pyplot


code:
import os, sys, io, win32api, win32console, pywintypes

def change_file_encoding(f, encoding):
    """
    TextIOWrapper is missing a way to change the file encoding, so we have to
    do it by creating a new one.
    """

    errors = f.errors
    line_buffering = f.line_buffering
    # f.newlines is not the same as the newline parameter to TextIOWrapper.
    # newlines = f.newlines

    buf = f.detach()

    # TextIOWrapper defaults newline to \r\n on Windows, even though the underlying
    # file object is already doing that for us.  We need to explicitly say "\n" to
    # make sure we don't output \r\r\n; this is the same as the internal function
    # create_stdio.
    return io.TextIOWrapper(buf, encoding, errors, "\n", line_buffering)

class ConsoleFile:
    class FileNotConsole(Exception): pass

    def __init__(self, handle):
        handle = win32api.GetStdHandle(handle)
        self.screen = win32console.PyConsoleScreenBufferType(handle)
        try:
            self.screen.GetConsoleMode()
        except pywintypes.error as e:
            raise ConsoleFile.FileNotConsole

    def write(self, s):
        self.screen.WriteConsole(s)

    def close(self): pass
    def flush(self): pass
    def isatty(self): return True

    @staticmethod
    def wrap_standard_handles():
        sys.stdout.flush()
        try:
            # There seems to be no binding for _get_osfhandle.
            sys.stdout = ConsoleFile(win32api.STD_OUTPUT_HANDLE)
        except ConsoleFile.FileNotConsole:
            sys.stdout = change_file_encoding(sys.stdout, "utf-8")

        sys.stderr.flush()
        try:
            sys.stderr = ConsoleFile(win32api.STD_ERROR_HANDLE)
        except ConsoleFile.FileNotConsole:
            sys.stderr = change_file_encoding(sys.stderr, "utf-8")

ConsoleFile.wrap_standard_handles()

print("English 漢字 Кири́ллица")

rawDescription: Python os.walk and japanese filename crash


rawDescription: Hiding Python Code from non-programmers

description: Hiding Python Code from non-programmers


code:
#models.py
class Room(models.Model):
    room_number = models.CharField(max_length=20, primary_key=True, null=False, blank=False)
    isolation_status = models.BooleanField()

class Treatment(models.Model):
    room_number = models.ForeignKey(Room, primary_key=True)
    treated = models.BooleanField()

    def save(self, *args, **kwargs):
        is_new = False
        if self.pk is None:
            is_new = True
        super(Treatment,self).save(*args, **kwargs)
        if is_new:
            self.room_number.isolation_status = False
            self.room_number.save()

class Isolation(models.Model):
    room_number = models.ForeignKey(Room, primary_key=True)

rawDescription: django model instance edit

description: Django model instance edit


code: [week_array[:] for _ in range(4)]

rawDescription: Creating a generator expression or list comprehension without variable "x in" (e.g. for range) in Python


rawDescription: Multiple assignments into a python dictionary


code:
string = "banana"
list(enumerate(string))  # Just to demonstrate
[x for x,y in enumerate(string) if y == 'a']
[x for x,y in enumerate(string) if y == 'n']

rawDescription: Finding the Positions of a Letter that Appear in a String


code: df.drop_duplicates(cols = 'uniqueid', inplace = True)

rawDescription: Selecting unique observations in a pandas data frame


code:
links = sel.xpath('//a[contains(@href, "enforcementactions.pdf") and contains(@class, "titlelink")]')
for link in links:
    item = PDFItem()
    item['title'] = link.xpath('text()').extract()[0]
    item['url'] = URL + link.xpath('@href').extract()[0]

rawDescription: python - pull pdfs from webpage and convert to html

description: Python - pull pdfs from webpage and convert to html


code:
from sqlalchemy.sql import compiler

from psycopg2.extensions import adapt as sqlescape
# or use the appropiate escape function from your db driver

def compile_query(query):
    dialect = query.session.bind.dialect
    statement = query.statement
    comp = compiler.SQLCompiler(dialect, statement)
    comp.compile()
    enc = dialect.encoding
    params = {}
    for k,v in comp.params.iteritems():
        if isinstance(v, unicode):
            v = v.encode(enc)
        params[k] = sqlescape(v)
    return (comp.string.encode(enc) % params).decode(enc)

rawDescription: How do I get a raw, compiled SQL query from a SQLAlchemy expression?

description: Get a raw, compiled SQL query from a SQLAlchemy expression


code:
class QScene(QtGui.QGraphicsScene):
    def __init__(self, *args, **kwds):
        QtGui.QGraphicsScene.__init__(self, *args, **kwds)

    def mousePressEvent(self, ev):
        if ev.button() == QtCore.Qt.LeftButton:
            item = QtGui.QGraphicsTextItem("CLICK")
            item.setPos(ev.scenePos())
            self.addItem(item)

rawDescription: pyQt4 QGraphicsView on mouse event help needed

description: PyQt4 QGraphicsView on mouse event help needed


code:
# main_script.py

#some code

p1 = subprocess.Popen(['/path/to/process.sh'], shell=True)
p1.wait()

#rest of code when process is done

rawDescription: Run a process in python, writing the process output to stdout?


code:
class CommentResource(ModelResource):
    def obj_create(self, bundle, request=None, **kwargs):
        if bundle.data.get("replace_existing_rating", False):
            try:
                bundle.obj = self._meta.object_class._default_manager.get(**conditions)
            except self._meta.object_class.DoesNotExist:
                bundle.obj = self._meta.object_class()

rawDescription: How can I make Django-Tastypie override a resource if it already exists?

description: Make Django-Tastypie override a resource if it already exists


rawDescription: Confused on this regular expression pattern in Python


code:
def format_name(fname, lname):
    if lname:
        return "{0} {1}.".format(fname, lname)
    return fname

rawDescription: Python simple first_name last_initial when last_name could be blank


code:
def formatCurrency(value):
    return "$" + format(value, '.2f')  # don't print the value but return it

print("That is %s for this service" % formatCurrenty(cost))

rawDescription: How to remove a space in Python

description: Remove a space in Python


code:
from dateutil import parser
list_dates = ['2013-05-01', '15th Oct 2013', '01-05-13', '2013/FEB/05']
[parser.parse(date).strftime('%Y-%m-%d') for date in list_dates]

rawDescription: How to convert Dates into Specified Format using python?

description: Convert Dates into Specified Format using python


code:
import sys
import threading
import unittest
from unittest.mock import patch

class T(threading.Thread):
    def __init__(self,  *args, **kwargs):
        super(T, self).__init__(*args, **kwargs)
        self._interrupt = threading.Event()
        self.started = threading.Event() #Used to be sure that we test run() behavior
        self.started.clear()
        self.terminated = False

    def interrupt(self):
        self._interrupt.set()

    def run(self, *args, **kwargs):
        self._interrupt.clear()
        self.started.set()
        while not self._interrupt.is_set():
            self._interrupt.wait(timeout=1)
        self.terminated = True
        sys.exit()

class TestInterrupt(unittest.TestCase):

    @patch("sys.exit", side_effect=Exception("Ignore it... just close thread"))
    def test_interrupt(self, mock_sys_exit):
        t = T()
        t.start()
        if not t.started.is_set():
            t.started.wait(timeout=0.2)
        self.assertTrue(t.started.is_set(), "t not started!")
        #Ok t is in run() main cycle: we can test interrupt
        t.interrupt()
        t.join(0.1)
        self.assertTrue(t.terminated)
        self.assertFalse(t.isAlive())

rawDescription: Return or break as a side effect in python mock?


code:
class Base(dict):
    def __init__(self, *args, **kwargs):
        super(Base, self).__init__(*args, **kwargs)
        self.setdefault('id', -1)
        self.setdefault('name', None)

class ClassA(Base):
    """ClassA is a class inherited from a Base class."""
    def __init__(self, *args, **kwargs):
        if not (args or kwargs):
             raise Exception('you need to give me *something*!')
        super(ClassA, self).__init__(*args, **kwargs)
        self.setdefault('win', None)
        self.setdefault('mac', None)

rawDescription: Python: Class Inheritance and Incoming Arguments


code:
#!/usr/bin/python

import asyncmongo
import tornado.web

class Handler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.db = asyncmongo.Client(pool_id='mypool', host='localhost',
                                          port=27107, dbname='mydb')

        self.db.first_names.find_one({'user_id': 1 },
                                     callback=self._on_response)

    def _on_response(self, response, error):
        first_name = response['first_name']
        data = {
              'first_name': first_name
        }

        # use processor
        self.first_name_html = self.generate_html("firstname.html").generate(**data)
        foo()

    def foo(self):
        self.db.last_names.find_one({'user_id': 1 },
                                 callback=self._on_response_two)

    def _on_response_two(self, response, error):
        last_name = response['last_name']
        data = {
              'last_name': last_name
        }

        # use processor
        last_name_html = self.generate_html("lastname.html").generate(**data)
        self.write(self.first_name_html + last_name_html)
        self.finish()

rawDescription: external asynchronous method inside asynchronous method

description: External asynchronous method inside asynchronous method


code:
s = set()

def letter(x,z):
    for i in x:
        for f in z:
            if i == f:
                s.add(i)

letter("hello","world")
print("".join(s))

rawDescription: python printing common items in a string without duplicating

description: Python printing common items in a string without duplicating


code:
def is_sorted(lst):
    return all(a <= b for a,b in zip(lst, lst[1:]))

rawDescription: How can I make a code that determines if a list is sorted or not in Python?

description: Make a code that determines if a list is sorted or not in Python


code:
class CommonModel(Base):
    __abstract__ = True

    id = Column(Integer, primary_key=True)
    a = Column(Text)
    b = Column(Text)

class Foo(CommonModel):
    __tablename__ = 'foo'

class Bar(CommonModel):
    __tablename__ = 'bar'

rawDescription: Is there a way to duplicate a table definition in SQLAlchemy?


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

fig, ((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2, figsize=(11,10))

labels1 = ('new', 'closed', 'developing', 'testing', 'tbd')
labels2 = ('Intern', 'Kunde')
labels3 = ('HW', 'SW')
labels4 = ('Closed', 'Open')

sizes1 = [1, 2, 3, 4, 5]
sizes2 = [1,2]
sizes3 = [1,2]
sizes4 = [1,2]

colors1 = ['#F5FC34', '#52FC34', '#FAAB23', '#237DFA', '#C863FA', ]
colors2 = ['#FAF063', '#63BBFA']
colors3 = ['#6A0D7D', '#503C3C']
colors4 = ['#58FB4C', '#F8183A']

explode1 = (0, 0, 0, 0, 0)
explode2 = (0, 0)
explode3 = (0, 0)
explode4 = (0, 0)

ax1.pie(sizes1, explode=explode1, colors=colors1, autopct='%1.1f%%',shadow=True, startangle=90)
ax2.pie(sizes2, explode=explode2, colors=colors2, autopct='%1.1f%%',shadow=True, startangle=90)
ax3.pie(sizes3, explode=explode3, colors=colors3, autopct='%1.1f%%',shadow=True, startangle=90)
ax4.pie(sizes4, explode=explode4, colors=colors4, autopct='%1.1f%%',shadow=True, startangle=90)

ax1.set_title("Status")
ax2.set_title("Department")
ax3.set_title("Origin")
ax4.set_title("Closed-Status")

ax1.legend(labels1, bbox_to_anchor=(0.05, 0.8))
ax2.legend(labels2, bbox_to_anchor=(1.25, 0.65))
ax3.legend(labels3, bbox_to_anchor=(0, 0.6))
ax4.legend(labels4, bbox_to_anchor=(1.25, 0.65))

plt.show()

fig.savefig('/Users/ite1/Desktop/test.png', bbox_inches="tight")

rawDescription: Matplotlib: Different views from plt.savefig() and manual saving


code: (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03)

rawDescription: What is python equivalent of CvTermCriteria in OpenCV 2.3.1 and above?


code:
with open("output.txt", "w") as file:
    file.write("\n".join(ipAddresses))

rawDescription: Write List of IP Addresses to text file - Python 2.7


code: NN = pd.concat((pd.read_csv(f.split('\n')[0]) for f in filename))

rawDescription: I have a bunch of csv files, I am reading them using pandas from python. I want to use a combination of map & lambda functions to do this


rawDescription: while loop (Python)

description: While loop (Python)


code:
from mock import patch
with patch('sys.exit') as exit_mocked:
    call_command(...)
    exit_mocked.assert_called_with(1)

rawDescription: How to return a non-zero exit code on a custom Django command while being able to test it?

description: Return a non-zero exit code on a custom Django command while being able to test it


code:
p.sendline('some command')
try:
    p.expect(processing_finished_mark)
except KeyboardInterrupt:
    p.sendintr()

rawDescription: In IPython, can extensions handle kernel interrupts?


code:
referrer = self.request.headers.get('referer')
if referrer:
    return self.redirect(referrer)
return self.redirect_to('home')

rawDescription: How to redirect user to previous page when Logout?

description: Redirect user to previous page when Logout


code:
for t1 in tags:
    if t1 not in todelete:
        for t2 in tags:
            if t2.name_insensitive == t1.name:
                merge(t1,t2)
                todelete.append(tag)

rawDescription: SQLAlchemy: Efficient way of merging duplicate tags


code:
ROWS = 200000
COLS = 100
PATLEN = 20
#random data for example's sake
a = np.random.rand(ROWS,COLS)
pattern = np.random.rand(PATLEN)

tmp = np.empty([ROWS, COLS-PATLEN])
for i in xrange(COLS-PATLEN):
    window = a[:,i:i+PATLEN]
    tmp[:,i] = np.sum((window-pattern)**2, axis=1)

result = np.sqrt(tmp)

rawDescription: Fast algorithm to search for pattern within text file


code:
#!/bin/env/python

import os

from subprocess import call

if __name__ == '__main__':
    if 'TRAVIS' in os.environ:
        rc = call('coveralls')
        raise SystemExit(rc)

rawDescription: Conditional Commands in tox? (tox, travis-ci, and coveralls)


rawDescription: Removing non-token punctation marks from a string


rawDescription: How to sort a list alphabetically FAVORING numbers

description: Sort a list alphabetically FAVORING numbers


code:
match = re.findall('"string":([^,]+)', name)
if len(match) > 0:
    movinf.write("\n".join(match))
movinf.close()

rawDescription: Find multiple instances of a string in a text file - python


code:
def print_host(host, address):
    f = open(host, 'w')
    f.write("""define host {{
        host_name            {host}
        alias                {host}
        display_name         {host}
        address              {address}
        use                  linux-server
        register             1
    }}\n""".format(host=host, address=address))

print_host("myhost", "10.10.10.10")

rawDescription: Python: write multiple str.format() lines to a file?


code:
#!/usr/bin/env python
def check(filename, vName):
    with open(filename, 'r') as f:
        count = 0
        for data in f:
            if vName in data:
                count += 1
                if count == 3:
                    print("You have already played 3 times!")
                    return 0

check("a.txt", "Reece")

rawDescription: Python not reading data from file?

description: Python not reading data from file


code:
def pytest_generate_tests(metafunc):
    funcarglist = metafunc.cls.cases[metafunc.function.__name__]
    argnames = list(funcarglist[0])
    argvalues = []
    ids = []
    for i in funcarglist:
        inner_argvalues_list = []
        inner_ids_list = []
        for j in argnames:
            inner_argvalues_list.append(i[j])
            if type(i[j]) != str:
                inner_ids_list.append(i[j].__repr__())
            else:
                inner_ids_list.append(i[j])
        argvalues.append(inner_argvalues_list)
        ids.append(inner_ids_list)
    metafunc.parametrize(argnames, argvalues, ids=ids)

rawDescription: How can I configure pytest to generate useful names when generating tests?

description: Configure pytest to generate useful names when generating tests


code:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privkey = paramiko.RSAKey.from_private_key_file('xxx.pem')
ssh.connect('xxx.compute-1.amazonaws.com', username='ubuntu', pkey=privkey)
stdin, stdout, stderr = ssh.exec_command("nohup ssh  -f -o StrictHostKeyChecking=no -i     ~/.ssh/xxx.pem ubuntu@xxx.compute-1.amazonaws.com -L 16646:localhost:16646 -L -N >& /dev/null < /dev/null &")
ssh.close()

rawDescription: Unable to truly background an SSH tunnel using Fabric and nohup


code:
from PySide import QtGui

def beep():
    print('beep')

app = QtGui.QApplication([])

toolbar = QtGui.QToolBar()
toolbar.show()

action = QtGui.QAction("Action", toolbar, shortcut=QtGui.QKeySequence("O, P"), triggered=beep)
toolbar.addAction(action)

app.exec_()

rawDescription: Two key shortcuts

description: Two key shortcuts


code:
import hashlib
"this is binary \0\1\2"
hashlib.sha1("this is binary \0\1\2").hexdigest()

rawDescription: Python - hashing binary value

description: Python - hashing binary value


code:
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull

# RANDOM DATA
x = np.random.normal(0,1,100)
y = np.random.normal(0,1,100)
xy = np.hstack((x[:,np.newaxis],y[:,np.newaxis]))

# PERFORM CONVEX HULL
hull = ConvexHull(xy)

# PLOT THE RESULTS
plt.scatter(x,y)
plt.plot(x[hull.vertices], y[hull.vertices])
plt.show()

rawDescription: Plotting a set of given points to form a closed curve in matplotlib


code:
import pandas as pd

meat_lng = pd.melt(meat, id_vars=['date'])

p = ggplot(aes(x='date', y='value'), data=meat_lng)
p + geom_point() + \
    stat_smooth(colour="red") + \
    facet_wrap("variable")

p + geom_hist() + facet_wrap("color")

p = ggplot(diamonds, aes(x='price'))
p + geom_density() + \
    facet_grid("cut", "clarity")

p = ggplot(diamonds, aes(x='carat', y='price'))
p + geom_point(alpha=0.25) + \
    facet_grid("cut", "clarity")

rawDescription: yhat ggplot facet_wrap type error

description: Yhat ggplot facet_wrap type error


rawDescription: gtk+ signal emitted when window/dialog is "presented"

description: Gtk+ signal emitted when window/dialog is "presented"


code:
def updatereds(val):
    global d0, z0
    delt = svlsr.val/c
    z = sreds.val

    if z!=0.0:
        if z != z0:
            delt = z
            svlsr.set_val(z*c) #set_val causes infinite loop??

    d0 = delt
    z0    = z
    fac = 1.0 + delt
    l.set_xdata(t*fac)
    fig.canvas.draw_idle()

def updatesvlsr(val):
   # put any code you need to execute on direct update to svlsr here
   # the only thing you can't do is set_val on sreds, otherwise again
   # you will infinitely recurse
   pass

svlsr.on_changed(updatesvlsr)
sreds.on_changed(updatereds)

rawDescription: Link two matplotlib sliders together

description: Link two matplotlib sliders together


code:
def find_element(L):
    pct = 0.75 * sum(L)
    s = 0
    for i, element in enumerate(L):
        if s > pct:
            break
        else:
            s += element
    return L[i]

rawDescription: percent capture value using if-else list condition

description: Percent capture value using if-else list condition


code:
import sys
sys.path.append('../src') # OnLinux  - use r'..\src' for Windows

rawDescription: Beginner at testing Python code, need help!


code: value = getattr(__builtins__, type_name)(value)

rawDescription: Get type instance from string in Python

description: Get type instance from string in Python


code:
a = [(datetime.date(2014, 8, 3), datetime.date(2014, 8, 16)), (datetime.date(2014, 7, 20), datetime.date(2014, 8, 2))]

[tuple(map(str, i)) for i in a]

rawDescription: How to convert a tuple to string in python

description: Convert a tuple to string in python


code:
import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen("http://yoursite.com")
soup = BeautifulSoup(page)

# See the docs on how to search through the soup. I'm not sure what
# you're looking for so my example stops here :)

rawDescription: Python Script to check website for a tag