code:
from collections import defaultdict
import random

data = [random.randint(1,10) for _ in xrange(100)]

d = defaultdict(int)  # means default value is 0
# d = {}

for x in data:  # go through list
    d[x] += 1  # increment counts
    # d[x] = d.get(x, 0) + 1

# sort dict items by value (count) in descending order
sorted_items = sorted(d.items(), key=lambda i: -i[1])
# sorted_items = sorted(d.items(), key=lambda i: i[1], reverse=True)

# extract the keys
sorted_keys = [k for k, v in sorted_items]

# take n best
n = 8
n_most = sorted_keys[:n]

# [9, 5, 10, 3, 6, 2, 4, 1]

rawDescription: How to Obtain k Most/Least Frequent in a list?

description: Obtain k Most/Least Frequent in a list


code:
import inspect
import types

def decorator(func):
    def inner(*args, **kwargs):
        print('function: ' + func.__name__)
        print('args: ' + repr(args))
        print('kwargs: ' + repr(kwargs) + '\n')
        func(*args, **kwargs)
    return inner

for name, fn in inspect.getmembers(Turtle):
    if isinstance(fn, types.FunctionType):
        if(name[0] != '_'):
            setattr(Turtle, name, decorator(fn))

rawDescription: How to output python turtle commands to terminal as they are being executed?

description: Output python turtle commands to terminal as they are being executed


code: c.f = lambda x, f=c.f: f(x) + 1

rawDescription: Infinite recursion using lambda in python


code:
results = ['N'] * 12  # prebuild results to all no

safety_courses = UserMonthlySafetyCurriculums.objects.filter(
                     users_id=id).order_by('month_assigned')

for course in safety_courses:
    results[course.month_assigned - 1] = 'Y'

rawDescription: Django query / Iteration issue

description: Django query / Iteration issue


code:
import re
s = 'hello <wolfrevokcats>, how <t uoy era>oday?'
re.sub('<(.*?)>', lambda m: m.group(1)[::-1], s)

rawDescription: Reverse marked substrings in a string

description: Reverse marked substrings in a string


rawDescription: Pad only in one direction with tkinter?

description: Pad only in one direction with tkinter


code:
def toCSVLine(data):
  return ','.join(str(d) for d in data)

lines = labelsAndPredictions.map(toCSVLine)
lines.saveAsTextFile('hdfs://my-node:9000/tmp/labels-and-predictions.csv')

rawDescription: How to write the resulting RDD to a csv file in Spark python

description: Write the resulting RDD to a csv file in Spark python


code:
import ctypes
import sdl2

def get_keyboard_state():
    """ Returns a list with the current SDL keyboard state,
    which is updated on SDL_PumpEvents. """
    numkeys = ctypes.c_int()
    keystate = sdl2.keyboard.SDL_GetKeyboardState(ctypes.byref(numkeys))
    ptr_t = ctypes.POINTER(ctypes.c_uint8 * numkeys.value)
    return ctypes.cast(keystate, ptr_t)[0]

rawDescription: PySDL2 and SDL_GetKeyboardState

description: PySDL2 and SDL_GetKeyboardState


code:
for player in self.players:
    for hand_idx in range(len(player.hands)):
        if player.hands[hand_idx].smallest_value() > 21:
            player.hands[hand_idx]=0
    player.hands=filter(None,hands)

rawDescription: Why can I not delete list elements while iterating in an OO setting?


code:
df_test
row_replacements = { 'one': [3.1, 2.2], 'two' : [8.8, 4.4] }
df_update = DataFrame.from_dict(row_replacements, orient='index')
df_update.columns = ['b', 'c']
df_test.update(df_update)
df_test

rawDescription: Using a dictionary to replace column values on given index numbers on a pandas dataframe


code:
lat = [1,2,3,1]
long = [7,8,9,7]
speed = [20,50,29,49]
data = {}
for i in range(len(lat)):
    try:
        data[(lat[i],long[i])].append(speed[i])
    except KeyError:
        data[(lat[i],long[i])]=[speed[i]]

data

rawDescription: Python: Average specific elements in a third array by the indexes of duplicate pairs of long and lat in two other arrays


code:
from pandas import Series
import datetime

datetime_index = [datetime.datetime(2010, 1, 5), datetime.datetime(2010, 1, 10)]
s1 = Series([5, 15], [datetime.datetime(2010, 1, 5), datetime.datetime(2010, 1, 15)])
s2 = Series(None, datetime_index)
s3 = s1.combine_first(s2)
s3.interpolate()

rawDescription: How can I do an interpolating reindex in pandas using datetime indices?

description: Do an interpolating reindex in pandas using datetime indices


code:
_, sep, rest = mystr.partition(",")
mystr = rest + sep + latestValue

rawDescription: What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python?


code:
import os
import unittest
from paste.fixture import TestApp

class RootTest (unittest.TestCase):

  def setUp(self):
    self.app = TestApp('config:%s/../development.ini' % os.path.dirname(os.path.abspath(__file__)))

  def tearDown(self):
    self.app = None

  def test_html(self):
    res = self.app.get('/')
    res.mustcontain('Hello from restest!')

if __name__ == '__main__':
    unittest.main()

rawDescription: Write unit tests for restish in Python

description: Write unit tests for restish in Python


code:
from subprocess import Popen, PIPE

args = ['/usr/bin/apachectl','configtest']

result = Popen(args,stdout=PIPE,stderr=PIPE).communicate()
# result[0] will be the standard output, result[1] will be the stderr output

rawDescription: Test Apache config file from Python

description: Test Apache config file from Python


code:
class MyDealModelView(ModelView):
    form_excluded_columns = ('merchant_id',)

    def on_model_change(form, model, is_created):
        model.merchant_id = login.current_user.merchant_id;

rawDescription: How to edit flask-admin to support multi tenancy?

description: Edit flask-admin to support multi tenancy


code:
from cStringIO import StringIO

s = "My very long string I want to read like a file"
file_like_string = StringIO(s)
data = file_like_string.read(10)

rawDescription: Python Input/Output, files

description: Python Input/Output, files


code:
import picamera                  # import files

camera = picamera.PiCamera()     # initialize camera
camera.color_effects = (128,128) # turn camera to black and white
camera.capture('image1.jpg')     # take a shot

rawDescription: how to set the camera in raspberry pi to take black and white image?

description: Set the camera in raspberry pi to take black and white image


code:
class C(CapitalizeAnimal, A):
     animal = 'puma'

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

rawDescription: Python Multiple Inheritance/Mixin

description: Python Multiple Inheritance/Mixin


code:
def add_or_find_vertex(g, name):
    try:
        return g.vs.find(name=name)
    except ValueError:
        g.add_vertex(name)
        return g.vs.find(name=name)

rawDescription: Add vertices and duplicate names

description: Add vertices and duplicate names


code:
import autocomplete_light.shortcuts as al

al.register(your_model,
    attrs={
        'data-autocomplete-minimum-characters': 0,
    },
)

rawDescription: Django-autocomplete-light textwidget display all the values before typing


code:
QTextBrowser.mousePressEvent(self, mouseEvent)

QTextBrowser.mouseReleaseEvent(self, mouseEvent)

rawDescription: Selection of text in QTextBrowser

description: Selection of text in QTextBrowser


code:
import scipy as sp
import scipy.integrate

xp = sp.linspace(0, 1000, 1000)
yp = sp.randn(1000)

datafunc = lambda x: sp.interp(x, xp, yp)

sp.integrate.quad(datafunc, 3, 1000)

rawDescription: Multiple integrations of a data-function over a small portion of its domain - accuracy and efficiency


rawDescription: How to display all label values in matlibplot?

description: Display all label values in matlibplot


rawDescription: Python: Write a list of numeric values on a single row with a repeated format


code:
class Inner(SomeBaseClass):
    def __init__(self, logger, *args):
        self.logger = logger
        self.logger.info('initializing Child with %', ' '.join(args))

class Outer(object):
    def __init__(self, logging, logger_name='Parent'):
        self.logging = logging
        self.logger = self.logging.getLogger(logger_name)

    def get_inner(self, *args):
        return Inner(self.logger, *args)

logging.config.fileConfig('logging.conf')
outerObject = Outer(logging)

inner1 = outerObject.get_inner('xyzz')
inner2 = outerObject.get_inner('abc')

rawDescription: Using varibles of a class inside nested classes in Python


code:
def labelConfig(string,append=False):
    if append:
        text = label.cget("text") + string
        label.configure(text=text)
    else:
        label.configure(text=string)

rawDescription: Appending text to label tkinter

description: Appending text to label tkinter


code:
import requests
import json

url = 'https://api.github.com/users'
token = "my_token"
headers = {'Authorization': 'token %s' % token}

outfile = open('users.json', 'a')

while True:
    r = requests.get(url, headers=headers)
    users = r.json()
    json.dump(users, outfile)
    url = r.links['next'].get('url')
    # I don't know what Github return in case there is no more users, so you need to double check by yourself
    if url == '':
        break

outfile.close()

rawDescription: Python append json to json file in a while loop


code:
class StrTest:
    def __init__(self, num):
        self.num = num

    def __str__(self):
        return str(self.num)

    def __html__(self):
        return mark_safe(
            'Number is {0}'.format(self.num))

rawDescription: Return mark_safe string from __str__

description: Return mark_safe string from __str__


code:
from lxml import etree
from cStringIO import StringIO
tag2values = ['newvalue1', 'newvalue2']
example = StringIO("""\
<main_tag>
   <first>
     <tag1>val1</tag1>
     <conf>
       <tag2>val2</tag2>
       <tag3>val3</tag3>
       <tag4>val4</tag4>
     </conf>
   </first>
   <second>
     <tag1>val2</tag1>
     <conf>
       <tag2>val6</tag2>
       <tag3>val7</tag3>
       <tag4>val8</tag4>
     </conf>
   </second>
</main_tag>
""")
tree = etree.parse(example)
value1selector = '*/conf/tag2[../../tag1/text() = "val1"]'
value2selector = '*/conf/tag2[../../tag1/text() = "val2"]'
for elem in tree.xpath(value1selector):
    elem.text = tag2values[0]

for elem in tree.xpath(value2selector):
    elem.text = tag2values[1]

print(etree.tostring(tree, pretty_print=True))

rawDescription: How to find a tag with some value in python and lxml

description: Find a tag with some value in python and lxml


code:
while GameOn:
  currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
  if len(currentguess) <=0:
    print('Sorry you must enter a guess')
  else:
    correctLength = guess(WordToGuess,currentguess)
    if correctLength == len(WordToGuess):
      print('statement')
      GameOn = False
    elif Guesses <= 0:
      GameOn = False
      print('statement')
    else:
      Guesses = Guesses -1
      print('statement')
      print('statment')

rawDescription: How can you compare frequency of letters between two words in python?

description: Compare frequency of letters between two words in python


code:
try:
    from Tkinter import *
except ImportError:
    from tkinter import *

class GUI:
    textid = 0

    def __init__(self):
        # root window of the whole program
        self.root = Tk()
        self.root.minsize(800, 600)

        # canvas/viewport for displaying the image and drawing vectors on it
        self.viewport = Canvas(self.root, bd=2, relief='ridge', highlightthickness=0)

        # define master buttons for audio preview, render to file and clear all vectors
        btn_preview = Button(self.root, text='Preview', command=self.Preview)

        # layout managing
        self.viewport.grid(columnspan=3, padx=5, pady=5, sticky=N+S+W+E)
        btn_preview.grid(row=1, padx=85, pady=10, ipadx=5, ipady=5, sticky=W)

        # weights of rows and columns
        self.root.rowconfigure(0, weight=1)
        self.root.columnconfigure(0, weight=1)

        # bind mouse actions for the canvas
        self.viewport.bind('<Configure>', self.ResizeCanvas)

    def Preview(self, event=None):
        textpos = (self.viewport.winfo_width(),self.viewport.winfo_height())
        print(textpos)

    def ResizeCanvas(self, event):
        if self.textid != 0:
            event.widget.delete('openfiletext')
        # position text on canvas to notify user he can load the image by clicking it
        textpos = (self.viewport.winfo_width(), self.viewport.winfo_height())
        self.textid = self.viewport.create_text(textpos[0] / 2, textpos[1] / 2, text="Click here to load an image!", justify='center', font='arial 20 bold', tag='openfiletext')

