code:
def updateEditorGeometry( self, editor, option, index ):
    # input data by here will update automatically
    col = index.column ()
    row = index.row ()
    val = int(self.tm.arraydata[row][col])
    editor.setValue (val)

    editor.setGeometry(rect)

rawDescription: how to update ( setvalue , sorting , editing , background color ) QProgressBar (QitemDelegate) inside QTableview (QAbstractTableModel)

description: Update ( setvalue , sorting , editing , background color ) QProgressBar (QitemDelegate) inside QTableview (QAbstractTableModel)


code: newx = "-".join(x[i:i+3] for i in range(0, len(x), 3))

rawDescription: Python: String Manipulation

description: Python: String Manipulation


code:
def func(args):
  if x_version != 1.7:
    return
  """docstring is here"""
func.__doc__ is None

rawDescription: Any reason to put code before the docstring in Python?


code:
class RecipeHandler(Handler):

    def extract_template_name_from_request(self):

        return self.request.path_info[9:] # strip leading '/recipes/' (or whatever else you need)

    def get(self):

        template_name = self.extract_template_name_from_request()
        try:
            template = JINJA_ENVIRONMENT.get_template(template_name)
        except Exception:
            # can't locate a template matching the requested path
            self.abort(404)
            return

        # prepare the template values as needed
        values = {'recipe': {'name': template_name[:-5]}}  # just an example

        try:
            self.response.write(template.render(values))
        except Exception:
            # failure rendering the template
            self.abort(500)

app = webapp2.WSGIApplication([
    ('/recipes/.*.html', RecipeHandler), # see extract_template_name_from_request()
    ('/.*', MainHandler),
], debug=True)

rawDescription: Render Multiple Jinja Templates with One Handler


code:
def sum_to_n(n, size, limit=None):
    """Produce all lists of `size` positive integers in decreasing order
    that add up to `n`."""
    if size == 1:
        yield [n]
        return
    if limit is None:
        limit = n
    start = (n + size - 1) // size
    stop = min(limit, n - size + 1) + 1
    for i in range(start, stop):
        for tail in sum_to_n(n - i, size - 1, i):
            yield [i] + tail

for partition in sum_to_n(6, 3):
    print (partition)

[2, 2, 2]
[3, 2, 1]
[4, 1, 1]

rawDescription: Python: Find all possible combinations of parts of a given number


code:
class Foo(object):
    def __init__(self):
        self.egg = [4,3,2,1,[4,3,2,1]]
        self.spam = (4,2)

    def process(self):
        # do something on self.egg[self.spam]
        print(self.eggspam)
        pass

    @property
    def eggspam(self):
        result = self.egg
        for item in self.spam:
            result = result[item]
        return result

f = Foo()
f.process()
# 2

f.spam = (1,)
f.process()
# 3

rawDescription: Aliasing python variables without dict

description: Aliasing python variables without dict


code:
import time
t1=time.gmtime(1284286794)
t1

rawDescription: Python Binary File CTime 4 Bytes

description: Python Binary File CTime 4 Bytes


code:
gmt = pytz.timezone('GMT')
eastern = pytz.timezone('US/Eastern')
time = "Tue, 12 Jun 2012 14:03:10 GMT"
date = datetime.datetime.strptime(time, '%a, %d %b %Y %H:%M:%S GMT')
date
dategmt = gmt.localize(date)
dategmt
dateeastern = dategmt.astimezone(eastern)
dateeastern

rawDescription: How to convert GMT time to EST time using python

description: Convert GMT time to EST time using python


code: {d["NAME"]:d["VALUE"] for d in input_dir}

rawDescription: How to change the Key and Value in a list of dict in python?

description: Change the Key and Value in a list of dict in python


rawDescription: A good data model for finding a user's favorite stories


code:
import re
s = "& how are you then? I am fine, % and i want to found some food #meat with vegetable# #tea# #cake# and #tea# so on."
re.findall(r'#([^#]*)#', s)
from collections import Counter
Counter(re.findall(r'#([^#]*)#', s))

rawDescription: Python - retrieve a specific sentence from a large text file


code:
form_fields = {
   "data": ["foo","bar"]
}

form_data = urllib.urlencode(form_fields, doseq=True)

rawDescription: Sending multiple POST data items with the same name, using AppEngine


code:
def create_list(n):
    new_list = cell.Cell(0)
    last_a = new_list
    for i in (range(1,n)):
        a = cell.Cell(i)
        cell.list_concat(last_a, a)
        last_a = a
    return new_list

rawDescription: Faster way to create a linked list of n-length in Python


code:
class Player(object):
    def __init__(self, name):
        self.name = name

p1 = Player("bernard")
p2 = Player("hoagie")

t = (p1, p2, ...)
d = {p: p.name + " something something" for p in t}

rawDescription: Python dictionary - is it possible to reference key in value?


code:
def opener():
    cj=cookielib.CookieJar()
    #Process Hadlers
    opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
    opener.addheaders=[
                    ('Accept', 'application/json, text/javascript, */*; q=0.01'),
                    ('X-Requested-With', 'XMLHttpRequest'),
                    ('Referer', 'http://www.namestation.com/domain-search?autosearch=1'),
                    ('Host', 'www.namestation.com'),
                    ('Content-Type', 'application/json; charset=UTF-8'),
                    ('Connection', 'keep-alive'),
                ]
    return opener

rawDescription: How do I add these headers to my python urllib opener?

description: Add these headers to my python urllib opener


code:
if line.startswith('Best CV Model'):
    re.findall(r'\d+\.{0,1}\d*', line)

rawDescription: extracting number after certain words in a text file

description: Extracting number after certain words in a text file


code:
import imaplib, getpass, re
pattern_uid = re.compile('\d+ \(UID (?P<uid>\d+)\)')

def connect(email):
    imap = imaplib.IMAP4_SSL("imap.gmail.com")
    password = getpass.getpass("Enter your password: ")
    imap.login(email, password)
    return imap

def disconnect(imap):
    imap.logout()

def parse_uid(data):
    match = pattern_uid.match(data)
    return match.group('uid')

if __name__ == '__main__':
    imap = connect('<your mail id>')
    imap.select(mailbox = '<source folder>', readonly = False)
    resp, items = imap.search(None, 'All')
    email_ids  = items[0].split()
    latest_email_id = email_ids[-1] # Assuming that you are moving the latest email.

    resp, data = imap.fetch(latest_email_id, "(UID)")
    msg_uid = parse_uid(data[0])

    result = imap.uid('COPY', msg_uid, '<destination folder>')

    if result[0] == 'OK':
        mov, data = imap.uid('STORE', msg_uid , '+FLAGS', '(\Deleted)')
        imap.expunge()

    disconnect(imap)

rawDescription: Move an email in GMail with Python and imaplib


code:
from pymongo import MongoClient
# Assuming youre running mongod on 'localhost' with port 27017
c = MongoClient('localhost',27017)
c.database_names()

rawDescription: how to issue a "show dbs" from pymongo

description: Issue a "show dbs" from pymongo


rawDescription: Diagonalising a Pandas series

description: Diagonalising a Pandas series


code:
pipe_verbose = sys.stdout
pipe_silent  = open('/dev/null', 'w')

subprocess.Popen(shlex.split(command), stdout=pipe_silent)
subprocess.Popen(shlex.split(command), stdout=pipe_verbose)

rawDescription: How to manage subprocess in Python when the output is huge?

description: Manage subprocess in Python when the output is huge


code:
import gc
import gevent
from greenlet import greenlet
gevent.killall([obj for obj in gc.get_objects() if isinstance(obj, greenlet)])

rawDescription: In a gevent appliction, how can I kill all greenlets that have been started?


rawDescription: How do you make a string repeat itself in python

description: Make a string repeat itself in python


code:
class MyDoc(Document):
    structure = {
        "name": unicode,
        "items": [{
             "category": int,
             "desc": unicode
        }]
    }

    def validate(self, *args, **kwargs):
        super(MyDoc, self).validate(*args, **kwars)
        for item in self["items"]:
            assert item["desc"], "desc is required: %s" % item

rawDescription: Mongokit validate dict inside list

description: Mongokit validate dict inside list


code:
import git
r = git.Repo(path_to_repo)
res = r.git.show("%s:%s" % (hexsha, file_path))

rawDescription: HOW-TO: git show hexsha:directorypath/file


code:
def dpMakeChange(coinValueList,change,minCoins):
   # Solve the problem for each number of cents less than the target
   for cents in range(change+1):

      # At worst, it takes all pennies, so make that the base solution
      coinCount = cents

      # Try all coin values less than the current number of cents
      for j in [c for c in coinValueList if c <= cents]:

            # See if a solution to current number of cents minus the value
            # of the current coin, with one more coin added is the best
            # solution so far
            if minCoins[cents-j] + 1 < coinCount:
               coinCount = minCoins[cents-j]+1

      # Memoize the solution for the current number of cents
      minCoins[cents] = coinCount

   # By the time we're here, we've built the solution to the overall problem,
   # so return it
   return minCoins[change]

rawDescription: Dynamic Programming Optimal Coin Change

description: Dynamic Programming Optimal Coin Change


code:
class Entities(object):
    # not here
    def __init__(self, name):
        self.name = name
        self.neighbor_list = [] # here

rawDescription: Appending list in Python

description: Appending list in Python


code:
s = ...
res = re.match(r'\D*' + 25 * r'(\d+)\D+')
numbers = [r for r in res.groups() if r is not None]

rawDescription: python regex repetition with capture question

description: Python regex repetition with capture question


code:
def primes(n, skip_range=None):
    """Modified "primes" with the original assertion from P.S. of the question.
    with skipping of an unimportant huge range.
    >>> primes(71)
    [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
    >>> # The smallest failing number for the first failing prime 71:
    >>> big_n = 10986448536829734695346889
    >>> primes(big_n + 2 * 71, (72, big_n))
    Traceback (most recent call last):
    AssertionError
    """
    if not skip_range:
        primes = list(range(2, n + 1))
    else:
        primes = list(range(2, skip_range[0]))
        primes.extend(range(skip_range[1], n + 1))
    p = 0
    while p < len(primes):
        c = p + 1
        while c < len(primes):
            if(primes[c] % primes[p] == 0):
                primes.pop(c)
                if c < len(primes):
                    assert primes[c] % primes[p] != 0
            c = c + 1
        p = p + 1
    return primes

# Verify that it can fail.
aprime = 71   # the first problematic prime
FIRST_BAD_NUMBERS = (
        10986448536829734695346889, 11078434793489708690791399,
        12367063025234804812185529, 20329913969650068499781719,
        30697401499184410328653969, 35961932865481861481238649,
        40008133490686471804514089, 41414505712084173826517629,
        49440212368558553144898949, 52201441345368693378576229)

for bad_number in FIRST_BAD_NUMBERS:
    try:
        primes(bad_number + 2 * aprime, (aprime + 1, bad_number))
        raise Exception('The number {} should fail'.format(bad_number))
    except AssertionError:
        print('{} OK. It fails as is expected'.format(bad_number))

rawDescription: Does this prime function actually work?

description: Does this prime function actually work


code:
import re
re.split(r'(?<=\d)\D', 'start 123 after text', maxsplit=1)

rawDescription: Python- can I split a string with str.split after the first integer?


code:
def grouper( page_size, iterable ):
    page= []
    for item in iterable:
        page.append( item )
        if len(page) == page_size:
            yield page
            page= []
    yield page

rawDescription: How to write a pager for Python iterators?

description: Write a pager for Python iterators


code:
import token
import keyword
import tokenize

s = open('hi.py').readline
counter = 0
l = []
for i in tokenize.generate_tokens(s):
    if i.type == token.NAME and keyword.iskeyword(i.string):
        counter += 1
        l.append(i.string)

print(counter)
print(l)

rawDescription: Python: How to count the keywords in a py file?


