code:
for line in fname:
    line = re.sub('[\(\)\{\}\'\'\,<>]','', line)
    line = re.sub(r"(\.\d)\d*_?\d*", r"\1", line, 1)
    fields = line.rstrip("\n").split()
    outfile.write('%s  %s  %s  %s  %s  %s\n' % (fields[0],fields[1],fields[2],fields[3],fields[4],(fields[5])))

rawDescription: How do I remove 2nd and rest digits after a period from column one of lines?

description: Remove 2nd and rest digits after a period from column one of lines


code:
import os
os.system("C:\path_to_python\python.exe C:\path_to_file\file.py")

rawDescription: Python script to run command line which starts python script with specific python version


code:
import itertools

fifties = [50 for i in range(5)]
twentyfives = [25 for i in range(10)]
tens = [10 for i in range(15)]
fives = [5 for i in range(20)]
bag = fifties + twentyfives + tens + fives
allcombinations = itertools.combinations(bag, 5)
less_than = [comb for comb in allcombinations if sum(comb) < 100]

rawDescription: Finding a Combination of Coins with dollar amount ceiling


code:
while running:
    DISPLAYSURF.fill((0, 0, 0)) # fill screen black

    for event in pygame.event.get():
        # handle events
        pass

    # I'm using 'key.get_pressed' here because using the KEYDOWN/KEYUP event
    # and a variable to track if a key is pressed totally sucks and people
    # should stop doing this :-)
    keys = pygame.key.get_pressed()
    if keys[pygame.K_UP]:
        # only draw image if K_UP is pressed.
        DISPLAYSURF.blit(arrow_left, (20, SCREEN_HEIGHT/2 - 28))

    pygame.display.flip()

rawDescription: make something while keypressed | python

description: Make something while keypressed | python


code:
import MyMod
obj = MyMod.MyClass(param1, param2)

rawDescription: Creating new instance objects

description: Creating new instance objects


code:
a = "username@102.1.1.2:/home/hello/there"
a.rpartition('/')[0]

rawDescription: How to remove a last word in the string in Python?

description: Remove a last word in the string in Python


code:
devices = []
network_name = "Data"
vnic_label = "pyvmomi sriov nic1"

content = si.content
vm = get_obj(content, [vim.VirtualMachine], vm_name)
nic = vim.vm.device.VirtualDeviceSpec()

# VM device
nic.operation = vim.vm.device.VirtualDeviceSpec.Operation.add
nic.device = vim.vm.device.VirtualSriovEthernetCard()
nic.device.addressType = 'assigned'
nic.device.key = 13016
nic.device.deviceInfo = vim.Description()
nic.device.deviceInfo.label = vnic_label
nic.device.deviceInfo.summary = network_name
nic.device.backing = vim.vm.device.VirtualEthernetCard.NetworkBackingInfo()
nic.device.backing.network = get_obj(content, [vim.Network], network_name)
nic.device.backing.deviceName = network_name
nic.device.backing.useAutoDetect = False
nic.device.connectable = vim.vm.device.VirtualDevice.ConnectInfo()
nic.device.connectable.startConnected = True
nic.device.connectable.allowGuestControl = True

nic.device.sriovBacking = vim.vm.device.VirtualSriovEthernetCard.SriovBackingInfo()
nic.device.sriovBacking.physicalFunctionBacking = vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
nic.device.sriovBacking.physicalFunctionBacking.id = '84:00.1'
nic.device.sriovBacking.virtualFunctionBacking = vim.vm.device.VirtualPCIPassthrough.DeviceBackingInfo()
nic.device.sriovBacking.virtualFunctionBacking.id = '84:11.1'

devices.append(nic)

vmconf = vim.vm.ConfigSpec(deviceChange=devices)
task = vm.ReconfigVM_Task(vmconf)

rawDescription: using pyVmomi to configure SRIOV on VM

description: Using pyVmomi to configure SRIOV on VM


code:
from collections import OrderedDict

class LimitedSizeDict(OrderedDict):
  def __init__(self, *args, **kwds):
    self.size_limit = kwds.pop("size_limit", None)
    OrderedDict.__init__(self, *args, **kwds)
    self._check_size_limit()

  def __setitem__(self, key, value):
    OrderedDict.__setitem__(self, key, value)
    self._check_size_limit()

  def _check_size_limit(self):
    if self.size_limit is not None:
      while len(self) > self.size_limit:
        self.popitem(last=False)

rawDescription: Limiting the size of a python dictionary


code: data = [row[0] for row in cursor.fetchall()]

rawDescription: Why is recordset result being returned in this way for Python database query?


code:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# simulate some artificial data
# ========================================
np.random.seed(0)
data1 = np.random.multivariate_normal([0,0], [[1,0.5],[0.5,1]], size=200)
data2 = np.random.multivariate_normal([0,0], [[1,-0.8],[-0.8,1]], size=100)

# both df1 and df2 have bivaraite normals, df1.size=200, df2.size=100
df1 = pd.DataFrame(data1, columns=['x1', 'y1'])
df2 = pd.DataFrame(data2, columns=['x2', 'y2'])

# plot
# ========================================
graph = sns.jointplot(x=df1.x1, y=df1.y1, color='r')

graph.x = df2.x2
graph.y = df2.y2
graph.plot_joint(plt.scatter, marker='x', c='b', s=50)

rawDescription: Plotting two distributions in seaborn.jointplot


code:
array = [{'id':'a','parent_id':'None'},{'id':'b','parent_id':'a'},{'id':'c','parent_id':'b'},{'id':'e','parent_id':'a'},{'id':'d','parent_id':'c'},{'id':'f','parent_id':'ZZZ'}]

def children_return(D,array):
    return filter(lambda Dict: D['id'] == Dict['parent_id'] ,array)

def offspring_return(D,array):
    offspring = []
    subli = children_return(D,array)
    offspring.extend(subli)
    for Dict in subli:
        sub = offspring_return(Dict,array)
        offspring.extend(sub)
    return offspring

print(offspring_return({'id':'a','parent_id':'None'},array))

rawDescription: How to filter an array for all dictionaries that are within the same family or hierarchy as a certain dictionary?

description: Filter an array for all dictionaries that are within the same family or hierarchy as a certain dictionary


code:
def literal_eval(node_or_string):
    """
    Safely evaluate an expression node or a string containing a Python
    expression.  The string or node provided may only consist of the following
    Python literal structures: strings, numbers, tuples, lists, dicts, booleans,
    and None.
    """
    _safe_names = {'None': None, 'True': True, 'False': False}
    if isinstance(node_or_string, basestring):
        node_or_string = parse(node_or_string, mode='eval')
    if isinstance(node_or_string, Expression):
        node_or_string = node_or_string.body
    def _convert(node):
        if isinstance(node, Str):
            return node.s
        elif isinstance(node, Num):
            return node.n
        elif isinstance(node, Tuple):
            return tuple(map(_convert, node.elts))
        elif isinstance(node, List):
            return list(map(_convert, node.elts))
        elif isinstance(node, Dict):
            return dict((_convert(k), _convert(v)) for k, v
                        in zip(node.keys, node.values))
        elif isinstance(node, Name):
            if node.id in _safe_names:
                return _safe_names[node.id]
        elif isinstance(node, BinOp) and \
             isinstance(node.op, (Add, Sub)) and \
             isinstance(node.right, Num) and \
             isinstance(node.right.n, complex) and \
             isinstance(node.left, Num) and \
             isinstance(node.left.n, (int, long, float)):
            left = node.left.n
            right = node.right.n
            if isinstance(node.op, Add):
                return left + right
            else:
                return left - right
        raise ValueError('malformed string')
    return _convert(node_or_string)

rawDescription: create a lambda function from a string **properly**

description: Create a lambda function from a string **properly**


code:
while True:
    answer = input("Create An Entry [Press 1] \nDisplay List [Press 2] \nEdit an Entry [Press 3] \nRemove Entry [Press 4] \nQuit [Press 5]")
    # collect information
    if answer == "1":
        firstname = input("What is the persons first name? ")
        names.append(firstname) # add data
    # Display Data
    elif answer == "2":
        print(names)
    # USER Quit
    elif answer == "5":
        exit() # Or just break

rawDescription: Python name project

description: Python name project


code:
string1 = "this is a string1."
string1.endswith('.')
string4 = "this is a string1?"
string4.endswith('.')

rawDescription: Check last matching character in a string


code: rotated = numpy.rot90(orignumpyarray,3)

rawDescription: Numpy image - rotate matrix 270 degrees

description: Numpy image - rotate matrix 270 degrees


rawDescription: Find substring from end to index of a delimiter in PYTHON


code:
import wx
import wx.lib.inspection

class MyRegion(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="My Region")
        b1=wx.BoxSizer(orient=wx.HORIZONTAL)
        b2=wx.BoxSizer(orient=wx.HORIZONTAL)

        d1 = wx.StaticText(self, label="hello world")
        b1.Add(d1)

        b1.AddStretchSpacer()  # <-- ADD THE SPACER HERE

        d2 = wx.StaticText(self, label="Measurement", style=wx.ALIGN_RIGHT)
        b1.Add(d2,
               flag=wx.ALIGN_RIGHT | wx.EXPAND)

        c1 = wx.StaticText(self, label="oh no world")
        b2.Add(c1)
        c2 = wx.StaticText(self, label="BIG BIG STRINNNNNNGGGGGGGGGGGGGGGGGGGGGGGGG",style=wx.ALIGN_RIGHT)
        b2.Add(c2,
           flag=wx.ALIGN_RIGHT| wx.EXPAND )

        sizer = wx.GridBagSizer()
        sizer.Add(item=b2, pos=(0,0), flag=wx.EXPAND)
        sizer.Add(item=b1, pos=(1,0), flag=wx.EXPAND)
        self.SetSizer(sizer)

if __name__ == "__main__":
    app = wx.App()
    frame = MyRegion(None)
    frame.Show()
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

rawDescription: wxPython: Aligning the elements within two boxsizers

description: WxPython: Aligning the elements within two boxsizers


rawDescription: Nested list comprehension equivalent

description: Nested list comprehension equivalent


code:
def hilite(string, status, bold):
    attr = []
    if status:
        # green
        attr.append('32')
    else:
        # red
        attr.append('31')
    if bold:
        attr.append('1')
    return '\x1b[%sm%s\x1b[0m' % (';'.join(attr), string)

rawDescription: Python | change text color in shell

description: Python | change text color in shell


rawDescription: Specifying digits (without decimal) in Python


code:
for i in areas:
  prob += dog_vars[i] >= min_dogs[i]
  prob += dog_vars[i] <= max_dogs[i]
  prob += cat_vars[i] >= min_cats[i]
  prob += cat_vars[i] <= max_cats[i]

rawDescription: PuLp: min and max thresholds for lpSum constraints


code:
with open('test.npz', 'wb') as testfile:
    header = {'TIME': 20, 'POSITION': 30}
    np.save(testfile, header)
    i = 0
    while i < 5:
         data = [i]*100 # generate row of data
         np.save(testfile, data) #append data to current file
         i += 1

rawDescription: Saving binary data to file row-by-row in python


code:
from Tkconstants import RIGHT, X
from Tkinter import Frame, Tk, Label, Entry, Button
import Tkinter

class App(Tk):

    def __init__(self):
        Tkinter.Tk.__init__(self)
        DAC_frame = Frame(self, width=180, height=240, bg="red")
        DAC_frame.pack(side=RIGHT)

        DAC_delete_label = Label(DAC_frame, text="Delete A Term:", bg="red")
        DAC_delete_label.pack(fill=X)

        DAC_delete_entry = Entry(DAC_frame)
        DAC_delete_entry.pack()

        DAC_delete = Button(DAC_frame, text="Delete Term",borderwidth=0, bg="red", activebackground="red")
        DAC_delete.pack()

        DAC_clear = Button(DAC_frame, text="Clear Dictionary",borderwidth=0, bg="red", activebackground="red")
        DAC_clear.pack()

ap = App()
ap.mainloop()

