code:
class QuestionForm(ModelForm):
    def save(self, user=None, force_insert=False, force_update=False, commit=True):
        q = super(QuestionForm, self).save(commit=False)
        q.author = user
        if commit:
            q.save()
        return q

    class Meta:
        model = Question
        exclude = ('author', 'pub_date')

def add_question(request):
    if request.method == "POST":
        form = QuestionForm(request.POST, request.FILES)
        if form.is_valid():
            form.save(user=request.user)
            return HttpResponseRedirect("/home/")
    else:
        form = QuestionForm()
        return render_to_response("qanda/add_question.html", {'form': form}, context_instance=RequestContext(request))

rawDescription: User won't auto save in View, but does in Admin


code:
import base64, zlib
decoded_data = base64.b64decode(zlib.decompress(encoded_data))

rawDescription: python - how to inflate gzipped, base64d string

description: Python - how to inflate gzipped, base64d string


code:
import tkinter as tk

root = tk.Tk()

word = 'hello'

def go(counter=1):
    l.config(text=word[:counter])
    root.after(150, lambda: go(counter+1))

b = tk.Button(root, text='go', command=go)
l = tk.Label(root)
b.pack()
l.pack()

root.mainloop()

rawDescription: Typewriter effect in tkinter

description: Typewriter effect in tkinter


code:
items = [i for i in db if 'dog' in i]
items[0] if items else None
# ('dog', 28, 30)

rawDescription: Search in python tuple list

description: Search in python tuple list


code:
from multiprocessing import Process, freeze_support, Queue

def func(my_id, q, begin, end):
    global myarray
    print('Process %d has range: %d - %d' % (my_id, begin, end))
    for i in range(begin,end):
        q.put((i, i * 2))

if __name__ == "__main__":
    freeze_support()

    q = Queue()
    processes = []
    myarray=[0] * 12
    print("At the beginning the array is ", myarray)

    for i in range(4):
        begin = i*3
        end = (i+1)*3
        p = Process(target=func, args=(i, q, begin, end))
        p.start()
        processes.append(p)

    for p in processes:
        p.join()

    while not q.empty():
        (index, value) = q.get()
        myarray[index] = value

    print("At the end the array is ", myarray)

rawDescription: python multiprocessing: processes don't work

description: Python multiprocessing: processes don't work


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(data)
div = soup.find("div", class_="myself", title=True)
print(div["title"])

rawDescription: Python Beautiful Soup extracting data within a div tag itself


code:
def callFilter(self, pos):
    column = self.horizontalHeader.logicalIndexAt(pos)

rawDescription: PyQt- Which column received the right-click?


code:
def numbers():
       a= input ("a:")
       a = int(a)
       b= input ("b:")
       b = int(b)
       return a,b

def add():
    a,b = numbers()
    print (a)
    print (b)

add()

rawDescription: How do I use multiple variable from one function into another?

description: Use multiple variable from one function into another


code:
class TCPServerProtocol(Protocol):

    # data = ''

    def connectionMade(self):
        self.deferred = self.factory.service.deferred
        self.deferred.addCallback(self.factory.service.s)
        self.deferred.addCallback(self.transport.write)
        self.deferred.addBoth(lambda r: self.transport.loseConnection)

    def dataReceived(self, data):
        self.data = data           # instead of self.data += data
        self.forward(self.data)    # this is the right place to call this method which in turn fires the callback through which the request is made to the server.

    def connectionLost(self, reason): pass
        # this will not be called until the connection from client is ended.
        # self.forward(self.data)

    def forward(self, data):
        if self.deferred is not None:
            d, self.deferred = self.deferred, None
            d.callback(data)

rawDescription: Unable to make http request to django server using twisted.web.AGENT


code:
#convert strings of the COUNT column to integers
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
LCC_PI_df.COUNT = LCC_PI_df.COUNT.apply(locale.atoi)

plot_table = LCC_PI_df.pivot_table(index=['RECL_LCC'], columns='RECL_PI', values='COUNT', aggfunc='sum')
#Calculate percentages
plot_table = plot_table.apply(lambda x : x / x.sum(), axis=1)

rawDescription: pandas transform dataframe pivot table

description: Pandas transform dataframe pivot table


code:
time_deltas = pd.to_timedelta(np.random.randint(-10**6, 10**6, size=10))
time_deltas
time_deltas < pd.Timedelta(0)

rawDescription: Filtering negative timedeltas

description: Filtering negative timedeltas


code:
( first_variable, second_variable,
  third_variable, fourth_variable ) = my_example_function()

rawDescription: Python PEP-8: Assignment following E122 and E501


rawDescription: How do I loop through each path from top to bottom in python?

description: Loop through each path from top to bottom in python


code:
print("List 1:", list_1)
print("List 2:", list_2)
removeElements = []
for k in range(len(list_1)):
    #if len(list_1[k]) == 0:
    #    removeElements.append(k)
    count = 0
    for i in range(0, len(list_2)):
        for j in range(0, len(list_1[k])):
            if len(list_2) <= i + j:
                break
            count = count + 1
            if list_1[k][j] != list_2[i + j]:
                count = 0
            if count == 2:
                print("removing", list_1[k])
                removeElements.append(k)

removeElements = sorted(set(removeElements))
for i in range(len(removeElements)):
    list_1.pop(removeElements[i] - i)

print("List_1:", list_1)

rawDescription: How to find sequence of numbers in list

description: Find sequence of numbers in list


code:
from django.db import models
from datetime import datetime
from time import strftime

class UnixTimestampField(models.DateTimeField):
    """UnixTimestampField: creates a DateTimeField that is represented on the
    database as a TIMESTAMP field rather than the usual DATETIME field.
    """
    def __init__(self, null=False, blank=False, **kwargs):
        super(UnixTimestampField, self).__init__(**kwargs)
        # default for TIMESTAMP is NOT NULL unlike most fields, so we have to
        # cheat a little:
        self.blank, self.isnull = blank, null
        self.null = True # To prevent the framework from shoving in "not null".

    def db_type(self, connection):
        typ=['TIMESTAMP']
        # See above!
        if self.isnull:
            typ += ['NULL']
        if self.auto_created:
            typ += ['default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP']
        return ' '.join(typ)

    def to_python(self, value):
        if isinstance(value, int):
            return datetime.fromtimestamp(value)
        else:
            return models.DateTimeField.to_python(self, value)

    def get_db_prep_value(self, value, connection, prepared=False):
        if value==None:
            return None
        # Use '%Y%m%d%H%M%S' for MySQL < 4.1
        return strftime('%Y-%m-%d %H:%M:%S',value.timetuple())

rawDescription: Timestamp fields in django

description: Timestamp fields in django


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

rawDescription: How do I iterate over all lines of files passed on the command line?

description: Iterate over all lines of files passed on the command line


code:
def nw_align(a, b, replace_func, insert, delete):

    ZERO, LEFT, UP, DIAGONAL = 0, 1, 2, 3

    len_a = len(a)
    len_b = len(b)

    matrix = [[(0, ZERO) for x in range(len_b + 1)] for y in range(len_a + 1)]

    for i in range(len_a + 1):
        matrix[i][0] = (insert * i, UP)

    for j in range(len_b + 1):
        matrix[0][j] = (delete * j, LEFT)

    for i in range(1, len_a + 1):
        for j in range(1, len_b + 1):
            replace = replace_func(a[i - 1], b[j - 1])
            matrix[i][j] = max([
                (matrix[i - 1][j - 1][0] + replace, DIAGONAL),
                (matrix[i][j - 1][0] + insert, LEFT),
                (matrix[i - 1][j][0] + delete, UP)
            ])

    i, j = len_a, len_b
    align_a = ""
    align_b = ""

    while (i, j) != (0, 0):
        if matrix[i][j][1] == DIAGONAL:
            align_a += a[i - 1]
            align_b += b[j - 1]
            i -= 1
            j -= 1
        elif matrix[i][j][1] == LEFT:
            align_a += "-"
            align_b += b[j - 1]
            j -= 1
        else: # UP
            align_a += a[i - 1]
            align_b += "-"
            i -= 1

    return align_a[::-1], align_b[::-1]

rawDescription: how to diff / align Python lists using arbitrary matching function?

description: Diff / align Python lists using arbitrary matching function


code:
# License: Creative Commons Zero (almost public domain) http://scpyce.org/cc0

import numpy as np

def sample_function(func, points, tol=0.05, min_points=16, max_level=16,
                    sample_transform=None):
    """
    Sample a 1D function to given tolerance by adaptive subdivision.

    The result of sampling is a set of points that, if plotted,
    produces a smooth curve with also sharp features of the function
    resolved.

    Parameters
    ----------
    func : callable
        Function func(x) of a single argument. It is assumed to be vectorized.
    points : array-like, 1D
        Initial points to sample, sorted in ascending order.
        These will determine also the bounds of sampling.
    tol : float, optional
        Tolerance to sample to. The condition is roughly that the total
        length of the curve on the (x, y) plane is computed up to this
        tolerance.
    min_point : int, optional
        Minimum number of points to sample.
    max_level : int, optional
        Maximum subdivision depth.
    sample_transform : callable, optional
        Function w = g(x, y). The x-samples are generated so that w
        is sampled.

    Returns
    -------
    x : ndarray
        X-coordinates
    y : ndarray
        Corresponding values of func(x)

    Notes
    -----
    This routine is useful in computing functions that are expensive
    to compute, and have sharp features --- it makes more sense to
    adaptively dedicate more sampling points for the sharp features
    than the smooth parts.

    Examples
    --------
    >>> def func(x):
    ...     '''Function with a sharp peak on a smooth background'''
    ...     a = 0.001
    ...     return x + a**2/(a**2 + x**2)
    ...
    >>> x, y = sample_function(func, [-1, 1], tol=1e-3)

    >>> import matplotlib.pyplot as plt
    >>> xx = np.linspace(-1, 1, 12000)
    >>> plt.plot(xx, func(xx), '-', x, y[0], '.')
    >>> plt.show()

    """
    return _sample_function(func, points, values=None, mask=None, depth=0,
                            tol=tol, min_points=min_points, max_level=max_level,
                            sample_transform=sample_transform)

def _sample_function(func, points, values=None, mask=None, tol=0.05,
                     depth=0, min_points=16, max_level=16,
                     sample_transform=None):
    points = np.asarray(points)

    if values is None:
        values = np.atleast_2d(func(points))

    if mask is None:
        mask = Ellipsis

    if depth > max_level:
        # recursion limit
        return points, values

    x_a = points[...,:-1][...,mask]
    x_b = points[...,1:][...,mask]

    x_c = .5*(x_a + x_b)
    y_c = np.atleast_2d(func(x_c))

    x_2 = np.r_[points, x_c]
    y_2 = np.r_['-1', values, y_c]
    j = np.argsort(x_2)

    x_2 = x_2[...,j]
    y_2 = y_2[...,j]

    # -- Determine the intervals at which refinement is necessary

    if len(x_2) < min_points:
        mask = np.ones([len(x_2)-1], dtype=bool)
    else:
        # represent the data as a path in N dimensions (scaled to unit box)
        if sample_transform is not None:
            y_2_val = sample_transform(x_2, y_2)
        else:
            y_2_val = y_2

        p = np.r_['0',
                  x_2[None,:],
                  y_2_val.real.reshape(-1, y_2_val.shape[-1]),
                  y_2_val.imag.reshape(-1, y_2_val.shape[-1])
                  ]

        sz = (p.shape[0]-1)//2

        xscale = x_2.ptp(axis=-1)
        yscale = abs(y_2_val.ptp(axis=-1)).ravel()

        p[0] /= xscale
        p[1:sz+1] /= yscale[:,None]
        p[sz+1:]  /= yscale[:,None]

        # compute the length of each line segment in the path
        dp = np.diff(p, axis=-1)
        s = np.sqrt((dp**2).sum(axis=0))
        s_tot = s.sum()

        # compute the angle between consecutive line segments
        dp /= s
        dcos = np.arccos(np.clip((dp[:,1:] * dp[:,:-1]).sum(axis=0), -1, 1))

        # determine where to subdivide: the condition is roughly that
        # the total length of the path (in the scaled data) is computed
        # to accuracy `tol`
        dp_piece = dcos * .5*(s[1:] + s[:-1])
        mask = (dp_piece > tol * s_tot)

        mask = np.r_[mask, False]
        mask[1:] |= mask[:-1].copy()

    # -- Refine, if necessary

    if mask.any():
        return _sample_function(func, x_2, y_2, mask, tol=tol, depth=depth+1,
                                min_points=min_points, max_level=max_level,
                                sample_transform=sample_transform)
    else:
        return x_2, y_2

