code:
from collections import defaultdict

def find_controlled(company, shares):
    # shares the company owns directly
    controls = set([company])       # avoid the recursion problem pointed out by @Justin
    owns     = defaultdict(float)
    owns.update(shares[company])

    # first level of controlled companies to look at
    add_control = set(k for k,v in owns.items() if v > 0.50)

    while add_control:
        # new level of controlled companies to look at next
        _add_control = set()

        for cpy in add_control:
            controls.add(cpy)
            for k,v in shares[cpy].items():
                owns[k] += v
                if owns[k] > 0.5 and k not in controls:
                    _add_control.add(k)
        add_control = _add_control

    return sorted(controls - set([company]))

def main():
    # Data structure: dict of dict of float
    #   shares['A']['B'] = 0.51     means    A owns 51% of B's shares
    shares = defaultdict(lambda: defaultdict(float))

    # Who owns what
    shares['A']['B'] = 0.60
    shares['A']['C'] = 0.55
    shares['A']['D'] = 0.41
    shares['C']['D'] = 0.10
    shares['B']['E'] = 0.20
    shares['C']['E'] = 0.20
    shares['D']['E'] = 0.20

    # See who A controls:
    controlled = find_controlled('A', shares)
    print('A controls {}'.format(','.join(controlled)))

if __name__=="__main__":
    main()

rawDescription: Suitable data structure

description: Suitable data structure


rawDescription: SQLAlchemy foreign keys access optimazation


code:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class MainMenu(Screen):
    def __init__(self, **kwargs):
        super(MainMenu, self).__init__(**kwargs)
        self.add_widget(Button(text = 'test'))

class Sis(App):
     def build(self):
         root = ScreenManager()
         root.add_widget(MainMenu(name = 'mainMenu'))
         root.current = 'mainMenu'
         return root

Sis().run()

rawDescription: Adding widgets to a screen subclass in .py file


code:
result = False
error = None
try:
    # Open URL
    urllib2.urlopen(url, timeout=TIMEOUT)
    result = True
except urllib2.URLError as exc:
    error = 'URL Error: {0}'.format(str(exc))
except urllib2.HTTPError as exc:
    error = 'HTTP Error: {0}'.format(str(exc))
except Exception as exc:
    error = 'Unknow error: {0}'.format(str(exc))

rawDescription: how can I detect whether the http and https service is ok in python?

description: Detect whether the http and https service is ok in python


code:
for edge in tree.findall(".//edge"):
    start = edge.get('from')
    end = edge.get('to')
    dk(start,end)

rawDescription: Parsing GXL in Python

description: Parsing GXL in Python


code:
import sys
from PySide.QtCore import *
from PySide.QtGui import *

class Editor(QPlainTextEdit):
    def __init__(self, parent):
        super(Editor, self).__init__()
        self.setPlainText( u'apple, banana\norange\nblah blah\n\nOh yeah!....\n'*6 )
        self.setParent( parent )

        self.setWordWrapMode( QTextOption.NoWrap )
        self.setViewportMargins( 50,0,0,0 )

        QObject.connect( self, SIGNAL("textChanged()"), self.repainting )

    def repainting(self):
        self.parent().update()

    def scrollContentsBy(self, *args, **kwargs):
        self.parent().update()
        return QPlainTextEdit.scrollContentsBy(self, *args, **kwargs)

class WinE(QMainWindow):
    def __init__(self, font=QFont( 'Monospace', 12 )):
        super(WinE, self).__init__()

        self.font = font
        self.font.setFixedPitch( True )

        self.ce = Editor( self )
        self.ce.setFont( self.font )

        self.setWindowTitle('Code Editor')

        self.textr = QRect( 3, 5, self.ce.childrenRect().x() -12, self.ce.childrenRect().height() )

        self.setGeometry( QRect(800, 840, 351, 250) )
        self.setCentralWidget( self.ce )

        self.show()

    def paintEvent(self, event):

        qp = QPainter   ()
        qp.begin        ( self )
        self.drawLiNums ( qp )
        qp.end          ()

    def drawLiNums(self, qp):

        qp.setPen       ( QColor(255, 255, 255) )
        qp.setFont      ( self.font )
        qp.drawText     ( self.textr, Qt.AlignRight, self.lineNumeration() )

    def lineNumeration(self):
        offset=self.ce.firstVisibleBlock().firstLineNumber()
        return ''.join(str(i)+"\n" for i in range(offset+1, self.ce.blockCount()+1))

def main():

    app = QApplication(sys.argv)
    ex = WinE()
    sys.exit(app.exec_())

if __name__ == '__main__': main()

rawDescription: How to scroll line numbers in a QTextEdit

description: Scroll line numbers in a QTextEdit


code:
string1.rstrip("-")
# "title"
string2.rstrip("-")
# "title"
string3.rstrip("-")
# "title-is-a-title"

rawDescription: How can I remove all trailing dashes from a string?

description: Remove all trailing dashes from a string


rawDescription: Tkinter Text Tags Select/User highlight Colour


rawDescription: Fast way to select n items (drawn from a Poisson distribution) for each element in array x


code:
from sqlalchemy.ext.hybrid import hybrid_property

Base = declarative_base()
class tblUser(Base):
    __tablename__ = 'tblUser'
    User_Id = Column('User_Id', String(100), primary_key=True)
    FullName = Column('FullName', String(50))

    _Sequence_No = Column('Sequence_No', Integer)
    _local_Sequence_No = None

    @hybrid_property
    @property
    def SequenceNo(self):
        if self._local_Sequence_No is not None:
            return self._local_Sequence_No
        return self._SequenceNo

    @SequenceNo.setter
    def SequenceNo(self, value):
        self._local_Sequence_No = value

rawDescription: SQLAlchemy exclude_properties not working in Declarative


code:
if re.match(r'your_regex', your_string):
    return your_string
else:
    return 'failed'

rawDescription: re.match accept any return value except for empty

description: Re.match accept any return value except for empty


code:
import shutil
import glob
import os

with tarfile.open('D:\Python34\Testing\sample.tar.gz', 'r:gz') as tar:
    tar.extractall()
    os.chdir('sample')
    for arch in glob.glob('hello_*'):
        shutil.unpack_archive(arch, 'D:\Python34\Testing')

rawDescription: How to extract a selected files from sample.tar.gz file usin gpython script

description: Extract a selected files from sample.tar.gz file usin gpython script


code:
@mock.patch('stripe.Customer.retrieve')
def test_add_card_failure(self, retrieve_mock):
    data = {
        'name': "shubham",
        'cvc': 123,
        'number': "4242424242424242",
        'expiry': "12/23",
    }
    e = CardError("Card Error", "", "")
    retrieve_mock.return_value.sources.create.return_value = e

    self.api_client.client.login(username=self.username, password=self.password)

    res = self.api_client.post('/biz/api/auth/card/add', data=data)

    self.assertEqual(self.deserialize(res)['success'], False)

rawDescription: Mock Stripe Methods in Python for testing


code:
from PIL import Image
import subprocess

p = subprocess.Popen(["display", "/tmp/test.png"])
raw_input("Give a name for image:")
p.kill()

rawDescription: how to display and close image in python?

description: Display and close image in python


code:
def xlongrange(start, limit, step):
    n = start
    while n < limit:
        yield n
        n += step

rawDescription: How to use long integers in Python to build a range?

description: Use long integers in Python to build a range


code:
from haystack.management.commands import update_index
update_index.Command().handle()

rawDescription: Updating a Haystack search index with Django + Celery


code:
def bubbleSort(alist):

    sample_list = (getRandomSample(alist, 100))

    for passnum in range(len(sample_list)-1,0,-1):
        for i in range(passnum):
            if sample_list[i]>alist[i+1]:
                temp = alist[i]
                sample_list[i] = alist[i+1]
                sample_list[i+1] = temp
    return(sample_list)

if __name__ == '__main__':
    pool = Pool(processes=4)
    for x in pool.imap_unordered(bubbleSort, (myArray for x in range(3000))):
        pass

rawDescription: Multiprocessing in Python not faster than doing it sequentially


code: driver = webdriver.Firefox()

rawDescription: Python Selenium open URL in same Firefox window


rawDescription: converting currency with $ to numbers in Python pandas

description: Converting currency with $ to numbers in Python pandas


rawDescription: How to set QTreeWidgetItem as not Editable

description: Set QTreeWidgetItem as not Editable


code:
class Thingy(object):
    def __mul__(self, other):
        print('mul', other)
    def __rmul__(self, other):
        print('rmul', other)
thingy = Thingy()
thingy * 3
3 * thingy

rawDescription: Python: Enable custom object to be multiplied with / added to a standard type


code:
with open('name.output', 'wb') as fout:
    fout.write(data)

rawDescription: writing to file from cython

description: Writing to file from cython


code:
def bigram_corr(line): #function with input line(sentence)
    words = line.split() #split line into words
    for idx, (word1, word2) in enumerate(zip(words[:-1], words[1:])):
        for i,j in fdist: #iterate over bigrams
            if (word2==j) and (jf.levenshtein_distance(word1,i) < 3): #if 2nd words of both match, and 1st word is at an edit distance of 2 or 1, replace word with highest occurring bigram
                words[idx] = i
                break
    return " ".join(words)

rawDescription: Replace Words on the basis of Bigram Frequency,Python


code:
def check_email(self, user):
  if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):
    return True

rawDescription: I can't test a Google App using OpenID single sign-on on the AppEngine devserver, locally


code:
import sys
from PyQt5 import QtWidgets, QtCore

class MyWidget(QtWidgets.QWidget):
    def __init__(self):
        QtWidgets.QWidget.__init__(self)
        self.setGeometry(400,50,200,200)

        self.pushButton = QtWidgets.QPushButton('show messagebox', self)
        self.pushButton.setGeometry(25, 90, 150, 25)
        self.pushButton.clicked.connect(self.onClick)

    def onClick(self):
        msgbox = QtWidgets.QMessageBox()
        msgbox.setText('to select click "show details"')
        msgbox.setTextInteractionFlags(QtCore.Qt.NoTextInteraction) # (QtCore.Qt.TextSelectableByMouse)
        msgbox.setDetailedText('line 1\nline 2\nline 3')
        msgbox.exec()

app = QtWidgets.QApplication(sys.argv)
w = MyWidget()
w.show()
sys.exit(app.exec_())

rawDescription: How to add QLineEdit to QMessageBox PyQt5

description: Add QLineEdit to QMessageBox PyQt5


code: l = [j for j in (func(i) for i in range(10)) if j]

rawDescription: How can I use a function call result in a conditional list comprehension?

description: Use a function call result in a conditional list comprehension


code:
items=(
    ("Animals", (("1","Monkey"), ("2","Turtle"))),
    ("Aliens", (("3","Zim"), ("4","Tak"))),
)

select=forms.ChoiceField(label="Selection", choices=items)

rawDescription: How to create grouped dropdown list in django admin?

description: Create grouped dropdown list in django admin


code:
with open("malenames.txt") as f:
   for line in f:
      print (line.split()[0])

rawDescription: python print only the names from text file

description: Python print only the names from text file


code:
for line in textwrap.wrap(some_text, 80, break_long_words=False):
  yield "%-80s" % (line)

rawDescription: Adding whitespace to the ends of textwrapping?


code:
import matplotlib.pyplot as plt
import numpy as np
mat = np.random.rand(500,5000)
plt.imshow(mat, interpolation='none', aspect='auto')
plt.show()

rawDescription: How to make a Python image 'fit' the figure?

description: Make a Python image 'fit' the figure


code:
import fileinput
for line in fileinput.input(remaining_args):
    process(line)

rawDescription: How to read from stdin or from a file if no data is piped in Python?

description: Read from stdin or from a file if no data is piped in Python


code:
import numpy as np
pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
pic
'\n'.join([''.join(row) for row in pic])

rawDescription: concatenate numpy string array along an axis?

description: Concatenate numpy string array along an axis