code:
import vtk
from numpy import random

class VtkPointCloud:

    def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6):
        self.maxNumPoints = maxNumPoints
        self.vtkPolyData = vtk.vtkPolyData()
        self.clearPoints()
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputData(self.vtkPolyData)
        mapper.SetColorModeToDefault()
        mapper.SetScalarRange(zMin, zMax)
        mapper.SetScalarVisibility(1)
        self.vtkActor = vtk.vtkActor()
        self.vtkActor.SetMapper(mapper)

    def addPoint(self, point):
        if self.vtkPoints.GetNumberOfPoints() < self.maxNumPoints:
            pointId = self.vtkPoints.InsertNextPoint(point[:])
            self.vtkDepth.InsertNextValue(point[2])
            self.vtkCells.InsertNextCell(1)
            self.vtkCells.InsertCellPoint(pointId)
        else:
            r = random.randint(0, self.maxNumPoints)
            self.vtkPoints.SetPoint(r, point[:])
        self.vtkCells.Modified()
        self.vtkPoints.Modified()
        self.vtkDepth.Modified()

    def clearPoints(self):
        self.vtkPoints = vtk.vtkPoints()
        self.vtkCells = vtk.vtkCellArray()
        self.vtkDepth = vtk.vtkDoubleArray()
        self.vtkDepth.SetName('DepthArray')
        self.vtkPolyData.SetPoints(self.vtkPoints)
        self.vtkPolyData.SetVerts(self.vtkCells)
        self.vtkPolyData.GetPointData().SetScalars(self.vtkDepth)
        self.vtkPolyData.GetPointData().SetActiveScalars('DepthArray')

pointCloud = VtkPointCloud()
for k in xrange(1000):
    point = 20*(random.rand(3)-0.5)
    pointCloud.addPoint(point)
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])
pointCloud.addPoint([0,0,0])

# Renderer
renderer = vtk.vtkRenderer()
renderer.AddActor(pointCloud.vtkActor)
renderer.SetBackground(.2, .3, .4)
renderer.ResetCamera()

# Render Window
renderWindow = vtk.vtkRenderWindow()
renderWindow.AddRenderer(renderer)

# Interactor
renderWindowInteractor = vtk.vtkRenderWindowInteractor()
renderWindowInteractor.SetRenderWindow(renderWindow)

# Begin Interaction
renderWindow.Render()
renderWindowInteractor.Start()

rawDescription: How to display point cloud in vtk in different colors?

description: Display point cloud in vtk in different colors


code:
def wrapped_func(**kwargs):
   # Do some preparation stuff here.
   func('/path/to/file.csv', **kwargs)
   # Do some other stuff.

rawDescription: Passing **kwargs received in a wrapper-function definition, to arguments of an enclosed (i.e. wrapped) function call


code:
import pygame

pygame.init()
pygame.mixer.init()
sounda= pygame.mixer.Sound("desert_rustle.wav")

sounda.play()
sounda.stop()

rawDescription: how to play audio file in python?

description: Play audio file in python


code:
class Parser():

    def __init__(self, uri):
        self.uri = uri
        self.soup = self.createSoup()

    def createSoup(self):
        htmlPage = urlopen(self.uri)
        htmlText = htmlPage.read()
        return BeautifulSoup(htmlText)

rawDescription: creating instance methods outside of the constructor in python

description: Creating instance methods outside of the constructor in python


code:
try:
    # Python 2
    from SimpleHTTPServer import test
except ImportError:
    # Python 3
    from http.server import test

test()

rawDescription: Python Start HTTP Server In Code (Create .py To Start HTTP Server)


code:
count = 0

for letter in set(string1):
  count += string2.count(letter)

print(count)

rawDescription: Occurence of characters in common in two strings


rawDescription: How to use select_for_update to 'get' a Query in Django?

description: Use select_for_update to 'get' a Query in Django


code:
L = ['a,b,c,d','e,f,g,h,i','j,k,l',]
[item.count(',')+1 for item in L]

rawDescription: counting elements in list of strings python

description: Counting elements in list of strings python


code:
from pathlib import Path
for subdir in sorted(Path('/some/path').iterdir()):
    print(subdir)

rawDescription: How to control order of result from iterator in python

description: Control order of result from iterator in python


code: client.create(path, ephemeral=True)

rawDescription: How to keep kazoo connected to zookeeper?

description: Keep kazoo connected to zookeeper


code:
cb1=plt.colorbar(i1,ax=ax1,ticks=[U.min(),(U.min()+U.max())/2., U.max()],fraction=0.046, pad=0.04,format='%.2f')

cb2=plt.colorbar(i2,ax=ax2,fraction=0.046, pad=0.04,ticks=[UU.min(),(UU.min()+UU.max())/2.,UU.max()],format='%.2f')

cb3=plt.colorbar(i3,ax=ax3,fraction=0.046, pad=0.04,ticks=[resU.min(), (resU.min()+resU.max())/2.,resU.max()],format='%.2f')

cb1.ax.tick_params(labelsize=6)
cb2.ax.tick_params(labelsize=6)
cb3.ax.tick_params(labelsize=6)

rawDescription: Python - Label size of colorbar

description: Python - Label size of colorbar


code:
alist=["Barney",["Wilma"]]

alist.append(t2) # ['Barney', ['Wilma'], ('A', 'B', 'Hello')]

pop1 = alist.pop(1) # ['Wilma']
extend1 = pop1.extend(t2) #extend1 = None, pop1 = ['Wilma', 'A', 'B', 'Hello']
print(alist.pop(1).extend(t2)) # None
print(alist) #you've popped wilma, so the rest remains:   ['Barney', ('A', 'B', 'Hello')]

rawDescription: tuples python pop and append

description: Tuples python pop and append


code:
import os

loc = os.getcwd()

rawDescription: How to get python to know what directory you're working in

description: Get python to know what directory you're working in


code: cookie['Cycle']['domain']    # lowercase domain !

rawDescription: Python how to get the domain of a cookie


code:
next(infile)  # Skip the first line
for line in infile:
    words = line.split(',')
    medalDict[words[0]] = tuple(map(int, words[1:]))

rawDescription: Making a dictionary from file, first word is key in each line then other four numbers are to be a tuple value


code:
import sys, shutil, time, threading

class CopyThread(threading.Thread):
    def __init__(self, source, destination):
        super(CopyThread, self).__init__()

        self.source = source
        self.destination = destination

    def run(self):
        time.sleep(5)  # Delete me later on, I'm just here to slow things down
        return shutil.copytree(src=self.source, dst=self.destination)

if __name__ == '__main__':
    thread = CopyThread('source_folder', 'destination_folder')
    thread.start()

    while thread.is_alive():
        sys.stdout.write('.')
        sys.stdout.flush()

        time.sleep(1)

    thread.join()

rawDescription: Print character while copying big folder


code:
import re
matches = re.findall(r'(\d+).*?Lo (\d+)', lines[line_number+4])
if matches:
    high, low = matches[0]

rawDescription: Finding the second of the same two words in a line


code:
import dj_database_url
DATABASES['default'] = dj_database_url.config()

rawDescription: How to use dj-database-url while connecting with postgresql in heroku using python

description: Use dj-database-url while connecting with postgresql in heroku using python


code: x = np.sort(np.hstack((orig, extra)))

rawDescription: Merging numpy arrays (inserting extra values into an existing array)


code:
import csv

def strip_empty_columns(line):
    return filter(lambda s: s.strip() != "", line)

def is_count(line):
    return len(line) == 1 and line[0].strip().isdigit()

def is_float(s):
    try:
        float(s.strip())
        return True
    except ValueError:
        return False

def is_data_line(line):
    return len(line) == 4 and is_float(line[1]) and is_float(line[2]) and is_float(line[3])

with open('frames.dat', 'r') as mest:
    r = csv.reader(mest, delimiter=' ')
    current_count = 0
    frame_nr = 0
    outfile = None

    for line in r:
        line = strip_empty_columns(line)
        if is_count(line):
            if frame_nr % 100 == 0:
                outfile = open("snapshot%d.xyz" % frame_nr, "w+")
            elif outfile:
                outfile.close()
                outfile = None
            frame_nr += 1 # increment the frame counter every time you see this header line like '18'
        elif is_data_line(line):
            if outfile:
                outfile.write("    ".join(line) + "\n")

rawDescription: How do I print a range of lines after a specific pattern into separate files when this pattern appears several times in an input file

description: Print a range of lines after a specific pattern into separate files when this pattern appears several times in an input file


code:
import xml.dom.minidom

importstring = "$(Projectname).targets"
filename = "test.xml"

tree = xml.dom.minidom.parse(filename)
Project = tree.getElementsByTagName("Project")[0]

for Import in Project.getElementsByTagName("Import"):
    if Import.getAttribute("Project") == importstring:
        break
else: # note this is else belongs to the for, not the if
    newImport = xml.dom.minidom.Element("Import")
    newImport.setAttribute("Project", importstring)
    Project.appendChild(newImport)

tree.writexml(open(filename, 'w'))

rawDescription: Add a line to a file if it not exist using python


code:
def get_member(a,the_list):
    if a in the_list:
        return a
    else:
        for elem in the_list:
            if isinstance(elem,list):
                if a in elem:
                    return elem
    return None

def merge_member(a,b,the_list):
    get_member_a = get_member(a,the_list)
    get_member_b = get_member(b,the_list)
    if get_member_a and get_member_b:
        the_list.remove(get_member_a)
        the_list.remove(get_member_b)
        if isinstance(get_member_b,list):
            get_member_b.extend(get_member_a)
            the_list.append(get_member_b)
        elif isinstance(get_member_a,list):
            get_member_a.extend(get_member_b)
            the_list.append(get_member_a)
        else:
            the_list.append([get_member_b,get_member_a])
    return the_list

rawDescription: Merging sets within sets in Python

description: Merging sets within sets in Python


code:
conversion_rates = {
    'in': 2.54, # 2.54 inches in a centimetre
    'cm': 1.00, # this is our reference unit
    'sun': 3.03 # a traditional Japanese unit of measurement
}

# raises ValueError if the number of words in the input is wrong
amount, original_unit, final_unit = line.split()

# raises ValueError if the amount is not formatted as a floating-point number
amount = float(amount)

# Now we do the conversion.
# raises KeyError if either unit is not found in the dict.
result = amount * conversion_rates[original_unit] / conversion_rates[final_unit]

rawDescription: Python, run a function based on formatting and contents of an input string


code:
for n in range(1, 10, 2):
    print(n, '\t', n + 10)

rawDescription: Python, printing two columns of numbers using for loop


code:
print(countChange(30, list(reversed(range(1, 31)))))
print(countChange2(30, list(reversed(range(1, 31)))))

rawDescription: Why does backward recursion execute faster than forward recursion in python


rawDescription: Create if-elif statements using for loop


code:
text = 'sassy'
for (regexp,subst) in [ (r'(?<=.)s', '5'),(r'^s', '$') ]:
  text = re.sub(regexp,subst,text)

text

rawDescription: transforming the same character into different characters depending on position in word

description: Transforming the same character into different characters depending on position in word


code:
from jupyter_client import find_connection_file
find_connection_file()

rawDescription: What is the Jupyter eqivalent to IPython's find_connection_file


rawDescription: Pascal's triangle in python

description: Pascal's triangle in python


code:
import datetime
start = datetime.datetime.strptime(u'2013-05-20 05:09:06', '%Y-%m-%d %H:%M:%S')
end = datetime.datetime.strptime(u'2013-05-20 05:10:06', '%Y-%m-%d %H:%M:%S')
(end - start).total_seconds()

rawDescription: How I calculate the difference of two date time


code:
stdin, stdout, stderr = client.exec_command(cmd)
stdin.channel.shutdown_write()

rawDescription: Python, Paramiko: How to do a "ssh -n user@host cmd" using paramiko?


