code:
import scrapy

class ExampleSpider(scrapy.Spider):
    name = "example"
    minimum = 15
    maximum = 25

    def start_requests(self):
        for i in range(self.minimum, self.maximum + 1):
            url = 'http://example.com/page.aspx?id={}'.format(i)
            yield scrapy.Request(url)

    def parse(self, response):
        pass

rawDescription: Scrapy Example: site.com/page.aspx?id=1

description: Scrapy Example: site.com/page.aspx?id=1


code:
class RackAdmin(admin.ModelAdmin):
    model = Rack
    readonly_fields = ('row',)

    def row(self, obj):
        return obj.position.row

rawDescription: django model referencing object from other class

description: Django model referencing object from other class


code:
class MyMap(object):
    def __init__(self, func, *iterables):
        self.func = func
        self.iterables = iterables
    def __iter__(self):
        return iter(itertools.imap(self.func, *self.iterables))

rawDescription: In python, how do I map an iterable to an iterable?


code:
thegmm = GMM(cvtype='tied', params='mc')
thegmm.fit(mydata)

rawDescription: GMM clustering algorithm with equal weight and shared diagonal covariance


code:
# command
class DrawCommand:
    def __init__(self, draw, point1, point2):
        self.draw = draw
        self.point1 = point1
        self.point2 = point2
    def execute_drawing(self):
        self.draw.execute(self.point1, self.point2)
# invoker
class InvokeDrawLines:
    def __init__(self, data):
        self.commandlist = data
    def addcommand(self, command):
        self.commandlist.append(command)
    def draw(self):
        for cmd in self.commandlist:
            cmd.execute_drawing()
    def undocommand(self, command):
        self.commandlist.remove(command)

# receiver
class DrawALine:
    def execute(self, point1, point2):
        print("Draw a line from" , point1, point2)

rawDescription: Do/Undo using command pattern in Python

description: Do/Undo using command pattern in Python


code:
from setuptools import setup

APP = ['MyApp.py']
DATA_FILES = []
OPTIONS = {'argv_emulation': True,
    'iconfile': 'MyAppIcon.icns' }

setup(
    app=APP,
    data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)

rawDescription: App dock icon in wxPython

description: App dock icon in wxPython


code:
items = Item.all().order('name').fetch(10)
headers = ['Name', 'Price', 'Quantity']
viewitems = [[getattr(x, h) for h in headers] for x in items]

template_values = {'items': viewitems,
                   'headers': headers}
render('Views/table.html', self, template_values)

rawDescription: Django: using variables as array indices?


rawDescription: Foreign key to User table in django

description: Foreign key to User table in django


code:
from django.core.urlresolvers import reverse
twitterpath = reverse('social:begin', args=('twitter',))

rawDescription: How do I access values from python social auth used in template

description: Access values from python social auth used in template


code:
d
[x[:2] for x in d]

rawDescription: How to go from a 3 element tuple to 2 element tuple python

description: Go from a 3 element tuple to 2 element tuple python


rawDescription: Class not refreshing on 2nd url call

description: Class not refreshing on 2nd url call


code:
def format_list(l):
  res = "["
  items = []
  for item in l:
    if isinstance(item,list):
      items.append(format_list(item))
    elif isinstance(item,tuple):
      items.append(item[0] + ':' + item[1])
  res += ", ".join(items) + "]"
  return res

rawDescription: matching between two different structured python lists

description: Matching between two different structured python lists


code:
import logging

class DispatchingFormatter:

    def __init__(self, formatters, default_formatter):
        self._formatters = formatters
        self._default_formatter = default_formatter

    def format(self, record):
        formatter = self._formatters.get(record.name, self._default_formatter)
        return formatter.format(record)

handler = logging.StreamHandler()
handler.setFormatter(DispatchingFormatter({
        'base.foo': logging.Formatter('FOO: %(message)s'),
        'base.bar': logging.Formatter('BAR: %(message)s'),
    },
    logging.Formatter('%(message)s'),
))
logging.getLogger().addHandler(handler)

logging.getLogger('base.foo').error('Log from foo')
logging.getLogger('base.bar').error('Log from bar')
logging.getLogger('base.baz').error('Log from baz')

rawDescription: How to use different formatters with the same logging handler in python

description: Use different formatters with the same logging handler in python


code:
import subprocess

execstr1 = 'ffmpeg -x -y -z ...'
execstr2 = 'ffmpeg -a -b -c ...'

out1 = subprocess.check_output(execstr1, shell=True)

out2 = subprocess.check_output(execstr2, shell=True)

rawDescription: Run two ffmpeg commands one after another


code:
import wx
import wx.lib.sheet as sheet

class MySheet(sheet.CSheet):
    def __init__(self, parent):
        sheet.CSheet.__init__(self, parent)

        self.SetLabelBackgroundColour('#CCFF66')
        self.SetNumberRows(50)
        self.SetNumberCols(50)

class Notebook(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, size=(600, 600))
        menubar = wx.MenuBar()
        file = wx.Menu()
        file.Append(101, 'Quit', '' )
        menubar.Append(file, "&File")
        self.SetMenuBar(menubar)
        wx.EVT_MENU(self, 101, self.OnQuit)
        nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
        self.sheet1 = MySheet(nb)
        self.sheet2 = MySheet(nb)
        self.sheet3 = MySheet(nb)
        nb.AddPage(self.sheet1, "Sheet1")
        nb.AddPage(self.sheet2, "Sheet2")
        nb.AddPage(self.sheet3, "Sheet3")
        self.sheet1.SetFocus()
        self.StatusBar()

        self.button1 = wx.Button(self, -1, label = "Ok")
        self.button2 = wx.Button(self, -1, label = "Not Ok")

        sizerV = wx.BoxSizer(wx.VERTICAL)
        sizerH = wx.BoxSizer(wx.HORIZONTAL)

        # add notebook first, with size factor 2:
        sizerV.Add(nb, 5)
        # then text, size factor 1, maximized
        sizerH.Add(self.button1, 1, wx.EXPAND)
        sizerH.Add(self.button2, 1, wx.EXPAND)
        sizerV.Add(sizerH, 1, wx.ALL|wx.EXPAND, 5)

        # assign the sizer to Frame:
        self.SetSizerAndFit(sizerV)

    def StatusBar(self):
        self.statusbar = self.CreateStatusBar()

    def OnQuit(self, event):
        self.Close()

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 400))
        self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
        self.Center()

class MyApp(wx.App):
    def OnInit(self):
        frame = Notebook(None, -1, 'Pandel.py')
        frame.Show(True)
        frame.Center()
        frame2 = MyFrame(None, -1, '')
        self.SetTopWindow(frame2)
        return True

app = MyApp(0)
app.MainLoop()

rawDescription: How to use sizers in Wxpython to place multiple widgets in the same frame?

description: Use sizers in Wxpython to place multiple widgets in the same frame


code:
a = u'Duncan\n\n'
a
a.strip()
str(a.strip())

rawDescription: Using html2text and clean some text in Python


code:
import json
line_items=[]
for q in ItemDetails:
    myItemName = q[0]
    myQuantity = q[1]
    myUnitAmount = float(q[2])
    myItemCode = str(q[3])

    myjson3 = {
                'ItemCode': myItemCode,
                'Description': myItemName,
                'UnitAmount': myUnitAmount * myDiscount,
                'Quantity': myQuantity,
                'AccountCode': myAccountCode,
                'TaxType': myTaxType
            }
    line_items.append(myjson3)
print(json.dumps(line_items))

rawDescription: Create JSON object with variables from an array


code:
if source == 'server':
    from HTMLParser import HTMLParser
    import urllib
    class ChrParser(HTMLParser):
        def handle_starttag(self, tag, attrs):
            if tag =='a':
                for key, value in attrs:
                    if key == 'href' and value.endswith('.csv'):
                        pre_fileslist.append(value)
    results_dir = 'http://chymera.eu/data/faceRT'
    data_url = urllib.urlopen(results_dir).read()
    parser = ChrParser()
    pre_fileslist = []
    parser.feed(data_url) # pre_fileslist gets populated here

rawDescription: python os.listdir() for remote locations

description: Python os.listdir() for remote locations


code:
def mytext(stmt, params):
    bindparams = []
    for k, v in params:
        if isinstance(v, datetime):
            type_ = MyType()
        else:
            type_ = None
        bindparams.append(bindparam(k, v, type_=type))
    return text(stmt, bindparams=bindparams)

rawDescription: SQLAlchemy override types.DateTime on raw sql expressions


code:
def _create_identifier():
    base = unicode("%s|%s" % (request.remote_addr,
                              request.headers.get("User-Agent")), 'utf8', errors='replace')
    hsh = md5()
    hsh.update(base.encode("utf8"))
    return hsh.digest()

rawDescription: Constant Flask Session IDs

description: Constant Flask Session IDs


code:
p = Project.objects.all().annotate(Count('informationunit__username',
                                         distinct=True))

rawDescription: Django annotate count with a distinct field


code:
def form_contractor_view(request):
    if request.method == 'POST':
        form = ContractorForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index_view')
    else:
        form = ContractorForm()
    return render(
       request,
       'form_contractor.html',
       {'form': form},
    )

rawDescription: Refactoring the "view" code

description: Refactoring the "view" code


code:
x = np.array([1, 2, np.nan, 3, np.nan, 4])
y = np.array([1, np.nan, 2, 5, np.nan, 8])
x = np.ma.masked_array(np.nan_to_num(x), mask=np.isnan(x) & np.isnan(y))
y = np.ma.masked_array(np.nan_to_num(y), mask=x.mask)
(x+y).filled(np.nan)

rawDescription: fast numpy addnan

description: Fast numpy addnan


code:
answers_dict = {}
for x, y in my_data.iteritems():
    lons, lats = y[0], y[1]
    answers = []
    for e,f in zip(lons,lats):
        answer = Pysolar.GetAltitude(e, f, datetime.datetime.utcnow())
        answers.append(answer)
    answers_dict[x] = answers

rawDescription: Retrieving answer in the dictionary form from for loop


code:
ar = [2, 4, 6, 8 ,1]
mins = ar[-1]
for i in range(len(ar)-1, 0, -1):
    if ar[i-1] > mins:
        ar[i] = ar[i-1]
    else:
        ar[i] = mins
        break
    print(ar)
if mins < ar[0]: ar[0] = mins
print(ar)

rawDescription: Unknown number of iterations to complete the sort


rawDescription: How can I tell which python implementation I'm using?

description: Tell which python implementation I'm using


code:
import queue

class Queue(queue.Queue):

    def get_if(self, condition, default=None):
        with self.not_empty:
            if not self._qsize():
                raise queue.Empty
            if condition(self._peek()):
                item = self._get()
                self.not_full.notify()
                return item
            return default

    def _peek(self):
        return self.queue[0]

def main():
    my_queue = Queue()
    for number in range(100, 200):
        my_queue.put_nowait(number)
    number = my_queue.get_if(lambda item: not item % 10)
    print(number)

if __name__ == '__main__':
    main()

rawDescription: Can I read content of the oldest element in a Queue without ruining thread safety?

description: Read content of the oldest element in a Queue without ruining thread safety


code:
class GroupMeeting(models.Model):
    date = models.DateTimeField()
    placeGPS = models.FloatField()
    placeName = models.CharField(max_length=30)
    dateRepeat= models.ForeignKey(RepeatDays)
    post = models.ForeignKey(Post, limit_choices_to = {'category': 0})

rawDescription: Selective Foreign Key Usage in Django (maybe with limit_choices_to argument?)


code:
list_1 = [1,1,2,3]
list_2 = ['a','b','c','d']
temp = dict(zip(list_1,list_2))
result_1 = temp.keys()
result_2 = temp.values()
result_1
result_2

rawDescription: Python: Removing entries of one list by duplicates of another list


code:
...
# I'd suggest using with ... as f as in 1 line
with open(filename, 'wb') as f:
    # set the delimiter to \t tab than comma
    writer = csv.writer(f, delimiter='\t')
    for row in soup('table')[5].findAll('tr'):
        tds = row('td')
        # you can writerow the list directly as it will convert it to string for you
        writer.writerow([cell.string for cell in tds if cell.string])
...

rawDescription: Python: Using BeautifulSoup to save content to CSV


code:
import Crypto.Hash.MD5 as MD5
import Crypto.PublicKey.RSA as RSA
import Crypto.PublicKey.DSA as DSA
import Crypto.PublicKey.ElGamal as ElGamal
import Crypto.Util.number as CUN
import os

