code:
#-*- coding: utf-8 -*-
#!python

from ctypes import *
from ctypes.wintypes import *

# stick to unicode version
LPWSTR = POINTER(WCHAR)
HINTERNET = LPVOID

INTERNET_PER_CONN_FLAGS = 1
INTERNET_PER_CONN_AUTOCONFIG_URL = 4
INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = 5
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_SETTINGS_CHANGED = 39
INTERNET_OPTION_PER_CONNECTION_OPTION = 75

PROXY_TYPE_AUTO_PROXY_URL = 4

class INTERNET_PER_CONN_OPTION(Structure):
    class Value(Union):
        _fields_ = [
            ('dwValue', DWORD),
            ('pszValue', LPWSTR),
            ('ftValue', FILETIME),
        ]

    _fields_ = [
        ('dwOption', DWORD),
        ('Value', Value),
    ]

class INTERNET_PER_CONN_OPTION_LIST(Structure):
    _fields_ = [
        ('dwSize', DWORD),
        ('pszConnection', LPWSTR),
        ('dwOptionCount', DWORD),
        ('dwOptionError', DWORD),
        ('pOptions', POINTER(INTERNET_PER_CONN_OPTION)),
    ]

InternetSetOption = windll.wininet.InternetSetOptionW
InternetSetOption.argtypes = [HINTERNET, DWORD, LPVOID, DWORD]
InternetSetOption.restype  = BOOL

if __name__ == '__main__':
    proxy = create_unicode_buffer('http://127.0.0.1:8086/proxy.pac')
    List = INTERNET_PER_CONN_OPTION_LIST()
    Option = (INTERNET_PER_CONN_OPTION * 2)()
    nSize = c_ulong(sizeof(INTERNET_PER_CONN_OPTION_LIST))

    Option[0].dwOption = INTERNET_PER_CONN_AUTOCONFIG_URL
    Option[0].Value.pszValue = proxy
    Option[1].dwOption = INTERNET_PER_CONN_FLAGS
    Option[1].Value.dwValue = PROXY_TYPE_AUTO_PROXY_URL

    List.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST)
    List.pszConnection = None
    List.dwOptionCount = 2
    List.dwOptionError = 0
    List.pOptions = Option

    assert InternetSetOption(None, INTERNET_OPTION_PER_CONNECTION_OPTION, byref(List), nSize) == True
    assert InternetSetOption(None, INTERNET_OPTION_SETTINGS_CHANGED, None, 0) == True
    assert InternetSetOption(None, INTERNET_OPTION_REFRESH, None, 0) == True

rawDescription: How to use ctypes.windll.Wininet.InternetQueryOptionW in python

description: Use ctypes.windll.Wininet.InternetQueryOptionW in python


code:
m = re.search('<title>(.*?)</title>', html)
if m:
    title = m.group(1)

rawDescription: Python if-statement based on content of HTML title tag


code:
button_texture = pyglet.image.load('button.png')
button_sprite = pyglet.sprite.Sprite(button_texture, x=135, y=window.height-65)

def on_mouse_press(x, y, button, modifiers):
   if x > button_sprite.x and x < (button_sprite.x + button_sprite.width):
      if y > button_sprite.y and y < (button_sprite.y + button_sprite.height):
         run_program()

rawDescription: python pyglet on_mouse_press

description: Python pyglet on_mouse_press


code:
import socket
import errno

def create_sock_pair(port=0):
    """Create socket pair.

    If socket.socketpair isn't available, we emulate it.
    """
    # See if socketpair() is available.
    have_socketpair = hasattr(socket, 'socketpair')
    if have_socketpair:
        client_sock, srv_sock = socket.socketpair()
        return client_sock, srv_sock

    # Create a non-blocking temporary server socket
    temp_srv_sock = socket.socket()
    temp_srv_sock.setblocking(False)
    temp_srv_sock.bind(('', port))
    port = temp_srv_sock.getsockname()[1]
    temp_srv_sock.listen(1)

    # Create non-blocking client socket
    client_sock = socket.socket()
    client_sock.setblocking(False)
    try:
        client_sock.connect(('localhost', port))
    except socket.error as err:
        # EWOULDBLOCK is not an error, as the socket is non-blocking
        if err.errno != errno.EWOULDBLOCK:
            raise

    # Use select to wait for connect() to succeed.
    import select
    timeout = 1
    readable = select.select([temp_srv_sock], [], [], timeout)[0]
    if temp_srv_sock not in readable:
        raise Exception('Client socket not connected in {} second(s)'.format(timeout))
    srv_sock, _ = temp_srv_sock.accept()

    return client_sock, srv_sock

rawDescription: How to emulate socket.socketpair on Windows

description: Emulate socket.socketpair on Windows


code:
def addAction(self, action):
    # set the Choice in the cell
    index = self.list.InsertStringItem(sys.maxint, '')
    self.list.SetStringItem(index, self.columns['#'], str(index))
    self.list.SetStringItem(index, self.columns['Action'], '')
    self.list.SetStringItem(index, self.columns['Parameters'], '')

    item = self.list.GetItem(index, self.columns['Action'])
    choice = wx.Choice(self.list, -1, name=action.name,
             choices=[availableAction.name for availableAction in self.availableActions])
    choice.SetClientData(0, index)
    choice.Bind(wx.EVT_CHOICE, self.onActionChange)
    item.SetWindow(choice, expand=True)
    self.list.SetItem(item)

    # set the third column's widgets
    self.setItemParameters(index, action)

def onActionChange(self, event):
    action = copy.deepcopy(self.availableActionsDict[event.GetString()])
    self.setItemParameters(event.GetEventObject().GetClientData(0), action)

rawDescription: Using a choice widget with ultimatelistctrl (wxpython)


code:
import xml.etree.ElementTree as ET

tree = ET.parse( file )
root = tree.getroot()
description = root[0][1].text

rawDescription: Python GDAL/OGR - get KML headers

description: Python GDAL/OGR - get KML headers


code:
today = datetime.datetime.today()
Example.objects.filter(
    date__year=today.year,
    date__month=today.month,
    date__day=today.day
)

rawDescription: Django/Python - How to get current date at 00:00:00?


code:
import re
text = '\xa0SOURCE:\r\nHult International Business School\r\n\r\n\r\n\r\n\r\nSUBJECT: ENTREPRENEURSHIP (92%);'
re.search(r'SOURCE[\s]*[:]*[\s]*(\r\n|\r|\n)*[\[#x3000\]]*[A-Za-z \!\.\-]*', text)

rawDescription: Regex - match to obtain words before and after \r\n


code:
def test():
    """
    ..
    """
    import doctest
    doctest.testmod()

if __name__=="__main__":
    test()  # if the module is called as a script then run tests

rawDescription: Put python doctest at the end of the code file?


code:
X = [0.1*i for i in xrange(40)]
Y = [TotalEnergy_GW_onelevel(x) for x in X]
plot(X,Y)

rawDescription: define an integration function in python

description: Define an integration function in python


code:
l = list()
for k in [5,4,3,2,1,0]:
    l.append(x[:-k or None])

rawDescription: What value do I use in a slicing range to include the last value in a numpy array?


code:
req = urllib2.Request('http://www.yoururl.com')
res = opener.open(req)

rawDescription: Need suggestion hot to move urllib2.install_opener() to a different class


code:
PROJECT_APPS=(
    'appname',
)

rawDescription: Django, Jenkins and PyLint looking at everything


code:
re_lookup = {
    state: re.compile(r'\b%s\b' % state, re.I)
    for state in stateset
}

for sent in sentences:
    for state in stateset:
        if re.search(re_lookup[state], sent):
            sentstatedict[sent] = state
            break

rawDescription: How to efficiently loop regex searches from set python

description: Efficiently loop regex searches from set python


code:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages('myplot.pdf')

x = np.linspace(0, 10, 100)
y1 = np.exp(x)
y2 = np.log(x)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(x, y1, '-ro', markersize=5, label='y1')
ax1.set_ylim(-0.1, 1.1 * max(y1))
ax1.set_ylabel('y1', fontsize=20)
ax1.legend(loc='upper left')
ax1.grid(ls='dotted', c='k')
ax1.patch.set_facecolor('white')

ax2 = ax1.twinx()
ax2.grid(False)
ax2.plot(x, y2, 'b-', label='y2')
ax2.set_ylim(-0.1, 1.1 * max(y2))
ax2.set_ylabel('y2', fontsize=20)
ax2.legend(loc='upper right')
plt.xlim([-0.5, 1.05 * max(x)])
ax1.set_xlabel('x', fontsize=20)

#plt.show()

pp.savefig(fig)
pp.close()
plt.close(fig)

rawDescription: Main axis are not shown when using grid

description: Main axis are not shown when using grid


code:
if not n:
    no_repeats = len(word)/i
else:
    no_repeats = n

rawDescription: Purpose of assigning None to variables

description: Purpose of assigning None to variables


code:
import suds.transport.http
from suds.client import Client

trans = suds.transport.http.HttpAuthenticated(username=username,
                                              password=password)
__client = Client(url, transport=trans)
func = __client.service.__getattr__("ReceiveData")
argument = __client.factory.create('DataModelType')
argument["Key"] = "0001"

#getting internal soap class and extracting entire soap_object:
clientclass = func.clientclass({})
SoapClient = clientclass(func.client, func.method)
binding = func.method.binding.input
soap_xml = binding.get_message(func.method, [modelthings], {})

#fix anything what we want, that is representation of all envelope that should be sent
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentInfo="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'attachmentData="true"')
soap_xml.children[0].children[1].children[0].attributes.append(u'ignoreEmptyElements="true"')

#then prepare it as suds would do it:
SoapClient.last_sent(soap_xml)
plugins = PluginContainer(SoapClient.options.plugins)
plugins.message.marshalled(envelope=soap_xml.root())
if SoapClient.options.prettyxml:
    soap_xml = soap_xml.str()
else:
    soap_xml = soap_xml.plain()
soap_xml = soap_xml.encode('utf-8')
plugins.message.sending(envelope=soap_xml)
request = Request(SoapClient.location(), soap_xml)
request.headers = SoapClient.headers()
my_reply = SoapClient.options.transport.send(request)

ctx = plugins.message.received(reply=my_reply)
my_reply = ctx.reply
if SoapClient.options.retxml:
    answer = my_reply
else:
    answer = SoapClient.succeeded(binding, my_reply)

return answer

rawDescription: How to add attributes to SOAP envelope part, using suds?

description: Add attributes to SOAP envelope part, using suds


rawDescription: How to add two strings alternatively?

description: Add two strings alternatively


code:
with open('myfile.txt', 'wb') as f:
    np.savetxt(f, A, fmt='%-7.8f', delimiter=',')

rawDescription: savetxt & close file + python + numpy

description: Savetxt & close file + python + numpy


code:
parser = argparse.ArgumentParser(description="Auto-segments a text based on "
    "the TANGO algorithm (Rie Kubota Ando and Lillian Lee, 'Mostly-Unsupervised "
    "Statistical Segmentation of Japanese Kanji Sequences' (Natural Language "
    "Engineering, 9(2):127-149, 2003)).")

rawDescription: Wrapping lines in python: breaking on an argument string


code:
t_query = session.query(func.strftime('%Y-%m-%d', getattr(MyBaseClass, "period")),
                        func.sum(getattr(MyBaseClass, "foo")),
                        func.sum(getattr(MyBaseClass, "other_name") * getattr(MyBaseClass, "value_one"))
                        )

rawDescription: sqlalchemy with dynamic mapping and complex object querying

description: Sqlalchemy with dynamic mapping and complex object querying


code:
import os
import sys

BASE_PATH = '/my/const/path'

fullpath = os.path.join(BASE_PATH,sys.argv[1])

rawDescription: Have a python script always reference the same directory regardless of where it's run in the system


code:
with open('your_file', 'w') as f:
    f.write('Some text\n')

rawDescription: Python: How do I clear a .txt file with the open() function?


code:
import re

fileopen = open("test.c")