code:
def test_func(x):
    """This function will try to calculate:

    .. math::
        \sum_{i=1}^{\\infty} x_{i}

    good luck!
    """
    pass

rawDescription: Using '\displaymath' directives in docstrings formulas


code:
def save_form(self, request, form, change):
    instance = super(MyModelAdmin, self).save_form(request, form, change)
    if instance.published and not user.has_perm('mark_published'):
        instance.published = False #You could be displaying a message here.
    return instance

rawDescription: Extending django forms

description: Extending django forms


code:
import hashlib

with open('example.csv') as fin, open('output.csv', 'w') as fout:
    for ex in fin:
        items = ex.split(',')
        items[0] = hashlib.md5(items[0].encode()).hexdigest()
        fout.write(','.join(items))

rawDescription: Appending back to the file/dictionary after hashing (and anonymizing names)


code:
df = pd.read_csv("myfile.csv")
df.to_html('your_file.html')

rawDescription: use python pandas convert csv to html

description: Use python pandas convert csv to html


code:
import clips
def clips_raw_input(prompt):
        return clips.String(raw_input(prompt))

clips.RegisterPythonFunction(clips_raw_input, "input")
r1 = clips.BuildRule(
       "what-are-qualities",
       """(quality ?name)
       (not (has ?name ?))""",
       """(bind ?response (python-call input (str-cat "Are you " ?name "? ")))
       (assert (has ?name ?response))""")
clips.Reset()
clips.Assert("(quality observative) ")
clips.Assert("(quality communicative) ")
clips.Assert("(quality emotionally-stable) ")
clips.Assert("(has human true)")
clips.Run()
clips.PrintFacts()

rawDescription: Displaying the value of a variable in PyClips


code:
import multiprocessing
import re

def mp_worker(filename):
    with open(filename) as f:
        text = f.read()
    m = re.findall("x+", text)
    count = len(max(m, key=len))
    return filename, count

def mp_handler():
    p = multiprocessing.Pool(32)
    with open('infilenamess.txt') as f:
        filenames = [line for line in (l.strip() for l in f) if line]
    with open('results.txt', 'w') as f:
        for result in p.imap(mp_worker, filenames):
            # (filename, count) tuples from worker
            f.write('%s: %d\n' % result)

if __name__=='__main__':
    mp_handler()

rawDescription: Python: Writing to a single file with queue while using multiprocessing Pool


code:
from BeautifullSoup import BeautifullSoup

#...

soup = BeautifulSoup(bufTwo)
imgTags = soup.findAll('img')
img = [tag['src'] for tag in imgTags]

rawDescription: Python to parser a web page's images URLs


code: all(not d for d in l)

rawDescription: Python: Check if all dictionaries in list are empty


code:
import base64

source = '''\
print('Hello World!')
print('Not sure why you'd ever do this though..')
'''
code = base64.b64encode(source)

rawDescription: Compile and eval of base64 string

description: Compile and eval of base64 string


code:
def foo(someString, listA, listB):
    for a,b in zip(listA, listB):
        if a in someString:
            return b

someString = "something about cheese"
listA = ['cheese', 'spam', 'sausage', 'eggs']
listB = ['cz', 'sp', 'sg', 'eg']
print(foo(someString, listA, listB))  # => cz

rawDescription: Python partial string mapping to value from list


code:
import pandas as pd
pd.Index(datetime(1990, 1, 1) + sec * pd.offsets.Second())

rawDescription: Pandas datetime index from seconds series


code: sub_info = {i.tag: i.text for i in tag}

rawDescription: python dynamic dictionary

description: Python dynamic dictionary


rawDescription: Is there a pythonic way for loop and use previous item


rawDescription: how to get the output info simply?

description: Get the output info simply


code: csv.writer(file, delimiter=':')

rawDescription: Write volatile strings to file in Python


code:
def copy_function(row):
    if row['col2']==1:
        return row['col2']
    else:
        return row['col1']
df['col3'] = df.apply(copy_function, axis=1)

rawDescription: Copy over values to new column with formula


code: cp = ax.imshow(H.transpose()[::-1], interpolation='nearest', extent=extent, cmap=cm.jet)

rawDescription: imshow and histogram2d: can't get them to work

description: Imshow and histogram2d: can't get them to work


code:
seq = [[11, 12, 13, 14], [15, 16, 17]]
nseq = [["Point {}".format(i) for i in range(1, len(sub)+1)] for sub in seq]
nseq

rawDescription: Creating matching list counter

description: Creating matching list counter


rawDescription: Is there an easier way to change the index values of a pandas dataframe?


code:
if ball.score2 == 50 or ball.score == 50:
    EndGame()

rawDescription: if statement in python not working with or and integers

description: If statement in python not working with or and integers


code:
import matplotlib.pyplot as plt
plt.gray()
plt.imshow(lena)
plt.show()

rawDescription: Opening images in Python through cmd window


rawDescription: How to run PyQt4 with flash web page?

description: Run PyQt4 with flash web page


rawDescription: Set the color of y axis coefficient in matplotlib


code:
for line in foo:
    elements = line.split()
    for elem in elements:
        if elem in d["keyword"]:
            keywords +=1

rawDescription: Search a textfile using elements from a dictionary or other data structure in python


code:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.properties import ListProperty, StringProperty

import re

from kivy.lang import Builder

Builder.load_string('''
<MainView>:
    ComboEdit:
        size_hint: .5, .3
        pos_hint: {'center':(.5, .5)}
        # `args` is the keyword for arguments passed to `on_text` in kv language
        on_text: root.on_text(self, args[1])
''')

class ComboEdit(TextInput):
    '''
    This class defines a Editable Combo-Box in the traditional sense
    that shows it's options
    '''

    options = ListProperty(('', ))
    '''
    :data:`options` defines the list of options that will be displayed when
    touch is released from this widget.
    '''

    def __init__(self, **kw):
        ddn = self.drop_down = DropDown()
        ddn.bind(on_select=self.on_select)
        super(ComboEdit, self).__init__(**kw)

    def on_options(self, instance, value):
        ddn = self.drop_down
        # clear old options
        ddn.clear_widgets()
        for option in value:
            # create a button for each option
            but = Button(text=option,
                        size_hint_y=None,
                        height='36sp',
                        # and make sure the press of the button calls select
                        # will results in calling `self.on_select`
                        on_release=lambda btn: ddn.select(btn.text))
            ddn.add_widget(but)

    def on_select(self, instance, value):
        # on selection of Drop down Item... do what you want here
        # update text of selection to the edit box
        self.text = value

class MainView(FloatLayout):

    rtsstr = StringProperty("".join(("Substrate1,,,Substrate1,,,Substrate1,,,",
                            "Substrate1,,,Substrate1,,,Substrate_coating",
                            ",,,silicon,,,silicon_Substrate,,,substrate_",
                            "silicon,,,")))

    def on_text(self, instance, value):
        if value == '':
            instance.options=[]
        else:
            match = re.findall("(?<=,{3})(?:(?!,{3}).)*?%s.*?(?=,{3})" % value,\
                                self.rtsstr, re.IGNORECASE)
            #using a set to remove duplicates, if any.
            instance.options = list(set(match))
        instance.drop_down.open(instance)

class TestApp(App):

    def build(self):
        return MainView()

if __name__ == '__main__':
    TestApp().run()

rawDescription: Kivy Clear_widget strange behaviour (reproducible code attached)


code:
def replaceFirstTwo(x,y,lst):
    if lst == []:
        return []
    else:
        if x is not None:
            if lst[0] == abs(x):
                if x > -1:
                    x = -x
                else:
                    x = None
                return [y] + replaceFirstTwo(x,y,lst[1:])
            else:
                return [lst[0]]+ replaceFirstTwo(x,y,lst[1:])
        else:
            return [lst[0]]+ replaceFirstTwo(x,y,lst[1:])

rawDescription: How to add a counter to a recursive function? [Python]

description: Add a counter to a recursive function? [Python]


code:
def foo(x):
    assert x in huge_global_computation_to_check_all_possible_x_values()
    # ok, go ahead and use x...

rawDescription: What is the use of Python's basic optimizations mode? (python -O)


code: cmds.ls(sl=1, fl=1)

rawDescription: Get vertex as single array

description: Get vertex as single array


code:
def database():
    with open ('Analysis.txt', 'w') as f: f.write (' \nDatabase Analysis: \n\n')

    import os, sqlite3
    from os import path
    import sqlite3 as lite

    PATH = "./"
    exist = False

    for path, dirs, files, in os.walk(PATH):
        for filename in files:
            fullpath =os.path.join(path, filename)
            if filename == 'database.db':
                conn = sqlite3.connect(fullpath)
                output = open("Analysis.txt", "a")

                cursor = conn.execute("select filename from history desc limit 100;")
                for row in cursor:
                    output.write(str(row) + "\n")
                conn.close()
                exist = True
                break
            else:
                continue
    if not exist:
            with open('Analysis.txt', 'a') as f1:
                f1.write("database.db does not exist.")
                f1.close()
database()

rawDescription: Unable to get a single file not found output from script in Python


code:
my_text="""This is a testing document for testing purposes only.[^0] This is a testing document for testing purposes only. This is a testing document for testing purposes only.[^121][^5] This is a testing document for testing purposes only.

[^0]: Footnote contents.

[^0]: Footnote contents.

[^0]: Footnote contents."""