rawDescription: Adaptive plotting of a function in python


code:
from random import choice

a = [[0,1,0],[0,1,1],[1,0,1]]
mylist = []

[[mylist.append((i,j)) for j, x in enumerate(v) if x == 1] for i, v in enumerate(a)]
print(choice(mylist))

rawDescription: Returning random element from a Python array based on search criteria


code:
class MM:
    def __init__(self):
        self._a = {} # Bs for each A
        self._b = {} # As for each B
        self._ab = {}

rawDescription: Efficient large dicts of dicts to represent M:M relationships in Python


code: limited_combinations = [(a, b, c) for ((a, b), c) in itertools.product(zip(A, B), C)]

rawDescription: Python itertools - Create only a subset of all possible products


code:
winning_numbers = [ {3, 4, 5}, {2, 3, 8}, {3, 2, 1} ]
players_numbers = {4, 3, 5}
players_numbers in winning_numbers

rawDescription: How do you check that a dictionary is in an array even in the worng order in python?

description: Check that a dictionary is in an array even in the worng order in python


rawDescription: python splitting string twice

description: Python splitting string twice


code:
import numpy as np
from scipy import ndimage

array = np.random.randint(0, 3, size=(200, 200))

label, num_label = ndimage.label(array == 0)
size = np.bincount(label.ravel())
biggest_label = size[1:].argmax() + 1
clump_mask = label == biggest_label

rawDescription: Python - Efficient way to find the largest area of a specific value in a 2D numpy array


code:
matches = ( re.search(r'some pattern to match', y) for x in something
                                                     for y in x.address  )
result = [ m.group(1) for m in matches if m ]

rawDescription: Python nested forloop list comprehension


code:
str
str(42)
import string
string
string.digits

rawDescription: Relationship between string module and str


code:
__author__ = 'Kavin'

from Bio import SeqIO
from Bio import SeqFeature
import xlrd
import sys
import re

workbook = xlrd.open_workbook(sys.argv[2])
sheet = workbook.sheet_by_index(0)
data = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]

# Create dicts to store TSS data
TSS = {}
row = {}
# For each entry (row), store the startcodon and strand information
for i in range(2, sheet.nrows - 1):
    if data[i][5] < -0.7:   # Ensures BASS score is within significant range
        Gene = data[i][0]
        row['Direction'] = str(data[i][3])
        row['StartCodon'] = int(data[i][4])
        TSS[str(Gene)] = row
        row = {}
    else:
        i += 1

# Create an output filename based on input filename
outfile_init = re.search('(.*)\.(\w*)', sys.argv[1])
outfile = str(outfile_init.group(1)) + '_modified.' + str(outfile_init.group(2))

final_features = []
for record in SeqIO.parse(open(sys.argv[1], "r"), "genbank"):
    for feature in record.features:
        if feature.type == "gene" or feature.type == "CDS":
            if TSS.has_key(feature.qualifiers["locus_tag"][0]):
                newstart = TSS[feature.qualifiers["locus_tag"][0]]['StartCodon']
                if feature.location.strand == 1:
                    feature.location = SeqFeature.FeatureLocation(SeqFeature.ExactPosition(newstart - 1),
                                                                  SeqFeature.ExactPosition(
                                                                      feature.location.end.position),
                                                                  feature.location.strand)
                else:
                    feature.location = SeqFeature.FeatureLocation(
                        SeqFeature.ExactPosition(feature.location.start.position),
                        SeqFeature.ExactPosition(newstart), feature.location.strand)
        final_features.append(feature)  # Append final features
    record.features = final_features
    with open(outfile, "w") as new_gb:
        SeqIO.write(record, new_gb, "genbank")

rawDescription: Modify location of a genbank feature

description: Modify location of a genbank feature


code:
g_markerList = [ (marker1,marker2) for marker1 in marker1List
                                   for marker2 in marker2List
                                   if marker1.type == marker2.type ]

rawDescription: Intersect 2 lists, store result in a tuple in python


code:
# All this work is un-necessary overkill
#root = Resource()
#root.putChild("",django_resource)
#from twisted.application import service
#application = service.Application("app")

internet.TCPServer(8080, Site(django_resource)).setServiceParent(application)

rawDescription: How does one incorporate a Django application into an existing twisted server?

description: Incorporate a Django application into an existing twisted server


code:
import ctypes

kernel32 = ctypes.windll.kernel32
kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7)

rawDescription: How to use the new support for ANSI escape sequences in the Windows 10 console?

description: Use the new support for ANSI escape sequences in the Windows 10 console


code:
for dirname, subdirs, files in os.walk("D:\\review docs"):
    if 'exclude directory' in subdirs:
        subdirs.remove('exclude directory')
    zf.write(dirname)
    for filename in files:
        zf.write(os.path.join(dirname, filename))
zf.close()

rawDescription: Exclude a directory from getting zipped using zipfile module in python


rawDescription: Plotting unique dates using matplotlib

description: Plotting unique dates using matplotlib


code:
class GrantAdminTestCase(TestCase):
    fixtures = [
        'grants/grant_config',
        'grants/grants',
    ]

    def setUp(self):
        self.g = Grant.objects.first()

        self.DeadlineFormSet = inlineformset_factory(
            Grant, Deadline, formset=DeadlineInlineFormset)

        self.data = {
            'additional_deadlines-INITIAL_FORMS': 0,
            'additional_deadlines-MAX_NUM_FORMS': 1000,
            'additional_deadlines-TOTAL_FORMS': 1,
            'additional_deadlines-0-deadline': date.today(),
            'additional_deadlines-0-grant': '2',
            'additional_deadlines-0-id': '',
        }

    def test_formset_is_valid_if_deadline_exists(self):
        formset = self.DeadlineFormSet(self.data, instance=self.g)
        self.assertEqual(formset.is_valid(), True)

    def test_formset_is_invalid_if_deadline_doesnt_exist(self):
        # formset should be invalid if there is an additional deadline
        # and no main deadline
        self.g.deadline = None
        formset = self.DeadlineFormSet(self.data, instance=self.g)
        self.assertEqual(formset.is_valid(), False)

    def test_formset_is_valid_if_deadline_blank(self):
        # formset should still be valid if deadline is blank
        # (it's not saved)
        self.data['additional_deadlines-0-deadline'] = ''
        formset = self.DeadlineFormSet(self.data, instance=self.g)
        self.assertEqual(formset.is_valid(), True)

    def test_formset_is_invalid_if_additional_deadlines_earlier(self):
        # formset should be invalid if any additional deadlines are earlier
        # than the main deadline
        self.g.deadline = date.today()
        yesterday = date.today() - timedelta(days=1)
        self.data['additional_deadlines-0-deadline'] = yesterday
        formset = self.DeadlineFormSet(self.data, instance=self.g)
        self.assertEqual(formset.is_valid(), False)

rawDescription: Unit testing validation on an inline in Django admin


code: itertools.product("ACGT", repeat=8)

rawDescription: Python Iterate through characters

description: Python Iterate through characters


code:
from django.db.models import Q

Chat.objects.filter(Q(chatsubscription__profile__in=[profileA,profileB]) & Q(community=communty))

rawDescription: Django getting especific object using QuerySet in reverse relationship many-to-one


code:
result = []

def nextSalaryFixed(salary, percentage, growth, years):
    if years == 1:
        tup = salary * (percentage * 0.01)
    else:
        tup = (nextSalaryFixed(salary, percentage, growth, years - 1) *
            ((1 + (0.01 * growth))) + (salary * (percentage * 0.01)))

    result.append((years, tup))
    return tup

nextSalaryFixed(10000, 10, 5, 5)
result # [(1, 1000.0), (2, 2050.0), (3, 3152.5), (4, 4310.125), (5, 5525.63125)]

rawDescription: Make Recursive Function Return a Tuple

description: Make Recursive Function Return a Tuple


code:
assert not (5 > 2)
assert not (2 > 5)

rawDescription: How do you assert something is not true in Python?

description: Assert something is not true in Python


code:
user_blogs = Blog.objects.filter(owner=user)

user_blogs_with_article = user_blogs.filter(articles=article)

rawDescription: Checking for contains in many-to-may field when doing a query in Django


code:
mylist = ['a','b']
def f(a,b):
    print(a,b)

sliderinterval=(0,10,1)
d = {k:sliderinterval for k in mylist}
w = interactive(f, **d)

rawDescription: Using string as variable in iPython interactive


code:
df_csv = pd.read_csv(outputPath, 'your settings here')

# provided that their lengths match
df_csv['to new column'] = df['from single column']

df_csv.to_csv(outputPath, 'again your settings here')

rawDescription: Append pandas DataFrame column to CSV

description: Append pandas DataFrame column to CSV


code:
def region_required(view_func):
    def new_view(request, ctx=None, *args, **kw):
        if ctx is None:
            ctx = {}
        import pdb; pdb.set_trace()
        ctx['regions'] = Region.objects.all()
        return view_func(request, context=ctx, *args, **kw)
    return new_view

rawDescription: Function argument having value that is neither passed in by caller nor default value


code:
model.keywordBlock.synchVersions()
def GetBlockPosition(model,blockPrefix):
 pos = 0
 for block in model.keywordBlock.sieBlocks:
  if string.lower(block[0:len(blockPrefix)])==string.lower(blockPrefix):return pos
  pos=pos+1
 return -1
model.keywordBlock.insert(GetBlockPosition(model,'*Restart')-1, """
*EL FILE,POSITION=AVERAGED AT NODES
S
""")

rawDescription: How to request nodal stress output in ABAQUS Python script

description: Request nodal stress output in ABAQUS Python script


code:
import sys, os
import subprocess
import threading
import signal
import time

#Use ctrl-c and ctrl-break to terminate the script/ping

def sigbreak(signum, frame):
    import sys
    if proc.poll() is None:
        print('Killing ping...')
        proc.kill()
    sys.exit(0)

signal.signal(signal.SIGBREAK, sigbreak)
signal.signal(signal.SIGINT, sigbreak)

#executes in a separate thread
def run(pid):
    while True:
        time.sleep(2)
        try:
            os.kill(pid, signal.CTRL_BREAK_EVENT)
        except WindowsError:
            #quit the thread if ping is dead
            break

cmd = [r'c:\windows\system32\ping.exe', '127.0.0.1', '-l', '10000', '-t']
flags = subprocess.CREATE_NEW_PROCESS_GROUP
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, creationflags=flags)
threading.Thread(target=run, args=(proc.pid,)).start()

while True:
    line = proc.stdout.readline()
    if b'statistics' in line:
        #I don't know what you're doing with the ping stats.
        #I'll just print them.
        for n in range(4):
            encoding = getattr(sys.stdout, 'encoding', 'ascii')
            print(line.decode(encoding).rstrip())
            line = proc.stdout.readline()
        print()

rawDescription: How to clear stdout in Python subprocess?

description: Clear stdout in Python subprocess


code:
sqlbase = """UPDATE media
             SET {query}
             WHERE media_id = %(media_id)s"""

mapping = {key: getattr(self, key, None) for key in ['filename', 'filesize']}
mapping['media_id'] = 12345
setpieces = ["{key} = %({key})s".format(key=key) for key in mapping] + \
            ["timestamp_modified = %s" % time.time()]