plaintext='The rain in Spain falls mainly on the Plain'

# Here is a hash of the message
hash=MD5.new(plaintext).digest()
print(repr(hash))
# '\xb1./J\xa883\x974\xa4\xac\x1e\x1b!\xc8\x11'

for alg in (RSA,DSA,ElGamal):
    # Generates a fresh public/private key pair
    key=alg.generate(384,os.urandom)

    if alg == DSA:
        K=CUN.getRandomNumber(128,os.urandom)
    elif alg == ElGamal:
        K=CUN.getPrime(128,os.urandom)
        while CUN.GCD(K,key.p-1)!=1:
            print('K not relatively prime with {n}'.format(n=key.p-1))
            K=CUN.getPrime(128,os.urandom)
        # print('GCD({K},{n})=1'.format(K=K,n=key.p-1))
    else:
        K=''

    # You sign the hash
    signature=key.sign(hash,K)
    print(len(signature),alg.__name__)
    # (1, 'Crypto.PublicKey.RSA')
    # (2, 'Crypto.PublicKey.DSA')
    # (2, 'Crypto.PublicKey.ElGamal')

    # You share pubkey with Friend
    pubkey=key.publickey()

    # You send message (plaintext) and signature to Friend.
    # Friend knows how to compute hash.
    # Friend verifies the message came from you this way:
    assert pubkey.verify(hash,signature)

    # A different hash should not pass the test.
    assert not pubkey.verify(hash[:-1],signature)

rawDescription: Signing and verifying data using pycrypto (RSA)


code:
if current_level_num == 1 and player.rect.x > SCREEN_WIDTH:
    current_level_num = 2
    current_level = levels[current_level_num]
    player.rect.x = 0

if current_level_num == 2 and player.rect.x < 1:
    current_level_num = 1
    current_level = levels[current_level_num]
    player.rect.x = SCREEN_WIDTH

rawDescription: My Character Sprite Doesn't Move Off Screen


rawDescription: How to remove values from Specific Dictionary Key Python

description: Remove values from Specific Dictionary Key Python


code:
from apiclient.discovery import build
service = build('drive', 'v2')

import httplib2
credentials = ... # Obtain OAuth 2.0 credentials
http = credentials.authorize(httplib2.Http())

body = {
  'mimeType': 'application/vnd.google-apps.spreadsheet',
  'title': 'Name of Spreadsheet',
}
file = service.files().insert(body=body).execute(http=http)

rawDescription: Create a empty spreadsheet in google drive using google spreadsheet api (python )?


code:
# First block. Store a,b,c separately.
a_lst, b_lst, c_lst = [], [], []
for i, p in enumerate(p_lst):
    for j, q in enumerate(q_lst):

        # a,b,c are obtained via some complicated function of p,q.
        # This is just for the purpose of this example.
        a_lst.append(1.*p)
        b_lst.append(1.*q)
        c_lst.append(p+q)

# As arrays.
a_lst, b_lst, c_lst = np.asarray(a_lst), np.asarray(b_lst), np.asarray(c_lst)

# Second block.
# Apply operation on nested list using np.outer.
lst = np.sum(abs(np.outer(a_lst, x) + np.outer(b_lst, y) + np.outer(c_lst, z)), axis=1)

rawDescription: Speed up operation on nested python array


code:
import ctypes

_decref = ctypes.pythonapi.Py_DecRef
_decref.argtypes = [ctypes.py_object]
_decref.restype = None

_decref(a_python_object)

rawDescription: Is there any way to manually decrease the reference count of an object in Python?


code:
import lxml.etree as ET
import lxml.html as LH
LH.tostring(ET.fromstring('<rt><CapName>asd</CapName></rt>'))

rawDescription: Is there a way to get a verbatim string out of an ElementTree element?


code:
mynewlist = mylist[:]
for pos, elem in zip(permutation, mylist):
    mynewlist[pos - 1] = elem

rawDescription: Python permutation as list comprehension


code:
def merge_sort(data):
    data1, data2, data3 = itertools.tee(data, 3)

    counter = 0
    for i in data1:
        counter += 1

    if counter < 2:
        return data3

    middle = int(counter / 2)

    y = itertools.islice(data2, 0, middle)
    z = itertools.islice(data3, middle, counter)

    sorted_y = merge_sort(y)
    sorted_z = merge_sort(z)

    return merge(sorted_y, sorted_z)

rawDescription: Merge sort with help Iterators

description: Merge sort with help Iterators


code:
with open("foo.csv", "w") as my_empty_csv:
  # now you have an empty file already
  pass  # or write something to it already

rawDescription: How do I create an empty csv file on a specific folder?

description: Create an empty csv file on a specific folder


code:
seen = set()

get_datetime = operator.itemgetter('datetime')
for row in data:
    dt = get_datetime(row)

    try:
        localized = timezone.localize(dt, is_dst=None)
    except pytz.NonExistentTimeError:
        localized = timezone.localize(dt, is_dst=True)
        seen = set()
    except pytz.AmbiguousTimeError:
        localized = timezone.localize(dt, is_dst=(dt not in seen))
        seen.add(dt)

rawDescription: Daylight savings transition at wrong time


code:
y
c_map = [[1, 1, 1], [0.6, 1, 0.8], [1, 0.6, 0.2], [0.75, 0.25, 0.25]]
cm = matplotlib.colors.ListedColormap(c_map)
imshow(y, interpolation='nearest', cmap=cm)

rawDescription: Create a colormap that is assigned to specific integer values with numpy/scipy


code:
with open('file.csv') as fh:
    header = [h.strip() for h in fh.next().split(',')]
    reader = csv.DictReader(fh, fieldnames=header)

rawDescription: python how to trim trailing spaces in csv DictReader keys

description: Python how to trim trailing spaces in csv DictReader keys


rawDescription: Scrapy pipeline spider_opened and spider_closed not being called


code:
from os import environ
IPYTHONDIR = environ["IPYTHONDIR"]
template_rel_path = '/nbextensions/templates'
template_path = IPYTHONDIR + template_rel_path
c.TemplateExporter.template_path = [
                                '.',
                                template_path
                                    ]

rawDescription: IPYTHON: adding a new folder to searchable template locations for `nbconvert`


code: text = BeautifulSoup(f).get_text()

rawDescription: Python: Better way to search and collect text strings from html. Strip off markdowns, tags, etc


code: df_foursquare.merge(df_categories, how='left', left_on=['CategoryID'], right_on=['Sub Categories ID'])

rawDescription: Create new dataframe based on two other dataframes


code:
import requests
r = requests.get('http://cdn.sstatic.net/stackoverflow/img/sprites.png')
r.status_code
r = requests.get('http://cdn.sstatic.net/stackoverflow/img/sprites.xxx')
r.status_code

rawDescription: How can I tell programatically if a filename I am asking for exists on a webserver?

description: Tell programatically if a filename I am asking for exists on a webserver


code:
from multiprocessing import Process, Value, Array

def f(n, a):
    n.value = 3.1415927
    for i in range(len(a)):
        a[i] = -a[i]

if __name__ == '__main__':
    num = Value('d', 0.0)
    arr = Array('i', range(10))

    p = Process(target=f, args=(num, arr))
    p.start()
    p.join()

    print(num.value)
    print(arr[:])

rawDescription: Sharing data structures between 2 Python processes


code:
mylists = {}

x = 'abhishek'
mylists[x] = []

rawDescription: How to create a List given a variable "x" in Python?

description: Create a List given a variable "x" in Python


code:
return '''

    %(numberofapplicants)s

    ''' % {"numberofapplicants": numberofapplicants}

rawDescription: CherryPy variables in html

description: CherryPy variables in html


code:
import os
from mock import patch

def test(*args):
    import ipdb; ipdb.set_trace()
    with patch('os.path.isdir', return_value=False):
        with patch('os.path.isfile', return_value=False):
            real_function(some_arguments)
    pass

test()

rawDescription: Patching a function with Mock only for one module?


code:
class LoggedAction(models.Model):
    ACTIONS = (
       ('I', 'logged in'),
       ('O', 'logged out')
    )
    user = models.ForeignKey(User)
    timestamp = models.DateTimeField(auto_now_add=True)
    action = models.CharField(max_length=1, choices=ACTIONS)

    def __unicode__(self):
        return u"%s: %s %s" % (self.timestamp, self.user, self.get_action_display())

rawDescription: Is there a sane way to simulate virtual inheritance in Django models?


code:
import datetime as DT
(DT.date(2010,1,1)-DT.date(2010,1,1)).days // 7 + 1

rawDescription: Converting python date to week

description: Converting python date to week


rawDescription: Python Pandas - how to do group by on a multiindex


code:
import bleach

def my_linkify(content,
               tags=bleach.ALLOWED_TAGS,
               allowed_attributes=bleach.ALLOWED_ATTRIBUTES,
               styles=bleach.ALLOWED_STYLES,
               strip=False,
               strip_comments=False):
    class Tokenizer(bleach.BleachSanitizer):
        allowed_elements = tags
        allowed_attributes = attributes
        allowed_css_properties = styles
        strip_disallowed_elements = strip
        strip_html_comments = strip_comments
    return bleach.linkify(content, tokenizer=Tokenizer)

rawDescription: python bleach linkify is removing my safe attributes

description: Python bleach linkify is removing my safe attributes


code:
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)

rawDescription: Testing python package bin scripts best practice


code:
import dis
def test(x, y):
    x, y = y, x

dis.dis(test)

rawDescription: Order of evaluation in Python is not clear


code:
import readline
import rlcompleter
if 'libedit' in readline.__doc__:
    readline.parse_and_bind("bind ^I rl_complete")
else:
    readline.parse_and_bind("tab: complete")

rawDescription: python tab completion Mac OSX 10.7 (Lion)

description: Python tab completion Mac OSX 10.7 (Lion)


code: sum(v for v in color_codes.itervalues() if v > x)

rawDescription: What is a good way to do a SUMIF on dictionary values?


code:
import scipy, pylab
names = ['Alice', 'Bob', 'Carol', 'David']
interests = [['Football', 'Swimming'], ['Swimming', 'Jooga', 'Jogging'],
             ['Cycling', 'Football'], ['Football', 'Tennis', 'Cycling']]
allinterests = list(set(reduce(lambda x,y:x+y, interests)))
X = scipy.zeros((len(interests), len(allinterests)))
for i, indinterests in enumerate(interests):
    for x in indinterests:
        X[i, allinterests.index(x)] = 1
pylab.matshow(X, interpolation='nearest', cmap=pylab.cm.gray_r)
pylab.show()
pylab.yticks(range(len(names)), names)
pylab.ylim([len(names)-0.5, -0.5])
pylab.xticks(range(len(allinterests)), allinterests)
pylab.savefig('interests.png')

rawDescription: Plot multidimensional data

description: Plot multidimensional data


code:
def select(self):
    #snip ...
    if len(fileObjOpenName) > 1:
       self.path_to_pdf = fileObjOpenName

def save(self):
    #snip ...
    if len(fileNameSave) > 1:
       path_to_pdf = self.path_to_pdf

rawDescription: Pyside: Pass a var generated in a function to another function


rawDescription: How to order a python list of "string" numbers by its value

description: Order a python list of "string" numbers by its value


code: indices = [i for i, s in enumerate(mylist) if 'aa' in s]

rawDescription: python - find index postion in list based of partial string

description: Python - find index postion in list based of partial string


code:
from collections import OrderedDict
d = OrderedDict({1:0, 2:0, 3:1, 4:1, 5:2, 6:3, 7:4, 8:4})
d
new_d = OrderedDict()
for i, j in d.iteritems():
    if j in new_d.values(): continue
    new_d[i] = j

new_d
dict(new_d)

rawDescription: Find unique of dictionary by values

description: Find unique of dictionary by values


code:
#create an index of just the date portion of your index (this is the slow step)
ts_days = pd.to_datetime(ts.index.date)

#create a range of business days over that period
bdays = pd.bdate_range(start=ts.index[0].date(), end=ts.index[-1].date())

#Filter the series to just those days contained in the business day range.
ts = ts[ts_days.isin(bdays)]

rawDescription: Extract Business Days in Time Series using Python/Pandas


rawDescription: convert a matrix(list of lists) into a square matrix in python

description: Convert a matrix(list of lists) into a square matrix in python


code:
url(r'^', include('frontpage.urls', namespace="frontpage")),

urlpatterns = patterns('frontpage.views',
    url(r'^$', 'index', name='index'),
)