if __name__ == '__main__':
    mainwindow = GUI()
    mainloop()

rawDescription: Tkinter: Get actual canvas size during init (including auto-stretching by "sticky")


code:
theIndices = [1,3,5]
theQIndexObjects = [self.myQStringListModel.createIndex(rowIndex, 0, self.coverages_lm) for rowIndex in theIndices]
for Qindex in theQIndexObjects:
    myListview.selectionModel().select(Qindex, QtGui.QItemSelectionModel.Select)

rawDescription: How do I set the selection in a listview?

description: Set the selection in a listview


code:
fruit = np.array(["apple", "pear", "orange", "grape"])
df.query("food in @fruit")

rawDescription: select rows with certain values of a column in pandas data frames

description: Select rows with certain values of a column in pandas data frames


code:
import re
re.sub(' +',' ','The     quick brown    fox')

rawDescription: A simple way to remove multiple spaces in a string in Python


code:
opinions = ['hello :)', 'world ;)']

emoji = {
    ':)': [],  # smile
    ';)': []   # wink
}

for i in opinions:
    for k, v in emoji.items():
        if k in i:
            v.append(i)
            break  # assuming opinions don't have multiple emoji

rawDescription: Grouping large text data with respect to emoji in Python


code:
import dateutil.parser
x = dateutil.parser.parse('Wed, 27 Oct 2010 22:17:00 GMT')
str(x)
x.strftime('%a, %d %b %Y %H:%M:%S %Z')

rawDescription: How do I parse timezones from dates in python

description: Parse timezones from dates in python


code:
import io
from PIL import Image

with open('pict.txt', 'rb') as img_file:
    img_file.read(2)  # skip over the '0x'
    hex_data = img_file.read()
    binary_data = hex_data.decode('hex')
    memory_file = io.BytesIO(binary_data)
    img = Image.open(memory_file)
    img.show()

rawDescription: Decode pictures from database

description: Decode pictures from database


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

F, (A1,A2) = plt.subplots(ncols=2,figsize=(15,5))

# Option 1:
xxm = np.ma.masked_less(x,25)

cmap1 = cm.get_cmap("jet",lut=10)
cmap1.set_bad("k")

A1.set_title("Using masked array")
P = A1.pcolormesh(LON,LAT,xxm,cmap=cmap1)
plt.colorbar(P,ax=A1)

# Option 2:
cmap2 = cm.get_cmap("jet",lut=10)
cmap2.set_under("k")

A2.set_title("Using vmin")
P = A2.pcolormesh(LON,LAT,xx,cmap=cmap2,vmin=25)
plt.colorbar(P,ax=A2)

plt.show()

rawDescription: pcolormesh with user-defined value level

description: Pcolormesh with user-defined value level


code:
import pycallgraph
import mycode
import stuff_i_dont_want_to_see

pycallgraph.start_trace()
#Initializations

pycallgraph.stop_trace()
stuff_i_dont_want_to_see()
pycallgraph.start_trace()

mycode.things()
pycallgraph.make_dot_graph('cleaner_graph.png')

rawDescription: How to prevent pycallgraph from entering standard library functions?

description: Prevent pycallgraph from entering standard library functions


code:
from functools import partial

def my_func_name(sequence, index):
    widget = sequence[index]
    widget.configure(bg='white') #  for example

for i in range(0,10):
    for j in range(1,11):
        p2 = i * 10 + j
        par = partial(my_func_name, button, p2)
        button[p2] = Button(root, text = vText[i] + str(j), command=par, padx=25, pady=25, bg = "#66CCCC")
        button[p2].grid(row=i, column=j)

rawDescription: Grid of buttons: Change color of one when it is clicked


code:
class F(FilterSet):
    username = MethodFilter(action='filter_username')

    class Meta:
        model = User
        fields = ['username']

    def filter_username(self, queryset, value):
        return queryset.filter(
            username=value
        )

rawDescription: How use MethodFilter from django-filter app?


code:
import socket, time
from threading import Thread

class UserSearcher(Thread):

    def __init__(self):
        print("Thread: User searching is will start now!")
        Thread.__init__(self)

    def run(self):
        self.__tcpListener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__tcpListener.bind(("", 2030))
        self.__tcpListener.listen(5)
        while True:
            try:
                self.__komm, self.__tcpAddr = self.__tcpListener.accept()
                self.__tcpMsg = self.__komm.recv(1024)
                print(self.__tcpMsg)
            except:
                print("Searching for chat members failed! Is the system shutting down?")
                break

    def stop(self):
        self.__tcpListener.shutdown(socket.SHUT_RDWR)
        time.sleep(1)
        print("Thread: User searching will quit NOW!")

rawDescription: Python - Thread with socket won't stop

description: Python - Thread with socket won't stop


code:
import contextlib
import selenium.webdriver as webdriver
import selenium.webdriver.support.ui as ui

with contextlib.closing(webdriver.Firefox()) as driver:
    driver.get('http://www.google.com')
    wait = ui.WebDriverWait(driver,10)
    # Do not call `implicitly_wait` if using `WebDriverWait`.
    #     It magnifies the timeout.
    # driver.implicitly_wait(10)
    inputElement=driver.find_element_by_name('q')
    inputElement.send_keys('Cheese!')
    inputElement.submit()
    print(driver.title)

    wait.until(lambda driver: driver.title.lower().startswith('cheese!'))
    print(driver.title)

    # This raises
    #     selenium.common.exceptions.TimeoutException: Message: None
    #     after 10 seconds
    wait.until(lambda driver: driver.find_element_by_id('someId'))
    print(driver.title)

rawDescription: Selenium waitForElement

description: Selenium waitForElement


code:
with open("test.txt", 'r') as f:
    theta = float(f.readline().strip())
    f.readline()
    alphabet = f.readline().split()
    f.readline()
    alignmentDF = pandas.read_fwf(f, widths=[1,1,1], header=None)

rawDescription: How do I read part of a file into a DataFrame with Python

description: Read part of a file into a DataFrame with Python


code:
x = bytearray(len(secret)*8)   # creates an array of zero bytes
i = 0
for secByte in secret:
    for j in range(8):
        x[i] = setBit(plain[i], 0, getBit(secByte, j))
        i += 1

rawDescription: How to speed up string concatenation in Python?

description: Speed up string concatenation in Python


code:
@app.route('/users/review/step2/c/<token>')
def if_template(token):
    return render_template(
        "template.jinja2",
        create=True)

@app.route('/users/review/step2/u/<token>')
def if_template(token):
    return render_template(
        "template.jinja2",
        update=True)

rawDescription: Parse url with jinja

description: Parse url with jinja


code:
html = '''...
<slide>
    America
    <a> 2 </a>
    <b> 3 </b>
    <c> 4 </c>
</slide>

<slide>
    Germany
    <a> 5 </a>
    <b> 6 </b>
    <c> 7 </c>
</slide>
....'''

import lxml.html
root = lxml.html.fromstring(html)
for slide in root.xpath('.//slide'):
    slide.text = ''

rawDescription: Delete a node lxml python

description: Delete a node lxml python


code:
import os.path

if os.path.splitext(filename)[1] != '.txt':  # Ending is not '.txt'.
   filename += '.txt'

rawDescription: How do I check to see if user added '.txt' to file name and add it if they did not?

description: Check to see if user added '.txt' to file name and add it if they did not


code:
import collections

class Coffee():
    def __init__(self, name='', color='', taste=''):
        self.name = name
        self.color = color
        self.taste = taste

    def __repr__(self):
        return '{0} {1} {2}'.format(self.name, self.color, self.taste)

prompt = "Enter name,color,taste or ctrl-d when done: "
coffees = collections.defaultdict(Coffee)

while True:
    try:
        name, color, taste = input(prompt).split(',')
        coffees[name].name = name
        coffees[name].color = color
        coffees[name].taste = taste
    except ValueError:
        print("Try again!")
    except EOFError:
        print()
        break

print(coffees)

rawDescription: Elegant and Pythonic Approach to Changing List of Objects


code:
import time
exit = True
'''your variables'''
while(exit):
    '''your Code'''
    x = input("Enter 'y' if you want to exit.")
    if x.lower() == y:
        exit = False
        print("All speeding Cars:") # Print all the Cars!
        for plate in numberplates:
            print(plate)

rawDescription: Speed sensor program, loop, python 3 , A level


code:
import pygame
from pygame.locals import *

pygame.init()

screen = pygame.display.set_mode((600,600))
clock = pygame.time.Clock()
FPS = 60

class MovableImage(pygame.Surface):
    def __init__(self, image, xpos=0, ypos=0):
        self.image = image
        self.xpos = xpos
        self.ypos = ypos
        self.width =  image.get_width()
        self.height = image.get_height()
        self.selected = False
        self.rect = pygame.Rect(xpos, ypos, image.get_width(), image.get_height())

    def move(self, move):
        self.xpos += move[0]
        self.ypos += move[1]
        self.rect = pygame.Rect(self.xpos, self.ypos, self.width, self.height)

def Transformation(element):
    element = pygame.transform.scale(element,(50,75))

def init():
    global ImageList
    fire = pygame.Surface((50,50))
    fire.fill((255,0,0))
    #fire = pygame.image.load("ElementIcon/fire.png").convert_alpha()
    #Transformation(fire)
    #fire.set_colorkey(BLACK)
    #fire_rect = fire.get_rect()

    earth = pygame.Surface((50,50))
    earth.fill((255,255,0))
    #earth = pygame.image.load("ElementIcon/earth.png").convert_alpha()
    #Transformation(earth)
    #earth.set_colorkey(BLACK)
    #earth_rect = earth.get_rect()

    fire_obj = MovableImage(fire, 408, 450)
    earth_obj = MovableImage(earth, 419,350)

    ImageList =[]
    ImageList.append(fire_obj)
    ImageList.append(earth_obj)

def run():

    global done
    done = False
    while not done:
        check_events()
        update()
        clock.tick(60)

def check_events():
    global done
    global ImageList

    mouse_pos = pygame.mouse.get_pos()

    for event in pygame.event.get():

        if event.type == pygame.QUIT:
            done = True
            print("User quits the game :(")
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                done = True
                print("Game stopped early by user :( ")

        if event.type == pygame.MOUSEBUTTONDOWN:
            for im in ImageList:
                if im.rect.collidepoint(mouse_pos):
                    im.selected = not im.selected

        if event.type == pygame.MOUSEBUTTONUP:
            for im in ImageList:
                if im.rect.collidepoint(mouse_pos):
                    im.selected = False

        if event.type == pygame.MOUSEMOTION:
            for im in ImageList:
                if im.rect.collidepoint(mouse_pos) and im.selected:
                    xmv = event.rel[0]
                    ymv = event.rel[1]

                    if event.buttons[0]:
                        if xmv < 0:
                            if im.xpos > 0:
                                im.move((xmv,0))

                        elif event.rel[0] > 0:
                            if im.xpos < screen.get_width():
                                im.move((xmv,0))

                        elif event.rel[1] < 0:
                            if im.ypos > 0:
                                im.move((0,ymv))

                        elif event.rel[1] > 0:
                            if im.ypos < screen.get_height():
                                im.move((0,ymv))

def update():
    global ImageList
    screen.fill((255, 255, 255)) #WHITE)

    #Update the screen with drawings
    for im in ImageList:
        screen.blit(im.image, (im.xpos, im.ypos))

    pygame.display.update()

