code:
import win32com.client
excel = win32com.client.Dispatch('Excel.Application')

wb = excel.Workbooks.Add()
ws = wb.Sheets(1)

if ws.Name!="TheSheetImLookingFor":
    raise ValueError(ws.Name)

rawDescription: Check worksheet name with win32com

description: Check worksheet name with win32com


code:
import numpy as np
y = [1,2,3,4,5]
f = [1.9, 3.7, 5.8, 8.0, 9.6]
SSres = sum(map(lambda x: (x[0]-x[1])**2, zip(y, f)))
SStot = sum([(x-np.mean(y))**2 for x in y])
SSres, SStot
1-(SSres/SStot)

rawDescription: Significant mismatch between `r2_score` of `scikit-learn` and the R^2 calculation


code:
from PyQt4 import QtGui, QtCore

import sys

class Window(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        widget = QtGui.QWidget()
        self.setCentralWidget(widget)

        self.menu_bar = QtGui.QMenuBar(self)
        menu = self.menu_bar.addMenu('File')

        exit_action = QtGui.QAction('Exit', self)
        exit_action.triggered.connect(self.close)
        menu.addAction(exit_action)
        self.setMenuBar(self.menu_bar)

    def closeEvent(self, event):
        print('Calling')
        print('event: {0}'.format(event))
        event.accept()

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

rawDescription: Generating a QCloseEvent won't close QMainWindow


code:
max_val, max_obj = max([(val, obj) for obj, val in tuple_list])
return max_obj, max_val

rawDescription: Tuples, Max Value, and Clean Iteration

description: Tuples, Max Value, and Clean Iteration


code:
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
from django.core.cache import cache
from models import MyStorage
default_storage.exists('storage_test')
file = default_storage.open('storage_test', 'w')
file.write('storage contents')
file.close()
default_storage.exists('storage_test')
file = default_storage.open('storage_test', 'r')
file.read()
file.close()
default_storage.delete('storage_test')
default_storage.exists('storage_test')

rawDescription: How to best save a file from Django on Heroku to S3

description: Best save a file from Django on Heroku to S3


rawDescription: combine two lists in a dictionary - python

description: Combine two lists in a dictionary - python


code:
from tkinter import *
import random

class App:
    def __init__(self, master):
        self.say_one()

    def say_one(self):
        v = IntVar()
        window = Toplevel(root)

        for i in range(1,11):
            self.label = Radiobutton(
                window, text = i , fg = "red",
                value = i, variable = v
            ).grid(row =i, column =0)

        # error is occurring in the next line
        self.report = Button(
            window, text="submit", command=lambda: num(v)
        ).grid(row = 12, column = 0)

def num(var):
    print(var.get())

root = Tk()
app = App(root)
root.mainloop()

rawDescription: trying to pass the current radiobutton value in tkinter but getting global name not defined

description: Trying to pass the current radiobutton value in tkinter but getting global name not defined


code:
a = '\\xeb\\x4d'   # a Unicode string
a.encode('latin1') # get a byte string
a.encode('latin1').decode('unicode_escape') # unescape, get a Unicode string
a.encode('latin1').decode('unicode_escape').encode('latin1') # get a byte string
a.encode('latin1').decode('unicode_escape').encode('latin1') == b'\xeb\x4d'

rawDescription: Convert string to bytes literally

description: Convert string to bytes literally


rawDescription: Wrapping python doctest results that are longer than 80 characters


code:
import subprocess, time
p = subprocess.Popen(['program1.exe'])
time.sleep(1) # Parameter is in seconds
p.terminate()
p.wait()

rawDescription: Run and terminate a program (Python under Windows)


code:
c = collections.Counter(a=1, b=999)
c.most_common()

rawDescription: Pythonic way to iterate over a collections.Counter() instance in descending order?


code:
icon_path = os.path.abspath('icons')
gtk.IconTheme.append_search_path(icon_path)

rawDescription: GTK Named Icons: Load while running from source, during development


code:
plt.plot(time[:-1], scipy.integrate.cumtrapz(signal, x=time))
plt.show()

rawDescription: How to plot the integral of a signal as time goes by?

description: Plot the integral of a signal as time goes by


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.set(title='Draw a 4-sided polygon by clicking points')
data = plt.ginput(4)

data.append(data[0])
ax.autoscale(False)
ax.fill(*zip(*data))
plt.show()

rawDescription: How to get multiple Button Click Events in Python

description: Get multiple Button Click Events in Python


code:
import gtk

def keypress(win, event):
    if event.keyval == gtk.keysyms.F11:
        win.is_fullscreen = not getattr(win, 'is_fullscreen', False)
        action = win.fullscreen if win.is_fullscreen else win.unfullscreen
        action()
        label.set_visible(not win.is_fullscreen)

win = gtk.Window()
win.connect("delete-event", gtk.main_quit)
win.connect('key-press-event', keypress)
image = gtk.image_new_from_stock(gtk.STOCK_ABOUT, gtk.ICON_SIZE_DIALOG)
label = gtk.Label(('test ' * 20 + '\n') * 20)
vbox = gtk.HBox()
vbox.add(label)
vbox.add(image)
win.add(vbox)
win.show_all()
gtk.main()

rawDescription: How to change the layout of a Gtk application on fullscreen?

description: Change the layout of a Gtk application on fullscreen


rawDescription: Creating a new input event dispatcher in Pyglet (infra red input)


code:
@task
def make_a_lot_of_calls(numbers):
    for num in numbers:
        # Assuming that reminder blocks till the call finishes
        reminder(number)

def make_calls(request):
    make_a_lot_of_calls.delay(phone_numers)
    return redirect('live_call_updates')

rawDescription: Create celery tasks then run synchronously


code:
df.groupby("CID", as_index=False).first()
df.groupby("CID", as_index=False, sort=False).first()

rawDescription: Pandas Groupby Row with Multiple Columns


rawDescription: Uploading Files in webapp2/GAE

description: Uploading Files in webapp2/GAE


code:
visit_urls=[]
self.br.get(url)
count = self.br.find_elements_by_xpath("//*[@class='count']").get_attribute("innerHTML")

for page_number in xrange(1, count+1):
    url = '{url}&page={page_number}'.format(url=url, page_number=page_number)
    visit_urls.append(url)

rawDescription: Loop For And Add To List

description: Loop For And Add To List


code:
with mock.patch('mymod.log') as log_mock:
    # test code
    log_mock.debug.assert_called_with('Init')

rawDescription: How can I patch / mock logging.getlogger()

description: Patch / mock logging.getlogger()


code:
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

def do_stuff(cell): #just so the plots show up
    ax = plt.subplot(cell)
    ax.plot()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
plt.subplots_adjust(hspace=0.0)
#make outer gridspec
outer = gridspec.GridSpec(2, 1, height_ratios = [1, 6])
#make nested gridspecs
gs1 = gridspec.GridSpecFromSubplotSpec(1, 1, subplot_spec = outer[0])
gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec = outer[1], hspace = .05)
for cell in gs1:
    do_stuff(cell)
for cell in gs2:
    do_stuff(cell)
plt.show()

rawDescription: Spacing between some subplots but not all


code:
import numpy as np
a = [['2012', '3', '22'], ['2012', '3', '27'], ['2012', '3', '30'], ['2012', '3', '30'], ['2012', '4', '7'], ['2011', '2', '12'], ['2011', '2', '14'], ['2011', '10', '10']]
# convert all date parts to integers
a = [[int(e) for e in d] for d in a]

years = set(d[0] for d in a)
minyear, maxyear = min(years), max(years)
nyears = maxyear - minyear + 1
nmonths = 12

monthly_counts = np.zeros((nyears,nmonths))
for year,month,_ in a:
    monthly_counts[year-minyear,month-1] += 1

rawDescription: Plot csv file in matplotlib

description: Plot csv file in matplotlib


code:
import os
os.system('ls -lt')

rawDescription: Execution of a OS command from a Python daemon


code:
p_number = forms.IntegerField(
               widget=forms.TextInput(
                                  attrs={'autocomplete':'off',}
                                     )
                              )

rawDescription: Disable autocomplete in django-crispy-forms PrendedText Field


code:
def commentHandler(t):
    result = []
    if "fixed" in t[0]:
        result.append("fixed")
    if "TODO: " in t[0]:
        try:
            message = t[0].split("TODO: ")[1].strip()
            result.append(message)
        except Exception as e:
            result.append(t[0])
    return result

comment.setParseAction(commentHandler)

rawDescription: Pyparsing ignore except

description: Pyparsing ignore except


code:
import random
coordinates = [(i, j) for i in xrange(10) for j in xrange(10)]
random.shuffle(coordinates)
coordinates[:60]

rawDescription: Pythonic way to sparsely randomly populate array?


code:
import sys
with open(sys.argv[1],'r+') as f1:
    lines=[x.strip() for x in f1]
    f1.truncate(0)
    f1.seek(0)
    for x in lines:
       if x:
         f1.write(x+'\n')
       else:
         f1.write("{0}:{1}\n\n".format(sys.argv[2],sys.argv[3]))
    f1.write("{0}:{1}\n\n".format(sys.argv[2],sys.argv[3]))

rawDescription: write at specific part of file in python

description: Write at specific part of file in python


code:
THIS_VAR = {}
for i in range(n):
    THIS_VAR[i] = 2 ** i

rawDescription: python efficiency Which is better for setting variables being used in the context of constants

description: Python efficiency Which is better for setting variables being used in the context of constants


code:
import numpy as np
from scipy.ndimage.filters import generic_filter as gf

kernel = np.zeros((2*radius+1, 2*radius+1))
y,x = np.ogrid[-radius:radius+1, -radius:radius+1]
mask = x**2 + y**2 <= radius**2
kernel[mask] = 1
#calculate
circular_min = gf(data, np.min, footprint=kernel)

rawDescription: Circular Neighborhood - Minimum Numpy

description: Circular Neighborhood - Minimum Numpy


code:
from datetime import date, timedelta

def from_excel_ordinal(ordinal, _epoch=date(1900, 1, 1)):
    if ordinal > 59:
        ordinal -= 1  # Excel leap year bug, 1900 is not a leap year!
    return _epoch + timedelta(days=ordinal - 1)  # epoch is day 1

rawDescription: How to convert a given ordinal number (from Excel) to a date

description: Convert a given ordinal number (from Excel) to a date


code: print(json.dumps(obj, indent=2))

rawDescription: Pretty JSON Formatting in IPython Notebook


code:
k = db.Key.from_path(FbUser.kind(), 131)
room = Room.all().filter('fb_user =', k).get()
db.delete(room)

rawDescription: How to get entity by child id while child is already deleted?

description: Get entity by child id while child is already deleted


code:
my_xml_string = """
<root>
      <content>
        <one>A value</one>
        <two>Here goes for ...</two>
      </content>
</root>"""

xml = parseString(xml_string)
result = xml.getElementsByTagName('one')[0].firstChild.data

rawDescription: simplexml_load_string equivalent Python / Django

description: Simplexml_load_string equivalent Python / Django


code:
def toJSON(self):
    clone = copy.deepcopy(self)
    if getattr(clone.data, '_state', False):
        del clone.data._state
    return jsonpickle.encode(clone, unpicklable=False)

rawDescription: Easy way to exclude django _state attribute from jsonpickle.encode


code:
from selenium.webdriver.firefox.webdriver import WebDriver

driver = WebDriver()
driver.get('https://example.com/examplelogin')

username = driver.find_element_by_id('username')
password = driver.find_element_by_id('password')

username.send_keys('MY_USERNAME')
password.send_keys('MY_PASSWORD')

submit.click()