cursor.execute(sqlbase.format(query=','.join(setpieces)), mapping)

rawDescription: Construct a MySQL update query in Python that only puts quotes around strings not numbers


rawDescription: Operation by indexing only last axis

description: Operation by indexing only last axis


code:
from System.Diagnostics import Process
p = Process()
p.StartInfo.RedirectStandardOutput = True
p.StartInfo.RedirectStandardError = True
p.StartInfo.UseShellExecute  = False
p.StartInfo.CreateNoWindow = True

rawDescription: IronPython launch subprocess without a console window


code: graph.get(page_id + "/feed", page=False, retry=3, limit=100, fields="message,picture")

rawDescription: Facebook Graph API not returning all the fields of a perticular post


code:
temp  # example data
temp.split(',')
temp.strip().split(',')

rawDescription: unwanted newline in python .write

description: Unwanted newline in python .write


code:
class MySqlModel(QSqlTableModel):
    def data(self, index, role=Qt.DisplayRole):
        if role == Qt.TextAlignmentRole:
            return Qt.AlignCenter
        return QSqlTableModel.data(self,index,role)

rawDescription: PyQt4 qTableView Alignment

description: PyQt4 qTableView Alignment


code:
import subprocess

subprocess.Popen("path/to/vla.exe mp3_1 mp3_2")

rawDescription: creating a playlist from listbox selection and playing it using VLC?

description: Creating a playlist from listbox selection and playing it using VLC


code:
with open('corpus.txt', 'r') as f:
    answer = []
    for line in f:
        cnt = 0
        sa = nltk.word_tokenize(line)
        answer.append([tuple([char, sa[i+1]]) for i,char in enumerate(sa[:-1])])

rawDescription: Lists in Python (Using NLTK)

description: Lists in Python (Using NLTK)


code:
with open('path/to/input') as infile, open('path/to/output', 'w') as outfile:
  for line in infile:
    if len(line) > 50:
      outfile.write('\n'.join(line[i:i+50] for i in xrange(0,len(line), 50)))
    else:
      outfile.write(line)

rawDescription: Python Insert new line if line has more than 50 characters


code:
class Node(...):
    def get_children(self, order='new'):
        if order == 'new':
            orderby = Node.created.desc()
        elif order == 'old':
            orderby = Node.created.asc()
        return DBSession.query(Node).filter(Node.parent_id == self.id).order_by(orderby).all()

rawDescription: How to make customizable "order by" for many-to-one relation to itself in Elixir or SQLAlchemy?

description: Make customizable "order by" for many-to-one relation to itself in Elixir or SQLAlchemy


rawDescription: The most frequent pattern of specific columns in Pandas.DataFrame in python


code:
def split_list(mylist, *args):
    ilist = map(lambda p : int(p * len(mylist) / 100.0), args) + [len(mylist)]
    return reduce(lambda l, v : [l[0] + [mylist[l[1]:v]], v], ilist, [[],0])[0]

rawDescription: Python - return a region of a list based on calculated percentages


code:
def search(request):
    errors = []
    q1 = request.GET.get('q1')
    q2 = request.GET.get('q2')
    if not (q1 or q2):
        errors.append('Enter a search term.')
    elif ((len(q1) > 20) or (len(q2) > 20)):
        errors.append('Please enter at most 20 characters.')
    else:
        hotels = Hotel.objects.all()
        if q1:
            hotels = hotels.filter(name__icontains=q1)
        if q2:
            hotels = hotels.filter(street__icontains=q2)
    return render(request, 'company/search_results.html', {'hotels': hotels, 'q1': q1, 'q2': q2, 'errors': errors})

rawDescription: Django multi-valued search bar

description: Django multi-valued search bar


code:
import os
import glob
newest = max(glob.iglob('*.[Mm][Pp]3'), key=os.path.getctime)

rawDescription: Python: Find newest file with .MP3 extension in directory


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

fig = plt.figure()

ax = fig.add_subplot(111)

x = np.linspace(0, 300, 20)

y = np.linspace(0,300, 20)
y = y*1e16

ax.plot(x,y)

ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))

plt.show()

rawDescription: Can I show decimal places and scientific notation on the axis of a matplotlib plot using Python 2.7?

description: Show decimal places and scientific notation on the axis of a matplotlib plot using Python 2.7


rawDescription: python get second value of a tuple in a list

description: Python get second value of a tuple in a list


code:
import re
s = '1 stores(s)'
if re.match('store\(s\)$',s):
    print('match')

rawDescription: matching parentheses in python regular expression

description: Matching parentheses in python regular expression


rawDescription: Split or Extract Strings into Arguments of Function?


code:
import os
cmd="bin/candc --models models"
subprocess.check_output('{} | tee /dev/stderr'.format( cmd ), shell=True, cwd=os.path.abspath('candc'))

rawDescription: python subprocess shouldn't run from within the folder

description: Python subprocess shouldn't run from within the folder


code:
UserList = tuple((n, a, w) if a >= 18 else ('', None, None) for (n, a, w) in UserList)
UserList

rawDescription: replace element from a tuple of tuples with empty

description: Replace element from a tuple of tuples with empty


code:
def post(self, request, *args, **kwargs):
    self.object = None
    evt_session = get_object_or_404(
        EventSession, pk=int(self.request.POST['session']))
    form_class = self.get_form_class()
    form = self.get_form(form_class)

    form.instance.session = evt_session

    if form.is_valid():
        return self.form_valid(form)
    else:
        return self.form_invalid(form)

rawDescription: Django class based generic views: setting a field to initial value based on context


code:
def hd(data):
    """ str --> hex dump """
    def printable(c):
        import string
        return c in string.printable and not c.isspace()
    result = ""
    for i in range(0, len(data), 16):
        line = data[i:i+16]
        result += '{0:05x} '.format(i)
        result += ' '.join(c.encode("hex") for c in line)
        result += " " * (50-len(line)*3)
        result += ''.join(c if printable(c) else '.' for c in line)
        result += "\n"
    return result

input_file = open('blind_willie.MP3', 'rb')
contents = input_file.read()
output_file = open('f2.txt', 'wb')
output_file.write(hd(contents))

rawDescription: Content miss match

description: Content miss match


code:
import requests
import json

#Token used to post
auth_token = "X"

#Take and parse payload for title and body at site 1.
def payload(nid):
    from urllib.request import urlopen
    with urlopen("www.site1.com/" + nid + ".json") as rr:
        result = json.loads(rr.read().decode(rr.headers.get_content_charset("utf-8")))
    title = (result["title"])
    body = (result["body"]["und"])
    return (title,body)
#Take title, body, auth_token and then also nid from user input, and POSTing  to site 2
def add(nid,title,body):
    url = "www.site2.com/stuff.json"
    headers = {"content-type": "application/json"}
    payload = {
        "auth_token": auth_token,
        "document":
            {
                "external_id": nid,
                "fields": [
                    {"name": "title", "value": title, "type": "string"},
                    {"name": "path", "value": "www.site1.com/node/"+nid,"type": "enum"},
                    {"name": "nid", "value": nid, "type": "integer"},
                    {"name": "body", "value": body, "type": "text"},
                ]}
    }

    r = requests.post(url, data=json.dumps(payload), headers=headers)
    print("{} was added".format(nid))

while True:

#Trigger User Input
    new_item = input("> ")

#Add nid
    if new_item == "A":
        nid = input("Give me an NID please: ")
        title,body = payload(nid)
        add(nid,title,body)

rawDescription: python GET and POST with json and variables

description: Python GET and POST with json and variables


code:
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class FilePaths(Base):
    __tablename__ = 'file_paths'
    __table_args__ = {'mysql_engine':'InnoDB'}

    table_id = Column(Integer, primary_key=True)
    fullpath = Column(String(255))
    filename = Column(String(255))
    extension = Column(String(255))
    created = Column(String(255))
    modified = Column(String(255))
    size = Column(Integer)
    owner = Column(String(255))
    permissions = Column(Integer)

Base.metadata.create_all(engine)

rawDescription: Automatically Build Database Table based on a Class with SQLAlchemy


code:
from Tkinter  import *

ALL=N+S+E+W

class Application(Frame):

    def __init__(self,master=None):
        Frame.__init__(self,master)

        # the UI is made up of two major areas: a bottom row
        # of buttons, and a top area that fills the result of
        # UI
        top_frame = Frame(self)
        button_frame = Frame(self)

        button_frame.pack(side="bottom", fill="x")
        top_frame.pack(side="top", fill="both", expand=True)

        # top frame is made up of three sections: two smaller
        # regions on the left, and a larger region on the right
        ul_frame = Frame(top_frame, background="green", width=200)
        ll_frame = Frame(top_frame, background="blue", width=200)
        right_frame = Frame(top_frame, background="red")

        ul_frame.grid(row=0, column=0, sticky=ALL)
        ll_frame.grid(row=1, column=0, sticky=ALL)
        right_frame.grid(row=0, column=1, rowspan=2, sticky=ALL)
        top_frame.columnconfigure(1, weight=1)
        top_frame.rowconfigure(0, weight=1)
        top_frame.rowconfigure(1, weight=1)

        # the right frame is made up of two widgets, an entry
        # on top and a text below
        entry = Entry(right_frame)
        text = Text(right_frame)

        entry.pack(side="top", fill="x")
        text.pack(side="top", fill="both", expand=True)

        # the button frame has five equally spaced buttons
        for color in ('Red', 'Blue', 'Green', 'Black'):
            b = Button(button_frame, text=color)
            b.pack(side="left", fill="x", expand=True)
        quit_button = Button(button_frame, text="Quit")
        quit_button.pack(side="left", fill="x", expand=True)

root = Tk()
app = Application(root)
app.pack(fill="both", expand=True)
root.mainloop()

rawDescription: python - tkinter -- Having trouble with resizing multiple grids

description: Python - tkinter -- Having trouble with resizing multiple grids


code:
import inspect
from collections import defaultdict

def clcoancl(*cls_list):
    mros = [list(inspect.getmro(cls)) for cls in cls_list]
    track = defaultdict(int)
    while mros:
        for mro in mros:
            cur = mro.pop(0)
            track[cur] += 1
            if track[cur] == len(cls_list):
                return cur
            if len(mro) == 0:
                mros.remove(mro)
    return None # or raise, if that's more appropriate

rawDescription: How to determine the closest common ancestor class

description: Determine the closest common ancestor class


code:
with open("lolpa.txt") as f:
    for word in f.readline().split(): # assuming all words are on the first line
        digits = [c for c in word if c.isdigit()]
        if digits: # digits list is not empty
            print(' '.join(digits)) # shows digits with space in between
        else:
            print(word) # prints word normally

rawDescription: Goes to a file and prints only the words that don't have any digits in them


code:
from __future__ import print_function

try:
    from collections import ChainMap  # Python 3
except ImportError:
    from ConfigParser import _Chainmap as ChainMap  # Python 2

class ChainMapWithAltKeys(ChainMap):
    def __init__(self, *maps, **kwargs):
        try:
            super(ChainMapWithAltKeys, self).__init__(*maps)
        except TypeError:  # Python 2
            ChainMap.__init__(self, *maps)  # Python 2
        self.altkeymap = kwargs.get('altkeymap', {})

    def __getitem__(self, key):
        if key in self.altkeymap:
            key = self.altkeymap[key]
        try:
            return super(ChainMapWithAltKeys, self).__getitem__(key)
        except TypeError:  # Python 2
            return ChainMap.__getitem__(self, key)  # Python 2

dict_one = {'a': 1, 'b': 2, 'c': 3, 'samekey': 'diffval_one'}
dict_two = {'x': 24, 'y': 25, 'z': 26, 'samekey': 'diffval_two'}

altkeymap = {'alpha': 'a', 'zulu': 'z'}

cmwak = ChainMapWithAltKeys(dict_one, dict_two, altkeymap=altkeymap)