if __name__=="__main__":
    init()
    run()

rawDescription: How to get coordinates of image in pygame

description: Get coordinates of image in pygame


code:
# add() works for mutual indices, so find intersection and call it
# fortunately, it appends list2 to list1!
intersection = series1.index.intersection(series2.index)
inter1 = series1[series1.index.isin(intersection)]
inter2 = series2[series2.index.isin(intersection)]
interAppend = inter1.add(inter2)

# combine_first() unions indices and keeps the values of the caller,
# so it will keep the appended lists on mutual indices,
# while it adds new indices and corresponding values
exclusiveAdd = interAppend.combine_first(series1).combine_first(series2)

rawDescription: Pandas: adding multiindex Series/Dataframes containing lists


code:
from collections import defaultdict
groups= defaultdict( list )
for obj in old_list:
    groups[obj.some_attr].append( obj )
new_list = groups.values()

rawDescription: How to group a list of tuples/objects by similar index/attribute in python?

description: Group a list of tuples/objects by similar index/attribute in python


code:
from ast import literal_eval

def get_type(input_data):
    try:
        return type(literal_eval(input_data))
    except (ValueError, SyntaxError):
        # A string, so return str
        return str

print(get_type("1"))        # <class 'int'>
print(get_type("1.2354"))   # <class 'float'>
print(get_type("True"))     # <class 'bool'>
print(get_type("abcd"))     # <class 'str'>

rawDescription: Identifying the data type of an input

description: Identifying the data type of an input


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

#data
data1 = [11,20,25,80]
data2 = [15,35,50,90]
data3 = [25,36,58,63]
data4 = [30,40,68,78]
element = np.arange(4)

# data is used to automatize the fill_between argument
data = [[data1,data2],[data3,data4]]

# creating an list of the colors used
cols = ['grey','red']

# creating the figure including all axes
fig,ax = plt.subplots(1,2)

for i,a in enumerate(ax):
    phase1 = a.plot(data1,color='blue', lw=2)
    phase2 = a.plot(data2,color='blue', lw=2)
    phase3 = a.plot(data3,color='green', lw=2)
    phase4 = a.plot(data4,color='green', lw=2)
    a.set_xticks(element)
    a.set_xticklabels(['La','Ce','Pr','Nd'])
    a.fill_between(element,data[i][0],data[i][1],color=cols[i])
    a.set_yscale('log')

fig.set_size_inches(10,5)

rawDescription: Subplots in matplotlib creating a loop

description: Subplots in matplotlib creating a loop


code:
import networkx as nx
import numpy as np
A = np.array([[0, 4, 3, 0],
              [0, 0, 0, 1],
              [0, 3, 0, 1],
              [2, 0, 0, 0]])
G = nx.from_numpy_matrix(A, create_using=nx.DiGraph())
print(nx.dijkstra_path(G, 0, 1))

rawDescription: Dijkstra's Algorithm from Adjacency Matrix


code:
from PyQt4 import QtCore, QtGui

class Window(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        message = self.tr('Hello World')
        label = QtGui.QLabel('%s' % message, self)
        buttonbox = QtGui.QDialogButtonBox(self)
        buttonbox.addButton(QtGui.QDialogButtonBox.Yes)
        buttonbox.addButton(QtGui.QDialogButtonBox.No)
        buttonbox.addButton(QtGui.QDialogButtonBox.Cancel)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(label)
        layout.addWidget(buttonbox)

if __name__ == '__main__':

    import sys, os, getopt

    options, args = getopt.getopt(sys.argv[1:], 'hl:')
    options = dict(options)
    if '-h' in options:
        print("""
Usage: %s [opts] [path/to/other.qm]

Options:
 -h        display this help and exit
 -l [LOC]  specify locale (e.g. fr, de, es, etc)
""" % os.path.basename(__file__))
        sys.exit(2)
    app = QtGui.QApplication(sys.argv)
    translator = QtCore.QTranslator(app)
    if '-l' in options:
        locale = options['-l']
    else:
        locale = QtCore.QLocale.system().name()
    # translator for built-in qt strings
    translator.load('qt_%s' % locale,
                    QtCore.QLibraryInfo.location(
                        QtCore.QLibraryInfo.TranslationsPath))
    app.installTranslator(translator)
    if args:
        # translator for app-specific strings
        translator = QtCore.QTranslator(app)
        translator.load(args[0])
        app.installTranslator(translator)
    window = Window()
    window.setGeometry(500, 300, 200, 60)
    window.show()
    sys.exit(app.exec_())

rawDescription: How do you implement multilingual support for pyqt4

description: Implement multilingual support for pyqt4


code:
float.__init__
float.__new__

rawDescription: What does __init__ method of Python immutable class, e.g. float look like?


code:
def function(L):
 if len(L) == 0:return []
 return L+list((L[index] + rest) for index in range(len(L)) for rest in function(L[:index])+L[index+1:])

rawDescription: Python Sum of all subset of list using list comprehension and recursion


code:
sequence = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

def caesar( original, variationShift):
    '''returns: a version of original created by replacing each letter with
       the letter "variationShift" units later in the alphabet sequence.
       If variationShift is negative, replacing letter is found earlier in
       alphabet.'''
    index = 0
    result = ''
    while index < len( original):
        lookFor = original[ index]
        foundAt = sequence.find( lookFor)
        if foundAt == -1:
            # untranslatable character
            result += lookFor
        else:
            result += sequence[ (foundAt + variationShift) % len(sequence)]
        index += 1
    return result

def encryptCaesar (original):
    return caesar( original, -3)

def decryptCaesar (original):
    return caesar( original, 3)

rawDescription: Variable not Defined, Function definition includes variable?


code:
kwargs = {
    '{0}__{1}'.format('name', 'startswith'): 'A',
    '{0}__{1}'.format('name', 'endswith'): 'Z'
}

Person.objects.filter(**kwargs)

rawDescription: In Django, how does one filter a QuerySet with dynamic field lookups?


code:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [TEMPLATE_PATH],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

rawDescription: Django can't find template directory

description: Django can't find template directory


code:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
        'TEST_NAME': 'mytestdatabase'
    }
}

rawDescription: how to test django project

description: Test django project


code:
2**1500
from math import pow
pow(2, 1500)

rawDescription: Python calculating power vs. factorial

description: Python calculating power vs. factorial


code:
import hashlib
from unittest import TestCase

import mock

def md5(file_name):
    hash_md5 = hashlib.md5()
    with open(file_name, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

class MD5TestCase(TestCase):
    def test(self):
        with mock.patch('%s.open' % __name__, mock.mock_open(read_data=b'aaa'), create=True) as m:
            result = md5("lalala")
            self.assertEqual(result, '47bce5c74f589f4867dbd57e9ca9f808')

rawDescription: Python: Mocking a file for unittesting

description: Python: Mocking a file for unittesting


code:
from BeautifulSoup import BeautifulSoup

soup = BeautifulSoup(some_html)

paragraphs = list(unicode(x) for x in soup.findAll('p'))

rawDescription: Python: Separating an HTML snippets to paragraphs


code:
myList = [1, 'from form', [1,2]]
myList[1]
myList[2]
myList[2].append('t')
myList
myList[1].append('t')

rawDescription: AttributeError: 'str' object has no attribute 'append'


code:
def populate( self, tree ):
    tree.setEditTriggers(tree.SelectedClicked)
    for i in range(10):
        item = QTreeWidgetItem(['Testing %02i' % i])
        item.setFlags(item.flags() | item.ItemIsEditable)

rawDescription: QTreeWidget: Windows Explorer-like editing


code:
#to loop through a dictionary
total_0 = 0
list_0 =[]
total_1 = 0
list_1 = []
somedict = {'key1':[1,1,1,0,1,0]}
for key,value in somedict.items():
    # now loop through each list of your dict, since value keep your list
    for item in value:
        if item == 1:
            total_1 += 1
            list_1.append(item)
        else :
            total_0 += 1
            list_0.append(item)

rawDescription: Accessing and manipulating the values ( in list form) of a dictionary


code:
for i in range(len(a[0])):
    b.append([elt[i] for elt in a])

rawDescription: How to append values from a 2d list to another lists and print it

description: Append values from a 2d list to another lists and print it


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

grid = np.zeros((10,10), dtype=np.bool)
square_length = 0.5
circles = {'c1':[[4,2],1.5],'c2':[[5,6],2.0]}

# Generate arrays of indices/coordiates so we can do the
# calculations the Numpy way, without resorting to loops
# I always get the index order wrong so double check...
xx = np.arange(grid.shape[0])
yy = np.arange(grid.shape[1])

for val in circles.itervalues():
    radius = val[1]
    # same index caveat here
    # Calling Mr Pythagoras: Find the pixels that lie inside this circle
    inside = (xx[:,None] - val[0][0]) ** 2 + (yy[None, :] - val[0][1]) ** 2 <= (radius ** 2)
    # do grid & inside and initialize grid with ones for intersection instead of union
    grid = grid | inside

plt.imshow(grid)
plt.show()

rawDescription: Changing the values in a numpy array depending on the area of a circle


code:
import logging

class BufferedRemoteHandler(object):
   def __new__(cls):
       return logging.handlers.MemoryHandler(capacity=5,target=myActualHandler)

rawDescription: returning another class when instantiating a class in python

description: Returning another class when instantiating a class in python


code:
for script in soup(["script", "style"]):
    script.replace_with(" ")

rawDescription: How to replace extracted HTML tags in a text with a blank?

description: Replace extracted HTML tags in a text with a blank


code:
lines = cv2.HoughLinesP(edges,1,np.pi/180,275, minLineLength = 600, maxLineGap = 100)[0].tolist()

for x1,y1,x2,y2 in lines:
    for index, (x3,y3,x4,y4) in enumerate(lines):

        if y1==y2 and y3==y4: # Horizontal Lines
            diff = abs(y1-y3)
        elif x1==x2 and x3==x4: # Vertical Lines
            diff = abs(x1-x3)
        else:
            diff = 0

        if diff < 10 and diff is not 0:
            del lines[index]

gridsize = (len(lines) - 2) / 2

rawDescription: Python cv2 HoughLines grid line detection


rawDescription: Swapping Axes in Pandas

description: Swapping Axes in Pandas


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

times = np.linspace(0, 10,  20)
x = np.linspace(0 ,2, 20)
T, X = np.meshgrid(times, x)   # make a grid that roughly matches the Strogatz grid

dxdt = X*(1-X)            # the equation of interest
dt = .5*np.ones(X.shape)  # a constant value (.5 is just so segments don't run into each other -- given spacing of times array
dx = dxdt * dt            # given dt, now calc dx for the line segment

plt.quiver(T, X, dt, dx, headwidth=0., angles='xy', scale=15.)
plt.show()

rawDescription: How do I generate a vector field plot for logistic equation K = 1 using matplotlib?

description: Generate a vector field plot for logistic equation K = 1 using matplotlib


code:
from distutils import sysconfig
site_packages_path = sysconfig.get_python_lib()

setup(...,
  data_files=[(site_packages_path, ["mypackage.pth"])]
 )

rawDescription: setup.py: installing just a pth file?

description: Setup.py: installing just a pth file


code:
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
# image and label are defined elsewhere
box.add(image)
box.add(label)
button = Gtk.Button(use_underline=True, always_show_image=True)
button.add(box)
button.show_all()

rawDescription: Implementing replacement label for depreciate Gtk 3.10+ stock buttons in PyGObject 3.16


rawDescription: A better way to print nested arrays

description: A better way to print nested arrays


code:
import subprocess
from time import time as timer, sleep

p = subprocess.Popen(["./Tracking", vidfile])
deadline = timer() + 840
while timer() < deadline:
    if p.poll() is not None: # already finished
        break
    sleep(1)
else: # timeout
    try:
        p.kill()
    except EnvironmentError:
        pass # ignore errors
    p.wait()

rawDescription: Subprocess not terminating after set amount of time


code:
from PIL import Image
import numpy
im = Image.open( filename )
data = numpy.asarray( im )

rawDescription: python: image to 2-dimensional list

description: Python: image to 2-dimensional list


code:
import matplotlib
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
import numpy as np

if __name__ == '__main__':
    xy = np.random.rand(8).reshape(1,4,2)

    p=PolyCollection(xy,closed=False, edgecolors = 'red', facecolors = 'white')
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.add_collection(p)

rawDescription: Why does PolyCollection always closed?

description: Why does PolyCollection always closed


code:
from datetime import datetime
d = datetime.strptime('Feb-15', '%b-%y')

rawDescription: how to handle a date format in mm-yy in Python?

description: Handle a date format in mm-yy in Python


code: fileString = fileString.replace('\r', '</p>')

rawDescription: BeautifulSoup treating '<' '>' html tags in BeautifulSoup


code: l = [my_string]

rawDescription: Most efficient way to build single-element list from string with or without spaces?


code:
from selenium import webdriver

firefox_profile = webdriver.FirefoxProfile()
firefox_profile.set_preference('permissions.default.stylesheet', 2)
firefox_profile.set_preference('permissions.default.image', 2)
firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')

driver = webdriver.Firefox(firefox_profile=firefox_profile)
driver.get('http://www.stackoverflow.com/')

driver.close()

rawDescription: Disable images in Selenium Python

description: Disable images in Selenium Python


code:
s = list("Hello zorld")
s
s[6] = 'W'
s
"".join(s)

rawDescription: Change one character in a string in Python?


code:
from __future__ import unicode_literals
s = 'hi'
type(s)

rawDescription: Python - is there a way to make all strings unicode in a project by default?


code: walk, walk2 = itertools.tee(walk)

rawDescription: How to clone a Python generator object?

description: Clone a Python generator object


code:
for step in [functionOne, functionTwo, ...]:
    step()
    if condition:
        conditionalFunction()

rawDescription: Python Function call every other time

description: Python Function call every other time


code:
import urlparse
url = urlparse.urlparse('http://google.com/sadfasdfsd?AA=mytag&SS=sdfsdf')
url.query
urlparse.parse_qs(url.query)

rawDescription: Get string between ampersand or at the end


code:
import time

def wait_timeout(proc, seconds):
    """Wait for a process to finish, or raise exception after timeout"""
    start = time.time()
    end = start + seconds
    interval = min(seconds / 1000.0, .25)

    while True:
        result = proc.poll()
        if result is not None:
            return result
        if time.time() >= end:
            raise RuntimeError("Process timed out")
        time.sleep(interval)

rawDescription: Python: Run a process and kill it if it doesn't end within one hour


rawDescription: Python 3: Regex matching 2 seperate conditions


rawDescription: Elixir/SQLAlchemy equivalent to SQL "LIKE" statement?


code:
fig, axs = plt.subplots(1,2)

df['korisnika'].plot(ax=axs[0])
df['osiguranika'].plot(ax=axs[1])

rawDescription: Make more than one chart in same IPython Notebook cell


code:
import zipfile,os

project='C:/Users/user1/Documents/work/filesToZip'

# prevent adding zip to itself if the old zip is left in the directory
zip_path = os.path.join(project,'jobs.zip')
if os.path.exists(zip_path):
    os.unlink(zip_path);

dirlist = os.listdir(project)

zip_file = zipfile.ZipFile(zip_path, 'w')
for file_name in dirlist:
    zip_file.write(os.path.join(project, file_name), file_name)
zip_file.close()

rawDescription: proper way for zipping files in python

description: Proper way for zipping files in python


code:
def doing_it(dic):
    new_mod = {}
    for i in sorted(dic.keys()):
        if dic[i] == 1:
            new_mod[i] = dic1
        elif dic[i] == 2:
            new_mod[i] = dic2
        else:
            new_mod[i] = doing_it(dic[i])
    return new_mod

rawDescription: How create dictionaries inside dictionaries, inside dictionaries... 'n' times


code:
import subprocess
import shlex  #just so you don't need break "comand" into a list yourself ;)

p=subprocess.Popen(shlex.split(comand),stdout=subprocess.PIPE)
first_line_of_output=p.stdout.readline()
second_line_of_output=p.stdout.readline()
...

rawDescription: How to read stdout output of ongoing process in Python?

description: Read stdout output of ongoing process in Python


code:
import matplotlib.pyplot as plt

lons = range(50)
lats = range(25, 75)
vals = range(50,100)

plt.scatter(lons, lats, c=vals, cmap='afmhot')
plt.colorbar()
plt.show()

rawDescription: Plotting color coded markers in matplotlib-basemap


code:
import tweepy
import csv

consumer_key ='XXX'
consumer_secret = 'XXX'
access_key = 'XXX'
access_secret = 'XXX'

handles_list = ["handle1", "handle2", "handle3"]

def get_all_tweets(screen_name, writer):
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)

    recenttweets = []
    recent_tweets = api.user_timeline(screen_name = handle, count=50)
    recenttweets.extend(new_tweets)

    Resultingtweets= [[tweet.user.name, tweet.user.screen_name, tweet.user.description, tweet.id_str, tweet.created_at, tweet.text.encode("utf-8")] for tweet in recenttweets]

    writer.writerow(["User Name","Twitter_Handle","Twitter_User_Description","tweet_id","created_at","Tweet_text"])
    writer.writerows(Resultingtweets)