rawDescription: Python Requests - POST confusion

description: Python Requests - POST confusion


code: numpy.set_printoptions(formatter={'float': lambda x: 'float: ' + str(x)})

rawDescription: How can I produce a nice output of a numpy matrix?

description: Produce a nice output of a numpy matrix


code:
import redis
r = redis.StrictRedis(host=YOUR_HOST, port=YOUR_PORT, db=YOUR_DB)
r.keys()

rawDescription: Get all keys in Redis database with python


code:
def remove_empty_dirs(path):
    for root, dirnames, filenames in os.walk(path, topdown=False):
        for dirname in dirnames:
            remove_empty_dir(os.path.realpath(os.path.join(root, dirname)))

rawDescription: How to delete recursively empty folders in Python3?

description: Delete recursively empty folders in Python3


code:
rows, cols = map(int, os.popen('stty size', 'r').read().split())
child.setwinsize(rows, cols)

rawDescription: How to clone pexpect winsize from current terminal?

description: Clone pexpect winsize from current terminal


code:
for ext in extension_list:
    mydict[ext] += 1

rawDescription: python - count files (can't count values in a dictionary)

description: Python - count files (can't count values in a dictionary)


code:
from bs4 import BeautifulSoup
import requests

resp = requests.get('http://dl.acm.org/results.cfm',
                    params={'CFID': '376026650', 'CFTOKEN': '88529867'})
soup = BeautifulSoup(resp.content, from_encoding=resp.encoding)

for title_link in soup.find_all('a', target='_self'):
    # find parent row to base rest of search of
    row = next(p for p in title_link.parents if p.name == 'tr')
    title = title_link.get_text()
    authors = row.find('div', class_='authors').get_text()
    journal = row.find('div', class_='addinfo').get_text()
    abstract = row.find('div', class_='abstract2').get_text()

rawDescription: Why am i getting authors, titles, abstract and journals first and then appearing together? They should be together per title.


code:
import pandas as pd

df = pd.DataFrame(
    [['John Lennon', 10], ['George Harrison', 6]],
    columns=['beatle', 'songs']
)

longform = pd.DataFrame(columns=['word', 'num'])

for idx, name, songs in df.itertuples():
    name_words = (i.lower() for i in name.split())

    longform = longform.append(
        [{'word': nw, 'num': songs} for nw in name_words],
        ignore_index=True
    )

print(longform.head())

#        word  num
# 0      john   10
# 1    lennon   10
# 2    george    6
# 3  harrison    6

rawDescription: Splitting sentences in a column and then appending in a data frame in python


code:
def get_from_dict(data, keys):
    for key in keys:
        data = data[key]
    return data

def set_in_dict(data, keys, value):
    get_from_dict(data, keys[:-1])[keys[-1]] = value

rawDescription: Convert reduce lambda to list comprehension


code:
import csv
testSet = set(['thissucks.in', 'whateverlife.in', 'crapface.in', 'lasttry.in'])
with open('mag.csv', 'ab+') as f:
    writer = csv.writer(f ,dialect= 'excel', delimiter= ',')
    for domain in testSet:
        writer.writerow([domain, '', 'Related'] )

rawDescription: Writing a set plus a formatted string to a CSV?


code:
x = [[] for i in range(3)]
map(id, x)
x[0].append(1)
x
y = [[]] * 3
y[0].append(1)
y
map(id, y)

rawDescription: Numpy appending to both elements of python list


code:
import re
mystring = "You said {single order='randomize'} that P.E is...Why?"
if mystring.find("randomize") != -1:
    if re.search(r'{[^{}]*randomize[^{}]*}', mystring):
        print("'randomize' present within braces")
    else:
        print("'randomize' present but not within braces")
else:
    print("'randomize' absent")

rawDescription: find a given word in between brackets in a string python regex

description: Find a given word in between brackets in a string python regex


code:
HOME_URL = "localhost:8080"
def initialize():
      #global HOME_URL #You don't need this
      home_url = HOME_URL
      with open("urls.txt", 'rb') as f:
           #Constants are not supposed to mutate
           home_url = json.load(f.read())['urls']

rawDescription: Python global variable usage

description: Python global variable usage


rawDescription: Separate lists stored in a variable using Python


rawDescription: Python string trimming

description: Python string trimming


code:
list_of_lists = [[1, 2], [1, 3], [1, 4]]
len(set([sublist[0] for sublist in list_of_lists])) == 1
# True

rawDescription: Compare 1st element of list from nest list in python


code:
import subprocess
p=subprocess.Popen('FILE_1.py')
p.communicate()

rawDescription: Open File with Python

description: Open File with Python


rawDescription: Append CSVs without column names

description: Append CSVs without column names


code:
for index, item in enumerate(lst):
    lst[index] = func(item)

rawDescription: Accessing elements of a list

description: Accessing elements of a list


code:
from collections import Counter

counts = Counter()

for d in bunch_of_dicts:
    counts.update(d)

rawDescription: Addition using Dictionary updates

description: Addition using Dictionary updates


code:
#!/usr/bin/python
# -*- coding: utf-8 -*-
#written by Sebastian Stetter in 2010

import sys
from PIL import Image
from PIL.ImageQt import ImageQt

from PyQt4.QtGui import *
from PyQt4.QtCore import *

def PILimageToQImage(pilimage):
    """converts a PIL image to QImage"""
    imageq = ImageQt(pilimage) #convert PIL image to a PIL.ImageQt object
    qimage = QImage(imageq) #cast PIL.ImageQt object to QImage object -that´s the trick!!!
    return qimage

if __name__ == "__main__":
    #Testcode
    app = QApplication(sys.argv)

    pim = Image.open(unicode(QFileDialog().getOpenFileName()))
    pim.show() #show pil image

    qim = PILimageToQImage(pim)
    pm = QPixmap(qim)
    lbl = QLabel()
    lbl.setPixmap(pm)
    lbl.show() #show label with qim image

    sys.exit(app.exec_())

rawDescription: Bug when drawing a QImage on a widget with PIL and PyQt


code:
from Crypto.Cipher import Blowfish
from binascii import hexlify

def encrypt(key, string):
    """
    Encrypts input string using BlowFish-Compat ECB algorithm.
    :param key: secret key
    :param string: string to encrypt
    :return: encrypted string
    """
    cipher = Blowfish.new(key, Blowfish.MODE_ECB)
    return hexlify(_reverse_bytes(cipher.encrypt(_reverse_bytes(string)))).decode('utf-8')

@staticmethod
def _reverse_bytes(data):
    """
    Takes data and reverses byte order to fit blowfish-compat format. For example, using _reverse_bytes('12345678')
    will return 43218765.
    :param data as bytes
    :return: reversed bytes
    """
    data_size = 0
    for n in data:
        data_size += 1

    reversed_bytes = bytearray()
    i = 0
    for x in range(0, data_size // 4):
        a = (data[i:i + 4])
        i += 4
        z = 0

        n0 = a[z]
        n1 = a[z + 1]
        n2 = a[z + 2]
        n3 = a[z + 3]
        reversed_bytes.append(n3)
        reversed_bytes.append(n2)
        reversed_bytes.append(n1)
        reversed_bytes.append(n0)

    return bytes(reversed_bytes)

rawDescription: java and Python implementation of Blowfish produce different results

description: Java and Python implementation of Blowfish produce different results


code:
from ggplot import *
import numpy as np
import pandas as pd
df = pd.DataFrame({ "x": np.arange(0, 10), "y": np.arange(0, 1, 0.1) })
ggplot(df, aes(x='x', y='y')) +\
geom_point() +\
scale_y_continuous(labels='percent')

rawDescription: Python ggplot format axis number as percent not functioning


code:
#!/usr/bin/env python

from Tkinter import *
from tkFileDialog  import askopenfilename

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.button = Button(frame, text="QUIT", command=frame.quit)
        self.button.pack(side=BOTTOM)

        self.text = Text(frame)
        self.text.pack(side=TOP)

        self.choosen = askopenfilename(initialdir='~')
        self.text.insert(END, open(self.choosen).read())

root = Tk()
app = App(root)
root.mainloop()

rawDescription: Python file I/O with Tkinter

description: Python file I/O with Tkinter


code:
import wx

class MainPanel(wx.Panel):
    def __init__(self, parent, bg_img='Logo4x3.png'):
        wx.Panel.__init__(self, parent=parent)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.bg = wx.Bitmap(bg_img)
        self._width, self._height = self.bg.GetSize()

        sizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        for num in range(4):
            btn = wx.Button(self, label="Button %s" % num)
            sizer.Add(btn, 0, wx.ALL, 5)
        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(sizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75)
        self.SetSizer(hSizer)
        self.Bind(wx.EVT_SIZE, self.OnSize)
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)

    def OnSize(self, size):
        self.Layout()
        self.Refresh()

    def OnEraseBackground(self, evt):
        pass

    def OnPaint(self, evt):
        dc = wx.BufferedPaintDC(self)
        self.Draw(dc)

    def Draw(self, dc):
        cliWidth, cliHeight = self.GetClientSize()
        if not cliWidth or not cliHeight:
            return
        dc.Clear()
        xPos = (cliWidth - self._width)/2
        yPos = (cliHeight - self._height)/2
        dc.DrawBitmap(self.bg, xPos, yPos)

app = wx.App()
frame = wx.Frame(None, size=(400,300))
panel = MainPanel(frame)
frame.Show()
app.MainLoop()

rawDescription: wxPython Background image on frame

description: WxPython Background image on frame


code:
def test(e1, d1):
    return eval(e1, globals(), d1)

rawDescription: Is it bad to use vars()

description: Is it bad to use vars()


code:
#!/usr/bin/env python3
import sys

filename = sys.argv[1]

# read the file line by line
with open(filename) as f:
    for line in f:
        # split the line
        columns = line.split(",")

        # print all lines with "hello" as the first column
        if columns[0] == "hello":
            print(line, end='')

rawDescription: How to print select lines of a text file in python?

description: Print select lines of a text file in python


code:
for big_index, cities in enumerate(lst):
    for index, char in enumerate(cities):
        if char == char.lower() and cities[index+1] != cities[index+1].lower():
            lst[big_index] = cities[:index] + "," + cities[index:]

rawDescription: Inserting ',' based on conditionals within a STR - Python


code:
def list_lolwut(list1, list2):
    tmp = dict([(str(list(reversed(b))), [a, list(reversed(b))]) for a,b in list2])
    return [tmp.get(str(item), False) for item in list1]

import unittest

class Test(unittest.TestCase):
    def test1(self):
        list1 = [[1,2],[2,3],[3,4],[4,5]]
        list2 = [[1,[3,2]], [3,[2,1]], [4,[5,4]]]
        expected = [[3,[1,2]], [1,[2,3]], False, [4,[4,5]]]
        self.assertEqual(expected, list_lolwut(list1, list2))

unittest.main()

rawDescription: Python: Match list of list item

description: Python: Match list of list item


code:
def create_proxy_admin(model_admin, model, name = None):
    # Create a proxy class for the specified model
    class  Meta:
        proxy = True
        app_label = model._meta.app_label

    attrs = {'__module__': '', 'Meta': Meta}
    proxy_model = type(name, (model,), attrs)

    # Register the proxy model with model_admin
    admin.site.register(proxy_model, model_admin)

for section in Section.objects.all():
    name = str(section.name.capitalize())

    # Define any attributes for the admin
    # Could be modified for each section as required!
    admin_attrs = {'list_display': ('some_field', ),
                  }

    # Select the appropriate model
    if section.model == section.FRUIT:
        Model = Fruit
    elif section.model == section.MEAT:
        Model = Meat
    else:
        Model = Food

    # Create ModelAdmin class
    Admin = type(name+'Admin', (admin.ModelAdmin,), admin_attrs)

    # Create proxy model and register with admin
    create_proxy_admin(Admin, name=name, model=Model)

rawDescription: Use dynamically created categories as models in the Django admin site and register a model more than once


rawDescription: removing columns which has only "nan" values from a numpy matrix

description: Removing columns which has only "nan" values from a numpy matrix


rawDescription: Parse URL from plain text

description: Parse URL from plain text


display_name: Python 2

rawDescription: Change kernel to another version of python instead of system Python in Mac OSX


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

# dummy correlation coefficients
coeffs = np.random.randn(10, 10)
row = coeffs[0]

# indexing with None (or equivalently, np.newaxis) inserts an extra singleton
# dimension
plt.imshow(row[None, :], cmap=plt.cm.jet, interpolation='nearest')

rawDescription: Plot only one or few rows of a correlation matrix


code:
import logging

logger = logging.getLogger(__name__)

class RetryMiddleware(object):
    def process_response(self, request, response, spider):
        if 'var PageIsLoaded = false;' in response.body:
            logger.warning('parse_page encountered an incomplete rendering of {}'.format(response.url))
            return self._retry(request) or response

        return response

    def _retry(self, request):
        logger.debug("Retrying %(request)s", {'request': request})

        retryreq = request.copy()
        retryreq.dont_filter = True
        return retryreq

rawDescription: Scrapy CrawlSpider retry scrape

description: Scrapy CrawlSpider retry scrape


rawDescription: Where is a good place/way to store Windows config files for Python scripts?


code:
s = "This is a very long string with many many many many and many more sentences and there is not one character that i can use to split by, just by number of words"
l = s.split()
n = 5
[' '.join(l[x:x+n]) for x in xrange(0, len(l), n)]

rawDescription: How do i split a very long string into a list of shorter strings in python

description: Split a very long string into a list of shorter strings in python


code:
name = os.path.join(os.path.dirname(__file__) or  ".", "binary_file.out")
subprocess.Popen(name)

rawDescription: subprocess, Popen to run command in a module

description: Subprocess, Popen to run command in a module


code:
class MyObject(models.Model):
    MALE = 0
    FEMALE = 1
    ROBOT = 2
    MY_CHOICES = [
        (MALE, 'Male'),
        (FEMALE, 'Female'),
        (ROBOT, 'Robot'),
    ]
    gender = models.IntegerField(choices=MY_CHOICES)

MyObject.objects.filter(gender=MyObject.ROBOT)

rawDescription: Alternatives to a ManytoManyField for static/hardcoded data?


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

def g(R, r):
    return (np.sqrt(2.0 * (R + r) / (r * R)) - (1 + np.sqrt(R)) / np.sqrt(R) -
            np.sqrt(2.0 / (r * (1 + r))) * (1 - r) -
            (1.0 / np.sqrt(R) - np.sqrt(2.0) * (1 - R) / np.sqrt(R * (1 + R))
             - 1))

R, r = np.mgrid[1:30:200j, 1:100:200j]
Z = g(R,r)
plt.contour(R, r, Z, colors='k', levels=[0])
plt.show()

rawDescription: Python: Plotting 2 dimensional function of two variables


code:
I, J = np.indices(values.shape)
triplets = np.column_stack(ar.ravel() for ar in (I, J, values))
np.savetxt(filename, triplets, '%i %i %.9f')

rawDescription: Matrix --> ijv (or triplet or co-ordinate) format --> file in Numpy?


code: {{ model.datetime|date:"g:i a" }}

rawDescription: Django datetimefield time in template

description: Django datetimefield time in template


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

#-- Generate Data -----------------------------------------
# Using linspace so that the endpoint of 360 is included...
azimuths = np.radians(np.linspace(0, 360, 20))
zeniths = np.arange(0, 70, 10)

r, theta = np.meshgrid(zeniths, azimuths)
values = np.random.random((azimuths.size, zeniths.size))

#-- Plot... ------------------------------------------------
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.contourf(theta, r, values)

plt.show()

rawDescription: Polar contour plot in matplotlib - best (modern) way to do it?


code:
#!/usr/bin/python

from jsonschema import Validator
checker = Validator()
schema = {
    "type" : "object",
    "properties" : {
        "source" : {
            "type" : "object",
            "properties" : {
                "name" : {"type" : "string" }
            },
            "additionalProperties": False, # add this
        }
    }
}
data ={
   "source":{
      "name":"blah",
      "bad_key":"This data is not allowed according to the schema."
   }
}
checker.validate(data,schema)

rawDescription: python data structure validation using Validator (or something similar)

description: Python data structure validation using Validator (or something similar)


code:
import subprocess
e = 'echo "perp -t ../data/ReviewTest.text | ./eva -b ../data/6.binlm'
subprocess.call(e, shell=true)

rawDescription: python call a command line which includes both "echo" and "|"

description: Python call a command line which includes both "echo" and "|"


code:
selected = []
for i in xrange(n):
    perm = nextPermutation()
    if random.random() < float(k-len(selected))/(n-i):
        selected.append(perm)

rawDescription: Lazily sample random results in python

description: Lazily sample random results in python


code:
import matplotlib.pyplot as plt
import matplotlib.patches as patches
class DraggablePoint:
    lock = None #only one can be animated at a time
    def __init__(self, point):
        self.point = point
        self.press = None
        self.background = None

    def connect(self):
        'connect to all the events we need'
        self.cidpress = self.point.figure.canvas.mpl_connect('button_press_event', self.on_press)
        self.cidrelease = self.point.figure.canvas.mpl_connect('button_release_event', self.on_release)
        self.cidmotion = self.point.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)

    def on_press(self, event):
        if event.inaxes != self.point.axes: return
        if DraggablePoint.lock is not None: return
        contains, attrd = self.point.contains(event)
        if not contains: return
        self.press = (self.point.center), event.xdata, event.ydata
        DraggablePoint.lock = self

        # draw everything but the selected rectangle and store the pixel buffer
        canvas = self.point.figure.canvas
        axes = self.point.axes
        self.point.set_animated(True)
        canvas.draw()
        self.background = canvas.copy_from_bbox(self.point.axes.bbox)

        # now redraw just the rectangle
        axes.draw_artist(self.point)

        # and blit just the redrawn area
        canvas.blit(axes.bbox)

    def on_motion(self, event):
        if DraggablePoint.lock is not self:
            return
        if event.inaxes != self.point.axes: return
        self.point.center, xpress, ypress = self.press
        dx = event.xdata - xpress
        dy = event.ydata - ypress
        self.point.center = (self.point.center[0]+dx, self.point.center[1]+dy)

        canvas = self.point.figure.canvas
        axes = self.point.axes
        # restore the background region
        canvas.restore_region(self.background)

        # redraw just the current rectangle
        axes.draw_artist(self.point)

        # blit just the redrawn area
        canvas.blit(axes.bbox)

    def on_release(self, event):
        'on release we reset the press data'
        if DraggablePoint.lock is not self:
            return

        self.press = None
        DraggablePoint.lock = None

        # turn off the rect animation property and reset the background
        self.point.set_animated(False)
        self.background = None

        # redraw the full figure
        self.point.figure.canvas.draw()

    def disconnect(self):
        'disconnect all the stored connection ids'
        self.point.figure.canvas.mpl_disconnect(self.cidpress)
        self.point.figure.canvas.mpl_disconnect(self.cidrelease)
        self.point.figure.canvas.mpl_disconnect(self.cidmotion)

fig = plt.figure()
ax = fig.add_subplot(111)
drs = []
circles = [patches.Circle((0.32, 0.3), 0.03, fc='r', alpha=0.5),
               patches.Circle((0.3,0.3), 0.03, fc='g', alpha=0.5)]

for circ in circles:
    ax.add_patch(circ)
    dr = DraggablePoint(circ)
    dr.connect()
    drs.append(dr)

plt.show()

rawDescription: Matplotlib drag overlapping points interactively


code:
s1 = 'ﻧ'
s2 = 'ﻨ'
unicodedata.normalize('NFKD', s1).casefold() == unicodedata.normalize('NFKD', s2)

rawDescription: Is there a way to compare Arabic characters without regard to their initial/medial/final form?


code:
@app.route('/server')
def server():
    return os.environ.get('SERVER_SOFTWARE')

rawDescription: Server information in a Flask app

description: Server information in a Flask app


code:
def get_last(a):
  for i, e in enumerate(reversed(a)):
    if e is not None:
      return len(a) - i - 1
  return -1

rawDescription: python find the index of the last value in a list that is not a "None"

description: Python find the index of the last value in a list that is not a "None"


code:
view.set_overwrite_status(True) # Or False
view.overwrite_status()

rawDescription: Sublime Text detect overwrite mode

description: Sublime Text detect overwrite mode


code:
from pytz import timezone
tz= timezone('America/Guatemala')
from datetime import datetime
tz.fromutc( datetime.utcnow() )

rawDescription: Exact time in server python

description: Exact time in server python


code:
import wx.py.crust
...
...
# then call

crustFrame = wx.py.crust.CrustFrame(parent = self)
crustFrame.Show()

rawDescription: Embedding a Python shell inside a Python program


code:
from gi.repository import Gtk, Wnck
Gtk.main_iteration()
screen = Wnck.Screen.get_default()
screen.force_update()
screen.get_windows()

rawDescription: How can I get a list of windows with Wnck, using PyGI?

description: Get a list of windows with Wnck, using PyGI


code:
for e in soup.findAll('br'):
    e.extract()

rawDescription: Remove <br> tags from a parsed Beautiful Soup list?


code:
CONCURRENT_REQUESTS = 1
DEPTH_PRIORITY = 1

rawDescription: Scrapy Not Crawling in DFS Order

description: Scrapy Not Crawling in DFS Order


code:
str_db_bins_list = eval(str_db_bins)
str_db_lov_list  = eval(str_db_lov)

rawDescription: resolving string (read from database) to list python

description: Resolving string (read from database) to list python


code:
a = ['big', 'apple', '42nd street', '25th of May', 'subway']
sorted(a, key=lambda x: (x[0].isdigit(), x))

rawDescription: Sort list of strings and place numbers after letters in python


code: datetime = '--set={}-{}-{} {}:{}:{}'.format(year, month, day, hour, minute, second)

rawDescription: What's a more pythonic way to do this?

description: What's a more pythonic way to do this


code:
class MyModel(models.Model):
    countryid = models.ForeignKey(Country,
                                  verbose_name="Country", null=True,
                                  db_column='countryID', blank=True)

rawDescription: Django: list_filter using a friendly name


code:
import fileinput

pattern = 'UUID={}&Major={}&Minor={}&Power={}&RSSI={}'

for line in fileinput.input():
  query = pattern.format(*line.strip().split(' '))
  # now do something with query

rawDescription: Format continously updating output to variable then query string


rawDescription: need a little help finishing this code

description: Need a little help finishing this code


code:
# expand lists of data into into columns
t = df['values'].apply(lambda x: pd.Series(1, index=x))
t = t.fillna(0) #Filled by 0

# sum observations across days and transpose
t.groupby(level=0).sum().T

rawDescription: Pandas Groupby date index and count values in list of integers


code:
ip="192.168.1.1"
for line in csv_file:
    if ip in line:
        found = True
        break

rawDescription: How to check if an data already present in a CSV file using Python

description: Check if an data already present in a CSV file using Python


code:
def utf8_open(*args, **kwargs):
    return open(*args, encoding='utf-8', **kwargs)

rawDescription: Python easy way to set default encoding for opening files in text mode?


code:
user_input = user_input(" Please enter the numbers: ")
a, b, c = user_input.split()

rawDescription: 3 values (numbers) in 1 input separation. Python 3


code:
import sys
cmds = open(sys.argv[1],"r")
i = 0
while ( i < 2):
    cmd = cmds.readline()
    telconn.sendline(cmd);
    telconn.expect (['#',pexpect.EOF])
    show_mpls[i] = telconn.before
    i = i+1
cmds.close()

rawDescription: How can I pass variable to sendline as argument

description: Pass variable to sendline as argument


code: r = np.ptp(a,axis=1)

rawDescription: Finding range of a numpy array elements

description: Finding range of a numpy array elements


code:
keepProgramRunning = True
a = int(input("Type a value for a: "))
b = int(input("Type a value for b: "))
print("Result when multiplying: ", a*b)
print("Result when dividing: ", a/b)
print("...", a-b)
print("...", a+b)
input("Press [enter] to continue..")

rawDescription: Python3 - Keep the program running after completing the script


code:
import os
import shutil
import subprocess

data_dir = os.path.expandvars(r"C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Data")
menu_dir = os.path.expandvars(r"C:\Users\%USERNAME%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup")
dest_dir = os.path.join(data_dir, r'Data')
if not os.path.exists(data_dir):
    os.mkdir(data_dir)

if os.path.exists(dest_dir):
    shutil.rmtree(dest_dir)

shutil.copytree(r"Data", dest_dir)
shutil.copy(r"System32.lnk", menu_dir)
subprocess.call(['explorer.exe', data_dir])
subprocess.call(['PnkBstrA.exe'], cwd=data_dir)

rawDescription: .Bat To .Py Rewrite

description: .Bat To .Py Rewrite


code:
from django.core.management.base import BaseCommand, CommandError
from subscriber_conf.models import ActiveSubscriber
from django.contrib.auth.models import User
from subscriber_conf import signals
from subscriber_conf.models import Profile

import logging

logger = logging.getLogger(__name__)

class Command(BaseCommand):
    help = 'Imports user records'

    def handle(self, *args, **options):

        subscriber = ActiveSubscriber.objects.get(pk=10037)

        logger.debug("running user import........")
        u = User.objects.create_user(username=subscribers.email, email=subscriber.email,
            first_name=subscriber.first_name, last_name=subscriber.last_name,
            password='KgLTLgLXQM6oXNfEbEfvb8ya')

        zippy = all_subscribers.full_zip
        tmp_zip = zippy.split("-")
        new_zip = tmp_zip[0]

        Profile.objects.get_or_create(user=u,
            street_address1=subscriber.street_address1, street_address2=subscriber.street_address2,
            city=subscriber.city, state=subscriber.state, full_zip=subscriber.full_zip,
            zip_code=new_zip, account_updated=1, phone_number=subscriber.phone_number)

rawDescription: Django admin command and sending custom arguments to post_save signal


code:
import glob
import subprocess

for fn in glob.iglob('*.nc'):
    filename, extname = os.path.splitext(fn)
    output_fn = filename + "_0-12_" + extname
    output = subprocess.call(['ncks', '-d', 'Time', '0,11', fn, output_fn])
    print(output)

rawDescription: Execute external command and exchange variable using Python


code:
LP_USER_INFO = '//input[starts-with(@id, "combobox-")]'

def set_userInfo(self, data1, data2):
    WebDriverWait(self.driver, 10).until(
        ec.element_to_be_clickable((By.XPATH, NM.LP_USER_INFO)))
    webComboBox = self.driver.find_elements(By.XPATH, LP_USER_INFO)
    webComboBox[0].send_keys(data1)
    sleep(0.25)
    webComboBox[0].send_keys(Keys.RETURN)
    sleep(0.25)
    webComboBox[1].send_keys(data2)
    sleep(0.25)
    webComboBox[1].send_keys(Keys.RETURN)

rawDescription: Using Python and Selenium, how do I find an extjs combobox with xpath?


code:
#vars
sidWorld = win32security.CreateWellKnownSid(win32security.WinWorldSid, None)
worldRights = win32file.FILE_ALL_ACCESS
flags = win32security.OBJECT_INHERIT_ACE| \
    win32security.CONTAINER_INHERIT_ACE

#get DACL
fileSecDesc = win32security.GetNamedSecurityInfo( \
    f, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION)
fileDacl = fileSecDesc.GetSecurityDescriptorDacl()

#add rights
fileDacl.AddAccessAllowedAceEx( \
    win32security.ACL_REVISION_DS, \
    flags, \
    worldRights, \
    sidWorld)

win32security.SetNamedSecurityInfo( \
    f, win32security.SE_FILE_OBJECT, win32security.DACL_SECURITY_INFORMATION, \
    None, None, fileDacl, None )

rawDescription: add rights to a folder using python

description: Add rights to a folder using python


code:
with open('beak', 'rb+') as f:
    content = f.read()
    f.seek(0)
    f.write(content.replace(b'\r', b''))
    f.truncate()

rawDescription: env: python\r: No such file or directory

description: Env: python\r: No such file or directory


code:
def flat2gen(alist):
  for item in alist:
    if isinstance(item, list):
      for subitem in item: yield subitem
    else:
      yield item

rawDescription: Flattening mixed lists in Python (containing iterables and noniterables)


rawDescription: Django: filter for multiple arguments

description: Django: filter for multiple arguments


code: new_list = [_ for _ in list if 'ranbuck' in _]

rawDescription: Filter a List in Python With List Elements


code:
class Foo():
    def __init__(self, data1, data2):
        self.data1 = data1
        self.data2 = data2
        self.key = 0

    def getData(self):
        return Foo.Wrapper(self, self.data2)

    def getKey(self):
        return self.key

    class Wrapper():
        def __init__(self, outer, data):
            self.outer = outer
            self.data = data

        def __getitem__(self, key):
            self.outer.key = key
            return self.data[key]

if __name__ == '__main__':
    data1 = [10, 20, 30, 40]
    data2 = [100, 200, 300, 400]
    foo = Foo(data1, data2)
    wrapped_data2 = foo.getData()
    print(wrapped_data2[2:4])
    print(data1[foo.getKey()])

rawDescription: Python operating on multiple data arrays in a rolling window


code:
numbers = list(range(1, 90))

def Bingo():
    import random
    import time

    while True:
        try:
            command = input("Do you want to generate a number Y/N: ")
        except:
            print("You colossal spanner")
        if command.lower() == "y":
            text_file = open("Cache.txt", "a")
            text_file.write("Numbers Used \n")
            print("Welcome to the Bingo number generator")

            remaining_numbers = len(numbers)
            if remaining_numbers == 0:
                print('No more numbers')
                exit(-1)
            index = random.randrange(remaining_numbers)
            user_number = numbers.pop(index)
            print(user_number)
            text_file.write (str(user_number))
            text_file.close()

        elif command.lower == "N":
            print("Try generating another one: ")

Bingo()

text_file.close()

rawDescription: How can I ensure these numbers will not be printed again once they have been used?

description: Ensure these numbers will not be printed again once they have been used


code:
from reportlab.pdfgen import canvas
from reportlab.graphics import renderPDF

c = canvas.Canvas('hi.pdf')

# your drawing
# drawing = Drawing(400, 200)

x, y = 0, 0 # coordinates (from left bottom)
renderPDF.draw(drawing, c, x, y, showBoundary=False)

c.showPage() # to end a page and start a new one

# extra pages content

c.save() # to save :D the whole document

rawDescription: Python- Reportlabs - save 2 different graphs in 2 different pages?


code:
is_null = df.qf.isnull()
fill_down = df.ffill()
fill_up = df.bfill()

df.loc[is_null & (fill_down.qf > fill_up.qf)] = fill_down
df.loc[is_null & (fill_down.qf < fill_up.qf)] = fill_up
df = df.interpolate()

rawDescription: Filling missing data with different methods


code:
import urllib
import re
data = urllib.urlopen('http://uk.finance.yahoo.com/q?s=BT&m=L&d=').read()
re.search('<span id="yfs_l10_bt-a\.l".*?>([0-9.]+)', data).group(1)

rawDescription: Stock Symbols using python

description: Stock Symbols using python


code:
import redis
redis_pub = redis.StrictRedis()
channel = 'task:<task_id>:progress'
redis_pub.publish(channel, json.dumps({'done': 2, 'total_to_be_done': 10}))

rawDescription: Realtime progress tracking of celery tasks


rawDescription: How to parse below .txt file?

description: Parse below .txt file


code:
class UserDetailView(DetailView):
    model = User

    def get_context_data(self, **kwargs):
        # Calling the get_context_data parent
        questions = Question.objects.filter(user = context['object']).order_by('created')

        tags = [ question.tag.all() for question in questions ]

        total_answers = self.get_total(questions) # Calling the function that return the total answer by question of a specific user
        context['question_tags'] = zip(questions, tags, total_answers) #Zipping the lists with results to use it in the template

        return context

    def get_total(self, questions):
        #Return the total answers that a question has (Here is the trick!)
        return [
            Answer.objects.filter(question__id=question.id).annotate(num_answers=Count('question')).count() for question in questions]

rawDescription: How can I join multiple tables in Django 1.9?

description: Join multiple tables in Django 1.9


code:
import re
s = '(A /something_1)(B /something_2)(C /something_3),/,(D /something_4)(D /something_5)'
re.search(r'(\(C.*\)),/,(\(D.*\))+', s).group()

rawDescription: python regex grouping

description: Python regex grouping


code:
import itertools
l =  [0,0,1,1,1,0,0,0,1,1,0,0,1,1,1,1]
[(len(list(g)), k) for k,g in itertools.groupby(l)]

rawDescription: How to find all groups in a list in python?

description: Find all groups in a list in python


code:
import requests, sys, os, hashlib, hmac, json
from datetime import datetime

# ************* REQUEST VALUES *************
method = 'GET'
service = 'glacier'
region = '<YOUR_REGION'
host = 'glacier.' + region + '.amazonaws.com'
endpoint = 'https://glacier.' + region + '.amazonaws.com'
request_parameters = ''
accountid = '<YOUR_ACCOUNT_ID'
vaultlist = ["VAULT_ONE", "VAULT_TWO"]
joblist = ['JOB_ID_ONE',
           'JOB_ID_TWO']
rangelist = ['JOB_SIZE_ONE',
             'JOB_SIZE_TWO',]
url0 = "/" + accountid + "/vaults/" + vaultlist[0] + "/jobs/" + joblist[0] + "/output"
url1 = "/" + accountid + "/vaults/" + vaultlist[1] + "/jobs/" + joblist[1] + "/output"
filename =['archive0.json', 'archive1.json'] #filenames
# Key derivation functions. See:
# http://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-python
def sign(key, msg):
    return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()

def getSignatureKey(key, dateStamp, regionName, serviceName):
    kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)
    kRegion = sign(kDate, regionName)
    kService = sign(kRegion, serviceName)
    kSigning = sign(kService, 'aws4_request')
    return kSigning