code:
VALUES = {-4: 0.1, -3: 0.2, -2: 0.3, -1: 0.4,
    0: 0.5, 1: 0.6, 2: 0.7, 3:  0.8, 4: 0.9}

def sum_part(start_point, diff):
    sum = 0.0
    for i in range(start_point - diff, start_point + diff + 1):
        try:
            sum += VALUES[i]
        except KeyError:
            pass
        #print('%d: %.2f' % (i, sum))
    return sum

def test_sum(start_point, diff):
    sum = sum_part(start_point, diff)
    print('sum(%d, %d): %.2f' % (start_point, diff, sum))

test_sum(1, 3)

rawDescription: summing up the values of particular range of second column in a data file

description: Summing up the values of particular range of second column in a data file


code:
s = "how much for the maple syrup? $20.99? That's ricidulous!!!"
re.sub(r'[^\w]', ' ', s)

rawDescription: How to remove symbols from a string with Python?

description: Remove symbols from a string with Python


code:
for x in range(225):
    screen.fill((0,0,0))  #or whatever your background color is
    newSurf.set_alpha(225-x)
    screen.blit(newSurf, (100,100))
    pygame.display.flip()
    pygame.time.display(20)

rawDescription: Unable to fade out text - PyGame

description: Unable to fade out text - PyGame


code:
for line in file:
    if username == line.strip():
       validusername = True
       break

rawDescription: Getting number of lines in a text file without readlines


code:
from pyface.api import beep
beep()

rawDescription: How to sound a beep with PyFace?

description: Sound a beep with PyFace


code:
import mmap
import struct
import multiprocessing as mp
import gmpy2