rawDescription: Widgets overriding their frame's background


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

theta = np.linspace(0, 2*np.pi, 16)
r = np.linspace(0, 1, 6)
x = np.cos(theta)[:,np.newaxis]*r
y = np.sin(theta)[:,np.newaxis]*r

quiveropts = dict(color='white', headlength=0, pivot='middle', scale=3,
    linewidth=.5, units='xy', width=.05, headwidth=1) # common options
f, (ax1, ax2) = plt.subplots(1,2, sharex=True, sharey=True)
ax1.quiver(x,y, -y, x, headaxislength=4.5, **quiveropts) # the default
ax2.quiver(x,y, -y, x, headaxislength=0, **quiveropts)

rawDescription: Python quiver plot without head

description: Python quiver plot without head


code:
from datetime import timedelta
from babel.dates import format_timedelta
delta = timedelta(days=6)
format_timedelta(delta, locale='en_US')
u'1 week'

rawDescription: Natural/Relative days in Python

description: Natural/Relative days in Python


code: [(sum(1 for _ in v), int(k)) for k,v in groupby(str(1223444556))]

rawDescription: more efficient use of itertools.groupby()

description: More efficient use of itertools.groupby()


code:
# view1
request.session['name1'] = male_results
request.session['userid1'] = male_pic_userid

# view2 (or elsewhere in view1)
male_results = request.session.get('name1')
male_pic_userid = request.session.get('userid1')

rawDescription: What is a more efficient way to pass variables from Template to View in Django?


rawDescription: Having trouble writing a url pattern in django


code:
con.execute_query('UPDATE tableA SET done=1 OUTPUT INSERTED.ID WHERE ID=(SELECT TOP(1) ID FROM tableA WHERE done=0)')
for row in con:
    #row['ID'] is exactly one ID where the done bit wasn't set, but now is.
    start_function(row['ID'])

rawDescription: Update and select in one operation in MSSQL


code:
import wx

class ValidationDemo(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Text Validation Tutorial")

        panel = wx.Panel(self)
        self.textOne = wx.TextCtrl(panel)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.textOne, 0, wx.ALL, 5)
        panel.SetSizer(sizer)

        self.Bind(wx.EVT_TEXT, self.OnTextType, self.textOne)

    def OnTextType(self, event):
        self.textOne.ChangeValue(unicode.upper(self.textOne.GetValue()))
        self.textOne.SetInsertionPointEnd()

# Run the program
if __name__ == "__main__":
    app = wx.App(False)
    frame = ValidationDemo()
    frame.Show()
    app.MainLoop()

rawDescription: How to convert alphabetic input in wx.TextCtrl to all capital letters?

description: Convert alphabetic input in wx.TextCtrl to all capital letters


code:
def CreateForm(for_model, request=None, instance=None, user=None):
    class _StateMachineBaseModelForm(ModelForm):
        class Meta:
            model = for_model
            exclude = ('societe',)

        def __init__(self, *args, **kwargs):
            super(_StateMachineBaseModelForm, self).__init__(*args, **kwargs)
            try:
                if user:
                    self.fields['banque'].queryset = Banque.objects.filter(pays=user.get_profile().societe.pays)
            except:
                pass

    if for_model: return _StateMachineBaseModelForm(request, instance=instance)

rawDescription: Django Dynamic Class

description: Django Dynamic Class


code:
class MyLayout(BoxLayout):
    def getPerson1Name(self):
        return App.get_running_app().person2.getName()

rawDescription: Kivy - How to make an object accessible from both Kv Language child widgets and Python widget's classes?


code:
class CConfigWindow(QtGui.QMainWindow):
    def __init__(self):
        super(CConfigWindow, self).__init__()
        self.setGeometry(200, 200, 800, 600)
        self.setWindowTitle("config")
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
        paneW = QtGui.QWidget()
        grid = QtGui.QGridLayout()
        paneW.setLayout(grid)
        tab = QtGui.QTabWidget(self)
        grid.addWidget(tab,0,0,1,5)

        hest2 = QtGui.QPushButton("Ok")
        hest2.clicked.connect(self.ok)
        grid.addWidget(hest2,1,0)

        hest2 = QtGui.QPushButton("Cancel")
        hest2.clicked.connect(self.cancel)
        grid.addWidget(hest2,1,1)

        hest2 = QtGui.QPushButton("Factory Defaults")
        hest2.clicked.connect(self.Reset)
        grid.addWidget(hest2,1,2)

        self.setCentralWidget(paneW)
        self.show()

        self.activateWindow()
        self.raise_()

    def Reset(self):
        pass
    def ok(self):
        self.close()

    def cancel(self):
        self.close()

    def closeEvent(self, event):
        event.accept()

self.crap = CConfigWindow()

rawDescription: Adjust position of items in QDialog

description: Adjust position of items in QDialog


code:
gender = ['male','male','female','male','female']

import matplotlib.pyplot as plt
from collections import Counter

c = Counter(gender)

men = c['male']
women = c['female']

bar_heights = (men, women)
x = (1, 2)

fig, ax = plt.subplots()
width = 0.4

ax.bar(x, bar_heights, width)

ax.set_xlim((0, 3))
ax.set_ylim((0, max(men, women)*1.1))

ax.set_xticks([i+width/2 for i in x])
ax.set_xticklabels(['male', 'female'])

plt.show()

rawDescription: Best way to plot categorical data

description: Plot categorical data


code:
#!/usr/bin/env python

#x=1.123
#y=2.123

pos = [1.123, 2.123]

with open('vars.txt','w') as f:
    f.write("%s %s" % (pos[0], pos[1]))
    #f.write("%s %s" % (x,y))

with open ('vars.txt', 'r') as myfile:
    position=myfile.read().split()

position = map(float, position)
# position = [1.123, 2.123]

rawDescription: How to write and read Python var from file

description: Write and read Python var from file


code:
arr = numpy.zeros((50,100,25))
arr.shape
new_arr = arr.reshape(5000,25)
new_arr.shape

rawDescription: How to flatten only some dimensions of a numpy array

description: Flatten only some dimensions of a numpy array


code:
class Spider(scrapy.Spider):

    name = 'spider'
    allowed_domains = ['domain.com']
    start_urls = ['url1', 'url2', ...]
    headers = ['id', 'name', 'description']

    def start_requests(self):
        for su in self.start_urls:
            yield Request('http://url.com%s' % su,
                        self.parse_pageNumber,
                        meta = {'su': su}
                          )

    def parse_pageNumber(self, response):
        pageNumber = response.xpath('get_page_number_expression')
        su = response.meta['su']
        for i in range(pageNumber):
                page = su + str(pageNumber)
                yield Request('http://url.com' % page,
                    self.parse_matches, meta={'page_number':str(pageNumber)})

    def parse_matches(self, response):
        pageNumber = response.meta['page_number']
        # do everything else

rawDescription: Return value from website using scrapy

description: Return value from website using scrapy


code:
gb_number = phonenumbers.parse("+447986123456")
cc = phonenumbers.region_code_for_number(gb_number)
cc
phonenumbers.parse("07986123456", cc)

rawDescription: Get matched region for a number in python's phonenumbers library


code:
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker

plt.plot(range(1000,11000,1000),range(10))

plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('%d cm'))
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%d cm'))

for txt in plt.gca().xaxis.get_majorticklabels():
    txt.set_rotation(90)

plt.tight_layout()
plt.show()

rawDescription: Set units to X-axis in matplotlib

description: Set units to X-axis in matplotlib


rawDescription: How do I fill NA values in multiple columns in pandas?

description: Fill NA values in multiple columns in pandas


code:
import pandas as pd
A = pd.Series([10,20,30])
B = pd.Series([2,5,5])
A/B

rawDescription: How to divide two columns of type `pandas.core.series.Series`?

description: Divide two columns of type `pandas.core.series.Series`


code:
import numpy as np
# Find out what shape your final array has (if you already know just hardcode these)
x_values = np.unique(X).size
y_values = np.unique(Y).size
img = np.reshape(Z, (x_values, y_values))

# Maybe you need to cast the dtype to fulfill png restrictions
#img = img.astype(np.uint) # alter it if needed

# Print image
from PIL import Image
Image.fromarray(img).save('filename.png')

rawDescription: Generate image data from three numpy arrays


code:
REGEXES = [
    (r'(?:(?P<doors>\d) Doors)', 'doors'),
    (r'.*(?P<transmission>Automatic|Manual)', 'transmission'),
]
FAILS = [(re.compile('^' + r[0], re.IGNORECASE), r[1]) for r in REGEXES]
MATCHER = re.compile('^' + ''.join([r[0] for r in REGEXES]), re.IGNORECASE)

# ... later ...

m = MATCHER.match(input)

if not m:
    working = input
    for r in FAILS:
        s = r[0].split(input)
        if len(s) > 1:
            working = s[-1]  # we use last group in the split
            continue
        # we have a problem here!!
        # we know the group (the regex and the label we gave it)
        # we can show the user what we're trying to match and against what
        return blah

# otherwise we can start working with m's groups.

rawDescription: Can I display where a Python regex matches up to?

description: Display where a Python regex matches up to


code:
min_length = 1
max_length = 30

# delays
delay = 100

# Speed of light
c_vaccum = 3e8

#Little class to keep our data in one place
class Lat:
    def __init__(self, filename, factor):
        self.filename = filename
        self.factor = factor
        self.file = open(filename, "w") #let the class open the file

#now our function needs only one parameter, neat!
def latcalc(lat):
    target_name = 0

    for length in range(min_length, max_length):
        if length < 2:
            target_name += (length / (lat.factor * c_vaccum)) #acces the class variable
        elif length == 2:
            target_name += delay
        else:
            target_name = target_name

        myline = "%s\t%s\n" % (length, target_name)
        lat.file.write(myline)

def create_lats():
    lats = []
    lats.append(Lat("file1.txt", 0.4))
    lats.append(Lat("file2.txt", 0.8))
    lats.append(Lat("file3.txt", 1))
    return lats

#loop over your lats created in create_lats
for lat in create_lats():
    latcalc(lat)
    lat.file.close() #close the file

rawDescription: passing files and values as parameter to a function in python

description: Passing files and values as parameter to a function in python


code:
from flask import Response, stream_with_context

return Response(stream_with_context(gen(text)))

rawDescription: Flask teardown_request happening before request sent


code:
from django.utils.functional import cached_property

class Personne(BaseModel):
    @cached_property
    def url_profile_picture(self):
        a = PersonnePhoto.objects.filter(personne=self,
                                         photo_type=PersonnePhoto.PHOTO_PROFIL)
        if len(a):
            a = reverse('url_public', kwargs={'path': a[0].photo})
        else:
            a = staticfiles.static('img/no-picture-yet.png')
        return a

rawDescription: Django: do I need to make a caching method?


code: [ip for ip, result in data['scan'].iteritems() if result['status']['state'] == 'up']

rawDescription: Getting Mobile Info connected in network using Python Nmap


code:
def appScan():
    os.system("system_profiler -xml SPApplicationsDataType > apps.xml")
    appList = plistlib.readPlist("apps.xml")
    output_str = 'Delimiters="^"\nstring50 string50\nName^Version\n'
    appDict = appList[0]['_items']
    for x in appDict:
        if 'version' in x:
           output_str = output_str + x['_name'] + "^" + x['version'] + "^"
        else:
           output_str = output_str + x['_name'] + "^" + "no version found" + "^"
    return output_str