print(cmwak['a'])  # 1
print(cmwak['alpha'])  # 1
print(cmwak['b'])  # 2
print(cmwak['y'])  # 25
print(cmwak['z'])  # 26
print(cmwak['zulu'])  # 26
print(cmwak['samekey'])  # diffval_one

rawDescription: Creating a new python dict from existing dicts with different keys but same ids


code:
from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        self.Dialog = Dialog
        self.Dialog.setObjectName(_fromUtf8("self.Dialog"))
        self.Dialog.resize(190, 98)
        self.pushButton = QtGui.QPushButton(self.Dialog)
        self.pushButton.setGeometry(QtCore.QRect(0, 0, 191, 101))
        font = QtGui.QFont()
        font.setPointSize(13)
        self.pushButton.setFont(font)
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.retranslateUi(self.Dialog)
        QtCore.QMetaObject.connectSlotsByName(self.Dialog)
        QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL('released()'), self.Dialog.close) # <- put signal to close when clicked.

    def retranslateUi(self, Dialog):
        self.Dialog.setWindowTitle(_translate("self.Dialog", "self.Dialog", None))
        self.pushButton.setText(_translate("self.Dialog", "hi", None))

class QCustomDialog (QtGui.QDialog): # <- Implement your own
    def closeEvent(self, event):
        reply = QtGui.QMessageBox.question(self, 'Message',
            "Are you sure to quit?", QtGui.QMessageBox.Yes |
            QtGui.QMessageBox.No, QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QCustomDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

rawDescription: PyQt4 ---- I want to use closeEvent() in my code


code:
def match_dict(new_list, old_list):
    old = dict((v['id'], v) for v in old_list)
    return [dict(d, **old[d['id']]) for d in new_list if d['id'] in old]

rawDescription: Match set of dictionaries. Most elegant solution. Python


code:
def setMesaj(self):
  mesaj = unicode(self.toPlainText().toUtf8(), "utf-8")
  ascii = mesaj.encode("ascii", "ignore")
  if ascii != mesaj:
    self.setPlainText(ascii)

  if (len(mesaj)) > 159:
    QtGui.QMessageBox.warning(self, 'warning', "[WARN-1] Mesaj 160 karakterden fazla?")
    i = len(mesaj) - 159
    mesaj = mesaj [:-i]
    self.setPlainText(mesaj)

rawDescription: How can I update QTextEdit as user writes on it? (on Python)

description: Update QTextEdit as user writes on it? (on Python)


code:
df
bi = df.C==0
df.ix[bi, 'C'] = df[bi][['A', 'D']].apply(max, axis=1)
df

rawDescription: Pandas DataFrame Apply

description: Pandas DataFrame Apply


code:
alerts = resp_data['alerts']
for alert in alerts:
    alert['alert_date'] = datetime.strptime(alert['alert_date'], "%Y-%m-%d %H:%M:%S")

rawDescription: Python: Convert Dictionary of String Times to Date Times


code: server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port), logRequests=False)

rawDescription: Silence output from SimpleXMLRPCServer

description: Silence output from SimpleXMLRPCServer


code:
class letter_generator:
 def __init__(self, prefix, places):
  self.prefix = prefix
  self.places = places
 current = 0
 def get_unique_id(self):
  self.current+=1
  return "%s%s" % (self.prefix, str(self.current).zfill(self.places))
l = letter_generator('TM',5)
l.get_unique_id()
l.get_unique_id()
l.get_unique_id()
l.get_unique_id()

rawDescription: How can I generate a alphanumeric series in Python

description: Generate a alphanumeric series in Python


code:
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
gvs = optimizer.compute_gradients(cost)
capped_gvs = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gvs]
optimizer.apply_gradients(capped_gvs)

rawDescription: How to effectively apply gradient clipping in tensor flow?

description: Effectively apply gradient clipping in tensor flow


code:
outputdata = {}
for id, stuff in jsonData.iteritems():
    outputdata[id.encode("ascii")] = stuff[u"name"]

rawDescription: Decomposition and decoding of nested dictionary/json


code: (lambda words, rules: sum([[word[:-len(rule)]] if word.endswith(rule) else [] for word in words for rule in rules], []))(str_test.split(), stem_rules)

rawDescription: Trying to convert a nested loop with two sequences into a lambda


code:
import urllib.request
external_ip = urllib.request.urlopen('http://ifconfig.me/ip').read()

rawDescription: Python SocketServer - Get own IP

description: Python SocketServer - Get own IP


code:
import pickle
mydata = [1, 2, 3, 5]
pickle.dump(mydata, open("mydata.p", "wb"))
mydata2 = pickle.load(open("mydata.p", "rb"))

rawDescription: Python saving large simulation

description: Python saving large simulation


code:
@EndpointsAliasProperty
def office_ltd(self):
    limited = doSomethingWith(self.office)
    return limited

@Building.query_method(collection_fields=('id', 'name', 'office_ltd'),
                       path='buildings', name='list')
def List(self, query):
    return query

rawDescription: GAE NDB with Endpoints Proto Datastore: How to format response fields of reference property?


rawDescription: Python - delete part of link in array

description: Python - delete part of link in array


code:
#!/usr/bin/env python

import sys, os
import wx
import wx.lib.scrolledpanel as scrolled

class ImgPanel(scrolled.ScrolledPanel):
    def __init__(self, parent):
        super(ImgPanel, self).__init__(parent,
                                       style = wx.SUNKEN_BORDER)

        self.bitmap=wx.StaticBitmap(parent=self)
        image = wx.Bitmap('image.jpg')
        self.bitmap.SetBitmap(image)

        self.imgSizer = wx.BoxSizer(wx.VERTICAL)
        self.imgSizer.Add(self.bitmap, 1, wx.EXPAND)
        self.SetSizer(self.imgSizer)

        self.SetAutoLayout(1)
        self.SetupScrolling()
        self.Bind(wx.EVT_PAINT, self.OnPaint)
        self.bitmap.Bind(wx.EVT_MOTION, self.OnMove)
        self.bitmap.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
        self.bitmap.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
        self.IsRectReady = False
        self.newRectPara=[0,0,0,0]

class  WinFrame(wx.Frame):
    def __init__(self, parent, title, width, height):
        super(WinFrame, self).__init__(parent,
                                       title=title,
                                       size=(width, height))

        self.imgPanel = ImgPanel(self)
        self.frameSizer = wx.BoxSizer(wx.HORIZONTAL)
        self.frameSizer.Add(self.imgPanel, 1, wx.EXPAND)
        self.SetAutoLayout(True)
        self.SetSizer(self.frameSizer)
        self.Layout()

        self.Centre()
        self.Show(True)

class MyApp(wx.App):
    def __init__(self, width, height):
        super(MyApp, self).__init__(0)

        self.width = width
        self.height = height

    def createFrame(self):
        self.frame = WinFrame(None, "test", self.width, self.height)
        self.SetTopWindow(self.frame)

def main():
    app = MyApp(640, 480)
    app.createFrame()
    app.MainLoop()

if "__main__" == __name__ :
    main()

rawDescription: How to display an image in a scrolled pannel

description: Display an image in a scrolled pannel


code:
from django.db.models import Avg
Product.objects.annotate(average_stars = Avg('rating__stars')).order_by('-average_stars')

rawDescription: Django: calculate average, and sort by field in submodel


code: cursor.execute("SELECT name FROM products WHERE rating > %s AND category like 'Automation %%'", (3));

rawDescription: Python MySQL parameterized query conflicts with % wildcard in LIKE statement


rawDescription: Pop off empty field

description: Pop off empty field


code:
#Import libraries
from gcloud import datastore
import os

#The next few lines will set up your environment variables
#Replace "YOUR_RPOEJCT_ID_HERE" with the correct value in code.py
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "key.json"

projectID = "YOUR_RPOEJCT_ID_HERE"

os.environ["GCLOUD_TESTS_PROJECT_ID"] = projectID
os.environ["GCLOUD_TESTS_DATASET_ID"] = projectID
datastore.set_default_dataset_id(projectID)

#Let us build a message board / news website

#First, create a fake email for our fake user
email = "me@fake.com"

#Now, create a 'key' for that user using the email
user_key = datastore.Key('User', email)

#Now create a entity using that key
new_user = datastore.Entity( key=user_key )

#Add some fields to the entity

new_user["name"] = unicode("Iam Fake")
new_user["email"] = unicode(email)

#Push entity to the Cloud Datastore
datastore.put( new_user )

#Get the user from datastore and print
print( datastore.get(user_key) )

rawDescription: Google Datastore API Authentication in Python


code:
from cachetools import cached, hashkey
from random import randint

@cached(cache={}, key=lambda db_handle, query: hashkey(query))
def find_object(db_handle, query):
    print("processing {0}".format(query))
    return query

queries = list(range(5))
queries.extend(range(5))
for q in queries:
    print("result: {0}".format(find_object(randint(0, 1000), q)))

rawDescription: Make @lru_cache ignore some of the function arguments


code:
req_ip = request.remote_addr
return Response(req_ip)

rawDescription: Python: How can the origin IP of an http request be determined


code:
webtable ={}
for frame in frames:
  for x, y in sources:
    if x_y_on_frame():
        keyTuple = (x,y,frame.filter.name)
        if not keyTuple in webtable:
            webtable[keyTuple] = {
            'ifile':frame.filename,
            'pFile':frame.pngfile,
            'fFile':frame.fitsfile,
            }

rawDescription: best data-structure that i can use to store tabular data?

description: Best data-structure that i can use to store tabular data


code:
import wx

class modalPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.okBtn = wx.Button(self, -1, "OK")
        self.okBtn.Bind(wx.EVT_BUTTON, self.OnOkClick)
        sizer.Add(self.okBtn, 0)
        self.SetSizer(sizer)

    def OnOkClick(self, event):
        #do stuff
        pass
        self.Hide()
        self.GetParent().GetParent().stuffPanel.Show()

class normalPanel(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, -1)
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.btn = wx.Button(self, -1, "Show Modal")

        sizer.Add(self.btn, 0)
        self.SetSizer(sizer)

class oranges(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1,'Stuff',size=(300,300))

        self.panel = wx.Panel(self)
        self.sizer = wx.BoxSizer(wx.HORIZONTAL)

        self.stuffPanel = normalPanel(self.panel)
        self.stuffPanel.btn.Bind(wx.EVT_BUTTON, self.OnBtn)

        self.panel2 = modalPanel(self.panel)
        self.panel2.Hide()

        self.sizer.Add(self.stuffPanel, 0, wx.EXPAND)
        self.sizer.Add(self.panel2, 0, wx.EXPAND)
        self.panel.SetSizer(self.sizer)

    def OnBtn(self, event):
        self.stuffPanel.Hide()
        self.panel2.Show()

        self.sizer.Layout()

if __name__=='__main__':
    app=wx.App(False)
    frame=oranges()
    frame.Show()
    app.MainLoop()

rawDescription: How to get MessageDialog on exiting frame?

description: Get MessageDialog on exiting frame


code:
# in your init method
self.Bind(wx.EVT_LISTBOX_DCLICK, self.EvtListBoxDClick, self.mainlist)

# the callback
def EvtListBoxDClick(self, event):
     self.otherlist.Append(self.mainlist.GetSelection())
     self.mainlist.Delete(self.lb1.GetSelection())

rawDescription: Shuttle control in wxPython

description: Shuttle control in wxPython


code:
a
np.where(np.ma.getmaskarray(a))

rawDescription: Optimised call to retrieve indices of the masked elements of a masked array?


code: set((remove_version(filepath) for filepath in iter_file(dic1))) == set((remove_version(filepath) for filepath in iter_file(dic2)))

rawDescription: python - compare two directories recursively and flag equivalent structure

description: Python - compare two directories recursively and flag equivalent structure


rawDescription: How to get number of inputs from a form

description: Get number of inputs from a form


code:
from django_select2 import AutoModelSelect2TagField