# Convert file to a string
source_code = ""
for var in fileopen:
    source_code += var

# Find the first comment from the source code
pattern = r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"'
var1 = re.search(pattern, source_code, re.DOTALL | re.MULTILINE).group() # first comment

var1 = unicode(var1, errors='ignore')
worksheet.write(i, 5, var1, cell_format)

rawDescription: How to dump the data from file to an excel sheet

description: Dump the data from file to an excel sheet


code:
def run(self):
    img_sky = ImageTk.PhotoImage(file="Images/night-sky.jpg")
    img_button = ImageTk.PhotoImage(file="button_instructions.png")
    self.canvas = Canvas(self.home, width=700, height=500)
    self.canvas.create_image(0, 0, image=img_sky)
    self.canvas.create_image(300, 200, image=img_button)
    self.canvas.pack()
    self.home.mainloop()

rawDescription: Image display issue

description: Image display issue


code:
def append(self, item):
    if item in self:
        print('This item is already in your list')
    else:
        return super(MyList, self).append(item)

rawDescription: Python: new class, inheriting and overriding


code:
# Get column indices corresponding to index2
col_idx = np.mod(np.arange(index1,index1-p,-1),p)

# Get all mat2 values with those column indices at kth row
mat2_val = mat2[k,col_idx]

# Mask of valid elements
mask = mat2_val > -1e10

# Set valid ones in mat1 with valid ones from mat2
# after scaling with mat2[k][index1]
mat1[k][mask] = mat2[k][index1]*mat2_val[mask]

rawDescription: python performance tips -- loop involving comparisons

description: Python performance tips -- loop involving comparisons


code:
#Headers as rows for now
df = pd.read_excel(xls_file,0, header=None, index_col=0)

#fill in Null values in "Headers"
df = df.fillna(method='ffill', axis=1)

#create multiindex column names
df.columns=pd.MultiIndex.from_arrays(df[:3].values, names=['top','mid','low'])

#Just name of index
df.index.name='Date'

#remove 3 rows which are already used as column names
df = df[pd.notnull(df.index)]

rawDescription: Parsing a Multi-Index Excel File in Pandas


code: l = list(iterable)

rawDescription: Convert Any Iterable to Array in Python

description: Convert Any Iterable to Array in Python


code:
doc = lh.parse("http://pastebin.com/raw.php?i=1WpFAfCt")
text = doc.xpath("//*[@id='bookmark_list']/*/div[3]/a/text()")
len(text) # => 40

rawDescription: Python: why does the following xpath returns empty list?


code:
edge, middle = '+', '|'
for i in range(5):
    edge += ' -- +'
    middle += '    |'
print(edge)
print(middle)
print(edge)

rawDescription: Iteration in python

description: Iteration in python


rawDescription: How to check for palindrome using Python logic

description: Check for palindrome using Python logic


code:
import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super(MyFrame,self).__init__(None, title="Frame", size=(100, 100))
        ##self.field = wx.TextCtrl(self, -1, "Text", (30, 7))
        self.field = wx.StaticText(self)

    def startIdle(self):
        self.counter = 0
        self.Bind(wx.EVT_IDLE, self.onIdle)

    def onIdle(self, evt):
        self.counter += 1
        ##self.field.SetValue(str(self.counter))
        self.field.SetLabel(str(self.counter))
        evt.RequestMore()

class Main(wx.App):
    def OnInit(self):
        self.frame = MyFrame()
        self.frame.Show()
        self.frame.startIdle()
        self.MainLoop()
        return True
Main()

rawDescription: wxPython memory leak with setValue

description: WxPython memory leak with setValue


code:
from selenium import webdriver
import time

browser=webdriver.Chrome()
browser.get('http://www.vliz.be/vmdcdata/mangroves/aphia.php?p=browser&id=235301&expand=true#ct')

while True:
      try:
          elem=browser.find_elements_by_xpath('.//*[@src="http://www.marinespecies.org/images/aphia/pnode.gif" or @src="http://www.marinespecies.org/images/aphia/plastnode.gif"]')[1]
          elem.click()
          time.sleep(2)
      except:
          break

content=browser.page_source

rawDescription: How to get data from the TreelView list

description: Get data from the TreelView list


code:
isinstance([0, 10, 20, 30], list)
isinstance(50, list)

rawDescription: python: how to identify if a variable is an array or a scalar

description: Python: how to identify if a variable is an array or a scalar


code:
class Record:
    def __init__(self,lines):
        self.record = {}
        self.__parse()

class CsvSet:
    def __init__(self,lines):
        self.records = []
        self.__parse()

rawDescription: Python list entries are overridden by last appended entry


code:
qry = (session.query(
                table.c.field1,
                table.c.field2,
                # #strftime* for year-month works on sqlite;
                # @todo: find proper function for mysql (as in the question)
                # Also it is not clear if only MONTH part is enough, so that
                # May-2001 and May-2009 can be joined, or YEAR-MONTH must be used
                func.strftime('%Y-%m', table.c.datestamp),
                func.count(),
                )
        # optionally check only last 2 month data (could have partial months)
        .filter(table.c.datestamp < datetime.date.today() - datetime.timedelta(60))
        .group_by(
                table.c.field1,
                table.c.field2,
                func.strftime('%Y-%m', table.c.datestamp),
                )
        # comment this line out to see all the groups
        .having(func.count()>1)
      )

rawDescription: SQLAlchemy: How to group by two fields and filter by date


code:
# A nice one liner (edited to remove square brackets)
my_dict.update((x, y*2) for x, y in my_dict.items())

rawDescription: Python: Perform an operation on each dictionary value


rawDescription: How do I filter ForeignKey choices in a Django ModelForm?

description: Filter ForeignKey choices in a Django ModelForm


code:
# somepackage.py

try:
  from lxml import etree
  print("running with lxml.etree")
except ImportError:
  try:
    # Python 2.5
    import xml.etree.cElementTree as etree
    print("running with cElementTree on Python 2.5+")
  except ImportError:
    try:
      # Python 2.5
      import xml.etree.ElementTree as etree
      print("running with ElementTree on Python 2.5+")
    except ImportError:
      try:
        # normal cElementTree install
        import cElementTree as etree
        print("running with cElementTree")
      except ImportError:
        try:
          # normal ElementTree install
          import elementtree.ElementTree as etree
          print("running with ElementTree")
        except ImportError:
          print("Failed to import ElementTree from any known place")

rawDescription: Python dependencies importing

description: Python dependencies importing


code:
class Node:
    def __init__(self):
        self.dist_ = []
        self.from_ = []

rt = []

rawDescription: Replicating struct in python

description: Replicating struct in python


code:
try:
    events = [event for event in events if event.key >= 273 and event.key <= 276]
except AttributeError:
    continue

rawDescription: Why do my keyboard events get halted by mouse movement?


code:
import win32api
fixed_file_info = win32api.GetFileVersionInfo(win32api.__file__, '\\')
fixed_file_info['FileVersionLS'] >> 16

rawDescription: Programmatically find the installed version of pywin32


code:
query = Model.all()
query_iterator = query.run(limit=5)
query.cursor()
list(query_iterator) # Exhaust iterator
query.cursor()

rawDescription: Cursor returns with fetch() but not run() on App Engine


code:
text='''

 This is some text,
 with some newlines \r
 and some \t tabs \t too;

 and a link too

I think we're done here

'''
response = scrapy.Selector(text=text)
response.xpath('//div[@class="d-grid-main"]')
div = response.xpath('//div[@class="d-grid-main"]')[0]

# you'll want to use relative XPath expressions, starting with "./"
div.xpath('.//p[@class="class-name"]/text()').extract()

# only leading and trailing whitespace is removed by strip()
map(unicode.strip, div.xpath('.//p[@class="class-name"]/text()').extract())

# normalize-space() will get you a single string on the whole element
div.xpath('normalize-space(.//p[@class="class-name"])').extract()

rawDescription: Strip \n \t \r in scrapy

description: Strip \n \t \r in scrapy


code:
import csv

data={}
with open('/tmp/text.txt') as fin:
    reader=csv.reader(fin, skipinitialspace=True, quotechar="'")
    for row in reader:
        data[row[0]]=row[1:]

print(data)
# {'Lisa plowed ': ['1A', 'field', 'field', 'field', 'field', 'field'], 'Tracy freed ': ['1A', 'animals', 'fish', 'slaves', 'slaves', 'slaves'], 'Paul alleged ': ['1A', 'truth', 'crime', 'facts', 'infidelity', 'incident'], 'John greased ': ['1A', 'axle', 'wheel', 'wheels', 'wheel', 'engine']}

rawDescription: Create a dictionary from a csv file in python 3


code: response.content_disposition = 'attachment; filename="my_filename.txt"'

rawDescription: How to set file name in response

description: Set file name in response


code:
humanTime = '2012/06/10T16:36:20.509Z'
datetime.datetime.strptime(humanTime[:19], "%Y/%m/%dT%H:%M:%S")

rawDescription: python datetime.strptime: ignore fraction of a second

description: Python datetime.strptime: ignore fraction of a second


rawDescription: Python encoding text from RSS using feedparser


code:
import numpy as np
from scipy.spatial import cKDTree

# convert inputs to numpy arrays
ilabels, ilocs = (np.array(vv) for vv in zip(*idealLoc.iteritems()))
rlocs = np.array(realLoc)

# construct a K-d tree that partitions the "ideal" points
tree = cKDTree(ilocs)

# query the tree with the real coordinates to find the nearest "ideal" neigbour
# for each "real" point
dist, idx = tree.query(rlocs, k=1)

# get the corresponding labels and coordinates
print(ilabels[idx])
# ['2' '4' '1' '5' '6' 'No_Data']

print(ilocs[idx])
# [[ 892 1152]
#  [ 969 1020]
#  [ 907 1026]
#  [ 949 1220]
#  [ 951 1404]
#  [   0    0]]

rawDescription: In python, what is a good way to match expected values to real values?


code:
f = open("test.txt","w")
f.write("Hello")

rawDescription: using pyserial flush method

description: Using pyserial flush method


code:
John = ['smith', 'brown', 'wilson']
Details = [{'age': 23, 'hometown': 'chicago'},{'age': 26, 'hometown': 'New York'}, {'age': 44, 'hometown': 'Boston'}]

combined = [dict(detail, John=surname) for detail, surname in zip(Details, John)]
# [{'hometown': 'chicago', 'age': 23, 'John': 'smith'}, {'hometown': 'New York', 'age': 26, 'John': 'brown'}, {'hometown': 'Boston', 'age': 44, 'John': 'wilson'}]

rawDescription: Adding a key to a list of dictionaries

description: Adding a key to a list of dictionaries


code:
cb = QComboBox()
cb.addItem("A", 4)
cb.addItem("B")
cb.setItemData(1, 1, Qt.UserRole)

# To get the data. or cb.itemData(cb.currentIndex(), Qt.UserRole)
cb.itemData(0, Qt.UserRole)

rawDescription: Order QComboBox items alphabetically regardless of index


code:
def main():
   run_wsgi_app(app2)

rawDescription: How do I actually use WSGI?

description: Actually use WSGI


code:
df
df["B"] = df["B"].str.replace("^and ","")
df

rawDescription: Pandas trim specific leading characters

description: Pandas trim specific leading characters


code:
count = ...
sql = "INSERT INTO ... VALUES(" + ",".join(count * ["?"]) + ")"
params = []
for i in ...:
    params += ['whatever']
cursor.execute(sql, params)

rawDescription: SQLite execute statement for variable-length rows


code:
def DollarFunc(x,pos=0):
    return "\${}K".format(x)

ax.xaxis.set_major_formatter(FuncFormatter(DollarFunc))

rawDescription: Seaborn Heatmap Colorbar Tick Label

description: Seaborn Heatmap Colorbar Tick Label


code:
from tkinter import *

master = Tk()
frame1 = Frame(master)
Label(frame1, text="First Name").grid(row=0)
Label(frame1, text="Last Name").grid(row=1)