rawDescription: Django can't get root url for my app

description: Django can't get root url for my app


code:
class Room(models.Model):
    players = models.ListField('Player', required = True)

rawDescription: Python cannot import name

description: Python cannot import name


code:
def flatten(NL):
    a = []
    for i in NL:
        if type(i) == int:
            a.append(i)
        elif type(i) == list:
            a += flatten(i) # Here we add the flattened version to a instead of just creating it.
    return a

rawDescription: How does putting the variable for empty list alter this python code?


code:
font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 14}

rcParams.update(font)

labels = 'a', 'b', 'c', 'd'
fracsQuads = [6, 14, 1, 79]
fracsTrips = [11, 16, 7, 66]
colors=['Goldenrod', 'LimeGreen', 'Crimson', 'DeepSkyBlue']

explode=(0, 0, 0, 0)

# Make square figures and axes

the_grid = GridSpec(1, 2)

ax1 = plt.subplot(the_grid[0, 0], aspect=1)
ax2 = plt.subplot(the_grid[0, 1], aspect=1)

ax1.pie(fracsQuads, autopct='%1.0f%%', colors=colors, pctdistance=1.2)
ax2.pie(fracsTrips, explode=explode, autopct='%.0f%%', colors=colors, pctdistance=1.2)

plt.figtext(0.19,0.2,'Four knockouts')
plt.figtext(0.61,0.2,'Three knockouts')

ax1.legend(labels, loc='lower center',bbox_to_anchor=(1.1, -0.1),
                 prop={'size':11})

plt.show()

rawDescription: Python matplotlib legend below multiple graphs


code:
import win32api, time

def moveFromTo(p1, p2):
    # slope of our line
    m = (p2[1] - p1[1]) / (p2[0] - p1[0])
    # y intercept of our line
    i = p1[1] - m * p1[0]
    # current point
    cP = p1
    # while loop comparison
    comp = isGreater
    # moving left to right or right to left
    inc = -1
    # switch for moving to right
    if (p2[0] > p1[0]):
        comp = isLess
        inc = 1
    # move cursor one pixel at a time
    while comp(cP[0],p2[0]):
        win32api.SetCursorPos(cP)
        cP[0] += inc
        # get next point on line
        cP[1] = m * cP[0] + i
        # slow it down
        time.sleep(0.01)

def isLess(a,b):
    return a < b
def isGreater(a,b):
    return a > b

moveFromTo([500,500],[100,100])

rawDescription: How Do I move my mouse with flexible speed


rawDescription: What is the best way to make the matrix operations more faster in python


code:
from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import HtmlXPathSelector

class Dic_crawler(BaseSpider):
    name = "thefreedictionary"
    allowed_domains = ["www.thefreedictionary.com"]
    start_urls = ['http://www.thefreedictionary.com/shame']

    def parse(self, response):
        hxs = HtmlXPathSelector(response)

        # loop on each "noun" or "verb" or something... section
        for category in hxs.select('id("MainTxt")//div[@class="pseg"]'):

            # this is simply to get what's in the <i> tag
            category_name = u''.join(category.select('./i/text()').extract())
            self.log("category: %s" % category_name)

            # for each category, a term can have multiple definition
            # category from .select() is a selector
            # so you can call .select() on it also,
            # here with a relative XPath expression selecting all definitions
            for definition in category.select('div[@class="ds-list"]'):
                definition_text = u'\n'.join(
                    definition.select('.//text()').extract())
                self.log(" - definition: %s" % definition_text)

rawDescription: xpath not getting selected

description: Xpath not getting selected


code:
i = df.groupby('type')['day'].transform('idxmin')
df['val@1st'] = df.loc[i, 'value'].values
df

rawDescription: Create new column from nth value in a groupby group with Python pandas


code:
from ctypes import *
from ctypes.wintypes import *

kernel32 = WinDLL('kernel32', use_last_error=True)

FILE_MAP_COPY       = 0x0001
FILE_MAP_WRITE      = 0x0002
FILE_MAP_READ       = 0x0004
FILE_MAP_ALL_ACCESS = 0x001f
FILE_MAP_EXECUTE    = 0x0020

PVOID = LPVOID
SIZE_T = c_size_t

class MEMORY_BASIC_INFORMATION(Structure):
    _fields_ = (('BaseAddress',       PVOID),
                ('AllocationBase',    PVOID),
                ('AllocationProtect', DWORD),
                ('RegionSize',        SIZE_T),
                ('State',             DWORD),
                ('Protect',           DWORD),
                ('Type',              DWORD))

PMEMORY_BASIC_INFORMATION = POINTER(MEMORY_BASIC_INFORMATION)

def errcheck_bool(result, func, args):
    if not result:
        raise WinError(get_last_error())
    return args

kernel32.VirtualQuery.errcheck = errcheck_bool
kernel32.VirtualQuery.restype = SIZE_T
kernel32.VirtualQuery.argtypes = (
    LPCVOID,                   # _In_opt_ lpAddress
    PMEMORY_BASIC_INFORMATION, # _Out_    lpBuffer
    SIZE_T)                    # _In_     dwLength

kernel32.OpenFileMappingW.errcheck = errcheck_bool
kernel32.OpenFileMappingW.restype = HANDLE
kernel32.OpenFileMappingW.argtypes = (
    DWORD,   # _In_ dwDesiredAccess
    BOOL,    # _In_ bInheritHandle
    LPCWSTR) # _In_ lpName

kernel32.MapViewOfFile.errcheck = errcheck_bool
kernel32.MapViewOfFile.restype = LPVOID
kernel32.MapViewOfFile.argtypes = (
    HANDLE, # _In_ hFileMappingObject
    DWORD,  # _In_ dwDesiredAccess
    DWORD,  # _In_ dwFileOffsetHigh
    DWORD,  # _In_ dwFileOffsetLow
    SIZE_T) # _In_ dwNumberOfBytesToMap

kernel32.CloseHandle.errcheck = errcheck_bool
kernel32.CloseHandle.argtypes = (HANDLE,)

if __name__ == '__main__':
    import mmap

    NPAGES = 9
    PAGE_SIZE = 4096

    TAGNAME = 'SHM_1001'
    mm1 = mmap.mmap(-1, PAGE_SIZE * NPAGES, TAGNAME)

    hMap = kernel32.OpenFileMappingW(FILE_MAP_ALL_ACCESS, False, TAGNAME)
    pBuf = kernel32.MapViewOfFile(hMap, FILE_MAP_ALL_ACCESS, 0, 0, 0)
    kernel32.CloseHandle(hMap)

    mbi = MEMORY_BASIC_INFORMATION()
    kernel32.VirtualQuery(pBuf, byref(mbi), PAGE_SIZE)

    assert divmod(mbi.RegionSize, PAGE_SIZE) == (NPAGES, 0)
    mm2 = (c_char * mbi.RegionSize).from_address(pBuf)

    # write using the mmap object
    mm1.seek(100)
    mm1.write(b'Windows')

    # read using the ctypes array
    assert mm2[100:107] == b'Windows'

rawDescription: mmap: can't attach to existing region without knowing its size (Windows)

description: Mmap: can't attach to existing region without knowing its size (Windows)


code:
import pygame

# you'll be able to shoot every 450ms
RELOAD_SPEED = 450

# the foes move every 1000ms sideways and every 3500ms down
MOVE_SIDE = 1000
MOVE_DOWN = 3500

screen = pygame.display.set_mode((300, 200))
clock = pygame.time.Clock()

pygame.display.set_caption("Micro Invader")

# create a bunch of events
move_side_event = pygame.USEREVENT + 1
move_down_event = pygame.USEREVENT + 2
reloaded_event  = pygame.USEREVENT + 3

move_left, reloaded = True, True

invaders, colors, shots = [], [] ,[]
for x in range(15, 300, 15):
    for y in range(10, 100, 15):
        invaders.append(pygame.Rect(x, y, 7, 7))
        colors.append(((x * 0.7) % 256, (y * 2.4) % 256))

# set timer for the movement events
pygame.time.set_timer(move_side_event, MOVE_SIDE)
pygame.time.set_timer(move_down_event, MOVE_DOWN)

player = pygame.Rect(150, 180, 10, 7)

while True:
    clock.tick(40)
    if pygame.event.get(pygame.QUIT): break
    for e in pygame.event.get():
        if e.type == move_side_event:
            for invader in invaders:
                invader.move_ip((-10 if move_left else 10, 0))
            move_left = not move_left
        elif e.type == move_down_event:
            for invader in invaders:
                invader.move_ip(0, 10)
        elif e.type == reloaded_event:
            # when the reload timer runs out, reset it
            reloaded = True
            pygame.time.set_timer(reloaded_event, 0)

    for shot in shots[:]:
        shot.move_ip((0, -4))
        if not screen.get_rect().contains(shot):
            shots.remove(shot)
        else:
            hit = False
            for invader in invaders[:]:
                if invader.colliderect(shot):
                    hit = True
                    i = invaders.index(invader)
                    del colors[i]
                    del invaders[i]
            if hit:
                shots.remove(shot)

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_LEFT]: player.move_ip((-4, 0))
    if pressed[pygame.K_RIGHT]: player.move_ip((4, 0))

    if pressed[pygame.K_SPACE]:
        if reloaded:
            shots.append(player.copy())
            reloaded = False
            # when shooting, create a timeout of RELOAD_SPEED
            pygame.time.set_timer(reloaded_event, RELOAD_SPEED)

    player.clamp_ip(screen.get_rect())

    screen.fill((0, 0, 0))

    for invader, (a, b) in zip(invaders, colors):
        pygame.draw.rect(screen, (150, a, b), invader)

    for shot in shots:
        pygame.draw.rect(screen, (255, 180, 0), shot)

    pygame.draw.rect(screen, (180, 180, 180), player)
    pygame.display.flip()

rawDescription: Move an object every few seconds in Pygame


code:
def simple_cull(inputPoints, dominates):
    paretoPoints = set()
    candidateRowNr = 0
    dominatedPoints = set()
    while True:
        candidateRow = inputPoints[candidateRowNr]
        inputPoints.remove(candidateRow)
        rowNr = 0
        nonDominated = True
        while len(inputPoints) != 0 and rowNr < len(inputPoints):
            row = inputPoints[rowNr]
            if dominates(candidateRow, row):
                # If it is worse on all features remove the row from the array
                inputPoints.remove(row)
                dominatedPoints.add(tuple(row))
            elif dominates(row, candidateRow):
                nonDominated = False
                dominatedPoints.add(tuple(candidateRow))
                rowNr += 1
            else:
                rowNr += 1

        if nonDominated:
            # add the non-dominated point to the Pareto frontier
            paretoPoints.add(tuple(candidateRow))

        if len(inputPoints) == 0:
            break
    return paretoPoints, dominatedPoints

def dominates(row, candidateRow):
    return sum([row[x] >= candidateRow[x] for x in range(len(row))]) == len(row)

import random
inputPoints = [[random.randint(70,100) for i in range(3)] for j in range(500)]
paretoPoints, dominatedPoints = simple_cull(inputPoints, dominates)

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
dp = np.array(list(dominatedPoints))
pp = np.array(list(paretoPoints))
print(pp.shape,dp.shape)
ax.scatter(dp[:,0],dp[:,1],dp[:,2])
ax.scatter(pp[:,0],pp[:,1],pp[:,2],color='red')

import matplotlib.tri as mtri
triang = mtri.Triangulation(pp[:,0],pp[:,1])
ax.plot_trisurf(triang,pp[:,2],color='red')
plt.show()

rawDescription: How to plot multi-objectives pareto frontier with DEAP in Python

description: Plot multi-objectives pareto frontier with DEAP in Python


code: print(max(['a', 'cat', 'sat', 'g'], key=lambda s: (len(s), s)))

rawDescription: finding longest word in a list python

description: Finding longest word in a list python


rawDescription: Running maximum of numpy array values

description: Running maximum of numpy array values


code:
import os, subprocess

d = dict(os.environ)   # Make a copy of the current environment
d['PYRO_HMAC_KEY'] = '123'
subprocess.Popen(['python', '-m', 'Pyro4.naming'], env=d)

rawDescription: python subprocess set shell var. and then run command - how?

description: Python subprocess set shell var. and then run command - how


code:
list_com_and_url = []
with open('my_file') as f:
    for line in f:
        name, url = line, next(f)
        list_com_and_url.append(zip(name, url))

rawDescription: How to read 2 value once in for loop by Python?

description: Read 2 value once in for loop by Python