# Number of mpz integers to place in the memory buffer.
z_count = 40000
# Maximum number of bits in each integer.
z_bits = 750000
# Total number of bytes used to store each integer.
# Size is rounded up to a multiple of 4.
z_size = 4 + (((z_bits + 31) // 32) * 4)

def f(instance):
    global mm

    s = 0
    for i in range(z_count):
        mm.seek(i * z_size)
        t = struct.unpack('i', mm.read(4))[0]
        z = gmpy2.from_binary(mm.read(t))
        s += z
    print(instance, z % 123456789)

def main():
    global mm

    mm = mmap.mmap(-1, z_count * z_size)
    rs = gmpy2.random_state(42)
    for i in range(z_count):
        z = gmpy2.mpz_urandomb(rs, z_bits)
        b = gmpy2.to_binary(z)
        mm.seek(i * z_size)
        mm.write(struct.pack('i', len(b)))
        mm.write(b)

    ctx = mp.get_context('fork')
    pool = ctx.Pool(4)
    pool.map_async(f, range(4))
    pool.close()
    pool.join()

if __name__ == '__main__':
    main()

rawDescription: sharing gmpy2 multi-precision integer between processes without copying

description: Sharing gmpy2 multi-precision integer between processes without copying


code:
import mymodule
mymodule.__init__(5)

rawDescription: python module __init__ function

description: Python module __init__ function


code:
import scipy.fftpack as sf
import numpy as np
def maxFrequency(X, F_sample, Low_cutoff=80, High_cutoff= 300):
        """ Searching presence of frequencies on a real signal using FFT
        Inputs
        =======
        X: 1-D numpy array, the real time domain audio signal (single channel time series)
        Low_cutoff: float, frequency components below this frequency will not pass the filter (physical frequency in unit of Hz)
        High_cutoff: float, frequency components above this frequency will not pass the filter (physical frequency in unit of Hz)
        F_sample: float, the sampling frequency of the signal (physical frequency in unit of Hz)
        """

        M = X.size # let M be the length of the time series
        Spectrum = sf.rfft(X, n=M)
        [Low_cutoff, High_cutoff, F_sample] = map(float, [Low_cutoff, High_cutoff, F_sample])

        #Convert cutoff frequencies into points on spectrum
        [Low_point, High_point] = map(lambda F: F/F_sample * M, [Low_cutoff, High_cutoff])

        maximumFrequency = np.where(Spectrum == np.max(Spectrum[Low_point : High_point])) # Calculating which frequency has max power.

        return maximumFrequency

voiceVector = []
for window in fullAudio: # Run a window of appropriate length across the audio file
    voiceVector.append (maxFrequency( window, samplingRate))

rawDescription: Pitch detection in Python

description: Pitch detection in Python


code:
def edit(request):
    if request.user.is_authenticated() and request.method == 'POST':
        current_user = request.user
        record_data = Program.objects.get(user=current_user)
        form = ProgramForm(request.POST, instance=record_data)

        if form.is_valid():
            instance = form.save(commit=False)
            instance.user = current_user
            instance.save()

        return HttpResponseRedirect('/member/')

    elif request.user.is_authenticated() and request.method != 'POST':
        current_user = request.user
        record_data = Program.objects.get(user=current_user)
        program_info = ProgramForm(request.POST, instance=record_data)

        return render(request, 'programs_dbase/edit.html', {'program_info': program_info})

    else:
        return redirect('login')

rawDescription: Django creating one-to-one records matching user account


rawDescription: Matplotlib: how to show plot again?

description: Matplotlib: how to show plot again


code:
from fastavro import writer

def csv_reader():
    with open('export.csv') as f:
        reader = csv.DictReader(f)
        for row in reader:
            yield row

    # If this is Python 3.3+, you could simplify further to just:
    with open('export.csv') as f:
        yield from csv.DictReader(f)

# schema could be from the keys of the first row which gets manually written
# or you can provide an explicit schema with documentation for each field
schema = {...}

with open('export.avro', 'wb') as out:
    writer(out, schema, csv_reader())

rawDescription: Creating list of dictionaries from big csv


rawDescription: Filtering DataFrame by finding exact word (not combined) in a column of strings


code:
ann.txt.set_text('new text')
plt.draw()

rawDescription: Python: How to 'anchor' text to be always visible and set_text method Matplotlib


code: list = map(str.strip, list)

rawDescription: Is there a better way to use strip() on a list of strings? - python


code:
class TABLE(models.Model):
    id = models.AutoField(primary_key=True)
    parent = models.ForeignKey('self')

rawDescription: Python/Django Modeling Question

description: Python/Django Modeling Question


code:
df
df.groupby('jim').count()

rawDescription: Group counts. Why every column?

description: Group counts. Why every column


code:
import numpy as np
import matplotlib.pylab as pl

nx = 4
ny = 5
data = np.random.randint(0,10,size=(ny,nx))

pl.figure()
tb = pl.table(cellText=data, loc=(0,0), cellLoc='center')

tc = tb.properties()['child_artists']
for cell in tc:
    cell.set_height(1/ny)
    cell.set_width(1/nx)

ax = pl.gca()
ax.set_xticks([])
ax.set_yticks([])

rawDescription: draw matrix as a table in python

description: Draw matrix as a table in python


code:
class LogWaitLogInOrder(pipeline.Pipeline):

  def run(self, message1, message2, delay):
    with pipeline.InOrder():
      yield LogMessage(message1)
      yield Delay(seconds=delay)
      yield LogMessage(message2)

    yield LogMessage('This would happen immediately on run')

rawDescription: How to execute tasks in (FIFO) order using Google App Engine Task Queues?

description: Execute tasks in (FIFO) order using Google App Engine Task Queues


code: super(Derived, cls).do(a)

rawDescription: Calling a base class's classmethod in Python


code:
newworkbook = xlwt.Workbook()
newsheet = newworkbook.add_sheet('ITEM DETAILS')
for i in range(sheet.nrows):
    for j in range(sheet.ncols):
        newsheet.write(r, c, sheet.cell_value(r, c))

rawDescription: python: Store all cell values with xlrd and write to new workbook using xlwt

description: Python: Store all cell values with xlrd and write to new workbook using xlwt


code:
class PersonAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(PersonAdminForm, self).__init__(*args, **kwargs)
        new_fields = {}
        initial = self.instance.groups.all()
        for group_type in GroupType.objects.all():
            field_name = '{0}_groups'.format(group_type.name.lower())
            qs = Group.objects.filter(group_type=group_type)
            field = forms.ModelMultipleChoiceField(
                queryset=qs,
                required=False,
                initial=initial,
            )
            new_fields[field_name] = field
        self.fields.update(new_fields)

    def clean(self):
        cleaned_data = super(PersonAdminForm, self).clean()
        groups = []
        for group_type in GroupType.objects.all():
            gt_name = '{0}_groups'.format(group_type.name.lower())
            groups.extend(cleaned_data.get(gt_name))
        self.instance.groups.clear()
        self.instance.groups.add(*groups)
        return cleaned_data

    class Meta:
        model = Person
        fields = '__all__'

@admin.register(Person)
class PersonAdmin(admin.ModelAdmin):
    form = PersonAdminForm

    # using the fieldsets attribute instead of fields in order to dynamically
    # add group type fields later.
    fieldsets = (
        (None, {
            'fields': (
                'name',
            ),
        }),
    )

    def get_form(self, request, obj=None, **kwargs):
        kwargs['fields'] = flatten_fieldsets(self.declared_fieldsets)
        return super(PersonAdmin, self).get_form(request, obj, **kwargs)

    def get_fieldsets(self, request, obj=None):
        fieldsets = super(PersonAdmin, self).get_fieldsets(request, obj)
        newfieldsets = list(fieldsets)
        fields = []
        for group_type in GroupType.objects.all():
            fields.append('{0}_groups'.format(group_type.name.lower()))
        newfieldsets.append(['Groups', {'fields': fields}])
        return newfieldsets

rawDescription: How do I create and save dynamic fields in Django ModelAdmin?

description: Create and save dynamic fields in Django ModelAdmin


rawDescription: How to find out which VM i have in my Python installation?

description: Find out which VM i have in my Python installation


rawDescription: Python: Split a list into sub-lists based on index ranges


code:
def __unicode__(self):
    return u'{0}'.format(self.lname)

rawDescription: How to choose the value and label from Django ModelChoiceField queryset

description: Choose the value and label from Django ModelChoiceField queryset


code:
while len(content) > 0:
    func(content)
    content = content[1:]

rawDescription: python3 iteratively remove first character from string

description: Python3 iteratively remove first character from string


code:
def body(self, master):
    self.e1 = tk.Listbox(master, selectmode=tk.SINGLE, height = 3, exportselection=0)
    self.e1.insert(tk.END, "1")
    self.e1.insert(tk.END, "2")

    self.e1.grid(row=0, column=1)
    self.selection = 0
    self.e1.select_set(self.selection)

    self.e1.bind("<Down>", self.OnEntryDown)
    self.e1.bind("<Up>", self.OnEntryUp)

def OnEntryDown(self, event):
    if self.selection < self.e1.size()-1:
        self.e1.select_clear(self.selection)
        self.selection += 1
        self.e1.select_set(self.selection)

def OnEntryUp(self, event):
    if self.selection > 0:
        self.e1.select_clear(self.selection)
        self.selection -= 1
        self.e1.select_set(self.selection)

rawDescription: Tkinter listbox that scrolls with arrow keys


code:
import ruamel.yaml as yaml

yaml_str = """\
Data: |-
      Some data, here and a special character like ':'
      Another line of data on a separate line
"""

data = yaml.load(yaml_str)
print(data)

rawDescription: Python YAML preserving newline without adding extra newline


code:
from datetime import datetime
import time

if __name__== '__main__':

    initTimeObj = datetime.now()
    nullRef = datetime(initTimeObj.year, initTimeObj.month, initTimeObj.day, 0, 0, 0)

    print("Initial time:")
    print(str(initTimeObj.hour) + ':' + str(initTimeObj.minute) + ':' + str(initTimeObj.second))
    print("")

    while(True):
        time.sleep(1)
        myDiff = datetime.now() - initTimeObj
        myTimeObj = nullRef + myDiff

        print(str(myTimeObj.hour) + ':' + str(myTimeObj.minute) + ':' + str(myTimeObj.second))

        # Now you get a counting as follows:
        # 0:0:1
        # 0:0:2
        # 0:0:3
        # ...
        # 0:0:59
        # 0:1:0
        # 0:1:1
        # 0:1:2
        # ...

rawDescription: How can i make a time counter using QTime()

description: Make a time counter using QTime()


code: match = re.search(r'(\w+)\s(?:D\.C\.), (\w\w)\W', location).groups()

rawDescription: How to match--but not capture--in Python regular expressions?

description: Match--but not capture--in Python regular expressions


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

import argparse
import re
from os import path

pattern = '<<([^>]*)>>'

def user_replace(match):
    return raw_input('%s? ' % match.group(1))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('infile', type=argparse.FileType('r'))
    parser.add_argument('outfile', type=argparse.FileType('w'))
    args = parser.parse_args()

    matcher = re.compile(pattern)

    for line in args.infile:
        new_line = matcher.sub(user_replace, line)
        args.outfile.write(new_line)

    args.infile.close()
    args.outfile.close()

if __name__ == '__main__':
    main()

rawDescription: How to Find a String in a Text File And Replace Each Time With User Input in a Python Script?


code:
import pexpect

kg = pexpect.spawn('ssh-keygen -t rsa')
kg.expect('Enter same passphrase again:')

rawDescription: Match a process' prompts and respond programmatically


code:
from itertools import chain
list(chain.from_iterable(zip([1, 2, 3, None, None], [4, 5, 6])))

rawDescription: Merging two lists in the order of each elements in two lists


code:
def pubListItemAdded(self, dbitem):
    """
    Add list if dbitem instance matches dbScKlass

    :param dbitem: an SA model instance

    If dbitem instance matches the list controls model it is added.
    """
    # protect from PyDeadObjectError
    if self:
        # E.g. Externalimp is a faked class and does not exist in db
        # so we need to protect for that
        if hasattr(db, self._klassName):
            tList = self.getList()
            cInst = getattr(db, self._klassName)
            if isinstance(dbitem, cInst):
                log.debug("olvbase - added: %s", dbitem)
                log.debug("olvbase - added: %s", self)
                # for some reason this creates dups on e.g. rating/tasting/consumption
                # so, lets check if it is there and only add if not
                idx = tList.GetIndexOf(dbitem)
                if idx == -1:
                    tList.AddObject(dbitem)
                else:
                    tList.RefreshObject(dbitem)

                # bring it into view
                self.resetSelection()
                tList.SelectObject(dbitem, deselectOthers=True,
                                   ensureVisible=True)

def pubListItemModified(self, dbitem):
    """
    Update list if dbitem instance matches dbScKlass

    :param dbitem: an SA model instance

    If dbitem instance matches the list controls model it is updated.
    """
    # protect from PyDeadObjectError
    if self:
        # E.g. Externalimp is a faked class and does not exist in db
        # so we need to protect for that
        if hasattr(db, self._klassName):
            cInst = getattr(db, self._klassName)
            if isinstance(dbitem, cInst):
                log.debug("olvbase - modified: %s", dbitem)
                log.debug("olvbase - modified: %s", self)
                tList = self.getList()
                # need to refresh to ensure relations are loaded
                wx.GetApp().ds.refresh(dbitem)
                tList.RefreshObject(dbitem)
                tList.SelectObject(dbitem, deselectOthers=True,
                                    ensureVisible=True)
                # deselect all, so if we select same item again
                # we will get a select event
                tList.DeselectAll()

def pubListItemDeleted(self, dbitem):
    """
    Delete from list if dbitem instance matches dbScKlass

    :param dbitem: an SA model instance

    If dbitem instance matches the list controls model it is updated.
    """
    # protect from PyDeadObjectError
    if self:
        # E.g. Externalimp is a faked class and does not exist in db
        # so we need to protect for that
        if hasattr(db, self._klassName):
            cInst = getattr(db, self._klassName)
            if isinstance(dbitem, cInst):
                log.debug("olvbase - deleted: %s", dbitem)
                log.debug("olvbase - deleted: %s", self)
                tList = self.getList()
                tList.RemoveObject(dbitem)
                self.currentObject = None
                self.currentItemPkey = None

rawDescription: Use ObjectListView in the Model-View-Controller pattern with SQLAlchemy in Python


code:
import xmlrpclib
import datetime

proxy=xmlrpclib.ServerProxy('<my_confluence>/rpc/xmlrpc')
token=proxy.confluence1.login('username', 'password')

blogpost = {
    'title' : 'myTitle',
    'content' : 'My Content',
    'space' : 'myspace',
    'publishDate' : datetime.datetime(2001, 11, 21, 16, 30)
}

proxy.confluence1.storeBlogEntry(token, blogpost)

rawDescription: Confluence XML-RPC: Set the "creation" date


code:
conection = boto.iam.connect_to_region("us-east-1")
response = connection.create_access_key(username)
secret_access_key = response['create_access_key_response']['create_access_key_result']['access_key']['secret_access_key']

rawDescription: get aws_secret_access_key to store in ~/.boto

description: Get aws_secret_access_key to store in ~/.boto


code:
from fractions import Fraction
a = Fraction(1,2)
a.denominator

rawDescription: Is there any way to access denominator of a fraction in Python 2


code:
pattern = re.compile('(?<=<meta-data\sandroid:value=\")[^"]+')
for each_config_line in manifest_original_xml_fh:
    each_config_line = re.sub(pattern, channel_name, each_config_line)

rawDescription: python regular expression substitution with matched group

description: Python regular expression substitution with matched group


code:
import subprocess
...
command_list = ['node', 'static/js/node_script.js']

try:
  output = subprocess.check_output(command_list)
except subprocess.CalledProcessError:
  output = "Error in command_list."

rawDescription: Server-side javascript with node (and Django)


code:
# get a matrix where the (i, j)th element is |x[i] - x[j]|^2
# using the identity (x - y)^T (x - y) = x^T x + y^T y - 2 x^T y
pt_sq_norms = (x ** 2).sum(axis=1)
dists_sq = np.dot(x, x.T)
dists_sq *= -2
dists_sq += pt_sq_norms.reshape(-1, 1)
dists_sq += pt_sq_norms

# turn into an RBF gram matrix
km = dists_sq; del dists_sq
km *= (-sigma**2 / 2)
np.exp(km, km)  # exponentiates in-place

rawDescription: Implementing Support Vector Machine - EFFICIENTLY computing gram-matrix K


code:
l
[(i, j, k, m) for p, j, k, m in l for i in p.split()]

rawDescription: how to split all first elements of tuples in list? (Python)

description: Split all first elements of tuples in list? (Python)


code:
def is_palindrome(word):
    if len(word) <= 1:
        return True
    elif first(word) == last(word):
        return is_palindrome(middle(word))  # <--
    else:
        return False

rawDescription: Why doesn't my python algorithm for checking palindromes work?


code:
fig1.suptitle('Test')
ax1 = fig1.add_subplot(221)
ax1.plot(x,y1,color='b',label='aVal')
ax2 = ax1.twinx()
ax2.plot(x,y2,color='g',label='bVal')
ax2.grid( ls='--', color='black')
h1, l1 = ax1.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
ax1.legend(h1+h2, l1+l2, loc=2)

rawDescription: Single legend for multiple axes

description: Single legend for multiple axes


code:
import datetime

current_time = datetime.datetime.now()

crofton = current_time + datetime.timedelta(minutes=7)

rawDescription: Trying to display a variable as a time when printed


code:
from pprint import pformat
hash(pformat(a)) == hash(pformat(b))

rawDescription: How to generate unique equal hash for equal dictionaries?

description: Generate unique equal hash for equal dictionaries


code: form.defaults={'myStruct': {'a': None, 'b': 'default_value'}}

rawDescription: How does one pre-populate a Python Formish form?

description: Pre-populate a Python Formish form


code:
user = 'username'
y = True

while y:
    openurl = urllib.urlopen("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&contributor_details&include_rts=true&screen_name="+user+"&count=3600")
    user += "a"
    #You have to do something in here to change y or this will be an infinite loop

rawDescription: Changing variables in a loop

description: Changing variables in a loop


code:
def _parse_response(self, response, callback, cb_kwargs, follow=True):
    if callback:
        cb_res = callback(response, **cb_kwargs) or ()
        cb_res = self.process_results(response, cb_res)
        for requests_or_item in iterate_spider_output(cb_res):
            yield requests_or_item

    if follow and self._follow_links:
        for request_or_item in self._requests_to_follow(response):
            yield request_or_item

rawDescription: Scrapy: only parse from pages with meta noindex


code:
df = pd.read_csv(data_string, header=0, parse_dates=[1], dayfirst=True)
df.dtypes

rawDescription: pandas parse_dates does not seem to work

description: Pandas parse_dates does not seem to work


code:
def method(self, arg1=0, arg2=None):
    if arg2 is None:
        arg2 = self.member
    ...

rawDescription: Not Possible to Reference self in a Method Declaration?


code:
def subclassfilter(x, baseclass):
    return x is not baseclass and isinstance(x, type) and issubclass(x, baseclass)

subclasses = [c for c in locals().values() if subclassfilter(c, ImageSpec)]

rawDescription: How to generate a choicelist from all ImageSpecs

description: Generate a choicelist from all ImageSpecs


code:
with ThreadPoolExecutor as exe:
    exe.submit(conn)

rawDescription: Parallel compute task to brute-force in python


code:
while True:
    # Do stuff that need less than 30 sec.
    do_stuff()
    # Check for shutdown or sleep.
    if runtime.is_shutting_down():
        break
    else:
        time.sleep(1)

rawDescription: Terminating GAE Python Background Threads


code:
from __future__ import print_function
# remove the above line if you're using Python 3.x

with open('color.txt') as f:
    colors = ', '.join(f.read().splitlines()).split(', ')

with open('car.txt') as f:
    for i in f:
        for car in i.strip().split(', '):
            for color in colors:
                print(car, color)

rawDescription: python all combinations of two files lines

description: Python all combinations of two files lines


code: conn.execute("""PRAGMA cache_size = 4000""")  # 4 Mb

rawDescription: Is sqlite fast enough for it to replace pre-loading stuff into memory?


code:
f = NamedTemporaryFile(delete=False)
f

rawDescription: How to get a file object from mkstemp()?

description: Get a file object from mkstemp()


code:
keywords = {'carrot': 'Green Vegetable.',
            'apple': 'Red or Green fruit.',
            'Orange': 'Orange fruit.'}

print ("Here is your Keyword")
import random
with open('keywords.txt') as f:
     a = random.choice(list(f))
     print("a =", keywords[a])

rawDescription: How to get defined value from another defined value, python?

description: Get defined value from another defined value, python


code:
item = [{'position': 0}, {'position': 4}]
min(set(range(10)) - set(x['position'] for x in item))

rawDescription: Find the lowest unoccupied space in a range of numbers


code: os = getattr(__builtins__, "".join(chr(ord(x) - 1) for x in  "``jnqpsu``"))("os")

rawDescription: Importing in python, how many ways can it be done?


code:
from matplotlib.patches import Rectangle
import numpy as np
import pylab as P

xs = np.arange(0,10,0.1)
line1 = P.plot(xs,np.sin(xs),"r-", label="lower limit")[0]
line2 = P.plot(xs,np.sin(xs-1)+3,"b-", label="upper limit")[0]
P.fill_between(xs,np.sin(xs), np.sin(xs-1)+3,color='green', alpha=0.5, label="test")
rect = Rectangle((0, 0), 1, 1, fc="g", alpha=0.5)
P.legend([line1, line2, rect], ["lower limit", "upper limit", "green area"])
P.show()

rawDescription: Labelling a coloured area under a graph

description: Labelling a coloured area under a graph


code:
degree_list = G.degree().values()
H = nx.expected_degree_graph(degree_list)

rawDescription: Keeping scale free graph's degree distribution after perturbation - python


code:
if request.method=='POST':
  PrimaryFunctionFormSet = inlineformset_factory(Position,Function)
  if 'add' in request.POST:
    cp = request.POST.copy()
    cp['prim-TOTAL_FORMS'] = int(cp['prim-TOTAL_FORMS'])+ 1
    prims = PrimaryFunctionFormSet(cp,prefix='prim')

rawDescription: Django: Adding inline formset rows without javascript


code:
import pandas as pd
import numpy as np
import random
np.random.seed(2013)

df_source = pd.DataFrame(
    np.random.randn(5, 2), index=range(0, 10, 2), columns=list('AB'))

rows = np.random.randint(2, size=len(df_source)).astype('bool')

df_source_train = df_source[rows]
df_source_test = df_source[~rows]

print(rows)
# [ True  True False  True False]

# if for some reason you need the index values of where `rows` is True
print(np.where(rows))
# (array([0, 1, 3]),)

print(df_source)
#           A         B
# 0  0.279545  0.107474
# 2  0.651458 -1.516999
# 4 -1.320541  0.679631
# 6  0.833612  0.492572
# 8  1.555721  1.741279

print(df_source_train)
#           A         B
# 0  0.279545  0.107474
# 2  0.651458 -1.516999
# 6  0.833612  0.492572

print(df_source_test)
#           A         B
# 4 -1.320541  0.679631
# 8  1.555721  1.741279

rawDescription: Sample two pandas dataframes the same way


code:
import subprocess, tempfile
from wand.image import Image

with Image(filename='wizard:') as imageOBJ:
    tempOBJ = tempfile.NamedTemporaryFile(suffix='.jpg',
                                          prefix='/tmp/myProject-',
                                          delete=False)
    imageOBJ.save(file=tempOBJ)
    subprocess.call('xdg-open {}'.format(tempOBJ.name), shell=True)

rawDescription: Prevent interruption of wand display method on Raspbian


code:
import os
import subprocess

path_7zip = r"C:\Program Files\7-Zip\7z.exe"
path_working = r"C:\temp"
outfile_name = "compressed.zip"
os.chdir(path_working)

ret = subprocess.check_output([path_7zip, "a", "-tzip", outfile_name, "*.txt", "*.py", "-pSECRET"])

rawDescription: Faster alternative to Python's zipfile module?


code: next(x for x in count(7) for y in count(5) if x==y)

rawDescription: Python: lambda: find the first common element of 2 sorted infinite iterators


code:
form.fields['template'].choices = templates_as_choices(request)

def templates_as_choices(request):
    templates = []
    default = []
    user = []
    for template in Template.objects.filter(default=1).order_by('name'):
        default.append([template.id, template.name])

    for template in Template.objects.filter(user=request.user).order_by('name'):
        user.append([template.id, template.name])

    templates.append(['Default Templates', default])
    templates.append(['User Templates', user])

    return templates

rawDescription: Use <optgroup> with form.fields.queryset?


code:
try:
    xrange
except NameError:  # Python3
    xrange = range

def hexdump(filename, length=16, sep='.'):
    result = []

    with open(filename, 'rb') as file:
        src = file.read()  # Read whole file into memory

    for i in xrange(0, len(src), length):
        subSrc = src[i:i+length]
        hexa = ''
        isMiddle = False;
        for h in xrange(0,len(subSrc)):
            if h == length/2:
                hexa += ' '
            h = subSrc[h]
            if not isinstance(h, int):
                h = ord(h)
            h = hex(h).replace('0x','')
            if len(h) == 1:
                h = '0'+h;
            hexa += h+' '
        hexa = hexa.strip(' ')
        text = ''
        for c in subSrc:
            if not isinstance(c, int):
                c = ord(c)
            if 0x20 <= c < 0x7F:
                text += chr(c)
            else:
                text += sep;
        result.append(('%08X:  %-'+str(length*(2+1)+1)+'s  |%s|') %
                      (i, hexa, text))

    return '\n'.join(result)

if __name__ == "__main__":
    import sys

    filename = sys.argv[1]
    print(hexdump(filename, length=16, sep='.'))

rawDescription: Converting .raw file into Hex

description: Converting .raw file into Hex


code:
lines = file.readlines()
lines = lines[:-1]

rawDescription: Python remove last line of a file

description: Python remove last line of a file


code:
from PIL import Image
import StringIO
import urllib2

class MyModel(models.Model):
    # ... fields 1,2,3 etc, and assuming the url field is called image_url

    def pre_save():
        # obtain attributes of image from url field
        # save it to various fields
        img = urllib2.urlopen(self.image_url).read()
        im = Image.open(StringIO.StringIO(img))
        self.image_width, self.image_height = im.size

    def save(self, *args, **kwargs):
        self.pre_save()
        super(MyModel, self).save(*args, **kwargs)

rawDescription: Django prepopulated_fields like method

description: Django prepopulated_fields like method


code:
for link in soup.select("section.LINK_CLASS > div.LINK_CLASS2 > div.LINK_CLASS3 > a[href]"):
    print(link["href"])

rawDescription: I’d like to scrape the text in nested elements within multiple divs


code: type(type(phoneNumRegex))

rawDescription: When type([object]) is used in an if statement, why must it be typecasted into a string?


code:
import glob
import shutil
import os
import re

root = 'path/to/folder/*'

for f in glob.glob(root):
    dirname = f.rsplit('.')[0]
    os.mkdir(dirname)
    filename = os.path.split(re.sub(r'\[\d+\]', '', f))[-1]
    shutil.move(f, os.path.join(dirname, filename))

rawDescription: Using glob and os to put files into folders & rename?


code: cc, cs = count_and_sum(c.width for c in cols if not c.hide)

rawDescription: Need a fast way to count and sum an iterable in a single pass


code:
import calendar
import datetime

def total_number_of_days(number_of_months=3):
    c = calendar.Calendar()
    d = datetime.datetime.now()
    total = 0
    for offset in range(0, number_of_months):
        current_month = d.month - offset
        while current_month <= 0:
            current_month = 12 + current_month
        days_in_month = len( filter(lambda x: x != 0, c.itermonthdays(d.year, current_month)))
        total = total + days_in_month
    return total

rawDescription: How to see if file is older than 3 months in Python?

description: See if file is older than 3 months in Python


code:
def get_caller_lineno():
    frame, _, lineno, _, _, _ = inspect.stack()[1]
    return lineno

rawDescription: problem with python inspect module-python

description: Problem with python inspect module-python


code:
from django.contrib.admin.filterspecs import FilterSpec
from django.db import models
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext as _

class NullFilterSpec(FilterSpec):
    #fields = (models.CharField, models.IntegerField, models.FileField)

    @classmethod
    def test(cls, field):
        #return field.null and isinstance(field, cls.fields) and not field._choices
        return field.null and not field._choices
    #test = classmethod(test)

    def __init__(self, f, request, params, model, model_admin, field_path=None):
        super(NullFilterSpec, self).__init__(f, request, params, model, model_admin, field_path)
        self.lookup_kwarg = '%s__isnull' % f.name
        self.lookup_val = request.GET.get(self.lookup_kwarg, None)

    def choices(self, cl):
        # bool(v) must be False for IS NOT NULL and True for IS NULL, but can only be a string
        for k, v in ((_('All'), None), (_('Has value'), ''), (_('Omitted'), '1')):
            yield {
                'selected' : self.lookup_val == v,
                'query_string' : cl.get_query_string({self.lookup_kwarg : v}),
                'display' : k
            }

# Here, we insert the new FilterSpec at the first position, to be sure
# it gets picked up before any other
FilterSpec.filter_specs.insert(0,
    # If the field has a `profilecountry_filter` attribute set to True
    # the this FilterSpec will be used
    (lambda f: getattr(f, 'isnull_filter', False), NullFilterSpec)
)

rawDescription: Filtering Django Admin by Null/Is Not Null


code:
for alias in models.Alias.objects.iterator() :
    alias.update_points()

rawDescription: Django : Iterate over a query set without cache


code:
orderings = (
    ('A2', 'A1'),
    ('B1', 'B2'),
    ('C2', 'C1')
)

orders = [dict([(v, i) for i, v in enumerate(o)]) for o in orderings]

mytable.sort(key=lambda r: tuple(o[c] for c, o in zip(r, orders)))

rawDescription: Multi-column table sort with custom ordering for each column


code:
from subprocess import Popen, PIPE
from subprocess import CalledProcessError as BaseCalledProcessError

class CalledProcessError(BaseCalledProcessError):
    def __init__(self, returncode, cmd, output=None):
        super(CalledProcessError, self).__init__(returncode, cmd)
        self.output = output

def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output as a byte string.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.  Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    'ls: non_existent_file: No such file or directory\n'
    """
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')
    process = Popen(stdout=PIPE, *popenargs, **kwargs)
    output, unused_err = process.communicate()
    retcode = process.poll()
    if retcode:
        cmd = kwargs.get("args")
        if cmd is None:
            cmd = popenargs[0]
        raise CalledProcessError(retcode, cmd, output=output)
    return output

rawDescription: Why the subprocess.check_call commands always return 0?


code: [print(x) for x in range(10)]

rawDescription: What is the advantage of the new print function in Python 3.x over the Python 2 print statement?


code: max(pets, key=pets.get)

rawDescription: Sorting a dictionary and outputting the key which corresponds to the highest value?


code: A = dot(A, R.T)

rawDescription: Efficiently rotate a set of points with a rotation matrix in numpy


code:
##
# Element factory.  This function returns an object implementing the
# standard Element interface.  The exact class or type of that object
# is implementation dependent, but it will always be compatible with
# the {@link #_ElementInterface} class in this module.
# <p>
# The element name, attribute names, and attribute values can be
# either 8-bit ASCII strings or Unicode strings.
#
# @param tag The element name.
# @param attrib An optional dictionary, containing element attributes.
# @param **extra Additional attributes, given as keyword arguments.
# @return An element instance.
# @defreturn Element

def Element(tag, attrib={}, **extra):
    attrib = attrib.copy()
    attrib.update(extra)
    return _ElementInterface(tag, attrib)

rawDescription: Verifying cElementTree or elementTree node type


code:
inp = open('input.txt', 'r')
out = open('output.txt', 'w')
prev = inp.readline()
for line in inp:
   if line.startswith('M05'):
      out.write(line)
      continue
   else:
      out.write(prev)
   prev = line
out.write(prev)
out.close()
inp.close()

rawDescription: Swap lines of text around in text file

description: Swap lines of text around in text file


code: help(dir)

rawDescription: How to document a Python project?

description: Document a Python project


code:
idx = indexes[:, None] + np.arange(-1, 3)
values[idx]

rawDescription: How to index with array and slice numpy array at the same time

description: Index with array and slice numpy array at the same time


code: exec("print 2+2")

rawDescription: Running a python code within a python script


code:
def join_with_tab(iterable):
    r"""
    >>> join_with_tab(['1', '2'])
    '1\t2'
    """

    return '\t'.join(iterable)

if __name__ == "__main__":
    import doctest
    doctest.testmod()

rawDescription: How can I include special characters (tab, newline) in a python doctest result string?

description: Include special characters (tab, newline) in a python doctest result string


code:
import shutil
with open('test') as old, open('newtest', 'w') as new:
    for line in old:
        if line.rsplit('|', 1)[-1].strip() == 'number3':
            new.write('this is replacement|number7\n')
        else:
            new.write(line)
shutil.move('newtest', 'test')

rawDescription: Python Read/Write text file

description: Python Read/Write text file


rawDescription: PyQt QPushButton Background color

description: PyQt QPushButton Background color


code:
# starting three balls
balls = [Ball(),Ball(),Ball()]

while True:
    amount = 0

    event = pygame.event.poll()
    keys = pygame.key.get_pressed()

    if event.type == QUIT:
        pygame.quit()
        sys.exit()

    if keys[K_q]:
        pygame.quit()
        sys.exit()

    #############################################################

    if keys[K_SPACE]:
        balls.append(Ball())

    #############################################################

    screen.fill(WHITE)

    for ball_in_play in balls:
        ball_in_play.move()
        ball_in_play.blitball()

    pygame.time.wait(int(1000/fps))

    pygame.display.update()

rawDescription: Adding new objects of the same class in a loop


code:
from django.db.models import Q
queryset1 = MyModel.objects.filter(name='john kennedy')
queryset2 = MyModel.objects.filter(~Q(name='john kennedy'))
queryset =  queryset1 | queryset2

rawDescription: django simple but hard order_by logic

description: Django simple but hard order_by logic


code:
class element_is_not(object):
    """ An expectation for checking that the element returned by
    the locator is not equal to a given element.
    """

    def __init__(self, locator, element):
        self.locator = locator
        self.element = element

    def __call__(self, driver):
        new_element = driver.find_element(*self.locator)
        return new_element if  self.element != new_element else None

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

driver = webdriver.Firefox()
wait = WebDriverWait(driver, 10)

driver.get("https://www.rockethub.com/projects")

# get the last box
by_last_box = (By.CSS_SELECTOR, '.project-box:last-of-type')
last_box = wait.until(element_is_not(by_last_box, None))

# click on menu Status > Successful
driver.find_element_by_link_text('Status').click()
driver.find_element_by_link_text('Successful').click()

# wait for a new box to be added
last_box = wait.until(element_is_not(by_last_box, last_box))

# scroll down the page
driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")

# wait for a new box to be added
last_box = wait.until(element_is_not(by_last_box, last_box))

rawDescription: Scroll down pages with selenium and python


code:
persons = [p[:4]+[p[4].replace('-','').replace('/',''),p[5]] for p in persons]
p4 = [p for p in persons if p[4][-2]=='4']
pblue = [p for p in persons if p[5]=='Blue']

rawDescription: String manipulation in list of lists in Python


code:
from bs4 import *

soup = BeautifulSoup(html_data_in_here)
text = soup.find(id = body_id).getText()

rawDescription: How can I display email messages in Tkinter?

description: Display email messages in Tkinter


code:
from selenium import webdriver

# To prevent download dialog
profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp')
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')

browser = webdriver.Firefox(profile)
browser.get("http://www.drugcite.com/?q=ACTIMMUNE")

browser.find_element_by_id('exportpt').click()
browser.find_element_by_id('exporthlgt').click()

rawDescription: downloading file using selenium

description: Downloading file using selenium


code: E.bind("<Return>", lambda e: root.destroy())

rawDescription: Close a tk window on key press

description: Close a tk window on key press


code: list1.append((i for i in list2 if not i in list1).next())

rawDescription: compare two lists of strings and remove duplicates python

description: Compare two lists of strings and remove duplicates python


code:
import datetime
from dateutil.relativedelta import *

march27 = datetime.datetime(2014, 3, 27)
print (march27 + relativedelta(weeks=+1)).strftime("Week of %m/%d")
#prints "Week of 04/03"

rawDescription: Display a range of dates based on current date, in Python


code:
import tkinter as tk

def create_grid(event=None):
    w = c.winfo_width() # Get current width of canvas
    h = c.winfo_height() # Get current height of canvas
    c.delete('grid_line') # Will only remove the grid_line

    # Creates all vertical lines at intevals of 100
    for i in range(0, w, 100):
        c.create_line([(i, 0), (i, h)], tag='grid_line')

    # Creates all horizontal lines at intevals of 100
    for i in range(0, h, 100):
        c.create_line([(0, i), (w, i)], tag='grid_line')

root = tk.Tk()

c = tk.Canvas(root, height=1000, width=1000, bg='white')
c.pack(fill=tk.BOTH, expand=True)

c.bind('<Configure>', create_grid)

root.mainloop()

rawDescription: how to create grid on TKINTER in python

description: Create grid on TKINTER in python


rawDescription: How do I set the minimum size of a Gtk ButtonBox child?

description: Set the minimum size of a Gtk ButtonBox child


code:
def CreateBoard(r, c, b, n):

  for i in range(1,(r+1)):
    n.append(str(i))
  b.append(n)

  for i in range(c):
    b.append(['*']*(r))
  return(b)

def printBoard(b):
  for lst in b:
    print(" ".join(lst))
  return b

def check(board, n):
  n = []
  for i in range(1,len(board[1])+1):
    if board[1][i-1] == '*':
      n.append(i)
  print(n)

  user = (input('Enter column: '))

  if(user.isdigit() == True):
    user = int(user)
    if (user in n):
      return(user)
  print('Invalid input')
  return check(board, n)

def WinningCon(b, r, u, c):
  loop1 = True
  rowCon = ""
  colCon = ""
  for i in range(0,len(b[1])):
    rowCon += b[r][i]
    if('X'*4 in rowCon) or('O'*4 in rowCon):
      return(True)
  for i in range(1,c+1):
    colCon += b[i][u-1]
    if('X'*4 in colCon) or('O'*4 in colCon):
      return(True)

def Diag2(u, r, b, column, row):
  utemp1 = u-1
  utemp2 = u-1
  rtemp1 = r
  rtemp2 = r
  end = ""
  beg = ""
  while(True):

    beg += b[rtemp1][utemp1]
    rtemp1 -= 1
    utemp1 += 1
    if(rtemp1 == 1):
      break
    elif(utemp1 >= column - 1):
      break
  while(True):
    end += b[rtemp2][utemp2]
    rtemp2 +=1
    utemp2 -=1
    if(rtemp2 >= row):
      break
    elif(utemp2 == 0):
      break
  beg = beg[::-1]
  fullstring = beg+end
  if('X'*4 in fullstring) or('O'*4 in fullstring):
    return(True)

def Diag1(u, r, b, column, row):
  utemp1 = u-1
  utemp2 = u-1
  rtemp1 = r
  rtemp2 = r
  end = ""
  beg = ""
  while(True):
    beg += b[rtemp1][utemp1]
    rtemp1 -= 1
    utemp1 -= 1
    if(rtemp1 == 1):
      break
    elif(utemp1 == 0):
      break
  while(True):
    print('Row ' + str(rtemp2))
    print('Colum ' +str(utemp2))

    end += b[rtemp2][utemp2]
    rtemp2 +=1
    utemp2 +=1
    if(rtemp2 >= row):
      break
    elif(utemp2 >= column-1):
      break
  beg = beg[::-1]
  fullstring = beg+end
  if('X'*4 in fullstring) or('O'*4 in fullstring):
    return(True)

def ProcessInput(u, s, b, r):
  rowNum = r
  u = u-1
  print('Row: ' + str(rowNum))
  print('Col: ' + str(u))
  while(not b[rowNum][u] == '*'):
    rowNum -= 1
    print('New Row Num: ' + str(rowNum))
  b[rowNum][u] = s
  printBoard(b)
  return(rowNum)

def EndGame(g, b, p):
  printBoard(b)
  print("Congrats %s, you've won!" %p)
  replayGame = input('Would you like to play again? Yes or No?\n').lower()
  if replayGame == 'yes':
    MainGame()
  else:
    g = False
    return(g)

def MainGame():
  column = int(input('Enter number of columns'))
  row = int(input('Enter number of rows'))
  board = []
  nums = []
  board = CreateBoard(column, row, board, nums)
  player1 = 'K'#input('Enter name: ')
  player2 = 'A'#input('Enter name: ')
  turn = 1
  GameOn = True
  while(GameOn):
    board = printBoard(board)
    user = check(board, nums)
    if(turn%2 != 0):
      print("It's %s's turn" %player1)
      rc = ProcessInput(user, "X", board, row)
    else:
      print("It's %s's turn" %player2)
      rc = ProcessInput(user, "O", board, row)

    if(WinningCon(board, rc , user, row) == True):
      GameOn = EndGame(GameOn, board, player1)
    elif(Diag1(user, rc, board, column, row) == True):
      GameOn = EndGame(GameOn, board, player1)
    elif(Diag2(user, rc, board, column, row) == True):
      GameOn = EndGame(GameOn, board, player1)

    turn +=1

MainGame()

rawDescription: Customisation on Connect 4 game

description: Customisation on Connect 4 game


code:
for sentence in tagged_sentences:
    for n, (word,tag) in enumerate(sentence):
        if word == 'and/or':
            sentence[n] = (word, "CC")

rawDescription: python: modify PerceptronTagger in nltk to recognize 'and/or'

description: Python: modify PerceptronTagger in nltk to recognize 'and/or'


rawDescription: How to print a signed integer as hexadecimal number in two's complement with python?

description: Print a signed integer as hexadecimal number in two's complement with python


rawDescription: Change window size each tab tkinter notebook


code:
flip = random.choice(coin) # get the random choice
print(flip) # print it
counting.append(flip) # add it to the list to keep track

rawDescription: How do you make python read a random value it printed and insert it into an array?

description: Make python read a random value it printed and insert it into an array


code:
s = 'testing[\x06I"text in between 1\x06;filler text[\x06I"text in between 2\x06;more filler[\x06I"text in between \n with some line breaks \n included in the text\x06;ending'
import re
p = re.compile('\[\x06I"(.+?)\x06;', re.DOTALL)
print(p.findall(s))

rawDescription: Returning every instance of whatever's between two strings in a file [Python 3]


code:
animal_list = []
find_info = True

while(find_info):
    _animal_type = input('\nWhat type of animal would you like to create? ')
    __name = input("What is the animal's name? ")
    more_animals = input('Would you like to add more animals (y/n)? ')
    if (more_animals != 'y'):
        find_info = False

    # Create an instance of the animal class
    animal_list.append(animals.Animal(_animal_type, __name))

print('\nAnimal List')
for animal in animal_list:
    print('------------- \n' + animal.get_animal_type() + ' the ' +  animal.get_name() + '\n')

rawDescription: Trouble making the while loop work when printing different objects from class


code:
url = "http://cancer.jpl.nasa.gov/fmprod/data?refIndex=0&productID=02965767-873d-11e5-a4ea-252aa26bb9af"
res = requests.head(url)
res.headers
int(res.headers['content-length'])

rawDescription: How to get size of a file from Webpage in BeautifulSoup

description: Get size of a file from Webpage in BeautifulSoup


code:
#import library - MUST use cv2 if using opencv_traincascade
import cv2

# rectangle color and stroke
color = (0,0,255)       # reverse of RGB (B,G,R) - weird
strokeWeight = 1        # thickness of outline

# set window name
windowName = "Object Detection"

# load an image to search for faces
img = cv2.imread("test.jpg")

# load detection file (various files for different views and uses)
cascade = cv2.CascadeClassifier("cascade.xml")

# preprocessing, as suggested by: http://www.bytefish.de/wiki/opencv/object_detection
# img_copy = cv2.resize(img, (img.shape[1]/2, img.shape[0]/2))
# gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)
# gray = cv2.equalizeHist(gray)

# detect objects, return as list
rects = cascade.detectMultiScale(img)

# display until escape key is hit
while True:

    # get a list of rectangles
    for x,y, width,height in rects:
        cv2.rectangle(img, (x,y), (x+width, y+height), color, strokeWeight)

    # display!
    cv2.imshow(windowName, img)

    # escape key (ASCII 27) closes window
    if cv2.waitKey(20) == 27:
        break

# if esc key is hit, quit!
exit()

rawDescription: OpenCV traincascade XML file error

description: OpenCV traincascade XML file error


code:
class TimeLogForm(forms.ModelForm):
    class Meta:
        exclude = ['begin_sec']
        model = TimeLog

    def __init__(self, *args, **kw):
        super(TimeLogForm).__init__(self, *args, **kw)

    def save(self, *args, **kw):
        instance = super(TimeLogForm, self).save(commit=False)
        last_entry = TimeLog.objects.all().order_by('-id')[0]
        if last_entry:
            instance.begin_sec = last_entry.begin_sec
        else:
            # this is the very first record do something
            pass
        instance.save()
        return instance

rawDescription: default django model filed with value from the immediatelly previous entry

description: Default django model filed with value from the immediatelly previous entry


code:
z = []
for i in ["I...love","you"]:
    for j in i.split("..."):
        z.append(j)
print(z)

rawDescription: Take out punctuation within a word

description: Take out punctuation within a word


code:
class Plaintext(object):
    def print_thing(self, thing):
        print("plain", thing)

    def print_blob(self, blob):
        for thing in blob:
            self.print_thing(thing)

    def print_goober(self, blob):
        print("plaintext")
        self.print_blob(blob)

class Markdown(Plaintext):
    def print_markdown_thing(self, thing):
        print("mark", thing)

    def print_markdown_blob(self, blob):
        for thing in blob:
            self.print_markdown_thing(thing)

    def print_goober(self, blob):
        print("markdown")
        self.print_markdown_blob(blob)
        self.print_blob(blob)

newclass = Markdown()
newclass.print_goober([1,2,3])

rawDescription: python multiple inheritance calling overridden functions in super context

description: Python multiple inheritance calling overridden functions in super context


code:
import math
from matplotlib.patches import Arc
import matplotlib.pyplot as plt

ax = plt.axes()
x0, y0 = 0.5, 0.5
radius = 0.4
angle = 135
angle_rad = angle * math.pi / 180  # degrees to radians
# Draw circle
circle = plt.Circle((x0,y0), radius, color='red', fill=False)
fig = plt.gcf()
fig.gca().add_artist(circle)
# Draw radius arrow
head_length = 0.05
ax.arrow(x0, y0,
         (radius - head_length) * math.cos(angle_rad),
         (radius - head_length) * math.sin(angle_rad),
         head_width=0.05, head_length=head_length, fc='k', ec='k')
# Draw arc with arrow.
arc_radius = radius / 4
arc = Arc((x0, y0),
          arc_radius*2, arc_radius*2,  # ellipse width and height
          theta1=0, theta2=angle, linestyle='dashed')
ax.add_patch(arc)
arc_arrow_length = 0.03
arc_arrow_dx = arc_arrow_length * math.cos(angle_rad + math.pi / 2)
arc_arrow_dy = arc_arrow_length * math.sin(angle_rad + math.pi / 2)
ax.arrow(
    x0 + arc_radius * math.cos(angle_rad) - arc_arrow_dx,
    y0 + arc_radius * math.sin(angle_rad) - arc_arrow_dy,
    # We want to define a vector,
    # but we don't want to draw any line besides arrow head,
    # so we make arrow "body" unnoticeable.
    arc_arrow_dx * 0.000001,
    arc_arrow_dy * 0.000001,
    head_width=0.01,
    head_length=0.03,
    color='black')
plt.show()

rawDescription: Plotting circle diagram with rotary arrow


code:
class FieldUser(models.Model):
    field1 = models.IntegerField()
    field2 = models.CharField() #etc
    class Meta:
        abstract=True #abstract class does not create a db table

class RealUser(FieldUser, auth.User):
    pass #abstract nature is not inherited, will create its own table to go with the user table

class FakeUser(FieldUser):
    pass #again, will create its own table

rawDescription: Python/django inherit from 2 classes

description: Python/django inherit from 2 classes


code:
import numpy as np
import pandas as pd
df1 =pd.DataFrame(np.random.rand(3,1))
df2 =pd.DataFrame(np.random.rand(3,356))
df3 =pd.concat([df1,df2],axis=1)
df3.columns = range(357)

rawDescription: python pandas concat- reindex column labels

description: Python pandas concat- reindex column labels


code:
from collections import defaultdict
import itertools as it

matches = defaultdict(list)

for index, value in enumerate(call_record_dict.values()):
    matches[value].append(index)

for values in matches.values():
    for index1, index2 in it.combinations(values, 2):
        g.add_edge((index1, index2))
        g.add_edge((index2, index1))

rawDescription: Dividing a huge for loop using multiprocessing in python


code:
from contextlib import contextmanager

xs = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

@contextmanager
def j(index):
    """Same as before. This is a simple context manager."""
    print("j init")
    yield xs[index]
    print("j cleanup")

def _real_f(the_xs):
    """Mostly the same as before. However, any share state created in the
    init phase should be passed as an argument. As an example I pass in xs."""
    for i in range(len(the_xs)):
        # can now use explicit with statements for j
        with j(i) as it:
            for item in it:
                yield item

class f(object):
    """f is now replaced by a class that can create contexts for the real
    f to work with"""
    def __enter__(self):
        """Init phase.
        State required by the real f should be passed as an argument (I
        pass in xs)."""
        print("f init")
        return _real_f(xs)

    def __exit__(self, exception_type, exception, traceback):
        """Clean up phase.
        Called at end of block. With any details of any exception that
        may have occured in the with block. Return a truthful value to
        swallow the exception. Can raise your own exception if there is a
        problem in the clean up phase."""
        print("f clean up")

with f() as it:
    for item in it:
        print(item)

rawDescription: nested context managers in python with list comprehension

description: Nested context managers in python with list comprehension


code:
def recur(n, count=0):
    if n == 0:
        return "Finished count %s" % count
    return recur(n-1, count+1)

rawDescription: Counting recursion in a python program!

description: Counting recursion in a python program!


code: #!/usr/bin/env python

rawDescription: How Perl is able to compile python scripts?


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

def setup_backend(backend='TkAgg'):
    import sys
    del sys.modules['matplotlib.backends']
    del sys.modules['matplotlib.pyplot']
    import matplotlib as mpl
    mpl.use(backend)  # do this before importing pyplot
    import matplotlib.pyplot as plt
    return plt

N = 5
width = 0.35       # the width of the bars: can also be len(x) sequence

def animate():
    # http://www.scipy.org/Cookbook/Matplotlib/Animations
    mu, sigma = 100, 15
    h = mu + sigma * np.random.randn((N*2))
    p1 = plt.bar(np.arange(N), h[:N], width, color='r')
    p2 = plt.bar(np.arange(N), h[N:], width, color='b', bottom=h[:N])
    assert len(p1) == len(p2)
    maxh = 0.
    for i in range(50):
        for rect1, rect2 in zip(p1.patches, p2.patches):
            h = mu + sigma * np.random.randn(2)
            #Keep a record of maximum value of h
            maxh = max(h[0]+h[1],maxh)
            rect1.set_height(h[0])
            rect2.set_y(rect1.get_height())
            rect2.set_height(h[1])
        #Set y limits to maximum value
        ax.set_ylim((0,maxh))
        fig.canvas.draw()

plt = setup_backend()
fig, ax = plt.subplots(1,1)
win = fig.canvas.manager.window
win.after(10, animate)
plt.show()

rawDescription: Dynamically updating a stacked bar plot in matplotlib


code:
def stairs(n):
    table = [1, 1]  # p = 0 and p = 1
    for i in range(2, n + 1):
        table.append(table[i - 2] + table[i - 1])
    return table[n]

rawDescription: Replacing recursion with while loop (stair climbing puzzle): Python


code: newA = dict(sorted(A.iteritems(), key=operator.itemgetter(1), reverse=True)[:5])

rawDescription: 5 maximum values in a python dictionary

description: 5 maximum values in a python dictionary


code:
def flip_vert(picture):
    width = getWidth(picture)
    height = getHeight(picture)

    for y in range(0, height/2):
        for x in range(0, width):
            sourcePixel = getPixel(picture, x, y)
            targetPixel = getPixel(picture, x, height - y - 1)
            color = getColor(sourcePixel)
            setColor(sourcePixel, getColor(targetPixel))
            setColor(targetPixel, color)

    return picture

def flip_horiz(picture):
    width = getWidth(picture)
    height = getHeight(picture)

    for y in range(0, height):
        for x in range(0, width/2):
            sourcePixel = getPixel(picture, x, y)
            targetPixel = getPixel(picture, width - x - 1, y)
            color = getColor(sourcePixel)
            setColor(sourcePixel, getColor(targetPixel))
            setColor(targetPixel, color)

    return picture

rawDescription: Flip horizontally an image in Python (JES)


code:
from random import random
lines = [line for line in open("/some/file") if random() >= .5]

rawDescription: Read a number of random lines from a file in Python


rawDescription: How do I convert a numeric string to its corresponding Unicode character?

description: Convert a numeric string to its corresponding Unicode character


code:
@app.route('/')
@app.route("/<path:reqpath>")
def serve_app(reqpath):
    serve_static_markup()

rawDescription: How to handle client-side routing received at the server with Flask?

description: Handle client-side routing received at the server with Flask


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

from os import environ
from ctypes import windll, byref, POINTER, FormatError, GetLastError
from ctypes.wintypes import (
  LPCWSTR, WCHAR, DWORD, HANDLE, BOOL
)

MAX_COMPUTERNAME_LENGTH = 15
LOGON32_LOGON_NETWORK_CLEARTEXT = 8
LOGON32_PROVIDER_DEFAULT = 0

CloseHandle = windll.Kernel32.CloseHandle
CloseHandle.argtypes = [HANDLE]
CloseHandle.restype = BOOL

LogonUser = windll.Advapi32.LogonUserW
LogonUser.argtypes = [LPCWSTR, LPCWSTR, LPCWSTR, DWORD, DWORD, POINTER(HANDLE)]
LogonUser.restype = BOOL

if __name__ == '__main__':
  username = 'MyUsername'
  password = 'MyPassword'

  token = HANDLE()
  status = LogonUser(username,
                     environ['COMPUTERNAME'],
                     password,
                     LOGON32_LOGON_NETWORK_CLEARTEXT,
                     LOGON32_PROVIDER_DEFAULT,
                     byref(token))
  error = GetLastError()

  if status:
    print('OK, successes')
    CloseHandle(token)
  else:
    print(FormatError(error))

rawDescription: Authenticate windows server user in Python / C


code:
data = [['Bob Person', 10], ['Josh Winner', 15], ['Jimmy Dexter', 5], ['Mary Goodsprings', 15]]
sorted(data, key=lambda item: (-item[1], item[0]))

rawDescription: Python 3.3.2 - Sorting a List of Names based on a Number


code:
print("Random string value", end="")
if a==0:
    print(" is random")
else:
    print()

rawDescription: Print() to previous line?

description: Print() to previous line


code:
import os
os.getcwd()
os.mkdir("foo")  #creates foo in /home/monty
os.chdir("foo") #change the current working diirectory to `foo`
os.getcwd()
os.mkdir("bar")  #now `bar` is created in `/home/monty/foo`

rawDescription: How to make a folder in python? -mkdir/makedirs doesn't do this right

description: Make a folder in python? -mkdir/makedirs doesn't do this right


code:
def update_user_social_data(request, *args, **kwargs):
    user = kwargs['user']
    if not kwargs['is_new']:
        return
    user = kwargs['user']
    if kwargs['backend'].__class__.__name__ == 'FacebookBackend':
        fbuid = kwargs['response']['id']
        access_token = kwargs['response']['access_token']

        url = 'https://graph.facebook.com/{0}/' \
              '?fields=email,gender,name' \
              '&access_token={1}'.format(fbuid, access_token,)

        photo_url = "http://graph.facebook.com/%s/picture?type=large" \
            % kwargs['response']['id']
        request = urllib2.Request(url)
        response = urllib2.urlopen(request).read()
        email = json.loads(response).get('email')
        name = json.loads(response).get('name')
        gender = json.loads(response).get('gender')

rawDescription: Django-Social-Auth Facebook doesn't save user's details


code:
orig = 'hello'
# table = {'h': 'L', 'e': 'O', 'l': 'A', 'o': 'W' }
# table_tr = dict( (ord(a), ord(b))  for a,b in table.items() )
table_tr = str.maketrans('helo', 'LOAW')
res = orig.translate(table_tr)
print(res)

rawDescription: Need to change letters to other letters (Python 2.7)


code:
with open(filename) as input_file:
    data = []
    for line in input_file:
        if not line.startswith("Sarah,Brown"):
            data.append(line)

with open(filename, 'w') as output_file:
    for d in data:
        output_file.write(d + '\n')

rawDescription: How can I delete from a text file

description: Delete from a text file


code:
def adendumSeach(request):
    if 'grupname' in request.POST  and request.is_ajax():
        grupname = request.POST['grupname']
        adendum_list = adendum.objects.filter(adendum_credencial=grupname).distinct()
        formulario = serializers.serialize('json', adendum_list)
        return HttpResponse(formulario, mimetype="application/json")
    else:
        return render_to_response('ExpedienteDetalle.html',
        context_instance=RequestContext(request))

rawDescription: I have duplicates values in my database how to get only one


code:
class BatchRequest:
    'Class for sending several HTTP requests in a single request'

    def __init__(self, url, uuid):
        self.batch_url = batch_url
        self.uuid = uuid
        self.data = ""
        self.headers = {"Content-Type" : "multipart/mixed; boundary=\"batch_{0}\"".format(uuid)}

    #Build sub-request depending on Method and Data supplied
    def add_request(self, method, url, data={}):

        if method == "GET":
            self.data += "--batch_{0}\r\nContent-Type: application/http; msgtype=request\r\n\r\n{1} {2} HTTP/1.1\r\nHost: localhost:65200\r\n\r\n\r\n".format(uuid, method, url)

        #If no data, have alternative option
        elif method == "POST" or method == "PUT":
            self.data += "--batch_{0}\r\nContent-Type: application/http; msgtype=request\r\n\r\n{1} {2} HTTP/1.1\r\nHost: localhost:65200\r\nContent-Type: application/json; charset=utf-8\r\n\r\n{3}\r\n".format(uuid, method, url, json.dumps(data))

        elif method == "DELETE":
            self.data += "--batch_{0}\r\nContent-Type: application/http; msgtype=request\r\n\r\n{1} {2} HTTP/1.1\r\nHost: localhost:65200\r\n\r\n\r\n".format(uuid, method, url)

    def execute_request(self):
        #Add the "closing" boundary
        self.data += "--batch_{0}--\r\n".format(uuid)

        result = requests.post(self.batch_url, data=self.data, headers=self.headers)
        return result

if __name__ == '__main__':

    url = "http://localhost:65200/api"

    batch_url = "{0}/batch".format(url)

    uuid = uuid.uuid4()

    br = BatchRequest("http://localhost:65200/api", uuid)

    #Get customers
    br.add_request("GET", "/api/Customers")

    #Create a new customer
    new_customer = {"Id" : 10, "Name" : "Name 10"};
    br.add_request("POST", "/api/Customers", new_customer)

    #Update the name of the first customer in the list
    update_customer = customer_list[0]
    update_customer["Name"] = "Peter"
    br.add_request("PUT", "/api/Customers/{0}".format(update_customer["Id"]), update_customer)

    #Remove the second customer in the list
    br.add_request("DELETE", "/api/Customers/{0}".format(customer_list[1]["Id"]))

    result = br.execute_request()

rawDescription: Create mime/multipart request containing multiple HTTP requests


code:
a = "hi"
b = ["hello there", "goodbye", "nice to meet you"]

next(w for w in b if len(w.split()) == len(a))
# returns 'hello there'

[w for w in b if len(w.split()) == len(a)]
# returns ['hello there']

rawDescription: match length of string with a string with the same length in a list

description: Match length of string with a string with the same length in a list


rawDescription: Convert timestamp into one of custom Periods in Pandas


code:
{
    'address': address,
    'sensor': sensor
}

rawDescription: Benefit of initializing dictionary in function call


code: filter(r.match, list)

rawDescription: Regular Expressions: Search in list

description: Regular Expressions: Search in list


code:
import urllib2
import json
import time

while True:
    citibikenycJson = json.loads(urllib2.urlopen('http://www.citibikenyc.com/stations/json').read())
    # do something with the JSON
    time.sleep(5)

rawDescription: how do you generate citibike station feed in real-time?

description: Generate citibike station feed in real-time


code:
a = {k: the_form.cleaned_data[k]
     for k in request.data.viewkeys() & the_form.cleaned_data.viewkeys()}

rawDescription: How do I get union keys of `a` and `b` dictionary and 'a' values?

description: Get union keys of `a` and `b` dictionary and 'a' values


code:
hash = {}
for line in file:
    key, value = map(int, line.split())
    if key in hash:
        hash[key] += value
    else:
        hash[key] = value

rawDescription: Sum of matches found in a CSV

description: Sum of matches found in a CSV


code:
def send_html_email(self, subject, html, to_email, from_email, password, from_name, image=None):
    msgRoot = MIMEMultipart('related')
    msgRoot['From'] = from_name
    msgRoot['To'] = to_email
    msgRoot['Subject'] = subject
    msg = MIMEMultipart('alternative')
    msgRoot.attach(msg)
    html_message = MIMEText(html, "html")
    msg.attach(html_message)

    if image:
        msgImage = MIMEImage(image)
        msgImage.add_header('Content-ID', '<image1>')
        msgRoot.attach(msgImage)

    session = smtplib.SMTP("smtp.gmail.com:587")
    session.starttls()
    session.login(from_email, password)
    session.sendmail(from_email, to_email, msgRoot.as_string().encode('utf-8'))
    session.quit()

rawDescription: python smtplib multipart email body not showing on iphone

description: Python smtplib multipart email body not showing on iphone


code:
def sumup(n):
    # this one is your emergency break. you return 1 if n gets below
    # a certain threshold, otherwise you'll end up with an infinite
    # loop
    if n <= 1:
        return n
    # here is the recursion step, we return (n + "the sum to n+1")
    else:
        return n + sumup(n-1)

print(sumup(50))

rawDescription: recursive function in python adding?

description: Recursive function in python adding


code:
import pythoncom, pyHook, win32api, sys
import math
import threading, time
from time import sleep
...
#attempt to stop pyHook hang...
lock = threading.Lock()
def KeyEventThread1(i):
    lock.acquire()
    sys.exit()
    lock.release()
def KeyEventThread2(i):
    lock.acquire()
    move_circle()
    lock.release()

def OnKeyboardEvent(event):
    if event.Key == "Media_Play_Pause":
        t = threading.Thread(target=KeyEventThread1, args=(1,))
        t.start()
        sys.exit()
    else:
        t = threading.Thread(target=KeyEventThread2, args=(1,))
        t.start()
    # return True to pass the event to other handlers
    return True

def MouseEventThread(i):
    lock.acquire()
    sleep(.2) #So that mouse is not depressed when moved
    move_circle() # move the cursor
    hm.UnhookMouse() # unhook the mouse
    lock.release()

def OnMouseEvent(event):
    # called when mouse events are received
    if event.MessageName == "mouse left down":
        t = threading.Thread(target=MouseEventThread, args=(1,))
        t.start()
    hm.HookKeyboard()
    return True

hm = pyHook.HookManager()
hm.MouseAll = OnMouseEvent
hm.KeyDown  = OnKeyboardEvent
# Hook the mouse
hm.HookMouse()
 # hook the keyboard

# Wait for any events
pythoncom.PumpMessages()

rawDescription: Pyhook stops capturing key events after 6 presses


code:
command = input("Type a command")
if command in ["1","D","dog"]:
   do_something()
else:
   do_something_else()

rawDescription: How to check if an input matches a set of desired values without repeating myself?

description: Check if an input matches a set of desired values without repeating myself


code:
class MainPage(webapp2.RequestHandler):
  def get(self):
    path = os.path.join(os.path.dirname(__file__), 'upload_stuff')
    for filename in os.listdir(path):
      # Here you can do what you need with the files
      self.response.out.write(filename)

rawDescription: Get list of static files in a folder in server in Google App Engine platform


code:
from Bio import SeqIO
from Bio import Seq

path = r'C:\path\to\file.fastq'
default_phred_score_for_N = 60

def pad_sequence(record):
    sequence = str(record.seq)
    if len(sequence) < 414:
        #pad sequence
        padding_length = 414 - len(sequence)
        sequence += 'N' * padding_length

        # pad annotation
        annotation = record.letter_annotations['phred_quality']
        annotation  += [default_phred_score_for_N] * padding_length
        record.letter_annotations = {}

        record.seq = Seq.Seq(sequence)
        record.letter_annotations = {'phred_quality': annotation}
        return record
    return record

padded_sequences = (pad_sequence(record) for record in \
                    SeqIO.parse(path, 'fastq'))

SeqIO.write(padded_sequences, "padded.fastq", 'fastq')

rawDescription: Homogenize reads length

description: Homogenize reads length


code: sorted(Thing.objects.all(), key=lambda t: t.name)

rawDescription: Ordering Django queryset by an @property


code:
class PartialAuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title')

rawDescription: Django update one field using ModelForm

description: Django update one field using ModelForm


code:
from django.template import Context
from django.template.loader import get_template
from django.template.loader_tags import BlockNode, ExtendsNode

def _get_node(template, context=Context(), name='subject'):
    for node in template:
        if isinstance(node, BlockNode) and node.name == name:
            return node.render(context)
        elif isinstance(node, ExtendsNode):
            return _get_node(node.nodelist, context, name)
    raise Exception("Node '%s' could not be found in template." % name)

rawDescription: Django: How can I get a block from a template?


code:
import string
string = ''.join([('' if c in string.punctuation else ' ')+c for c in wordlist]).strip()

rawDescription: Python conditional list joins

description: Python conditional list joins


code: opt1 = OptionMenu(root, var1, *optionlist)

rawDescription: Pass to python method based on length of a list


code:
import subprocess

subprocess.call(r'C:\Python27\Lib\idlelib\idle.py -e C:\Python27\something.py',
                shell=True)

rawDescription: Opening IDLE from another Python script with command line paramteters


code:
from google.appengine.ext.webapp import template
from django import template as django_template

def in_list(value, arg):
  """
  Given an item and a list, check if the item is in the list.
  Usage:
  {% if item|in_list:list %}
      in list
  {% else %}
      not in list
  {% endif %}
  """
  return value in arg

register = template.create_template_register()
ifinlist = register.filter(in_list)

rawDescription: How to check a List for a match in Django?

description: Check a List for a match in Django


code:
from joblib import Parallel, delayed
from itertools import product
from scipy.optimize import nnls
results = Parallel(n_jobs=10)(delayed(nnls)(A, b_array[:,i,j])[0]
             for i, j in product(range(100), range(100)))
x_array = np.array(results).reshape(100, 100, -1).transpose(2, 0, 1)

rawDescription: SciPy: element-wise non-negative least squares using an array of b vectors


rawDescription: write a Python 3 list to .csv

description: Write a Python 3 list to .csv


code:
from datetime import datetime as dt
date_as_string = '1/12/07 00:07 AM'
format_12 = '%d/%m/%y %I:%M %p'
format_24 = '%d/%m/%y %H:%M %p'
date_string, time_string = date_as_string.split(' ', 1)
try:
    dt.strptime(date_string + ' ' + time_string, format_12)
except ValueError:
    dt.strptime(date_string + ' ' + time_string, format_24)

rawDescription: python strptime wrong format with 12-hour hour

description: Python strptime wrong format with 12-hour hour


code:
class myclass(object):
    def __getattr__(self, name):
        module = __import__(name)
        func = getattr(module, name)
        setattr(self, name, func)
        return func

rawDescription: Lazy loading class instance methods

description: Lazy loading class instance methods


code:
import struct
struct.unpack('<i', 'o\xf2\x00\x00')

rawDescription: How to convert hex string 'o\xf2\x00\x00' into a int32?

description: Convert hex string 'o\xf2\x00\x00' into a int32


code: outfile = re.sub(r"(?<!\.min)\.js$", ".min.js", infile)

rawDescription: Regular expression: replace the suffix of a string ending in '.js' but not 'min.js'


code:
z = x[:]
z = list(x)

rawDescription: "backtracking" variables in python del function


code:
with requests.Session() as sesssion:
    response = session.get(login_url)
    response.raise_for_status()  # raises HTTPError if: 400 <= status_code < 600

    csrf = session.cookies['csrftoken']
    data = {
        'username': self.username,
        'password': self.password,
        'csrfmiddlewaretoken': csrf
    }

    response = session.post(login_url, data=data)
    response.raise_for_status()

    headers = {'X-CSRFToken': csrf, 'Referer': url}
    response = session.post('another_url', data={}, headers=headers)
    response.raise_for_status()

    return response  # At this point we probably made it

rawDescription: django and python requests - getting a 403 on a post request

description: Django and python requests - getting a 403 on a post request


code:
while len(numbers) < minimumNumberOfElementsRequired:
    index = 1
    while index < len(numbers):
        numbers.insert(index, (numbers[index-1] + numbers[index]) / 2.0)
        index += 2

rawDescription: How should one loop over two elements of a Python list at a time while building a new list?


code:
for alpha_i in alpha:
    Phase = phase_angle(alpha_i,f,f_eig)
    host.plot(Freq, Phase, label=r'$\alpha = {0}$'.format(alpha_i), linewidth=2)

rawDescription: Mixing Latex symbol and concatenation in a label


code:
import csv

fileAin = open('old.csv','rb')
fOld = csv.reader(fileAin)

fileBin = open('new.csv','rb')
fNew = csv.reader(fileBin)

fileCout = open('NewAndUpdated.csv','wb')
fNewUpdate = csv.writer(fileCout)

old = {row[0]:row[1:] for row in fOld}
new = {row[0]:row[1:] for row in fNew}
fileAin.close()
fileBin.close()

output = {}

for row_id in new:
    if row_id not in old or not old[row_id] == new[row_id]:
        output[row_id] = new[row_id]

for row_id in output:
    fNewUpdate.writerow([row_id] + output[row_id])

fileCout.close()

rawDescription: Optimize python file comparison script

description: Optimize python file comparison script


code:
from Tkinter import * #from tkinter

root = Tk()
i = PhotoImage(width=100, height=100)
l = Label(root, image=i)
l.pack()
i.put("{red}", to=(4,6,80,80))
root.update()
root.after(3000)
i.put("{blue}", to=(4,6,80,80))
root.mainloop()

rawDescription: tkinter photoimage constructor

description: Tkinter photoimage constructor


code:
test = [{"first" : "xyz", 'score': [1,2,3,4]},{"first" : "tests", 'score': [22,33,4]}]
for i in test:                    # Iterate through the loop
    if i["first"] == 'xyz':       # Check if the dict's value at "first"
        print("The score is {}".format(i["score"]))
                                  # Print the score

rawDescription: how to get index of a dictionary within a list

description: Get index of a dictionary within a list


code:
from odf import text as odftext
from odf import opendocument
document = opendocument.OpenDocument()
document.text.addElement(odftext.Section(name="section1"))

rawDescription: Add Section to OpenDocument Text file with ODFpy


code:
df = DataFrame(randn(5,1),columns=['value'])
df
df.loc[df['value']<0,'value'] = 0
df

rawDescription: Return max of zero or value for a pandas DataFrame column


code:
import fileinput
from glob import glob

log_files = glob('/some/dir/with/logs/*.log')
for line in fileinput.input(log_files):
    pass # do something

rawDescription: How to run logic over several large apache log files in Python?

description: Run logic over several large apache log files in Python


code:
import mahotas as mh
import numpy as np

original_img = np.array(mh.imread('figure1.jpg'), dtype=np.float64) / 255
# check dimension, RGB
original_img.shape
Out[13]: (1536, 2048, 3)

width, height, depth = original_img.shape
# reshape
image_flattened = np.reshape(original_img, (width*height, depth))

image_flattened.shape
Out[17]: (3145728, 3)

rawDescription: How can I read jpeg file binary (without decoding) properly and save it?

description: Read jpeg file binary (without decoding) properly and save it


rawDescription: Special characters in countVectorizer Scikit-learn


code: trait = self.trait if self.trait == self.spouse.trait else defaultTrait

rawDescription: Python version of C#'s conditional operator (?)


code: fsolve(lambda a,x,b: eqn(x, a, b), x0=0.5, args=(x,b))

rawDescription: Choose which variable to solve for (Python root finding using fsolve)


code:
mad = lambda x: np.fabs(x - x.mean()).mean()
rolling_apply(ts, 60, mad).plot(style='k')

rawDescription: How to apply a complex formula using Pandas in Python?

description: Apply a complex formula using Pandas in Python


code: df.apply(lambda x: '.'.join(x[['col2', 'col3', 'col4']]),axis=1)

rawDescription: Pasting selected columns into new column with separator in Pandas


code:
plugin_url_for = plugin.url_for
_, dirs, _ = iter(os.walk(PATH_TO_DIRECTORY)).next()
items = [{
     'label': directory, 'path': plugin_url_for('test')
} for directory in dirs]

rawDescription: Using os.walk to add to list

description: Using os.walk to add to list


code:
import random

def insert_spaces(s):
    s = list(s)
    for i in xrange(len(s)-1):
        while random.randrange(2):
            s[i] = s[i] + ' '
    return ''.join(s)

rawDescription: Is there a pythonic way to insert space characters at random positions of an existing string?


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

N = 5
menMeans = (20, 35, 30, 35, 27)
menStd =   (2, 3, 4, 1, 2)

ind = np.arange(N)  # the x locations for the groups
width = 0.35       # the width of the bars

fig = plt.figure()
ax = fig.add_subplot(111)
rects1 = ax.bar(ind, menMeans, width, color='r', yerr=menStd)

womenMeans = (25, 32, 34, 20, 25)
womenStd =   (3, 5, 2, 3, 3)
rects2 = ax.bar(ind+width, womenMeans, width, color='y', yerr=womenStd)

# add some
ax.set_ylabel('Scores')
ax.set_title('Scores by group and gender')
ax.set_xticks(ind+width)
ax.set_xticklabels( ('G1', 'G2', 'G3', 'G4', 'G5') )

ax.legend( (rects1[0], rects2[0]), ('Men', 'Women') )

plt.show()

rawDescription: How to plot bar graphs with same X coordinates side by side

description: Plot bar graphs with same X coordinates side by side


code:
from flask.views import MethodView
from flask.ext.login import login_required

class LoggedInView(MethodView):
    decorators = [login_required]

    def get(self):
        pass

    def post(self):
        pass

    # ...

rawDescription: Decorate methods in derived classes of Flask MethodView


code:
import matplotlib.pyplot as plt

x = ["i","like","python"]
y = [1,2,3]

plt.plot(y,y)  # y,y because both are numeric (you could create an xt = [1,2,3]
plt.xticks(y,x) # same here, the second argument are the labels.
plt.show()

rawDescription: Python 2.7 time series non numeric values


code:
from Tkinter import *
def yes_command():
    global answer
    answer.set('yes')
    window.destroy()

def no_command():
    global answer
    answer.set('no')
    window.destroy()

window = Tk()

yes_no_label = Label(window, text="Yes or no?")
yes_no_label.grid(row=0, column=1)

global answer
answer=StringVar()

YESbutton = Button(window, text="Yes", fg='green', command = lambda :yes_command())
YESbutton.grid(row=1, column=0)
NObutton = Button(window, text = 'No', fg = 'red', command= lambda :no_command())
NObutton.grid(row=1, column=2)

window.mainloop()

print(answer.get())

rawDescription: Python 3.4.2, using Tkinter buttons to return a variable to be used by the program


code:
# use with to open files, this makes sure that it's properly closed after an exception
with open('output.txt', 'a') as f:
    # iterate over individual Records in RecordList
    for record in results:
        # concatenate all columns of the Record into a string, comma separated
        # list comprehension with str() to handle int and other types
        output_string = ','.join([str(x) for x in record])
        # actually write to file
        print(output_string, file=f)

rawDescription: Output py2neo recordlist to text file

description: Output py2neo recordlist to text file


code:
from pycuda import driver, gpuarray
from pycuda.compiler import SourceModule
import pycuda.autoinit
kernel_code_template="""

#include "adoublecuda.h"
__global__ void myfunction(float* inx, float* outy, float* outderiv)
{
    //defining thread index
    ...
    //declare dependent and independet variables as adoubles
    //this is a part of my question
    adtl::adouble y[3];
    adtl::adouble x[3];
    // ...
}

"""

module = SourceModule(kernel_code_template, include_dirs=['path/to/adoublecuda'])

rawDescription: Passing a C++/CUDA class to PyCUDA's SourceModule


code:
import subprocess, time

s = subprocess.Popen(['foo', 'args'])
timeout = 1
poll_period = 0.1
s.poll()
while s.returncode is None and timeout > 0:
    time.sleep(poll_period)
    timeout -= poll_period
    s.poll()
if timeout <= 0:
    s.kill() # timed out
else:
    pass # completed

rawDescription: Run a external program with specified max running time


code:
import win32com.client

xl = win32com.client.Dispatch("Excel.Application")
print(xl.ActiveWorkbook.FullName)

rawDescription: Python detect and retrieve filename of open csv file


code:
from copy import deepcopy

g={1:'a',2:'b',3:["k",'c'],4:'d'}

gt=copy.deepcopy(g)

gt[3].remove('c')

rawDescription: How can I leave the original dictionary unchanged, when editing a the new dict

description: Leave the original dictionary unchanged, when editing a the new dict


code:
from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.get("http://www.hillsproducts.com/General.aspx/en-GB/PD/a-d-canine/original/can")

index = 0
while True:
    select = Select(driver.find_element_by_id("productSpecifier_product"))

    # exit the loop if all the options were seen
    if index >= len(select.options):
        break

    select.select_by_index(index)
    print(driver.current_url)

    index += 1

rawDescription: Read a page after another from a drop down menu - Can't find the drop down on 2nd page


code:
from tkinter import *

root = Tk()
def cheese():
    root.destroy()
logo = PhotoImage(file = '../Desktop/logothing.gif')
background_label = Label(root, image=logo)
background_label.image = logo
background_label.place(x=0, y=0, relwidth=1, relheight=1)
explanation = """Flaming Arrows whizz over your hair, War rages around you. Suddenly,
it charges into you. A 8 foot tall mechanical beast the enemy have been training for war.
You have no chance but to fight it. You swing your sword as hard as you can...Only to
leave a minor dent on it's armor. With one blow from its club, you fall unconscious."""
w= Label(root, image=logo).pack(side='right')
w1 = Button(root, text = 'Wake Up',command = cheese, fg='blue', font = "Impact 20")
w1.pack(side='bottom')

w2 = Label(root,
           justify=LEFT,
           text=explanation,
           compound = CENTER,
           fg="blue", padx=0,font="ComicSansMS 32 bold")
w2.pack(side='left')

rawDescription: PhotoImage not showing up the image associated with it


code:
words = input("Enter a word or sentence: ").strip()
words = words.lower()
if 'water' in words and 'phone' in words:
    print('Dry your phone')

rawDescription: Searching for keywords in python

description: Searching for keywords in python


code:
developmentServer = False

if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
    developmentServer = True

class BaseRequestHandler(webapp2.RequestHandler):
    def dispatch(self):
        retValue = super(BaseRequestHandler, self).dispatch()
        if developmentServer:
                from google.appengine.tools import dev_appserver
                dev_appserver.TearDownStubs()

        return retValue

rawDescription: GAE SDK 1.6.4 dev_appserver datastore flush


code:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
    return 2 * x

def g(x):
    return f(x) - np.random.uniform(-0.5, 0.5, size=x.shape)

x = np.linspace(0, 5, 51)
y = f(x)
y2 = g(x)

# plot
plt.plot(x, y, 'b-')
plt.plot(x, y2, 'ro')
plt.show()

rawDescription: Scattered plot Numpy Matplot

description: Scattered plot Numpy Matplot