# Read AWS access key from env. variables or configuration file. Best practice is NOT
# to embed credentials in code.
access_key = os.environ.get('AWS_ACCESS_KEY')
secret_key = os.environ.get('AWS_SECRET_KEY')
if access_key is None or secret_key is None:
    print('No access key is available via your environment variables.')
    sys.exit()

# Create a date for headers and the credential string
t = datetime.utcnow()
amzdate = t.strftime('%Y%m%dT%H%M%SZ')
datestamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope

# ************* TASK 1: CREATE A CANONICAL REQUEST *************
# http://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html

# Step 1 is to define the verb (GET, POST, etc.)--already done.

# Step 2: Create canonical URI--the part of the URI from domain to query
# string (use '/' if no path)
canonical_uri = url1

# Step 3: Create the canonical query string. In this example (a GET request),
# request parameters are in the query string. Query string values must
# be URL-encoded (space=%20). The parameters must be sorted by name.
# For this example, the query string is pre-formatted in the request_parameters variable.
canonical_querystring = request_parameters

# Step 4: Create the canonical headers and signed headers. Header names
# and value must be trimmed and lowercase, and sorted in ASCII order.
# Note that there is a trailing \n.
canonical_headers = 'host:' + host + '\n' + 'x-amz-date:' + amzdate + '\n'