num_notes = len(re.findall("\[\^\d+\]",my_text))
i = -1
def do_sub(m):
    global i
    i+=1
    return "[^%d]"%(i if i < num_notes//2 else i-num_notes//2)

re.sub("\[\^\d+\]",do_sub,my_text)

rawDescription: Python substitute with numbering inside patterns


code:
load_data = csv.reader(open( "multientry.csv", "r" ))
header = next(load_data)
header = filter(bool,header)
categories = header
categories.pop(0)
categories = set(categories)
dofd={}
for row in load_data:
    row = filter(bool,tuple(value for  value in row))
    dofd[row[0]]={}
    for item in categories:
        val = [float(k) for k in [row[i+1] for i in [i for i, x in enumerate(header) if x == item]]]
        dofd[row[0]][item] = sum(val)/float(len(val))

rawDescription: Read and aggregate data from CSV file

description: Read and aggregate data from CSV file


code: grid[y][x1:x2+1] = row

rawDescription: Python slice assignment changes nearby element in list


code:
import requests
import hashlib
page = requests.get('http://www.stackoverflow.com')
hashlib.sha256(page.text.encode('utf-8')).hexdigest()

rawDescription: Create a checksum for a fetched webpage

description: Create a checksum for a fetched webpage


code:
from datetime import datetime
datetime.strptime("2010-11-13 10:33:54.227806", "%Y-%m-%d %H:%M:%S.%f")

rawDescription: how to convert a datetime string back to datetime object?

description: Convert a datetime string back to datetime object


code:
from sympy.solvers import solve
from sympy import Symbol

r = Symbol('r')
for C in np.linspace(0,50,100):
    result = solve(((r/100)*(0.6108*np.exp((17.27*C)/(C+273.3))))-0.5, r )
    print("For C = {} RH = {}".format(C, result[0]))

rawDescription: Curve Fitting to Exponential

description: Curve Fitting to Exponential


rawDescription: Ordering linestring direction algorithm

description: Ordering linestring direction algorithm


code:
df["sold_at_same_place"] = df.groupby(["day", "place"])["sold"].transform(sum)
df

rawDescription: Column aggregates filtered by row values with pandas DataFrame


code:
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt

m = Basemap(projection='cyl')

p0_ll =  -73.98, 40.78
p1_ll = 0.08, 51.53

m.drawgreatcircle(p0_ll[0], p0_ll[1], p1_ll[0], p1_ll[1],
                  linewidth=2, color='b')
m.drawcoastlines()
m.fillcontinents()

plt.show()

rawDescription: Plotting curved line in Python Basemap

description: Plotting curved line in Python Basemap


code: " ".join(my_list)

rawDescription: convert list into string with spaces in python

description: Convert list into string with spaces in python


code:
import numpy as np
import pylab
x = np.linspace(0, 20, 1000)
y1 = np.sin(x)
y2 = np.cos(x)

pylab.plot(x, y1, '-b', label='sine')
pylab.plot(x, y2, '-r', label='cosine')
pylab.legend(loc='upper left')
pylab.ylim(-1.5, 2.0)
pylab.show()

rawDescription: Adding a legend to PyPlot in Matplotlib in the most simple manner possible


code:
def sim_yahtzee(nrolls,n,sides=6):
    first_roll = []
    for i in range (n):
        rn = random.randint(1,6)
        first_roll.append(rn)
        number_one = first_roll.count(1)
        number_two = first_roll.count(2)
        number_three = first_roll.count(3)
        number_four = first_roll.count(4)
        number_five = first_roll.count(5)
        number_six = first_roll.count(6)
        for i in range (nrolls):
            if number_one > number_two and number_three and number_four and number_five and number_six:
                keep = [1] * number_one
            elif number_two > number_one and number_three and number_four and number_five and number_six:
                keep = [2] * number_two
            elif number_three > number_one and number_two and number_four and number_five and number_six:
                keep = [3] * number_three
            elif number_four > number_one and number_two and number_three and number_five and number_six:
                keep = [4] * number_four
            elif number_five > number_one and number_two and number_three and number_four and number_six:
                keep = [5] * number_five
            elif number_six >= number_one and number_two and number_three and number_four and number_five:
                keep = [6] * number_six
            elif number_five == number_four or number_three or number_two or number_one:
                keep = [5] * number_five
            elif number_four == number_three or number_two or number_one:
                keep = [4] * number_four
            elif number_three == number_two or number_one:
                keep = [3] * number_three
            elif number_two == number_one:
                keep = [2] * number_two
            reroll = []
            for i in range (len(first_roll)-len(keep)):
                rn = random.randint(1,6)
                reroll.append(rn)
            first_roll = (keep + reroll)
    print (first_roll)

sim_yahtzee(1,5)

rawDescription: Where can I call my function so I can test it?


code: df2 = pd.concat([df2,df],axis=1)

rawDescription: Python - Picking DataFrame columns from all csv files in directory and merging into one


code:
Result = namedtuple('Result', ['x', 'y'])
result = Result(5, 6)

rawDescription: how do I add fields to a namedtuple?

description: Add fields to a namedtuple


code:
import urllib
query = 'project = ITTICKETS AND "Build Info" ~ CI_-STD.INT-2'
jql = '/rest/api/2/search?jql=%s' % urllib.quote(query)

rawDescription: how to write queries using python and REST to retrieve data from JIRA

description: Write queries using python and REST to retrieve data from JIRA


code:
import sys
sys.path.append(path/of/directory)
import customPyScript

rawDescription: Make my .py file importable from any directory


code:
pd.__version__
np.__version__
import sys
sys.version
df = DataFrame(np.arange(9).reshape(9,-1),index=pd.MultiIndex.from_product([list('abc'),date_range('20140721',periods=3)],names=['symbol','date']),columns=['value'])
df
df.to_hdf('test.h5','df',mode='w',format='table')
pd.read_hdf('test.h5','df',where='date=20140722')
pd.read_hdf('test.h5','df',where='symbol="a"')

rawDescription: Python (pandas): store a data frame in hdf5 with a multi index


code:
from django.conf.settings import BASE_DIR # won't work

from django.conf import settings # correct way
base_dir = settings.BASE_DIR

rawDescription: how can you get your BASE_DIR for any script in any location in Django project?

description: Get your BASE_DIR for any script in any location in Django project


code: input = int(raw_input("Enter the inputs : ") or "42")

rawDescription: default values on empty user input in python

description: Default values on empty user input in python


code:
m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcolm Reynolds")
m.start('last_name')

rawDescription: Determine Python regex named group numbers?


code:
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')

rawDescription: How to test Python readline completion?

description: Test Python readline completion


code:
import mimetypes
mimetypes.init()
mimetypes.knownfiles
mimetypes.suffix_map['.tgz']
mimetypes.encodings_map['.gz']
mimetypes.types_map['.tgz']

rawDescription: Filetype information

description: Filetype information


code:
import re #Regex may be the easiest way to split that line

with open(infile) as in_f, open(outfile,'w') as out_f:
    f = (i for i in in_f if i.rstrip()) #iterate over non empty lines
    for line in f:
        _, k = line.split('\t', 1)
        x = re.findall(r'^1..100\t([+-])chr(\d+):(\d+)\.\.(\d+).+$',k)
        if not x:
            continue
        out_f.write(' '.join(x[0]) + '\n')

rawDescription: inconsistent indentation with Python after split

description: Inconsistent indentation with Python after split


code:
matches = []
biglist1_indexed = {}

for item in biglist1:
	biglist1_indexed[(item["transaction"], item["date"])] = item

for item in biglist2:
	if (item["transaction"], item["date"]) in biglist1_indexed:
		matches.append(item)

rawDescription: Comparing massive lists of dictionaries in python


code:
separator = ' '
parameters = raw_input("parameters:").split(separator)

rawDescription: python multiple user input in single line

description: Python multiple user input in single line


code:
import pandas
from collections import Counter
a = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'd', 'e', 'e', 'e', 'e', 'e']
letter_counts = Counter(a)
df = pandas.DataFrame.from_dict(letter_counts, orient='index')
df.plot(kind='bar')

rawDescription: Python: How to make a histogram from a list of strings in python?


code: plt.imshow(image, extent=(-30,30,-30,30)) # (left, right, bottom, top)

rawDescription: Set X/Y axis in imshow in Python

description: Set X/Y axis in imshow in Python


code:
import decimal

a = decimal.Decimal('54.12')
b = decimal.Decimal('54.00')

for n in (a, b):
    print("You have just bought an item that cost ${0:.{1}f}."
          .format(n, 0 if n == n.to_integral() else 2))

rawDescription: String formatting in Python: Showing a price without decimal points


code:
import requests
def githubimport(user, repo, module):
   d = {}
   url = 'https://raw.githubusercontent.com/{}/{}/master/{}.py'.format(user, repo, module)
   r = requests.get(url).text
   exec(r, d)
   return d

qoperator = githubimport('biryani', 'Quacpy', 'qoperator')

rawDescription: Importing python libraries from Github

description: Importing python libraries from Github


code:
delta_x = delta_y = 3
while True:
      objects = canv.find_overlapping(canv.coords(ball)[0], canv.coords(ball)[1], canv.coords(ball)[2], canv.coords(ball)[3])
      for obj in objects:
        if obj == 1:
            delta_y = -delta_y
        if obj == 2:
            delta_x = -delta_x
        if obj == 3:
            delta_x = -delta_x
        if obj == 4:
            delta_y = -delta_y

      new_x, new_y = delta_x, delta_y
      canv.move(ball, new_x, new_y)
      canv.update()
      time.sleep(0.025)

      root.bind('<Right>', move_right)
      root.bind('<Left>', move_left)

rawDescription: Move a ball inside Tkinter Canvas Widget (simple Arkanoid game)


code:
from datetime import date

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

rawDescription: Age from birthdate in python

description: Age from birthdate in python


code:
project_list = [1, 2, 3, 8]
p.prodeucts.add(*project_list)

rawDescription: Calling Model.add() with a variable as parameter


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

x = np.linspace(0, 6*np.pi, 200)
y = np.sin(x)

plt.stem(x, y, markerfmt=" ")

plt.show()

rawDescription: Python matplotlib.stem plot with no markers


code:
from django.core.cache import cache

def cached_user_passes_test(test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME):
    if not login_url:
        from django.conf import settings
        login_url = settings.LOGIN_URL

    def decorator(view_func):
        def _wrapped_view(request, *args, **kwargs):
            key = str(test_func) + str(request.user)
            cached_test_result = cache.get(key)
            if cached_test_result != None:
                test_result = cached_test_result
            else:
                test_result = test_func(request.user)
                cache.set(key, test_result, 60)

            if test_result:
                return view_func(request, *args, **kwargs)
            path = urlquote(request.get_full_path())
            tup = login_url, redirect_field_name, path
            return HttpResponseRedirect('%s?%s=%s' % tup)
        return wraps(view_func)(_wrapped_view)
    return auto_adapt_to_methods(decorator)

rawDescription: Caching non-view returns

description: Caching non-view returns


code:
import xml.etree.ElementTree
tree = xml.etree.ElementTree.parse("foo.xml")
myArray = [int(x.text) for x in tree.getroot().findall("human/weight")]

rawDescription: How to read and parse XML without schema in Python?

description: Read and parse XML without schema in Python


code:
# Remember -> OpenCV stores things in BGR order
lowerBound = cv.Scalar(120, 80, 100);
upperBound = cv.Scalar(140, 85, 110);

# this gives you the mask for those in the ranges you specified,
# but you want the inverse, so we'll add bitwise_not...
cv.InRange(cv_im, lowerBound, upperBound, cv_rgb_thresh);
cv.Not(cv_rgb_thresh, cv_rgb_thresh);

rawDescription: Fast RGB Thresholding in Python (possibly some smart OpenCV code?)


code:
delta = meta_dict['timestamp_start']
with open('cache', 'r') as f:
    while True:
        line = f.readline()
        if not line:
            break
        line = json.loads(line)
        if delta - parser.parse(line['timestamp_start']) <= cache_timeout:
            fresh_cache.append(json_line)

rawDescription: How to optimize reading in and working over a large file?

description: Optimize reading in and working over a large file


code:
from bulbs.neo4jserver import Graph, FulltextIndex
from bulbs.element import Vertex
index_name="fulltext_vertex"
g = Graph()
g.vertices.fulltext = g.factory.get_index(Vertex, FulltextIndex, index_name)
james = g.vertices.create(name="James Thornton", city="Dallas")
g.vertices.fulltext.put(james.eid, name=james.name)
vertices = g.vertices.fulltext.query(name="James")
vertices.next()

rawDescription: How to make a selective fulltext index for neo4j in bulbs framework for Python?

description: Make a selective fulltext index for neo4j in bulbs framework for Python


code:
import ConfigParser
from unittest import TestCase

from mock import create_autospec, patch, Mock

class FooBar(object):
    def method(self, filename):
        config=ConfigParser.ConfigParser()
        config.read(filename)

class TestFooBar(TestCase):

    def setUp(self):
         self.myfoobar = FooBar()

    @patch('ConfigParser.ConfigParser')
    def test_method(self, config_parser_class_mock):
        config_parser_mock = config_parser_class_mock.return_value

        self.myfoobar.method("configuration.ini")

        config_parser_class_mock.assert_called_once_with()
        config_parser_mock.read.assert_called_once_with("configuration.ini")

    def test_method_better(self):
        config_parser_mock = create_autospec(ConfigParser.ConfigParser, instance=True)
        config_parser_class_mock = Mock(return_value=config_parser_mock)

        with patch('ConfigParser.ConfigParser', config_parser_class_mock):
            self.myfoobar.method("configuration.ini")

        config_parser_class_mock.assert_called_once_with()
        config_parser_mock.read.assert_called_once_with("configuration.ini")

rawDescription: Python internal entity mocking

description: Python internal entity mocking


code:
data = pandas.read_csv('file.csv')
# keep only rows with x equals to 2
data = data[data['x'] == 2]
# convert to numpy array
arr = numpy.asarray(data)

rawDescription: Using numpy load only lines fitting certain criteria


code:
@app.route('/author/<username>')
def show_user(username):
    user = User.query.filter_by(username=username).first_or_404()
    name = user.name
    last_name = user.last_name
    adres = user.adres
    return render_template('show_user.html', user=user, name=name, last_name=last_name, adres=adres)