e1 = Entry(frame1)
e2 = Entry(frame1)

e1.grid(row=0, column=1)
e2.grid(row=1, column=1)

frame1.pack()  # <------
mainloop()

rawDescription: cant place widget on frame tkinter

description: Cant place widget on frame tkinter


code:
def word_to_int(hex_str):
    value = int(hex_str, 16)
    if value > 127:
        value = value-256
    return value

rawDescription: How to convert hexadecimal word to signed integer in python 2-7?

description: Convert hexadecimal word to signed integer in python 2-7


code:
from getpass import getpass
from time import sleep
Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
# These next two lines aren't necessary - these variables are never used; you may want to read up about namespaces:  http://bytebaker.com/2008/07/30/python-namespaces/
#Username = ("")
#Password = ()
def LogIn():
    Database = open("C:\\Users\Dark Ariel7\\Desktop\\USB BAckup\\Scripts\\Database.txt", encoding='utf-8')
#   Removed the parentheses; they have no effect here.  Putting parens around lone statements doesn't have any effect in python.
    Data = Database.read()
#   These next two lines are pointless, because you subsequently overwrite the values you give these variables.  It looks like you're trying to "declare" variables, as you would in Java, but this isn't necessary in python.
#   Username = ("")
#   Password = ()
#   Changed this from "input" to "raw_input" because input does something else that you don't want.
    Username = raw_input("Username: ")
    Password = getpass(str("Password: "))
    LogIn= ",".join((Username,Password))
    if LogIn in Data:
        print("Welcome, " + Username)
#   Not sure why you want the script to sleep, but I assume you have your reasons?
        sleep(3)
#   no need to pass
#       pass
    else:
        print("Failed, Sucker!")
        sleep(5)
#   exit() isn't necessary - the function will end by itself.
#       exit()

LogIn()

rawDescription: txt file to dictionary and login implementation Python 3

description: Txt file to dictionary and login implementation Python 3


code:
def get_previous(object, date):
    """Returns the latest version of an object prior to the given date."""
    versions = reversion.get_for_object(object)
    versions = versions.filter(revision__date_created__lt=date)
    try:
        version = versions[0]
    except IndexError:
        raise Version.DoesNotExist
    else:
        return version

rawDescription: Previous version of a django-reversion controlled object


rawDescription: How to select first rows when column changes value in numpy.array

description: Select first rows when column changes value in numpy.array


rawDescription: Adding the values of a series to a dataframe


code:
#sorting
order = dict( enumerate(keys) )
direction = request.GET['sSortDir_0']
column = request.GET['iSortCol_0']
dirs = {'asc': '', 'desc': '-'}
if direction == 'asc' and column == '1':
    ordering = dirs[direction] + order[int(column)]
    objects = objects.order_by('liquorID__BrandName')
elif direction == 'desc' and column == '1':
    ordering = dirs[direction] + order[int(column)]
    objects = objects.order_by('-liquorID__BrandName')
else:
    ordering = dirs[direction] + order[int(column)]
    objects = objects.order_by(ordering)

rawDescription: Django how to order an object based on a related field


code:
ax.axis('auto')
ax.set_autoscale_on()

rawDescription: Re-adjusting (automatically) limits on plot in matplotlib


code:
def HTTPSProxyRequest(method, host, url, proxy, header=None, proxy_headers=None, port=443):
    https = http.client.HTTPSConnection(proxy[0], proxy[1])
    https.set_tunnel(host, port, headers=proxy_headers)
    https.connect()
    https.request(method, url, headers=header)
    response = https.getresponse()
    return response.read(), response.status

# calling the function
HTTPSProxyRequest('GET','google.com', '/index.html', ('myproxy.com',8080))

rawDescription: HTTPS requests are sent without headers with Python's Requests


code:
import ast
(options, args) = parser.parse_args()
myopt = ast.literal_eval(options.myopt)

rawDescription: Using optparse to read in a list from command line options


code: age = [x.replace(" ", "") for x in age]

rawDescription: Replacing white space inside a list of strings in python


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

# def discrete_cmap() is omitted here...

# some sample data
x = np.linspace(0,10,11)
y = np.linspace(0,10,11)
z = x+y

# setup a Normalization instance
norm = colors.Normalize(z.min(),z.max())

# define the colormap
cmap = discrete_cmap(4, 'cubehelix')

# Use the norm and cmap to define the edge colours
edgecols = cmap(norm(z))

# Use that with the `edgecolors` argument. Set c='None' to turn off the facecolor
plt.scatter(x,y, edgecolors=edgecols, c = 'None', marker='o', s=40 )

plt.show()

rawDescription: Is it possible to assign a colourmap for edgecolors in matplotlib?


code:
dictVar={'one':1,'two':2,'three':3}
listVar=dictVar.viewvalues()
listVar
dictVar['one']=100
listVar
dictVar['four']=4
listVar
list(listVar)==dictVar.values()

rawDescription: How to make live connection between two objects

description: Make live connection between two objects


code:
page = urllib2.urlopen( "http://securities.stanford.edu/1046/BWEN00_01" )
page.info().headers

rawDescription: python - A problem happen when I'm trying to fetch documents from a website

description: Python - A problem happen when I'm trying to fetch documents from a website


code:
rdd = sc.parallelize([(1,1,2),(2,2,3)])
rdd.map(set).flatMap(lambda x:x).collect()

rawDescription: Distinct Lists inside of RDD in Spark, not the whole RDD


code:
father_name = raw_input("Please enter your Father's Name: ")
mother_name = raw_input("Please enter your Mother's Name: ")

rawDescription: Trying to negate the end of the string

description: Trying to negate the end of the string


code:
import inspect

def foo(a, b, c=5):
    return a + b + c
def show_defaults(f):
    args, varargs, varkw, defaults = inspect.getargspec(f)
    if defaults:
        for arg, default in zip(args[-len(defaults):], defaults):
            print('{a} = {d}'.format(a=arg,d=default))

show_defaults(foo)
# c = 5

rawDescription: How to I determine the default value for a given function parameter at runtime?


rawDescription: Insert table into QTextEdit with PyQt4

description: Insert table into QTextEdit with PyQt4


code:
def ScaleRotateTranslate(image, angle, center = None, new_center = None, scale = None,expand=False):
    if center is None:
        return image.rotate(angle)
    angle = -angle/180.0*math.pi
    nx,ny = x,y = center
    sx=sy=1.0
    if new_center:
        (nx,ny) = new_center
    if scale:
        (sx,sy) = scale
    cosine = math.cos(angle)
    sine = math.sin(angle)
    a = cosine/sx
    b = sine/sx
    c = x-nx*a-ny*b
    d = -sine/sy
    e = cosine/sy
    f = y-nx*d-ny*e
    return image.transform(image.size, Image.AFFINE, (a,b,c,d,e,f), resample=Image.BICUBIC)

rawDescription: affine transform in PIL python

description: Affine transform in PIL python


code:
a = Hello.hello
b = Hello.hello
id(a) == id(b)

rawDescription: `id` function in Python 2.7, `is` operator, object identity and user-defined methods


code:
@login_required
def home(request, team_member_id=None):
    user = request.user
    team_members = Team.objects.all().filter(site__user=user).order_by('team_member_name')

rawDescription: How to filter on a foreign key relationship

description: Filter on a foreign key relationship


rawDescription: Find sub string in the column value

description: Find sub string in the column value


rawDescription: How to get string after last comma in a field

description: Get string after last comma in a field


code:
from sklearn.cross_validation import train_test_split
set_1, temp = train_test_split(ds2, train_size=0.6, random_state=42)
set_2, set_3 = train_test_split(temp, train_size=0.5, random_state=42)

rawDescription: Randomly spread a dataset in Python

description: Randomly spread a dataset in Python


code:
s1 = 'class="input {{#if Required}}required{{/if}}"'
s2 = 'class="input {{#if emailRequired}}required{{/if}}{{#if contactPointRequired}}required{{/if}}"'

# 0. Split strings into meaningful parts
# In this case I am using a crude regex to detect token boundaries
# Remember, this step is optional

import re
pat = re.compile(r'(\=+|\"+| |\{+|\}+)')
a = pat.split(s1)
b = pat.split(s2)

# 1. Create SequenceMatcher

from difflib import SequenceMatcher
matcher = SequenceMatcher(a=a, b=b, autojunk=False)

# 2. Format output
# Here I am using ANSI escape codes to colorize the output

GREEN='\033[92m'
RED='\033[91m'
ENDC='\033[0m'
line = []
for op, ai, aj, bi, bj in matcher.get_opcodes():
    if op == 'equal':
        line.extend(a[ai:aj])
    else:
        if aj > ai:
            line.append(RED)
            line.extend(a[ai:aj])
            line.append(ENDC)
        if bj > bi:
            line.append(GREEN)
            line.extend(b[bi:bj])
            line.append(ENDC)

print(''.join(line))

rawDescription: Concatenate uncommon literals of 2 strings leaving common literals in python