if __name__ == '__main__':
    with open('all_tweets.csv', 'w', encoding='utf-8') as f_all:
        writer = csv.writer(f_all)

        for handle in handles_list:
            get_all_tweets("handles", writer)
            print ("Done.")

rawDescription: How to append tweets of multiple users into a single CSV file

description: Append tweets of multiple users into a single CSV file


code:
phoneDict = dict((row[0],row[1]) for row in cybReader)

with open('./out.csv', 'w') as outFile:
    writer = csv.writer(outFile)
    for row in josReader:
        if not row[4]:
            row[4] = phoneDict[row[0]]
        writer.writerow(row)

rawDescription: Comparing columns on 2 csv files

description: Comparing columns on 2 csv files


code:
import argparse
Install = []
hostName = str(sys.argv[1])

for i in config.package:
 Install.append("deploy:"+i+",host=")

for f in Install:
 subprocess.call(["fabric", f+hostName])

rawDescription: how to create a command-line-argument in python

description: Create a command-line-argument in python


code:
import ckan.plugins as plugins
import ckan.plugins.toolkit as tk
from ckan.plugins.toolkit import Invalid

def date_str_validator(value, context):
    valid_date = tk.get_validator('isodate')(value, context)
    if not valid_date or not isinstance(valid_date, datetime.datetime):
        raise Invalid("Invalid date")
    return value

class MyPlugin(plugins.SingletonPlugin, tk.DefaultDatasetForm):

    plugins.implements(plugins.IDatasetForm, inherit=False)

    def _modify_package_schema(self, schema):
        schema.update({
            # Custom extras
            'origination_date':[tk.get_validator('ignore_missing'),
                                date_str_validator,
                                tk.get_converter('convert_to_extras')]
        })
        return schema

    def create_package_schema(self):
        schema = super(MyPlugin, self).create_package_schema()
        schema = self._modify_package_schema(schema)

        return schema

    def update_package_schema(self):
        schema = super(MyPlugin, self).update_package_schema()
        schema = self._modify_package_schema(schema)
        return schema

    def show_package_schema(self):
        schema = super(MyPlugin, self).show_package_schema()

        schema.update({
            # Custom extras
            'origination_date':[tk.get_converter('convert_from_extras'),
                                tk.get_validator('ignore_missing'),
                                date_str_validator]
        })

        return schema

rawDescription: How can I define custom validator in CKAN 2.2

description: Define custom validator in CKAN 2.2


rawDescription: Getting request param from url

description: Getting request param from url


rawDescription: Forcing tuples within tuples?

description: Forcing tuples within tuples


code:
p = cs.collections[0].get_paths()[0]
v = p.vertices
x = v[:,0]
y = v[:,1]

rawDescription: matplotlib - extracting data from contour lines

description: Matplotlib - extracting data from contour lines


rawDescription: Python save matplotlib figure with exact pixel size


code:
for i,curve in enumerate(data):
   pylab.plot(xaxis,curve,color=colours[i],marker=markers[i],label=labels[i])

pylab.legend(loc=0)
pylab.show()

rawDescription: How do I assign a legend to some data within a for loop in Python?

description: Assign a legend to some data within a for loop in Python


code:
from subprocess import Popen, PIPE
from select import select

cmd = ('lzma', '-kdc', '-S', 'bi5', 'path/to/datafile')
p = Popen(cmd, stdout=PIPE)

while p.poll() == None:
    r,w,e = select([p.stdout], [], [])
    if r:
        data = p.stdout.read(512)
        # unpack and append to csv file ...

rawDescription: How to process the ouput of POpen as a stream with struct.unpack?

description: Process the ouput of POpen as a stream with struct.unpack


code:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result1 = sock.connect_ex(('127.0.0.1',9001))
result2 = sock2.connect_ex(('127.0.0.1',8119))
sock.close()
sock2.close()

rawDescription: Python Socket:Handling multiple connection with same socket


code: import sys; sys.version

rawDescription: any way to tell if user's python environment is anaconda

description: Any way to tell if user's python environment is anaconda


rawDescription: Creating indexes - MongoDB

description: Creating indexes - MongoDB


code:
import matplotlib
import matplotlib.pyplot as plt

# Use LaTeX for rendering
matplotlib.rcParams["text.usetex"] = True
# load the xfrac package
matplotlib.rcParams["text.latex.preamble"].append(r'\usepackage{xfrac}')

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.text(.5, .5, r'$\sfrac{1}{2}$')

rawDescription: matplotlib mathtext slanted fractions

description: Matplotlib mathtext slanted fractions


code:
import random
import string

allowable_gibberish = string.ascii_letters + string.digits + string.punctuation
def gibberish_maker(gibberish=allowable_gibberish,n=512,new_line_every=15):
    str = ''.join(random.choice(gibberish) for x in range(n))
    return '\n'.join(str[i:i+new_line_every] for i in xrange(0, len(str), new_line_every))

rawDescription: Python random digit letter and additional generator


code:
df
df['B'].apply(lambda x: sum(map(int, x.split(','))))

rawDescription: Pandas sum integers separeted by commas in a string column


code:
#models.py
class MyClass(models.Model):
    title = models.CharField(max_length=255, null=False)
    body = models.TextField(max_length=255, null=False)

    def body_formatted(self):
        return "formatted string {0}".format(self.body)

#views.py
def myview(request):
   # Get a model instance corresponding to the first DB row
   obj = MyClass.objects.first()
   body_formatted = obj.body_formatted()    # Calling the model's method
   return HttpResponse(body_formatted)

rawDescription: Django calling methods from models

description: Django calling methods from models


code:
def requireAuthentication(json=False):
    def decorator(fn):
        def wrapper(**kwargs):
            # Is user logged on?
            if "user" in request.session:
                return fn(**kwargs)

            # No, return error
            if json:
                return {
                    "exception": "NotAuthorized",
                    "error" : "You are not authorized, please log on"
                }
            redirect('/login?url={0}{1}'.format(request.path, ("?" + request.query_string if request.query_string else '')))
        return wrapper
    return decorator

rawDescription: Combine two python decorators into one

description: Combine two python decorators into one


code:
class AdvancedSearchInboxFilter(django_filters.FilterSet):
    received = django_filters.DateFromToRangeFilter(
        label='Received Date Range',
        widget=django_filters.widgets.RangeWidget(attrs={'placeholder': 'yyyy/mm/dd'}))

    class Meta:
        model = File
        fields = ['received']