proc = subprocess.Popen(["/opt/altiris/notification/inventory/lib/helpers/aex-     sendcustominv","-t","-"], shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
proc.communicate(input=appScan())

rawDescription: Pass python script output to another programs stdin


rawDescription: Python split string based on regex

description: Python split string based on regex


code:
threads = {}
for row in csv_f:
    # Populate already the list of processes
    processes.append(row[2])
    threads.setdefault(row[2], []).append(row)

rawDescription: How to add a list under a dictionary?

description: Add a list under a dictionary


code:
from threading import Thread
import requests
import time
import smtplib
def email_sender(input_message, email_to, client):
    ''' function to send email '''
    to = email_to
    gmail_user = 'email of sender account'
    gmail_pwd = 'password of sender account'
    smtpserver = smtplib.SMTP("smtp.gmail.com",587)
    smtpserver.ehlo()
    smtpserver.starttls()
    smtpserver.ehlo
    smtpserver.login(gmail_user, gmail_pwd)
    header = 'To:' + to + '\n' + 'From: ' + gmail_user + '\n' + 'Subject:site down! \n'
    input_message = input_message + client
    msg = header + input_message
    smtpserver.sendmail(gmail_user, to, msg)
    smtpserver.close()

rawDescription: Send email django from any host

description: Send email django from any host


code:
while True:
    chunk = fp.read(1)
    if chunk == '':
        break

rawDescription: Is there an already existing EOF character in python?


code: filtered_collection = From(some_collection).where("item.property > 10").select_many()

rawDescription: structured query language for JSON (in Python)

description: Structured query language for JSON (in Python)


code:
import requests
import json

searchTerm = 'parrot'
startIndex = '1'
key = ' Your API key here. '
cx = ' Your CSE ID:USER here. '
searchUrl = "https://www.googleapis.com/customsearch/v1?q=" + \
    searchTerm + "&start=" + startIndex + "&key=" + key + "&cx=" + cx + \
    "&searchType=image"
r = requests.get(searchUrl)
response = r.content.decode('utf-8')
result = json.loads(response)
print(searchUrl)
print(r)
print(result)

rawDescription: Search image on Google images with the new Custom Search API?


rawDescription: How to convert list into string without loop and join() in Python

description: Convert list into string without loop and join() in Python


code:
ldap_output_Emply_dict[result_affil[i][1]['uid'][0]] = [
    result_affil[i][1]['mail'][0],
    result_affil[i][1]['uconnPersonPrimaryAffiliation'][0],
    result_affil[i][1].get('eduPersonEntitlement', None)
]

rawDescription: In Python can i perform [if exists] inside the assignment of a key:value pair?


code:
import unittest
from unittest.mock import patch, MagicMock
import io
import sys

from Run import main

class MyTestCase(unittest.TestCase):

    #@patch('builtins.input', side_effects=['y','1'])
    @patch('builtins.input', MagicMock(side_effect=['y','1']))
    def test_output(self):
      saved_stdout = sys.stdout
      try:
          out = io.StringIO()
          sys.stdout = out
          main()
          output = out.getvalue().strip()
          self.assertIn("TEST", output)
          #I used equals to see if I am truly grabbing the stdout
          #self.assertEquals("TEST", output)
      finally:
          sys.stdout = saved_stdout

if __name__ == "__main__":
  unittest.main(verbosity=2)

rawDescription: Output is empty when mocking input in Python Unit Test


rawDescription: Read files in reverse till specific line (character) in Python


code:
from datetime import datetime
from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy, event

app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SECRET_KEY'] = 'super-secret'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///:memory:'
app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)