code:
my_list = list(my_set)
my_list.sort()
chosen_element = my_list[0]

rawDescription: Select an item from a set in Python

description: Select an item from a set in Python


code:
with open("input.txt") as infile, open("output.txt", "w") as outfile:
    for line in infile:
        outfile.write("[" + ", ".join(line.strip().split()) + "]\n")

rawDescription: reading a set of points from file and making a .OFF file

description: Reading a set of points from file and making a .OFF file


code:
from collections import deque
d = deque(maxlen=2)
d.append(3)
d.append(4)
d.append(5)
d

rawDescription: Python: Limiting number of elements in an array


rawDescription: How do I get inside Python http.client.HTTPResponse objects?

description: Get inside Python http.client.HTTPResponse objects


code:
params = dict(ami='ami-XXX', key_name='XXX15a.pem', instance_type='t1.macro', placement='us-east-1a')
ec2_conn.run_instances(**params)

rawDescription: passing the values to a function

description: Passing the values to a function


code:
ax = plt.gca()
def format_coord(x, y):
    return 'x=%.4f, y=%.4f'%(m(x, y, inverse = True))
ax.format_coord = format_coord

rawDescription: Interactively get readable(i.e. lng/lat) coordinates from a matplotlib basemap plot?


rawDescription: Python list comparison differences

description: Python list comparison differences


code:
import json
import datetime
import dateutil.parser
import decimal

CONVERTERS = {
    'datetime': dateutil.parser.parse,
    'decimal': decimal.Decimal,
}

class MyJSONEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, (datetime.datetime,)):
            return {"val": obj.isoformat(), "_spec_type": "datetime"}
        elif isinstance(obj, (decimal.Decimal,)):
            return {"val": str(obj), "_spec_type": "decimal"}
        else:
            return super().default(obj)

def object_hook(obj):
    _spec_type = obj.get('_spec_type')
    if not _spec_type:
        return obj

    if _spec_type in CONVERTERS:
        return CONVERTERS[_spec_type](obj['val'])
    else:
        raise Exception('Unknown {}'.format(_spec_type))

def main():
    data = {
        "hello": "world",
        "thing": datetime.datetime.now(),
        "other": decimal.Decimal(0)
    }
    thing = json.dumps(data, cls=MyJSONEncoder)

    print(json.loads(thing, object_hook=object_hook))

if __name__ == '__main__':
    main()

rawDescription: Parsing datetime in python json loads

description: Parsing datetime in python json loads


code:
rows = {}

with open(inputfilename, 'rb') as inputfile:
    reader = csv.reader(inputfile)
    headers = next(reader)  # collect first row as headers for the output
    for row in reader:
        key = (row[0], row[1][:5])
        if key not in rows:
            rows[key] = row + [0,]
        rows[key][-1] += 1  # count

with open('myfilewithoutduplicates.csv', 'wb') as outputfile:
    writer = csv.writer(outputfile)
    writer.writerow(headers + ['Count'])
    writer.writerows(rows.itervalues())

rawDescription: Remove duplicate rows from csv file based on 2 columns with regex in Python


code:
f = io.BytesIO(b'abc')
view = f.getbuffer()
view[:] = b'def'
f.getvalue()
view[3] = b'g'
f.seek(0, 2)
f.write(b'g')
del view
f.write(b'g')
f.getvalue()

rawDescription: Python 3 - non-copying stream interface to bytearray?


rawDescription: Python list element syntax

description: Python list element syntax


code:
import youtube_dl

options = {
    'format': 'bestaudio/best',  # choice of quality
    'extractaudio': True,        # only keep the audio
    'audioformat': "mp3",        # convert to mp3
    'outtmpl': '%(id)s',         # name the file the ID of the video
    'noplaylist': True,          # only download single song, not playlist
    'listformats': True,         # print a list of the formats to stdout and exit
}

with youtube_dl.YoutubeDL(options) as ydl:
    ydl.download(['http://www.youtube.com/watch?v=BaW_jenozKc'])

rawDescription: How can I list video resolutions in youtube-dl while using it as a python module?

description: List video resolutions in youtube-dl while using it as a python module


code:
import sys

def main():
   input1 = sys.argv[1]
   input2 = sys.argv[2]
...

if __name__ == "__main__":
   main()

rawDescription: how to input variable into a python script while opening from cmd prompt?

description: Input variable into a python script while opening from cmd prompt


code:
from sys import stdin
from math import sqrt, ceil

next(stdin) # skip unecessary line

def is_prime(number):
    initial_divider = sqrt(number)

    if number % 2 == 0 or int(initial_divider) == initial_divider:
      return False

    for divider in range(2, ceil(initial_divider)+1):
        if number % divider == 0:
            return False

    return True

for line in stdin:
    low, high = [int(x) for x in line.split(' ')]
    primes = '\n'.join(str(number) for number
                     in range(max(low, 3), high+1)
                     if is_prime(number))

    if low <= 2: print(2)
    print (primes)
    print('')

rawDescription: printing all prime numbers in given range, algorithm too slow.. how to improve? (code-challenge)

description: Printing all prime numbers in given range, algorithm too slow.. how to improve? (code-challenge)


code:
graph = facebook.GraphAPI(oauth_access_token)
photo = open("picture.jpg", "rb")
graph.put_object("me", "photos", message="You can put a caption here", source=photo.read())
photo.close()

rawDescription: Post picture to Facebook using Python

description: Post picture to Facebook using Python


code: img_id="{{ message.key }}"

rawDescription: db.key() function to a string representation and back

description: Db.key() function to a string representation and back


code:
import operator

def equalize(im):
    h = im.convert("L").histogram()
    lut = []
    for b in range(0, len(h), 256):
        # step size
        step = reduce(operator.add, h[b:b+256]) / 255
        # create equalization lookup table
        n = 0
        for i in range(256):
            lut.append(n / step)
            n = n + h[i+b]
    # map image through lookup table
    return im.point(lut*im.layers)

rawDescription: Normalize histogram (brightness and contrast) of a set of images using Python Image Library (PIL)


code:
from collections import Counter
from itertools import combinations

d  = Counter()
for sub in a:
    if len(a) < 2:
        continue
    sub.sort()
    for comb in combinations(sub,2):
        d[comb] += 1

print(d.most_common())
[(('Jennifer', 'John'), 3), (('John', 'Mark'), 2), (('Jennifer', 'Mark'), 2), (('Anna', 'John'), 1), (('Joe', 'Mark'), 1), (('Anna', 'Jennifer'), 1)]

rawDescription: Finding the most frequent occurrences of pairs in a list of lists


code:
import matplotlib.pyplot as plt
G = nx.karate_club_graph()
pos = nx.spring_layout(G)
nx.draw(G,pos,node_color='k')
# draw path in red
path = nx.shortest_path(G,source=14,target=16)
path_edges = zip(path,path[1:])
nx.draw_networkx_nodes(G,pos,nodelist=path,node_color='r')
nx.draw_networkx_edges(G,pos,edgelist=path_edges,edge_color='r',width=10)
plt.axis('equal')
plt.show()

rawDescription: Highlighting the shortest path in a Networkx graph


code:
def Lap(self):
    if len(self.laps) == 3:
        return
    tempo = self._elapsedtime - self.lapmod2
    if self._running:
        self.laps.append(self._setLapTime(tempo))
        self.m.insert(END, self.laps[-1])
        self.m.yview_moveto(1)
        self.lapmod2 = self._elapsedtime

rawDescription: How to make a Listbox limits to 3 column in Tkinter?

description: Make a Listbox limits to 3 column in Tkinter


rawDescription: Vectorized implementation to get index of minimum element in each row


code:
from django.utils.html import escape

def create_markup(event):
    output = ...
    return escape(output)

rawDescription: Looking for a simple way to display a code block in Django admin


code:
# setup.py
from distutils.core import setup
import py2exe,sys,os

origIsSystemDLL = py2exe.build_exe.isSystemDLL
def isSystemDLL(pathname):
        if os.path.basename(pathname).lower() in ("msvcp71.dll", "dwmapi.dll"):
                return 0
        return origIsSystemDLL(pathname)
py2exe.build_exe.isSystemDLL = isSystemDLL

rawDescription: py2exe - How do I reduce dll dependencies?

description: Py2exe - How do I reduce dll dependencies


code:
def main():
    run_my_stuff()

if __name__ == "__main__":
    main()

rawDescription: How to run a python program that uses numpy on multiple cores, preferably using threading

description: Run a python program that uses numpy on multiple cores, preferably using threading


code:
class UseThread(threading.Thread):
    def __init__(self, devID):
        super(UseThread, self).__init__()
        self.devID = devID
    def run(self):
        ## threaded stuff ....
        ## threaded stuff ....
        pass

## ...
for devID in line:
   t=UseThread(devID) # this calls UseThread.__init__()
   t.start()          # this creates a new thread that will run UseThread.run()

rawDescription: Thread in python not working

description: Thread in python not working


code: [sum(i) for i in zip(*key)]

rawDescription: Python: sum elements in the same places of nested lists