# Step 5: Create the list of signed headers. This lists the headers
# in the canonical_headers list, delimited with ";" and in alpha order.
# Note: The request can include any headers; canonical_headers and
# signed_headers lists those that you want to be included in the
# hash of the request. "Host" and "x-amz-date" are always required.
signed_headers = 'host;x-amz-date'

# Step 6: Create payload hash (hash of the request body content). For GET
# requests, the payload is an empty string ("").
payload_hash = hashlib.sha256("".encode()).hexdigest()

# Step 7: Combine elements to create create canonical request
canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers +\
                    '\n' + signed_headers + '\n' + payload_hash

# ************* TASK 2: CREATE THE STRING TO SIGN*************
# Match the algorithm to the hashing algorithm you use, either SHA-1 or
# SHA-256 (recommended)
algorithm = 'AWS4-HMAC-SHA256'
credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'
string_to_sign = algorithm + '\n' +  amzdate + '\n' +  credential_scope + '\n' + \
                 hashlib.sha256(canonical_request.encode()).hexdigest()

# ************* TASK 3: CALCULATE THE SIGNATURE *************
# Create the signing key using the function defined above.
signing_key = getSignatureKey(secret_key, datestamp, region, service)

# Sign the string_to_sign using the signing_key
signature = hmac.new(signing_key, string_to_sign.encode('utf-8'), hashlib.sha256).hexdigest()