class Parent(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    version = db.Column(db.Integer)
    timestamp = db.Column(db.DateTime,
                          default=datetime.utcnow,
                          onupdate=datetime.utcnow)
    children = db.relationship('Child',
                             backref='parent',
                             lazy='dynamic',
                             cascade="all, delete-orphan")

class Child(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    version = db.Column(db.Integer)
    timestamp = db.Column(db.DateTime,
                          default=datetime.utcnow,
                          onupdate=datetime.utcnow)
    parent_id = db.Column(db.Integer, db.ForeignKey('parent.id'), nullable=False)

@event.listens_for(Parent.children, 'append')
@event.listens_for(Parent.children, 'remove')
def receive_append_or_remove(target, value, initiator):
    # Update when a child is added or removed
    target.timestamp = datetime.utcnow()

@event.listens_for(Child.version, 'set')
def receive_attribute_change(target, value, oldvalue, initiator):
    # Update when a child's "version" attribute is set
    if target.parent:
        target.parent.timestamp = datetime.utcnow()

def render_html():
    _html = ""
    parents = Parent.query.all()
    for parent in parents:
        _html += "
Parent : {version}; Timestamp: {timestamp}
".format(version=parent.version, timestamp=parent.timestamp)
        _html += "
"
        for child in parent.children:
            _html += "
Child : {version}; Timestamp: {timestamp}
".format(version=child.version, timestamp=child.timestamp)
        _html += "
"
    return _html

@app.route('/')
def index():
    return render_html()

@app.route('/insert_child/')
def insert_child():
    parent = Parent.query.first()
    child_version = parent.children.count() + 1
    child = Child(version=child_version, parent=parent)
    db.session.add(child)
    db.session.commit()
    return render_html()

@app.route('/delete_child/')
def delete_child():
    parent = Parent.query.first()
    if parent.children.count() > 0:
        last_child = parent.children[-1]
        parent.children.remove(last_child)
        db.session.commit()
    return render_html()

@app.route('/update_child/')
def update_child():
    parent = Parent.query.first()
    first_child = parent.children[0]
    first_child.version += 1
    db.session.commit()
    return render_html()

@app.before_first_request
def before_first_request():
    db.drop_all()
    db.create_all()

    parent = Parent(version=1)
    child = Child(version=1, parent=parent)
    db.session.add_all([parent, child])
    db.session.commit()

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

rawDescription: How to update parent table timestamp when child table is modified?

description: Update parent table timestamp when child table is modified


code:
x = range(1,10)
x
from math import log
map(log, x)

rawDescription: How to take the ln of a function in python?

description: Take the ln of a function in python


code:
import numpy as np

lons = [-97.9547, -97.9747, -97.4256]
lats = [35.5322, 35.864, 35.4111]
data = [2,2,2]

xs, ys = np.meshgrid(lons, lats)

dataMesh = np.empty_like(xs)
for i, j, d in zip(lons, lats, data):
    dataMesh[lons.index(i), lats.index(j)] = d

map = Basemap(llcrnrlon = -103.068237, llcrnrlat = 33.610045, urcrnrlon = -94.359076, urcrnrlat = 37.040928, resolution = 'i')

CS = map.contour(xs, ys, dataMesh)
map.drawstates()
plt.show()

rawDescription: Plotting Contours of Lat/Lon Based Values


code:
import numpy as np
import pandas as pd
index = np.arange(0, 10)
df = pd.DataFrame(index=index, columns=['foo', 'bar'])
df

rawDescription: How to delete all rows in a dataframe?

description: Delete all rows in a dataframe


code:
a = data['A']>0
b = data['B']>0
data.groupby([a,b]).count()

rawDescription: Is there a pythonic way to do a contingency table in Pandas?


code:
import urllib
from bs4 import BeautifulSoup

headers = {
    'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Origin': 'http://www.indiapost.gov.in',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko)  Chrome/24.0.1312.57 Safari/537.17',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Referer': 'http://www.indiapost.gov.in/pin/',
    'Accept-Encoding': 'gzip,deflate,sdch',
    'Accept-Language': 'en-US,en;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
}

class MyOpener(urllib.FancyURLopener):
    version = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17'

myopener = MyOpener()
url = 'http://www.indiapost.gov.in/pin/'
# first HTTP request without form data
f = myopener.open(url)
soup = BeautifulSoup(f)
# parse and retrieve two vital form values
viewstate = soup.select("#__VIEWSTATE")[0]['value']
eventvalidation = soup.select("#__EVENTVALIDATION")[0]['value']

formData = (
    ('__EVENTVALIDATION', eventvalidation),
    ('__VIEWSTATE', viewstate),
    ('__VIEWSTATEENCRYPTED',''),
    ('txt_offname', ''),
    ('ddl_dist', '0'),
    ('txt_dist_on', ''),
    ('ddl_state','1'),
    ('btn_state', 'Search'),
    ('txt_stateon', ''),
    ('hdn_tabchoice', '1'),
    ('search_on', 'Search'),
)

encodedFields = urllib.urlencode(formData)
# second HTTP request with form data
f = myopener.open(url, encodedFields)

try:
    # actually we'd better use BeautifulSoup once again to
    # retrieve results(instead of writing out the whole HTML file)
    # Besides, since the result is split into multipages,
    # we need send more HTTP requests
    fout = open('tmp.html', 'w')
except:
    print('Could not open output file\n')
fout.writelines(f.readlines())
fout.close()

rawDescription: post request using python to asp.net page

description: Post request using python to asp.net page


code: l = [x*x for x in range(0, 10)]

rawDescription: Appending data into an undeclared list

description: Appending data into an undeclared list


code:
from os.path import splitext

test = '<name>-<gender>-<age>.jpg'

fname, ext = splitext(test) # works with names like 'xxx.yyy.jpg'
if ext in ('.jpg', '.jpeg'):
    name, gender, age = (fname.split('-') + [None, None])[:3]

rawDescription: In Python Regular Expressions, how can I disregard an expression inside a captured group?


rawDescription: Flask-SQLAlchemy query with negative condition on filter


code:
nodes = points3d(x,y,z)
nodes.glyph.scale_mode = 'scale_by_vector'

#this sets the vectors to be a 3x5000 vector showing some random scalars
nodes.mlab_source.dataset.point_data.vectors = np.tile( np.random.random((5000,)), (3,1))

nodes.mlab_source.dataset.point_data.scalars = np.random.random((5000,))

rawDescription: Mayavi points3d with different size and colors


code: results = SourceBusiness.objects.filter(resultbusiness__isnull=False).distinct().values_list('source', flat=True)

rawDescription: Django - is it possible to quickly code this query through Django's models?


code:
def RecursiveProcess(ListIn2, target): #Recursive function that adds to target value the value to its right
    if target > -1:  #stop function if index is below 0
        ListIn2[target] = ListIn2[target] + ListIn2[target+1]  #Add value to the right of target to the target value
        return RecursiveProcess(ListIn2, target-1) #Call the function again with lower taget value to process the next value
    else:
        return ListIn2  #return the changed list

l = [5, 10, 11, 6, 7, 1, 2, 4, 6, 7]
d = RecursiveProcess(l, len(l)-2)
print(d) # [59, 54, 44, 33, 27, 20, 19, 17, 13, 7]

rawDescription: Python recursive function doesn't return


code:
def wheelEvent(self, event):
    oldscale = self.scale
    self.scale += event.delta() / 1200.0
    if (self.scale < 0.1):
        self.scale = oldscale

    screenpoint = self.mapFromGlobal(QtGui.QCursor.pos())
    dx, dy = screenpoint.x(), screenpoint.y()
    oldpoint = (screenpoint.x() + self.position[0], screenpoint.y() + self.position[1])
    newpoint = (oldpoint[0] * (self.scale/oldscale),
                oldpoint[1] * (self.scale/oldscale))
    self.position = (newpoint[0] - dx, newpoint[1] - dy)

rawDescription: Controlling the pan (to anchor a point) when zooming into an image


code:
def change(l):
    x = ['some other list', 3, 4, 5]
    l[:] = x

rawDescription: Python: overwrite a list passed as an argument, with changes visible to the outer scope


code:
def printy(v):
    for x, y in v:
        print('Original index:', x, ', original element:', y)

# Original list
a = [1, 2, 2, 4, 4, 4, 5, 0]
with_original_indexes = tuple(zip(range(len(a)), a)) # or list()
with_original_indexes = tuple(enumerate(a)) # Equivalent to the above
printy(with_original_indexes)
printy(with_original_indexes[1:5])
printy(with_original_indexes[1:5][2:5])

rawDescription: How to obtain the original indexes from a sliced list in python?

description: Obtain the original indexes from a sliced list in python


code:
x = np.arange(1, 100, 0.1)
f = 2 * x # a simple function to see the results are good
f_int = scipy.interpolate.InterpolatedUnivariateSpline(x, f, k=2)
x = np.arange(25).reshape(5, 5) + 1
x
x_int = f_int(x.reshape(-1)).reshape(x.shape)
x_int

rawDescription: Using interpolate function over 2-D array


code:
def update(data):
  global grid
  newGrid = grid.copy()

  """
  do your updating. this needs to be done on a copy of 'grid' because you are
  updating element-by-element, and updates to previous rows/columns will
  affect the result at 'grid[i,j]' if you don't use a copy
  """

  # you do need to update the global 'grid' otherwise the simulation will
  # not progress, but there's no need to copy()
  mat.set_data(newGrid)
  grid = newGrid

  # # there's no reason why you couldn't do it in the opposite order
  # grid = newGrid
  # mat.set_data(grid)

  # at least in my version of matplotlib (1.2.1), the animation function must
  # return an iterable containing the updated artists, i.e. 'mat,' or '[mat]',
  # not 'mat'
  return [mat]

rawDescription: Python matplotlib - updating data during animation in Conway's Game of Life


rawDescription: Plot pandas data frame with year over year data


code:
class NdtvXoloNewsItem(CrawlSpider):
    name = "ndtvxolonews"
    allowed_domains = ["gadgets.ndtv.com"]
    start_urls = ["http://gadgets.ndtv.com/tags/xolo/articles"]
    rules = [Rule(LinkExtractor(allow=['http://gadgets.ndtv.com/tags/.*/page\-\d+']))]

rawDescription: Python RegEx - How do I form a regex that contains a hyphen inside a word


rawDescription: fast way to remove lowercase substrings from string?

description: Fast way to remove lowercase substrings from string


code:
import wx

class MyApp(wx.App):
    def __init__(self, redirect=False, filename=None):
        wx.App.__init__(self, redirect, filename)
        self.frame = wx.Frame(None, wx.ID_ANY, title='My Title')
        self.panel = wx.Panel(self.frame, wx.ID_ANY)
        b = wx.Button(self.panel, -1, "Toggle the read-only flag", (50,50))
        self.abc= wx.TextCtrl(self.panel, -1, "", (30, 70), size=(410,90), style=wx.TE_MULTILINE)

        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        self.cnt = 0
        self.frame.Show()

    def OnButton(self, evt):
        self.cnt += 1
        print(self.abc.IsEditable()) # for debugging
        self.abc.SetEditable((True, False)[self.cnt%2])

if __name__ == '__main__':
   app = MyApp()
   app.MainLoop()

rawDescription: how to set style of text ctrl in wxpython?

description: Set style of text ctrl in wxpython


code:
import pandas as pd

# Create an pandas excel writer based on xlsxwriter.
writer = pd.ExcelWriter('test.xlsx', engine='xlsxwriter')

# Create a worksheet with an empty dataframe so the sheet is empty.
df = pd.DataFrame()
df.to_excel(writer, sheet_name='Sheet1')

# Access the underlying xlsxwriter worksheet and write to it.
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
worksheet.write(0, 0, 'test')

# Create another dataframe with data.
df = pd.DataFrame({'a': [1, 2, 3, 4],
                   'b': ['aa', 'bb', 'cc', 'dd']})

# Write the dataframe to another worksheet.
df.to_excel(writer, sheet_name='Sheet2')

writer.save()

rawDescription: Pandas: save dataframe to open Workbook

description: Pandas: save dataframe to open Workbook


code:
class mm(object):
    def __init__(self, **kwargs):
        for varname, value in kwargs.iteritems():
            setattr(self, varname, value)

rawDescription: Instantiating a class with an arbitrary number of attributes


code:
class MainWindow(wx.Frame):
    def __init__(self, parent, id, title, app):
        wx.Frame.__init__(self, parent, id, title)
        self.app = app
        #...

class CustomApp(wx.App):
    def __init__(self):
        wx.App.__init__(self)
        self.value = None

    def SetValue(self, value):
        self.value = value

    def GetValue(self):
        return self.value

app = CustomApp()
frm = MainWindow(None, wx.ID_ANY, "Main Window", app)
frm.Show()
app.MainLoop()

print(app.GetValue())

rawDescription: wxpython: return value from Mainloop

description: Wxpython: return value from Mainloop


code:
for line in file:
    line = line.lower()

    if 'my string' in line:
        print ('found my string in the file')

rawDescription: string.find() aways evaluate to true

description: String.find() aways evaluate to true


code:
strs="some text Total Cost: 37 some more more Total Cost: -100"
re.findall(r"Total Cost:\s?([-+]?\d+)",strs)

rawDescription: How to match a specific word from the beginning of a sentence and get the unmatched part in Python?

description: Match a specific word from the beginning of a sentence and get the unmatched part in Python


code:
from flask import Flask
import time

@app.route('/api/<seconds>')
def api_seconds(seconds):
    currenttime = int(round(time.time() * 1000))

    milliseconds = int(seconds) * 1000
    finaltime = int(currenttime + milliseconds)
    return 'Seconds: ' + seconds + '
' + 'Milliseconds: ' + str(milliseconds) + \
       '
' + 'Time: ' + str(currenttime) + '
' + 'Final Time: ' + str(finaltime)

rawDescription: current time using time.time() doesn't change on refresh [Python]

description: Current time using time.time() doesn't change on refresh [Python]


code:
from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

i = grouper(3,range(100))
i.next()
(0, 1, 2)

rawDescription: idiomatic way to take groups of n items from a list in Python?

description: Idiomatic way to take groups of n items from a list in Python


code:
dirOpts = { 'initialdir': '/', 'mustexist': True, 'title': 'MyFileDialog' }
dirName = tkFileDialog.askdirectory(**dirOpts)

rawDescription: Getting a path from the User with Tkinter


code:
def image_download(self, links):
    for each in links:
        url = each
        name = each.split('/')[-1]
        r = requests.get(url, stream=True)
        with open(name, 'wb') as f:
            for chunk in r.iter_content(1024):
                if not chunk:
                    break

                f.write(chunk) #This has been indented to be in the for loop.

rawDescription: Python image scraper works when run alone but not when called from somewhere else


code:
import tkinter as tk
from tkinter import ttk

def OnDoubleClick(event):
    item = tree.selection()
    print('item:', item)
    print('event:', event)
    item = tree.selection()[0]

    print("you clicked on", tree.item(item,"text"))

root = tk.Tk()
tree = ttk.Treeview()
tree.pack()

for i in range(10):
    tree.insert("", "end", text="Item %s" % i)

#tree.bind("<Double-1>", OnDoubleClick) # double click
#tree.bind("<Button-1>", OnDoubleClick) # single click
tree.bind("<<TreeviewSelect>>", OnDoubleClick) # single click, without "index out of range" error

root.mainloop()

rawDescription: How to make a ttk treeview row/item act as a button?

description: Make a ttk treeview row/item act as a button


rawDescription: How to Split Multiple Arrays Simultaneously

description: Split Multiple Arrays Simultaneously


code:
result = db((db.company.location.belongs(locations)) &
            (db.company.emp_id.belongs(employee_ids)) &
            (db.company.type.belongs(types))).select(db.company.id, db.company.name)

rawDescription: How can I optimize DAL web2py query?

description: Optimize DAL web2py query


code: {(i, j) for i, j in diof if i > 0 and j > 0}

rawDescription: How can I declare natural symbols with sympy?

description: Declare natural symbols with sympy


code:
text = '"motor 1" "12.345 " "motor2" 80 "sonar 8" "Pin 11 On"'
import shlex
shlex.split(text)
[item.replace(' ','') for item in shlex.split(text)]
' '.join([item.replace(' ','') for item in shlex.split(text)])

rawDescription: How to I parse problematic strings

description: I parse problematic strings


code:
from sklearn.datasets import load_iris
from sklearn.cluster import KMeans
iris = load_iris()
km = KMeans(3).fit(iris.data)
km.inertia_

rawDescription: Distortion function from K Means of Scikit-Learn


code:
class Node:

    def __init__(self):
        self.pred = set()
        self.suce = set()

    def addSucessor(self, node):
        self.suce.add(node)
        node.pred.add(self)

rawDescription: Directed graph nodes: Keep track of successors and predecessors


code:
common_words = frozenset(("if", "but", "and", "the", "when", "use", "to", "for"))
title = "When to use Python for web applications"
title_words = set(title.lower().split())
keywords = title_words.difference(common_words)
print(keywords)

rawDescription: How to efficiently filter a string against a long list of words in Python/Django?

description: Efficiently filter a string against a long list of words in Python/Django


code:
List2 = {' '.join(x) for x in List2}
isct = set(List1) & List2

rawDescription: Comparison of bigrams between lists

description: Comparison of bigrams between lists


code:
#Add QApplication on top #################
from PyQt4.QtGui import QApplication
##########################################
def on_pushButton_clicked(self):
        '''
            Simulate some long process to be performed.
            Before Long Process starts, show an oscillating progress bar to
            indiate process is running in background.
        '''
        dialog = QtGui.QDialog()
        progressBar = Ui_porcessProgress()
        progressBar.setupUi(dialog)
        dialog.show()
        #dialog.exec_()

        start = time.time()
        diff = 0
        while diff < 10:
            end = time.time()
            diff = end - start

            ###################################################
            #add routine to update progressBar value
            progressBar.porcessProgressBar.setValue(diff)
            QApplication.processEvents()
            #add routine to update progressBar value
            ###################################################

            print (diff)

class Ui_porcessProgress(object):
    def setupUi(self, porcessProgress):
        porcessProgress.setObjectName(_fromUtf8("porcessProgress"))
        porcessProgress.setWindowModality(QtCore.Qt.ApplicationModal)
        porcessProgress.resize(329, 81)
        porcessProgress.setMinimumSize(QtCore.QSize(329, 81))
        porcessProgress.setMaximumSize(QtCore.QSize(329, 81))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/WFT/wftlogo2.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        porcessProgress.setWindowIcon(icon)
        porcessProgress.setModal(True)
        self.verticalLayout = QtGui.QVBoxLayout(porcessProgress)
        self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
        self.label = QtGui.QLabel(porcessProgress)
        self.label.setObjectName(_fromUtf8("label"))
        self.verticalLayout.addWidget(self.label)
        self.porcessProgressBar = QtGui.QProgressBar(porcessProgress)

        ###########################################
        ####Set max value of progress bar
        self.porcessProgressBar.setMaximum(10)
        ############################################

        self.porcessProgressBar.setProperty("value", 10)
        self.porcessProgressBar.setTextVisible(False)
        self.porcessProgressBar.setObjectName(_fromUtf8("porcessProgressBar"))
        self.verticalLayout.addWidget(self.porcessProgressBar)
        porcessProgress.setWindowTitle(QtGui.QApplication.translate("porcessProgress", "Please wait...", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("porcessProgress", "Time History data extraction from ODB file in progress...", None, QtGui.QApplication.UnicodeUTF8))
        QtCore.QMetaObject.connectSlotsByName(porcessProgress)
#
#------------------------------------------------------------------------------

rawDescription: Progress Bar issues in PyQt4

description: Progress Bar issues in PyQt4


code: x = hash(frozenset([a, b]))

rawDescription: Get Unique value "Hashcode" from a Set

description: Get Unique value "Hashcode" from a Set


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

def main():
    with open('C:\\Temp\\001.txt', 'r') as fileopening, \
    open('C:\\Temp\\002.txt', 'w') as fileTarget:
        for line in fileopening:
            if 'printing' in line and '$' not in line:
                lineInfo = line.split('"')
                lineInfo[0] += '("'
                if line.endswith(','):
                    lineInfo[-2] += '", '
                    lineInfo[-1] = 'shell=" ")'
                else:
                    lineInfo[-2] += '")'
                line = ''.join(lineInfo)

            elif 'printing' in line and '$' in line:
                lineInfo = line.split('"')
                lineInfo[0] += '("'
                lineInfo[1] += '")'
                lineInfo[-2] = '"'+lineInfo[-2]+'"'
                line = ''.join(lineInfo)
            fileTarget.write(line)

main()

rawDescription: Replace one part of strings based on its another part


code:
def is_broadcastable(shp1, shp2):
    for a, b in zip(shp1[::-1], shp2[::-1]):
        if a == 1 or b == 1 or a == b:
            pass
        else:
            return False
    return True

rawDescription: Test if an array is broadcastable to a shape?


code:
def start_requests(self):
    yield Request('http://a.com', self.parse_a)
    yield Request('http://b.com', self.parse_b)
    yield Request('http://c.com', self.parse_data)

def parse_a(self, response):
    links = LinkExtractor(
        # ... extract links from http://a.com
    ).extract_links(response)
    return (Request(url=link.url, callback=self.parse_data) for link in links)

def parse_b(self, response):
    links = LinkExtractor(
        # ... extract links from http://b.com
    ).extract_links(response)
    return (Request(url=link.url, callback=self.parse_data) for link in links)

rawDescription: How to apply different rules for different start_urls in python scrapy?

description: Apply different rules for different start_urls in python scrapy


code:
def get_brand_count(filename, brand):
    return int(subprocess.check_output('''zcat %s |  '''
                                       '''awk 'BEGIN {FS=";"};{print $6}' | '''
                                       '''grep -i %r | wc -l''' %
                                       (filename, brand), shell=True))

brands = 'hummer', 'bmw', 'audi'
with open('results.csv', 'wb') as csvfile:
    csvwriter = csv.writer(csvfile)
    csvwriter.writerow(brands)  # csv header row (if desired)
    for myfilename in glob.iglob('*.gz'):
        csvwriter.writerow([get_brand_count(myfilename, brand)
                                for brand in brands])

rawDescription: python - how to write to a csv file while in a loop

description: Python - how to write to a csv file while in a loop


code:
delta = end_financial_month - from_day
return delta.days

rawDescription: how to convert months into days when using relativedelta?

description: Convert months into days when using relativedelta


code:
import matplotlib.pyplot as plt
#plot signals
plt.plot(y1, label = 'Signal 1')
plt.plot(y2, label = 'Signal 2')
#plot alignment
for i, j in matches:
    plt.plot((i, j), (y1[i], y2[j]), color = 'black')
plt.show()

rawDescription: How to plot a point-to-point alignment between two sequences of datapoints?

description: Plot a point-to-point alignment between two sequences of datapoints


code:
class Steamroller(object):

    def __eq__(self, other):
        return True

    __lt__ = __gt__ = __ge__ = __le__ = __ne__ = __eq__

def checkio(*dont, **care):
    return Steamroller()

rawDescription: Is it possible to redefine __eq__ function in __main__ from script?


rawDescription: How to loop over a queryset for instantiate all formset?

description: Loop over a queryset for instantiate all formset


rawDescription: Redirect using webapp2 to capture the URL parameters


rawDescription: Python Real Time Binning of data

description: Python Real Time Binning of data


code:
from pyramid.traversal import ResourceTreeTraverser as BaseResourceTreeTraverser

class ResourceTreeTraverser(BaseResourceTreeTraverser):
    VIEW_SELECTOR = "++"

from pyramid.config import Configurator
from pyramid.interfaces import ITraverser
from zope.interface import Interface

config = Configurator()
config.registry.registerAdapter(ResourceTreeTraverser, (Interface,), ITraverser)

rawDescription: Change the view prefix in pyramid traversal from "@@" to "+"


rawDescription: Setting sensitivity to specific Gtk3 MenuActions (python)


code:
import Tkinter,Tix

r=Tix.Tk()
p=Tkinter.PanedWindow(r)

f1=Tix.Frame(p)
l1=Tix.Listbox(f1)
l1.pack(side=Tix.LEFT, expand=Tix.YES, fill=Tix.BOTH)
p.add(f1)

f2=Tix.Frame(p)
l2=Tix.Listbox(f2)
l2.pack(side=Tix.LEFT, expand=Tix.YES, fill=Tix.BOTH)
p.add(f2)

p.pack(side=Tix.LEFT, expand=Tix.YES, fill=Tix.BOTH)
r.mainloop()

rawDescription: PanedWindow in module Tix

description: PanedWindow in module Tix


code:
def roundrobin_limited_nodupe(limit, *iterables):
    """A round-robin iterator duplicates removed and a limit.

        >>> list(roundrobin_limited_nodupe(6, 'ABC', 'DB', 'EFG'))
        ['A', 'D', 'E', 'B', 'F', 'C']  # only six elements, only one 'B'

    Notes:
      - Recipe credited to George Sakkis

    """
    pending = len(iterables)
    seen = set()  # keep track of what we've seen
    nexts = cycle(iter(it).next for it in iterables)
    while pending:
        try:
            for next in nexts:
                candidate = next()
                if candidate not in seen:  # only yield when it's new
                    seen.add(candidate)
                    yield candidate
                    limit -= 1
                    if limit == 0:
                        return
        except StopIteration:
            pending -= 1
            nexts = cycle(islice(nexts, pending))

rawDescription: python itertools round robin with no duplications

description: Python itertools round robin with no duplications


code:
import numpy as np
import seaborn as sns
from matplotlib.colors import ListedColormap

data = np.random.randint(-1, 2, (10,10)) # Random [-1, 0, 1] data
sns.heatmap(data, cmap=ListedColormap(['green', 'yellow', 'red']), annot=True)

rawDescription: Map value to specific colour in seaborn heatmap


rawDescription: How can one change the size of SVGFIG plots


code: l =  [ float(line) for line in open('file.txt') ]

rawDescription: Python: How to create a list out of txt with n lines?


code:
import numpy as np

def read_file(file_path, input_format="xyzb", desired_format="bxyz", delimiter=" "):
    usecols = [input_format.index(col) for col in desired_format]
    with open(file_path, "r") as inf:
        return np.loadtxt(inf, usecols=usecols, delimiter=delimiter)

rawDescription: text file parsing and importing permuted result

description: Text file parsing and importing permuted result


rawDescription: split a string by a delimiter in a context sensitive way

description: Split a string by a delimiter in a context sensitive way


rawDescription: Numpy - Replace a number with NaN

description: Numpy - Replace a number with NaN


code:
text = (text + '\n')*1000
fw.write(text)

rawDescription: Repeating contents of a file into another file using Python


code: [int(val) for val in x]

rawDescription: Converting matlab program to equivalent python code


code:
descItem = soup.find('div', attrs={'class': 'op_gd14 FL'}) # get the DIV
[s.extract() for s in descItem('a')]                       # remove <a> tags
return descItem.get_text()                                 # return the text

rawDescription: Removing particular content from result parces using beautifulsoup


code:
with open('/tmp/test.txt', 'w') as file:
    print(file)
    print(file.name)
# <_io.TextIOWrapper name='/tmp/test.txt' mode='w' encoding='UTF-8'>
# /tmp/test.txt

rawDescription: Python: Extracting data inside first set of quotes?


code:
import feedparser

d = feedparser.parse('http://pplware.sapo.pt/feed/')
updates = []
for i in range(10):
    updates.append({"url": d.entries[i].link, "msg": d.entries[i].summary + ", "})

rawDescription: Python and FeedParser question

description: Python and FeedParser question


code:
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = "http://example.com/"
password_mgr.add_password(None, top_level_url, 'user', 'password')
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(urllib2.HTTPHandler, handler)
request = urllib2.Request(url)

rawDescription: How to send a HTTP Header request rather than HTTP URL in Python

description: Send a HTTP Header request rather than HTTP URL in Python


rawDescription: Pandas - Create two columns - Simple, no?


code:
[(tag.text, urlparse.urljoin(url, tag['href']))
        for tag in soup.findAll('a', href=True)]

rawDescription: Create a list of tuples from list in python


code:
config = 'H/2'
config == 'H/2' or 'H' or '2H'
config == 'H/2' or config == 'H' or config == '2H'
config = 'H'
config == 'H/2' or 'H' or '2H'
config == 'H/2' or config == 'H' or config == '2H'
config = 'R'
config == 'H/2' or 'H' or '2H'
config == 'H/2' or config == 'H' or config == '2H'

rawDescription: Python, Conditionals - Are these equivalent?


code: return HttpResponseRedirect("/%s/" % topic.id)

rawDescription: How to render previous page after jQuery post in Django

description: Render previous page after jQuery post in Django


code:
import matplotlib.pyplot as plt
z = [[0,0,0], [1,0,0], [0,1,0], [1,1,0], [.5,.5,1]]
x, y, z = zip(*z)
cn = plt.tricontourf(x, y, z)
plt.show()

rawDescription: Python/MatPlotLib yield odd, unexpected contours


code:
_client = gdata.docs.client.DocsClient('My-Prety-App-v1')
# Set your prefered auth method
# ...
entry = _client.GetDoc('document:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX')
exportFormat = 'html'
content = _client.GetFileContent(uri=entry.content.src + '&exportFormat=' + exportFormat)
self.response.out.write(content)

rawDescription: Retrieving a GoogleDoc via API and generate a PDF replacing with own text


rawDescription: Pandas: use array index all values

description: Pandas: use array index all values


code:
import os
from glob import glob
from shutil import rmtree

path = os.getcwd()
pattern = os.path.join(path, "tin*")

for item in glob(pattern):
    if not os.path.isdir(item):
        continue
    rmtree(item)

rawDescription: How to delete directories starting with "tin" in Python?

description: Delete directories starting with "tin" in Python


code:
from collections import defaultdict
xx = defaultdict(list)
table=[{'device': 'a', 'iface': 'i1'}, {'device': 'a', 'iface': 'i2'}, {'device': 'a', 'iface': 'i4'}, {'device': 'b', 'iface': 'i5'}, {'device': 'a', 'iface': 'i3'}, {'device': 'b', 'iface': 'i7'}]
for tab in table:
  xx[tab['device']].append(tab['iface'])

xx
yy = dict(xx)
yy
new_table = []
for a in yy:
  new_table.append({'device': a, 'iface': yy[a]})

new_table

rawDescription: Python: How to group unsorted list of dictionary into new list


code:
with open(data_path("ref/block.png"), "rb") as f:
    as_png = f.read()
bm = BlockModel.from_png(as_png)
with open("my_schematic.schematic", "wb") as f:
    f.write(bm.schematic)

rawDescription: blockmodel: convert png to schematic

description: Blockmodel: convert png to schematic


code:
newVals = []
i = 0
while( i < len(X) and X[i][1] >= 0):
    newVals.append(X[i])
    i += 1

rawDescription: Python - Cutting an array at a designated point based on value in row


code:
g_signal_connect (timeline, "marker-reached::my-marker",
                  G_CALLBACK (on_my_marker_reached),
                  NULL);

rawDescription: Clutter - run method at marker?

description: Clutter - run method at marker


code:
def run_with_reloader(main_func, extra_files=None, interval=1,
                      reloader_type='auto'):
    """Run the given function in an independent python interpreter."""
    import signal
    reloader = reloader_loops[reloader_type](extra_files, interval)
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
    try:
        if os.environ.get('WERKZEUG_RUN_MAIN') == 'true':
            t = threading.Thread(target=main_func, args=())
            t.setDaemon(True)
            t.start()
            reloader.run()
        else:
            sys.exit(reloader.restart_with_reloader())
    except KeyboardInterrupt:
        pass

rawDescription: Handling atexit for multiple app objects with Flask dev server reloader


code:
def better_run(observer):
   try:
      observer.start()
      while True:      # instead of this infinite loop, you can do
         pass          # whatever processing you wanted
   except KeyboardInterrupt:
      observer.stop()

rawDescription: How to exit from a Python program using MacFSEvents using Ctrl-C

description: Exit from a Python program using MacFSEvents using Ctrl-C


code:
import numpy as NP
from scipy import polyval, polyfit
from matplotlib import pyplot as PLT

n=10   # 10 data points
# make up some data
x = NP.linspace(0, 1, n)
y = 7*x**2 - 5*x + 3
# add some noise
noise = NP.random.normal(.5, .3, 10)
y += noise

# the shape of the data suggests a 2d polynomial, so begin there
# a, b, c are the polynomial coefficients: ax^2 + bx + c
a, b, c = polyfit(x, y, 2)
y_pred = polyval([a, b, c], x)    # y_pred refers to predicted values of y

# how good is the fit?
# calculate MSE:
MSE = NP.sqrt( NP.sum((y_pred-y)**2)/10 )
# MSE = .2

# now use the model polynomial to generate y values based on x values outside
# the range of the original data:
x_out = NP.linspace(0, 2, 20)   # choose 20 points, 10 in, 10 outside original range
y_pred = polyval([a, b, c], x_out)

# now plot the original data points and the polynomial fit through them
fig = PLT.figure()
ax1 = fig.add_subplot(111)

ax1.plot(x, y, 'g.', x_out, y_pred, 'b-' )

PLT.show()

rawDescription: Extrapolation from data plotted using matplotlib


code: Info["City_Name"].update({"Population": 20000, "Population_Density": 200})

rawDescription: How to assign multiple values to multiple keys with a single command

description: Assign multiple values to multiple keys with a single command


code:
def make_nice_list(your_list):
   if len(your_list) == 0:
       return ''

   if len(your_list) == 1:
       return your_list[0]

   last = your_list.pop()
   return '%s and %s' % (', '.join(your_list), last)

rawDescription: How to use .join() using and

description: Use .join() using and


code:
from kivy.clock import Clock
class Test(GridLayout):
    def __init__(self, **kwargs):
        super(Test, self).__init__(**kwargs)
        Clock.schedule_once(self.update, 2)  # 2 is for 2 seconds
    def update(self, *args):
        self.clear_widgets()
        # then add some more widgets here

rawDescription: Print and clear output on screen with Kivy


code: #usrout { white-space: pre-wrap; }

rawDescription: Changing values in pre-formatted text using javascript


code: list_of_objects = [(i, i in A, i in B) for i in set(A) | set(B)]

rawDescription: Python create list of objects from multiple files showing intersection


code:
class A():
    def __init__(self):
        self.logger = Logger.get() #this works fine didn't include the Logger class

    def log(self):
        b = B(self.logger)

class B():
    def __init__(self, logger):  # pass the logger when instantiating B
        self.a = 'hello'

rawDescription: Calling an instance variable from a class that is inside of that class


code:
from django.contrib.auth.models import User
user_type = ContentType.objects.get_for_model(User)
user_type

rawDescription: How to create a `ContentType` model object through a model class in Django?

description: Create a `ContentType` model object through a model class in Django


code:
project
--templates
----admin
------base.html

rawDescription: Django CMS how do I add a CSS file to the admin


code:
from Tkinter import *

root = Tk()

left_outer = Frame(root, bd=1)
left_outer.pack(side=LEFT, fill=Y, pady=5, padx=5)
right_outer = Frame(root, bd=1)
right_outer.pack(side=LEFT, fill=Y, pady=5, padx=5)

left = Frame(left_outer, bd=2, relief=SUNKEN)
right = Frame(right_outer, bd=2, relief=SUNKEN)
left.pack(fill=Y)
right.pack(fill=Y)

t_start = Text(left, width=20, height=200)
t_start.pack(side=LEFT, fill=Y)
s_start = Scrollbar(left)
s_start.pack(side=RIGHT, fill=Y)
s_start.config(command=t_start.yview)
t_start.config(yscrollcommand=s_start.set)

t_end = Text(right, width=20, height=200)
t_end.pack(side=LEFT, fill=Y)
s_end = Scrollbar(right)
s_end.pack(side=RIGHT, fill=Y)
s_end.config(command=t_end.yview)
t_end.config(yscrollcommand=s_end.set)

root.geometry("400x200")
root.mainloop()

rawDescription: Python Tkinter setting an inactive border to a text box?


code:
a, b = [], []
with open('myfile', 'r') as f:
    for num, line in enumerate(f.readlines()):
        if num >= 10:
            b.push(line)
        else:
            a.push(line)

rawDescription: Problem configparser in python

description: Problem configparser in python


code:
def check_unique_elem(L):
    seen = set()
    for row in L:
        for i in row:
            if i in seen:
                return False
            seen.add(i)
    return True

rawDescription: how to check all items in a list/matrix are different in python

description: Check all items in a list/matrix are different in python


code:
def form_valid(self, form):
    messages.success(self.request, "Success", extra_tags='msg')
    return super(UserCreateView, self).form_valid(form)
    # ModelFormMixin will now save
    # FormMixin will now redirect to success_url()
    # override above behavior if you need to do something with the object

rawDescription: Problem with class based generic views in Django


code: d = {k: [] for k in keys}

rawDescription: Appending to dict of lists adds value to every key


rawDescription: how to change and save a matrix in another document in python?

description: Change and save a matrix in another document in python


code:
threads = []
for url in URLs:
    t = Thread(target = thread_func, args = (url, ))
    t.start()
    threads.append(t)

# All threads started, now wait for them to finish
for t in threads:
    t.join()

rawDescription: Improving performance of python multithreading for downloading webpages


code: m = re.search(r'\[Classification:\s*([^]]+)\]', line).group(1)

rawDescription: Regex in Python 2.7 for extraction of information from Snort log files


code:
records = zip(
    tree.xpath("/rss/channel/item/title/text()"),
    tree.xpath("/rss/channel/item/link/text()"),
    tree.xpath("/rss/channel/item/pubDate/text()")
)

# records => [
#    ('Klistermärkesuppsättning i Trollhättan',
#     'https://www.nordfront.se/klistermarkesuppsattning-trollhattan.smr',
#     'Mon, 02 Feb 2015 14:00:37 +0000'),
#    ('Dror Feiler vill inte betala sina böter – spelar judekortet',
#     'https://www.nordfront.se/dror-feiler-vill-inte-betala-sina-boter-spelar-judekortet.smr',
#     'Mon, 02 Feb 2015 12:45:27 +0000'),
#    ....
# ]

rawDescription: Merging xpath generated lists, Python, lxml


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

# Random r,g,b data similar to what you seem to be loading in....
data = np.random.random((30000, 3))

# Make data a 1 x size x 3 array
data = data[None, ...]

# Plotting using `imshow` instead of `bar` will be _much_ faster.
fig, ax = plt.subplots()
ax.imshow(data, interpolation='nearest', aspect='auto')
plt.show()

rawDescription: Matplotlib slow when plotting pre-cached data into many subplots


code:
import Params
__all__ = ["Params"]
from Params import *
__all__ += Params.__all__

rawDescription: Import classes in subpackages into main namespace with Python package


code: #define PyTuple_SET_ITEM(op, i, v) (((PyTupleObject*)(op))->ob_item[i] = v

rawDescription: Limitations of PyTuple_SetItem

description: Limitations of PyTuple_SetItem


rawDescription: How to convert this Python to C++ without overflow?

description: Convert this Python to C++ without overflow


code:
EVT_FOO =0x0001
EVT_BAR =0x0002
EVT_SPAM=0x0004
EVT_EGGS=0x0008

def getEvtName( val ):
    return next((i for i,j in globals().iteritems() if j==val and i.startswith(something)),None)

getEvtName(0x0001)

rawDescription: Convert numeric value in module to its variable name


code:
def test_something(self):
    self.assertEqual(self._mine.attribute, 'myAttribute')

rawDescription: How do I use the unittest setUpClass method()?

description: Use the unittest setUpClass method()


code:
def governor_lowest_avg_unemployment(g_db,unemployment_db):
    all_unemploy = {}
    lowest_avg = 1e99    # some huge number, obviously above max possible
    lowest_gov = None
    for  governor in g_db.keys():
        avg_unemploy = avg_unemployment_for_governor(g_db,unemployment_db, governor)
        if avg_unemploy==None:
            all_unemploy[governor]=0
        else:
            all_unemploy[governor] = avg_unemploy
            if avg_unemploy < lowest_avg:
                lowest_avg = avg_unemploy
                lowest_gov = governor
    return lowest_gov

rawDescription: Using a for loop to compare if current value is less than previous


code:
import configparser

config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path'])     # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/'    # update
config['DEFAULT']['default_message'] = 'Hey! help me!!'   # create

with open('FILE.INI', 'w') as configfile:    # save
    config.write(configfile)

rawDescription: how to read and write INI file with Python?

description: Read and write INI file with Python


code:
import sqlite3
conn = sqlite3.connect('database.db')
cursor = conn.cursor()

with open("...", "rb") as input_file:
    ablob = input_file.read()
    cursor.execute("INSERT INTO notes (id, file) VALUES(0, ?)", [sqlite3.Binary(ablob)])
    conn.commit()

with open("Output.bin", "wb") as output_file:
    cursor.execute("SELECT file FROM notes WHERE id = 0")
    ablob = cursor.fetchone()
    output_file.write(ablob[0])

cursor.close()
conn.close()

rawDescription: Writing blob from SQLite to file using Python


code:
html_str = """

Example Information

{}

""".format(wikipedia.summary("Julius Caesar", sentences=2))

rawDescription: Insert a variable into a string

description: Insert a variable into a string


code:
class YourView(DetailView):

    queryset = YourModel.objects.all()

    def get_object(self):
        object = super(YourView, self).get_object()
        object.views = object.views + 1
        object.save()
        return object

rawDescription: Django Generic List/Detail Class based views


rawDescription: RegEx Tokenizer to split a text into words, digits and punctuation marks


code:
def parser(lst):
    vars = []
    for obj in data: # did you mean "for obj in lst:"?
        if isinstance(obj,list):
            parser(obj)
        else:
            for string in obj:
                vars.append(o) # did you mean "vars.append(string)"?

rawDescription: Is there a way to append an integer to the end of a variable name in python


code:
class MyStream(object):

    @classmethod
    def from_file(cls, filepath, ignore_comments=False):
        with open(filepath, 'r') as fileobj:
            for obj in cls(fileobj, ignore_comments):
                yield obj

    @classmethod
    def from_socket(cls, socket, ignore_comments=False):
        raise NotImplemented # Placeholder until implemented

    def __init__(self, iterable, ignore_comments=False):
       ...

rawDescription: What's an example use case for a Python classmethod?


code:
d = {"x":2, "h":15, "a":2222}
it = iter(sorted(d.iteritems()))
it.next()
it.next()
it.next()

rawDescription: In Python, how do I iterate over a dictionary in sorted order?


code:
def fly_away(session, line_id):
  query = session.\
          query(
            Pilot.Id,
            Pilot.EntityId,
            Pilot.From,
          ).\
          outerjoin(CTower, Pilot.Id == CTower.Associate).\
          filter(Pilot.Id == line_id)
  return query

rawDescription: How to join 2 queries in Python

description: Join 2 queries in Python


code:
# 1
result = data.count(data[0]) > 1

# 2
it = iter(data)
result = it.next() in it

rawDescription: Taking list's tail in a Pythonic way?

description: Taking list's tail in a Pythonic way


code:
def reverseStr(s):
  return ' '.join([x[::-1] for x in s.split(' ')])

rawDescription: How do I reverse a string in place with Python

description: Reverse a string in place with Python


code:
import sys
from PySide import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)
        widget = QtGui.QWidget()
        self.edit = QtGui.QPlainTextEdit()
        QtCore.QObject.connect(self.edit, QtCore.SIGNAL('textChanged()'), self.handleTextChange)
        self.button = QtGui.QPushButton('Generate Report')
        self.button.setEnabled(False)
        layout = QtGui.QVBoxLayout(widget)
        layout.addWidget(self.edit)
        layout.addWidget(self.button)
        self.setCentralWidget(widget)

    @QtCore.Slot()
    def handleTextChange(self):
        self.button.setDisabled(self.edit.toPlainText() == '')

app = QtGui.QApplication(sys.argv)
main = MainWindow()
main.show()
sys.exit(app.exec_())

rawDescription: Python: How detect text in a plainTextEdit and only then enable a button?


code:
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib.pyplot as plt

mat = np.array([[1.0,  0.5,  0.0],
                [0.5,  1.0, -0.5],
                [1.0, -0.5,  0.5],
                [0.0,  0.5, -0.5]])

dist_mat = mat
linkage_matrix = linkage(dist_mat, "single")

plt.clf()

ddata = dendrogram(linkage_matrix,
                   color_threshold=1,
                   labels=["a", "b", "c", "d"])

# Assignment of colors to labels: 'a' is red, 'b' is green, etc.
label_colors = {'a': 'r', 'b': 'g', 'c': 'b', 'd': 'm'}

ax = plt.gca()
xlbls = ax.get_xmajorticklabels()
for lbl in xlbls:
    lbl.set_color(label_colors[lbl.get_text()])

plt.show()

rawDescription: Scipy dendrogram leaf label colours

description: Scipy dendrogram leaf label colours


code:
def get_values(self, env):
    class ValUsers(models.Model):
        name = models.TextField(max_length=64)
        value = models.TextField(max_length=2048)
    ret = EnvUsers.objects.raw(
        'SELECT a.id, a.name, v.value '
        ' FROM Authorization a, Value v '
        ' WHERE a.user_root = v.parent '
        '      and a.active = %s '
        '      and v.active = %s '
        '      and v.name = %s ',
        [True, True, env]
    )

    return {u.name: u.value for u in ret}

rawDescription: Span models in Django without a ForeignKey


code:
import numpy as np
from scipy.signal import convolve2d

kernel = np.ones((3,3))
kernel[1,1] = 0
print(kernel)
# Create a decent test array that shows the features
test = np.array(
    [[0,1,1,0,1,1],
     [1,1,1,1,1,0],
     [1,0,1,1,0,1],
     [1,1,1,0,0,0],
     [1,1,1,0,1,0],
     [1,1,1,0,0,0]])

mask = convolve2d(test, kernel, mode='same', fillvalue=1)
print(mask)
result = test.copy()
result[np.logical_and(mask==8, test==0)] = 1
print(result)

rawDescription: Removing pixels surrounded by white pixels OpenCV


code:
def itersorted(d):
    for key in sorted(d):
        yield d[key]

rawDescription: Sorting a dict on __iter__

description: Sorting a dict on __iter__


code:
with open('fileName', 'r') as file:
    first_line = file.readline()
    DoStuff_1(first_line)
    DoStuff_2(first_line)

    # remaining lines
    for line in file:
        DoStuff_2(line)

rawDescription: How to read first line of a file twice?

description: Read first line of a file twice


code:
mydates[0] - np.datetime64(datetime.date(2013,9,20))
mydates - np.datetime64(datetime.date(2013,9,20))

rawDescription: Convert existing datetime array to date

description: Convert existing datetime array to date


code:
with open(TEXT, 'rt') as f:
    dictionary = set(f.read().split())

rawDescription: How to remove duplicates from a read and split text file?

description: Remove duplicates from a read and split text file


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

N = 1000
x = np.linspace(0, 10, N)
y = x**2
ones = np.ones(N)

vals = [30, 20, 10] # Values to iterate over and add/subtract from y.

fig, ax = plt.subplots()

for i, val in enumerate(vals):
    alpha = 0.5*(i+1)/len(vals) # Modify the alpha value for each iteration.
    ax.fill_between(x, y+ones*val, y-ones*val, color='red', alpha=alpha)

ax.plot(x, y, color='red') # Plot the original signal

plt.show()

rawDescription: Making a Python Fan Chart / Fan Plot

description: Making a Python Fan Chart / Fan Plot


code:
def avg(A):
    if not A:
        return 0
    return sum(A) / len(A)

def SampleFunction(): # Example Function
    A = list(range(300))
    for i in range(300):
        if i%2:
            A[i] = 3.1*(i+1)**1.2 - 7.9*i
        else:
            A[i] = 4.2*(i+2)**.8 - 6.8*i
    return avg(A)     #Return the avg of A instead of just A

rawDescription: Use output of one function and average it in another function


code:
m = []
for i,(k, v) in enumerate(n):
    n[i] = (str(k)+'B', str(v) + 'B')
    m.append(n[i])

rawDescription: Editing the contents of tuples

description: Editing the contents of tuples


code:
buf = bytearray(toread)
view = memoryview(buf)
while toread:
    nbytes = sock.recv_into(view, toread)
    view = view[nbytes:] # slicing views is cheap
    toread -= nbytes

rawDescription: using bytearray with socket.recv_into

description: Using bytearray with socket.recv_into


rawDescription: Validating a Unicode Name

description: Validating a Unicode Name


code:
dialog = QInputDialog()
dialog.exec_()

rawDescription: Make a window appear on top of another, block access to other windows until button clicked


code:
def map_the_home(home):
    result = dict([(a.room, a) for a in home])
    return result

rawDescription: python class Inheritance understanding

description: Python class Inheritance understanding


code:
class KVStore(ndb.Model):
  v = ndb.TextProperty()

  @classmethod
  def get(cls, k):
    e = cls.get_by_id(k)
    return e.v if e else None

  @classmethod
  def set(cls, k, v):
    e = cls(id=k, v=v)
    e.put()

rawDescription: Using Google App Engine as simple key/value store


code:
def jsonify(data, dimensions, metrics, struc = {}):
    for row in data:
        pointer = struc
        for dimension in dimensions:
            pointer.setdefault(row[dimension], {})
            pointer = pointer[row[dimension]]
        for metric in metrics:
            pointer.setdefault(metric, 0)
            pointer[metric] += row[metric]
    return struc

rawDescription: function to aggregate a set of data and output nested dictionary

description: Function to aggregate a set of data and output nested dictionary


code: fixed_angle = np.where(z > 0, angle, -angle)

rawDescription: Using python array's column as boolean to change another column's values


code:
import pandas as pd
import json

# Declare the nested dictionary that will hold the result
class NestedDict(dict):
    def __missing__(self, key):
        self[key] = NestedDict()
        return self[key]

# Creation of the dataframe
df = pd.DataFrame({\
'level_1':['alpha' ,'alpha' ,'alpha' ,'alpha' ,'beta' ,'beta' ,'beta' ,'beta'],\
'level_2':['one' ,'one' ,'two' ,'two' ,'one' ,'one' ,'two' ,'two'],\
'level_3':['a' ,'b' ,'a' ,'b' ,'a' ,'b' ,'a' ,'b'],\
'numeric':[1 ,2 ,3 ,4 ,5 ,6 ,7 ,8]})

# Creation of a multi-index
rr  = df.set_index(['level_1', 'level_2', 'level_3'])

d = NestedDict()
# Loop to store all elements of the dataframe in
# the instance of NestedDict
for k in rr.iterrows():
    d[k[0][0]][k[0][1]][k[0][2]] = k[1].values[0]
# JSON output
json.dumps(d,default=str)

rawDescription: pandas long-form table to nested json

description: Pandas long-form table to nested json


code:
a=urllib.urlopen('http://www.google.com/asdfsf')
a.getcode()
a=urllib.urlopen('http://www.google.com/')
a.getcode()

rawDescription: In Python, how do I use urllib to see if a website is 404 or 200?


rawDescription: Pandas tables, running .apply() on de-duped column values


code:
def get_queryset(self):
    queryset = Post.objects.all()

    if self.request.GET.get('price'):
        queryset = queryset.filter(price=self.request.GET.get('price'))
    return queryset

rawDescription: Filtering Objects in Class based view Django using Query parameters?


code:
def index(request):
    template_name = "index/index.html"
    is_teamleader = request.user.groups.filter(name='TL').exists()
    is_employee = request.user.groups.filter(name='Employee').exists()
    context = {
       'is_teamleader': is_teamleader,
       'is_employee': is_employee
    }
    return render(request, template_name, context)

rawDescription: Using group filter in template from view results


code:
s = "nnnABCnnnnDEFnnnnnGHInnnnnn"
import re

re.findall(r'n{2,}', s.strip('n'), re.I)

rawDescription: Regex, find pattern only in middle of string


code: plt.pie(sizes, labels=labels, autopct='%1.0f%%', pctdistance=1.1, labeldistance=1.2)

rawDescription: matplotlib percent label position in pie chart

description: Matplotlib percent label position in pie chart


code:
#!python
## !/usr/bin/env python3
import random

class Player (object):
    def __init__(self, attack, defence, speed, agility, hitpoints):
        self.attack    = attack
        self.defence   = defence
        self.speed     = speed
        self.agility   = agility
        self.hitpoints = hitpoints

    def is_alive(self):
        return self.hitpoints > 0

    def Attack(self, target):
        dodgeChance = target.agility - self.speed
        damage = 0
        roll = random.randint(0,100)
        if roll > dodgeChance:
             damage = abs(self.attack - target.defence)
        target.hitpoints -= damage
        return (target.hitpoints, damage, dodgeChance, roll)

if __name__ == '__main__':
    player1 = Player(5, 2, 9, 9, 50)
    player2 = Player(9, 9, 5, 2, 100)

    while player1.is_alive() or player2.is_alive():
        damage = dodge = roll = 0
        askMove = input("Attack(1) Brace(2)")
        if askMove.startswith("1"):
             damage, x, dodge, roll = player1.Attack(player2)
        player2.Attack(player1)
        print("Player 2 recieved", damage, "damage!")
        print("Player 2's HP is at %s!" % player2.hitpoints)
        print("\t\tDodge: %s\tRoll: %s!" % (dodge, roll))
        print("\tPlayer 1 HP: %s\n" % (player1.hitpoints))

rawDescription: Missing arguments that shouldn't be missing(Python)?


code: value = next(v for (k,v) in some_dict.iteritems() if 'substring' in k)

rawDescription: How to retrieve from python dict where key is only partially known?

description: Retrieve from python dict where key is only partially known


rawDescription: How to reset the index after inserting one dataframe into another

description: Reset the index after inserting one dataframe into another


rawDescription: timedelta64 and datetime conversion

description: Timedelta64 and datetime conversion


code:
app = webapp2.WSGIApplication([
  ('/', Home),
  ('/get/something', AnotherHandler),
  ('/(.+)/?', oldPathsHandler),
], debug = True)

rawDescription: Redirect old website urls in new GAE/Python/webapp2 website


code:
import os.path
with open('titles.txt') as f:
    for line in f:
        newfile = os.path.join('C:\\titles',line.strip()) + '.txt'
        ff = open( newfile, 'a')
        ff.close()

rawDescription: Python blank txt file creation

description: Python blank txt file creation


code:
class ParserZZ(Parser):
    def __init__(self, whatever):
        self.myparser = MyParser(whatever)

    def parse(self, foo):
        return self.myparser.parse(foo)

rawDescription: Python Classes Within a Class

description: Python Classes Within a Class


code:
lasso = Lasso(alpha=alpha).fit(X_train, y_train)
lasso.coef_ != 0
import numpy as np
np.nonzero(lasso.coef_)

rawDescription: How is the scikit Lasso/LARS used as a regressive feature selection tool?


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

"""
    long comment about IPython.Shell that you
    might want to read; omitted here for brevity
"""
import IPython.Shell

IPython.Shell.start().mainloop()

rawDescription: ipython for python 2.6.1 uninstall needed?

description: Ipython for python 2.6.1 uninstall needed


code:
cnxn = pyodbc.connect('DRIVER={Teradata};DBCNAME=PRD;UID=*;PWD=*;QUIETMODE=YES;',
                       unicode_results=True)

rawDescription: Encode a dataframe after in import in sql


code: #!/usr/bin/env python

rawDescription: How to convert this Python script to a shell script?

description: Convert this Python script to a shell script


code:
string = 'sdjskjhdvsnea'
substring = 'sdkj'
counter = 0
for x in string:
    if x in substring:
        counter += 1
counter

rawDescription: How to find the total number of occurrences of the characters of a word in a string?

description: Find the total number of occurrences of the characters of a word in a string


code:
class Klass:
    def __init__(self, values):
        self._values = values
        self.more = None

    def __getitem__(self, name):
        return self._values[name]

    def __iter__(self):
        return iter(self._values)

    def keys(self):
        return self._values.keys()

    def items(self):
        return self._values.items()

    def values(self):
        return self._values.values()

rawDescription: How to iterate over `dict` in class like if just referring to `dict`?

description: Iterate over `dict` in class like if just referring to `dict`


code:
class MyClass(object):
    classattrs = {'numbers': [1,2,3,4,5]}

MyClass.classattrs['letters'] = ['a','b','c']

rawDescription: Mapping dict items on class attributes

description: Mapping dict items on class attributes


code: soup.select('div#test > div.filters > span.text')[:10]

rawDescription: How to limit the result of select tag in beautifulsoup?

description: Limit the result of select tag in beautifulsoup


code:
def all_function(predicate, iterable):
    return all(map(predicate, iterable))

rawDescription: There's no "all" where I can pass a lambda?


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

fig, ax = plt.subplots()

x = [1, 2, 3, 4]
y = [5, 6, 7, 8]

for t in range(10):
    if t == 0:
        points, = ax.plot(x, y, marker='o', linestyle='None')
        ax.set_xlim(0, 10)
        ax.set_ylim(0, 10)
    else:
        new_x = np.random.randint(10, size=5)
        new_y = np.random.randint(10, size=5)
        points.set_data(new_x, new_y)
    plt.pause(0.5)

rawDescription: Simple animation of 2D coordinates using matplotlib and pyplot


code: button = Button(..., command=lambda row=i, column=j: doSomething(row, column))

rawDescription: How to get grid information from pressed Button in tkinter?

description: Get grid information from pressed Button in tkinter


code:
import matplotlib.pyplot as plt
# generate some data
x = [1,2,3,4,5,8]
y= [i**2 for i in x]
y2= [60-i**2+3*i for i in x]

# plot markers with thick borders
plt.subplot(121)
plt.scatter(x,y, s=500, marker='s', edgecolor='black', linewidth='3', facecolor='green', hatch='|')
# compare with no borders, and denser hatch.
plt.subplot(122)
plt.scatter(x,y, s=500, marker='s', edgecolor='black', linewidth='0', facecolor='green', hatch='||||')

plt.show()

rawDescription: How to change marker border width and hatch width?

description: Change marker border width and hatch width


code:
import csv

# read data
with open('testresponseFS.csv', 'rb') as inf:
    incsv = csv.reader(inf)
    header = next(incsv)
    data = [row for row in incsv]

# process data
header.append('Comments')
response_column = 4
for row in data:
    response = row[response_column]
    newval = response[:4].lower()    # or whatever you do to it
    row.append(newval)

# write data back out
with open('finaldata.csv', 'wb') as outf:
    outcsv = csv.writer(outf)
    outcsv.writerow(header)
    outcsv.writerows(data)

rawDescription: Reading File in Python and putting column into Array


code: df.groupby(df.index / 3).mean()

rawDescription: Bin pandas dataframe by every X rows

description: Bin pandas dataframe by every X rows


code:
import numpy as np
import pandas as pd
import math
from sys import stdout

#function Takes the pandas dataframe, Input features list and the target column name
def get_numpy_data(data, features, output):

    #Adding a constant collumn with value 1 in the dataframe.
    data['constant'] = 1
    #Adding the name of the constant collumn in the feature list.
    features = ['constant'] + features
    #Creating Feature matrix(Selecting columns and coverting to matrix).
    features_matrix=data[features].as_matrix()
    #Target collumn is converted to the numpy array
    output_array=np.array(data[output])
    return(features_matrix, output_array)

def predict_outcome(feature_matrix, weights):
    weights=np.array(weights)
    predictions = np.dot(feature_matrix, weights)
    return predictions

def errors(output,predictions):
    errors=predictions-output
    return errors

def feature_derivative(errors, feature):
    derivative=np.dot(2,np.dot(feature,errors))
    return derivative

def regression_gradient_descent(feature_matrix, output, initial_weights, step_size, tolerance):
    converged = False
    #Initital weights are converted to numpy array
    weights = np.array(initial_weights)
    while not converged:
        # compute the predictions based on feature_matrix and weights:
        predictions=predict_outcome(feature_matrix,weights)
        # compute the errors as predictions - output:
        error=errors(output,predictions)
        gradient_sum_squares = 0 # initialize the gradient
        # while not converged, update each weight individually:
        for i in range(len(weights)):
            # Recall that feature_matrix[:, i] is the feature column associated with weights[i]
            feature=feature_matrix[:, i]
            # compute the derivative for weight[i]:
            #predict=predict_outcome(feature,weights[i])
            #err=errors(output,predict)
            deriv=feature_derivative(error,feature)
            # add the squared derivative to the gradient magnitude
            gradient_sum_squares=gradient_sum_squares+(deriv**2)
            # update the weight based on step size and derivative:
            weights[i]=weights[i] - np.dot(step_size,deriv)

        gradient_magnitude = math.sqrt(gradient_sum_squares)
        stdout.write("\r%d" % int(gradient_magnitude))
        stdout.flush()
        if gradient_magnitude < tolerance:
            converged = True
    return(weights)

#Example of Implementation
#Importing Training and Testing Data
# train_data=pd.read_csv("kc_house_train_data.csv")
# test_data=pd.read_csv("kc_house_test_data.csv")

# simple_features = ['sqft_living', 'sqft_living15']
# my_output= 'price'
# (simple_feature_matrix, output) = get_numpy_data(train_data, simple_features, my_output)
# initial_weights = np.array([-100000., 1., 1.])
# step_size = 7e-12
# tolerance = 2.5e7
# simple_weights = regression_gradient_descent(simple_feature_matrix, output,initial_weights, step_size,tolerance)
# print simple_weights

rawDescription: Simple Linear Regression in Python

description: Simple Linear Regression in Python


code: from __future__ import braces

rawDescription: How can I write readable Python code when there are no curly brackets and semicolons?

description: Write readable Python code when there are no curly brackets and semicolons


code:
my_dict = {}
with open("file1.txt") as f:
    for line in f:
        value, key = line.strip().split()    # taking rs... as key and SNP-.. as value
        my_dict[key] = value

rs_values = open("file2.txt").readlines()

with open("file2.txt", "w") as f:
    for x in rs_values:
        f.write(my_dict[x.strip()] + "\n")

rawDescription: Replacing lines in one file by keys in another file-python


code:
responce = urllib2.urlopen('http://address.co/download')
assert responce.getcode() == 200

rawDescription: Selenium Grid - Python File Path

description: Selenium Grid - Python File Path


rawDescription: Daubechies orthogonal wavelet in python

description: Daubechies orthogonal wavelet in python


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

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)

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

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

        self.resize(94, 35)
        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QLabel(self)
        self.label.setText("Text Label")

        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(5)
        self.label.setGraphicsEffect(self.shadow)

        self.verticalLayout.addWidget(self.label)