class TagChoices(AutoModelSelect2TagField):
    queryset = Tag.objects
    search_fields = ['name__icontains']

    def get_model_field_values(self, value):
        return {'name': value }

class SimpleForm(forms.ModelForm):
    tags = TagChoices(required=False)

rawDescription: Manage tag with django-select2

description: Manage tag with django-select2


code:
class NewVisitorTest(unittest.TestCase):

    def setUp(self):
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        #self.testbed.setup_env(app_id='dermalfillersecrets')
        self.testbed.init_datastore_v3_stub()

        # setup the dev_appserver
        APP_CONFIGS = ['app.yaml']
        python_runtime._RUNTIME_ARGS = [
                    sys.executable,
                    os.path.join(os.path.dirname(dev_appserver.__file__),
                                 '_python_runtime.py')
        ]
        ######## This is the Where I moved the import clause ####
        from main import Customer
        #########################################################

        options = devappserver2.PARSER.parse_args([
            '--admin_port', '0',
            '--port', '9080',
            '--datastore_path', ':memory:',
            '--logs_path', ':memory:',
            '--skip_sdk_update_check',
            '--',
        ] + APP_CONFIGS)
        server = devappserver2.DevelopmentServer()
        server.start(options)
        self.server = server

        self.browser = webdriver.Firefox()
        self.browser.implicitly_wait(3)

rawDescription: Where does app get assigned? I keep getting BadArgumentError: app must not be empty


code:
average = m.mean(axis=1)
average
m/average

rawDescription: Normalize Numpy matrix rows by their average


code:
from math import floor

def sample(input, count):
    output = []
    sample_size = float(len(input)) / count
    for i in range(count):
        output.append(input[int(floor(i * sample_size))])
    return output

rawDescription: Array undersampling Python

description: Array undersampling Python


code: (a is b) and (b == b) and (b == a) and (a is c)

rawDescription: Unexpected behavior in Python with "is" operator


code:
def fetch_xml(url):
    """
    Fetch a url and parse the document's XML.

    :param url: the URL that the XML is located at.
    :return: the root element of the XML.
    :raises:
        :requests.exceptions.RequestException: Requests could not open the URL.
        :xml.etree.ElementTree.ParseError: xml.etree.ElementTree failed to parse the XML document.
    """

    return ET.fromstring(requests.get(url).content)

rawDescription: XML Parsing with ElementTree and Requests


code:
'''least square qbezier fit using penrose pseudoinverse
    >>> V=array
    >>> E,  W,  N,  S =  V((1,0)), V((-1,0)), V((0,1)), V((0,-1))
    >>> cw = 100
    >>> ch = 300
    >>> cpb = V((0, 0))
    >>> cpe = V((cw, 0))
    >>> xys=[cpb,cpb+ch*N+E*cw/8,cpe+ch*N+E*cw/8, cpe]
    >>>
    >>> ts = V(range(11))/10
    >>> M = bezierM (ts)
    >>> points = M*xys #produces the points on the bezier curve at t in ts
    >>>
    >>> control_points=lsqfit(points, M)
    >>> linalg.norm(control_points-xys)<10e-5
    True
    >>> control_points.tolist()[1]
    [12.500000000000037, 300.00000000000017]

'''
from numpy import array, linalg, matrix
from scipy.misc import comb as nOk
Mtk = lambda n, t, k: t**(k)*(1-t)**(n-k)*nOk(n,k)
bezierM = lambda ts: matrix([[Mtk(3,t,k) for k in range(4)] for t in ts])
def lsqfit(points,M):
    M_ = linalg.pinv(M)
    return M_ * points

rawDescription: Bézier curve fitting with SciPy

description: Bézier curve fitting with SciPy


code:
def set_colour(x, trigger=False):
    if trigger:
        return 'blue'
    elif x > 0.0:
        return 'green'
    elif x < 0.0:
        return 'red'
    else:
        return 'black'

rawDescription: Better way to check if value is bigger, smaller or equal zero in python


code:
import numpy as np
import matplotlib.colors as mcolors
import networkx as nx
import matplotlib.pyplot as plt
n = 10000  # Number of nodes
m = 3  # Number of initial links
seed = 500
G = nx.barabasi_albert_graph(n, m, seed)