rawDescription: How to put placeholder in Django date range filter

description: Put placeholder in Django date range filter


code:
for power in range(n):
    amt=(math.pow(2,power))
    print('*'*int(amt))
for power in range(n-1)[::-1]:
    amt=(math.pow(2,power))
    print('*'*int(amt))

rawDescription: Reversing the output of a while sequence in python 3?


code:
def call_api(url, data):
    unused_keys = set()
    for k, value in data.items():
        key_pattern = "{" + k + "}"
        if key_pattern in url:
            formatted_value = ';'.join(map(str, value))
            url = url.replace(key_pattern, formatted_value)
        else:
            unused_keys.add(k)

rawDescription: More pythonic way to replace keywords in a string?


rawDescription: Measuring efficiency of Huffman coding with Python bitstring


code:
df=df.rename(columns = {'two':'new_name'})
df

rawDescription: Changing a specific column name in pandas DataFrame


code:
# The short X.Y version.
version = '0.0.1'
# The full version, including alpha/beta/rc tags.
release = version

rawDescription: Sphinx does not change version number

description: Sphinx does not change version number


rawDescription: hex string to SHA256 digest in python

description: Hex string to SHA256 digest in python


code:
def bicubic(fx, fy, img):

   img = img.astype(float)
   h,w = np.shape(img)

   if(fx < 0 or fx > w-1 or fy < 0 or fy > h-1):
       val = 0
       return val

   x = int(fx)
   y = int(fy)

   dx = fx - x
   dy = fy - y

   px = 0 if x-1<0 else x-1
   py = 0 if y-1<0 else y-1

   nx = x+1 if dx>0 else x
   ny = y+1 if dy>0 else y

   ax = w-1 if x+2>=w else x+2
   ay = h-1 if y+2>=h else y+2

   Ipp = img[py,px]; Icp = img[py,x]; Inp = img[py,nx]; Iap = img[py,ax];
   Ip = Icp + 0.5*(dx*(-Ipp+Inp) + dx*dx*(2*Ipp-5*Icp+4*Inp-Iap) + dx*dx*dx*(-Ipp+3*Icp-3*Inp+Iap))
   Ipc = img[y,px]; Icc = img[y,x]; Inc = img[y,nx]; Iac = img[y,ax];
   Ic = Icc + 0.5*(dx*(-Ipc+Inc) + dx*dx*(2*Ipc-5*Icc+4*Inc-Iac) + dx*dx*dx*(-Ipc+3*Icc-3*Inc+Iac))
   Ipn = img[ny,px]; Icn = img[ny,x]; Inn = img[ny,nx]; Ian = img[ny,ax];
   In = Icn + 0.5*(dx*(-Ipn+Inn) + dx*dx*(2*Ipn-5*Icn+4*Inn-Ian) + dx*dx*dx*(-Ipn+3*Icn-3*Inn+Ian))
   Ipa = img[ay,px]; Ica = img[ay,x]; Ina = img[ay,nx]; Iaa = img[ay,ax];
   Ia = Ica + 0.5*(dx*(-Ipa+Ina) + dx*dx*(2*Ipa-5*Ica+4*Ina-Iaa) + dx*dx*dx*(-Ipa+3*Ica-3*Ina+Iaa))

   val = Ic + 0.5*(dy*(-Ip+In) + dy*dy*(2*Ip-5*Ic+4*In-Ia) + dy*dy*dy*(-Ip+3*Ic-3*In+Ia))
   return val

rawDescription: CImg cubic subpixel location

description: CImg cubic subpixel location


code:
name = list(input("Enter your name"))
name
First_letter = name[0]
Second_letter = name[1]
Third_letter = name[2]

rawDescription: How to get python to display the first letter from input

description: Get python to display the first letter from input


rawDescription: filter by foreign key in django models

description: Filter by foreign key in django models


code:
import decimal

first = decimal.Decimal('1.1')
second = decimal.Decimal('1.3')
avg = (first + second) / 2
print(avg)

rawDescription: Python, Averages, and Division

description: Python, Averages, and Division


code:
import multiprocessing

def run_as_process(func, *args):
    p = multiprocessing.Process(target=func, args=args)
    try:
        p.start()
        p.join()
    finally:
        p.terminate()

rawDescription: Python: garbage collection fails?

description: Python: garbage collection fails


code:
import pygame
import random

RED = (255,0,0)
WHITE = (255,255,255)
GREEN = (0,255,0)
BLUE = (0,128,255)

#------------------------------FUNCTIONS--------------------------------#
def main():

    pygame.init()
    display_width=460
    display_height=460
    gameDisplay = pygame.display.set_mode((display_width, display_height))
    pygame.display.set_caption('Snake')
    clock = pygame.time.Clock()
    FPS = 10

    schlange = Snake(gameDisplay, 220, 220, 20, 20, BLUE)
    essen = Food(gameDisplay)
    speed = (0,0)

    while True:
            #event loop
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    speed = (0, -20)
                if event.key == pygame.K_DOWN:
                    speed = (0, 20)
                if event.key == pygame.K_LEFT:
                    speed = (-20, 0)
                if event.key == pygame.K_RIGHT:
                    speed = (20, 0)

        if pygame.Rect.colliderect(schlange.rect, essen.rect) == True:
            essen = Food(gameDisplay)
            schlange.eat()

        """ ADDED """

        """ I realized that you're storing the tail pieces in self.position.
            Iterating through this list and checking for collisions seems to do the trick.
            Skip check when there's only one element in schlange.position to avoid a collision as soon as the game starts.
            Now you probably just need to prevent the snake from going straight back
            into itself (180 degree turn) since that would trigger a collision that you might not want """

        if len(schlange.position) > 1:
            for coords in schlange.position:
                if pygame.Rect.colliderect(schlange.rect, pygame.Rect(coords[0], coords[1], schlange.width, schlange.height)) == True:
                    print('rip')
                    pygame.quit()
                    quit()

        """ /ADDED """

        schlange.move(speed[0], speed[1])
        essen.spawn()
        clock.tick(FPS)
        pygame.display.update()

#------------------------------CLASSES---------------------------------#
class Snake():
    def __init__(self, screen, startx, starty, width, height, color):
        self.screen = screen
        self.startx = startx
        self.starty = starty
        self.width = width
        self.height = height
        self.color = color
        self.amount_tiles = 5
        self.tile = 0
        self.position = []
        self.rect = pygame.Rect(startx, starty, width, height)
        pygame.draw.rect(screen, color, self.rect)

    def move(self, x_change, y_change):
        self.screen.fill(WHITE)
        self.x_change = x_change
        self.y_change = y_change
        self.position.insert(0, (self.startx, self.starty))

        self.pos = self.position[self.tile]

        '''self.add_tile()'''
        self.existing_tiles()

        self.startx += x_change
        self.starty += y_change
        self.rect = pygame.Rect(self.startx, self.starty, self.width, self.height)
        pygame.draw.rect(self.screen, self.color, self.rect)

        """ ADDED """

        """ You kept adding to self.position but never deleted any elements.
            That's unnecessary and would eventually cause a MemoryError """

        if len(self.position) > self.tile+1:
            del self.position[-1]

        """ /ADDED """

    def existing_tiles(self):
        self.count = self.tile

        while self.count > 0:
            self.current_pos = self.position
            x = self.current_pos[self.count - 1]
            self.rect_new = pygame.Rect(x[0], x[1], self.width, self.height)
            pygame.draw.rect(self.screen, GREEN, self.rect_new)
            self.count = self.count - 1

    '''def add_tile(self):
        x = self.pos[0]
        y = self.pos[1]
        pygame.draw.rect(self.screen, GREEN, (x, y, self.width, self.height))'''

    def eat(self):
        self.amount_tiles += 1
        self.tile += 1

class Food():

    def __init__(self, screen):
        self.screen = screen
        self.width = 20
        self.height = 20
        self.spawnx = random.randrange(0, 460, 20)
        self.spawny = random.randrange(0, 460, 20)
        self.rect = pygame.Rect(self.spawnx, self.spawny, self.width, self.height)

    def spawn(self):
        pygame.draw.rect(self.screen, RED, self.rect)

if __name__ == '__main__':
    main()

rawDescription: Pygame checking for collision not working


code: ages = driver.execute_script("function get_ages() { arr=[]; $('#faces .tooltip-inner div').each(function () { arr.push($(this).text()); }); return arr;}; return get_ages()")

rawDescription: Selenium + Python - how to get the response from the site after uploading an image


code:
import numpy as np
from skimage import data

astro = data.astronaut()
l_row, l_col, nb_channel = astro.shape
rows, cols = np.mgrid[:l_row, :l_col]
radius = np.sqrt((rows - l_row/2)**2 + (cols - l_col/2)**2)
alpha_channel = np.zeros((l_row, l_col))
r_min, r_max = 1./3 * radius.max(), 0.8 * radius.max()
alpha_channel[radius < r_min] = 1
alpha_channel[radius > r_max] = 0
gradient_zone = np.logical_and(radius >= r_min, radius <= r_max)
alpha_channel[gradient_zone] = (r_max - radius[gradient_zone])/(r_max - r_min)
alpha_channel *= 255
feathered = np.empty((l_row, l_col, nb_channel + 1), dtype=np.uint8)
feathered[..., :3] = astro[:]
feathered[..., -1] = alpha_channel[:]

import matplotlib.pyplot as plt
plt.imshow(feathered)
plt.show()

rawDescription: Feathered edges on image with PIL

description: Feathered edges on image with PIL