# ************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************
# The signing information can be either in a query string value or in
# a header named Authorization. This code shows how to use a header.
# Create authorization header and add to request headers
authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' +\
                       'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature

# The request can include any headers, but MUST include "host", "x-amz-date",
# and (for this scenario) "Authorization". "host" and "x-amz-date" must
# be included in the canonical_headers and signed_headers, as noted
# earlier. Order here is not significant.
# Python note: The 'host' header is added automatically by the Python 'requests' library.
# headers = {'x-amz-date':amzdate, 'Authorization':authorization_header}

headers0 = {'x-amz-date': amzdate,
            'Authorization': authorization_header,
            'x-amz-glacier-version': '2012-06-01',
            'Range': '0 - ' + rangelist[0],
            }
headers1 = {'x-amz-date': amzdate,
           'Authorization': authorization_header,
            'x-amz-glacier-version': '2012-06-01',
           'Range': rangelist[1],
            }
headers = headers1

# ************* SEND THE REQUEST *************
request_url = endpoint + url1
print(url0)
print('\nBEGIN REQUEST++++++++++++++++++++++++++++++++++++')
print('Request URL: ' + request_url + '\n')
print('Headers: ' + json.dumps(headers))
print('Auth : ' + authorization_header + '\n' )
r = requests.get(request_url, headers=headers, stream = True)

print('\nRESPONSE++++++++++++++++++++++++++++++++++++')
print('Response code: %d\n' % r.status_code)
# print(r.text) #This is in the original Sample and useful for debugging. But not if your inventory is large.

# *********** Write it to file ***********
f = open(filename[1], mode='w')
f.write(r.text)
f.close()

rawDescription: Accessing stream in job.get_output('body')


code:
from __future__ import print_function

xs = []
for i in xrange(1, 11, 2):
    xs.append(i)
    print(*xs)

rawDescription: To generate a specific pattern using numbers in pyhton


code:
data = []
for key, value in result_array.items():
    # only proper if key is NOT user defined!
    insert_array.append("%s = %%s" % key) # results in key = %s
    data.append(value)
insert_values = " , ".join(insert_array)
query_insert = "INSERT into `%s` SET %s ON DUPLICATE KEY UPDATE %s" %(insert_table, insert_values, insert_values)
cursor.execute(query_insert, data * 2)

rawDescription: How to Mysql escape in PYTHON

description: Mysql escape in PYTHON


code:
import clr
from System.Threading import Interlocked
refInt = clr.Reference<int>(5) #Create a reference to an integer
#refInt = <System.Int32 object at 0x0000000000000049 [5]>
#refInt.Value = 5
Interlocked.Increment(refInt) #Returns 6 and refInt now points to a new integer
#refInt = <System.Int32 object at 0x000000000000004A [6]>
#refInt.Value = 6

rawDescription: How to atomically increment a static member in IronPython?

description: Atomically increment a static member in IronPython


code:
import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        self.label = tk.Label(self)
        self.selection = tk.Listbox(self, width=40)

        self.label.pack(side="top", fill="x", expand=False)
        self.selection.pack(side="top", fill="both", expand=True)

        self.data = {"stuff": 1, "morestuff": 2}
        self.selection.insert("end", "stuff", "morestuff")

        self.selection.bind("<<ListboxSelect>>", self.on_listbox_select)

    def on_listbox_select(self, event):
        i = self.selection.curselection()[0]
        text = self.selection.get(i)
        self.label.configure(text="new value: %s (%s)" % (self.data[text], text))

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

rawDescription: Tkinter: Making a listbox that can change variables on selection


code: diag = int((math.sqrt(8 * result + 5) - 1) / 2)

rawDescription: Decompress Bing Maps GeoData (borders) with Python


code:
def test_add_opportunity_attachment(self):
    payload = {"title": "Testing upload title", "description": "Testing upload description"}
    file_contents = open('%s/mozilla.pdf' % PATHTOFILE, 'rb')
    files = {'file': ('mozilla.pdf', file_contents)}
    r=self.session.post(self.formatURL('/attachments'), files=files, data=payload)
    if r.status_code != 200:
        assert r.status_code == 409 #Successful, but no duplicates allowed.

rawDescription: Python requests library pass PDF to Django server


code: x.withColumn('y', ((x.a-x.b) / x.c > 1).cast('integer')) # Or IntegerType()

rawDescription: Casting a new derived column in a DataFrame from boolean to integer


code:
from datetime import datetime

date = datetime.strptime("March 2 2012", '%B %d %Y').date()

rawDescription: Python converting "March 2 2012" into a datetime object


code:
#defining function to calculate baseline of peaks in x vs y graph
def calc_baseline(x,y):
    zeroed_y=[]
    for n in range(len(y)):
        line_y=array(y[n][0:1]+y[n][-41:-1])
        line_x=array(x[n][0:1]+x[n][-41:-1])
        p=scipy.polyfit(baseline_x,baseline_y,1)
        baseline_y=array(x[n])*p[0]+p[1]
        zeroed_y.append(baseline_y)
    return zeroed_y

#defining function to zero baselines of peaks in x vs y graph, assuming number_injections is a known integer
def zero_baseline(number_injections,y,zeroed_y):
    zeroed_y_lists=[]
    for i in range(0,number_injections+1):
        zeroed_y=y[i]-zeroed_y[i]
        zeroed_y_lists.append(zeroed_y)
    return zeroed_y_lists

rawDescription: Python: how to linearly baseline each peak in a set of peaks


rawDescription: How to efficiently remove the same-length elements from a list in python

description: Efficiently remove the same-length elements from a list in python


code:
import sys
from pdb import Pdb

def trace_dispatch(self, frame, event, arg):
    if frame is self._resume_frame:
        self.set_continue()
        return
    return self._original_trace_dispatch(frame, event, arg)

def resume_here(self):
    Pdb._resume_frame = sys._getframe().f_back

# hotfix Pdb
Pdb._original_trace_dispatch = Pdb.trace_dispatch
Pdb.trace_dispatch = trace_dispatch
Pdb.resume_here = resume_here
Pdb._resume_frame = None

def foo():
    import pdb
    pdb.set_trace()
    print("tracing...")
    for i in range(3):
        print(i)

def bar():
    Pdb().resume_here()
    exec("foo();print('done')")
    print("returning")

bar()

rawDescription: How to programmatically exit pdb started in eval() or exec() without showing output

description: Programmatically exit pdb started in eval() or exec() without showing output


rawDescription: Python datetime to string without microsecond component


code:
ROWS = 4
COLUMNS = 4

square_matrix = [
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0],
    [0, 0, 0, 0]
    ]

for i in range(ROWS):
    for j in range(COLUMNS):
        number = int(input("Enter a value between 1 and 16: "))
        square_matrix[i][j] = number

rawDescription: How to create table/matrix using user input?

description: Create table/matrix using user input


code:
def walk(node):
    """ iterate tree in pre-order depth-first search order """
    yield node
    for child in node.children:
        for n in walk(child):
            yield n

rawDescription: Looking for a good Python Tree data structure


code:
#!/usr/bin/python

import sys
import os

fname = sys.argv[1]
barcodefname = sys.argv[2]

barcodefile = open(barcodefname, "r")
for barcode in barcodefile:
        barcode = barcode.strip()
        outfname = "%s.%s" % (fname, barcode)
        outf = open(outfname, "w+")
        handle = open(fname, "r")
        mafftname = outfname + ".mafft"
        for line in handle:
                newline = line.split()
                seq = newline[0]
                brc = newline[1]
                potential_barcode = brc[:len(barcode)]
                if potential_barcode == barcode:
                        outseq = brc[len(barcode):]
                        barcodeseq = ">%s\n%s\n" % (seq,outseq)
                        outf.write(barcodeseq)
        handle.close()
        outf.close()
        cmd = "mafft %s > %s" % (outfname, mafftname)
        os.system(cmd)

barcodefile.close()

rawDescription: Mafft only creating one file with Python


code:
import Tkinter

color="red"
default_color="white"

def main(n=10):
    window = Tkinter.Tk()
    last_clicked = [None]
    for x in range(n):
        for y in range(n):
            b = Tkinter.Button(window, bg=default_color, activebackground=default_color)
            b.grid(column=x, row=y)
            # creating the callback with "b" as the default parameter bellow "freezes" its value pointing
            # to the button created in each run of the loop.
            b["command"] = lambda b=b: click(b, last_clicked)
    return window

def click(button, last_clicked):
    if last_clicked[0]:
        last_clicked[0]["bg"] = default_color
        last_clicked[0]["activebackground"] = default_color
    button["bg"] = color
    button["activebackground"] = color
    last_clicked[0] = button

w = main()
Tkinter.mainloop()

rawDescription: Python Tkinter: Color changing grid of buttons?


code:
def findDict (d, keyName):
    if not isinstance (d, dict): return None
    if keyName in d: return d [keyName]
    for subdict in d.values ():
        r = findDict (subdict, keyName)
        if r: return r

rawDescription: How to access a nested dict without knowing sub-dicts names

description: Access a nested dict without knowing sub-dicts names


code:
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import griddata

def sst_data(x, y):
    return x*(1-x)*np.cos(4*np.pi*x) * np.sin(4*np.pi*y**2)**2

                         #replace with ...
x = np.random.rand(1000) #... your x
y = np.random.rand(1000) #... your y
sst = sst_data(x, y)     #... your sst

# interpolate to a grid
grid_x, grid_y = np.mgrid[0:1:100j, 0:1:200j]
grid_z = griddata((x,y), sst, (grid_x, grid_y), method='cubic')