ncols = 100
pos = {i : (i % ncols, (n-i-1)//ncols) for i in G.nodes()}

fig, ax = plt.subplots()
degrees = G.degree() #Dict with Node ID, Degree
nodes = G.nodes()
n_color = np.asarray([degrees[n] for n in nodes])
sc = nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_color=n_color, cmap='viridis',
                            with_labels=False, ax=ax, node_size=n_color)
# use a log-norm, do not see how to pass this through nx API
# just set it after-the-fact
sc.set_norm(mcolors.LogNorm())
fig.colorbar(sc)

rawDescription: Python: how to color the nodes of a network according to their degree?


code:
class graphicsScene(QtGui.QGraphicsScene):
    def __init__ (self, parent=None):
        super(graphicsScene, self).__init__ (parent)

    def mousePressEvent(self, event):
        super(graphicsScene, self).mousePressEvent(event)
        item = graphicsItem()
        position = QtCore.QPointF(event.scenePos()) - item.rectF.center()
        item.setPos(position.x() , position.y())
        self.addItem(item)

rawDescription: MousePressEvent, position offset in QGraphicsView


code:
import sys
if sys.version_info[0] < 3:
    from StringIO import StringIO
else:
    from io import StringIO

import pandas as pd

TESTDATA=StringIO("""col1;col2;col3
    1;4.4;99
    2;4.5;200
    3;4.7;65
    4;3.2;140
    """)

df = pd.read_csv(TESTDATA, sep=";")

rawDescription: How to create a Pandas DataFrame from String

description: Create a Pandas DataFrame from String


code:
readme_file = open("/pathto/somefile.txt")

for line in readme_file.xreadlines():
    if line.startswith("JIRA"):
        version_num = str(line).split()[1].split("-")[0]
        break
    else:
        continue
readme_file.close()

rawDescription: How can I write a python script to read a file and return the version

description: Write a python script to read a file and return the version


code:
import os, zipfile

def zipfiles(source_folder, destination_name):
    source_folder = os.path.abspath(source_folder)
    destination_path = os.path.abspath(destination_name)
    try:
        with zipfile.ZipFile(destination_name, 'w', zipfile.ZIP_DEFLATED) as zf:
            for dirname, subdirs, files in os.walk(source_folder):
                # zf.write(dirname) # not needed
                for filename in files:
                    filepath = os.path.join(dirname, filename)
                    if filepath != destination_path:
                        zf.write(filepath)
    except Exception as e:
        print(e)

def main():
   x = ''
   while not x:
       x = raw_input('Enter source folder name: ')
   y = ''
   while not y:
       y = raw_input('Enter destination archive file name: ')
   zipfiles(x, y+'.zip')

main()

rawDescription: Why compression output larger zip file

description: Why compression output larger zip file


code:
# generator version
def collect_sum(iterable,n):
  for e in range(1,len(iterable)+1):
    if e%n==0:
      yield sum(iterable[e-n:e])

# list comprehension version
def collect_sum(iterable,n):
  return [sum(iterable[e-n:e]) for e in range(1,len(iterable)+1) if e%n==0]

for i in collect_sum(range(1,21),5):
  print(i,end=' ')

rawDescription: How do I convert this into a comprehension? (Python)

description: Convert this into a comprehension? (Python)


code:
try:
    finder()
except KeyboardInterrupt:
    pass

rawDescription: Escaping within nested functions

description: Escaping within nested functions


code:
import threading

class ConnectedClients(threading.Thread):

    used_ressources = list()
    used_ressources_lock = threading.Lock()

    def run(self, ressource_to_get):
        if ressource_to_get in used_ressources:
            raise Exception('Already used ressource:' + repr(ressource_to_get))
        else:
            can_access = self.used_ressources_lock.acquire(blocking=True, timeout=5)
            if can_access:
                self.used_ressources.append(ressource_to_get)
                self.used_ressources_lock.release()
                # Do something...
                # You will have to acquire lock and remove ressource from
                # the list when you're done with it.
            else:
                raise Exception("Cannot acquire lock")

rawDescription: Sending commands to running python progress


code:
def tictactoe_state(moves):
  for r in range(len(moves)):
    for c in range(len(moves[r])):
      if moves[0][c] == moves[1][c] == moves[2][c]:
        return "'%s' wins (%s)." % (moves[0][c], 'vertical')
      elif moves[r][0] == moves[r][1] == moves[r][2]:
        return "'%s' wins (%s)." % (moves[r][0], 'horizontal')
      elif moves[0][0] == moves[1][1] == moves[2][2]:
        return "'%s' wins (%s)." % (moves[0][0], 'diagonal')
      elif moves[0][2] == moves[1][1] == moves[2][0]:
        return "'%s' wins (%s)." % (moves[0][2], 'diagonal')

  # You still have to make sure the game isn't a draw.
  # To do that, see if there are any blank squares.

  return 'Still playing'

rawDescription: pyschools-tictactoe

description: Pyschools-tictactoe


code:
from Bio import SeqIO
import re

with open('output.txt', 'w') as outFile: # open for writing
    for i in SeqIO.parse('input.txt', 'fasta'): # parse as FASTA
        m = re.search('sp\|(.*)\|', i.id) # look for sp|.*| in the id
        if m:
            outFile.write(m.group(1).split('.')[0] + '\n') # take only what's before the first dot, if any

rawDescription: Search and import multiple words from txt file on Biopython


rawDescription: Replacements for switch statement in Python?


code:
import os
from os.path import join, getsize

file_list = []
for root, dirs, files in os.walk('Test'):
    file_list.extend( join(root,f) for f in files )
    #May be *slightly* faster at the expense of a little readability
    # and a little memory
    # file_list.extend( [ join(root,f) for f in files ] )

print (sorted(file_list, key=getsize))

rawDescription: How to get list of all sub directories and files along with their size ordered by size?

description: Get list of all sub directories and files along with their size ordered by size


code:
from tkinter import *
import random, math

class master():
    def __init__(self):
        self.mySim = simulation(self)
        self.myGUI = GUI(self)
        self.myGUI.menu.mainloop()
    def startSim(self, newdata):
        self.mySim.start(newdata)

class GUI():
    def __init__(self, master):
        self.myMaster = master
        self.menu = Tk()
        self.menu.title("Menu")
        self.createMainGUI()

    def createMainGUI(self):
        #Create Menu
        self.catalyst = Checkbutton(self.menu, text = "Catalyst", anchor = 'w', justify = LEFT)
        self.temperature = Scale(self.menu, from_=0, to=1000, orient = HORIZONTAL)
        self.concA = Scale(self.menu, from_=1, to=50, orient = HORIZONTAL)
        self.concB = Scale(self.menu, from_=1, to=50, orient = HORIZONTAL)
        self.start = Button(self.menu, text="Start", width=5, height=2)
        self.exit = Button(self.menu, text="Exit", width = 5, height=2)
        self.title = Label(self.menu, text = "Chemistry reaction model", width = 20, height = 2)
        self.option = Label(self.menu, text = "Options:", width = 10, height = 2, anchor = 'w', justify = LEFT)
        self.temperaturelabel = Label(self.menu, text = "Temperature in Kelvin:")
        self.concALabel = Label(self.menu, text = "Concentration of A:")
        self.concBLabel = Label(self.menu, text = "Concentration of B:")

        #Format Menu
        self.title.grid(column = 1, row = 1, columnspan = 3)
        self.option.grid(column = 1, row = 2)
        self.catalyst.grid(column = 1, row = 3)
        self.temperature.grid(column = 2, row = 4, columnspan = 2)
        self.concA.grid(column = 2, row = 5, columnspan = 2)
        self.concB.grid(column = 2, row = 6, columnspan = 2)
        self.start.grid(column = 1, row = 7)
        self.exit.grid(column = 2, row = 7)
        self.temperaturelabel.grid(column =1, row = 4)
        self.concALabel.grid(column =1, row = 5)
        self.concBLabel.grid(column =1, row = 6)

        #Event Handlers
        self.start.bind('<Button-1>', self.startSimulationGUI)
        self.exit.bind('<Button-1>', self.quit)

    def update_canvas(self, particles):
        self.canvas.delete('all') #clears canvas and redraws all particles at new positions
        for i in particles:
            self.canvas.create_oval(i.x, i.y, i.x+i.size,i.y+i.size , fill = "red")

    def quit(self, event):
        self.menu.destroy()

    def startSimulationGUI(self, event):
        self.simGUI = Toplevel(master=self.menu)
        self.simGUI.title("Simulation")
        self.canvas = Canvas(self.simGUI)
        self.canvas.grid(column = 0, row = 1)
        self.canvas.config(width = 400, height=400, bg = "Ghost White")
        # (0,0) is the top left and  (400, 400) is the bottom right coordinates
        self.Toolbar = LabelFrame(self.simGUI, relief = RAISED, width = 200, height = 50, padx = 105)
        self.Toolbar.grid(column = 0, row =2)
        self.Toolbar.config()

        self.MenuExit = Button(self.Toolbar, text="Quit to Menu")
        self.MenuExit.grid(row = 0, column = 0)
        self.MenuExit.bind('<Button-1>', self.simExit)

        self.time = Label(self.Toolbar, text ="Timer:", padx = 30)
        self.time.grid(row = 0, column = 1)

        #Get Data
        newdata = data()
        newdata.temp = self.temperature.get()
        newdata.catalyst = self.catalyst.getint()
        newdata.concA = self.concA.get()
        newdata.concB = self.concB.get()
        newdata.temperature = self.temperature.get() ###
        self.myMaster.startSim(newdata)

    def simExit(self, event):
        self.simGUI.destroy()
        self.myMaster.mySim.particles.clear() #makes sure that if the user exits, changes the settings and restarts no extra particles are drawn

class simulation():
    def __init__(self, master):
        self.particles = []
        self.myMaster = master
        #self.myParticleData = data()
        #self.myParticle = particle(0,0) ###

    def start(self, myParticleData):
        self.myParticleData = myParticleData
        for i in range(0, self.myParticleData.concA):
            self.particles.append(particle(random.randint(0,400),random.randint(0,400),self.myParticleData.temperature)) ###
        for i in range(0, self.myParticleData.concB):
            self.particles.append(particle(random.randint(0,400),random.randint(0,400),self.myParticleData.temperature)) ###
        self.myMaster.myGUI.update_canvas(self.particles)
        self.animate()

    def animate(self):
        for i in self.particles:
            i.walls()
            i.move()
        self.myMaster.myGUI.update_canvas(self.particles)
        self.myMaster.myGUI.menu.after(100, self.animate)

class particle():
    def __init__(self, x, y, temp): ###
        self.x = x
        self.y = y
        self.temp = temp ###
        #self.tag = a or b or c
        self.speed = 0
        self.direction = 0
        self.myGUI = GUI
        self.size = 5
        self.myParticleData= data()
        #self.hyp = sqrt(self.size**2+self.size**2)

    def move(self):
        self.direction = random.randint(0, 360)
        self.x += math.sin(self.direction) * .1 * self.temp     ###
        self.y -= math.cos(self.direction) * .1 * self.temp     ###

    def walls(self):
        if self.x > 390 - self.size:
            self.x = 2*(400 - self.size) - self.x
            self.direction = -self.direction

        elif self.x < 10+self.size:
            self.x = 2*self.size - self.x
            self.direction = - self.direction

        if self.y > 390 - self.size:
            self.y = 2*(400 - self.size) - self.y
            self.direction = 180 - self.direction

        elif self.y < 10 + self.size:
            self.y = 2*self.size - self.y
            self.direction = 180 - self.direction

class data():
    def __init__(self):
        self.temp = None
        self.concA = None
        self.concB = None
        self.catalyst = None

if __name__ == '__main__':
    x = master()

rawDescription: Getting value from GUI and using it in another class


code:
from mock import MagicMock
import inspect

class _WrappedMagicMock(MagicMock):
    def __init__(self, *args, **kwds):
        object.__setattr__(self, '_mockclass_wrapper', None)
        super(_WrappedMagicMock, self).__init__(*args, **kwds)

    def wrap(self, cls):
        # get defined attribtues of spec class that need to be preset
        base_attrs = dir(type('Dummy', (object,), {}))
        attrs = inspect.getmembers(self._spec_class)
        new_attrs = [a[0] for a in attrs if a[0] not in base_attrs]

        # pre set mocks for attributes in the target mock class
        for name in new_attrs:
            setattr(cls, name, getattr(self, name))

        # eat up any attempts to initialize the target mock class
        setattr(cls, '__init__', lambda *args, **kwds: None)

        object.__setattr__(self, '_mockclass_wrapper', cls)

    def unwrap(self):
        object.__setattr__(self, '_mockclass_wrapper', None)

    def __setattr__(self, name, value):
        super(_WrappedMagicMock, self).__setattr__(name, value)

        # be sure to reflect to changes wrapper class if activated
        if self._mockclass_wrapper is not None:
            setattr(self._mockclass_wrapper, name, value)

    def _get_child_mock(self, **kwds):
        # when created children mocks need only be MagicMocks
        return MagicMock(**kwds)

class A(object):
    x = 1

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

    def get_value_direct(self):
        return self.value

    def get_value_indirect(self):
        return self.value

class B(A):
    def __init__(self, value):
        super(B, self).__init__(value)

    def f(self):
        return 2

    def get_value_direct(self):
        return A.get_value_direct(self)

    def get_value_indirect(self):
        return super(B, self).get_value_indirect()

# nominal behavior
b = B(3)
assert b.get_value_direct() == 3
assert b.get_value_indirect() == 3
assert b.f() == 2
assert b.x == 1

# using mock class
MockClass = type('MockClassWrapper', (), {})
mock = _WrappedMagicMock(A)
mock.wrap(MockClass)

# patch the mock in
B.__bases__ = (MockClass, )
A = MockClass

# set values within the mock
mock.x = 0
mock.get_value_direct.return_value = 0
mock.get_value_indirect.return_value = 0

# mocked behavior
b = B(7)
assert b.get_value_direct() == 0
assert b.get_value_indirect() == 0
assert b.f() == 2
assert b.x == 0

rawDescription: How do I directly mock a superclass with python mock?

description: Directly mock a superclass with python mock


code: subparsers = parser.add_subparsers(title="Commands", metavar="<command>")

rawDescription: Argparse python, remove subparser list in help menu


code:
def home(request):
    templatename="login.html"
    if request.method=="POST":
        u=request.POST.get("username")
        p=request.POST.get("password")
        user=authenticate(username=u, password=p)
        if user is not None:
            if user.is_active:
                state="This User is valid, active and authenticated"
                login(request,user)
                return HttpResponseRedirect("/welcome/")
            else:
                state="This User is valid but the account has been disabled"
        else:
            state="The Username and Password entered were incorrect"
    else:
        user=None
    return render_to_response(templatename,{'user': user,'state':state},RequestContext(request))

rawDescription: How to raise a note on the html page

description: Raise a note on the html page


code:
import matplotlib.pyplot as plt
plt.rcParams['keymap.save']
plt.rcParams['keymap.save'] = ''

rawDescription: How do I disable the keyboard shortcuts in Matplotlib?

description: Disable the keyboard shortcuts in Matplotlib


code:
from Tkinter import Button, END, Listbox, Tk
from time import sleep

root = Tk()

# My version of Tkinter doesn't have a MultiListbox
# So, I use its closest alternative, a regular Listbox
listbox = Listbox(root)
listbox.pack()

def start():
    """This is where your loop would go"""

    for i in xrange(100):
        # The sleeping here represents a time consuming process
        # such as making a PDF
        sleep(2)

        listbox.insert(END, i)

        # You must update the listbox after each entry
        listbox.update()

# You must create a button to call a function that will start the loop
# Otherwise, the display won't appear until after the loop exits
Button(root, text="Start", command=start).pack()

root.mainloop()

rawDescription: Tkinter box packing in loop is slow

description: Tkinter box packing in loop is slow


code:
def displayMessageInbox(mf, c, vm):
    recipient = config.nameInput

    cursor.execute("""SELECT m.id, CONCAT('Title: ', m.title, '\n',
                    'From: ', s.sender, '\n',
                    'Sent: ', s.timeSent) As messagetxt
                    FROM Message m
                    INNER JOIN SentMessage s ON m.id = s.messageID
                    WHERE s.recipient = %s""", (recipient))

    i = 3
    for message in cursor.fetchall():
          mID = message[0]
          messagetxt = message[1]
          ...

          if (viewReply == somevalue): # ENTER LOGIC TO CAPTURE WHICH MESSAGE USER SELECTED
                 readMessage(mf, mID)

def readMessage(mf, mID):

    cursor.execute("""SELECT CONCAT('From: ', sm.sender, '\n',
            'Title: ', m.title, '\n',
            'Message: ', m.content)
            FROM Message m
            INNER JOIN SentMessage sm ON m.id = sm.messageID
            WHERE m.id = %s""", (mID))
    rows = cursor.fetchone()

    message = rows[0]
    ...

rawDescription: Python/MySQL: Select data in a for loop

description: Python/MySQL: Select data in a for loop


code:
# after app creation, but before the views
SimpleTemplate.defaults["get_url"] = app.get_url
SimpleTemplate.defaults["url"] = lambda: request.url
SimpleTemplate.defaults["fullpath"] = lambda: request.fullpath
SimpleTemplate.defaults["sorted"] = sorted

rawDescription: Include variables in template context on every page with Bottle.py


code:
class MyClass(object):
    def entry_deletion_images_delete(self, sender, instance, using, **kwargs):
        ...

instance = MyClass()
pre_delete.connect(instance.entry_deletion_images_delete, sender=Document, dispatch_uid='document_delete_signal')

rawDescription: passing self to a function

description: Passing self to a function


code:
a, (b, c) = None
a, (b, c) = ('foo', None)

rawDescription: GeocoderDotUS Geopy ('NoneType' object is not iterable)


code:
class MyPanel(wx.Panel):

    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.Bind(wx.EVT_PAINT, self.OnPaint)

        self.loc = wx.Bitmap("intro/image.png")

    def OnPaint(self, evt):
        dc = wx.PaintDC(self)
        dc.SetBackground(wx.Brush("WHITE"))

        # ... drawing here all other images in order of overlapping
        dc.DrawBitmap(self.loc, 0, 0, True)

rawDescription: wx.StaticBitmap - simple transparency (mask, png, bmp?)

description: Wx.StaticBitmap - simple transparency (mask, png, bmp?)


code:
tips = sns.load_dataset("tips")
tips["all"] = ""
ax = sns.violinplot(x="all", y="total_bill", hue="sex", data=tips, split=True)
ax.set_xlabel("")

rawDescription: split violinplot in seaborn with hue parameter

description: Split violinplot in seaborn with hue parameter


rawDescription: How to take same index element from a list with 2 lists

description: Take same index element from a list with 2 lists


code:
for s, c in zip(date_list, count_list):
    self.cursor.execute(
        'INSERT INTO ufo_info(date, count) VALUES (%s, %s);'
        , (s, c)
    )

rawDescription: Multiple insert statements failing postgresql / psycopg2


code:
def thing(list_):
  temp = enumerate(max(x) - min(x) for x in list_)
  return max(x[::-1] for x in temp)

rawDescription: Returning index of list with greatest value


code:
msg = email.message_from_string('\n'.join([
    'To: michael@mydomain.com',
    'From: michael@mydomain.com',
    'Subject: test email',
    '',
    'Just testing'
]))
smtp = smtplib.SMTP()
smtp.connect()
smtp.sendmail('something@something.com', 'michael@mydomain.com', msg.as_string())

rawDescription: Setting Return-Path with Python sendmail for a MIME message


code:
from collections import Counter
import re
import csv

cnt = Counter()

writefile = open('test1.csv', 'wb')
writer = csv.writer(writefile)

with open('screenplay.txt') as file:
    text = file.read().lower()
    text = re.sub('[^a-z\ \']+', " ", text)
    words = list(text.split())
    for word in words:
        cnt[word] += 1
    for key, count in cnt.iteritems(): #De-dent this block
        writer.writerow([key,count]) #Output both the key and the count

writefile.close() #Make sure to close your file to guarantee it gets flushed

rawDescription: Exporting Python Counter to .CSV file

description: Exporting Python Counter to .CSV file


code:
from sqlite3 import connect

conn = connect("/path/to/your/sqlite.db")
# Do what you need to with the database here
# Changes (inserts, updates, etc) will be persisted
# to disk whenever you commit a transaction.

rawDescription: Get sqlite3 database from disk, load it to memory, and save it to disk?


code:
l = [{'label_1': 'labelone', 'value_1': 'valueone', 'label_2': 'label two', 'value_2':'v2'}]

values = int(len(l[0])/2)
dicts = []
for i in range(values):
    label_name = 'label_%s' % (i+1)
    value_name = 'value_%s' % (i+1)
    dicts.append({'label':l[0][label_name], 'value':l[0][value_name]})

rawDescription: Parse html form into a list of dicts in python / Flask


code: [d for d in list_products if sum(bool(v) for v in d.values()) > 2]

rawDescription: Filter list of dictionaries if at least x keys have empty value


code:
def returnIDs(IDfile):# extract the IDs
    IDs = set()
    with open(IDfile) as f:
        reader = csv.DictReader(f, fieldnames=['ID', 'other', 'fields'])
        for row in reader:
            IDs.add(row['ID'])
    return list(IDs)

rawDescription: How to extract values from CSV file without headers?

description: Extract values from CSV file without headers


code:
from PyQt4 import QtCore, QtGui

class PhotoViewer(QtGui.QGraphicsView):
    def __init__(self, parent):
        super(PhotoViewer, self).__init__(parent)
        self._zoom = 0
        self._scene = QtGui.QGraphicsScene(self)
        self._photo = QtGui.QGraphicsPixmapItem()
        self._scene.addItem(self._photo)
        self.setScene(self._scene)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
        self.setFrameShape(QtGui.QFrame.NoFrame)

    def fitInView(self):
        rect = QtCore.QRectF(self._photo.pixmap().rect())
        if not rect.isNull():
            unity = self.transform().mapRect(QtCore.QRectF(0, 0, 1, 1))
            self.scale(1 / unity.width(), 1 / unity.height())
            viewrect = self.viewport().rect()
            scenerect = self.transform().mapRect(rect)
            factor = min(viewrect.width() / scenerect.width(),
                         viewrect.height() / scenerect.height())
            self.scale(factor, factor)
            self.centerOn(rect.center())
            self._zoom = 0

    def setPhoto(self, pixmap=None):
        self._zoom = 0
        if pixmap and not pixmap.isNull():
            self.setDragMode(QtGui.QGraphicsView.ScrollHandDrag)
            self._photo.setPixmap(pixmap)
            self.fitInView()
        else:
            self.setDragMode(QtGui.QGraphicsView.NoDrag)
            self._photo.setPixmap(QtGui.QPixmap())

    def zoomFactor(self):
        return self._zoom

    def wheelEvent(self, event):
        if not self._photo.pixmap().isNull():
            if event.delta() > 0:
                factor = 1.25
                self._zoom += 1
            else:
                factor = 0.8
                self._zoom -= 1
            if self._zoom > 0:
                self.scale(factor, factor)
            elif self._zoom == 0:
                self.fitInView()
            else:
                self._zoom = 0

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window, self).__init__()
        self.viewer = PhotoViewer(self)
        self.edit = QtGui.QLineEdit(self)
        self.edit.setReadOnly(True)
        self.button = QtGui.QToolButton(self)
        self.button.setText('...')
        self.button.clicked.connect(self.handleOpen)
        layout = QtGui.QGridLayout(self)
        layout.addWidget(self.viewer, 0, 0, 1, 2)
        layout.addWidget(self.edit, 1, 0, 1, 1)
        layout.addWidget(self.button, 1, 1, 1, 1)

    def handleOpen(self):
        path = QtGui.QFileDialog.getOpenFileName(
            self, 'Choose Image', self.edit.text())
        if path:
            self.edit.setText(path)
            self.viewer.setPhoto(QtGui.QPixmap(path))