code:
s = s.replace("\r\n", "
")
s = s.replace("\n", "
")

rawDescription: Converting Carriage Return to HTML Break


code:
# Function to Create user Account/Profile
def create_user_account(sender, instance, created, **kwargs):
    if created:
        attrs_needed = ['_language', '_field', '_otherfield']
        if all(hasattr(instance, attr) for attr in attr_needed):
            models.Account.objects.create(
                user=instance,
                language=instance._language,
                field=instance._field,
                otherfield=instance._otherfield)

# Create User / User Registration
def UserRegistration(request):
  if request.method == 'POST':
    username = request.POST['fn'].capitalize() + ' ' + request.POST['ln'].capitalize()
    # CREATE USER
    newuser = User.objects.create_user(
        username=username, email=request.POST['email'],
        password=request.POST['pw'])
    newuser.first_name = request.POST['fn'].capitalize()
    newuser.last_name = request.POST['ln'].capitalize()

    # Set some extra attrs to the instance to be used in the handler.
    newuser._language = request.POST['language']
    newuser._field = request.POST['field']
    newuser._otherfield = request.POST['otherfield']
    newuser.save()

  return HttpResponse(username)

#Post Save handler to create user Account/Profile
post_save.connect(create_user_account, sender=User)

rawDescription: Pass additional parameters to post_save signal


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

def annotate_axes(x1,y1,x2,y2,x3,y3,text):
    ax.annotate('', xy=(x1, y1),xytext=(x2,y2),             #draws an arrow from one set of coordinates to the other
            arrowprops=dict(arrowstyle='<->'),              #sets style of arrow
            annotation_clip=False)                          #This enables the arrow to be outside of the plot

    ax.annotate(text,xy=(0,0),xytext=(x3,y3),               #Adds another annotation for the text
                annotation_clip=False)

fig, ax = plt.subplots()
image=np.random.rand(10,10)
plt.imshow(image)
plt.colorbar()

#annotate x-axis
annotate_axes(-0.5,10,4.5,10,2.5,10.5,'A')       # changing these changes the position of the arrow and the text
annotate_axes(5,10,9.5,10,7.5,10.5,'B')

#annotate y-axis
annotate_axes(-1,0,-1,4,-1.5,2,'A')
annotate_axes(-1,4.5,-1,9.5,-1.5,7.5,'B')

plt.show()

rawDescription: putting some text to a python plot

description: Putting some text to a python plot


rawDescription: Control LaTeX expression color in ipython qtconsole


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

runoff = np.array([1,4,5,6,7,8,9])
precipitation = np.array([4,5,6,7,3,3,7])

fig, ax = plt.subplots()

# x axis to plot both runoff and precip. against
x = np.linspace(0, 10, len(runoff))

ax.plot(x, runoff, color="r")

# Create second axes, in order to get the bars from the top you can multiply
# by -1
ax2 = ax.twinx()
ax2.bar(x, -precipitation, 0.1)

# Now need to fix the axis labels
max_pre = max(precipitation)
y2_ticks = np.linspace(0, max_pre, max_pre+1)
y2_ticklabels = [str(i) for i in y2_ticks]
ax2.set_yticks(-1 * y2_ticks)
ax2.set_yticklabels(y2_ticklabels)

plt.show()

rawDescription: Plotting a hydrograph-precipitation plot


code:
def check_lower(pair):
    key,value = pair
    return (key.lower(),value)

meaningHash={'Banana':'fruit','apple':'fruit'}

sortedMeaningHash = collections.OrderedDict(sorted(meaningHash.items(),
                                                    key=check_lower))
print(sortedMeaningHash)

rawDescription: How can I sort a dictionary by key incasesensitive?

description: Sort a dictionary by key incasesensitive


code:
response = urllib2.urlopen(url)
fh = BytesIO(response.read())
media_body = MediaIoBaseUpload(fh, mimetype='image/jpeg',
              chunksize=1024*1024, resumable=True)
body = {
        'title': 'pic.jpg'
    }
drive_service.files().insert(body=body, media_body=media_body).execute()

rawDescription: Google Drive Python API; upload a media object which is NOT a file


code:
import re

pin_pattern = re.compile(r'^(\d{1,2})(\d{3})(\d{4})(\d{3})?$')

pin_formats = {
    3: '{0:02d}-{1:03d}-{2:04d}',
    4: '{0:02d}-{1:03d}-{2:04d}-{3:03d}'
}

def parse_pin(s):
    groups = [int(d) for d in pin_pattern.search(s).groups() if d is not None]
    return pin_formats[len(groups)].format(*groups)

rawDescription: formatting a string where variable does not always exist in Python

description: Formatting a string where variable does not always exist in Python


code:
def mergeList(lst1,lst2):
    lst3 = [item for t in zip(lst1, lst2) for item in t]
    if len(lst2) > len(lst1):
        lst3 += lst2[len(lst1):]
    if len(lst1) > len(lst2):
        lst3 += lst1[len(lst2):]
    return lst3

rawDescription: Why this is giving me out of range(lst3.append(lst4 [ j ] ) )?


code:
entities = Model.get_by_key_name(key_names)
content_keys = [db.Key.from_path('Model', name, 'ContentModel', name)
                for name in key_names]
content_entities = ContentModel.get(content_keys)

rawDescription: Getting a list of child entities in App Engine using get_by_key_name (Python)


code: span = cat.xpath('span/span')

rawDescription: How to navigate through elements in lxml?

description: Navigate through elements in lxml


code:
for key, value in animals.iteritems():
    if key == 'ANIMALS':
        for name in value:
            text.replace(name,""+name+"")

rawDescription: BeautifulSoup. Find and replace all instances of a word with one from my list


code:
df['Data_lagged'] = df.groupby(['Group'])['Data'].shift(1)
df

rawDescription: Pandas equivalent of Oracle Lead/Lag function


code:
import os.path

subdirectory = datetime + "-dst"
try:
    os.mkdir(subdirectory)
except Exception:
    pass

for ip in open("list.txt"):
    with open(os.path.join(subdirectory, ip.strip() + ".txt"), "a") as ip_file:
        ...

rawDescription: Create file in sub directory Python?

description: Create file in sub directory Python


code:
def symmetric_enc(message, key):
    return [ord(char) ^ key for char in message]

def symmetric_dec(cipher, key):
    return ''.join(num ^ key for num in cipher)

def asymmetric_enc(message, pubkey) :
    msg = [ord(char) for char in message]
    e,n = pubkey
    c = [m**e%n for m in msg]
    return c

def asymmetric_dec(cipher, prikey) :
    d,n = prikey
    msg = [c**d%n for c in cipher]
    msg = [chr(m) for m in msg]
    message = ''.join(msg)
    return message

def enc(message, pubkey):
    session_key = random.randrange(1, 256)
    return (asymmetric_enc(session_key, pubkey),
            symmetric_enc(message, session_key))

def dec(message, prikey):
    session_key, body = message
    session_key = asymmetric_dec(session_key, prikey)
    return symmetric_dec(body, session_key)

rawDescription: Add randomness to a simple RSA encryption example


code:
import xml.etree.ElementTree as etree
tree = etree.fromstring("<all_products><product instrument_name='nice_instrument'></product></all_products>")
product_iter = tree.iterfind("product[@instrument_name='nice_instrument']")
products = list(product_iter)
len(products)
len(products)

rawDescription: lenght of a list of elementtree turn 0 after second call

description: Lenght of a list of elementtree turn 0 after second call


code:
pos = {}
for node in G.nodes():
    pos[node] = (xcoord,ycoord)

nx.draw(G,pos)

rawDescription: Fixed position hierarchical output from NetworkX without graphviz?


code:
import tkinter as tk

colors = (
    #background, #activebackground
    ("#F4C364", "#826232"), #tan
    ("#111111", "#777777"), #black
    ("#DDDDDD", "#E8C8A8"),  #white
)

class Tile(object):
    """ A tile is a point on a game board where black or white pieces can be placed.
        If there are no pieces, it remains tan.
        The basic feature is the "core" field which is a tkinter button.
        when the color is changed, the button is configured to represent this.
    """

    def __init__(self, win, x, y):
        #States: 0=empty, 1=black, 2=white
        self.state = 0
        bg, abg = colors[self.state]

        self.core = tk.Button(win, height=2, width=3,
            bg=bg, activebackground=abg,
            command=self.cycle)
        self.core.grid(row=y, column=x)

        #self.location = x, y

    def cycle(self):
        """ the cycle function makes the tile object actually change color,
            going between three options: black, white, or tan.
        """
        #cycle to the next state. 0 -> 1 -> 2 -> 0
        self.state = (self.state + 1) % 3
        bg, abg = colors[self.state]
        self.core.config(bg=bg, activebackground=abg)

        #print(self.location)

window = tk.Tk()
n = 9

board = []
for y in range(n):
    row = [Tile(window, x, y) for x in range(n)]
    board.append(row)

window.mainloop()

rawDescription: (Instantiating an array of Buttons, but only one works


code:
import tornado.ioloop
import tornado.web
from PIL import Image
import cStringIO as StringIO

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("<img src='http://localhost:8888/img'>")

class ImgHandler(tornado.web.RequestHandler):
    img_name = "bg.jpg"
    img = pygame.image.load(img_name)
    str_img = pygame.image.tostring(img, "RGB")
    size = img.get_size()
    fimg = Image.frombytes("RGB", size, str_img, "raw")
    fobj = StringIO.StringIO()
    fimg.save(fobj, format="png")  #jpeg encoder isn't available in my install...
    for line in fobj.getvalue():
        self.write(line)
    self.set_header("Content-type",  "image/png")

application = tornado.web.Application([
    (r"/", MainHandler),
    (r"/img", ImgHandler),
    #(r'/(.*)', tornado.web.StaticFileHandler, {'path': ''})
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: Serving Images using Tornado without File I/O


code:
condlist = [omega < 0.0, omega >= 2.0*np.pi]
choicelist = [omega + 2.0*np.pi, omega - 2.0*np.pi]
omega = np.select(condlist,choicelist,default=omega)

rawDescription: numpy slice assignment

description: Numpy slice assignment


code:
names = ['Server1', 'Server2', 'Server3']
inactives = {}

for name in names:
    inactives[name] = []

currentServer = None
for line in open('/home/Workspace/temp2'):
    if line.strip() in names:
        currentServer = line.strip()
        active = None

    if line.startswith('Currently Active Slave: '):
        active = line.split(':')[-1].strip()

    if active and line.startswith('Slave Interface: '):
        interface = line.split(':')[-1].strip()

        if interface != active:
            inactives[currentServer].append(interface)

print(inactives)

rawDescription: Parse a file to find inactive elements

description: Parse a file to find inactive elements


code:
@task(alias = 'database-reset')
def database_reset():
    ...

rawDescription: Can fabric tasks have names that are not valid Python function names?


code:
def getBlendShape(shape):
    '''
    @param Shape: Name of the shape node.
    Returns MFnBlendShapeDeformer node or None.
    '''
    # Create an MDagPath for our shape node:
    selList = OpenMaya.MSelectionList()
    selList.add(shape)
    mDagPath = OpenMaya.MDagPath()
    selList.getDagPath(0, mDagPath)

    #Create iterator.
    mItDependencyGraph = OpenMaya.MItDependencyGraph(
        mDagPath.node(),
        OpenMaya.MItDependencyGraph.kPlugLevel)

    # Start walking through our shape node's dependency graph.
    while not mItDependencyGraph.isDone():
        # Get an MObject for the current item in the graph.
        mObject = mItDependencyGraph.currentItem()
        # It has a BlendShape.
        if mObject.hasFn(OpenMaya.MFn.kBlendShape):
            # return the MFnSkinCluster object for our MObject:
            return OpenMayaAnim.MFnBlendShapeDeformer(mObject)
        mItDependencyGraph.next()

if __name__ == '__main__':
    #TargetMesh
    targetMesh = "pSphereShape1"

    #Get Blendshape.
    blndShpNode = getBlendShape(targetMesh)

    if blndShpNode:
        #Get base objects.
        mObjArr = OpenMaya.MObjectArray()
        blndShpNode.getBaseObjects(mObjArr)
        mDagPath = OpenMaya.MDagPath()
        OpenMaya.MFnDagNode(mObjArr[0]).getPath(mDagPath)
        print(mDagPath.fullPathName())

    else:
        print("No Blendshape found.")

rawDescription: Finding Blendshape from Target Maya Python API


rawDescription: Scaling regex on big strings in Python

description: Scaling regex on big strings in Python


code:
s = 'word1 word2 word3'
s.split(' ', 1)
s.split(' ', 1)[1]

rawDescription: Remove the first word in a Python string?


code:
from twisted.python.log import err
from twisted.internet.protocol import Protocol

class YourProtocol(Protocol):
    ...
    def messageReceived(self, message):
        d = lookupWebService(message)
        d.addCallback(queryDatabase)
        d.addCallback(saveResults)
        d.addErrback(err, "Servicing %r failed" % (message,))

rawDescription: Python Twisted TCP application - How to prevent incoming message loss by blocking process


code:
from operator import itemgetter
x = n = o = u = 0
items = itemgetter('a','n','o','u')
for entry in indata:
    A,N,O,U = items(entry)
    x += A*N  # n - number of data points
    n += N
    o += O    #don't know what you're doing with O or U, but I'll leave them
    u += U

average = int(round(x / n)), n, o, u

rawDescription: Optimization of average calculation from a list of dictionaries


code:
from signal import alarm, signal, SIGALRM, SIGKILL

TIMEOUT=-9

def run_proc_timeout(proc, timeout):

    class _Alarm(Exception):
        pass

    def alarm_handler(signum, frame):
        raise _Alarm

    # setup alarm for timeout length
    signal(SIGALRM, alarm_handler)
    alarm(timeout)

    try:
        stdout, stderr = proc.communicate()
        alarm(0)
    except _Alarm:
        pids = [proc.pid]
        # kill proc and all its children
        return TIMEOUT, "", ""

    return proc.returncode, stdout, stderr

rawDescription: Timing a process started by a batch file which was called in python


code:
import gtk

def _clipboard_changed(clipboard, event):
    text = clipboard.wait_for_text()

clip = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)
clip.connect("owner-change", _clipboard_changed)

rawDescription: How do I get the selected text in desktop application using python-dbus?

description: Get the selected text in desktop application using python-dbus


code:
def example_function(self):
    number = self.lineEdit_4.text() #Takes input from GUI
    start = "python3 /path/to/launched/script.py "+variable1+" "+variable2+" "+variable3 #Bash command to execute python script with args.
    procs = []
    for i in range(0,number):
        x = subprocess.Popen(start,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)#Launch another script as a subprocess
        procs.append(x)
    # Do stuff
    ...
    # Now kill all the subprocesses
    for p in procs:
        p.kill()

rawDescription: How can I terminate all child processes opened in subprocess

description: Terminate all child processes opened in subprocess


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

# fake date
genes = 10*np.random.rand(10,5)
age = 10*np.random.rand(5)

# plot the data
plt.boxplot(genes)
h, = plt.plot(range(1,6),age,'go',ms=15) # used a large marker size so these points show up.

# add a legend
plt.legend([h],['age'],numpoints=1)

plt.show()

rawDescription: Matplotlib Box and Whisker with Points

description: Matplotlib Box and Whisker with Points


code:
import sys
import time  # for invoking time.sleep(n_seconds) inside loop

counter = 0
while counter <= 100:
    time.sleep(1)
    counter += 1
    sys.stdout.write("\rTesting (%ss elapsed)" % counter)
    sys.stdout.flush()

rawDescription: print progress counter of python in DOS

description: Print progress counter of python in DOS


rawDescription: Python integer infinity for slicing

description: Python integer infinity for slicing


code:
list1 = []
list2 = []
with open("input.csv", "rb") as f:
    for record in csv.reader(f, delimiter=";"):
        if len(record) == 3:
            list1.append(record)
        else:
            list2.append(record)

rawDescription: How to parse a mixed CSV file in Python?

description: Parse a mixed CSV file in Python


code:
import subprocess
pro = subprocess.Popen("cmd", stdout=subprocess.PIPE, stdin=subprocess.PIPE)
pro.stdin.write("mybat.bat\n")
pro.stdin.write("myother.bat\n")
pro.stdin.write("start mysillyprogram\n")
pro.stdin.flush()
pro.terminate() # kill the parent

rawDescription: Python/CMD command

description: Python/CMD command


code:
import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
import numpy as np
import sys
import Tkinter as tk
import time

def function1(fig, ax):
    ax.cla()
    color_grade_classes = ['#80FF00','#FFFF00','#FF8000', '#FF0000']
    varsi =  random.randint(1, 100)

    for colors, rows  in zip(color_grade_classes, [3,2,1,0] ):
        indexs = np.arange(5)
        heights = [varsi,varsi/2,varsi/3,0,0]
        ax.bar(indexs, heights, zs = rows,  zdir='y', color=colors, alpha=0.8)
    return fig

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.root.wm_title("Embedding in TK")

        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111, projection='3d')
        self.ax.set_xlabel('X')
        self.ax.set_ylabel('Y')
        self.fig = function1(self.fig, self.ax)

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.root)
        self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.root )
        self.toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        self.fig = function1(self.fig,self.ax)
        self.canvas.show()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

rawDescription: matplotlib draw() freezes window

description: Matplotlib draw() freezes window


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

class Pendulum:

    def __init__(self):
        self.fig = plt.figure()

    def plot1(self):
        ax = self.fig.add_subplot(211)
        ax.plot([1,2],[3,4])

    def plot2(self):
        ax = self.fig.add_subplot(212)
        ax.plot([1,2],[4,3])

p = Pendulum()
p.plot1()
p.plot2()
plt.show()

rawDescription: Matplotlib: plot multiple graphs as subplots on the same figure when different functions in the same class call the plot routine?


code:
from csv import writer
from itertools import izip_longest

GO_list = {'Seq_A': ['GO:1234', 'GO:2345', 'GO:3456'],
'Seq_B': ['GO:7777', 'GO:8888']}

with open("test.csv","wb") as csvfile:
    wr = writer(csvfile)
    wr.writerow(GO_list.keys())#writes title row
    for each in izip_longest(*GO_list.values()): wr.writerow(each)

rawDescription: Write dictionary of lists (varying length) to csv in Python


code:
# imports
import pandas as pd

# Create a sample DataFrame.
cols = ['store_name', 'sku', 'comp', 'price', 'ship', 'comp_url']
records = [['CSA', 'A1025', 'compA', 30.99, 9.99, 'some url'],
           ['CSB', 'A1025', 'compB', 32.99, 9.99, 'some url2'],
           ['CSA', 'A1026', 'compC', 30.99, 19.99, 'some url'],
           ['CSB', 'A1026', 'compD', 30.99, 9.99, 'some url3']]
df = pd.DataFrame.from_records(records, columns=cols)

# Move both 'sku' and 'store_name' to the rows index; the combination
# of these two columns provide a unique identifier for each row.
df.set_index(['sku', 'store_name'], inplace=True)
# Move 'store_name' from the row index to the column index. Each
# unique value in the 'store_name' index gets its own set of columns.
# In the multiindex, 'store_name' will be below the existing column
# labels.
df = df.unstack(1)
# To get the 'store_name' above the other column labels, we simply
# reorder the levels in the MultiIndex and sort it.
df.columns = df.columns.reorder_levels([1, 0])
df.sort_index(axis=1, inplace=True)

# Show the result.
df

rawDescription: Reshaping non-numeric values in pandas dataframe


code:
import re
s = "maria 10 years maria 10 maria10 maria10 years"
re.findall(r"(\maria\s?[0-9]+)\s(?!years)", s)

rawDescription: Negative Lookahead matching

description: Negative Lookahead matching


code:
import datetime
from matplotlib import pyplot as plt
from matplotlib.dates import date2num

def date_to_days(date):
    return date2num(datetime.datetime.strptime(date, '%Y-%m-%d'))

def time_to_hours(time):
    [hh, mm, ss] = [int(x) for x in time.split(':')]
    seconds = datetime.timedelta(hours=hh, minutes=mm, seconds=ss).seconds
    hours = seconds / float(3600)
    return hours

if __name__ == '__main__':
    start_date = '2015-08-01'
    end_date = '2015-12-31'

    dates = ['2015-12-20','2015-09-12']
    times = ['22:50:12','19:33:09']

    days = [date_to_days(d) for d in dates]
    hours = [time_to_hours(t) for t in times]

    plt.plot_date(days, hours, ydate=False)
    plt.axis([date_to_days(start_date), date_to_days(end_date), 0, 24])
    plt.xlabel('Date')
    plt.ylabel('Time (hours)')
    plt.show()

rawDescription: Plot date and time on a matplotlib scatter graph using lists


code:
#!/usr/bin/python
import sys
import gzip

f = open('out.gz', 'wb')
gz = gzip.GzipFile('', 'wb', 9, f, 0.)
gz.write('this is a test')
gz.close()
f.close()

rawDescription: Python gzip omit the original filename and timestamp


rawDescription: decode self.request.body

description: Decode self.request.body


code:
import subprocess
p = subprocess.Popen(['lessc', '-x', '-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
output = p.communicate(less_content)

rawDescription: Using Unix command (node.js/lessc in my case) inside python?


code:
initialNumber = (raw_input("Enter your 10 digit number: "))

while len(str(initialNumber)) != 10:
    print("Next time please enter a 10 digit numerical value excluding decimals...")
    time.sleep(1)
    initialNumber = (raw_input("Enter your 10 digit number: "))

leadingZeros = (len(initialNumber) - len(str(int(initialNumber)))) * "0"

calculator()

rawDescription: How can I have an int variable with 0 as the first number in Python?

description: Have an int variable with 0 as the first number in Python


code:
result = [vapp for vapp in vapps if
          vapp['name'] in names and
          (names.remove(vapp['name']) or 1)]
names # now contains names not found in vapps

rawDescription: Python : filter list items from list of dictionary


code:
def login_required(self, f):
    @wraps(f)
    def decorated(*args, **kwargs):
        ...

rawDescription: Is there a pythonic way to skip decoration on a subclass' method?


code:
#Bind listbox selection into entry field
def get_list(event):
    index = listbox1.curselection()[0]
    seltext = listbox1.get(index)
    enter1.delete(0, 50)
    enter1.insert(0, seltext)

#Bind entry text into listbox
def set_list(event):
    try:
        index = listbox1.curselection()[0]
        listbox1.delete(index)
    except IndexError:
        index = tk.END
    listbox1.insert(index, enter1.get())

listbox1 = tk.Listbox(root, width=50, height=6)
listbox1.grid(row=0, column=0)

enter1 = tk.Entry(root, textvariable=source, width=50)
enter1.insert(0, 'Click on Fetch Button, then select item in the listbox')
enter1.grid(row=1, column=0)

enter1.bind('<Return>', set_list)
enter1.bind('<Double-1>', set_list)

listbox1.bind('<ButtonRelease-1>', get_list)

rawDescription: Load Listbox Selection into Entry Box with Sqlite3 Connection


code:
vowels = 'aeiou'
s = 'fooBArSpaM'
sum(c.lower() in vowels for c in s)

rawDescription: Find multiple list items within a string


code:
def OnBoxChecked(self, event):
    if self.HideToolbarMenuItem.IsChecked():
        self.statusbar.SetStatusText('Checked')
    else:
        self.statusbar.SetStatusText('Not Checked')

rawDescription: Checkbox menu items in wxPython

description: Checkbox menu items in wxPython


code: null_data = df[df.isnull().any(axis=1)]

rawDescription: Python, Pandas : Return only those rows which have missing values


code:
t = time.localtime()
suffix = 'st' if t.tm_mday in [1,21,31] else 'nd' if t.tm_mday in [2, 22] else 'rd' if t.tm_mday in [3, 23] else 'th'
time.strftime('%d%%s %B %Y', t) % suffix

rawDescription: Python equivalent of PHP's date()

description: Python equivalent of PHP's date()


code:
re_newspeaker =         r'^(<bullet> |  )(?P<name>(%s|(((Mr)|(Ms)|(Mrs))\. [-A-Z\']+|((Miss) [-A-Z\']+)( of [A-Z][a-z]+)?))|((The ((VICE|ACTING|Acting) )?(PRESIDENT|SPEAKER|CHAIR(MAN)?)( pro tempore)?)|(The PRESIDING OFFICER)|(The CLERK)|(The CHIEF JUSTICE)|(The VICE PRESIDENT)|(Mr\. Counsel [A-Z]+))( \([A-Za-z.\- ]+\))?)\.'

re_speaking =           r'^(<bullet> |  )((((((Mr)|(Ms)|(Mrs))\. [A-Z\']+|((Miss) [-A-Z\']+)(of [A-Z][a-z]+)?)|((The (VICE |Acting |ACTING )?(PRESIDENT|SPEAKER)( pro tempore)?)|(The PRESIDING OFFICER)|(The CLERK))( \([A-Za-z.\- ]+\))?))\. )?(?P<start>.)'

rawDescription: Python Regex Matching Apostrophes

description: Python Regex Matching Apostrophes


code:
output_list, temp_list, list_two = [], [], []
input_list = [...]
for element in input_list:
    if element not in list_two:
         list_two.append(element)

for index, val in enumerate(list_two, start=1):
    temp_list.append(val)
    if index % 3 == 0:
        output_list.append(temp_list)
        temp_list = []

if temp_list:
    output_list.append(temp_list)

rawDescription: Take a list of elements, insert non-unique elements, then return a list of lists of three elements.


code:
sensors = [sensor_1, sensor_2, sensor3]
for sensor in sensors:
    sensor.get_status()

rawDescription: Python: Calling functions whose names are stored in variables


code:
list1 = [["Value1",1],["Value2",3],["Value3",2]]
list1.sort(key=lambda x: x[1])
list1

rawDescription: Sorting List of Lists of Strings and Integers


code:
template = get_template('email/email_blast_template.html')
body = template.render(context)

connection = get_connection()
connection.open()

for recipient in recipients:
    email = EmailMultiAlternatives()
    email.subject = email_script.subject
    email.from_email = DEFAULT_FROM_EMAIL
    email.bcc = recipient
    email.body = body.replace('{email}', recipient)
    email.attach_alternative(body.replace('{email}', recipient), "text/html")
    email.connection = connection
    email.send()

connection.close()

rawDescription: Creating a unsubscribe link while sending a mass email


code:
with open(sys.argv[1]) as f:
  L1, L2, L3 = (line.rstrip() for line in f.readlines()[:3])

rawDescription: reading a file and getting each line of the file separately

description: Reading a file and getting each line of the file separately


code:
from tempfile import mktemp
from os import path
from os import remove as delfile
class excel:
    def __init__( self):
        self.app = DispatchEx( "Excel.Application" )
        self.dct =     {51:'xlsx',
                        52:'xlsm',
                        50:'xlsb',
                        56:'xls'
                        }

    def saveas_default_ext_format( self, workbook, filename):
        # filename - file name with path but without extension

        fullname = '.'.join((filename, self.dct[self.app.DefaultSaveFormat]))
        workbook.SaveAs( fullname)

        return fullname

rawDescription: excel how to find the default file extension

description: Excel how to find the default file extension


rawDescription: How do I insert multiple copies of an integer into the middle of a list?

description: Insert multiple copies of an integer into the middle of a list


code:
datain = msk_array

fig = plt.figure(figsize=(12,5))
map = Basemap(projection='robin',resolution='c',lat_0=0,lon_0=0)

ny, nx = datain.shape

xin = np.linspace(map.xmin,map.xmax,nx) # nx is the number of x points on the grid
yin = np.linspace(map.ymin,map.ymax,ny) # ny in the number of y points on the grid

lons = np.arange(-180,180,0.25) #from raster.GetGeoTransform()
lats  = np.arange(90,-90,-0.25)

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

xx, yy = m(lons,lats)

levels = [-1000,-800,-600,-400,-200,0,200,400,600,800,1000]
cntr = map.contourf(xx, yy,datain, levels,cmap=cm.RdBu)

cbar = map.colorbar(cntr,location='bottom',pad='15%')

# Add some more info to the map
cstl = map.drawcoastlines(linewidth=.5)
meri = map.drawmeridians(np.arange(0,360,60), linewidth=.2, labels=[1,0,0,1], labelstyle='+/-', color='grey' )
para = map.drawparallels(np.arange(-90,90,30), linewidth=.2, labels=[1,0,0,1], labelstyle='+/-', color='grey')
boun = map.drawmapboundary(linewidth=0.5, color='grey')

rawDescription: How to correctly project a tif image using matplotlib-basemap

description: Correctly project a tif image using matplotlib-basemap


code:
user_input = (numinput("New Letter Height", "Please set the new letter height: ",
                             minval=10, maxval=170))
letter_height = letter_height if user_input is None else user_input

rawDescription: Store and return a previous value for same variable


code:
dict1 = {'Jamal': 10, 'Steve': 20}
dict2 = {'Frank': 200, 'Steve': 30}
dict3 = {'Carl': 14, 'Jamal': 26}
import itertools
it = itertools.chain.from_iterable(d.items() for d in (dict1, dict2, dict3))
', '.join('{}: {}'.format(*x) for x in sorted(it, key=lambda x: x[1], reverse=True))

rawDescription: Combining and ordering dictionaries in python


code:
cur.execute('''select * from sqlite_master''')
l = cur.fetchall()
#we will populate a list with the names of your tables
tbl_name_list = []
for sql_type, sql_name, tbl_name, rootpage, sql in l:
    if sql_type == 'table':
        tbl_name_list.append(sql_name)
#your list of table names is constructed
print(tbl_name_list)

rawDescription: How to get table name of the executed query? (python / sqlite)

description: Get table name of the executed query? (python / sqlite)


code:
import sys
sys.path.append("/home/usuario/Desktop/")

import my_proyect

rawDescription: Is it possible to create a temporary python file and import the class and attribute of that .py file


code: ['{}{}'.format(a,b) for a,b in zip(list1, list2)]

rawDescription: Combining elements in Python

description: Combining elements in Python


code: [ [letter for letter in List if letter not in stoplist] for List in nested]

rawDescription: Nested Python list comprehension

description: Nested Python list comprehension


rawDescription: How to know how many bytecodes a python program executes at runtime

description: Know how many bytecodes a python program executes at runtime


code:
self.Bind(wx.EVT_CHECKLISTBOX, self.check_list_param, self.list_param)

def check_list_param(self, evt):
    checked = self.list_param.GetChecked()
    if len(checked) > 1 and 5 in checked:
        self.list_param.Check(5, check=False)

rawDescription: With wxpython CheckListBox, how do I automatically uncheck a box if another is checked?


code:
from gi.repository import Gtk, GtkSource, GObject
from os.path import abspath, dirname, join

WHERE_AM_I = abspath(dirname(__file__))

class MyApp(object):

    def __init__(self):
        self.builder = Gtk.Builder()
        self.glade_file = join(WHERE_AM_I, 'test.glade')
        GObject.type_register(GtkSource.View)
        self.builder.add_from_file(self.glade_file)

if __name__ == '__main__':
    try:
        gui = MyApp()
        Gtk.main()
    except KeyboardInterrupt:
        pass

rawDescription: Load GUI from a Glade with GtkSourceView in PyGObject


code:
l = [(3, 'one'), (2, 'was'), (2, 'two'), (1, 'too'), (1, 'racehorse'), (1, 'a')]
l.sort(key=lambda x: x[1], reverse=True)
l.sort(key=lambda x: x[0])
l

rawDescription: Python reverse alphabetical order

description: Python reverse alphabetical order


code:
def TwoPic():
    run = 0
    Lats = []
    Longs = []
    while run < 2:
        run = run + 1
        getCoordinates()

        Lats.append(latitude)
        Longs.append(longitude)

    root.quit()

rawDescription: Python - different variable with each function run


code:
import pandas as pd
import matplotlib.pyplot as plt
import datetime
from dateutil.relativedelta import relativedelta
import calendar

#wind = pd.read_csv('2014.csv')
data = [['2014-01-01 00:00:00', 13, 179],
        ['2014-01-01 00:01:00', 13, 178],['2014-01-01 00:02:00', 11, 169],['2014-01-01 00:03:00', 11, 178],
        ['2014-01-01 00:04:00', 11, 181]]

rawDf = pd.DataFrame(data, columns = ['Date','Speed','Dir'])

rawDf['Date']=pd.to_datetime(rawDf['Date'])

#Define beginning and end of loop - start at first month, end at last month
currDate = datetime.date(rawDf['Date'].min().year, rawDf['Date'].min().month, 1)
endDate = datetime.date(rawDf['Date'].max().year, rawDf['Date'].max().month, 1)

#loop
while currDate <= endDate:

    currMoEnd = datetime.date(currDate.year, currDate.month, calendar.monthrange(currDate.year,currDate.month)[1])
    wind = rawDf[(rawDf['Date']>= currDate) & (rawDf['Date']<= currMoEnd)]
    wind.set_index('Date', inplace = True)

    dates = pd.date_range(currDate, currMoEnd, freq='1min')

    janwin = pd.Series(wind['Speed'], index=dates)
    jandir = pd.Series(wind['Dir'], index=dates)

    plt.figure(1)
    plt.subplot(211)
    plt.plot(dates, janwin)

    plt.ylabel("Km/hr")
    plt.rcParams.update({'font.size': 4})
    plt.grid(which='major', alpha = .5)

    plt.subplot(212)
    plt.plot(dates, jandir)
    plt.ylabel("Degrees")
    plt.rcParams.update({'font.size': 4})
    plt.grid(which='major', alpha = 5)
    plt.ylim(0,360)
    plt.axis(minor=True)

    plt.show()
    plt.savefig('{0}_output.pdf'.format(datetime.stftime(currDate,'%Y-%m')),  dpi=900)

    currDate = currDate + relativedelta(months = 1)

rawDescription: Multiple timeseries plots from Pandas Dataframe


code:
from scipy.interpolate import griddata
from jdcal import jd2jcal
from datetime import datetime

n = 366*24
df = pd.DataFrame(index=pd.date_range(start='2016-01-01 00:00', freq='H', periods=n),
                  data={'z': np.random.randn(n)})
df["x"] = df.index.date
df["y"] = df.index.hour
df.head()

xi = np.linspace(df.index.to_julian_date().min(), df.index.to_julian_date().max(), 1000)
yi = np.linspace(df.y.min(), df.y.max(), 1000)
zi = griddata((df.index.to_julian_date(),df.index.hour),df.z,(xi[None,:],yi[:,None]),method='linear')
xij = [jd2jcal(0,v) for v in xi]
xid = [datetime(x[0],x[1],x[2]) for x in xij]
plt.contourf(xid,yi,zi)
plt.colorbar()
plt.show()

rawDescription: Heatmap with date on horizontal and hour on vertical axis ("fingerprint plot")


code:
def init_site_settings(request):
    return settings.CONFIG

rawDescription: Site configuration in django-admin

description: Site configuration in django-admin


code:
r = re.compile(r'(
.*?
\n(?!\s*
))', re.DOTALL)
r.sub('
\\1
', string_with_li_tags)

rawDescription: Python Regex - Identifying the first and last items in a list


code: combo.setStyleSheet('background-color: grey; padding: 0px 10px 0px 10px;')

rawDescription: How to customize QComboBox with CSS

description: Customize QComboBox with CSS


code:
if d > datetime.now():
    d = datetime(d.year - 100, d.month, d.day)

rawDescription: 2 digit years using strptime() is not able to parse birthdays very well


rawDescription: Remove last line from file excerpt

description: Remove last line from file excerpt


code:
def URLPost(url, params, method="POST", headers = {}):
    req = urllib2.Request(url)
    for k, v in headers.items():
        req.add_header(k, v)
    r  = urllib2.urlopen(req, data=urllib.urlencode(params))
    return r

rawDescription: How do I modify my simple Python code, to take into account HTTP headers?

description: Modify my simple Python code, to take into account HTTP headers


code:
class UserResource(ModelResource):
   class Meta:
      queryset = User.objects.all()

   def prepend_urls(self):
      return [
        url(r"^(?P<resource_name>%s)/(?P<username>[\w\d_.-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
    ]

rawDescription: django-tastypie REST update or delete resource with username

description: Django-tastypie REST update or delete resource with username


code:
with open('input.csv', 'r') as ifile:
    with open('output.csv', 'w') as ofile:
        for line in ifile:
            try:
                c1, c2 = [int(val.strip()) for val in line.split(',', 1)]
            except ValueError:
                # skip malformed lines
                continue
            ofile.write("%s,%s\n" % (
                (c1, c2) if c1 > c2 else (c2, c1)))

rawDescription: Compare two columns' number and output result


code:
from Tkinter import *

heat_map = [[20, 21, 22, 23, 20],
            [20, 22, 21, 23, 20],
            [20, 21, 20, 20, 20],
            [20, 21, 23, 23, 23],
            [21, 21, 22, 23, 22]]

heat_min = min(min(temp for temp in row) for row in heat_map)
heat_max = max(max(temp for temp in row) for row in heat_map)

def pseudocolor(value, minval, maxval, palette):
    max_index = len(palette)-1
    # convert value in range minval...maxval to the range 0..max_index
    v = (float(value-minval) / (maxval-minval)) * max_index
    i = int(v); f = v-i
    c0r, c0g, c0b = palette[i]
    c1r, c1g, c1b = palette[min(i+1, max_index)]
    dr, dg, db = c1r-c0r, c1g-c0g, c1b-c0b
    return c0r+f*dr, c0g+f*dg, c0b+f*db

def colorize(value, minval, maxval, palette):
    color = [int(c*255) for c in pseudocolor(value, minval, maxval, palette)]
    return '#' + '%02x' % color[0] + '%02x' % color[1] + '%02x' % color[2]

root = Tk()
root.title('heatmap')

palette = [(0,0,1), (0,.5,0), (0,1,0), (1,.5,0), (1,0,0)]
width, height = 400, 400

frame = Frame()
frame.pack()

canvas = Canvas(frame, width=width, height=height)
rows, cols = len(heat_map), len(heat_map[0])
rect_width, rect_height = width // rows, height // cols
for y, row in enumerate(heat_map):
    for x, temp in enumerate(row):
        x0, y0 = x * rect_width, y * rect_height
        x1, y1 = x0 + rect_width-1, y0 + rect_height-1
        color = colorize(temp, heat_min, heat_max, palette)
        canvas.create_rectangle(x0, y0, x1, y1, fill=color, width=0)
canvas.pack()

root.mainloop()

rawDescription: Heat map from data points in python

description: Heat map from data points in python


code:
class Integer:
  def __init__(self, val=0):
    self.val = int(val)
  def __eq__(self, other):
    return self.val == other

Integer(1) == 1.1
Integer(1.2) == Integer(1.3)
Integer(4) == Integer(7)
Integer(2) == 2

rawDescription: Overwriding Equality Test in Integer Wrapper Class


code:
red = workbook.add_format({'color': 'red'})
worksheet.write_number(1, 1, 10.24, red)

rawDescription: Format decimal value

description: Format decimal value


rawDescription: How do I get minidom to ignore namespaces?

description: Get minidom to ignore namespaces


code:
from PySide import QtGui, QtCore

app = QtGui.QApplication([])
app.setStyleSheet('QMainWindow{background-color: darkgray;border: 1px solid black;}')

w = QtGui.QMainWindow()
w.setWindowFlags(QtCore.Qt.FramelessWindowHint)
w.show()

app.exec_()

rawDescription: How to change color of QMainWindow borders and title bar?

description: Change color of QMainWindow borders and title bar


code:
for key in d:
    li = d[key]
    for i,item in enumerate(li):
        li[i] = d_find_and_replace.get(item, item)

rawDescription: Find and replace strings in a python dictionary


code:
def show_player_table():
    query = ("SELECT name FROM field_player")
    cursor.execute(query)

    for result in cursor:
        if len(result):
            print("{}".format(result[0]))

rawDescription: Trying to print out data from database

description: Trying to print out data from database


rawDescription: If I have this string in Python, how do I decode it?


code:
def connectionMade(self):
        # Asks user for their name
        name = input('What is your name?')
        # sends name to server
        self.transport.write(name)

rawDescription: Python Twiested, where to read client input


code:
import subprocess

subprocess.call('clear') # subprocess.call('cls', shell=True) on Windows

rawDescription: Print output at the very beginning of the terminal


rawDescription: Multiple Plots in Matplotlib Widget

description: Multiple Plots in Matplotlib Widget


code:
c.execute("""SELECT MonkeyVillage.BananaType, count(*)
FROM MonkeyVillage
WHERE MonkeyVillage.BananaType IN (
SELECT MonkeyHouse.BananaType
FROM MonkeyHouse)
GROUP BY MonkeyVillage.BananaType""")

rawDescription: Retriving the count from one table given a value from another


code:
result_exp = sqlalchemy.sql.expression.label('result',
   ((test2_table.c.a * test2_table.c.b)
    - (test2_table.c.x + test2_table.c.y)
    / test2_table.c.z))
select([result_exp], from_obj=[test2_table], order_by="result")

rawDescription: How do I ORDER BY an arithmetic express in SQLAlchemy?


code:
def f(in_str):
    out_str = in_str.upper()
    return True, out_str # Creates tuple automatically

succeeded, b = f("a") # Automatic tuple unpacking

rawDescription: What's the best way to return multiple values from a function in Python?


code:
from collections import Counter

animals_dict = [{'type': key, 'amount': value} for key, value in Counter(animals).items()]

rawDescription: Python: Increment value of dictionary stored in a list


code:
from pylab import *
A = arange(25)/25.
A = A.reshape((5,5))

figure()
imshow(A, interpolation='nearest', origin='lower')

figure()
imshow(A, interpolation='nearest')

d = arange(5)
figure()
plot(d)
ylim(5, 0)

show()

rawDescription: Matplotlib coord. sys origin to top left


code:
class CachedProperties(object):
    @property
    def expensiveValue(self):
        cacheKey = (self.var1, self.var2)
        if cacheKey in self._expensiveValueCache:
            return self._expensiveValueCache[cacheKey]

        # No cached value available, calculate it now
        res = self._expensiveValueCache[cacheKey] = calculation(self.var1, self.var2)
        return res

rawDescription: How to monitor changes to a mutable object?

description: Monitor changes to a mutable object


code: any(item in l for item in cornerCase for l in (top, bottom, left, right))

rawDescription: Check if an element in a list is present in multiple lists in python


code:
def ffmpeg_cmd(self, fname, fps, codec, frame_prefix):
    # Returns the command line parameters for subprocess to use
    # ffmpeg to create a movie
    return ['ffmpeg', '-y', '-r', str(fps), '-b', '1800k', '-i',
        '%s%%04d.png' % frame_prefix, fname]

def mencoder_cmd(self, fname, fps, codec, frame_prefix):
    # Returns the command line parameters for subprocess to use
    # mencoder to create a movie
    return ['mencoder', 'mf://%s*.png' % frame_prefix, '-mf',
        'type=png:fps=%d' % fps, '-ovc', 'lavc', '-lavcopts',
        'vcodec=%s' % codec, '-oac', 'copy', '-o', fname]

def _make_movie(self, fname, fps, codec, frame_prefix, cmd_gen=None):
    # Uses subprocess to call the program for assembling frames into a
    # movie file.  *cmd_gen* is a callable that generates the sequence
    # of command line arguments from a few configuration options.
    from subprocess import Popen, PIPE
    if cmd_gen is None:
        cmd_gen = self.ffmpeg_cmd
    command = cmd_gen(fname, fps, codec, frame_prefix)
    verbose.report('Animation._make_movie running command: %s'%' '.join(command))
    proc = Popen(command, shell=False,
        stdout=PIPE, stderr=PIPE)
    proc.wait()

rawDescription: matplotlib.animation error - The system cannot find the file specified

description: Matplotlib.animation error - The system cannot find the file specified


code:
field_type = {
 0: 'DECIMAL',
 1: 'TINY',
 2: 'SHORT',
 3: 'LONG',
 4: 'FLOAT',
 5: 'DOUBLE',
 6: 'NULL',
 7: 'TIMESTAMP',
 8: 'LONGLONG',
 9: 'INT24',
 10: 'DATE',
 11: 'TIME',
 12: 'DATETIME',
 13: 'YEAR',
 14: 'NEWDATE',
 15: 'VARCHAR',
 16: 'BIT',
 246: 'NEWDECIMAL',
 247: 'INTERVAL',
 248: 'SET',
 249: 'TINY_BLOB',
 250: 'MEDIUM_BLOB',
 251: 'LONG_BLOB',
 252: 'BLOB',
 253: 'VAR_STRING',
 254: 'STRING',
 255: 'GEOMETRY' }

rawDescription: How can I get column types width MySQLdb?

description: Get column types width MySQLdb


code:
import os
import shutil

# Open the file and raise an exception if it exists
fd = os.open(filename, os.O_CREAT | os.O_EXCL | os.O_WRONLY)

# Copy the file and automatically close files at the end
with os.fdopen(fd) as f:
    with open(src_filename) as sf:
        shutil.copyfileobj(sf, f)

rawDescription: Copy a file, but don't overwrite, without TOCTTOU issues in Python


code:
d = {1: [1]}
for v in d.itervalues():
    v[0] += 1

rawDescription: Python - changing values of a dictionary when using itervalues()


code:
from Tkinter import *
master = Tk()
listbox = Listbox(master, selectbackground="red")

rawDescription: python modify Tkinter.Listbox parameter

description: Python modify Tkinter.Listbox parameter


code: result = [' '.join(zip(*row)[0]) for row in data]

rawDescription: How to extract 'x' of each tuple in a list and concatenate in python way?

description: Extract 'x' of each tuple in a list and concatenate in python way


code:
import multiprocessing
from itertools import product

alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;"
num_parts = 4
part_size = len(alphabet) // num_parts

def do_job(first_bits):
    for x in product(first_bits, alphabet, alphabet, alphabet):
        print(x)

if __name__ == '__main__':
    pool = multiprocessing.Pool(processes=4)
    results = []
    for i in range(num_parts):
        if i == num_parts - 1:
            first_bit = alphabet[part_size * i :]
        else:
            first_bit = alphabet[part_size * i : part_size * (i+1)]
        results.append(pool.apply_async(do_job(first_bit)))

    pool.close()
    pool.join()

rawDescription: How do I "multi-process" the itertools product module?


code:
with open('file','rb') as fin:
    header = fin.read(header_size)
    data_str = fin.read(num_data_bytes)
    data_tuple = struct.unpack('100f',data_str)  #100 4-byte floats

rawDescription: Read numeric data from binary file using python


code:
text = 'This is the part (a) of question number one. i. This is sub part one of part (a) question one ii. This is sub part two of part (a) question one iii. This is sub part three of part (a) question one'

for m in re.split(r' [MDCLXVI]+\. ', text, flags=re.IGNORECASE):
    print(m)

rawDescription: Split on roman numbers using regular expression in python


code:
msg = QtDBus.QDBusMessage.createMethodCall('org.onboard.Onboard', '/org/onboard/Onboard/Keyboard','org.onboard.Onboard.Keyboard'
                'org.onboard.Onboard.Keyboard.Show')
QtDBus.QDBusConnection.sessionBus().send(msg)
text, ok = QtGui.QInputDialog.getText(self, 'Input Dialog',
            'Enter your name:')
msg2 = QtDBus.QDBusMessage.createMethodCall('org.onboard.Onboard', '/org/onboard/Onboard/Keyboard','org.onboard.Onboard.Keyboard'
                'org.onboard.Onboard.Keyboard.Hide')
QtDBus.QDBusConnection.sessionBus().send(msg2)

rawDescription: How to make a QInputDialog trigger the virtual keyboard to show up?

description: Make a QInputDialog trigger the virtual keyboard to show up


code:
import paramiko
import re

class ShellHandler:

    def __init__(self, host, user, psw):
        self.ssh = paramiko.SSHClient()
        self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh.connect(host, username=user, password=psw, port=22)

        channel = self.ssh.invoke_shell()
        self.stdin = channel.makefile('wb')
        self.stdout = channel.makefile('r')

    def __del__(self):
        self.ssh.close()

    def execute(self, cmd):
        """

        :param cmd: the command to be executed on the remote computer
        :examples:  execute('ls')
                    execute('finger')
                    execute('cd folder_name')
        """
        cmd = cmd.strip('\n')
        self.stdin.write(cmd + '\n')
        finish = 'end of stdOUT buffer. finished with exit status'
        echo_cmd = 'echo {} $?'.format(finish)
        self.stdin.write(echo_cmd + '\n')
        shin = self.stdin
        self.stdin.flush()

        shout = []
        sherr = []
        exit_status = 0
        for line in self.stdout:
            if str(line).startswith(cmd) or str(line).startswith(echo_cmd):
                # up for now filled with shell junk from stdin
                shout = []
            elif str(line).startswith(finish):
                # our finish command ends with the exit status
                exit_status = int(str(line).rsplit(maxsplit=1)[1])
                if exit_status:
                    # stderr is combined with stdout.
                    # thus, swap sherr with shout in a case of failure.
                    sherr = shout
                    shout = []
                break
            else:
                # get rid of 'coloring and formatting' special characters
                shout.append(re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]').sub('', line).
                             replace('\b', '').replace('\r', ''))

        # first and last lines of shout/sherr contain a prompt
        if shout and echo_cmd in shout[-1]:
            shout.pop()
        if shout and cmd in shout[0]:
            shout.pop(0)
        if sherr and echo_cmd in sherr[-1]:
            sherr.pop()
        if sherr and cmd in sherr[0]:
            sherr.pop(0)

        return shin, shout, sherr

rawDescription: Implement an interactive shell over ssh in Python using Paramiko?


rawDescription: Fetch two objects beside eachother in Django


code:
import turtle
from random import randint

x = 50

turtle = turtle.Turtle()

degrees = randint(0, 360)
turtle.left(degrees)
turtle.forward(x)

turtle.getscreen()._root.mainloop()

rawDescription: Python Turtle Graphics Choose Point X Distance Away


code:
payload={
    'grant_type': 'authorization_code',
    'code': request.args['code'],
    'state': request.args['state'],
    'redirect_uri': 'http://xxx.xyz.com/request_listener',
}

url = 'https://serviceprovider.xxx.com/auth/j_oauth_resolve_access_code'

response = requests.post(url, data=payload, verify=False)

rawDescription: Correct way to make a Python HTTPS request using requests module?


code:
def upload_file():
    if request.method == 'POST':
        # ... snip ...
        return url_for('uploaded_image', filename=filename)

rawDescription: Sending Data from Python (Flask) to Javascript?


code:
df = pd.DataFrame(data)
df.pivot(index=0, columns=1, values=2)
df.pivot(index=0, columns=1, values=3)

rawDescription: Construct pandas DataFrame from list of tuples


code:
# Cartesian Coordinates
x = np.zeros(n)
y = np.zeros(n)
for i in range(n):
    x[i] = radii[i] * np.cos(angle[i])
    y[i] = radii[i] * np.sin(angle[i])

plt.plot(x,y,'bo')

rawDescription: How to Generate a Homogeneous Poisson Point Process in a circle?


rawDescription: How to convert an object array to a normal array in python

description: Convert an object array to a normal array in python


code:
def get_args(s):
    # prepare
    syn = {'"': False, "'": False, '(': 0, '[': 0}
    mapping = {')': '(', ']': '['}
    args = []
    arg = {'name': '', 'def': ''}
    type = 'name'
    # iterate through chars
    for c in s:
        bracket = syn['('] == 0 and syn['['] == 0
        quote = (syn['"'] is True and c is not '"') or (syn["'"] is True and c is not "'")
        # add to argument definition
        if re.match(r"[a-zA-Z0-9._ ]", c) or quote:
            arg[type] += c
        # quotes
        elif re.match(r"[\"\']", c):
            syn[c] = not syn[c]
            arg[type] += c
        # brackets
        elif re.match(r"[\(\[]", c):
            syn[c] += 1
            arg[type] += c
        elif re.match(r"[\)\]]", c):
            syn[mapping[c]] -= 1
            arg[type] += c
        # '=' to define default value
        elif re.match(r"=", c) and bracket:
            type = 'def'
        # ',' to seperate arguments
        elif re.match(r",", c) and bracket:
            type = 'name'
            args.append({'name': arg['name'].strip(), 'def': arg['def'].strip()})
            arg = {'name': '', 'def': ''}
        else:
            arg[type] += c
    # add last arg
    if syn['('] == 0 and syn['['] == 0 and syn['"'] is False and syn["'"] is False:
        args.append({'name': arg['name'].strip(), 'def': arg['def'].strip()})
    # return
    return args

rawDescription: Matching and parsing to extract information from complicated string