rawDescription: How to make page content Dynamic with Flask?

description: Make page content Dynamic with Flask


code:
import subprocess
output = subprocess.check_output(("arp", "-a"))
# Parse output here

rawDescription: Is there a way to execute arp -a cmd command in python script?


code:
try:
    fn = argv[1]

except IndexError:
    fn = raw_input("filename > ")

rawDescription: argv vs. raw_input

description: Argv vs. raw_input


rawDescription: Is is possible to clean a verbose python regex before printing it?


code: cur.execute('''insert into test (id, long) values (%s, %s);''', (id, long))

rawDescription: python sql modulo inserting

description: Python sql modulo inserting


code:
import iris

cubes = iris.load('input.nc')       # each variable in the netcdf file is a cube
iris.save(cubes[0],'output.grib2')  # save a specific variable to grib

rawDescription: Converting NetCDF to GRIB2

description: Converting NetCDF to GRIB2


code:
import SocketServer
import concurrent.futures
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
from Queue import Queue

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)

# create a global queue object that both the handle() method and the QThread (see later in the code) can access
queue = Queue()

class MyRequestHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        print('...connected from:', self.client_address)
        data = self.rfile.readline().strip()
        print('Data from client %s' % data)
        queue.put(data)

class ServerWindow(QtGui.QMainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.setGeometry(1500, 100, 500, 500)

        self._control = QtGui.QWidget()
        self.setCentralWidget(self._control)

        l = QtGui.QVBoxLayout(self._control)
        self.t = QtGui.QTextEdit()
        l.addWidget(self.t)

        self.executor = futures.ThreadPoolExecutor(max_workers=1)
        self.startServerThread()

        self.show()

    @QtCore.pyqtSlot(str)
    def receive_data(self, data):
        self.t.moveCursor(QtGui.QTextCursor.End)
        self.t.insertPlainText( data )

    def startServerThread(self):
        self.executor.submit(self.startServer)

        # How to get information from the thread while it is still running?

    def startServer(self):
        print('starting server')
        self.tcpServ = SocketServer.TCPServer(ADDR, MyRequestHandler)
        print('waiting for connection...')
        self.tcpServ.serve_forever()

        # How to get information from the client (custom request handler)
        # back to the GUI in a thread safe manner?

# This class runs in a QThread and listens on the end of a queue and emits a signal to the GUI
class MyReceiver(QtCore.QObject):
    mysignal = QtCore.pyqtSignal(str)

    def __init__(self,queue,*args,**kwargs):
        QtCore.QObject.__init__(self,*args,**kwargs)
        self.queue = queue

    @QtCore.pyqtSlot()
    def run(self):
        while True:
            text = self.queue.get()
            self.mysignal.emit(text)

def launch():
    app = QtGui.QApplication(sys.argv)

    ex = ServerWindow()

    # Create thread that will listen on the other end of the queue, and send the text to the textedit in our application
    thread = QtCore.QThread()
    my_receiver = MyReceiver(queue)
    my_receiver.mysignal.connect(ex.receive_data)
    my_receiver.moveToThread(thread)
    thread.started.connect(my_receiver.run)
    thread.start()

    ret_code = app.exec_()
    ex.tcpServ.shutdown()
    sys.exit(ret_code)

if __name__ == '__main__':
    launch()

rawDescription: How to have two programs communicate with one another

description: Have two programs communicate with one another


code:
load_zipped_png_files = Image(
    source = 'explosion.zip',
    anim_delay = 0,
    allow_stretch = True,
    keep_ratio = False,
    keep_data = True)

rawDescription: speed up loading of animated gif kivy

description: Speed up loading of animated gif kivy


code:
from django.db.models import Q

query = 'fun'
books = Fun.objects.filter(Q(categories__id__in=[1,2,3]),
                     Q(name__icontains=query) | \
                     Q(description__icontains=query) | \
                     Q(keywords__title__icontains=query))

rawDescription: In Django, correctly making a queryset with multiple categories, multiple tags and search?


code:
df = pd.DataFrame(None, columns=['v'+str(i) for i in range(1,201)])
sql = 'SELECT x_id, x_attr FROM elements WHERE x_hash = %s'
cur.execute(sql, (x_hash,))
x1_id, features = cur.fetchone()
df.loc[x1_id] = 0  # Initializes all values for the ID to zero.
df.loc[x1_id, features] = 1  # Sets relevant features to a value of one.

rawDescription: create a feature vector using pandas or python

description: Create a feature vector using pandas or python


code:
headers = {
    'User-Agent': 'My User Agent 1.0',
    'From': 'youremail@domain.com'  # This is another valid field
}

response = requests.get(url, headers=headers)

rawDescription: Sending "User-agent" using Requests library in Python


code:
pipe = [{'$group': {'_id': None, 'total': {'$sum': '$goals'}}}]
db.goals.aggregate(pipeline=pipe)

Out[8]: {u'ok': 1.0, u'result': [{u'_id': None, u'total': 12.0}]}

rawDescription: MongoDB aggregate/group/sum query translated to pymongo query


code:
import sys
if sys.version_info[0] < 3:
    import Tkinter as tk     ## Python 2.x
else:
    import tkinter as tk     ## Python 3.x
print("version", tk.TclVersion)

rawDescription: Add Tkinter in the project on Python

description: Add Tkinter in the project on Python


code:
b = Button(text="click me", command=self.callback)
# Or if you want to pass parameters
b = Button(text="click me", command=lambda: self.callback("1"))

rawDescription: Passing Argument to function python

description: Passing Argument to function python


code:
def my_doc_skip(app, what, name, obj, skip, options):
    if what != "method":
        return True

    # if obj is decorated with @api
    #     return True
    # return False

def setup(app):
    app.connect('autodoc-process-docstring', my_process_docstring)
    app.connect('autodoc-skip-member', my_doc_skip)

rawDescription: Sphinx Public API documentation

description: Sphinx Public API documentation


code:
{
    content_html: "the html for the videos",
    load_more_widget_html: "      \n\n\n\n    \u003cbutton class=\"yt-uix-button yt-uix-button-size-default yt-uix-button-default load-more-button yt-uix-load-more browse-items-load-more-button\" type=\"button\" onclick=\";return false;\" aria-label=\"Load more\n\" data-uix-load-more-href=\"\/browse_ajax?action_continuation=1\u0026amp;continuation=4qmFsgJAEhhVQ0JKeWNzbWR1dllFTDgzUl9VNEpyaVEaJEVnWjJhV1JsYjNNZ0FEZ0JZQUZxQUhvQk03Z0JBQSUzRCUzRA%253D%253D\" data-uix-load-more-target-id=\"channels-browse-content-grid\"\u003e\u003cspan class=\"yt-uix-button-content\"\u003e  \u003cspan class=\"load-more-loading hid\"\u003e\n      \u003cspan class=\"yt-spinner\"\u003e\n      \u003cspan class=\"yt-spinner-img  yt-sprite\" title=\"Loading icon\"\u003e\u003c\/span\u003e\n\nLoading...\n  \u003c\/span\u003e\n\n  \u003c\/span\u003e\n  \u003cspan class=\"load-more-text\"\u003e\n    Load more\n\n  \u003c\/span\u003e\n\u003c\/span\u003e\u003c\/button\u003e\n\n\n"
}

rawDescription: Python3 Parse more than 30 videos at a time from youtube


code:
import sys
import logging

def create_logger():
    # create logger for "Sample App"
    logger = logging.getLogger('automated_testing')
    logger.setLevel(logging.DEBUG)

    # create file handler which logs even debug messages
    fh = logging.FileHandler('results.log', mode='w')
    fh.setLevel(logging.DEBUG)

    # create console handler with a higher log level
    ch = logging.StreamHandler(stream=sys.stdout)
    ch.setLevel(logging.INFO)

    # create formatter and add it to the handlers
    formatter = logging.Formatter('[%(asctime)s] %(levelname)8s --- %(message)s ' +
                                  '(%(filename)s:%(lineno)s)',datefmt='%Y-%m-%d %H:%M:%S')
    fh.setFormatter(formatter)
    ch.setFormatter(formatter)

    # add the handlers to the logger
    logger.addHandler(ch)
    logger.addHandler(fh)

    return logger

logger = create_logger()

logger.log(logging.NOTSET,   "NOTSET   Message - 0")
logger.log(logging.DEBUG,    "DEBUG    Message - 10")
logger.log(logging.INFO,     "INFO     Message - 20")
logger.log(logging.WARNING,  "WARNING  Message - 30")
logger.log(logging.CRITICAL, "CRITICAL Message - 40")

rawDescription: Is there a way to change the filemode for a logger object that is not configured using basicConfig?


code:
A = np.loadtxt('stack.txt',skiprows=2,delimiter=',',dtype=str)
keep_headers=np.loadtxt('keepheader.csv',delimiter=',',dtype=str)

headers = A[0,:]
cols_to_keep = np.in1d( headers, keep_headers )

B = np.float_(A[1:,cols_to_keep])
np.savetxt('cmap.csv',B,fmt='%.3f',delimiter=",")

rawDescription: Python 3 code to read CSV file, manipulate then create new file....works, but looking for improvements


code:
def read_poetry_from_desc(poetry_forms_file):
    poem_form = {}

    with open(poetry_forms_file, 'r') as f:
        cur_header = None # latest header found in file

        for line in f:
            line = line.strip()

            # Skip empty lines
            if len(line) == 0:
                continue

            if line[0].isalpha():
                # Found new header, add empty entry to dict
                cur_header = line
                poem_form[cur_header] = ([], [])

            else:
                # Found data, record it
                pair = line.split() # split on space

                data = poem_form[cur_header]
                data[0].append(int(pair[0]))
                data[1].append(pair[1])

    return poem_form

rawDescription: Create a dict of tuples from file

description: Create a dict of tuples from file


code: Pos_List, Room_List, Type_List, Spec_List, Sub_List, Rtr_List, IPa_List, MAC_List = [], [], [], [], [], [], [], []

rawDescription: Is there a shorter way to assign these variables?


rawDescription: Get a set of 2d list in python

description: Get a set of 2d list in python


code:
import pickle
class Example():
    def __init__(self, x):
            self.x = x
a = Example('foo')
astr = pickle.dumps(a) # (i__main__\nExample\np0\n(dp1\nS'x'\np2\nS'foo'\np3\nsb.
b = pickle.loads(astr)
b
b.x

rawDescription: How to make type cast for python custom class

description: Make type cast for python custom class


code:
import wx

########################################################################
class RandomPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent, color):
        """Constructor"""
        wx.Panel.__init__(self, parent)
        self.SetBackgroundColour(color)