if __name__ == '__main__':

    import sys
    app = QtGui.QApplication(sys.argv)
    window = Window()
    window.setGeometry(500, 300, 800, 600)
    window.show()
    sys.exit(app.exec_())

rawDescription: How to enable Pan and Zoom in a QGraphicsView

description: Enable Pan and Zoom in a QGraphicsView


code:
def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if('query' in filters):
        query = filters['query']
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        orm_filters.update({'custom': qset})

    return orm_filters

def apply_filters(self, request, applicable_filters):
    if 'custom' in applicable_filters:
        custom = applicable_filters.pop('custom')
    else:
        custom = None

    semi_filtered = super(BusinessResource, self).apply_filters(request, applicable_filters)

    return semi_filtered.filter(custom) if custom else semi_filtered

rawDescription: Django Tastypie Advanced Filtering: How to do complex lookups with Q objects


code:
with open('file.txt') as f:
    result = [line.split('\t', 1)[0] for line in f]

result

rawDescription: Reading each line form a text file and determining if it has another letter


code:
text = file.read()
text = re.sub(r'[.,:;-_]', '', text)
text = text.upper()
words = re.split(r'\\s+', text)
c = Counter()
c.update(words)

rawDescription: Is it possible to make this shell script faster?


code:
import requests
import os
import re

arc='Diabolik Lovers - 12.mp4'
sessionObj = requests.session()
sessionObj.post('http://bestream.tv/login.html', data={'loginUsername':'my_user', 'loginPassword':'my_pass', 'submitme':'1'})
filehandle = open(arc, 'rb')

resp = sessionObj.get('http://bestream.tv/account_home.html')

url_form = re.search('url: \'(http:\/\/.*)?\'', resp.text).group(1)

tam = os.path.getsize(arc)
l = 0
n = 0
headers={}

while l < tam:
    start = n*100000000
    if start+99999999 < tam:
        stop = min(start+99999999, tam)
    else:
        stop = tam-1
    contentrange = 'bytes {}-{}/{}'.format(start, stop, tam)
    headers['Content-Range'] = contentrange
    filehandle.seek(start)
    fi = 'file_%s' % n
    filehandle2 = open(fi, 'wb')
    f=filehandle.read(100000000)
    filehandle2.write(f)
    filehandle2.close()
    ff=open(fi, 'rb')
    r = sessionObj.post(url_form, headers=headers, files = {'files[]': (filehandle.name, ff)})
    ff.close()
    os.remove(fi)
    l+=len(f)
    n+=1

rawDescription: Python - As I can upload the file into several pieces to the server?


code:
import codecs
BLOCKSIZE = 1048576 # or some other, desired size in bytes
with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile:
    with codecs.open(targetFileName, "w", "utf-8") as targetFile:
        while True:
            contents = sourceFile.read(BLOCKSIZE)
            if not contents:
                break
            targetFile.write(contents)

rawDescription: How to convert a file to utf-8 in Python?

description: Convert a file to utf-8 in Python


code:
# spawn a subprocess.
# then wait for expected output from the child process,
# and send additional commands to the child.

child = pexpect.spawnu('ftp ftp.openbsd.org')
child.expect('(?i)name .*: ')
child.sendline('anonymous')
child.expect('(?i)password')
child.sendline('pexpect@sourceforge.net')
child.expect('ftp> ')
child.sendline('cd /pub/OpenBSD/3.7/packages/i386')
child.expect('ftp> ')

rawDescription: Repeatedly interacting with program using subprocess


rawDescription: Pythonic way to check if number falls in a certain range


code:
import wx
import wx.lib.agw.foldpanelbar as fpb
import wx.lib.scrolledpanel as scrolled

class MyPanel(scrolled.ScrolledPanel):

    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent=parent,
                                        size=parent.GetSize(),
                                        style = wx.ALL|wx.EXPAND)
        #self.SetAutoLayout(1)
        self.SetupScrolling()
        self.boxSizer = wx.BoxSizer(wx.VERTICAL)
        csStyle = fpb.CaptionBarStyle()
        csStyle.SetFirstColour(wx.Colour(190, 190, 190, 255))
        csStyle.SetSecondColour(wx.Colour(167, 232, 146, 255))
        csStyle.SetCaptionFont(wx.Font(9, wx.DEFAULT, wx.NORMAL, wx.BOLD))

        m_pnl = fpb.FoldPanelBar(self, wx.ID_ANY, wx.DefaultPosition, (600,800),
                            fpb.FPB_VERTICAL)

        item = m_pnl.AddFoldPanel("Set 1", collapsed=True, cbstyle=csStyle)

        self.listContainer = wx.ListCtrl(item, style=wx.LC_REPORT)
        self.listContainer.InsertColumn(0, 'Column1', width=250)
        self.listContainer.InsertColumn(1, 'Column2', width=150)
        self.listContainer.InsertColumn(2, 'Column3')

        m_pnl.AddFoldPanelWindow(item, self.listContainer)
        btnAutoFix = wx.Button(item, wx.ID_ANY, "Go", size=(50,-1))
        m_pnl.AddFoldPanelWindow(item, btnAutoFix)
        self.boxSizer.Add(m_pnl)

        item = m_pnl.AddFoldPanel("Set 2", collapsed=True, cbstyle=csStyle)
        self.listContainer2 = wx.ListCtrl(item, style=wx.LC_REPORT)
        self.listContainer2.InsertColumn(0, 'Column1', width=250)
        self.listContainer2.InsertColumn(1, 'Column2', width=150)
        self.listContainer2.InsertColumn(2, 'Column3')

        m_pnl.AddFoldPanelWindow(item, self.listContainer2)

        self.pnl = m_pnl
        self.SetSizer(self.boxSizer)

class MainFrame(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, title='Test')
        panel = MyPanel(self)
        self.Show()

if __name__ == '__main__':
    app = wx.App(False)
    frame = MainFrame()
    app.MainLoop()

rawDescription: Scrollbars are not appearing on expanding FoldPanelBar in wxPython


code:
from collections import Counter
counts = Counter([-1,2,3,-1,3,4,4,4,4,4])
counts.viewvalues() # counts.values() in Python 3+

rawDescription: exact histogram of an array

description: Exact histogram of an array


code:
def index(request):
    def do_work():
        step_1()
        yield "step 1 complete"
        step_2()
        yield "step 2 complete"
        step_3()
        yield "step 3 complete"
    return HttpResponse(do_work())

rawDescription: Django - flush response?

description: Django - flush response


code:
def execu(lst, seq, raw_para):
  return reduce(lambda x, y: y(x), reversed(operator.itemgetter(*seq)(lst)), raw_para)

rawDescription: python function list chained executing?

description: Python function list chained executing


code:
response = HttpResponse(mimetype="image/png")
# create your image as usual, e.g. pylab.plot(...)
pylab.savefig(response, format="png")
return response

rawDescription: Returning MatPotLib image as string

description: Returning MatPotLib image as string


code:
particles = np.vstack([xA, xB, xC])
rot = rotation_matrix(axis, angle)
rotated = np.dot(rot, particles)
xA, yA, zA = rotated

rawDescription: How to speed up rotation operations in Python?

description: Speed up rotation operations in Python


code:
import pandas as pd
from calendar import isleap
dates = pd.date_range("2001-01-01", "2012-12-31")
pd.DatetimeIndex(data=(t for t in dates if not isleap(t.year)), freq="D")

rawDescription: Exclude leap year days from date_range in pandas


code:
# this will remove minimized status
# and restore window with keeping maximized/normal state
window.setWindowState(window.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)

# this will activate the window
window.activateWindow()