if __name__ == "__main__":
    import  sys

    app = QApplication(sys.argv)
    main = testShadow()
    main.show()
    sys.exit(app.exec_())

rawDescription: Qt QGraphicsDropShadowEffect is not showing


code: new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}

rawDescription: How to remove specific substrings from a set of strings in Python?

description: Remove specific substrings from a set of strings in Python


code:
import pandas as pd
df = pd.DataFrame({'Name':['Tom','Major','Pete'], 'Age':[23,45,30]})

from pyspark import SQLContext
sqlc = SQLContext(sc)

spark_df = sqlc.createDataFrame(df)

rawDescription: How to write to a Spark SQL table from a Panda data frame using PySpark?

description: Write to a Spark SQL table from a Panda data frame using PySpark


code:
from tkinter import *
def inp():
    global inpt
    number=inpt.get()
    try:
        int(number)
        info.configure(text=number)
    except ValueError:
        info.configure(text="Please enter an integer")
    root.update()
root=Tk()
root.geometry("300x100-0+0")
Label(root,text="Input ", height=1, width=7).grid(row=0)
inpt=Entry(root, width=35)
inpt.grid(row=0, column=1)
info=Label(root,text="", height=1)
info.grid(row=3, column=1)
get=Button(root, text="Input", command=inp)
get.grid(row=2, column=1)
mainloop()