########################################################################
class MainPanel(wx.Panel):
    """"""

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent)

        topSplitter = wx.SplitterWindow(self)
        hSplitter = wx.SplitterWindow(topSplitter)

        panelOne = RandomPanel(hSplitter, "blue")
        panelTwo = RandomPanel(hSplitter, "red")
        hSplitter.SplitVertically(panelOne, panelTwo)
        hSplitter.SetSashGravity(0.5)

        panelThree = RandomPanel(topSplitter, "green")
        topSplitter.SplitHorizontally(hSplitter, panelThree)
        topSplitter.SetSashGravity(0.5)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(topSplitter, 1, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class MainFrame(wx.Frame):
    """"""

    #----------------------------------------------------------------------
    def __init__(self):
        """Constructor"""
        wx.Frame.__init__(self, None, title="Nested Splitters",
                          size=(800,600))
        panel = MainPanel(self)
        self.Show()

#----------------------------------------------------------------------
if __name__ == "__main__":
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: wxpython: Multiple panels

description: Wxpython: Multiple panels


code:
#!/usr/bin/python

import gtk

class app(gtk.Window):

  def __init__(self):
    super(app, self).__init__()

    self.set_position(gtk.WIN_POS_CENTER)
    self.set_title("Window Position Test")
    self.set_decorated(True)
    self.set_has_frame(False)
    self.set_resizable(False)
    self.set_default_size(320, 50)
    self.connect("destroy", gtk.main_quit)
    vbox = gtk.VBox(spacing=4)
    hbox = gtk.HBox(spacing=4)

    self.pos_label = gtk.Label()
    vbox.add(self.pos_label)

    self.add(vbox)

    self.update_pos()
    self.show_all()

    self.connect("configure-event", self.update_pos)

  def update_pos(self, *args):
    ''' Get window position, display + log '''
    pos = str( self.get_position() )
    print( pos )
    self.pos_label.set_label( pos )

app()
gtk.main()

rawDescription: PyGtk - Call function when window position changes?


code:
def grepVar(filepath, var):
    lst = []
    inquote = False
    with open(filepath, "r") as fil:
        for num, line in enumerate(fil, 1):
            if inquote:
                lst.append(line)
                if line.count('"') > 0:
                    inquote = False
            elif var in line:
                if line.count('"') == 2:
                    lst.append(line)
                else:
                    lst.append(line)
                    inquote = True
    return lst

rawDescription: Function to get content of a bash variable


code:
import os
from django.test import TestCase
from django.conf import settings
import xml.etree.ElementTree as ET

# Configure your XML_FILE_DIR inside your settings, this can be the
# same dir as the FIXTURE_DIR that Django uses for testing.
XML_FILE_DIR = getattr(settings, 'XML_FILE_DIR')

class MyExampleTestCase(TestCase):

    def setUp(self):
        """
        Load the xml files and pass them to the parser.
        """
        test_file = os.path.join(XML_FILE_DIR, 'my-test.xml')
        if os.path.isfile(test_file):
            # Through this now you can reffer to the parser through
            # self.parser.
            self.parser = ET.parse(test_file)
            # And of course assign the root as well.
            self.root = self.parser.getroot()

rawDescription: How to properly mock big XML in unit test in Django and Python?

description: Properly mock big XML in unit test in Django and Python


code:
table='''乘客姓名,性别,出生日期
HuangTianhui,男,1948/05/28
姜翠云,女,1952/03/27
李红晶,女,1994/12/09
LuiChing,女,1969/08/02
宋飞飞,男,1982/03/01
唐旭东,男,1983/08/03
YangJiabao,女,1988/08/25
提江·阿布拉,男,1979/07/10
安文兰,女,1949/10/20
胡偲婠(婴儿),女,2011/02/25
(有待确定姓名),男,1985/07/20
'''
table = table.encode('gb18030')
data = [[cell  for cell in row.split(b",")]
        for row in table.split(b"\n")  if row]
len0 = max([len(x[0]) for x in data])
len1 = max([len(x[1]) for x in data])
len2 = max([len(x[2]) for x in data])

for cell in data:
    print("_" * (len0+len1+len2+4))
    line = (
        b"|" + cell[0].rjust(len0) +
        b"|" + cell[1].rjust(len1) +
        b"|" + cell[2].rjust(len2) + b"|"
    )
    print(line.decode('gb18030'))

rawDescription: how to control output format when chinese characters and ascii mixed?

description: Control output format when chinese characters and ascii mixed


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

browser = webdriver.Firefox() # Get local session of firefox

browser.implicitly_wait(10) #wait 10 seconds when doing a find_element before carrying on

browser.get("http://myServer/WebAccess/login.html") # Load App page
elem = browser.find_element_by_name("LoginID") # Find the Login box
elem.send_keys("Administrator")
elem = browser.find_element_by_name("Password") # Find the Password box
elem.send_keys("Administrator" + Keys.RETURN)
#try:
elem = browser.find_element_by_link_text("Home")
elem.click()

rawDescription: How to use find_element_by_link_text() properly to not raise NoSuchElementException?

description: Use find_element_by_link_text() properly to not raise NoSuchElementException


code:
def transform(line):
    if 'quoted_status' in line:
        return (
            # Is `and` what you really want here?
            line, line["text"].lower() and line["quoted_status"]["text"].lower()
        )
    else:
        return line, line["text"].lower()

actual_tweets.map(transform)

rawDescription: Apply function to spark RDD

description: Apply function to spark RDD


code: [[np.round(float(i), 2) for i in nested] for nested in outerlist]

rawDescription: Rounding numbers in a list of lists

description: Rounding numbers in a list of lists


code:
def f(x,y,opt_a=None, opt_b=None):
    if opt_a is None: opt_a = rcParams['group1.opt_a']

rawDescription: How to design a program with many configuration options?

description: Design a program with many configuration options


code:
url(r'^mitarbeiter/list/$', generic.ListView.as_view(
    queryset=Mitarbeiter.objects.order_by('name'),
    paginate_by=25),
    name='mitarbeiter_liste'),
url(r'^mitarbeiter/form/$',
    generic.CreateView.as_view(
        model=Mitarbeiter,
        fields='__all__',
        success_url=reverse_lazy('auftragsverwaltung:mitarbeiter_liste'),
        template_name='generic_form_template.html',
    ),
    name='mitarbeiter_form'),
url(r'^mitarbeiter/update/(?P<pk>[\d]+)/$',
    generic.UpdateView.as_view(
        model=Mitarbeiter,
        fields='__all__',
        success_url=reverse_lazy('auftragsverwaltung:mitarbeiter_liste'),
        template_name='generic_update_view.html',
    ),
    name='mitarbeiter_update'),
url(r'^mitarbeiter/delelte/(?P<pk>[\d]+)/$',
    generic.DeleteView.as_view(
        model=Mitarbeiter,
        success_url=reverse_lazy('auftragsverwaltung:mitarbeiter_liste'),
        template_name='generic_confirm_delete.html',
    ),
    name='mitarbeiter_delete'
    )

rawDescription: DRY approach for Django

description: DRY approach for Django


code:
import tornado.ioloop
import tornado.web

class PDFHandler(tornado.web.RequestHandler):
    def get(self):
        filename = 'current_page.pdf'

        self.set_header('Content-Disposition', 'attachment; filename=current_page.pdf')
        self.set_header('Content-Type', 'application/force-download')

        with open(filename, 'r') as handle:
            data = handle.read()
            self.set_header('Content-Length', len(data))
            self.write(data)

if __name__ == "__main__":
    application = tornado.web.Application([
        (r'/', PDFHandler),
    ])

    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

rawDescription: What is the Python equivalent to Django File object?


code:
testList = [(0.0, 0.25), (0.25, 0.25), (0.5, 0.5), (1.0, 0.25), (1.25, 0.75), (2.0, 1.0)]
from operator import itemgetter
testList.sort(key=itemgetter(0)) # Making sure it is sorted. If list is pre-sorted, skip this step.
from itertools import groupby
final_list = [list(lst) for _, lst in groupby(testList, lambda x: int(x[0]))]
from pprint import pprint
pprint(final_list)

rawDescription: How to split a Python sequence of tuples according to a predicate?

description: Split a Python sequence of tuples according to a predicate


rawDescription: How can I remove these parenthesis in the output?

description: Remove these parenthesis in the output


rawDescription: Python - how to normalize time-series data


code:
class Skill(models.Model):
    name = models.CharField(max_length=255)
    value = IntegerRangeField(min_value=1, max_value=10)

class Character(models.Model):
    name = models.CharField(max_length=255)
    skill = models.ManyToManyField(Skill)

rawDescription: What's the accepted best practice when specifying a set of related fields in Django?


code:
class ListCreateView(ListView, BaseCreateView):
    def get_context_data(self, **kwargs):
        self.object = None
        self.object_list = self.get_queryset()

        form_class = self.get_form_class()
        form = self.get_form(form_class)

        kwargs.update({'object_list': self.object_list, 'form': form})

        context = super(ListCreateView, self).get_context_data(**kwargs)
        return context

rawDescription: Can I combine Create and List class based generic views using mixins?

description: Combine Create and List class based generic views using mixins


code:
import csv

name = input('Name: ')
score = int(input('Score: '))

try:
    with open('class1.csv', 'r', newline='') as inf:
        class1 = {row['name']: [row['score0'], row['score1'], row['score2']]
                    for row in csv.DictReader(inf)}
except FileNotFoundError:
    class1 = {}

print('Updating' if name in class1 else 'Creating', name+"'s", 'profile')
del class1.setdefault(name, [0, 0, 0])[0]
class1[name].append(score)
print('Score added')

with open('class1.csv', 'w', newline='') as outf:
    FIELD_NAMES = ['name', 'score0', 'score1', 'score2']
    writer = csv.DictWriter(outf, FIELD_NAMES)
    writer.writeheader()
    writer.writerows(dict(zip(FIELD_NAMES, [name] + scores))
                        for name, scores in class1.items())
print('File written')

rawDescription: Reading from a dictionary in a csv file

description: Reading from a dictionary in a csv file


code:
import re

_pat_student_parser = re.compile(r'((?P<id>\d{4})(?P<name>\w{4}))')

def nested_dict_from_text(text):
    m = re.search(_pat_student_parser, text)
    if not m:
        raise ValueError
    d = m.groupdict()
    return { "student": d }

result = nested_dict_from_text('1234STUD')
print(result)

rawDescription: Python Regex - Dictionary inside Dictionary


code:
class MyDictReader(DictReader):

    @property
    def fieldnames(self):
        return [field.strip().lower() for field in super(MyDictReader, self).fieldnames]

rawDescription: Reading csv header white space and case insensitive


code:
alpha = 0.6
to_rgba = matplotlib.colors.ColorConverter().to_rgba

for i, col in enumerate(plt.rcParams['axes.color_cycle']):
    plt.rcParams['axes.color_cycle'][i] = to_rgba(col, alpha)

rawDescription: How to set the alpha value for matplotlib plots globally

description: Set the alpha value for matplotlib plots globally


rawDescription: How to fix sympy LaTeX denominator output?

description: Fix sympy LaTeX denominator output


code: (datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() - time.time()

rawDescription: python time vs datetime

description: Python time vs datetime


code:
if len(sys.argv) > 1:
    ssid_end = sys.argv[1].lower()
else:
    ssid_end = raw_input("==> ").lower()

rawDescription: How to add/wait for user input?

description: Add/wait for user input


code:
master_list = [[a,a,b,b,b,c,c,c], [d,d,d,a,a,a,c,c,c], [c,c,c,a,a,f,f,f]]
counters = []
for list_ in master_list:
    counters.append(Counter(list_))

rawDescription: Creating a separate Counter() object and Pandas DataFrame for each list within a list of lists


code:
import urllib2
import urlparse

url = 'http://www.tip.it/runescape/gec/price_graph.php?avg=1&start=1327715574&mainitem=10350&item=10350'
response = urllib2.urlopen(url)
content = response.read()
params = urlparse.parse_qs(content)
print(params['values'])

rawDescription: Reading data from a website

description: Reading data from a website


code:
def get_node(node_id):
    request = urllib2.Request(ROOT_URL + node_id)
    response = json.loads(urllib2.urlopen(request).read())
    temp_obj = {}
    temp_obj['id'] = response['id']
    temp_obj['name'] = response['name']
    temp_obj['children'] = [get_node(child['id']) for child in response['childNode']]
    return temp_obj

hierarchy = get_node(ROOT_NODE)

rawDescription: Recursive function to create hierarchical JSON object?


code:
start = time.clock()
z=open('Number.txt','r+')
data=z.read()
global a
a=gmpy2.mpz(data)
end = time.clock()
secs = (end - start)
print("Number read in","%s" % (secs),"seconds.", file=f)
print("Number read in","%s" % (secs),"seconds.")
f.flush()
del end,secs,start,z,data

rawDescription: Reading Very Large One Liner Text File

description: Reading Very Large One Liner Text File


code:
import numpy as np

#here y2 is the new extrapolated array
y2 = np.interp(x2,x1,y1)

rawDescription: Extrapolate python array with unequal spacing between elements


code:
class StringCache(dict):
    def __missing__(self, key):
        return key

f1_list = [None] * NUMBER_OF_ITEMS
string_cache = StringCache()

with open('F1.csv') as f1:
    for col1, col2, col3 in csv.reader(f1):
         for index in xrange(int(col1), int(col2) + 1):
              f1_list[index] = string_cache[col3]

with open('F2.csv') as f2:
    for (col,) in csv.reader(f2):
        print(f1_list[int(col)])

rawDescription: Find range an element belongs to

description: Find range an element belongs to


rawDescription: Python "in" magic method?

description: Python "in" magic method


code:
# The following line spawns the psftp process and binds its standard input
# to p.stdin and its standard output to p.stdout
p = subprocess.Popen('psftp -l testuser -pw testpass'.split(),
                     stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# Send the 'cd some_directory' command to the process as if a user were
# typing it at the command line
p.stdin.write('cd some_directory\n')

rawDescription: Can i control PSFTP from a Python script?

description: Control PSFTP from a Python script


code:
p = pexpect.spawn(your_cmd_here)
p.sendcontrol('z')

rawDescription: passing ctrl+z to pexpect

description: Passing ctrl+z to pexpect


code:
class LoginView(generic.edit.FormView):
    def dispatch(self, request, *args, **kwargs):
        if request.user.is_authenticated():
            return HttpRedirect('/whatever/')
        else:
            return super(LoginView, self).dispatch(request, *args, **kwargs)

rawDescription: how to redirect loggedin in users from viewing login page in django, using generic views

description: Redirect loggedin in users from viewing login page in django, using generic views


code:
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
        print('You pressed Ctrl+C!')
        sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()

rawDescription: How do I capture SIGINT in Python?

description: Capture SIGINT in Python


code: struct.pack('bbbb', *(int(x) for x in '127.0.0.1'.split('.')))

rawDescription: How to convert ip address to DWORD?

description: Convert ip address to DWORD


code:
from mod2sbml import Parser
p = Parser()

with open('sbmlconvert.xml', 'w') as of:
    s = open('sbmltest3.mod', 'r').read()
    d = p.parse(s)
    of.write(d.toSBML())

rawDescription: Python: Writing output to text file, but text file does not contain the entire string and truncates randomly?


code: x[np.newaxis, :, :] & y[:, np.newaxis, :] & z[:, :, np.newaxis]

rawDescription: Three 2d profiles to 3d array

description: Three 2d profiles to 3d array


code:
n = user_input_length
list = [None for x in range(n)]

rawDescription: Creating lists with variable lengths Python


code:
totNEA2014 = 1266

def to_percent(y, position):
    # Ignore the passed in position. This has the effect of scaling the default
    # tick locations.
    s = str(100 * y)
    if matplotlib.rcParams['text.usetex'] == True:
        return s + r'$\%$'
    else:
        return s + '%'

# Plot Details
bar_width = 0.18
line_width = 1
opacity = 1.
centre_bar_positions = arange(20)
zeros = [0 for k in range(len(centre_bar_positions))]

# Make bar plots
fig = plt.figure(figsize=[12, 9])
ax1 = fig.add_subplot(111)
bar_60_22 = plt.bar(centre_bar_positions, twentytwo[60.0], bar_width, bottom=10**-1, alpha=opacity, color='green', log=True, label='V < 22')

plt.title("Some Place")
plt.ylabel("Number of NEAs")
plt.xlabel("Number of apparitions")
ax1.set_ylim([ax1.set_ylim()[0], totNEA2014])
ax1.set_yscale("log")
plt.legend(loc='best')

ax2 = ax1.twinx()
ax2.yaxis.set_label_position("right")
ax2.set_yscale("log")
ax1.bar(centre_bar_positions, zeros, bar_width, bottom=10**-1, color='white', edgecolor='grey', linewidth=line_width, hatch='0', log=True)
ax2.set_ylim([0.0001, 1])
ax2.set_yticks([0.0001, 0.001, 0.01, 0.1, 1.])
formatter = FuncFormatter(to_percent)
ax2.get_yaxis().set_major_formatter(formatter)
plt.ylabel("Percentage of NEAs discovered in 2014")

plt.xlim([.6, 5.8])
plt.show()

rawDescription: Two y-axes ticks for one set of data, aligning both sets of ticks


code:
from concurrent.futures import ThreadPoolExecutor

with ThreadPoolExecutor(max_workers=2) as executor:
    for n in range(processors):
        name = "sql%i" % (n + 1)
        if os.path.exists(name):
            future = executor.submit(loadData, name)

rawDescription: Python subprocess spools too many processes


code:
f3.grid_rowconfigure(0, weight=1)
f3.grid_columnconfigure(0, weight=1)

rawDescription: TKinter - widgets not 'sticking' in Frame using grid layout


code: x.select("//body").extract()    # extract body

rawDescription: Scrapy Body Text Only

description: Scrapy Body Text Only


code:
from pyo import *
s = Server().boot()
osc1 = Sine(freq=440).out()
osc2 = Sine(freq=810).out()
s.start()
s.gui(locals())

rawDescription: Play 2+ sine waves together in python with pyo


code:
import time
urllib2.urlopen("http:\example.com?time=%s" % int(time.time()))

rawDescription: How to By pass WP super cache using python?

description: By pass WP super cache using python


code:
case1 = ['one', 'two']
case2 = ['three', 'four']
x = df.loc[df.category.isin(case1), 'number'].sum()/2
y = x + df.loc[df.category.isin(case2), 'number'].sum()

rawDescription: Pandas: using iterrows to return calculated values


code:
model = QSqlQueryModel()
model.setQuery("select some stuff", db)
while model.canFetchMore():
    model.fetchMore()
tableView.setModel(model)

rawDescription: Qt - Normal vertical scrollbar handle behavior in QTableView


code:
from minimock import mock
import os.path
mock('os.path.isfile', returns=True)

rawDescription: Mocking imported modules in Python

description: Mocking imported modules in Python


code:
class YourModelForm(forms.ModelForm):

    extra_field = forms.CharField()

    def __init__(self, *args, **kwargs):
        super(YourModelForm, self).__init__(*args, **kwargs)
        initial = '%s*rnd' % self.instance.pk if self.instance.pk else 'new'
        self.fields['extra_field'].initial = initial

rawDescription: How do you load a custom field in django

description: Load a custom field in django


code:
from django import forms

class FoobarForm():
    class Meta:
        model = Foobar

    def __init__(self, *args, **kwargs):
        super(FoobarForm, self).__init__(*args, **kwargs)
        self.fields['foobar'].widget = forms.TextInput()

rawDescription: Django form ForeignKey database field not as dropdown


code:
infile = open("bowlingscores.txt", "r")
name=0
score=0
averagescore=0
count=0
bowlersinfo=[]
for line in infile:
   bowler,score= line.split()
   score = int(score)
   averagescore += score
   bowlersinfo.append([bowler,score])
print (bowlersinfo)

infile.close()

averagescore /= float(len(bowlersinfo))

outfile = open("bowlingaverages.txt", "w")

for name,score in bowlersinfo:
 if score==300:
     outcome= "Perfect"
 elif score > averagescore:
     outcome= "Above Average"
 elif score== averagescore:
     outcome= "Average"
 else:
     outcome= "Below Average"
 print ("%s, %0.0f, %s" % (name, float(score), outcome))
 outfile.write(name+": " )
 outfile.write(outcome+"\n")
outfile.close()

rawDescription: using indexes in lists in an if statment

description: Using indexes in lists in an if statment


code:
def askUser():
    while True:
        try:
            choice = int(input("Do you want to: \n(1) Go to stack overflow \n(2) Import from phone \n(3) Import from camcorder \n(4) Import from camcorder?"))
        except ValueError:
            print("Please input a number")
            continue
        if 0 < choice < 5:
            break
        else:
            print("That is not between 1 and 4! Try again:")
    print ("You entered: {} ".format(choice)) # Good to use format instead of string formatting with %
    mydict = {1:go_to_stackoverflow, 2:import_from_phone, 3:import_from_camcorder, 4:import_from_camcorder}
    mydict[choice]()

rawDescription: Getting user input and making a decision


code:
dna_list = ['TTACCTTAAC', 'GATATCTGTC', 'ACGGCGTTCG', 'CCCTAAAGAG', 'CGTCAGAGGT']
k_mer = 'AAA'
k_mer_length = len(k_mer)
distance = 0

def HammingDistance(s1, s2):
    """ Return the Hamming distance between equal-length sequences """

    if len(s1) != len(s2):
        raise ValueError("Undefined for sequences of unequal length")

    return sum(ch1 != ch2 for ch1, ch2 in zip(s1, s2))

for index, dna in enumerate(dna_list):

    greatest_hamming_distance = 0

    for offset in range(len(dna) - k_mer_length + 1):

        motif = dna[offset:offset + k_mer_length]

        hamming_distance = HammingDistance(k_mer, motif)

        if hamming_distance > greatest_hamming_distance:
            greatest_hamming_distance = hamming_distance

    distance += greatest_hamming_distance

print(distance)

rawDescription: Calculate the sum of distances between Pattern and each string in Dna = {Dna1, ..., Dnat}


rawDescription: How to split python strings with multiple separators?

description: Split python strings with multiple separators


code:
# I have used os comands for a while
# this program will try to close a firefox window every ten secounds

import os
import time

# creating a forever loop
while 1 :
    os.system("TASKKILL /F /IM firefox.exe")
    time.sleep(10)

rawDescription: How to Close a program using python?

description: Close a program using python


rawDescription: pythonic manner of merging last three columns into a single pipe seperated column

description: Pythonic manner of merging last three columns into a single pipe seperated column


rawDescription: Open a URL with the OS default action from Python


code:
import tensorflow as tf
import numpy as np

def body(x):
    a = tf.random_uniform(shape=[2, 2], dtype=tf.int32, maxval=100)
    b = tf.constant(np.array([[1, 2], [3, 4]]), dtype=tf.int32)
    c = a + b
    return tf.nn.relu(x + c)

def condition(x):
    return tf.reduce_sum(x) < 100

x = tf.Variable(tf.constant(0, shape=[2, 2]))

with tf.Session():
    tf.initialize_all_variables().run()
    result = tf.while_loop(condition, body, [x])
    print(result.eval())

rawDescription: How to use tf.while_loop() in tensorflow

description: Use tf.while_loop() in tensorflow


rawDescription: python-qgis version information

description: Python-qgis version information


rawDescription: pywin32: how do I get a pyDEVMODE object?

description: Pywin32: how do I get a pyDEVMODE object


code:
first = {'1':['a', 'b', 'c'], '2':['a', 'b', 'c', 'd']} # the first dictionary
second = {'1':['b', 'c'], '2':['a', 'b', 'c', 'd']} # the second dictionary
result = {} # initialize a result dictionary
for key in first: # go through the keys in one of them
    # look into dictionary indexing vs the get() method
    f = set(first[key]) # make a set out of this key's values for first
    s = set(second[key]) # make a set out of this key's values for second
    # add this entry to the result -
    # will produce key:(elements in first for this ID that are not in second,
    #                   elements in second for this ID that are not in first)
    result[key] = (f-s, s-f)

rawDescription: Python 2.7 Removing Duplicate Elements in a List of Lists compared to another List of Lists


code:
import numpy as np
import netCDF4
rootgrp = netCDF4.Dataset('test.cdf', 'r', format='NETCDF4')
f = open('testoutput.csv','wb')

np.set_printoptions(threshold='nan')
f.write(str(rootgrp.variables['grid_optical_depth'][:]))
f.close()
rootgrp.close()

rawDescription: Printing one variable from a netCDF file using Python


code:
a.time = 1234567890
wrpcap('single-tcp-packet.pcap', a)

rawDescription: Specify timestamp on each packet in Scapy?


code: profile = list(profile)

rawDescription: Can't change the values of fields of model objects in lists


code:
# Assume that you have 12GB of GPU memory and want to allocate ~4GB:
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333)

sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))