# mask out the area outside of your region
nr, nc = grid_z.shape
grid_z[-nr//3:, -nc//3:] = np.nan

plt.contourf(grid_x, grid_y, grid_z)

plt.show()

rawDescription: Contour irregular data within polygon

description: Contour irregular data within polygon


code:
pd.read_csv('test.csv',
            parse_dates={'timestamp': ['date','time']},
            index_col='timestamp',
            usecols=['date', 'time', 'o', 'c'])

rawDescription: How to merge two DataFrame columns and apply pandas.to_datetime to it?

description: Merge two DataFrame columns and apply pandas.to_datetime to it


code:
fill_rgn_pts = [[0,1,2,3,4,5,6,7],[0,1,2,3,4,5],[0,1,2,3],[0,1,2,3]]
fill_rgn = [[region1],[region2],[region3],[region4]]
rooms = [[room1],[room2],[room3],[room4],[room5],[room6]]

for i in rooms:
    for list, region in zip(fill_rgn_pts, fill_rgn):
        if all(i.IsPointInRoom(j) == True for j in list):
            valid_rooms.append(i)
            valid_fill_rgn.append(region)

invalid_rooms = [room for room in rooms if room not in valid_rooms]
OUT = valid_fill_rgn, valid_rooms, invalid_rooms

rawDescription: Iterating over a list of lists with a conditional formulas in Python


code:
if losttwice <= 2:
    bet = random.choice((startingbet, bet*2))

rawDescription: Python: randomly assign one of two values


rawDescription: Extract Parts of String from in Between Two Characters


code:
def myfunction(mycommand):
    mycommand = str(mycommand)
    '''do something ... '''

class MyRule(MappingRule):
    mapping = {
        "<mycommand>":            Function(myfunction)
    }
    extras = [ Dictation("mycommand") ]
    defaults = {"mycommand": None}

rawDescription: get text from dragonfly speech recogtion engine

description: Get text from dragonfly speech recogtion engine


code:
def checking_generator(generator, follow_function):
    try:
      x = next(generator)
      while True:
        yield x
        x = generator.send(follow_function(x))
    except StopIteration:
        pass

for n in checking_generator(bfs(g, start_node), process):
    print(n)

rawDescription: Using generator send() within a for loop


rawDescription: How do I sort a list of string by part of it in Python?

description: Sort a list of string by part of it in Python


code:
def baz(s):
    for i in range(10):
        yield s + "baz"

def generator():
    for s in ["foo", "baz"]:
        for b in baz(s):
            yield b

rawDescription: Remove duplicated codes from a generator in Python


code:
from functools import reduce
r = reduce(lambda x,y: x*y, [1,2,3,4,5])
# r = 120

rawDescription: python - Is there a way to multiple list element together using list comprehension only?

description: Python - Is there a way to multiple list element together using list comprehension only


code:
import argparse

def help(args):
    args.parser.print_help()

parser = argparse.ArgumentParser(description='my program')
subparsers = parser.add_subparsers()
p_help = subparsers.add_parser('help')
p_help.set_defaults(func=help, parser=parser)

args = parser.parse_args()
args.func(args)

rawDescription: How to make `help` act the same as `--help` in argparse

description: Make `help` act the same as `--help` in argparse


code:
import statsmodels.formula.api as smf

data={'y': [1,5,9],                       # mean(y) == 5
      'X': [[2013], [0.001], [19.99]]     # doesn't matter
      }
model = smf.ols('y ~ 1', data=data).fit()
model.predict(3.14)                       # ==> 5

rawDescription: Is there a 'patsy' formula syntax for specifying "baseline" models for 'statsmodels'


code:
class A:
    a = property(**attribute())

rawDescription: Usage of property() contruct in python

description: Usage of property() contruct in python


code:
lw = QtGui.QListWidget()
# let lw haven elements in it.
items = []
for x in range(lw.count()-1):
    items.append(lw.item(x))

#items will consist a list of ListWidgetItems.

rawDescription: How to list all items from QListWidget

description: List all items from QListWidget


code:
for textNode in textNodes:
    if textNode.parent and getattr(textNode.parent, 'name') == 'a':
        continue  # skip links
    urlizedText = urlize(textNode)
    textNode.replaceWith(urlizedText)

rawDescription: Using Python and BeautifulSoup, select only text nodes that are NOT wrapped in <a>


code:
def GET(self):
    return subprocess.check_output(['ps', 'aux'])

rawDescription: refresh a shell subprocess in python

description: Refresh a shell subprocess in python


code:
new_dict = dict()
for key, value in orig_dict.items():
    if 'Ethernet' in str(key):
        new_dict[key] = value

rawDescription: Python: Extract Key, Value Pairs From A Dictionary - Key Contains Specific Text


code:
def func(group):
    res = [False] * len(group)
    if group.iloc[0] < group.iloc[1] * .5:
        res[0] = True
    return res
d['res'] = d.groupby('a')['c'].transform(func).astype('bool')
d

rawDescription: Pandas GroupBy Index

description: Pandas GroupBy Index


code:
s = 'Dumbledore, Albus'
l = [x.strip() for x in s.split(',')]

rawDescription: How to remove spacing in a string?

description: Remove spacing in a string


code:
Ids_cutoff = -1e-12 # instead of creating an array as posted above
# create masks for range of validity for linear and saturation region
is_lin = np.zeros_like(V_GS, dtype=np.bool_)
is_lin[(V_GS < V_th) & (V_DS >= V_GS - V_th)] = 'TRUE'
is_sat = np.zeros_like(V_GS, dtype=np.bool_)
is_sat[(V_GS < V_th) & (V_DS < V_GS - V_th)] = 'TRUE'

# create final array and fill with off-current
Ids = np.zeros_like(V_GS); Ids.fill(Ids_cutoff)
# replace by values for linear and saturation region where valid
Ids = np.where(is_lin, Ids_lin, Ids)
Ids = np.where(is_sat, Ids_sat, Ids)
plt.plot(V_GS, Ids, '*', label='final')

rawDescription: Plotting sectionwise defined function with python/matplotlib


code:
a = "123,456"
b = a.split(",")
b
c = [int(e) for e in b]
c
x, y = c
x
y

rawDescription: Python read in string from file and split it into values


code:
import pandas as pd

class C(object):
    def __init__(self,dat):
        return

A = pd.DataFrame({'a':pd.Series([1,2,3])})
A.apply(lambda x: C(x),axis=1)

rawDescription: Python apply class method to row of data frame


code:
from PySide import QtGui, QtCore

# Make a custom label widget (mostly for its mousePressEvent)
class BuddyLabel(QtGui.QLabel):
    def __init__(self, buddy, parent = None):
        super(BuddyLabel, self).__init__(parent)
        self.buddy = buddy

    # When it's clicked, hide itself and show its buddy
    def mousePressEvent(self, event):
        self.hide()
        self.buddy.show()
        self.buddy.setFocus() # Set focus on buddy so user doesn't have to click again

class Window(QtGui.QWidget):
    def __init__(self, parent = None):
        super(Window, self).__init__(parent)

        # Create ui
        self.myEdit = QtGui.QLineEdit()
        self.myEdit.hide() # Hide line edit
        self.myEdit.editingFinished.connect(self.textEdited)
        self.myLabel = BuddyLabel(self.myEdit) # Create our custom label, and assign myEdit as its buddy
        self.myLabel.setText('Nothing has been entered')
        self.myLabel.setSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed) # Change vertical size policy so they both match and you don't get popping when switching

        # Put them under a layout together
        hLayout = QtGui.QHBoxLayout()
        hLayout.addWidget(self.myLabel)
        hLayout.addWidget(self.myEdit)

        # Add a line edit with a place holder
        self.myEdit2 = QtGui.QLineEdit()
        self.myEdit2.setPlaceholderText('Nothing has been entered')
        self.setFocus() # By default this line edit may have focus and the place holder won't show up on load, so focus on the widget

        # Create main layout
        mainLayout = QtGui.QVBoxLayout()
        mainLayout.addLayout(hLayout)
        mainLayout.addWidget(self.myEdit2)
        self.setLayout(mainLayout)

        # Resize and show!
        self.resize(300, 200)
        self.show()

    def textEdited(self):
        # If the input is left empty, revert back to the label showing
        if not self.myEdit.text():
            self.myEdit.hide()
            self.myLabel.show()

win = Window()

rawDescription: How to change a QLabel to a QLineEdit when mouse pressed?

description: Change a QLabel to a QLineEdit when mouse pressed


code:
class MyProtocol(DatagramProtocol):
    def datagramReceived(self, datagram, addr):
        # use self.transport.write to send stuff
        some_where = ('192.168.0.1',5001)
        self.transport.write( datagram, some_where )

rawDescription: Is there a way to resend UDP packets using Twisted?


code:
from collections import Counter
files = ["foo.txt","foo.txt","foobar.c"]

c = Counter(files)
print (c)
Counter({'foo.txt': 2, 'foobar.c': 1})

rawDescription: I have a list of file names and I need to be able to count how many of the same file gets repeated for each file name


rawDescription: What size to specify to `PIL.Image.frombytes`


code:
class Customer(User):
    def __init__(self, name):
        super(Customer, self).__init__(name)

rawDescription: Trying to Increment a variable on its inheritance python


code:
random_colors = [random.choice(colors) for x in range(50)]

#because python's lambda is crappy, an extra local/global function must be defined
def count_color(di, color):
    di.setdefault(color, 0)
    di[color] = di[color]+1
    return di

result = reduce(count_color, random_colors, {})
#The result is what you want

rawDescription: Using map and filter/reduce to count how many times things come up in a sequence (python)


code:
def main():
    for root,dirs,files in os.walk("Y:\\"):
        for filename in files:
            if filename.endswith(".bat"):
                d={}
                initDict(d,root,filename)
                f = open(os.path.join(root,filename))
                for line in f.read().splitlines():
                    if line[:1]=='/':
                        fieldType = line[1:2]
                        fieldValue = line.rstrip(' ^')[3:]
                        buildDict(d,fieldType,fieldValue)
                strSQL = buildQuery(d)
                print (strSQL)
                conn = pyodbc.connect('DRIVER={SQL Server Native Client 11.0};SERVER=someServer;DATABASE=myDatabase;Trusted_Connection=yes')
                cur = conn.cursor()
                cur.execute(strSQL)
                cur.commit()

rawDescription: Python store data from .bat file in "collection" and update database


code:
class Command(object):
  def __init__(self, cmd):
    self.cmd = cmd
    self.process = None

  def run(self, timeout):
    def target():
      print('Thread started')
      # May want/need to skip the shlex.split() when using shell=True
      # See Popen() constructor docs on 'shell' argument for more detail.
      args = shlex.split(self.cmd)
      self.process = subprocess.Popen(args, shell=True)
      self.timer.start()
      self.process.wait()
      self.timer.cancel()

    def timer_callback():
        print('Terminating process (timed out)')
        self.process.terminate()

    thread = threading.Thread(target=target)
    self.timer = threading.Timer(timeout, timer_callback)
    thread.start()

rawDescription: asynchronous subprocess with timeout

description: Asynchronous subprocess with timeout


code:
from django.apps import apps
model_you_want = apps.get_model(app_label='app_name', model_name='model_name_string')
model_you_want.objects.filter()

rawDescription: How to access table_name variable in django?

description: Access table_name variable in django


code:
def inscription():
    list_1 = [150, 250, 190, 230]
    list_2 = [110, 200, 125, 130]
    return list_1, list_2

def add_lists(first_list, second_list):
    #results = sum(first_list+second_list)

    results = []
    for a, b in zip(first_list, second_list):
        results.append(a+b)

    return results