rawDescription: Python 3 Input Dialog

description: Python 3 Input Dialog


code:
#!/usr/bin/env python

from PyQt4 import QtGui, QtCore
import sys

class Application(QtGui.QApplication):

    def __init__(self):
        QtGui.QApplication.__init__(self, sys.argv)

        self.main = MyWidget()
        self.main.show()

class MyWidget(QtGui.QWidget):
    def __init__(self, parent=None):
        QtGui.QLabel.__init__(self, parent)

        self.setStyleSheet("QWidget { background-color : white}")
        self.setGeometry(0, 0, 200, 200)

        self.sub_widget = QtGui.QWidget(self)
        self.sub_widget.setStyleSheet("QWidget { background-color : black}")
        self.sub_widget.setGeometry((self.width()-100)/2, (self.height()-100)/2 , 100, 100)

    def resizeEvent(self, event):

        self.sub_widget.setGeometry((self.width()-100)/2, (self.height()-100)/2 , 100, 100)

rawDescription: Centre widget on parent widget without layout


code:
df
df.loc[idx,['L','R']] = df.loc[idx,['R','L']].values
df

rawDescription: What is correct syntax to swap column values for selected rows in a pandas data frame using just one line?


code:
for object in mybucket.objects.all():
    print(object)

rawDescription: Listing contents of a bucket with boto3