rawDescription: How to prevent tensorflow from allocating the totality of a GPU memory?

description: Prevent tensorflow from allocating the totality of a GPU memory


code:
from itertools import chain, permutations
chain.from_iterable(map(permutations, integer_partitions))

rawDescription: combinations of blocks with maximum height

description: Combinations of blocks with maximum height


code:
import subprocess
p = subprocess.Popen(["mycmd", "--somearg"], stdout=subprocess.PIPE)
out, err = p.communicate()

rawDescription: How to run processes in the background and override standard streams

description: Run processes in the background and override standard streams


code: import C.D.module

rawDescription: How to import module from the parent directory of my parent folder?

description: Import module from the parent directory of my parent folder


code:
import csv

idata = open("KEY_ABC.csv","rU")
odata = open("KEY_XYZ.csv","rU")

leftdata = csv.reader(idata)
rightdata = csv.reader(odata)

def gen_chunks(reader, chunksize=1000000):
    chunk = []
    for i, line in enumerate(reader):
        if (i % chunksize == 0 and i > 0):
            yield chunk
            del chunk[:]
        chunk.append(line)
    yield chunk

count = 0

d1 = dict([(rows[3],rows[0]) for rows in rightdata])
odata.seek(0)
d2 = dict([(rows[3],rows[1]) for rows in rightdata])
odata.seek(0)
d3 = dict([(rows[3],rows[2]) for rows in rightdata])