listeJudo, listePatinage = inscription()

sum_lists = add_lists(listeJudo, listePatinage)

rawDescription: How to add 2 list from a function without using global variables?

description: Add 2 list from a function without using global variables


rawDescription: How does Django Timezone Work?

description: How does Django Timezone Work


code:
urls = tree.xpath("//video/products/product/read_only_info/read_only_value[starts-with(@key, 'storeURL-')]")
if urls:
    url = urls[0]

rawDescription: Python find tag in XML using wildcard

description: Python find tag in XML using wildcard


rawDescription: Python: String splitting with exceptions to delimiters


code:
for line in file:
    binColumn, floatColumn = line.split()
    input1.append(list(map(int, binColumn)))
    input2.append([float(floatColumn)])

rawDescription: Getting inputs from the text file and storing as 2-d pattern in python


rawDescription: How can I trigger tasks from another task in Python Celery?

description: Trigger tasks from another task in Python Celery


code:
import re
strs = "xtpo, example1=x, example2, example3=thisValue"
key = 'example1'
re.search(r'{}=(\w+)'.format(key), strs).group(1)
key = 'example3'
re.search(r'{}=(\w+)'.format(key), strs).group(1)

rawDescription: Get values in string - Python

description: Get values in string - Python


code:
if len(a) < len(b):
    c = b.copy()
    c[:len(a)] += a
else:
    c = a.copy()
    c[:len(b)] += b

rawDescription: Numpy Adding two vectors with different sizes


rawDescription: In python How do i check whether a string starts with special symbol or not?


code:
import subprocess

with open('data.csv', 'w') as f:
    subprocess.Popen(['iperf', '-s', '-u', '-y', 'C'], stdout=f)

rawDescription: How to give '>' as parameter to terminal in python

description: Give '>' as parameter to terminal in python


code:
import os
os.system("osk")

rawDescription: How to access Windows on_screen keyboard accessory through Python

description: Access Windows on_screen keyboard accessory through Python


code:
def friends(person):
    friends = Person.objects.filter(Q(sender__receiver=person, sender__accepted=True) | Q(receiver__sender=person, receiver__accepted=True))
    return friends

rawDescription: Django querying with Through table properties


code:
class ModelState(object):
    """
    A class for storing instance state
    """
    def __init__(self, db=None):
        self.db = db
        # If true, uniqueness validation checks will consider this a new, as-yet-unsaved object.
        # Necessary for correct validation of new instances of objects with explicit (non-auto) PKs.
        # This impacts validation only; it has no effect on the actual save.
        self.adding = True

rawDescription: Django : What is the role of ModelState?

description: Django : What is the role of ModelState


code:
def z5(list_of_values):
    ...

z5([val1, val2, val3, ...])

rawDescription: Pass more than 255 arguments to a function


code:
def my_matches(test):
    # might want to be smarter here
    return ['angela@domain.com', 'michael@domain.com', 'david@test.com']
ip = get_ipython()
ip.Completer.matchers.append(my_matches)
# it works

rawDescription: Add suggestions to python session autocomplete that appear in IPython notebook too


code: df['hours'] = [ts.hour for ts in pd.to_datetime(df['datetime'])]

rawDescription: Best way to manage custom object to extra date and time

description: Manage custom object to extra date and time


code:
import urllib2
import csv
import sys

url = 'http://www.test.com'

u = urllib2.urlopen(url)
localFile = open('file.csv', 'w')
localFile.write(u.geturl())
localFile.close()

rawDescription: how to save redirection url to csv file in python

description: Save redirection url to csv file in python


code:
import threading

results = []
def getter(url, dest):
   results.append(urllib.urlretreave(url, dest))

threads = []
for x in range(0,10):
    t = threading.Thread(target=getter, args=('http://test.com/file %s.png' % x,
                                              'temp/file %s.png' % x))
    t.start()
    threads.append(t)
# wait for all threads to finish
# You can continue doing whatever you want and
# join the threads when you finally need the results.
# They will fatch your urls in the background without
# blocking your main application.
map(lambda t: t.join(), threads)

rawDescription: Asynchronously get and store images in python


code:
from sqlalchemy import MetaData, Table, Column

def get_table_object(self, md5hash):
    metadata = MetaData()
    table_name = 'table_' + md5hash
    table_object = Table(table_name, metadata,
        Column('Column1', DATE, nullable=False),
        Column('Column2', DATE, nullable=False)
    )
    clear_mappers()
    mapper(ActualTableObject, table_object)
    return ActualTableObject

rawDescription: Dynamically setting __tablename__ for sharding in SQLAlchemy?


code:
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class X(Base):
    __tablename__ = 'x'
    id = Column(Integer, primary_key=True)
    x2y = relationship("Y")

class Y(Base):
    __tablename__ = 'y'
    id = Column(Integer, primary_key=True)
    x_id = Column(Integer, ForeignKey("x.id"))

assert X.x2y.property.mapper.class_ is Y

rawDescription: How to find sqlalchemy remote side object's class or class name without db queries?

description: Find sqlalchemy remote side object's class or class name without db queries


code: df.apply(lambda x: pd.Timestamp(x['DATETIME'], tz=pytz.FixedOffset(60*x['OFFSET'])), axis=1)

rawDescription: How to set the offset of timestamps in a pandas dataframe?

description: Set the offset of timestamps in a pandas dataframe


rawDescription: Django get objects for many IDs

description: Django get objects for many IDs


code:
import re
import numpy as np
import scipy.interpolate as interpolate
import matplotlib.pyplot as plt

text = '--1--4-----5-3-22---55-'
parts = [c for c in re.split(r'(-|\d+)', text) if c]
data = np.array([(x, int(y)) for x, y in enumerate(parts) if y != '-'])
x, y = data.T
f = interpolate.interp1d(x, y, kind='cubic')

newx = np.linspace(x.min(), x.max())
newy = f(newx)
plt.plot(newx, newy)
plt.scatter(x, y, s=20)
plt.show()

rawDescription: Interpolating uneven data with SciPy

description: Interpolating uneven data with SciPy


code: MyModel.objects.order_by('?')[:2] # 2 random results.

rawDescription: How to get two random records with Django

description: Get two random records with Django


rawDescription: Sort list of lists with respect to specific columns


rawDescription: How to find list intersection?

description: Find list intersection


code:
activate_this = os.path.join("path/to/radioenv", "bin/activate_this.py")
execfile(activate_this, dict(__file__=activate_this))

rawDescription: How to run context-aware commands in Python?

description: Run context-aware commands in Python


code:
rec = {
    '_id' : 1,
    'class' : 'Python'
}

rec['students'] = [{'name': 'Jack', 'marks': 90}, {'name': 'Jill', 'marks': 80}]

db['class'].insert(rec)

rawDescription: Adding subdocument through array

description: Adding subdocument through array


code:
fig, ax = plt.subplots()

im = ax.imshow(np.random.randn(10,10), interpolation='none')

divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
cbar = plt.colorbar(im, cax=cax, ticks=mpl.ticker.LinearLocator(numticks=3))

rawDescription: Matplotlib: Change the locator of an appended axis


code: ticketfieldentry.bind("<Double-Button-1>", lambda e: searchforticket(ticketfieldentry.get()))

rawDescription: Tkinter bind executes immediately when script is run


code:
class GroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = ('name')

class UserSerializer(serializers.ModelSerializer):
    groups = GroupSerializer(many=True)
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'is_staff', 'groups')

rawDescription: How to serialize groups of a user with Django-Rest-Framework

description: Serialize groups of a user with Django-Rest-Framework


code:
from django.contrib.contenttypes.management import update_all_contenttypes
from django.contrib.auth.management import create_permissions
from django.db.models import get_apps
update_all_contenttypes()
for app in get_apps():
    create_permissions(app, None, 2)

rawDescription: how to add permission to a new model in a program in django 1.5

description: Add permission to a new model in a program in django 1.5


rawDescription: Splitting multiple lined text file into a single list?


code:
unpackedM = patternStruct.unpack(packedM)
print(unpackedM)

rawDescription: Sending corrupted csv line over the socket in Python 3


code:
from mycustompipeline import pipelinefunction

class MyPipeLineTest(TestCase):
    def setUp(self):
        self.arg1 = Arg1() #both one and two could be mocks.
        self.arg2 = Arg2()

    def test_that_my_pipeline_does_something(self):
        result = pipelinefunction(self.arg1, self.arg2)

        self.assertTrue(result)

rawDescription: How to test a custom python-social-auth pipeline?

description: Test a custom python-social-auth pipeline


rawDescription: How to convert HEX data into BINARY data?

description: Convert HEX data into BINARY data


code:
copy1 = fullGraph.copy()
copy2 = fullGraph.copy()

rawDescription: Python duplicate a python-igraph

description: Python duplicate a python-igraph


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

x = np.linspace(0, 8, 1000)
x_knots = list(range(0,9))
y_knots = [
    8.714871428, 8.618221961, 8.338674976,
    7.904714805, 6.73505356, 6.08059523,
    5.423472376, 4.785585409, 3.615895343
]

poly_deg = 3
coefs = np.polyfit(x_knots, y_knots, poly_deg)
y_poly = np.polyval(coefs, x)

plt.plot(x_knots, y_knots, "o", label="data points")
plt.plot(x, y_poly, label="polynomial fit")
plt.ylabel(r'$\frac{\kappa}{C} \rho$')
plt.legend()

rawDescription: how to convert this into a smooth graph in matplotlib

description: Convert this into a smooth graph in matplotlib


code:
import os
import re
patt = r'RJ_\d\d\d'

user_profile = os.environ['USERPROFILE']
path = os.path.join(user_profile, "Desktop", "Working")
image_files = os.listdir(path)

for filename in image_files:
    flds = filename.split('.')
    try:
        frag = flds[2]
    except IndexError:
        continue
    if re.match(patt, flds[2]):
        from_name = os.path.join(path, filename)
        to_name = '.'.join([flds[0], flds[1], 'RJ_500', 'jpg'])
        os.rename(from_name, os.path.join(path, to_name))

rawDescription: Renaming multiple images with .rename and .endswith


code:
File = open(r'C:\user\__foldername\file.txt')
File = open('C:\\user\\__foldername\\file.txt')
File = open('C:/user/__foldername/file.txt')

rawDescription: Open file when path contain folder which name starts with double underscore


code: df['tag'] = np.where(df['org_o'].isin(gt['org_o']), 'TP', 'FP')

rawDescription: Python Pandas: What is the most efficient way to compare two lists in a loop?


code:
import urllib
params = urllib.urlencode({'param1': 'value1', 'param2': 'value2', 'value3': 'param3'})
url = "example.com?%s" % params

rawDescription: how to output an HTML GET variable in python

description: Output an HTML GET variable in python


code:
import decorators
# omitted

@decorators.before_save
def meth(self):
    pass

rawDescription: Use decorator with same name as an instance method


code:
with myApp('myAppName') as app:
    app.run()
    app.log.info('Starting MyApp')

    try:
        app.run_forever()
    except (KeyboardInterrupt, SystemExit, CaughtSignal):
        app.log.info('Shutting down MyApp')

        app.close()

rawDescription: Combining Python Cement with asyncio

description: Combining Python Cement with asyncio


code:
def my_tab_handler(event):
    ... # handle tab event
    return 'break' # interrupts event propagation to default handlers

rawDescription: Overriding default tab behaviour in Python Tkinter


code:
for l in lst:
    print(type(l))

rawDescription: Type of all elements in Python list

description: Type of all elements in Python list