description: Listing contents of a bucket with boto3


rawDescription: Python3 Display certain number of output


code:
from HTMLParser import HTMLParser

class MLStripper(HTMLParser):
  def __init__(self):
    self.reset()
    self.fed = []
  def handle_data(self, d):
    self.fed.append(d)
  def get_data(self):
    return ''.join(self.fed)

def strip_tags(html):
  s = MLStripper()
  s.feed(html)
  return s.get_data()

rawDescription: strip the html tags and return only text using mechanize in python

description: Strip the html tags and return only text using mechanize in python


code: df.pivot_table(columns=['Activity'],values=['Timestamp'],index=['Job_Id'], aggfunc=lambda x : x)

rawDescription: Pandas Groupby: Summarizing Activity Log


code:
s = "aaa About DoctorTardi this Stats for Project Ares bbb"
head, sep1, x = s.partition("About DoctorTardi")
_, sep2, tail = x.partition("Stats for Project Ares")
head + sep1 + sep2 + tail

rawDescription: How to remove all the text in a string between two sub-strings. Python 2.7

description: Remove all the text in a string between two sub-strings. Python 2.7


code:
number_pairs = [(100,200), (110, 190), (90, 210)]

max_width = 50
min_value = min([i for j in number_pairs for i in j])
max_value = max([i for j in number_pairs for i in j])
step = max_width / float(max_value - min_value)