code:
def repeating_counter(times):
    return (x // times for x in count())

rawDescription: One line repeating counter with itertools?


code:
list1 = {'i': 1, 'k': 1, 'j': 1, 'o': 2, 'q': 1, 's': 1, 'x': 1, 'z': 1}
string1 = 'ikjoosgx'
for letter in string1:
    list1[letter] = list1.setdefault(letter, 0) - 1

rawDescription: How to substract from dictionary value in Python?

description: Substract from dictionary value in Python


code:
s = 'abcabc'
s.rindex('abc')  # evaluates to 3

rawDescription: How to find the last targeted string in a string by Python?

description: Find the last targeted string in a string by Python


code:
import re

lst=['beak','back','bear','kill','keel']
regex=re.compile('k..l')
locs, matches = zip(*[(idx, string) for idx, string in enumerate(lst) if re.match(regex, string)])
print(matches)
print(locs)

rawDescription: search list of string with wildcard and return matches & indexes python

description: Search list of string with wildcard and return matches & indexes python


rawDescription: Set minimum column width to header width in PyQt4 QTableWidget


code: Avg = np.sqrt(Avg)

rawDescription: sqrtm() function returns nan

description: Sqrtm() function returns nan


code:
import sys

def get_path():
    namespace = sys._getframe(1).f_globals  # caller's globals
    return namespace.get('__file__')

rawDescription: How to get the file path of a module from a function executed but not declared in it, in Python?

description: Get the file path of a module from a function executed but not declared in it, in Python


code:
class SoundManager:
    sounds = [] # list of sound objects

    @staticmethod
    def playRandom():
        random.choice(SoundManager.sounds).play()

rawDescription: Choosing a random sound Pygame

description: Choosing a random sound Pygame


code:
from collections import OrderedDict, Callable

class DefaultOrderedDict(OrderedDict):
    # Source: http://stackoverflow.com/a/6190500/562769
    def __init__(self, default_factory=None, *a, **kw):
        if (default_factory is not None and
           not isinstance(default_factory, Callable)):
            raise TypeError('first argument must be callable')
        OrderedDict.__init__(self, *a, **kw)
        self.default_factory = default_factory

    def __getitem__(self, key):
        try:
            return OrderedDict.__getitem__(self, key)
        except KeyError:
            return self.__missing__(key)

    def __missing__(self, key):
        if self.default_factory is None:
            raise KeyError(key)
        self[key] = value = self.default_factory()
        return value

    def __reduce__(self):
        if self.default_factory is None:
            args = tuple()
        else:
            args = self.default_factory,
        return type(self), args, None, None, self.items()

    def copy(self):
        return self.__copy__()

    def __copy__(self):
        return type(self)(self.default_factory, self)

    def __deepcopy__(self, memo):
        import copy
        return type(self)(self.default_factory,
                          copy.deepcopy(self.items()))

    def __repr__(self):
        return 'OrderedDefaultDict(%s, %s)' % (self.default_factory,
                                               OrderedDict.__repr__(self))

rawDescription: Can I do an ordered, default dict in Python?

description: Do an ordered, default dict in Python


code:
# in python3:
# table = str.maketrans('ABC', 'ZYX')

# in python2:
from string import maketrans
table = maketrans('ABC', 'ZYX')  # add the rest of the alphabet and the desired
                                 # subsitutions

print('CBA'.translate(table))
# output: 'XYZ'

rawDescription: Convert input letter to different letter


rawDescription: Handling binary literal in python

description: Handling binary literal in python


code:
from enum import Enum
class Shake(Enum):
    __order__ = 'vanilla chocolate cookies mint'
    vanilla = 7
    chocolate = 4
    cookies = 9
    mint = 3

for s in Shake:
    print(s)

rawDescription: Iterate python Enum in definition order

description: Iterate python Enum in definition order


code:
for sharedkey in dct1.keys() & dct2.keys():  # intersection of two dictionaries
    print(dct1[sharedkey], dct2[sharedkey])

rawDescription: Why use dict.keys?

description: Why use dict.keys


code:
from itertools import cycle
color = cycle([91, 93, 92, 96, 94, 95])

with open(sys.argv[1]) as f:
    for i in f.read():
       print('\033[{0}m{1}\033[{0};m'
             .format(next(color), i), end='', flush=True)

rawDescription: Use for loop inside another for loop

description: Use for loop inside another for loop


code:
profile = EnterpriseProfile.objects.get(pk=1)  # or whatever to get the object
# next returns all users related to that enterprise in the M2M
profile.enterprise.users.all()

rawDescription: Django complex Query through database API


code:
a='alRfflkafdfaeGlkAYEuRFSbbvvcbF'
import re
r=re.compile("[A-Z]{3}[a-z][A-Z]{3}")
r.findall(a)

rawDescription: Search for a pattern in a lot of scramble letters (upper & lower cases)


code:
def cmdMessage(message):
    subprocess.call('cmd /K "echo ' + message + '"')

cmdMessage('One or more of the IPs failed to respond to their ping. Check Logs')

rawDescription: Python subprocess command to run echo and leave the window open


code:
files = ['text1.txt', 'text2.txt']

with open('result.txt', 'w') as result:
    for file_ in files:
        for line in open(file_, 'r'):
            result.write(line)

rawDescription: Combine specific files and put it in a single file python


code:
ids = set(B)
L = [obj for obj in A if obj.id in ids]

rawDescription: get a list from another list with minimum iteration in python

description: Get a list from another list with minimum iteration in python


code:
threads = [node1, node2, node3, node4]
[thread.start() for thread in threads]

rawDescription: Python sockets not receiving message

description: Python sockets not receiving message


code:
mylist = ['LION', 'tv', 'TIGER', 'keyboard', 'cd-writer','ELEPHANT']
[word for word in mylist if word==word.lower()]

rawDescription: Groupby the list according to category

description: Groupby the list according to category


code:
#!/usr/bin/env python

from twisted.internet.protocol import Factory, Protocol
from twisted.internet import reactor

class StreamCounter(Protocol):
    def connectionMade(self):
        self.factory.counter += 1
        self.transport.write(str(self.factory.counter)+'\r\n')
        self.transport.loseConnection()

class DatagramCounter(DatagramProtocol):
    def __init__(self, factory):
        self.factory = factory

    def datagramReceived(self, data, address):
        self.factory.counter += 1
        self.transport.write(str(self.factory.counter), address)

class QOTDFactory(Factory):
    counter = 0
    protocol = StreamCounter

factory = QOTDFactory()
reactor.listenTCP(8007, factory)
reactor.listenUDP(8007, DatagramCounter(factory))

reactor.run()

rawDescription: Twisted share a variable between tcp/udp protocols


code:
import Tkinter as tk
from tkintertable.Tables import TableCanvas
class createTable(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        #########################################
        self.master.grid_rowconfigure(0, weight=1)
        self.master.grid_columnconfigure(0, weight=1)

        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)

        self.grid(sticky=tk.NW+tk.SE)
        #########################################
        self.F = tk.Frame(self)
        self.F.grid(row=0, column=0, sticky=tk.NW+tk.SE)
        self.createWidgets()

    def createWidgets(self):
        self.table = TableCanvas(self.F,rows=30,cols=30)
        self.table.createTableFrame()

app = createTable()
app.master.title('Sample Table')
app.mainloop()

rawDescription: How to make tkintertable Table resizable

description: Make tkintertable Table resizable


code:
with open('test.csv', 'w', newline='') as csv_file:
    writer = csv.writer(csv_file, quotechar='"', quoting=csv.QUOTE_ALL)
    for record in my_dict.values():
        final = [",".join(index) for index in record]
        writer.writerow(final)

rawDescription: Write csv with each list as column

description: Write csv with each list as column


code:
def isInAlphabeticalOrder(word):
    for i in range(len(word) - 1):
        if word[i] > word[i + 1]:
            return False
    return True

rawDescription: checking if a string is in alphabetical order in python

description: Checking if a string is in alphabetical order in python


code:
myArray[myotherArray == 0] *= 5
myArray

rawDescription: Update array based on other array Python


code:
scipy.sparse.csr_matrix([[1, 2], [3, 0]])
scipy.sparse.csr_matrix([1, 2])

rawDescription: convert list and list of lists to scipy sparse arrays

description: Convert list and list of lists to scipy sparse arrays


code:
remote_repo = self.repo.remotes[remote]

# here is where you could choose an executable based on the platform.
# Shell scripts might just not work plainly on windows.
ssh_executable = os.path.join(rw_dir, 'my_ssh_executable.sh')
# This permanently changes all future calls to git to have the given environment variables set
# You can pass additional information in your own environment variables as well.
self.repo.git.update_environment(GIT_SSH_COMMAND=ssh_executable)

# now all calls to git which require SSH interaction call your executable
remote_repo.push(self.repo.active_branch.name)

rawDescription: Gitpython ssh password

description: Gitpython ssh password


code:
address_form = AddressForm(request.POST)
profile_form = UserProfileForm(request.POST)
contacts_form = ContactInfoForm(request.POST)
if address_form.is_valid() and profile_form.is_valid() and contacts_form.is_valid():
    address_form.save()
    profile_form.save()
    contacts_form.save()

rawDescription: Saving Django ModelForms with Multiple Inheritance


code:
print("This program 'is' designed to find the average of n numbers you input\n") #print statement that introduces the average finder

counter = 0 #this counter will count how many numbers the user has inserted into the     program and will be used as denominator
sum_of_numbers = 0 #this number is set as 0 as currently the sum is 0, as more numbers are inputed, they will be added together

first_question = input('''Would you like to enter a number? Type "yes" if you do, and "no" if you don't. \n\n''') #takes input of yes or no to see whether user wants to find average of numbers

while first_question == "yes" :
    ent_num = int(input("Enter your number here:"))
    sum_of_numbers = sum_of_numbers + ent_num
    counter = counter + 1
    first_question = input('''Would you like to enter another number after this? Type "yes" if you do, and "no" if you don't. \n''')

print("Your average is " + str(sum_of_numbers/counter))

rawDescription: Finding the average of n numbers with Python


code:
from itertools import product, cycle
s = 'abcde'
[''.join(chars) for chars in product(*zip(s, cycle('*')))]

rawDescription: Replacing chars in a string in every way


code:
import subprocess as sub

def write_data(filename, data):
    cmd = ('exiftool', '-Comment=%s' % data, filename)
    sub.check_call(cmd)

def get_data(filename):
    cmd = ('exiftool', '-Comment', filename)
    return sub.check_output(cmd).split(':', 1)[-1].strip()

write_data('IMG_0001.jpg', 'a'*2048)
assert get_data('IMG_0001.jpg') == 'a'*2048

rawDescription: Embed and retrieve long string from image meta-data in Python


code:
import os
os.mkdir('foo')
open('foo/__init__.py', 'w').write('print "__name__:", __name__')
open('foo/bar.py', 'w').write('# nothing done here')
from foo import bar
import sys
sys.modules['foo']
sys.modules['foo'].__name__

rawDescription: What is the value of __name__ when accessed in a __init__.py


code:
where = " OR ".join(["order LIKE %s"]*len(orders))
sql = "SELECT order from `customers` WHERE " + where
cur.execute(sql, ["%{}%".format(o) for o in orders])

rawDescription: Use wild cards with IN syntax in SQL with python


code:
from matplotlib.pyplot import show
sns.set(style="darkgrid")
titanic = sns.load_dataset("titanic")
total = float(len(titanic)) # one person per row
ax = sns.barplot(x="class", hue="who", data=titanic)
for p in ax.patches:
    height = p.get_height()
    ax.text(p.get_x(), height+ 3, '%1.2f'%(height/total))
show()

rawDescription: How to add percentages on top of bars in seaborn?

description: Add percentages on top of bars in seaborn


code:
d = {}
d[list_x.pop(1)] = list_x

rawDescription: Python list to dictionary (regardless of length)


code:
self.db[self.mongo_collection].create_index(
    [("url", pymongo.DESCENDING), ("category", pymongo.ASCENDING)],
    unique=True
)

rawDescription: PyMongo create_index unique with 2 columns


code:
import os
os.makedirs("TEST")

rawDescription: Run Python script with path as argument from total commander


code:
def word_start_index2(text, seek_word):
    camel_case = seek_word[0].upper() + seek_word[1:].lower()
    seek_word_i = ''.join('[' + c.lower() + c.upper() + ']'
                           for c in seek_word)
    regex1 = r'(?:(?<=[^a-zA-Z])|^)' + seek_word_i + r'(?=$|[^a-zA-Z])'
    regex2 = r'(?:(?<=[a-z]|[^A-Z])|^)' + camel_case + r'(?=$|[A-Z]|[^a-z])'
    regex = '%s|%s' % (regex1,  regex2)
    import re
    m = re.search(regex, text)
    if not m:
        return None
    else:
        return m.start()

rawDescription: tricky string matching

description: Tricky string matching


code:
# for each element
row_dict = dict.fromkeys(xpathdict.keys())
...
# for each key
row_dict[key] = element.xpath(xpathdict[key]) or None
...
dictwriter.writerow(row_dict)

rawDescription: Parsing weirdly structured XML with lxml


code:
values = [2, 4, 6, 8, 10, 12, 14]
for x in reversed(values):
    print(x)

rawDescription: Reading files in reverse order

description: Reading files in reverse order


code:
class Application(models.Model):
    name = models.CharField(max_length=50)

    def next_upcoming_release(self):
        future_releases = self.release_set.filter(release_date__gte=datetime.datetime.now())
        return future_releases.order_by('release_date').first()

rawDescription: Django - sorting foreign key objects by date


code:
#!/usr/bin/env python3

def main():

    testConfFile = 'test2.txt' # /etc/apache2/apache2.conf
    testConfLabel = 'timed_combined'
    testConfData = r'''###This is an important line that needs to be copied - ##-#-####
Very Important Line of information that the above line is a \"r\" comment for - message_label'''

    testFormatAppend(testConfFile, testConfData, testConfLabel)     # Add new test format

def testFormatAppend(filename, data, label):
    dataSplit = data.splitlines()
    fileDataStr = ''

    with open(filename, 'r') as file:
        fileData = stringToDictByLine(file)

    for key, val in fileData.items():
        for row in dataSplit:
            if val.strip().endswith(row.strip().split()[-1]):
                fileData[key] = ''

    fileLen = len(fileData)
    if fileData[fileLen] == '':
        fileLen += 1
        fileData[fileLen] = data
    else:
        fileLen += 1
        fileData[fileLen] = '\n' + data

    for key, val in fileData.items():
        fileDataStr += val

    with open(filename, 'w') as file:
        file.writelines(str(fileDataStr))

def stringToDictByLine(data):
    fileData = {}
    i = 1
    for line in data:
        fileData[i] = line
        i += 1
    return fileData

if __name__ == "__main__": main()

rawDescription: How do I search a file for a string and replace it with multiple lines in Python?

description: Search a file for a string and replace it with multiple lines in Python


code:
with open(name) as infile, open('output', 'w') as outfile:
    contents = infile.read()
    new_contents = re.sub(r'\s+([A-Z])', r'\n\1', contents)
    outfile.write(new_contents)

rawDescription: re.sub replacing everything with the last item in the list

description: Re.sub replacing everything with the last item in the list


code:
import zlib
def compress(chunks):
    c = zlib.compressobj()
    for chunk in chunks:
       yield c.compress(chunk)
    yield c.flush(zlib.Z_FINISH)

rawDescription: Python : Generating a gzip string by returning chunks


code:
z = np.load('heights.npy')
plt.contour(np.transpose(z),np.linspace(z.min(),z.max(),25))
plt.title('even contour lines')
plt.savefig('myFig2.png', format='png')

rawDescription: Matplotlib evenly spaced contour lines

description: Matplotlib evenly spaced contour lines


code:
from .models import Snippet
from serializers import SnippetSerializer
from rest_framework.renderers import JSONPRenderer
from rest_framework.parsers import JSONParser
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt

class JSONResponse(HttpResponse):

    def __init__(self, data, **kwargs):
        content = JSONPRenderer().render(data)
        kwargs['content_type'] = 'aplication/json'
        super(JSONPRenderer, self).__init__(content, **kwargs)

@csrf_exempt
def snippet_list(request):
    """
    List all code snippets or create new code snippet
    """
    if request.method == "GET":
        snippet = Snippet.objects.all()
        serializer = SnippetSerializer(snippet, many=True)
        return JSONResponse(serializer.data)

    elif request.method == "POST":
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JSONResponse(serializer.data, status=201)
        return JSONResponse(serializer.data, status=400)

@csrf_exempt
def snippet_detail(request, pk):
    """
    Retrive, delete or update code snippet
    """
    try:
        snippet = Snippet.objects.get(pk=pk)
    except Snippet.DoesNotExist:
        return HttpResponse(status=404)

    if request.response == "GET":
        serializer = SnippetSerializer(snippet)
        return JSONResponse(serializer.data)

    elif request.method == "PUT":
        data = JSONParser().parse(request)
        serializer = SnippetSerializer(snippet, data=data)
        if serializer.is_valid():
            serializer.save()
            return HttpResponse(serializer.data)
        return HttpResponse(serializer.errors, status=400)

    elif request.method == "DELETE":
        snippet.delete()
        return HttpResponse(status=204)

rawDescription: Django Rest: The view does not want to import


code: countryname = aliases.get(countryname, countryname)

rawDescription: Finding fast default aliases in Python

description: Finding fast default aliases in Python


code:
def mydeco(count):
    def multipass(fn):
        def caller(*args, **kw):
            return [fn(*args, **kw) for x in range(count)]
        return caller
    return multipass

@mydeco(5)
def printer(text):
    print(text)

printer("Yabbadabbadoo!")

rawDescription: Python decorator with options

description: Python decorator with options


code:
import ast
ast.literal_eval('(0,0,0)')

rawDescription: Converting strings into another data type, Python


code: "they're bill's friends from the UK".title()

rawDescription: Capitalizing strings

description: Capitalizing strings


code:
...
main_sheet.write(1, 0, 'internal:linkable_sheet!A1', integer_format)
main_sheet.write(1, 0, 100,                          integer_format)
...

rawDescription: xlsxwriter: How to put an internal hyperlink in a table and have content formatted as integer

description: Xlsxwriter: How to put an internal hyperlink in a table and have content formatted as integer


code:
class Foo(float):
    def __new__(self, value, extra):
        return float.__new__(self, value)
    def __init__(self, value, extra):
        float.__init__(value)
        self.extra = extra

foo = Foo(1,2)
print(str(foo))
1.0
print(str(foo.extra))
2

rawDescription: Python: Can a subclass of float take extra arguments in its constructor?


code:
def run(self, result=None):
    if result is None: result = self.defaultTestResult()
    result.startTest(self)
    testMethod = getattr(self, self._testMethodName)
    try:
        try:
            self.setUp()
        except KeyboardInterrupt:
            raise
        except:
            result.addError(self, self._exc_info())
            return

        ok = False
        try:
            testMethod()
            ok = True
        except self.failureException:
            result.addFailure(self, self._exc_info())
            result.stop()
        except KeyboardInterrupt:
            raise
        except:
            result.addError(self, self._exc_info())
            result.stop()

        try:
            self.tearDown()
        except KeyboardInterrupt:
            raise
        except:
            result.addError(self, self._exc_info())
            ok = False
        if ok: result.addSuccess(self)
    finally:
        result.stopTest(self)

rawDescription: PyUnit: stop after first failing test?

description: PyUnit: stop after first failing test


code:
array = np.array([1, 2, 3, 4])
1. / array

rawDescription: Getting inverse (1/x) elements of a numpy array


code:
latex_custom = r'''
\definecolor{Admonition}{RGB}{221,233,239}

\makeatletter
  \newenvironment{admonitionbox}{
    \begin{lrbox}{\@tempboxa}\begin{minipage}{\columnwidth}
  }{
    \end{minipage}\end{lrbox}
    \colorbox{Admonition}{\usebox{\@tempboxa}}
  }

  \renewenvironment{notice}[2]{
    \begin{admonitionbox}
  }{
    \end{admonitionbox}
  }
\makeatother
'''

latex_elements = {'preamble': latex_custom}

rawDescription: Adding background color of notes to Sphinx-generated PDF files?


code:
from django.db.models import F
qs = InstanceItemEvaluation.objects.filter(
    user=user,
    instance=instance,
    factor__is_active=True,
    measure__is_active=True).exclude(
    factor__measure=None).filter(
    factor__measure=F('measure_id'))

rawDescription: Django queryset filter model attribute against other model attribute


code: import pdb; pdb.set_trace(); pdb.set_trace = lambda: 0

rawDescription: Python, pdb, adding breakpoint which only breaks once


code:
first_list, secnd_list = [], []
for line in file:
    first, second = line.split('/')
    first_list.append(first)
    secnd_list.append(second)

rawDescription: Split string when a certain character is read


code:
class Api(models.Model):
    myUrl = models.CharField(max_length=500, blank=True, verbose_name="Url", editable=False)

    def save(self, *args, **kwargs):
        super(Api, self).save(*args, **kwargs)
        self.formUrl = "https://custumUrl/"+str(self.id)+"/"
        super(Api, self).save(*args, **kwargs)

rawDescription: How to save a changed value in Django admin on api creation?

description: Save a changed value in Django admin on api creation


code: subprocess.Popen([exe, '-version'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

rawDescription: extract audio with youtube-dl on windows

description: Extract audio with youtube-dl on windows


code: myDict = defaultdict(lambda: defaultdict(list))

rawDescription: Python How to make myDcitionary['key1']['key2']=list()


code:
import time
tic = time.time() #start
while True:
   do_big_job()
   toc = time.time();
   if ( toc - tic > timeout ):
      break

rawDescription: simplest way to time output of function

description: Simplest way to time output of function


code:
import ctypes
from wand.image import Image
from wand.api import library

library.MagickSepiaToneImage.argtypes = [ctypes.c_void_p, ctypes.c_double]
library.MagickSepiaToneImage.restype = None

img = Image(filename="img.jpg")
threshold = img.quantum_range * 0.8
library.MagickSepiaToneImage(img.wand, threshold)
img.save(filename="out.jpg")

rawDescription: Sepia tone via wand api (using wand-py) produces completely wrong image (no sepia, high brightness)


code:
import time
timestamp = 1284375159
time.strftime("%m %d %Y",time.localtime(timestamp))

rawDescription: Getting formatted datetime in Python like in PHP


code:
import scipy as sp
import numpy as np
import scipy.ndimage as nd
import matplotlib.pyplot as plt

lena = sp.misc.lena()
LoG = nd.gaussian_laplace(lena, 2)
thres = np.absolute(LoG).mean() * 0.75
output = sp.zeros(LoG.shape)
w = output.shape[1]
h = output.shape[0]

for y in range(1, h - 1):
    for x in range(1, w - 1):
        patch = LoG[y-1:y+2, x-1:x+2]
        p = LoG[y, x]
        maxP = patch.max()
        minP = patch.min()
        if (p > 0):
            zeroCross = True if minP < 0 else False
        else:
            zeroCross = True if maxP > 0 else False
        if ((maxP - minP) > thres) and zeroCross:
            output[y, x] = 1

plt.imshow(output)
plt.show()

rawDescription: Python implementation of the laplacian of gaussian edge detection


code:
from functools import partial

try:
    old_save = bundle.obj.save
    bundle.obj.save = partial(old_save, user=bundle.request.user)
    return super(FooResource, self).save(bundle)
finally:
    bundle.obj.save = old_save

rawDescription: Django-tastypie pass request.user to custom save method


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

url = "http://www.oddsportal.com/soccer/england/premier-league/aston-villa-chelsea-Ea6xur9j/?r=1#over-under;2"
browser = webdriver.Firefox()
browser.implicitly_wait(10)
wait = WebDriverWait(browser, 10)

browser.get(url)

if browser.find_element_by_xpath(
'//a[@id = "user-header-oddsformat-expander"]/span').text != 'IN Odds':
 # choose a type of odd that you want from the top dropdown menu
    browser.find_element_by_xpath(
    '//a[@id = "user-header-oddsformat-expander"]').click()
    browser.find_element_by_xpath(
    '//ul[@id = "user-header-oddsformat"]/li/a/span[contains(text(), "IN Odds")]').click()

    wait.until(EC.text_to_be_present_in_element((By.XPATH, '//a[@id = "user-header-oddsformat-expander"]/span'), "IN Odds"))

table = browser.find_elements_by_css_selector('div#odds-data-table')
for elem in table:
    print(elem.text)

rawDescription: How to get updated data from a table after selecting from dropdown using Selenium?

description: Get updated data from a table after selecting from dropdown using Selenium


code: print("the value is: %s" % thismyvar.get())

rawDescription: How to get variables from radio buttons with multiple variables

description: Get variables from radio buttons with multiple variables


code: f2 = np.interp(np.arange(0,31,.1), t, ft)

rawDescription: retrieving data from a plot in python?

description: Retrieving data from a plot in python


code:
import os
path = r"\users\temp"   #use raw string as otherwise \t will be converted to tab space
folder = [x for x in os.listdir(path) if os.path.isdir(os.path.join(path,x))]

rawDescription: Assign a variable to every directory inside one folder. (python)


code:
ulong, ulat = request.session['user_latitude'], request.session['user_longitude']
sorted(shop_list, key=lambda shop: distance_of_the_shop(shop, ulong, ulat))

rawDescription: How to pass multiple arguments to the method 'key' of sorted()?

description: Pass multiple arguments to the method 'key' of sorted()


code:
from Tkinter import *

class Sorting(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Sorting")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S )

        nums = [10, 20, 8, 5, 7]       # example of entry
        result = sorted(nums)          # sorted result = [3 ,5 , 8, 10 ,20]

        # the color list holds the items changing position when sortened
        color = [ind for ind, (x, y) in enumerate(zip(nums, result)) if x != y]

        entry_num = ''.join('%4i' % num for num in nums)
        sort_nums = ''.join('%4i' % num for num in result)

        l1 = Label(self,  text="entry", width=25, height=1)
        l1.grid(row=0, column=1, sticky=N)

        t_entry = Text(self,  width=25, height=2)
        t_entry.grid(row=1, column=1, sticky=N)
        t_entry.insert(END, entry_num)

        l2 = Label(self, text='sorted', width=25, height=1)
        l2.grid(row=2, column=1, sticky=N)

        t_sorted = Text(self,  width=25, height=2)
        t_sorted.grid(row=3, column=1, sticky=N)
        t_sorted.insert(END, sort_nums)

        t_sorted.tag_config('red_tag', foreground='red')

        for pos in color:
            a = '1.%i' % (4 * pos)
            b = '1.%i' % (4 * pos + 4)
            t_sorted.tag_add('red_tag', a, b)

if __name__ == "__main__":
    Sorting().mainloop()

rawDescription: A GUI for sorting: how to colour certain numbers in each step of sorting?


code:
class Category(MPTTModel):
    name = models.CharField()
    parent = models.ForeignKey("self", blank=True, null=True,
             related_name="sub_category")

    class MPTTMeta:
        order_insertion_by = ['name']

rawDescription: Django-mptt order

description: Django-mptt order


code:
from tkinter import *

class Application(Frame):
    def __init__(self, master):
        """ Initialize frame"""
        super(Application, self).__init__(master)
        self.grid()
        self.create_widgets()
    def create_widgets(self):
        """Create 3 useless buttons"""
        #first one
        self.bttn1=Button(self, text ="I do nothing!")
        self.bttn1.grid()
        #second button
        self.bttn2 = Button(self)
        self.bttn2.grid()
        self.bttn2.configure(text ="Me too!")
        #third one
        self.bttn3 = Button(self)
        self.bttn3.grid()
        self.bttn3["text"]="And me also!"

root=Tk()
#alter window
root.title("The simpliest gui")
root.geometry("200x100")
app=Application(root)
root.mainloop()

rawDescription: Creating a simple gui program using Tkinter in Python


code:
from bs4 import BeautifulSoup, Tag

for strong in soup.select(".car-profile-info strong"):
    label = strong.get_text()
    value = ""
    for elm in strong.next_siblings:
        if getattr(elm, "name") == "br":
            break
        if isinstance(elm, Tag):
            value += elm.get_text(strip=True)
        else:
            value += elm.strip()

    print(label, value)

rawDescription: How to find text with a particular value BeautifulSoup python2.7

description: Find text with a particular value BeautifulSoup python2.7


code:
pycurl_connect = pycurl.Curl()
pycurl_connect.setopt(pycurl.URL, your_url)
pycurl_connect.setopt(pycurl.HTTPHEADER, ['header_name1: header_value1',
                                          'header_name2: header_value2'])
pycurl_connect.perform()

rawDescription: Custom headers with pycurl

description: Custom headers with pycurl


code:
from pyramid.events import NewRequest

def do_something(request):
    # do something here
    pass

def setup_post_request(event):
    event.request.add_finished_callback(do_something)

config.add_subscriber(setup_post_request, NewRequest)

rawDescription: Post-process request event in Pyramid/Pylons


rawDescription: Changing the title of a frame in wxPython


code:
FilePath = 'temp' # replace the temp with your file path/name
modifiedTime = os.path.getmtime(FilePath)

timeStamp =  datetime.datetime.fromtimestamp(modifiedTime).strftime("%b-%d-%y-%H:%M:%S")
os.rename(FilePath,FilePath+"_"+timeStamp)

rawDescription: Making a backup file + appending date time + moving file if the file exists. PYTHON


code:
content = sys.stdin.read()
data = json.loads(content)
newURL = data.get('newURL')
if newURL == 'dog':
    newURL = 'http://www.DogsAreCool.com'
elif not newURL:
    newURL = defaultPageURL
response = urllib2.urlopen(newURL)
# ...

rawDescription: Handle JSON events in Python

description: Handle JSON events in Python


code:
#-*- coding:utf-8 -*-
import os
import urllib2

with open('path_to_your_hash_url', 'r') as fh:
    url_to_be_download = fh.read().split("\n")

with open('path_to_your_FileNames', 'r') as fh:
    fileNames = fh.read().split('\n')

siteurl = 'http://whatever.com/'  #path to your site

downloadFolder = r'YourDownloadFile folder'

for i, url in enumerate(url_to_be_download):
    location = os.path.join(downloadFolder, url_to_be_download[i])
    with open(newloc,"w") as fh:
        full_url = siteurl+ url
        ufile = urllib2.urlopen(full_url).read()
        fh.write(ufile)

rawDescription: Wget download files using lins in a file and rename


code:
import unittest

from selenium import webdriver

import subprocess

import urllib2

execfile("applications/tukker/controllers/default.py", globals())

ROOT = 'http://localhost:8001'

def start_web2py_server():
    return subprocess.Popen([
        'python', '/home/alan/web2py/web2py/web2py.py', 'runserver',
         '-a "passwd"', '-p 8001' ])

class FunctionalTest(unittest.TestCase):

    @classmethod
    def setUpClass(self):
        self.web2py = start_web2py_server()
        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(1)

    @classmethod
    def tearDownClass(self):
        self.browser.close()
        self.web2py.kill()

    def get_response_code(self, url):
        """Returns the response code of the given url
        url     the url to check for
        return  the response code of the given url
        """
        handler = urllib2.urlopen(url)
        return handler.getcode()

    def test_can_view_home_page(self):
        # John opens his browser and goes to the home-page of the tukker app
        self.browser.get(ROOT + '/tukker/')
        # He's looking at homepage and sees Heading "Messages With 300 Chars"
        body = self.browser.find_element_by_tag_name('body')
        self.assertIn('Messages With 300 Chars', body.text)

suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(FunctionalTest))
unittest.TextTestRunner(verbosity=2).run(suite)

rawDescription: unittest - Importerror

description: Unittest - Importerror


rawDescription: Numpy: get the higest L value

description: Numpy: get the higest L value


code:
def only_uses_letters_from(string1, string2):
   """Check if the first string only contains characters also in the second string."""
   return set(string1) <= set(string2)

rawDescription: Return True if all characters in a string are in another string


rawDescription: finding particular lists in a dictionary in python

description: Finding particular lists in a dictionary in python


code:
fig, ax = plt.subplots()
my_dataframe.plot(ax=ax)
plt.show() # plt in place of ax

rawDescription: Show a Pandas plot from a script

description: Show a Pandas plot from a script


code:
if myObject.TotalGrade.value__ == Grade.Fail.value__:
    pass  # your code here...

rawDescription: Comparing Enum Values within IronPython

description: Comparing Enum Values within IronPython


code:
class Outer(object):
    class InnerBase(object): _var = {'foo', 'bar'}
    Derived = type('Derived',
                   (InnerBase,),
                   {'_var': InnerBase._var | {'baz'}}
                  )

rawDescription: Access base class attribute in derived class - in "class scope"


code:
def utf8len(s):
    return len(s.encode('utf-8'))

rawDescription: How can I determine the byte length of a utf-8 encoded string in Python?

description: Determine the byte length of a utf-8 encoded string in Python


code:
import os
target_dir = r"C:\full\path\to\where\you\want\it"

fullname = os.path.join(target_dir,filename)
with open(fullname,"w") as f:
   f.write("<html>....</html>")

import webbrowser

url = "file://"+fullname.replace("\\","/")
webbrowser.open(url,True,True)

rawDescription: Python3:Save File to Specified Location

description: Python3:Save File to Specified Location


code: from django.contrib.auth.forms import PasswordChangeForm

rawDescription: Django + form for resetting the password


code:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://xx.yy.zz")

# Click the "New comer, click here to play!" button
elem = driver. find_element_by_partial_link_text("Click here to play")
elem.send_keys(Keys.RETURN)

rawDescription: Using AutoIT with Selenium

description: Using AutoIT with Selenium


code:
def __hash__(self):
    return hash(tuple(self.list_attribute))

rawDescription: Making a list subclass hashable

description: Making a list subclass hashable


code:
def editObject(object_id, **kwargs):

    object = session.query(Object).filter_by(id = object_id).one()

    for attr, value in kwargs.iteritems():
        if value:
            setattr(object, attr, value)

    session.add(object)
    session.commit()

rawDescription: Python: update attribute value if not None


code:
import sys

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

class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.view = QGraphicsView(self)
        self.scene = QGraphicsScene(self.view)
        self.view.setScene(self.scene)
        self.setCentralWidget(self.view)
        self.group = QGraphicsItemGroup()
        self.text = QGraphicsTextItem()
        self.text.setPlainText("I'm visible")
        self.group.addToGroup(self.text)
        self.scene.addItem(self.group)
        self.group.removeFromGroup(self.text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())

rawDescription: QGraphicsItemGroup.removeFromGroup -- child items not correctly reparented to Scene


code:
username = "Max"
query = """
    SELECT
        username, password
    FROM
        UserInfo.User
    WHERE
        username = %s
"""

mycursor.execute(query, (username, ))
username, password = mycursor.fetchone()  # here we can unpack the tuple returned from fetchone

rawDescription: reading/storing from mysql using variables python

description: Reading/storing from mysql using variables python


rawDescription: Write a list to csv file without looping in python


code:
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")

rawDescription: How do I clear the cookies in urllib.request (python3)

description: Clear the cookies in urllib.request (python3)


code:
import itertools

lstrep = [('A',('aa','aA','Aa','AA')),('I',('ii','iI','Ii','II'))]
input_str = 'DArA'

# make substitution list a dict for easy lookup
lstrep_map = dict(lstrep)

# a substitution is an index plus a string to substitute. build
# list of subs [[(index1, sub1), (index1, sub2)], ...] for all
# characters in lstrep_map.
subs = []
for i, c in enumerate(input_str):
    if c in lstrep_map:
        subs.append([(i, sub) for sub in lstrep_map[c]])

# build output by applying each sub recorded
out = [input_str]
for sub in itertools.product(*subs):
    # make input a list for easy substitution
    input_list = list(input_str)
    for i, cc in sub:
        input_list[i] = cc
    out.append(''.join(input_list))

print(out)

rawDescription: Optionally replacing a substring python

description: Optionally replacing a substring python


code:
import requests

api_url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s'
query = 'xxx'
query_url = api_url %query
response = requests.get(query_url).json()
results = response['responseData']['results']
if results:
   first_result_url = results[0]['url']

rawDescription: Python search scraping

description: Python search scraping


code:
from datetime import datetime, timedelta

start = 2012.5
year = int(start)
rem = start - year

base = datetime(year, 1, 1)
result = base + timedelta(seconds=(base.replace(year=base.year + 1) - base).total_seconds() * rem)
# 2012-07-02 00:00:00

rawDescription: decimal years to datetime in python

description: Decimal years to datetime in python


code:
A['D'] = pd.Series(B)
A

rawDescription: In Python, how can I transform a dictionary into a df column, where the keys match the df.index values?


code:
class X(object):
    def get_i(self):
        return self._i
    def set_i(self, value):
        self._i= value
    i= property(get_i, set_i)

rawDescription: Make a python property with the same name as the class member name


code:
from matplotlib.colors import LinearSegmentedColormap
import matplotlib.pyplot as plt
import numpy as np

dic = {'red': ((0., 1, 0),
               (0.66, 1, 1),
               (0.89,1, 1),
               (1, 0.5, 0.5)),
       'green': ((0., 1, 0),
                (0.375,1, 1),
                (0.64,1, 1),
                (0.91,0,0),
                (1, 0, 0)),
       'blue': ((0., 1, 1),
               (0.34, 1, 1),
               (0.65,0, 0),
               (1, 0, 0))}

a = np.random.rand(10,10)
a[0,:2] = 0
a[0,2:4] = 0.0001

fig, ax = plt.subplots(1,1, figsize=(6,6))

cmap = LinearSegmentedColormap('custom_cmap', dic)
cmap.set_bad('white')

ax.imshow(np.ma.masked_values(a, 0), interpolation='none', cmap=cmap)

rawDescription: Matplotlib python change single color in colormap


code:
import comtypes.client

def PPTtoPDF(inputFileName, outputFileName, formatType = 32):
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
    deck.Close()
    powerpoint.Quit()

rawDescription: How to convert a .pptx to .pdf using Python

description: Convert a .pptx to .pdf using Python


code:
import cv2
img1 = cv2.imread('abc.jpg')
import numpy as np
a = np.double(img1)
b = a + 15
img2 = np.uint8(b)
cv2.imshow("frame",img1)
cv2.imshow("frame2",img2)
cv2.waitKey(0)
cv2.destroyAllWindows()

rawDescription: how to change image illumination in opencv python

description: Change image illumination in opencv python


code:
import numpy as np
import pandas as pd

# Create a dtype with the binary data format and the desired column names
dt = np.dtype([('a', 'i4'), ('b', 'i4'), ('c', 'i4'), ('d', 'f4'), ('e', 'i4'),
               ('f', 'i4', (256,))])
data = np.fromfile(file, dtype=dt)
df = pd.DataFrame(data.tolist(), columns=data.dtype.names)

rawDescription: Reading binary data into pandas

description: Reading binary data into pandas


code:
def log_saved_event(sender, instance, signal, *args, **kwargs):
    # handle Event class
    pass

from django.db.models import signals
from django.db import models

for m in models.get_models():
    signals.post_save.connect(log_saved_event, sender=m)

rawDescription: Decorating a model class in django issuing save in the decorator


code:
def uniques2(numbers):
    for number in numbers:
        seen = set()
        quotient = number
        while quotient > 10:
            quotient, remainder = divmod(quotient, 10)
            if remainder in seen:
                break
            else:
                seen.add(remainder)
        else:
            yield number

rawDescription: How to filter numbers that contain unique digits?

description: Filter numbers that contain unique digits


code:
import datetime
str_due_date = self.request.get('duedate')
goal.duedate = datetime.datetime.strptime(str_due_date, '%Y-%m-%d')

rawDescription: GAE Howto get Date from form Request

description: GAE Howto get Date from form Request


rawDescription: Can I remove a single value from a dictionary?

description: Remove a single value from a dictionary


code:
...
self.titleLbl = QLabel(self, self.movie['title'])
...

rawDescription: pyqt: show() for labels shows up in different window?

description: Pyqt: show() for labels shows up in different window


code:
import win32com.client
xl = win32com.client.Dispatch("Excel.Application")
xl.Visible = 1
wb = xl.Workbooks.Open(r'<full path of excel spreadsheet>')
sheet = wb.ActiveSheet
sheet.Range("A1").AddComment()
sheet.Range("A1").Comment.Visible = True
sheet.Range("A1").Comment.Text("Hello World")
wb.SaveAs(r'<full path of modified spreadsheet>')
wb.Close()
xl.Quit()

rawDescription: How to write excel comments using python?

description: Write excel comments using python


code:
from lxml import etree
SOAPENV_NAMESPACE = "http://schemas.xmlsoap.org/soap/envelope"
SOAPENV = "{%s}" % SOAPENV_NAMESPACE
ns0_NAMESPACE = "http://xmlns.CLT.com/consume/ENTBUS"
ns0 = "{%s}" % ns0_NAMESPACE
ns1_NAMESPACE = "http://xmlns.CLT.com/Core/ENTBUS"
ns1 = "{%s}" % ns1_NAMESPACE
ns2_NAMESPACE = "http://xmlns.CLT.com/output/EBO"
ns2 = "{%s}" % ns2_NAMESPACE
NSMAP = {'SoapEnv' : SOAPENV_NAMESPACE,'ns0':ns0_NAMESPACE,'ns1':ns1_NAMESPACE,'ns2':ns2_NAMESPACE}
envelope = etree.Element(SOAPENV + "Envelope", nsmap=NSMAP)
ConsumptionRequestENTBUS=etree.SubElement(envelope, ns0 + "ConsumptionRequestENTBUS", nsmap=NSMAP)
ENTBUS=etree.SubElement(ConsumptionRequestENTBUS, ns1 + "ENTBUS", nsmap=NSMAP)
ENTBUSHeader=etree.SubElement(ENTBUS, ns1 + "ENTBUSHeader", nsmap=NSMAP)
ENTBUSDetail=etree.SubElement(ENTBUSHeader, ns2 + "ENTBUSDetail", nsmap=NSMAP)
print(etree.tostring(envelope, pretty_print=True))

rawDescription: lxml - XML Document with multiple NameSpaces

description: Lxml - XML Document with multiple NameSpaces


rawDescription: How to sort Pitch / Octave pairs

description: Sort Pitch / Octave pairs


code:
import pandas as pd

df_total.groupby(['name']).mean()
df_total.groupby(['name']).std()
df_total.groupby(['name']).apply(pd.isnull).sum() / df_total.groupBy(['name']).size()

rawDescription: Python - Summary Statistics using date and name


code:
entry = "1      0    0    7     1    1    2    3    4    5    6     0"
elems = entry.split()

string_id = 'c' + str(elems[4]) + 'x' + str(elems[6]) + 'e' + str(elems[7]) + 's' + str(elems[8]) + 'n' + str(elems[9])  # 'c1x2e3s4n5'

print(string_id)  # '12345'

rawDescription: Fastest Way in Python to Parse Space-delimited Numbers


code:
a = [[1,2,3],[4,5,6],[7,8,9]]
ar = array(a)

import csv

fl = open('filename.csv', 'w')

writer = csv.writer(fl)
writer.writerow(['label1', 'label2', 'label3']) #if needed
for values in ar:
    writer.writerow(values)

fl.close()

rawDescription: how to write python array (data = []) to excel?

description: Write python array (data = []) to excel


code:
#!/usr/bin/env python3

import sys

def create_apache_vhost(*args, **kwargs):
    pass

def create_lighty_vhost(*args, **kwargs):
    pass

def main(argv):
        import argparse

        parser = argparse.ArgumentParser(description="Some server",
                                         formatter_class=argparse.RawDescriptionHelpFormatter)

        parser.add_argument('--username', type=str)
        parser.add_argument('-u', dest='username', type=str)

        parser.add_argument('--apache', dest='httpd', action='store_const', const='apache')
        parser.add_argument('-a',       dest='httpd', action='store_const', const='apache')
        parser.add_argument('--lighthttpd', dest='httpd', action='store_const', const='lighthttpd')
        parser.add_argument('-l',           dest='httpd', action='store_const', const='lighthttpd')

        parser.add_argument('--domain', type=str)
        parser.add_argument('--vhost',  type=str)
        parser.add_argument('-v', dest='domain', type=str)

        parser.add_argument('--dir', dest='directory', type=str)
        parser.add_argument('-d', dest='directory', type=str)

        defaults = {
            'httpd': 'apache',
            }
        parser.set_defaults(**defaults)

        args = parser.parse_args(args=argv)

        print(args)

        if args.httpd == 'apache':
                create_apache_vhost(args.domain, args.directory, args.username)
        elif args.httpd == 'lighttpd':
                create_lighty_vhost(args.domain, args.directory, args.username)

if __name__ == '__main__':
        main(sys.argv[1:])

rawDescription: parse command line arguments not reading all arguments?

description: Parse command line arguments not reading all arguments


code:
import itertools
firms = [Firm_loc('Firm_type_0') for i in range(5)]
other_firms = [Firm_loc('Firm_type_1') for i in range(5)]
distances = [i.distance(j) for i, j in itertools.product(firms, other_firms)]

rawDescription: Python: Using OOP and accessing methods (self, other)


code:
class PhoneForm(forms.ModelForm):
    class Meta:
        model = Phone

class ContractForm(forms.ModelForm):
    class Meta:
        model = Contract
        exclude = ('phone',)

def add(request):
   ...
   if request.method == 'POST':
       phone_form = PhoneForm(request.POST)
       contract_form = ContractForm(request.POST)
       if phone_form.is_valid() and contract_form.is_valid():
           phone = phone_form.save()
           contract = contract_form.save(commit=False)
           contract.phone = phone
           contract.save()
   ...

rawDescription: How do I make a form that creates a new related model object that is to be used on that same form?

description: Make a form that creates a new related model object that is to be used on that same form


code:
from reportlab.platypus import Image

class HyperlinkedImage(Image, object):

    # The only variable I added to __init__() is hyperlink. I default it to None for the if statement I use later.
    def __init__(self, filename, hyperlink=None, width=None, height=None, kind='direct', mask='auto', lazy=1):
        super(HyperlinkedImage, self).__init__(filename, width, height, kind, mask, lazy)
        self.hyperlink = hyperlink

    def drawOn(self, canvas, x, y, _sW=0):
        if self.hyperlink: # If a hyperlink is given, create a canvas.linkURL()
            x1 = self.hAlignAdjust(x, _sW) # This is basically adjusting the x coordinate according to the alignment given to the flowable (RIGHT, LEFT, CENTER)
            y1 = y
            x2 = x1 + self._width
            y2 = y1 + self._height
            canvas.linkURL(url=self.hyperlink, rect=(x1, y1, x2, y2), thickness=0, relative=1)
        super(HyperlinkedImage, self).drawOn(canvas, x, y, _sW)

rawDescription: Is it possible to get a Flowable's coordinate position once it's rendered using ReportLab.platypus?


code:
import numpy as np
a = np.array([[1],[2],[3],[4]])
b = np.eye(1, 4)
b
c = a * b
c

rawDescription: python matrix operation with numpy

description: Python matrix operation with numpy


code:
for aa in all_firm:
    r = open (aa,'r+')
    lines = r.readlines()
    r.close()
    w = open (aa,'w')
    for bb in lines:
        raw = nltk.clean_html(bb)
        raw2=str(raw)
        w.write(low_firm)

rawDescription: Python: Writing File after modifying contents


code:
def update_inv(inv1, inv2):
    """
    update inv1 dict with inv2 dict
    """
    for k,v in inv2.items():
        if k in inv1:
            inv1[k] += inv2[k]
        else:
            inv1[k] = inv2[k]

update_inv(char['inv'], goblin['inv'])

rawDescription: Python - Text Based RPG inventory system using dictionary


code:
def halfTuple(oldTuple):
    return tuple(x * 0.5 for x in oldTuple)

rawDescription: How do I halve each item in a tuple quickly?

description: Halve each item in a tuple quickly


code:
class MyModelForm(forms.ModelForm):
    class Meta:
         model = FirstClass
         exclude = ('SecondClass',)

# urls.py
(r'^foo/(?P<object_id>\d+)/$','django.views.generic.create_update.update_object',
                                                 {'form_class': MyModelForm})

rawDescription: Update only some field with create_update.update_object


code:
#!/usr/bin/env python
import argparse, daemon, os
from flup.server.fcgi import WSGIServer
from fwd_msg import app

SOCKET_LOCATION = '/tmp/fingerprinter-fcgi.sock'

def main():
    app = flask.Flask(__name__)
    @app.route('/', methods=['GET'])
    def index():
        pass # your actions here

if __name__ == '__main__':
    # arg parse (and daemonize)
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('--daemon', action='store_true', default=False, help='Run as daemon')
    arg_parser.add_argument('--cwd', action='store', default='/',
                            help='Full path of the working directory to which the process should change on daemon start.')
    arg_parser.add_argument('--uid', action='store', type=int, default=os.getuid(),
        help='The user ID ("UID") value and group ID ("GID") value to switch the process to on daemon start.')
    args = vars(arg_parser.parse_args())

    if args['daemon']:
        context = daemon.DaemonContext(working_directory=args['cwd'], uid=args['uid'])
        with context:
            main()
    else:
        main()

rawDescription: When running nginx + python flask + python-daemon: upstream sent unsupported FastCGI protocol version 91


code:
import logging
import Queue
import threading
logger = logging.getLogger(__name__)
N = 100
sentinel = object()

def worker(jobs):
    name = threading.current_thread().name
    for task in iter(jobs.get, sentinel):
        logger.info(task)
    logger.info('Done')

def main():
    logging.basicConfig(level=logging.DEBUG,
                            format='[%(asctime)s %(threadName)s] %(message)s',
                            datefmt='%H:%M:%S')

    jobs = Queue.Queue()
    # put tasks in the jobs Queue
    for task in range(N):
        jobs.put(task)

    threads = [threading.Thread(target=worker, args=(jobs,))
               for thread_number in range (5)]
    for t in threads:
        t.start()
        jobs.put(sentinel)     # Send a sentinel to terminate worker
    for t in threads:
        t.join()

if __name__ == '__main__':
    main()

rawDescription: Execute Thread 5 by 5

description: Execute Thread 5 by 5


code: args, option_dict = ParseArguments(['', colCasaBasePath, "--default_partition="])

rawDescription: How to access Google App Engine's dev server data from the command line

description: Access Google App Engine's dev server data from the command line


code:
import numpy as np
from scipy.stats import nanmean
s = np.array([[1.0, 2.0, 3.0], [5.0, np.nan, 7.0], [np.nan, 4.0, 2.0]])

In [4]: nanmean(s)
Out[4]: array([ 3.,  3.,  4.])

rawDescription: Pointwise array average ignoring NaN

description: Pointwise array average ignoring NaN


code:
class MyCycle(object):
    def __init__(self, lst):
        self.list = lst

    def __iter__(self):
        while True:
            items_left = False
            for x in self.list:
                if x is not None:
                    items_left = True
                    yield x
            if not items_left:
                return

    def remove(self, e):
        self.list[self.list.index(e)] = None

rawDescription: cycle with possibility to remove elements

description: Cycle with possibility to remove elements


code: data.pivot('index', 'col', 'data')

rawDescription: make the values in a column being rownames

description: Make the values in a column being rownames


code:
from collections import OrderedDict

ol = [('n2', 9), ('n1', 3)]
dc = OrderedDict(ol)
dc

rawDescription: rebuilt a dictionary in python after reversing the order using a list

description: Rebuilt a dictionary in python after reversing the order using a list


code:
from datetime import datetime, timedelta

date = datetime(1904,1,1) # January 1st, 1904 at midnight

delta = timedelta(seconds = 10000000)

newdate = date + delta

rawDescription: How can I convert a time that is a number of seconds from a date to the actual date? [Python]

description: Convert a time that is a number of seconds from a date to the actual date? [Python]


code: Blocked, Wall, Floor = range(3)

rawDescription: Python User-Defined Data Type

description: Python User-Defined Data Type


rawDescription: How to create the union of many sets using a generator expression?

description: Create the union of many sets using a generator expression


code:
import re
non_decimal = re.compile(r'[^\d.]+')
non_decimal.sub('', '12.34fe4e')

rawDescription: Strip all non-numeric characters (except for ".") from a string in Python


code:
light_vect = light_position - face_center_position
cam_vect = cam_position - face_center_position
halfangle_vect = (light_vect.normal() + cam_vect.normal()).normal()

rawDescription: Calculating a half vector from eye/camera vector and surface normal


code:
from rpy2.robjects.functions import SignatureTranslatedFunction
lattice = importr("lattice")
lattice.levelplot = SignatureTranslatedFunction(lattice.levelplot,
                                                init_prm_translate={'col_regions': 'col.regions'})
foo = lattice.levelplot(formula, data=df, col_regions=grayvector)

rawDescription: Problem setting lattice plot options using rpy2


code:
def set(module, device, state, logger, attributes=None):
    """ Set the state of the specified device"""
    try:
            acquire_lock(device)
    except:
            #state object doesn't exist yet
            pass
    try:
            state_object = StateTable.select().where(StateTable.device == device).get()
    except:
            state_object = StateTable()

    state_object.device = device
    state_object.state = state
    state_object.attributes = attributes
    state_object.lastChange = datetime.datetime.now()
    state_object.save()
    logger.debug("Setting state for", device, "with state", state, "and attributes", attributes)
    release_lock(device)
    logger.debug("SETTING MQTT STATE")
    attributes_mqtt = {"device" : device, "module" : module, "state" : state, "attributes" : json.loads(attributes)}
    logger.debug("MQTT:", attributes_mqtt)
    mqttc.publish("state", json.dumps(attributes_mqtt))

rawDescription: Objects inside functions not working. Banging my head against this one


code:
import re

t=re.search(r"(.+?)\\(.+)\\(.+)", reg)
t.groups()
('HKEY_LOCAL_MACHINE', 'SOFTWARE\\TT\\Tools\\SYS', 'exePath')

rawDescription: problem about split a string

description: Problem about split a string


code:
import matplotlib.pyplot as plt
import cartopy.crs as ccrs

ax = plt.axes(projection=ccrs.PlateCarree())
ax.set_global()
ax.coastlines()

# Define a transformation which takes latitude and longitude values,
# and returns pixel coordinates.
ll_to_pixel = ccrs.Geodetic()._as_mpl_transform(ax)

# We need to call draw to ensure that the axes location has been defined
# fully.
plt.draw()

# Now lets figure out the pixel coordinate of Sydney.
x_pix, y_pix = ll_to_pixel.transform_point([151.2111, -33.8600])

# We can even plot these pixel coordinates directly with matplotlib.
plt.plot(x_pix, y_pix, 'ob', markersize=25, transform=None)

plt.savefig('figure_1.png', dpi=plt.gcf().get_dpi())
plt.show()

rawDescription: cartopy country map with html area links

description: Cartopy country map with html area links


code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import cherrypy

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  }
}

class App:

  @cherrypy.expose
  def index(self):
    return '''<!DOCTYPE html>

        <title>CherryPy demo</title>

Send JSON

Send form

    '''

  @cherrypy.expose
  @cherrypy.tools.json_out()
  def formin(self, **kwargs):
    # You can just print a variable a see it in the terminal
    # where CherryPy is executed
    print(kwargs)
    # You would see
    # {
    #   'cars[1][year]': u'1998',
    #   'name': u'Bob',
    #   'cars[0][model]': u'Renault C15',
    #   'address': u'Springfield',
    #   'cars[0][year]': u'1965',
    #   'cars[1][model]': u'Ford Ka'
    # }
    return kwargs.items()

  @cherrypy.expose
  @cherrypy.tools.json_in()
  @cherrypy.tools.json_out()
  def jsonin(self):
    data = cherrypy.request.json # just the same structure
    return data.items()

if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

rawDescription: How to pass an array from AngularJS up python and store?

description: Pass an array from AngularJS up python and store


code:
u8s = myrawdata.view(np.uint8) # no copy, just change "shape"
comp = -u8s # or do you want np.invert(u8s) ?
bits = np.unpackbits(comp)

rawDescription: convert list of integers to list of two's complement bit representation using multiple cores

description: Convert list of integers to list of two's complement bit representation using multiple cores


code:
lut = range(256)  # initialize to an identity lut
lut[0]   = 2
lut[128] = 1
lut[255] = 0
Image.open(imgname).convert('L').point(lut).save(imgname)

rawDescription: How to save/convert and read image in python with defined values for colors

description: Save/convert and read image in python with defined values for colors


rawDescription: Copy columns of subarray in Numpy

description: Copy columns of subarray in Numpy


code:
def compare(a, b):
    for x, y in zip(a, b):
        if x == y:
            ...

rawDescription: How to compare individual characters in two strings in Python 3

description: Compare individual characters in two strings in Python 3


code:
def set_proxy(self, type_, host='localhost', port=8888, user='',
        password=''):
    """Set up proxy for FURTHER connections.

    :param type_: proxy type to use: \
        none/default/socks5/https/http.
    :param host: proxy server ip or host name.
    :param port: proxy port.
    """
    _types = {
        'default': QNetworkProxy.DefaultProxy,
        'none': QNetworkProxy.NoProxy,
        'socks5': QNetworkProxy.Socks5Proxy,
        'https': QNetworkProxy.HttpProxy,
        'http': QNetworkProxy.HttpCachingProxy
    }

    if type_ is None:
        type_ = 'none'
    type_ = type_.lower()
    if type_ in ['none', 'default']:
        self.manager.setProxy(QNetworkProxy(_types[type_]))
        return
    elif type_ in _types:
        proxy = QNetworkProxy(_types[type_], hostName=host, port=port,
            user=user, password=password)
        self.manager.setProxy(proxy)
    else:
        raise ValueError('Unsupported proxy type:' + type_ \
        + '\nsupported types are: none/socks5/http/https/default')

rawDescription: Ghost.py and proxy

description: Ghost.py and proxy


code:
class Superclass(object):
    @classmethod
    def get_instance(cls):
        #This should return an instance of subclass1 or subclass2
        return cls()

class Subclass1(Superclass):
    pass
class Subclass2(Superclass):
    pass

rawDescription: Instantiate subclass from superclass

description: Instantiate subclass from superclass


rawDescription: In Django, how do I filter where language column = "null"?


code:
class ADUser(object):
    numEmployees = 0
    def __init__(self):
        self.firstname = self.firstname() # returns a random name from a big list
        self.lastname = self.lastname()   # returns a random name from a big list
        self.fullname = self.firstname + " " + self.lastname
        ADUser.numEmployees += 1
        self.employeeid = ADUser.numEmployees

rawDescription: Incremental instance counters in class instances


code:
tabulate = dict(L)
f = tabulate.get

rawDescription: Python: fastest way to define a function using a list of 2-tuples


code:
Builder.load_string("""
#:import ListItemButton kivy.uix.listview.ListItemButton
#:import la kivy.adapters.listadapter

<ListViewModal>:
    size_hint: None, None
    size: 400, 400
    ListView:
        id: listview_modal
        size_hint: .8, .8
        adapter:
            la.ListAdapter(
            data=[s.strip() for s in open('/Users/zen/Dropbox/todo/todo.txt').readlines()],
            cls=ListItemButton,  ### use ListItemButton instead of Label
            selection_mode='single',
            allow_empty_selection=True)
""")

class ListViewModal(ModalView):
    def __init__(self, **kwargs):
        super(ListViewModal, self).__init__(**kwargs)
        ### Bind to `on_selection_change` here in `__init__`
        self.ids['listview_modal'].adapter.bind(on_selection_change=self.callback)

    ### in `__init__`, we don't have a parent yet, so we proxy the callback
    def callback(self, adapter):
        return self.parent.callback(adapter)

class MainView(GridLayout):
    '''Implementation of a simple list view that reads data from a file.
    '''

    def __init__(self, **kwargs):
        kwargs['cols'] = 2
        super(MainView, self).__init__(**kwargs)

        self.listview_modal = ListViewModal()
        self.add_widget(self.listview_modal)

        self.text_input = TextInput()  ### use `self.text_input` instead of `text_input`
        self.add_widget(self.text_input)

    def callback(self, adapter):
        self.text_input.text = adapter.selection[0].text  ### get `text` from the first selected item

rawDescription: Kivy: Binding a callback to SimpleListAdapter in kv


code:
list1 = [1,2,3]
list2 = [4,5,6]
list1.append(list2)
list1

rawDescription: Cannot append list to a list?

description: Cannot append list to a list


code: posts = Post.objects.filter(postreply__owner=self.request.user, postreply__accepted=True)

rawDescription: How to get all 'Post' objects where 'User' has replied?

description: Get all 'Post' objects where 'User' has replied


code:
duplicates = set()
found = set()
for item in source:
    if item in found:
        duplicates.add(item)
    else:
        found.add(item)

rawDescription: In Python, how do I take a list and reduce it to a list of duplicates?


code:
with open('somefile.txt', 'w') as fp:
  for i, s in enumerate(X):
    print >>fp, '%d. %s' % (i + 1, ' '.join(s))

rawDescription: print lists in a file in a special format in python

description: Print lists in a file in a special format in python


rawDescription: How to concatenate element-wise two lists in Python?

description: Concatenate element-wise two lists in Python


code:
import xlwt

def xlwt_res(result):
    workbook = xlwt.Workbook(encoding="utf-8")

    for key, value in result.items():
        worksheet = workbook.add_sheet(key)
        row = 0  # we assign 'col' later instead

        for line in value:
            # we're going to iterate over the line object
            # and write directly to a cell, incrementing the column id
            for col, cell in enumerate(line):
                worksheet.write(row, col, cell)  # writes the list contents just like xlsxwriter.write_row!
            row += 1

    workbook.save('filename.xls')

xlwt_res({'one': ["just one element"], 'two': ["that's a list", "did you know it"], 'three': ["let's", "have", "3"]})

rawDescription: python how to port from xlsxwriter to xlwt

description: Python how to port from xlsxwriter to xlwt


rawDescription: pandas frequency table histograms distribution fitting

description: Pandas frequency table histograms distribution fitting