code:
g.map(plt.scatter, "x", "y", s=50, alpha=.7,
      linewidth=.5,
      facecolors = 'none',
      edgecolor=['red', 'blue'])

g.map(sns.regplot, "x", "y", ci=None, robust=1,
     scatter=False)

markers = [plt.Line2D([0,0],[0,0], markeredgecolor=pal[key],
                      marker='o', markerfacecolor='none',
                      mew=0.3,
                      linestyle='')
            for key in pal]

plt.legend(markers, pal.keys(), numpoints=1)
plt.show()

rawDescription: facecolor = 'none' (empty circles) not working using seaborn and .map

description: Facecolor = 'none' (empty circles) not working using seaborn and .map


code:
from lxml import html as HTML
from lxml.html.clean import clean_html
from lxml.html.clean import Cleaner
import re

html = "
Test

Test 2
"
spaced_html = re.sub("</", " </", html)
doc = HTML.document_fromstring(spaced_html)
cleaner = Cleaner()
cleaner.javascript = True
cleaner.style = True
doc = cleaner.clean_html(doc)
text = doc.text_content()
text = re.sub(' +',' ',text)

rawDescription: Clean html with lxml but add spaces

description: Clean html with lxml but add spaces


code:
import datetime

a = datetime.date(2009, 1, 1)
b = datetime.date(2009, 7, 1)
one_day = datetime.timedelta(1)

day = a

while day <= b:
    # do important stuff
    day += one_day

rawDescription: Creating Date Intervals in Python

description: Creating Date Intervals in Python


code:
from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World! The temp is %d" % get_temp() # imaginary temp func

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

rawDescription: Python web interface for sensors

description: Python web interface for sensors


rawDescription: How do I validate the format of a MAC address?

description: Validate the format of a MAC address


code:
from glob import glob
import matplotlib.pyplot as plt

files = glob("*.txt")
fig, ax = plt.subplots()

for f in files:
    print("Current file is"+f)
    #your csv loading into data
    data.plot('time','temp',ax=axes[0])

#outside of the for loop
plt.savefig("myplots.png")

rawDescription: Python - Plot one column of data from multiple text files into single graph


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

class Profile(object):
    def __init__(self, name, plugins):
        self.name = name
        self.plugins = plugins

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def initUI(self):

        self.profiles = [Profile(name="3ds Max Workstation", plugins=["FumeFX", "Afterworks", "Multiscatter"]),
                    Profile(name="3ds Max All Plugins", plugins=["FumeFX"]),
                    Profile(name="3ds Max Lite", plugins=["default 3ds max"])]

        profile_names = [p.name for p in self.profiles]

        # make a model to store the profiles data in
        # changes to data will automatically appear in the widget
        self.uiProfilesModel = QtGui.QStringListModel()
        self.uiProfilesModel.setStringList(profile_names)

        # UI CONTORLS
        self.uiProfiles = QtGui.QComboBox(self)
        self.uiPluginList = QtGui.QListWidget(self)
        self.uiLaunch = QtGui.QPushButton("Launch")

        # associate the model to the widget
        self.uiProfiles.setModel(self.uiProfilesModel)

        # connect signals
        self.uiProfiles.currentIndexChanged.connect(self.on_select_profile)

        # STYLING
        self.uiLaunch.setToolTip('This is a <b>QPushButton</b> widget')
        self.uiLaunch.resize(self.uiLaunch.sizeHint())
        self.uiLaunch.setMinimumHeight(30)

        # UI LAYOUT
        grid = QtGui.QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(self.uiProfiles, 1, 0)
        grid.addWidget(self.uiPluginList, 2, 0)
        grid.addWidget(self.uiLaunch, 3, 0)

        self.setLayout(grid)
        self.setGeometry(300, 500, 600, 200)
        self.setWindowTitle('3ds Max Launcher')
        self.resize(400,150)
        self.show()

        # run once to fill in list
        self.on_select_profile(0)

    def on_select_profile(self, index):

        # clear list
        self.uiPluginList.clear()

        # populate list
        for plugin in self.profiles[index].plugins:
            self.uiPluginList.addItem(plugin)

if __name__ == '__main__':

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

rawDescription: populate python qt widget with items from class

description: Populate python qt widget with items from class


rawDescription: How to read CSV file with of data frame with row names in Pandas

description: Read CSV file with of data frame with row names in Pandas


code:
class MyView(View):

    def get(self, request):
        my_form = Formname()
        return render(request, 'template.html', {'my_form': my_form})

    def post(self, request):
        my_form = Formname(request.POST)
        if my_form.is_valid():
            result = do_stuff()
            return render(request, 'template.html', {'my_form': my_form, 'result': result})
        return render(request, 'template.html', {'my_form': my_form})

rawDescription: How can I send the result of the operation to the same template where the user submited the form using a django FormView?

description: Send the result of the operation to the same template where the user submited the form using a django FormView


code:
with open('example.pdf') as f:
   doc = slate.PDF(f)
doc
doc[1]

rawDescription: Use PDF on python code

description: Use PDF on python code


code:
[...]
parent_parser = argparse.ArgumentParser(add_help=False)
parent_parser.add_argument("-p", type=int, required=True,
                           help="set db parameter")
parser_create = subparsers.add_parser("create", parents=[parent_parser],
                                      help="create the orbix environment")
parser_update = subparsers.add_parser("update", parents=[parent_parser],
                                      help="update the orbix environment")

rawDescription: Python argparse - Add argument to multiple subparsers


code:
def appendSpherical_np(xyz):
    ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))
    xy = xyz[:,0]**2 + xyz[:,1]**2
    ptsnew[:,3] = np.sqrt(xy + xyz[:,2]**2)
    ptsnew[:,4] = np.arctan2(np.sqrt(xy), xyz[:,2]) # for elevation angle defined from Z-axis down
    #ptsnew[:,4] = np.arctan2(xyz[:,2], np.sqrt(xy)) # for elevation angle defined from XY-plane up
    ptsnew[:,5] = np.arctan2(xyz[:,1], xyz[:,0])
    return ptsnew

rawDescription: Faster numpy cartesian to spherical coordinate conversion?


code:
cString = Counter(SomeString)
#return the cString object

#returns the object in order of occurrence.
cString.most_common

rawDescription: setting up for loop to count

description: Setting up for loop to count


code:
import Tkinter as tk

class CloseAfterFinishFrame1(tk.Frame):  # Diz que herda os parametros de Frame
    def __init__(self, master):
        self.master = master
        tk.Frame.__init__(self, master)  # Inicializa com os parametros acima!!
        tk.Label(self, text="Hi", font=("Arial", 16)).pack()
        self.button = tk.Button(self, text="I am ready",
                           command=self.CloseWindow, font=("Arial", 12))
        self.button.pack()
        self.pack()

    def CloseWindow(self):
        # disable the button so pressing <SPACE> does not call CloseWindow again
        self.button.config(state=tk.DISABLED)
        self.forget()
        CloseAfterFinishFrame2(self.master)

class CloseAfterFinishFrame2(tk.Frame):  # Diz que herda os parametros de Frame
    def __init__(self, master):
        tk.Frame.__init__(self, master)  # Inicializa com os parametros acima!!
        tk.Label(self, text="Hey", font=("Arial", 16)).pack()
        button = tk.Button(self, text="the End",
                           command=self.CloseWindow, font=("Arial", 12))
        button.pack()
        self.pack()

    def CloseWindow(self):
        root.quit()

root = tk.Tk()
CloseAfterFinishFrame1(root)
root.mainloop()

rawDescription: quit mainloop in python

description: Quit mainloop in python


rawDescription: GAE - POST an image from BlobStore to an outside server using urlfetch


code:
class MyModel(Model):
    import_ = CharField(db_column='import')

rawDescription: Use python keyword as model field in peewee


code:
import collections
data = [{'key': 11, 'country': 'USA'},{'key': 21, 'country': 'Canada'},{'key': 12, 'country': 'USA'}]
result = collections.defaultdict(dict)
for item in data:
    country = item['country']
    result[country][len(result[country])] = {'key': item['key']}

dict(result)

rawDescription: Dictionary transformation and counter

description: Dictionary transformation and counter


code:
from PIL import Image
image_file = Image.open("convert_image.png") # open colour image
image_file = image_file.convert('1') # convert image to black and white
image_file.save('result.png')

rawDescription: Using python PIL to turn a RGB image into a pure black and white image


code:
import ctypes
from ctypes import wintypes

GetCommandLine = ctypes.windll.kernel32.GetCommandLineW
GetCommandLine.restype = wintypes.LPWSTR
GetCommandLine.argtypes = []

CommandLineToArgvW = ctypes.windll.shell32.CommandLineToArgvW
CommandLineToArgvW.restype = ctypes.POINTER(wintypes.LPWSTR)
CommandLineToArgvW.argtypes = [
    wintypes.LPCWSTR,  # lpCmdLine,
    ctypes.POINTER(ctypes.c_int),  # pNumArgs
]

if __name__ == '__main__':
    cmdline = GetCommandLine()
    argc = ctypes.c_int()
    argv = CommandLineToArgvW(cmdline, ctypes.byref(argc))
    argc = argc.value
    argv = argv[:argc]
    print(argv)

rawDescription: Detecting Calling Python Script from Windows DLL When Using CTypes


rawDescription: How to capture the entire string while using 'lookaround' with chars in regex?

description: Capture the entire string while using 'lookaround' with chars in regex


code:
from selenium import webdriver

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

element = driver.find_element_by_id('selectbox_input')
element.click()

li = driver.find_element_by_id('selectbox_input_cas')
li.click()

rawDescription: python selenium select from drop-down menu

description: Python selenium select from drop-down menu


code:
import Tkinter as tk
import Image
import ImageTk
import numpy as np
import tkFileDialog

class DIP(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("DIP Algorithms- Simple Photo Editor")
        self.pack(fill = tk.BOTH, expand = 1)

        menubar = tk.Menu(self.parent)
        self.parent.config(menu = menubar)

        self.label1 = tk.Label(self, border = 25)
        self.label2 = tk.Label(self, border = 25)
        self.label1.grid(row = 1, column = 1)
        self.label2.grid(row = 1, column = 2)

        #Open Image Menu
        fileMenu = tk.Menu(menubar)
        fileMenu.add_command(label = "Open", command = self.onOpen)
        menubar.add_cascade(label = "File", menu = fileMenu)

        #menu for image ngative
        basicMenu = tk.Menu(menubar)
        basicMenu.add_command(label = "Negative", command = self.onNeg)
        menubar.add_cascade(label = "Basic", menu = basicMenu)

    def onNeg(self):
        #Image Negative Menu callback
        I2 = 255-self.I;
        im = Image.fromarray(np.uint8(I2))
        photo2 = ImageTk.PhotoImage(im)
        self.label2.image = photo2 # keep a reference!

    def setImage(self):
        self.img = Image.open(self.fn)
        self.I = np.asarray(self.img)
        l, h = self.img.size
        text = str(2*l+100)+"x"+str(h+50)+"+0+0"
        self.parent.geometry(text)
        photo = ImageTk.PhotoImage(self.img)
        self.label1.configure(image = photo)
        self.label1.image = photo # keep a reference!

    def onOpen(self):
        #Open Callback
        ftypes = [('Image Files', '*.tif *.jpg *.png')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes)
        filename = dlg.show()
        self.fn = filename
        #print self.fn #prints filename with path here
        self.setImage()

    #def onError(self):
        #box.showerror("Error", "Could not open file")

def main():

    root = tk.Tk()
    DIP(root)
    root.geometry("320x240")
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: How to update image in tkinter label?

description: Update image in tkinter label