for chunk in gen_chunks(leftdata):
    res = [[k[0], k[1], k[2], k[3], k[4], k[5], k[6],
                d1.get(k[6], "NaN")] for k in chunk]
    res1 = [[k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7],
                d2.get(k[6], "NaN")] for k in res]
    res2 = [[k[0], k[1], k[2], k[3], k[4], k[5], k[6], k[7], k[8],
                d3.get(k[6], "NaN")] for k in res1]
    namestart = "FINAL_"
    nameend = ".csv"
    count = count+1
    filename = namestart + str(count) + nameend
    with open(filename, "wb") as csvfile:
        output = csv.writer(csvfile)
        output.writerows(res2)

rawDescription: MemoryError with python/pandas and large left outer joins


code:
from StringIO import StringIO
import pandas as pd

text_string = StringIO(
"""
Cars,Country,Type,Score
1564,Australia,Stolen,1
200,Australia,Stolen,2
579,Australia,Stolen,3
156,Japan,Lost,4
900,Africa,Burnt,5
2000,USA,Stolen,6
1000,Indonesia,Stolen,7
900,Australia,Lost,8
798,Australia,Lost,9
128,Australia,Lost,10
200,Australia,Burnt,11
56,Australia,Burnt,12
348,Australia,Burnt,13
1246,USA,Burnt,14
""")

df = pd.read_csv(text_string, sep = ",")
# Specifically checks in column name "Cars"
group = df.loc[df['Country'] == 'Australia'].boxplot(column = 'Cars', by = 'Type')

rawDescription: Boxplot needs to use multiple groupby in Pandas


rawDescription: Launching python within python and timezone issue


code:
def popupError(s):
    popupRoot = Tk()
    popupRoot.after(2000, exit)
    popupButton = Button(popupRoot, text = s, font = ("Verdana", 12), bg = "yellow", command = exit)
    popupButton.pack()
    popupRoot.geometry('400x50+700+500')
    popupRoot.mainloop()

rawDescription: How to display a system notification in Python?

description: Display a system notification in Python


rawDescription: Merging keys on a dictionary - Python

description: Merging keys on a dictionary - Python


code:
order = 'asc'
column_sorted = getattr(ResultsDBHistory.postsize, order)()
sql_session.query(ResultsDBHistory).order_by(column_sorted).limit(max_items_shown)

rawDescription: python sqlalchemy dynamic order_by

description: Python sqlalchemy dynamic order_by


code:
', '.join(['%s']*7)
'INSERT INTO tablename(col1,col2,col3,col4,col5,col6,col7) VALUES (' + ', '.join(['%s']*7) + ');'

rawDescription: Is there a shorter syntax to insert values into a postgres table using psycopg2?


code:
options = [option1, option2, option3, option4, option5, option6, option7, option8]
future = random.randint(0,7)
answer = options[future]

rawDescription: How to make this elif statement more efficient

description: Make this elif statement more efficient


code:
import sys, os
python = sys.executable
os.execl(python, python, * sys.argv)

rawDescription: Restart (entire) program function Python 3.5


rawDescription: Searching for one of two complexish regex patterns in Python without creating submatches


code:
from nltk.corpus import wordnet as wn

acknowledgment_synset = wn.synset('acknowledgement.n.01')
acknowledgment_lemma = acknowledgment_synset.lemmas[1]

print(acknowledgment_lemma.derivationally_related_forms())
# [Lemma('admit.v.01.acknowledge'), Lemma('acknowledge.v.06.acknowledge')]

rawDescription: NLTK words lemmatizing

description: NLTK words lemmatizing


code:
def my_key(a):
    if a.part_of_subset:
        return 0,
    return 1, a.sort_key

collection.sort(key=my_key)

rawDescription: Delegate sort based on a condition

description: Delegate sort based on a condition


code:
from django.db import connections
cursor = connections['my_db_alias'].cursor()

rawDescription: Can i access different database in django than other default database

description: Access different database in django than other default database


code:
infile = "name_path.txt"
d={}
with open(infile, "r") as f:
  for line in f:
    path,label = line.split(";")
    d.setdefault(label,[]).append(path)

rawDescription: How to read all files that name store in text file

description: Read all files that name store in text file


code:
class MyAdminModelForm(ModelForm):
    class Meta(object):
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyAdminModelForm, self).__init__(*args, **kwargs)

        if not self.instance.pk:
            return # don't fetch related choices for new objects

        current_event = self.instance.event
        self.fields['route'] = ChoiceField(choices=OtherModel.objects.filter(event=current_event).values_list('id', 'title'))

@admin.register(MyModel)
class MyModelAdmin(ModelAdmin):
    form = MyAdminModelForm

rawDescription: Django admin form field - display objecy-dependent query results in a select box


code:
import re
string = 'YAN300,000,000'
match = re.search(r'([\D]+)([\d,]+)', string)
output = (match.group(1), match.group(2).replace(',',''))
output

rawDescription: Python efficiently split currency sign and number in one string


code:
ind = np.indices(myarray.shape)[0]
rm = np.hstack([ind[i] for i in mylist])

ans = np.take(myarray, sorted(set(ind)-set(rm)))

rawDescription: Deleting multiple slices from a numpy array


rawDescription: How can I match all alphanumerical characters and the underscore, the plus, the minus and the decimal point?

description: Match all alphanumerical characters and the underscore, the plus, the minus and the decimal point


code:
import time
#where you want to pause
time.sleep(3)
#then if you want to restart at the begnining:
main()

rawDescription: Returning / restarting program in python 3.x


code:
import datetime
now = datetime.datetime.now()
past = now - datetime.timedelta(hours=10)

rawDescription: Datetime - 10 Hours

description: Datetime - 10 Hours


code:
def editline(file,n_line,text):
    with open(file) as infile:
        lines = infile.readlines()
    lines[n_line] = text+' \n'
    with open(file, 'w') as outfile:
        outfile.writelines(lines)

rawDescription: How to erase line from text file in Python?

description: Erase line from text file in Python


code:
def user_new_unicode(self):
    return self.get_full_name()
User.__unicode__ = user_new_unicode #or User.__str__ = user_new_unicode

rawDescription: django foreignkey - format output value in selectlist

description: Django foreignkey - format output value in selectlist


code:
qus = [Q1, Q2, Q3, ...]
ans = [A1, A2, A3, ...]

def  quiz():
    for q, a in zip(qus, ans):
        if str(input(q)) == a:
             print ("Correct answer")
        else:
             print("Wrong Answer, Correct Answer is", a)
quiz()

rawDescription: Looping through variables and testing for user input


rawDescription: Word boundary within negative lookahead?

description: Word boundary within negative lookahead


code: item['Source_Website'] = response.url

rawDescription: How to add start_url as an item?

description: Add start_url as an item


code:
import web
import paramiko
import time

urls = (
        '/wlc', 'Index'
)

app = web.application(urls, globals())

render = web.template.render('templates/')

class Index(object):
        def GET(self):
                return render.hello_form()

        def POST(self):
                #Retrieve user input from web form
                form = web.input(user=" ", passwd=" ", device=" ")
                user = form.user
                passwd = form.passwd
                device = form.device

                #Make it so we don't need to hit a key to scroll through the output
                def disable_paging(remote_conn, command="config paging disable", delay=1):

                        remote_conn.send(command)
                        remote_conn.send("\n")
                        time.sleep(delay)

                #Have remote_conn_pre equal to the SSHClient module in paramiko
                remote_conn_pre = paramiko.SSHClient()

                #This allows us to bypass the ssh key popup that comes up when you ssh into a device for the first time
                remote_conn_pre.set_missing_host_key_policy(
                        paramiko.AutoAddPolicy())

                remote_conn_pre.connect(device, username=user, password=passwd) #Connect to the device using our defind parameters

                remote_conn = remote_conn_pre.invoke_shell() #invoke_shell module gives us access to talk to the device via the cli

                #Log into the WLC
                remote_conn.send(user)
                remote_conn.send("\n")
                remote_conn.send(passwd)
                remote_conn.send("\n")

                #Run the disable_paging function
                output = disable_paging(remote_conn)

                #Run command
                remote_conn.send("sh ap summary")
                remote_conn.send("\n")

                #Some WLCs can be slow to show output, have program wait 5 seconds
                time.sleep(5)

                output = remote_conn.recv(65535) #Read all output given

                return output #print output to screen

                remote_conn.close() #Close the SSH connection

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

rawDescription: Logging into a Cisco Wireless Controller via SSH


code: phone = re.search(r'(\d+-?){1,2}$', addr_str)

rawDescription: Extract phone numbers with hyphen using Python regex


code: #!/usr/bin/env python

rawDescription: How do I call a python 3 cgi script on RedHat Enterprise Linux using their Software Collections?

description: Call a python 3 cgi script on RedHat Enterprise Linux using their Software Collections


code:
class A(object):
    def __init__(self, b):
        self.b = b
    # .. some methods that reference self.b

rawDescription: Import trouble in python

description: Import trouble in python


code:
main_dict = {}
for item in json_data:
    values1_list = item['sub_values1']
    values2_str = item['sub_values2']
    vals = main_dict.setdefault('main_key', {'sub_key1': values1_list, 'sub_key2': values2_str})
    vals['sub_key1'].append(values1_list)

rawDescription: Append to a list inside of a nested dictionary in Python


code:
import jinja2
import scrubber

def sanitize_html(text):
    return jinja2.Markup(scrubber.Scrubber().scrub(text))

jinja_env.filters['sanitize_html'] = sanitize_html

rawDescription: Jinja2 escape all HTML but img, b, etc

description: Jinja2 escape all HTML but img, b, etc


code:
i = iter(data)
attr = [next(i) for x in range(next(i))]
[{x:next(i) for x in attr} for y in range(next(i))]

rawDescription: Parsing a single dimensional list into dict


code:
date_rng = pd.date_range('20060101','20060105',freq='D')
pd.Series(date_rng.format())

rawDescription: How to convert a Pandas DatetimeIndex to string accordingly

description: Convert a Pandas DatetimeIndex to string accordingly


code:
def foo(): pass

foo.__name__

rawDescription: Get function name to string

description: Get function name to string