for num1, num2 in number_pairs:
    line = list('-' * max_width)
    pos1 = int((num1 - min_value + 1) * step - 1)
    pos2 = int((num2 - min_value + 1) * step - 1)
    line[pos1] = 'x'
    line[pos2] = 'x'
    print(''.join(line))

rawDescription: Script to draw pairs of numbers linearly in python


rawDescription: How to parse StackExchange OAuth response?

description: Parse StackExchange OAuth response


code:
import collections

def make_hashable(obj):
    """WARNING: This function only works on a limited subset of objects
    Make a range of objects hashable.
    Accepts embedded dictionaries, lists or tuples (including namedtuples)"""
    if isinstance(obj, collections.Hashable):
        #Fine to be hashed without any changes
        return obj
    elif isinstance(obj, collections.Mapping):
        #Convert into a frozenset instead
        items=list(obj.items())
        for i, item in enumerate(items):
                items[i]=make_hashable(item)
        return frozenset(items)
    elif isinstance(obj, collections.Iterable):
        #Convert into a tuple instead
        ret=[type(obj)]
        for i, item in enumerate(obj):
                ret.append(make_hashable(item))
        return tuple(ret)
    #Use the id of the object
    return id(obj)

rawDescription: Using non-hashable Python objects as keys in dictionaries


code:
import numpy as np
import pylab as pl

y, x = np.ogrid[-1:1:100j, -1:1:100j]
z = np.sin(4*(x**2+y**2))

pl.imshow(z, origin="lower", extent=(-1,1,-1,1))
pl.xlim(-0.5, 0)
pl.ylim(0.5, 1.0)
pl.show()

rawDescription: How to resize images in pylab

description: Resize images in pylab