code:
def download_file(url):
    local_filename = url.split('/')[-1]
    # NOTE the stream=True parameter
    r = requests.get(url, stream=True)
    with open(local_filename, 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk: # filter out keep-alive new chunks
                f.write(chunk)
                #f.flush() commented by recommendation from J.F.Sebastian
    return local_filename

rawDescription: How to download large file in python with requests.py?

description: Download large file in python with requests.py


code:
engine= create_engine('postgresql://user:pswd@localhost/db1')
DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
DBSession.configure(bind=engine)

engine2= create_engine('postgresql://user:pswd@localhost/db2')
DBSession2 = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
DBSession2.configure(bind=engine2)

rawDescription: Multiple databases in Pyramid

description: Multiple databases in Pyramid


code:
class VarListView(TemplateView):
    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(VarListView, self).get_context_data(**kwargs)
        context['locations'] = self.locations()
        context['locvarnames'] = self.locavarnames()
        context['locvars'] = self.locvars()
        return context

rawDescription: Django - iterating a queryset produces hundreds of queries


code:
def sqsort(xxs):
    left, right = [], []
    while True:
        if len(xxs) == 1 or len(xxs) == 0:
            return left + xxs + right
        x = xxs[0]
        xs = xxs[1 :]
        l = []
        g = []
        for x2 in xs:
            if x2 < x:
                l.append(x2)
            if x2 >= x:
                g.append(x2)
        if len(l) <= len(g):
            left += sqsort(l) + [x]
            xxs = g
        else:
            right = [x] + sqsort(g) + right
            xxs = l

l = list(reversed(range(15000)))
print(l)
print(sqsort(l))

rawDescription: Options to make pypy run faster

description: Options to make pypy run faster


rawDescription: Set numpy.ndarray values to a scalar

description: Set numpy.ndarray values to a scalar


code:
class Car:
    def __init__(self, driver):
        self.driver = driver

class Driver:
    pass

driver = Driver()
car = Car(driver)

rawDescription: Python: object as an argument of another object


code: Counter(item[:2] for item in list1)

rawDescription: Comparing the first couple characters in a string


code:
import re
formattuple = (1990,12,24,13,37,11,1)
formatstr = 'bla,%d,%02d,%02d %02d:%02d:%02d.%03d'

def rep_format(fmt):
    fmt = fmt.group(0)
    if fmt[0] != '%':
        return fmt
    if fmt == '%d':
        return r'(\d+)'
    ftype = fmt[-1]
    if ftype == 'd':
       fwidth = int(fmt[1:-1])
       return r'(\d{%d})'%(fwidth)
    else:
       return fmt

scanstr = re.sub(r'%\d+[df]', rep_format, formatstr)
scanstr
'bla,(\\d+),(\\d{2}),(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})'

fstr = formatstr%formattuple
fstr
'bla,1990,12,24 13:37:11.001'

match = re.match(scanstr, fstr)
match.groups()
('1990',
 '12',
 '24',
 '13',
 '37',
 '11',
 '001')
mtuple = tuple(int(x) for x in match.groups())

rawDescription: Deserialize string into values using format pattern


code:
import Tkinter as tk

class Application(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.canvas = tk.Canvas(self.master, width=400, height=400)
        self.canvas.bind('<Button-1>', self.coordinates)
        self.canvas.pack()

    def coordinates(self, event):
        self.x = (event.x, event.y) # set x (or another attr) to coordinate tuple

if __name__ == "__main__":
    root = tk.Tk()
    app = Application(root)
    app.mainloop()

rawDescription: New to Python, need an event listener equivalent?


code:
def shortest(textList):
    shortest_string_len=len(textList.pop())
    for text in textList:
        actual_text_len=len(text)
        if actual_text_len < shortest_string_len:
            shortest_string_len=actual_text_len
    return (shortest_string_len)

beatleLine = ['I', 'am', 'the', 'walrus']
print(shortest(beatleLine))

rawDescription: Write a function named shortest() that finds the length of the shortest string in a list of strings


code: cursor.execute("update records set y = ? where x = ?", (y, x))

rawDescription: Writing a single table value in sqlite3

description: Writing a single table value in sqlite3


rawDescription: How can I convert a character to a integer in Python, and viceversa?

description: Convert a character to a integer in Python, and viceversa


code:
from HTMLParser import HTMLParser

class ImageFinder(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self.file = open('output.txt', 'w')
    def handle_starttag(self, tag, attrs):
        if tag == "img":
            url = [u[1] for u in attrs if u[0] == "src"][0]
            self.file.write(url+"\n")
    def __exit__(self):
        self.file.close()

inputdata = open("myfile.txt").read()
parser = ImageFinder()
parser.feed(inputdata)

rawDescription: Write delimited strings from an infile to an outfile


code:
mySet = {str(i) for i in {1010101, 20202030}}
myList = ["1 1010101 20202030 15.3"]

result = any(all(s in l for s in mySet) for l in myList)

print(result)

rawDescription: Test if two items in a set are found in a list element


code:
mylist = ['BMW', 'Lamborghini', 'Porsche']
cars = Car.objects.filter(name__in=mylist)
self.fields['possible_cars'].queryset = cars

rawDescription: Running into issues with Django's ModelChoiceField "queryset" attribute


code:
picks_user = np.random.randint(0,10, (10,3))
picks_user
target_users = np.array([1,7,8])
picks_user[np.in1d(picks_user[:,1], target_users)]

rawDescription: How to use numpy where for several possible values?

description: Use numpy where for several possible values


code:
import re

def loadfile(filename):
    '''
    Returns a string containing all data from file
    '''
    infile = open(filename, 'r')
    infile_string = infile.read()
    infile.close()
    return infile_string

def main():
    #load the files into strings
    original = loadfile("original.xml")
    replacement = loadfile("replacement.xml")

    #grab all of the "replacement" lines from the replacement file
    replacement_regex = re.compile("(<replacement>.*?</replacement>)")
    replacement_list = replacement_regex.findall(replacement)

    #grab all of the "TEXT" blocks from the original file
    original_regex = re.compile("(<TEXT>.*?</TEXT>)", re.DOTALL)
    original_list = original_regex.findall(original)

    #a string to write out to the new file
    outfile_string = ""
    to_find = "</original>" #this is the point where the replacement text is going to be appended after
    additional_len = len(to_find)
    for i in range(len(original_list)): #loop through all of the original text blocks
        #build a new string with the replacement text after the original
        build_string = ""
        build_string += original_list[i][:original_list[i].find(to_find)+additional_len]
        build_string += "\n" + " "*4
        build_string += replacement_list[i]
        build_string += "\n</TEXT>\n"
        outfile_string+=build_string

    #write the outfile string out to a file
    outfile = open("outfile.txt", 'w')
    outfile.write(outfile_string)
    outfile.close()

if __name__ == "__main__":
    main()

rawDescription: want to merge specific code lines from 2 text files

description: Want to merge specific code lines from 2 text files


code:
if __name__ == '__main__':
    q = multiprocessing.Process(target=worker2,)
    q.start()

    p = multiprocessing.Process(target=worker,)
    p.start()

    q.join()
    p.join()

rawDescription: Multiprocessing, does join prevent processes from working in parallel?


code:
keys = db.inspect(Post).columns.keys()
get_columns = lambda post: {key: getattr(post, key) for key in keys}

posts = Post.query.filter(Post.expiry > ts)
db.session.bulk_insert_mappings(OldPost, (get_columns(post) for post in posts))
posts.delete()
db.session.commit()

rawDescription: Bulk move rows from one table to another with SQLAlchemy


rawDescription: Indicating format of multiple numbers in numpy.savetxt


code:
def get_top_scorers(dataset):
    if dataset and all(isinstance(d, list) for d in dataset):
        return [get_top_scorers(d) for d in dataset]
    selected_list = []
    for candidate in dataset:
        chosen = candidate
        for next_candidate in dataset:
            if next_candidate == chosen:
                continue
            next_name, next_surname, next_score = next_candidate

            shares_name_with_selected = any(
                next_name == s[0] or next_surname == s[1]
                for s in selected_list
            )
            if shares_name_with_selected:
                continue

            name, surname, score = chosen
            if (name == next_name or surname == next_surname) and score < next_score:
                chosen = next_candidate

        shares_name_with_selected = any(
            chosen[0] == s[0] or chosen[1] == s[1]
            for s in selected_list
        )
        if chosen not in selected_list and not shares_name_with_selected:
            selected_list.append(chosen)
    return selected_list

rawDescription: Selecting from a tuples of list

description: Selecting from a tuples of list


code:
import bokeh.plotting as bk
from bokeh.models import ColumnDataSource, Plot
from bokeh.models.widgets import Select, AppVBox
from bokeh.simpleapp import simpleapp

data = {"a": {"x": [1,2,3], "y": [1,2,3]},
        "b": {"x": [3,2,1], "y": [1,2,3]},
        "c": {"x": [2,2,2], "y": [1,2,3]},}

options = ["a", "b", "c"]
select1 = Select(name = 'ticker1', value = options[0], options =     options)

@simpleapp(select1)
def test_layout(ticker1):
    p = bk.figure(title = "layout test")

    chart_data = data[ticker1]

    df = ColumnDataSource(data = chart_data)
    p.circle(x = chart_data["x"], y = chart_data["y"])

    return {'plot': p}

@test_layout.layout
def layout(app):
    return AppVBox(app=app, children=['ticker1', 'plot'])

test_layout.route("/bokeh/layout/")

rawDescription: Specify position of combo box

description: Specify position of combo box


code:
import re

def assert_dict(template, thing):
    if len(template) != len(thing):
        raise AssertionError("Assertion failed")
    for key in template:
        if isinstance(template[key], dict):
            assert_dict(template[key], thing[key])
        else:
            if template[key] == thing[key]:
                continue
            elif re.fullmatch(template[key], thing[key]):
                continue
            else:
                raise AssertionError("Assertion failed")

rawDescription: assertion dict with regex

description: Assertion dict with regex


code:
import random

name = input("what is your name?")
number = random.randint(1, 20)
#print("%s I am thinking of a number between 1 and 20..." % name)
print(name + " I am thinking of a number between 1 and 20...")

guesses = 0
while guesses < 7:
    guess = int(input("Take a guess."))
    guesses += 1

    if guess < number:
        print ("your guess is too low!")

    elif guess > number:
        print ("your guess is too high!")

    else:
        #print("Good job %s you guessed my number in %d guesses" % (name, guesses))
        print ("Good job, " + name + " you guessed my number in " + str(guesses) + " guesses!")
        break

rawDescription: Guess the number game, error.

description: Guess the number game, error.


code:
class W(object):

  def __init__(self, x):
    self.x = x
    self.t = type(x)

  def __eq__(self, other):
    t = type(other)
    if t != type(self):
      return False
    return self.x == other.x and self.t == other.t

  def __hash__(self):
    return hash(self.x) ^ hash(self.t)

  def __getattr__(self, name):
    return getattr(self.x, name)

rawDescription: Problem with hash function: hash(1) == hash(1.0)


code:
def set_border(ws, cell_range):
    rows = list(ws.iter_rows(cell_range))
    side = Side(border_style='thin', color="FF000000")

    rows = list(rows)  # we convert iterator to list for simplicity, but it's not memory efficient solution
    max_y = len(rows) - 1  # index of the last row
    for pos_y, cells in enumerate(rows):
        max_x = len(cells) - 1  # index of the last cell
        for pos_x, cell in enumerate(cells):
            border = Border(
                left=cell.border.left,
                right=cell.border.right,
                top=cell.border.top,
                bottom=cell.border.bottom
            )
            if pos_x == 0:
                border.left = side
            if pos_x == max_x:
                border.right = side
            if pos_y == 0:
                border.top = side
            if pos_y == max_y:
                border.bottom = side

            # set new border only if it's one of the edge cells
            if pos_x == 0 or pos_x == max_x or pos_y == 0 or pos_y == max_y:
                cell.border = border

rawDescription: Apply Border To Range Of Cells Using Openpyxl


code:
f = Obj.objects.get(id=obj_id)
myfile = open(os.path.join(MEDIA_ROOT, f.Audio.path)).read()
...

response = HttpResponse(myfile, content_type="audio/mpeg")
response['Content-Disposition'] = 'attachment; filename=myfile.mp3'

return response

rawDescription: How to download a file uploaded using django-filebrowser?

description: Download a file uploaded using django-filebrowser


code:
import numpy as np
from matplotlib.pyplot import step, xlim, ylim, show
x = np.arange(0, 7)
y = np.array([0, 1, 0, 1, 1, 0, 1])
xlim(0, 7)
ylim(-0.5, 1.5)
step(x, y)
show()

rawDescription: How to plot a binary sequence of data in python

description: Plot a binary sequence of data in python


rawDescription: Hide unselected in Maya/Python

description: Hide unselected in Maya/Python


code:
b = Binding(url='/cgi-bin/simple-test', tracefile=fp)
b.cookies['foo'] = 'bar'

rawDescription: Adding Cookie to ZSI Posts

description: Adding Cookie to ZSI Posts


code: itertools.product(range(2), repeat=4)

rawDescription: Is there a cleaner way to iterate through all binary 4-tuples?


code:
def sign_extend(value, bits):
    sign_bit = 1 << (bits - 1)
    return (value & (sign_bit - 1)) - (value & sign_bit)

rawDescription: Two's complement sign extension python?

description: Two's complement sign extension python


code: [''.join(i) for i in itertools.product("ab",repeat=4)]

rawDescription: Is there a function in Python which generates all the strings of length n over a given alphabet?


code:
latest_content = None
while True:
    driver.refresh()
    new_content = driver.find_element_by_xpath("html").text
    if new_content != latest_content:
        with open('urls.txt', 'a') as f:
            f.write(new_content)
            latest_content = new_content

rawDescription: How to loop over refreshing a webpage each time I finish processing some data?

description: Loop over refreshing a webpage each time I finish processing some data


code:
for line in lines:
    split = str(line.split())
    k = split.count(s)
    tot = tot + k
return tot

rawDescription: Why does this code only read the first line rather than the whole .txt file?


code:
from Tkinter import *

# dictionary to hold words and colors
highlightWords = {'if': 'green',
                  'else': 'red'
                  }

def highlighter(event):
    '''the highlight function, called when a Key-press event occurs'''
    for k,v in highlightWords.iteritems(): # iterate over dict
        startIndex = '1.0'
        while True:
            startIndex = text.search(k, startIndex, END) # search for occurence of k
            if startIndex:
                endIndex = text.index('%s+%dc' % (startIndex, (len(k)))) # find end of k
                text.tag_add(k, startIndex, endIndex) # add tag to k
                text.tag_config(k, foreground=v)      # and color it with v
                startIndex = endIndex # reset startIndex to continue searching
            else:
                break

root = Tk()
text = Text(root)
text.pack()

text.bind('<Key>', highlighter) # bind key event to highlighter()

root.mainloop()

rawDescription: Tkinter Text Widget Keyword Colouring

description: Tkinter Text Widget Keyword Colouring


code:
import sys, os

from zope.interface import implements

from twisted.python.failure import Failure
from twisted.python.log import err
from twisted.internet.error import ConnectionDone
from twisted.internet.defer import Deferred, succeed, setDebugging
from twisted.internet.interfaces import IStreamClientEndpoint
from twisted.internet.protocol import Factory, Protocol

from twisted.conch.ssh.common import NS
from twisted.conch.ssh.channel import SSHChannel
from twisted.conch.ssh.transport import SSHClientTransport
from twisted.conch.ssh.connection import SSHConnection
from twisted.conch.client.default import SSHUserAuthClient
from twisted.conch.client.options import ConchOptions

# setDebugging(True)

class _CommandTransport(SSHClientTransport):
    _secured = False

    def verifyHostKey(self, hostKey, fingerprint):
        return succeed(True)

    def connectionSecure(self):
        self._secured = True
        command = _CommandConnection(
            self.factory.command,
            self.factory.commandProtocolFactory,
            self.factory.commandConnected)
        userauth = SSHUserAuthClient(
            os.environ['USER'], ConchOptions(), command)
        self.requestService(userauth)

    def connectionLost(self, reason):
        if not self._secured:
            self.factory.commandConnected.errback(reason)

class _CommandConnection(SSHConnection):
    def __init__(self, command, protocolFactory, commandConnected):
        SSHConnection.__init__(self)
        self._command = command
        self._protocolFactory = protocolFactory
        self._commandConnected = commandConnected

    def serviceStarted(self):
        channel = _CommandChannel(
            self._command, self._protocolFactory, self._commandConnected)
        self.openChannel(channel)

class _CommandChannel(SSHChannel):
    name = 'session'

    def __init__(self, command, protocolFactory, commandConnected):
        SSHChannel.__init__(self)
        self._command = command
        self._protocolFactory = protocolFactory
        self._commandConnected = commandConnected

    def openFailed(self, reason):
        self._commandConnected.errback(reason)

    def channelOpen(self, ignored):
        self.conn.sendRequest(self, 'exec', NS(self._command))
        self._protocol = self._protocolFactory.buildProtocol(None)
        self._protocol.makeConnection(self)

    def dataReceived(self, bytes):
        self._protocol.dataReceived(bytes)

    def closed(self):
        self._protocol.connectionLost(
            Failure(ConnectionDone("ssh channel closed")))

class SSHCommandClientEndpoint(object):
    implements(IStreamClientEndpoint)

    def __init__(self, command, sshServer):
        self._command = command
        self._sshServer = sshServer

    def connect(self, protocolFactory):
        factory = Factory()
        factory.protocol = _CommandTransport
        factory.command = self._command
        factory.commandProtocolFactory = protocolFactory
        factory.commandConnected = Deferred()

        d = self._sshServer.connect(factory)
        d.addErrback(factory.commandConnected.errback)

        return factory.commandConnected

class StdoutEcho(Protocol):
    def dataReceived(self, bytes):
        sys.stdout.write(bytes)
        sys.stdout.flush()

    def connectionLost(self, reason):
        self.factory.finished.callback(None)

def copyToStdout(endpoint):
    echoFactory = Factory()
    echoFactory.protocol = StdoutEcho
    echoFactory.finished = Deferred()
    d = endpoint.connect(echoFactory)
    d.addErrback(echoFactory.finished.errback)
    return echoFactory.finished

def main():
    from twisted.python.log import startLogging
    from twisted.internet import reactor
    from twisted.internet.endpoints import TCP4ClientEndpoint

    # startLogging(sys.stdout)

    sshServer = TCP4ClientEndpoint(reactor, "localhost", 22)
    commandEndpoint = SSHCommandClientEndpoint("/bin/ls", sshServer)

    d = copyToStdout(commandEndpoint)
    d.addErrback(err, "ssh command / copy to stdout failed")
    d.addCallback(lambda ignored: reactor.stop())
    reactor.run()

if __name__ == '__main__':
    main()

rawDescription: Best way to run remote commands thru ssh in Twisted?

description: Run remote commands thru ssh in Twisted


code: p.add_argument("-sw", action="store", help="Enter a specific file to process")

rawDescription: How to add a new functionality to a command line arparse menu?

description: Add a new functionality to a command line arparse menu


rawDescription: Grab the focus from GTK popup menu

description: Grab the focus from GTK popup menu


code:
def search_query(query, pages):
    valid_pages = 0
    for p in pages:
        i = 0
        for q in query:
            j = p.find(q, i)
            if j < 0:
                break
            i = j + 1
        else:
            valid_pages += 1
    return valid_pages

rawDescription: search_query - check the order of queries

description: Search_query - check the order of queries


code:
def spaces(sentences):
  textList = sentences.split('. ')
  whiteList = [whitespaces.count(' ') for whitespaces in textList]

  return max(whiteList)

print(spaces(sentences))

rawDescription: Python - None value is being returned from a count


code:
with open('result_'+ namefile + '.csv', 'rb') as master1:
    for row in csv.reader(master1):
        target = row[1]
        lecteur = row[5]
        epoch_ref = int(row[-1])
        with open('epoch_'+ namefile + '.csv', 'rb') as hosts1:
            for row2 in csv.reader(hosts1):
                epoch1 = int(row2[-1])
                lecteur1 = row2[5]
                with open('result_scout' + namefile + '.csv', 'a') as results1:
                     if epoch1 > (epoch_ref - ecart) and epoch1 < (epoch_ref + ecart) and lecteur1 == lecteur:
                        writer1 = csv.writer(results1)
                        writer1.writerow([target]+[sys.argv[1]]+row2)
                        results1.close()

rawDescription: Python nested loop doesn't loop

description: Python nested loop doesn't loop


code: os.system('''cat member.php\?%d* | grep -i '<li class="navbit lastnavbit"><span>' | cut -d'>' -f3 | cut -d'<' -f1  >> users.txt''' % count)

rawDescription: run linux cat command in python or bash loop

description: Run linux cat command in python or bash loop


code:
for x in range(1, columns):
    for x in range(x):
        print(" ", end="")
    print("*")

for x in range(columns,0,-1):
    for x in range(x):
        print(" ", end="")
    print("*")

rawDescription: Print the reverse of an arrow pattern in Python


code:
s
re.sub(r'(?P<table>/table\[\d+\])', r'\g<table>/tbody', s)
#similarly you can also reference by group number
re.sub(r'(?P<table>/table\[\d+\])', r'\g<1>/tbody', s)

rawDescription: Python replace different character

description: Python replace different character


code:
from myapp import Account  # replace myapp with the script name of your app
import zodbbrowser.standalone
zodbbrowser.standalone.main()

rawDescription: How to inject types for standalone zodbbrowser?

description: Inject types for standalone zodbbrowser


code:
searchValue = "192.168.0.10:80"
newNumber = 2

f = open("datafile.txt", "r+b")

for line in file:
    if line.split()[0] == searchValue:
        position = f.tell() - len(line) #the tell() method gives the current position in the file
        f.seek(position)
        f.write("%s = %d" % (searchValue, newNumber))
        break

f.close()

rawDescription: Find specific line in text file, find specific character in the same line and change / modify its value


code:
import dis
dis.dis(compile('if x not in d: pass', '', 'exec'))
dis.dis(compile('if not x in d: pass', '', 'exec'))

rawDescription: if loop: x not in VS not x in

description: If loop: x not in VS not x in


code:
def testMyModelFilter(self):
  # Change the auto_now parameter to False
  MyModel.timestamp._auto_now = False

  # Test as usual...
  test1 = MyModel()
  test1.timestamp = datetime.datetime.now() - datetime.timedelta(hours=2)
  test1.put()
  test2 = MyModel()
  test2.timestamp = datetime.datetime.now() - datetime.timedelta(hours=1)
  test2.put()

  hour_ago = datetime.datetime.now() - datetime.timedelta(hours=1)
  fetched = MyModel.query().filter(MyModel.timestamp < hour_ago).fetch(
      None, keys_only=True)

rawDescription: How to test DateTimeProperty in App Engine NDB?

description: Test DateTimeProperty in App Engine NDB


code:
class CheckSerializer(serializers.ModelSerializer):

    subscribers = serializers.SlugRelatedField(many=True, read_only=True, slug_field='name')

    class Meta:
        model = Check
        fields = ('id', 'name', 'subscribers')

rawDescription: Serializing one field from a ManyToManyField DRF


code:
file.flush()
# typically the above line would do. however this is used to ensure that the file is written
os.fsync()

rawDescription: Can I save a text file in python without closing it?

description: Save a text file in python without closing it


code:
#   Useless stuff to help type info
if False :
    conn._set_tunnel("example.com")

rawDescription: When would `if False` execute in Python?

description: When would `if False` execute in Python


code:
import os
import sys

args = sys.argv
path = "\\".join(args[1].split('\\')[:-1])
file_name = args[1].split("\\")[-1]

file_name = file_name.lower()
file_name = file_name.replace(' ','_')

file_name = path+'\\'+file_name
os.rename(args[1],file_name)

rawDescription: Drag and drop on script not behaving properly


code:
import os
os.system('listdlls PID_OR_PROCESS_NAME_HERE')

rawDescription: How to list all dlls loaded by a process with Python?

description: List all dlls loaded by a process with Python


code:
import multiprocessing.Pool

p = multiprocessing.Pool() # use all available CPUs

input = open("input.txt")
x = (process_line(line) for line in input)
y = p.imap(process_item, x)
z = (generate_output_line(item) + "\n" for item in y)
output = open("output.txt", "w")
output.writelines(z)

rawDescription: How can I parallelize a pipeline of generators/iterators in Python?

description: Parallelize a pipeline of generators/iterators in Python


rawDescription: Python/postgres: Any advantage to converting mxDateTime to built in datetime objects?


code:
class table_name(models.Model):
    ID = models.CharField(max_length=9, primary_key=True)
    title = models.CharField(max_length=20, null=True)
    first_name = models.CharField(max_length=60, null=True)
    middle_name = models.CharField(max_length=60, null=True)
    last_name = models.CharField(max_length=60)

    class Meta:
        db_table="table_name_oracle_database"

rawDescription: How to connect to oracle legacy database using cx_oracle django package?

description: Connect to oracle legacy database using cx_oracle django package


code:
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://bitcoinity.org/markets')
driver.find_element_by_id('last_price').text

rawDescription: Missing Attribute in a Python HTML request


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

rawDescription: Retrieving the return value of a Python script


code:
from django.db import models
from django.dispatch import receiver

@receiver(models.signals.post_delete, sender=Server)
def delete_contact(sender, instance, **kwargs):
    if not Server.objects.filter(contact=instance.contact):
        instance.contact.delete()

rawDescription: How do I delete an object if not referenced by another object

description: Delete an object if not referenced by another object


code: updated_dict = dict(old_dict, **extra_dict)

rawDescription: In python is there something like updated that is to update what sorted is to sort?


rawDescription: Using DataFrame.ix with a tuple index in Pandas


code:
events = self.driver.find_elements_by_xpath("...")
item['event'] = [{'event_date': event.find_element_by_xpath("td[1]").text,
                  'event_time_type': event.find_element_by_xpath("td[2]").text,
                  'event_locate': event.find_element_by_xpath("td[3]").text}
                 for event in events]

rawDescription: python : save dictionary into list

description: Python : save dictionary into list


code:
import re
s = """
    ac1cA.txt
    ac1c-A.txt
    ac1c_A.txt
    AC1CA.txt
    AC1C-A.txt
    AC1C_A.txt
"""
re.findall(r'(?:ac1c|AC1C)(?:-|_)?A\.txt', s)

rawDescription: Check if file that match regexp is in directory


code:
class ServerClass():
    def make_new_thread(self, state):
        new_thread = ClientThread(state)
        new_thread.start()

class ClientThread(Thread):
    local_state = None

    def __init__(self, state):
        self.local_state = state

    def run(self):
        do_some_stuff()

rawDescription: Creating a Member Variable that is Local to a thread


code:
import ctypes
class sts( ctypes.BigEndianStructure ):
    _pack_ = 1
    _fields_ = [( "valid", ctypes.c_uint8, 1 ),
                ( "inout", ctypes.c_uint8, 2 ),
                ( "exception", ctypes.c_uint8, 2 ),
                ( "error", ctypes.c_uint8, 3 ), ]

class pkt( ctypes.BigEndianStructure ):
    _pack_ = 1
    _fields_ = [( "uid", ctypes.c_uint8 ),
                ( "sid", ctypes.c_uint16 ),
                ( "sts", sts, ), ]

print("sts {:d}-byte".format(ctypes.sizeof(sts)))
print("pkt {:d}-byte".format(ctypes.sizeof(pkt)))
a=pkt(0xFF,0xDEAD,(0x1,0x3,0x3,0x7))
print("uid {:02X}".format(a.uid))
print("sid {:02X}".format(a.sid))
print("sts {:02X}".format(ctypes.string_at(ctypes.addressof(a.sts))[0]))
for b in ctypes.string_at(ctypes.addressof(a),8):
    print("{:02X}".format(b))

rawDescription: Python Ctypes doesn't compact structure when field and structure fits


code:
import csv
import itertools

with open('1.csv') as f1, open('2.csv') as f2, open('new.csv', 'w') as f3:
    reader1 = csv.DictReader(f1, skipinitialspace=True)
    reader2 = csv.DictReader(f2, skipinitialspace=True)
    fieldnames = sorted(set(reader1.fieldnames) | set(reader2.fieldnames))
    # If want empty-name column to be placed at the end,
    #   uncomment following statement.
    # Otherwise it will be place at the beginning.
    #fieldnames.remove(''); fieldnames.append('')

    writer = csv.DictWriter(f3, fieldnames)
    writer.writeheader()
    writer.writerows(itertools.chain(reader1, reader2))

rawDescription: Merging two csv file based on header values in python


code:
import lxml.etree
# Python 2/3 compatibility
try:
    from StringIO import StringIO
except ImportError:
    from io import StringIO

class Elhanced(lxml.etree._ElementTree):
    def __init__(self, htmlString):
        super(Elhanced, self).__init__()
        self.x = 'useful'
        self.parse(StringIO(htmlString), lxml.etree.HTMLParser())

    def useful_function():
        pass

rawDescription: How to subclass when creating an object indirectly

description: Subclass when creating an object indirectly


code:
for field in fields_ls:
    null_crit = {field + "__isnull": True}
    blank_crit = {field + "__exact": ''}

    counts[field] = Ticket.objects.exclude(**null_crit).exclude(**blank_crit).count()

rawDescription: Is it possible to use a variable as code in python


code: max(piece.get('id', 0) for row in self.board for cell in row for piece in cell['b'])

rawDescription: Fast code for finding the max value of a 2d array


code:
class Category(MPTTModel):
    descr = models.CharField(max_length=200)
    parent = TreeForeignField('self', null=True, related_name='children')

class CategoryResource(ModelResource):
    category = fields.ToOneField('self', 'parent', full=True, null=True)

    # Rest of your Resource class

rawDescription: Representing Hierarchical Data in Tastypie


code: d['hi'] = d.pop('hii')

rawDescription: python: how to change the name of a key in a dictionary

description: Python: how to change the name of a key in a dictionary


code:
import sqlite3
from StringIO import StringIO

def init_sqlite_db(app):
    # Read database to tempfile
    con = sqlite3.connect(app.config['SQLITE_DATABASE'])
    tempfile = StringIO()
    for line in con.iterdump():
        tempfile.write('%s\n' % line)
    con.close()
    tempfile.seek(0)

    # Create a database in memory and import from tempfile
    app.sqlite = sqlite3.connect(":memory:")
    app.sqlite.cursor().executescript(tempfile.read())
    app.sqlite.commit()
    app.sqlite.row_factory = sqlite3.Row

rawDescription: How to load existing db file to memory in Python sqlite3?

description: Load existing db file to memory in Python sqlite3


code:
startDate = datetime.datetime(2016,1,1).strftime('%m/%d/%Y')
endDate = datetime.datetime(2016,2,20).strftime('%m/%d/%Y')

serviceurl = 'https://www.nysaves.org/nytpl/fundperform/fundHistorySearch.do'
payload = {'fundid': 1003022, 'startDate': startDate, 'endDate': endDate}
r = requests.post(serviceurl, data=payload)
print(r.text)

rawDescription: Python: How to click submit button in a form?


code:
class Home_Page(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent, background='black')

rawDescription: I cannot change the background color of my python 2.7 tkinter application


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1)

        sampleList = ['zero', 'one', 'two', 'three', 'four', 'five',
                      'six', 'seven', 'eight', 'nine', 'ten', 'eleven',
                      'more', 'and more']

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.clb = wx.CheckListBox(self, -1, (30,30), wx.DefaultSize, sampleList)
        self.Bind(wx.EVT_LISTBOX, self.EvtListBox, self.clb)
        self.Bind(wx.EVT_CHECKLISTBOX, self.EvtCheckListBox, self.clb)
        self.clb.SetSelection(0)

        sizer.Add(wx.Panel(self), 1, flag=wx.EXPAND)
        sizer.Add(self.clb, 0, flag=wx.EXPAND)
        sizer.Add(wx.Panel(self), 1, flag=wx.EXPAND)
        self.SetSizer(sizer)
        self.Fit()

    def EvtListBox(self, event):
        pass

    def EvtCheckListBox(self, event):
        pass

if __name__ == '__main__':

    app = wx.PySimpleApp()
    frame = MyFrame(None)
    frame.Show(True)
    app.MainLoop()

rawDescription: Something like the wx.MultiChoiceDialog in a panel instead of a dialog


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

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

z = np.array([0,1,2,3,4,5,6,7,8,9,10])
radius = np.array([0,1,1.5,1,0,2,4,5,4,2,1])
temp = np.array([150,200,210,220,225,220,195,185,160,150,140])

angle = np.linspace(0,2*np.pi,20)
Z,ANG = np.meshgrid(z,angle)
T,ANG = np.meshgrid(temp,angle)
# transform them to cartesian system
X,Y = radius*np.cos(ANG),radius*np.sin(ANG)

ax.plot_surface(X, Y, Z, rstride=1, cstride=1, facecolors=cm.jet(T/float(T.max())))
plt.show()

rawDescription: Representing 4D data in mplot 3D using colormaps


code:
import sys
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from matplotlib.patches import Circle
from matplotlib import animation
from time import sleep

class Window(QtGui.QDialog): #or QtGui.QWidget ???

    def __init__(self):
        super(Window, self).__init__()
        self.fig = Figure(figsize=(5, 4), dpi=100)
        self.canvas = FigureCanvas(self.fig)
        self.ax = self.fig.add_subplot(111)  # create an axis
        self.ax.hold(False)  # discards the old graph
        self.ax.set_aspect('equal', 'box')
        self.circle = Circle((0,0), 1.0, animated=True)
        self.ax.add_artist(self.circle)
        self.ax.set_xlim([0, 10])
        self.ax.set_ylim([-2, 2])
        self.button = QtGui.QPushButton('Animate')
        self.button.clicked.connect(self.animate)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)
        self.canvas.draw()
        self.ax_background = self.canvas.copy_from_bbox(self.ax.bbox)

    def animate(self):
        self.animate_loop(0)

    def animate_loop(self,i):
        for i in range(10):
            self.canvas.restore_region(self.ax_background)
            self.circle.center=(i,0)
            self.ax.draw_artist(self.circle)
            self.canvas.blit(self.ax.bbox)
            self.canvas.flush_events()
            sleep(0.1)

def main():

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

if __name__ == '__main__':
    main()

rawDescription: Getting blitting to work in funcAnimation embedded in PyQT4 GUI


code: {k: v for k, v in parent_dict.items() if k not in derived_dict}

rawDescription: Delete a dictionary from another dictionary python


code:
amount = 5
costFieldList = [amount]

for index, field in enumerate(costFieldList):
    if isinstance(field,int):  # use issinstance to check if field is an integer
        costFieldList[index] = field * 2
        print(costFieldList)
        amount=costFieldList[index] # set amount to value of costFieldList index
print(amount,costFieldList )
(10, [10])

rawDescription: How do i change a list element's value in a for loop in python?

description: Change a list element's value in a for loop in python


code:
import cv2

cv2.namedWindow("lala")
img = cv2.imread(filedir + orange.jpg) # load initial image

while True:
    cv2.imshow("lala", img)

    k = cv2.waitKey()
    if k == 'w':                      # toggle current image
        img = cv2.imread(filedir + orange.jpg)
    elif k == 'a':
        img = cv2.imread(filedir + banana.jpg)
    elif k == 27:
        break

cv2.destroyAllWindows()

rawDescription: Python OpenCV: Refresh images when a key is pressed


code:
import _winreg as winreg
import ctypes

ENV_HTTP_PROXY = u'http://87.254.212.121:8080'

class Registry(object):
    def __init__(self, key_location, key_path):
        self.reg_key = winreg.OpenKey(key_location, key_path, 0, winreg.KEY_ALL_ACCESS)

    def set_key(self, name, value):
        try:
            _, reg_type = winreg.QueryValueEx(self.reg_key, name)
        except WindowsError:
            # If the value does not exists yet, we (guess) use a string as the
            # reg_type
            reg_type = winreg.REG_SZ
        winreg.SetValueEx(self.reg_key, name, 0, reg_type, value)

    def delete_key(self, name):
        try:
            winreg.DeleteValue(self.reg_key, name)
        except WindowsError:
            # Ignores if the key value doesn't exists
            pass

class EnvironmentVariables(Registry):
    """
    Configures the HTTP_PROXY environment variable, it's used by the PIP proxy
    """

    def __init__(self):
        super(EnvironmentVariables, self).__init__(winreg.HKEY_LOCAL_MACHINE,
                                                   r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment')

    def on(self):
        self.set_key('HTTP_PROXY', ENV_HTTP_PROXY)
        self.refresh()

    def off(self):
        self.delete_key('HTTP_PROXY')
        self.refresh()

    def refresh(self):
        HWND_BROADCAST = 0xFFFF
        WM_SETTINGCHANGE = 0x1A

        SMTO_ABORTIFHUNG = 0x0002

        result = ctypes.c_long()
        SendMessageTimeoutW = ctypes.windll.user32.SendMessageTimeoutW
        SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, u'Environment', SMTO_ABORTIFHUNG, 5000, ctypes.byref(result));

rawDescription: Modify `PATH` environment variable globally and permanently using Python


code: ukeys = request.POST.getlist('ukeys[]')

rawDescription: django - getlist()

description: Django - getlist()


rawDescription: How to keep index when using pandas merge

description: Keep index when using pandas merge