rawDescription: How to make a PyQT4 window jump to the front?

description: Make a PyQT4 window jump to the front


code:
track_data['recent_tracks'] = [
    {"artist": x.track.artist.name, "title": x.track.title}
    for x in recent_tracks
]

rawDescription: JSON dumping an object with two inner objects


code:
def doWork(self, prueba):
    prueba.read(callback=self.catchValue)
    return True

rawDescription: Collecting a value of a function

description: Collecting a value of a function


code:
for aline in sorted(mf2):
    mf3.write(aline)
mf3.close()

rawDescription: Python: Organizing a Text File

description: Python: Organizing a Text File


rawDescription: I want collect all characters and events that end with a certain text?


code:
number_of_integers = int(input('Number of integers: '))
data = input('Input values separated by spaces: ')
values = data.split()
if number_of_integers != len(values):
    print('Wrong number of values')
else:
    print(max(map(int, values)))

rawDescription: Python string and integer

description: Python string and integer


code:
from pylab import *

L1 = ['London', 'Paris', 'Tokio', 'Berlin', 'Barcelona', 'Reykjavik']
pos = arange(len(L1))
yticks(pos, L1)

I1 = [['London',0],['Paris',10],['Barcelona',23]]
I2 = [['Paris',10],['Tokio',19],['Berlin',21],['Reykjavik',23]]

I1_y = [L1.index(el[0]) for el in I1]
I1_x = [el[1] for el in I1]

I2_y = [L1.index(el[0]) for el in I2]
I2_x = [el[1] for el in I2]

plot(I1_x, I1_y, 'o-')
plot(I2_x, I2_y, 'x-')
grid(True)
savefig('countries.png')
show()

rawDescription: Pyplot Mapping <string,number> pairs on graph matrix


code:
class recursive_summer:
    def __init__(self, lst=[]):
        self.lst = lst
    def recursive_sum(self):
        return self.recursive_sum_helper(self.lst)
    def recursive_sum_helper(self, a_lst):
        if len(a_lst) == 1:
            return a_lst[0]
        else:
            first_element = a_lst[0]
            list_without_first_element = a_lst[1:]
            return first_element + self.recursive_sum_helper( list_without_first_element )

r = recursive_summer([1,2,3,4])
r.recursive_sum()

rawDescription: Using recursion in a class

description: Using recursion in a class


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

np.random.seed(101)
a = np.random.normal(size=1000)
b = np.random.normal(size=1000)
c = np.random.normal(size=1000)

common_params = dict(bins=20,
                     range=(-5, 5),
                     normed=True)

plt.subplots_adjust(hspace=.4)
plt.subplot(311)
plt.title('Default')
plt.hist(a, **common_params)
plt.hist(b, **common_params)
plt.hist(c, **common_params)
plt.subplot(312)
plt.title('Skinny shift - 3 at a time')
plt.hist((a, b, c), **common_params)
plt.subplot(313)
common_params['histtype'] = 'step'
plt.title('With steps')
plt.hist(a, **common_params)
plt.hist(b, **common_params)
plt.hist(c, **common_params)

plt.savefig('3hist.png')
plt.show()

rawDescription: Displaying 3 histograms on 1 axis in a legible way - matplotlib


code:
query = session.query(
    Account,
    case([(FollowAssociation.follower_id == None, False)], else_=True).label('first'),
    case([(ali.follower_id == None, False)], else_=True).label('second')
).outerjoin(
    FollowAssociation,
    and_(Account.id == FollowAssociation.followee_id, FollowAssociation.follower_id == 1)
).outerjoin(ali, and_(Account.id == ali.follower_id, ali.followee_id == 1))

class CustomAccount(object):
    pass

mapper(CustomAccount, query.statement.alias())

res = session.query(CustomAccount).all()
print(res[0].id)
print(res[0].first)

rawDescription: SQLAlchemy mapping case statements into model fields


code:
a="/foo/bar/boz"
import os
os.path.relpath(a, '/foo')

rawDescription: Use os.path to remove element in path

description: Use os.path to remove element in path


code:
e = ET.Element('p')
# you set the text to hello first
e.text = "hello "
# and you set a subelement with br, which is what you want
br = ET.SubElement(e, 'br')
# then using tail to append the text after br
br.tail = ' world'

...

rawDescription: how to print new line in elementtree's Element().text

description: Print new line in elementtree's Element().text


code:
name = raw_input("What is your name?")
myFile = open(name + ' score.txt', 'w')
myFile.write('Score: 6')
myFile.close()

rawDescription: Creating files in python

description: Creating files in python


rawDescription: How to write (long) integer values to Berkeley DB using bsddb3?

description: Write (long) integer values to Berkeley DB using bsddb3


code:
plt.subplots_adjust(top=0.9)
g.fig.suptitle('THIS IS A TITLE, YOU BET') # can also get the figure from plt.gcf()

rawDescription: How to add a title to Seaborn Facet Plot

description: Add a title to Seaborn Facet Plot


code:
from distutils import setup
import os

for path in [my_package_directories]:
    filename = os.path.join(pagh, '__init__.py')
    if not os.path.exists(filename):
        init = open(filename, 'w')
        init.close()

setup(
...
)

rawDescription: Can distutils create empty __init__.py files?


code:
i = 0
m = ''
while i < len(s):
    m += ch2 if s[i] == ch else s[i]
    i += 1

return m

rawDescription: Python: Return string using while loop (no methods or for loops)


code:
import re
re.sub('(StartNum)(.*)(/StartNum)', r"\1boop\3", 'StartNumbworp/StartNum')

rawDescription: python change string between certain two words

description: Python change string between certain two words


code:
import webbrowser

url = 'http://docs.python.org/'

# MacOS
chrome_path = 'open -a /Applications/Google\ Chrome.app %s'

# Windows
# chrome_path = 'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe %s'

# Linux
# chrome_path = '/usr/bin/google-chrome %s'

webbrowser.get(chrome_path).open(url)

rawDescription: Python webbrowser.open() to open Chrome browser


code:
import string
d = dict.fromkeys(string.ascii_lowercase, 0)

rawDescription: Is there a fast way to generate a dict of the alphabet in Python?


code:
#!/usr/bin/python

import sys
from PyQt4 import QtGui, QtCore

app = QtGui.QApplication(sys.argv)

w = QtGui.QComboBox()
w.setEditable(True)
c = QtGui.QCompleter(['Hello', 'World'])
c.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
c.popup().setStyleSheet("background-color: yellow")
w.setCompleter(c)
w.show()

sys.exit(app.exec_())

rawDescription: Styling the popup of a QCompleter in PyQt


rawDescription: How can I increment only the first element of the first row of a Python list of lists?

description: Increment only the first element of the first row of a Python list of lists


code:
def do_my_stuff(numbers):
    def is_even(i):
        return i % 2 == 0

    # use is_even, where it can be trivially referenced above
    return map(numbers, is_even)

rawDescription: Why does Python not have an 'is even' method for integers and what should I do about it?


code:
from sympy import *
variables = symbols('x y z')
equations = [3*x-z+2, y-3*z-5, x+y-z]
A, b = linear_eq_to_matrix(equations, variables)
linsolve((A, b), variables)

rawDescription: "GenerateMatrix" equivalent command in SymPy


code:
from tkinter import *
from tkinter import ttk

# Create Tk Interface root
root = Tk()

# Initialize mainFrame
mainFrame = ttk.Frame( root )
mainFrame.grid()

# Initialize label of mainframe
theLabel = ttk.Label( mainFrame, text='Current Message' )
theLabel.grid( padx=10, pady=10 )

def createPopup():
    # Initialize popup window
    popup = Toplevel( mainFrame )
    popup.grid()
    # Initialize text box of popup window
    textBox = Text( popup, width=20, height=5 )
    textBox.grid( column = 0, row = 0 )
    textBox.insert( END, 'New Message Here' )
    # Initialize button of popup window
    button = ttk.Button( master  = popup,
                         command = lambda: theLabel.config(text=textBox.get(0.0, END)),
                         text = 'Update')
    button.grid( column=0, row=1, padx=5, pady=5 )

# Initialize button of main frame
theButton = ttk.Button( mainFrame, command=createPopup, text='Click' )
theButton.grid( padx=10, pady=10 )

# Enter event loop
mainFrame.mainloop()

rawDescription: Python tkinter: access child widgets of a widget


code:
TEXT_ADDITIONAL_TAGS = ('iframe',)
TEXT_ADDITIONAL_ATTRIBUTES = ('scrolling', 'allowfullscreen', 'frameborder', 'src', 'height', 'width')

rawDescription: How to use iframes in django-cms

description: Use iframes in django-cms


code:
#!usr/bin/python
import glob
import re

for infileName in glob.glob("*.xml"):
    # Open Source File
    infile = open(infileName, 'r')
    # Append to file
    outfile = open('ExtractedIPs.csv', 'a')
    # Create a list
    BadIPs = []

    #search each line in doc
    for line in infile:
        # ignore empty lines
        if line.isspace(): continue

        # find IP that are Indicator Titles
        IP = (re.findall(r"(?:<indicator:Title>IP:) (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})", line))
        # Only take finds
        if not IP: continue
        # Add each found IP to the BadIP list
        BadIPs.append(IP)

    #tidy up for CSV format
    data = str(BadIPs)
    data = data.replace('[', '')
    data = data.replace(']', '')
    data = data.replace("'", "")
    # Write IPs to a file
    outfile.write(data)

    infile.close
    outfile.close

rawDescription: How do I run this Python 2.7 script over multiple files in the same directory

description: Run this Python 2.7 script over multiple files in the same directory


code:
# embed.ly keys which map 1:1 with your database record keys
RESPONSE_KEYS = set([
    'provider_url', 'description', 'title', 'author_name', 'thumbnail_url',
    'thumbnail_width', 'thumbnail_height', 'author_url'
    ])

# mapping from embed.ly's key name to your database record key
KEY_MAP = {
    'url': 'content_url',
    'width': 'width_px',
    'height': 'height_px',
    'type': 'url_type'
    }

url_return = get_oembed(content_url)
record = ContentQueue(submitted_url=content_url)
record.version = 1

# iterate over the response keys and add them to the record
for key_name in url_return.iterkeys():
    key = key_name if key_name in RESPONSE_KEYS else KEY_MAP.get(key_name)
    if key:
        record[key] = url_return[key_name]

rawDescription: Better way to write a JSON file to a DB?

description: Better way to write a JSON file to a DB


code:
import pandas as pd
import numpy as np
df = pd.DataFrame()

def repeat_fun(times, f, args):
    for i in range(times): f(i,args)

def f(iteration,df):
    g = np.random.normal(0, 1, 32)
    mm = np.random.normal(491.22, 128.23, 32)
    x = 491.22+(0.557*(mm -491.22))+(g*128.23*(np.sqrt(1-0.557**2)))
    df[iteration] = x

repeat_fun(2,f,df)

rawDescription: How to run single function in to a number of times in python

description: Run single function in to a number of times in python


code: factors = [set() for index in xrange(1001)]

rawDescription: Python: list of distinct, empty sets

description: Python: list of distinct, empty sets


rawDescription: pandas define a season over which to calculate statistics

description: Pandas define a season over which to calculate statistics


code:
import pandas as pd

d = {'Apple':{'Weight':12,'Colour':'red'},
     'Banana':{'Weight':11,'Colour':'yellow','Bunched':1}
    }

df = pd.DataFrame.from_dict(d, orient='index') # convert dict to dataframe

df.to_csv('fruits.csv') # write dataframe to file

rawDescription: Importing and Exporting Nested Dictionary to Excel in an Easy-to-Edit-and-Read Way


code:
import time

is_dst = time.daylight and time.localtime().tm_isdst > 0

rawDescription: python time module: daylight savings

description: Python time module: daylight savings


code: itertools.product(L, repeat=n)

rawDescription: cross product in python of arbitrarily many lists

description: Cross product in python of arbitrarily many lists