code:
from datetime import datetime
from csv import reader

with open('onlyOnce.txt', 'r') as fp:
    for f_time, sec_time, dte in filter(None, reader(fp, delimiter="_")):
        check_stime = f_time.split(":")
        stask_hour= int(check_stime[0])
        stask_minutes = int(check_stime[1])
        check_etime = sec_time.split(":")
        etask_hour = int(check_etime[0])
        etask_minutes = int(check_etime[1])

        # check every minute if current information = desired information
        now = datetime.now()
        hour_min_sec = now.hour, now.minute, now.second

        if now.strftime("%Y-%d-%m") == dte and (stask_hour, stask_minutes, 0) <= hour_min_sec <= (etask_hour, etask_minutes, 0):
            print("this line in range time: " + f_time)
        else:
            print("")

rawDescription: How to split each line from file using python?

description: Split each line from file using python


code: screen -list

rawDescription: print in new terminal window

description: Print in new terminal window


code:
login_form = LoginForm()
pay_form=CardForm()
register_form = RegisterForm()
if request.method == 'POST':
    login_form = LoginForm(data=request.POST)
    register_form = RegisterForm(data=request.POST)
    pay_form = CardForm(data=request.POST)

    if 'loginform' in  request.POST:
      if login_form.is_valid():
        username = request.POST['username']
        password = request.POST['password']
        user=authenticate(username=username,password=password)
        if user:
            if user.is_active:
                login(request,user)
                return HttpResponseRedirect('/')
            else:
                return HttpResponse("Your account is disabled")
        else:
            return HttpResponse("Yanlış Kullanici adi ya da şifre")
      else:
        return HttpResponse("Login Form is not valid")
    if 'register_form' in request.POST:
      if register_form.is_valid():
        register_form.save()
      else:
        return HttpResponse("Register Form is not valid")
    if 'pay_form' in request.POST:
      if pay_form.is_valid():
        holder_name = request.POST['holder_name']
        card_number = request.POST['card_number']
        exp_year = request.POST['exp_year']
        exp_month = request.POST['exp_month']
        cvv = request.POST['cvv']
        satinAl(request,event_id,card_number,holder_name,exp_month,exp_year,cvv)
      else:
        return HttpResponse("Pay Form is not valid")

return render_to_response('index.html', locals(),context_instance=RequestContext(request))

rawDescription: Three Form In Same Page With Django

description: Three Form In Same Page With Django


code:
def select_xsel(text):
    import subprocess
    xsel_proc = subprocess.Popen(['xsel', '-pi'], stdin=subprocess.PIPE)
    xsel_proc.communicate(some_text)

rawDescription: Copy string - Python

description: Copy string - Python


rawDescription: How to redirect to a view with argument from urls.py?

description: Redirect to a view with argument from urls.py


code:
pickle.dumps(set.union)
f = pickle.loads(pickle.dumps(set.union))
f({1, 2, 3}, {5})

rawDescription: Pickling method descriptor objects in python


code:
from urlparse import unquote
unquote('%2C')

rawDescription: Python Requests: Using lists when specifying parameters


code:
from collections import OrderedDict
from itertools import imap

t[:] = imap(list, OrderedDict.fromkeys(imap(tuple, t)))

print(t)

rawDescription: Removing duplicate lists within another list


code:
def popen_wrapper(inqueue, outqueue):
    for i in iter(inqueue.get, SENTINEL):
        logger.warn('echo "hi"')
        outqueue.put(i)

rawDescription: python multiprocessing - select-like on running processes to see which have one have finished

description: Python multiprocessing - select-like on running processes to see which have one have finished


rawDescription: Need to create upper column for many lower columns and filling the existing data in it


code: path = "/home/tester/scripts/" + HOST + ".txt"

rawDescription: I Wish to Save Configuration With System IP Address


code: from testingA import *

rawDescription: Python creating a module

description: Python creating a module


code:
with open('somefile.txt') as f:
    ttk = next(f).replace('Mid-access token:', '').strip()

rawDescription: Reading a specific text in a file and assigning to a variable in python


code:
import Ship1
Ship1.main()

rawDescription: Files only importing if opened from certain place


code:
def mypath(request):
    if request.method == 'POST':
        greetings = request.POST.getlist('hi') # will be ['heya1','heya2']

rawDescription: Django equivalent of PHP's form value array/associative array


code:
def runningMean(seq, n=0, total=0):
    if not seq:
        return []
    total = total+seq[-1]
    return runningMean(seq[:-1], n=n+1, total=total) + [total/float(n+1)]

rawDescription: running average of items list in python in reverse order

description: Running average of items list in python in reverse order


code:
from modA import A
from modA1 import A1
from modA2 import A2

rawDescription: How to split a Python module into multiple files?

description: Split a Python module into multiple files


code:
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^',                include('mainsite.urls')), # include your app urls once
    url(r'^admin/',          include(admin.site.urls)),
)

rawDescription: How Do I Properly Set Up URLConf in Django (RegEx?)


code:
charList = list(parsedContent)

while self.trimmedCode:
    key, value = self.trimmedCode.pop()
    charList[key] = value + charList[key] # the change is here! No O(N) slice assignment!

parsedContent = ''.join(charList)

rawDescription: Efficient way to do string insertion in python?


code:
class MyNewForm(forms.ModelForm):
    class Meta:
        model = New

    def clean(self):
        cleaned_data = super(MyNewForm,self).clean()
        title = cleaned_data.get('title')
        body = cleaned_data.get('body')
        editable = cleaned_data.get('editable')

        if self.instance.pk:
            try:
                row = New.objects.get(id=self.instance.pk)
            except New.DoesNotExist:
                raise forms.ValidationError('Record not found')

            if not row.editable and not editable:
                raise forms.ValidationError('This record is not editable')

        return cleaned_data

rawDescription: State Control/Workflow in Django

description: State Control/Workflow in Django


code: import matplotlib.pyplot as plt

rawDescription: scipy: savefig without frames, axes, only content

description: Scipy: savefig without frames, axes, only content


code:
d = {}
for x in a:
    d.update(x)

rawDescription: swap one element list to int

description: Swap one element list to int


code:
def authentication(fun):
    @tornado.gen.coroutine  # note
    def test(self, *args, **kwargs):
        ...
    return test

rawDescription: how to use coroutine in custom decorator when working with db operations in tornado

description: Use coroutine in custom decorator when working with db operations in tornado


code: t[:, None]

rawDescription: Numpy matrix combination

description: Numpy matrix combination


rawDescription: Spark: Use same OneHotEncoder on multiple dataframes


code:
mylist=[[2],[9],[3],[5],[7]]
mylist = [item for sub in mylist for item in sub]
mylist
mylist[0]

rawDescription: integer extraction from list of lists in python

description: Integer extraction from list of lists in python


code:
from html.parser import HTMLParser

def unescape_entities(value, parser=HTMLParser()):
    return parser.unescape(value)

def process(ob):
    if isinstance(ob, list):
        return [process(v) for v in ob]
    elif isinstance(ob, dict):
        return {k: process(v) for k, v in ob.items()}
    elif isinstance(ob, str):
        return unescape_entities(ob)
    return ob

theJSON = process(theJSON)

rawDescription: When accessing a website (Glosbe.com) via json API special characters don't decode


rawDescription: Python Power Multiplication

description: Python Power Multiplication


code: ref_seq = "AGATAA"

rawDescription: Total Mismatches between two strings

description: Total Mismatches between two strings


code:
sorted_list_of_tuples = sorted(list_of_tuples,
                               key=lambda x: (x[1], x[0]), reverse=True)

rawDescription: Sort a list of tuples with two tuple entries in opposite order


code:
items = []
for entry in cartEntries:
    items.append(entry.item)

rawDescription: Python: How to refactor this simple list code?


code:
import time

MY_SLEEP = 1 # inside a config file

class Engine(object):

    @staticmethod
    def say(text):
        print(text)
        time.sleep(MY_SLEEP)

    #some methods
    def say_hello(self, exit):
        Engine.say("Hello")
        exit.say_goodbye()

class Another(object):

    def say_goodbye(self):
        Engine.say("ok")
        Engine.say("goodbye")

me = Engine()
bye = Another()
me.say_hello(bye)

rawDescription: Python can i access a class method from another class without passing it as a parameter?


rawDescription: Python, how to decode Binary coded decimal (BCD)


code:
fig, axes = plt.subplots(nrows=4, sharex=True)
for y, ax in zip(ydata, axes):
    ax.plot(x, y, color='salmon')
    ax.margins(x=0, y=0.05)
    ax.locator_params(axis='y', nbins=5, prune='both')

fig.subplots_adjust(hspace=0)
plt.show()

rawDescription: Python Numpy 2D plot set total number of y-tics with autoscaling


code: new_time_set = range(int(data_times[0]), int(data_times[-1])+1)

rawDescription: Python : list index out of range error for filling in data set


code:
vc = ViewClient(*ViewClient.connectToDeviceOrExit())
newAlliance = vc.findViewByIdOrRaise('id/new_alliance')
newAlliance.type('Legion of Anarchy')
allianceLeader = vc.findViewByIdOrRaise('id/alliance_leader')
allianceLeader.type('DeathAngel')

rawDescription: Android: Emulator: Python: Tabbing between Fields in a Form


code:
import urlparse

def process_url(url, keep_params=('CONTENT_ITEM_ID=',)):
    parsed= urlparse.urlsplit(url)
    filtered_query= '&'.join(
        qry_item
        for qry_item in parsed.query.split('&')
        if qry_item.startswith(keep_params))
    return urlparse.urlunsplit(parsed[:3] + (filtered_query,) + parsed[4:])

rawDescription: Slicing URL with Python

description: Slicing URL with Python


code:
import urllib2
from BeautifulSoup import BeautifulSoup
url = "http://www.my_url.com"
data = urllib2.urlopen(url).read()
soup = BeautifulSoup.BeautifulSoup(data)

all_links = soup.find('a')
# you can look for specific link

rawDescription: Analyze and grab link from an html page

description: Analyze and grab link from an html page


code:
for i in range(6):
    screen.blit(platformimg, (i*50+x, y))

rawDescription: In pygame, can i use a list to blit an object multiple times with only one line of code?


code:
label
colors
img = colors[label.ravel()].reshape(label.shape+(3,))
label[4,0]
img[4,0]
label[5,1]
img[5,1]

rawDescription: Change numpy array under condition from another array


code: sys.modules[mod_name] = mock.Mock()

rawDescription: autodoc a class that extends a mocked class

description: Autodoc a class that extends a mocked class


code: parseTags("tHiS iS a tAg, AnD tHIs, \t\n!&#^ , se@%condcomment$ , No!pUnc$$, ifNOSPACESthenPRESERVEcaps")

rawDescription: Python regular expression to remove space and capitalize letters where the space was?


code:
class TZDateTime(TypeDecorator):
    """
    Coerces a tz-aware datetime object into a naive utc datetime object to be
    stored in the database. If already naive, will keep it.

    On return of the data will restore it as an aware object by assuming it
    is UTC.

    Use this instead of the standard :class:`sqlalchemy.types.DateTime`.
    """

    impl = DateTime

    def process_bind_param(self, value, dialect):
        if value.tzinfo is not None:
            value = value.astimezone(utc).replace(tzinfo=None)
        return value

    def process_result_value(self, value, dialect):
        if value.tzinfo is None:
            value = utc.localize(value)
        return value

rawDescription: How do I handle "out of range" warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy

description: Handle "out of range" warnings for timezone-aware datetime objects on MySQL with and without SQLAlchemy


code:
while 1:
    data = sys.stdin.read(1024)
    if not data: break
    stream.write(data)

rawDescription: python audio player filtered without jitter

description: Python audio player filtered without jitter


code:
def splitby( lst, breaker='00:00'):
    current = []
    it = iter(lst)
    first = next(it)
    assert first==breaker, "`lst` must begin with `breaker`"
    for item in it:
        if item == breaker:
            yield current
            current = []
        current.append(item)
    yield current

rawDescription: Python: how to split a list into an unknown number of smaller lists based on a delimeter


code:
def checkTableExists(dbcon, tablename):
    dbcur = dbcon.cursor()
    dbcur.execute("""
        SELECT COUNT(*)
        FROM information_schema.tables
        WHERE table_name = '{0}'
        """.format(tablename.replace('\'', '\'\'')))
    if dbcur.fetchone()[0] == 1:
        dbcur.close()
        return True

    dbcur.close()
    return False

rawDescription: python - how to check if table exists?

description: Python - how to check if table exists


rawDescription: Working with bit streams

description: Working with bit streams


code:
class Foo(object):
    def __init__(self, foo):
        self.__foo = foo
    def __call__(self):
        return self.__foo
blank = Foo('-blank-')
last_game = collections.defaultdict(blank)

rawDescription: Python - loop through file to call most recent row that contained a variable in current row


code:
def avg2(x):
    res = []
    total = 0
    for i in x:
        total += i
        res.append(total / len(x))
    return res

rawDescription: Average Iterating through list

description: Average Iterating through list


code: radio_var = IntVar()

rawDescription: Python Tkinter - get selection on Radiobutton


code:
for one_enemy in enemies:
    one_enemy.stop()

rawDescription: appending code to create multiple random moving sprites - python tkinter

description: Appending code to create multiple random moving sprites - python tkinter


code: tx=transactionID

rawDescription: Accepting single paypal payments

description: Accepting single paypal payments


code:
import os
import sys

filename, extension = os.path.splitext(os.path.basename(sys.argv[0]))
trialname = './trial/{0}'.format(filename)

rawDescription: PyCharm file path separator

description: PyCharm file path separator


code: top_two = [fruit for fruit, count in Counter(fruits).most_common(2)]

rawDescription: comparing two lists and finding most preferred pairs

description: Comparing two lists and finding most preferred pairs


rawDescription: How to use generator expression with tuples in python

description: Use generator expression with tuples in python


rawDescription: How to schedule action at various timings from a list in Python

description: Schedule action at various timings from a list in Python


code:
lag = np.timedelta64(12, 'h')
df['cnt'] = (df['b'] < df['a']) & (df['a'] < df['b'] + lag)
ts = df.groupby(['PersonID', 'AnotherID', 'a'])['cnt'].sum()
ts

rawDescription: pandas: vectorize counting rows in time interval

description: Pandas: vectorize counting rows in time interval


code:
def POST(self):
    i = web.webapi.rawinput()
    try:
        files = i.files
        if not isinstance(files, list):
            files = [files]
        for f in files:
            if f.filename:
                filetype, encoding = mimetypes.guess_type(f.filename)
                # do smth with f.file
    except KeyError:
        pass
    if web.ctx.env.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest':
        web.header("Content-Type", "application/json")
        return json.dumps(dict(status=1, html=unicode(render_partial.files(uploaded_files))))
    else:
        raise web.seeother(web.ctx.env.get("HTTP_REFERER", "/"))

rawDescription: Get upload status in webpy

description: Get upload status in webpy


code:
for value in foo.values():
    value.sort()

rawDescription: Sorting a list of lists with itertools imap in Python


rawDescription: I want to calculate the difference between two values in a "distance_table = []" with permutations, how can I use permutations correctly in this case?


code:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get('https://accounts.google.com/ServiceLogin?continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fhl%3Den%26feature%3Dcomment%26app%3Ddesktop%26next%3D%252Fall_comments%253Fv%253DLAr6oAKieHk%26action_handle_signin%3Dtrue&uilel=3&service=youtube&passive=true&hl=en')

# log in
driver.find_element_by_id('Email').send_keys('username')
driver.find_element_by_id('Passwd').send_keys('password')
driver.find_element_by_id('signIn').click()

# post a comment
comment = "test"

box = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CLASS_NAME, "box")))
box.click()

frame = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//iframe[@title="+1"]')))
driver.switch_to.frame(frame)

driver.find_element_by_xpath('//div[@onclick]').click()

element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@jsname="msEQQc"]/following-sibling::div//div[@g_editable="true"]')))
driver.execute_script("arguments[0].innerHTML='%s';" % comment, element)

rawDescription: How to Post Youtube Comment with Selenium

description: Post Youtube Comment with Selenium


code: driver = webdriver.PhantomJS() # or add to your PATH

rawDescription: Is there a way to use PhantomJS in Python?


code:
import numpy as np
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt

# one minute interval
start = dt.datetime.now( )
end = start + dt.timedelta( minutes=1 )

# sin curve at seconds frequancy
idx1 = pd.date_range( start, end, freq='S' )
ts1 = pd.Series( np.sin( np.linspace( 0, 4 * np.pi, len( idx1 ) ) ), index=idx1 )

# cosine curve at milisecond frequency
idx2 = pd.date_range( start, end, freq='L' )
ts2 = pd.Series( np.cos( np.linspace( 0, 4 * np.pi, len( idx2 ) ) ), index=idx2 )

rawDescription: Subtracting two interleaved, differently based time-series arrays with numpy?


code:
syn = IP(dst='www.google.com') / TCP(dport=80, flags='S')
syn

rawDescription: Python-Scapy or the like-How can I create an HTTP GET request at the packet level


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

newvid = asciitable.read('user4.cat')

n_new = newvid['n']
re_new = newvid['re']
number = newvid['number']
std_dev = newvid['standard_deviation']

n_max = float(number.max())  # for coloring later

plt.figure()
plt.title('sersic parameter vs. standard deviation distribution of noise')
plt.xlabel('standard deviation')
plt.ylabel('sersic parameter')
plt.xlim(0,12)
plt.ylim(0,5)
for n in np.unique(number):
    n_mask = number == n                 # pick out just where n_new is the current n
    order = np.argsort(std_dev[n_mask])  # sort by std_dev, so line doesn't zig zag
    plt.plot(std_dev[n_mask][order], n_new[n_mask][order],
             label=str(n), color=cm.jet(n/n_max))    # label and color by n
plt.legend()
plt.show()

plt.figure()
plt.title('half-light radius vs. standard deviation distribution of noise')
plt.xlabel('standard deviation')
plt.ylabel('half-light radius')
plt.xlim(0,12)
plt.ylim(-2,15)

# do one plot per number
for n in np.unique(number):
    n_mask = number == n                 # pick out just where n_new is the current n
    order = np.argsort(std_dev[n_mask])  # sort by std_dev, so line doesn't zig zag
    plt.plot(std_dev[n_mask][order], re_new[n_mask][order],
             label=str(n), color=cm.jet(n/n_max))    # label and color by n
plt.legend()
plt.show()

rawDescription: Matching y axis points together

description: Matching y axis points together


code:
urlpatterns += patterns('myapp.views',

    url(r'^getstuff/$', 'getstuff' ),
)

rawDescription: Django for a simple web application

description: Django for a simple web application


code:
if expected_rep > REPUTATION_MAX_GAIN_PER_DAY:
   expected_rep = REPUTATION_MAX_GAIN_PER_DAY
delta = expected_rep - current_rep

rawDescription: Python work out difference to 0

description: Python work out difference to 0


code: python --version

rawDescription: ubuntu scipy works for python2.7 but not for 3.2

description: Ubuntu scipy works for python2.7 but not for 3.2


code:
msilib.add_data(self.db, "Shortcut",
        [("S_APP_%s" % index, executable.shortcutDir,
                executable.shortcutName, "TARGETDIR",
                "[TARGETDIR]%s" % baseName, None, None, None,
                None, None, None, "TARGETDIR")]) # <--- Working directory.

rawDescription: How to set shortcut working directory in cx_freeze msi bundle?

description: Set shortcut working directory in cx_freeze msi bundle


rawDescription: How to force genfromtxt read csv as record array?

description: Force genfromtxt read csv as record array


code:
def f():

    ...
    yield 'first function finished'
    ...
    yield 'almost done'
    ...

for message in f():
    try:
        time.sleep(2)
    except KeyboardInterrupt:
        print(message)

rawDescription: Python Generators and yield : How to know which line the program is at


rawDescription: Set height and width of figure created with plt.subplots in matplotlib?


code:
def iterVowelCount(s):
    vowels = frozenset('aeiouAEIOU')
    return sum(1 for c in s if c in vowels)

rawDescription: Counting vowels in a string using recursion


code:
def create_A(**kwargs):
    return A(**kwargs)

rawDescription: python explicitly not passing optional parameter

description: Python explicitly not passing optional parameter


code:
Person.children = Mock()
dad = Person(health=2)
dad.spawn()

num_children = len(Person.children.create.mock_calls)
assert num_children == 2, num_children

Person.children.create.assert_called_with(name='Child1')

rawDescription: Simplify Django test set up with mock objects


rawDescription: print number in some digits in python

description: Print number in some digits in python


code:
['*random words*', '*random words*']
['*random words*', '*random words*']

rawDescription: Slicing a String after certain key words are mentioned into a list


rawDescription: Using Queues in Multi-Thread Python, Passing the queue to a subfunction as reference


code:
def recur_dictify(frame):
    if len(frame.columns) == 1:
        if frame.values.size == 1: return frame.values[0][0]
        return frame.values.squeeze()
    grouped = frame.groupby(frame.columns[0])
    d = {k: recur_dictify(g.ix[:,1:]) for k,g in grouped}
    return d

rawDescription: Convert pandas DataFrame to a nested dict


code: True

rawDescription: Python Regex strange behavior with accented characters


code:
og_dict_list =[]
for i in range(2,5):
    og_dict = {'name':'user1', 'salary':str(i) +'k'}
    og_dict_list.append(og_dict)
for og_dict_obj in og_dict_list:
    print(og_dict_obj)

rawDescription: how to create a new dictionary in for loop?

description: Create a new dictionary in for loop


code:
span.text
span.text[pos+2:]
span.text[pos+2:].split(' ')
span.text[pos+2:].split(' ')[0]
int(span.text[pos+2:].split(' ')[0])

rawDescription: convert to int using python

description: Convert to int using python


code:
arr2_pairs = as_strided(arr2.T, strides=(8, 8, 32), shape=(3, 2, 3))
dist = arr2_pairs - arr1.T
(dist ** 2).sum(axis=2) ** 0.5

rawDescription: Distance between numpy arrays, columnwise


code:
from numpy.lib.stride_tricks import as_strided
sz = x.itemsize
d = as_strided(x[-1::-1,:], shape=(3,4), strides=sz*np.array([-4,-3]))
d

rawDescription: Numpy: Column dependent slicing

description: Numpy: Column dependent slicing


code:
from sklearn.trees import DecisionTreeClassifier
#make your sample matrix
samples = [[1,1], [0,0], [1,0], [0,1], [0,0]]
#make your target vector ( in this case fruit)
fruitname = [1, 0, 1, 0, 0]
#create and fit the model
dtree =  DecisionTreeClassifier()
dtree =  dtree.fit(samples, fruitname)
#test an unknown red fruit that is oblong
dtree.predict([0,1])

rawDescription: Decision tree implementation for returning the next feature to split the tree


code: ', '.join(['{}_{}'.format(k,v) for k,v in d.iteritems()])

rawDescription: Python getting a string (key + value) from Python Dictionary


code:
from collections import OrderedDict
month_dictionary = OrderedDict((('012013', 3), ('022013', 1), ('032013', 5)))
total = 0
for key, value in month_dictionary.iteritems():
    total += value
    month_dictionary[key] = total

month_dictionary

rawDescription: accumulating an orderedDict

description: Accumulating an orderedDict


code:
lines_1=par1.plot(perform_1,linestyle='', marker='H', markerfacecolor ='k')
lines_2=par1.plot(perform_2,linestyle='', marker='*',markerfacecolor ='m')
ax.legend((rects1[0], rects2[0],lines_1[0],lines_2[0]), ('Current time period', 'Next time Period','Current Period Performance', 'Next Period Performance'),prop=dict(size=10) )

rawDescription: Aligning markers for individual points in matplotlib and removing "double" legend for markers in matplotlib in Python


code:
df['Period'].diff()
df['Period'].diff() > 1

rawDescription: How to filter a Dataframe based on a criteria using .shift()

description: Filter a Dataframe based on a criteria using .shift()


rawDescription: pythonic way to create 3d dict

description: Pythonic way to create 3d dict


code:
class MainPage(MethodView):
    navigation=False
    context={}

    def prepare(self,*args,**kwargs):
        if self.navigation:
            self.context['navigation']={
                #building navigation
                #in your case based on request.args.get('page')
            }
        else:
            self.context['navigation']=None

    def dispatch_request(self, *args, **kwargs):
        self.context=dict() #should nullify context on request, since Views classes objects are shared between requests
        self.prepare(self,*args,**kwargs)
        return super(MainPage,self).dispatch_request(*args,**kwargs)

class PageWithNavigation(MainPage):
    navigation = True

class ContentPage(PageWithNavigation):
    def get(self):
        page={} #here you do your magic to get page data
        self.context['page']=page
        #self.context['bread']=bread
        #self.context['something_Else']=something_Else
        return render_template('page.html',**self.context)

rawDescription: Dynamic navigation in Flask

description: Dynamic navigation in Flask


code: send(ARP(op=ARP.is_at, psrc=router_ip, hwdst=victim_mac, pdst=victim_ip))

rawDescription: Python 2.7 -scapy and ARP

description: Python 2.7 -scapy and ARP


code:
c.executemany(
      """INSERT INTO breakfast (name, spam, eggs, sausage, price)
      VALUES (%s, %s, %s, %s, %s)""",
      [
      ("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95 ),
      ("Not So Much Spam Plate", 3, 2, 0, 3.95 ),
      ("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95 )
      ] )

rawDescription: how do I avoid avoid multiple round trips for queries with MySQLdb with python?

description: Avoid avoid multiple round trips for queries with MySQLdb with python


code:
import time

@timeout()
def test_timeout(a, b, c):
    time.sleep(1)

@timeout(1)
def test_timeout2():
    time.sleep(2)

if __name__ == '__main__':
    test_timeout(1, 2, 3)

    test_value = False
    try:
        test_timeout2()
    except TimeoutError as e:
        test_value = True

    assert test_value

rawDescription: PyUnit - How to unit test a method that runs into an infinite loop for some input?


rawDescription: Combine (3) 32-char hex hashes into a single unique 32-char hash?


code:
def rec_fetcher(obj):
    if isinstance(obj, list):
        for item in obj:
            yield from rec_fetcher(item)
    elif isinstance(obj, dict):
        for item in obj:
            yield from rec_fetcher(obj[item])
    else:
        yield obj

list(rec_fetcher(data))

rawDescription: Obtaining Values from a List-Dictionary Hybrid List Dynamically


code: tt.tm_min * 60 + tt.tm_sec

rawDescription: Python: Parse elapsed time (minutes : seconds) to seconds


rawDescription: How to slice one MultiIndex DataFrame with the MultiIndex of another

description: Slice one MultiIndex DataFrame with the MultiIndex of another


rawDescription: Increase the data size

description: Increase the data size


code:
mylist = ['a', 'b', None, 'c', None]
id(mylist)
mylist[:] = [0 if x is None else 1 for x in mylist]
id(mylist)

rawDescription: How to convert a list of elements into a list with 0 or 1

description: Convert a list of elements into a list with 0 or 1


Subcellular:
Ribosome
Plasma Membrane

Bio_target:
RNA 18S
Insuline receptor

Unity: J nM

LAB: IMED Lasige

Conditions: Temperature of 25\\xbaC and normal pressure

Conditions: Computational simulation in R module canislup

Asay_parameter: enthalpy concentration

Journal: Nature Science

Title: Glutamine is a novel compound in Brainstem studies

Title: Glucose concetration is essential to calcium inducted waves

Cell_type: Neuron Myocite

Comparisons:
enthalpy>70 J
Concentration< 10 uM

Mol_name: Glutamine Glucose

target_type: Peptide Protein

Tissue: Brainstem Pericardium

Species:
Homo sapiens
Canis lupus

Observations:
Outliers were not found
Python modules were also used

rawDescription: json_decode produces a string

description: Json_decode produces a string


code:
# -*- coding: utf-8 -*-
import random

import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError

class HttpbinSpider(CrawlSpider):
    name = "httpbin"

    # this will generate test links so that we can see CrawlSpider in action
    start_urls = (
        'https://httpbin.org/links/10/0',
    )
    rules = (
        Rule(LinkExtractor(),
             callback='parse_page',
             # hook to be called when this Rule generates a Request
             process_request='add_errback'),
    )

    # this is just to no retry errors for this example spider
    custom_settings = {
        'RETRY_ENABLED': False
    }

    # method to be called for each Request generated by the Rules above,
    # here, adding an errback to catch all sorts of errors
    def add_errback(self, request):
        self.logger.debug("add_errback: patching %r" % request)

        # this is a hack to trigger a DNS error randomly
        rn = random.randint(0, 2)
        if rn == 1:
            newurl = request.url.replace('httpbin.org', 'httpbin.organisation')
            self.logger.debug("add_errback: patching url to %s" % newurl)
            return request.replace(url=newurl,
                                   errback=self.errback_httpbin)

        # this is the general case: adding errback to all requests
        return request.replace(errback=self.errback_httpbin)

    def parse_page(self, response):
        self.logger.info("parse_page: %r" % response)

    def errback_httpbin(self, failure):
        # log all errback failures,
        # in case you want to do something special for some errors,
        # you may need the failure's type
        self.logger.error(repr(failure))

        if failure.check(HttpError):
            # you can get the response
            response = failure.value.response
            self.logger.error('HttpError on %s', response.url)

        elif failure.check(DNSLookupError):
            # this is the original request
            request = failure.request
            self.logger.error('DNSLookupError on %s', request.url)

        elif failure.check(TimeoutError):
            request = failure.request
            self.logger.error('TimeoutError on %s', request.url)

rawDescription: Scrapy get website with error "DNS lookup failed"


code:
import pandas as pd
df = pd.DataFrame({'cat':['A','B','C','B','C','D','C','E'], 'value':[3,6,7,7,9,8,3,1]})
result = df.groupby('cat').sum().sort_values('value', ascending=False)
mask = (result['value'].div(result['value'].sum()).cumsum() < 0.9)
result = result.loc[mask].append(pd.Series(result.loc[~mask].sum(), name='Other'))
print(result)

rawDescription: pandas: how to aggregate a subset of groupby rows into a single row?

description: Pandas: how to aggregate a subset of groupby rows into a single row


code:
def grouper(line):
    if is_event(line):
        grouper.count += 1
    return grouper.count
grouper.count = 0

result_as_iterators = (x[1] for x in itertools.groupby(lines, grouper))

rawDescription: How to collect data from a list into groups based on condition?

description: Collect data from a list into groups based on condition


code:
back_to_string = save_as_binary.decode('utf-8')
print(back_to_string)

rawDescription: How to translate from a hexdigest to a digest and vice-versa?

description: Translate from a hexdigest to a digest and vice-versa


code:
import datetime as dt
from bson import ObjectId
import pytz

def get_timestamp_from_uuid(uuid_object):

    generation_time = dt.datetime.utcfromtimestamp((uuid_object.time - 0x01b21dd213814000) * 100 / 1e9)
    generation_time = generation_time.replace(tzinfo=pytz.UTC)

    return int(generation_time.timestamp())

def get_timestamp_from_object_id(object_id):

    generation_time = object_id.generation_time
    return int(generation_time.timestamp())

def return_decimal_bytes(binary):

    binary = binary[2:]
    rest = len(binary) % 8

    if rest != 0:
        binary = '0'*(8 - rest) + binary
    bytes = {}

    for i in range(0, len(binary)//8):
        bytes[i] = binary[:8]
        binary = binary[8:]

    return bytes

def uuid_to_object_id(uuid_object):
    """
    Converts UUID to ObjectId

    :param uuid_object: UUID
    :return: ObjectId
    """

    uuid_to_bin = bin(int(uuid_object))
    parts_of_uuid = return_decimal_bytes(uuid_to_bin)

    timestamp_of_uuid = hex(get_timestamp_from_uuid(uuid_object))
    timestamp_of_uuid = timestamp_of_uuid.replace('0x', '')

    uuid_time = uuid_object.time

    fourth = int(parts_of_uuid[8], 2) & 0x3F | (uuid_time << 6)
    fourth = str(hex(fourth))[-2:]

    fifth = str(hex(int(parts_of_uuid[9], 2)))
    sixth = str(hex(int(parts_of_uuid[10], 2)))
    seventh = str(hex(int(parts_of_uuid[11], 2)))
    eighth = str(hex(int(parts_of_uuid[12], 2)))
    ninth = str(hex(int(parts_of_uuid[13], 2)))
    tenth = str(hex(int(parts_of_uuid[14], 2)))

    try:
        eleventh = str(hex(int(parts_of_uuid[15], 2)))
    except Exception as e:
        print(e)
        eleventh = str(hex(1))

    def rep(el):
        if len(el) <= 3:
            return el.replace('x', '')
        else:
            return el.replace('0x', '')

    res = rep(fifth) + rep(sixth) + rep(seventh) + rep(eighth) + rep(ninth) + rep(tenth) + rep(eleventh)

    return ObjectId(timestamp_of_uuid + fourth + res)

rawDescription: Find documents in MongoDB by UUID (Convert ObjectId to UUID)


code: array = np.fromiter(result.iteritems(), dtype=dtype, count=len(result))

rawDescription: python dict to numpy structured array

description: Python dict to numpy structured array


code:
from PIL import Image

def white_bg_square(img):
    "return a white-background-color image having the img in exact center"
    size = (max(img.size),)*2
    layer = Image.new('RGB', size, (255,255,255))
    layer.paste(img, tuple(map(lambda x:(x[0]-x[1])/2, zip(size, img.size))))
    return layer

rawDescription: Python adding extra area to image

description: Python adding extra area to image


code: [row for row in zip(*Matrix) if all(e != ['-'] for e in row)]

rawDescription: Delete Column IF all column cell contain NULL value


code:
points = [Point(i, i) for i in xrange(500)]
assert isinstance(p[-1], Point)

rawDescription: Dynamically define variable names

description: Dynamically define variable names


code: freqs = lambda s: [c for c in set(s) if s.count(c) > 1]

rawDescription: What is happening in this Python function?


code:
class Example(db.Model):
    __tablename__ = 'example'
    normal_column = db.Column(db.Integer, primary_key=True, autoincrement=True)
    html_column = db.Column(CleanedHtml)

rawDescription: Flask + SQLAlchemy - custom metaclass to modify column setters (dynamic hybrid_property)


code:
class Breakfast(models.Model):
    pass
    # other fields

class Egg(m.Model):
    breakfast = OneToOneOrNoneField(Breakfast, related_name="egg")

breakfast = Breakfast()
assert breakfast.egg == None

rawDescription: Django: Return 'None' from OneToOneField if related object doesn't exist?


code:
from string import punctuation
import numpy as np

stg = "abcde123]\nefghi456}\njk{lmn789"
arr = np.array([[ch for ch in line ] for line in stg.translate(None, punctuation).split()])
print(arr)

rawDescription: Convert a long string into a matrix, cleaning it


code: df = df.iloc[2:]

rawDescription: Pandas: parse merged header columns from Excel


code:
def triangle_sum(n):
    start = n*(n-1)//2+1
    return sum(range(start,start+n))

rawDescription: Sum of all numbers

description: Sum of all numbers


rawDescription: python BeautifulSoup getting variables from a garbage page

description: Python BeautifulSoup getting variables from a garbage page


code: os.environ["PATH"] += os.pathsep + path

rawDescription: Python: Platform independent way to modify PATH environment variable


code:
mask = totals['dirty']+totals['swap'] > 1e7
result = mask.loc[mask]
region_types = result.index.get_level_values('region_type').unique()

rawDescription: Is there a better way to collect unique index values in pandas?


code:
from collections import defaultdict

result = defaultdict(list)

for key, *values in data:
    result[key].extend(values)

rawDescription: Merging repeated items in a list into a python dictionary


rawDescription: Re-order three lists and maintain relation between indices?


code:
import numpy as np

def split_into_parts(number, n_parts):
    return np.linspace(0, number, n_parts+1)[1:]

rawDescription: Numpy method to split a real number into n-equal parts?


code:
def __init__(self, *args, custom_name=None, **kwargs):
    self.custom_name = custom_name

    # do your stuff...

rawDescription: Python: passing an optional named variable with *args **kwargs


rawDescription: Complicated Django annotation with self reference


code:
fit = []
for t in range(result.k_ar, len(data)):
    value = result.params[0]
    for i in range(2, result.k_ar + 2):
        value += result.params[i - 1] * data[t - i + 1]
    fit.append(value)

rawDescription: How to get constant term in AR Model with statsmodels and Python?

description: Get constant term in AR Model with statsmodels and Python


code:
import subprocess as sp

''' Runs a program '''
def run(prog):
      print("Lets run program %s" % prog)
      sp.Popen([prog], stdout=sp.STDOUT, stderr=sp.STDOUT)

      # This makes the script wait until the end of the program
      sp.wait()

rawDescription: How to fetch python output and get to dynamic massive

description: Fetch python output and get to dynamic massive


code:
departments = db.relationship('Department',
    secondary='users_departments',
    viewonly=True,
    backref=db.backref('users', viewonly=True, lazy='dynamic'),
    lazy='dynamic')

rawDescription: How to add value to join table with SQLAlchemy?

description: Add value to join table with SQLAlchemy


rawDescription: Python - Merge lists in a row from a list


code:
def html_to_bow_bs(text):
    if not text:
        return []

    soup = BeautifulSoup(text, "lxml", parse_only=SoupStrainer('body'))

    # Remove all irrelevant tags
    for elem in soup.find_all(['script','style','a']):
        elem.extract()

    body = soup.find("body")
    if not body:
        return []

    the_text = body.get_text(strip=True).encode('utf-8')
    the_text = re.sub(r'[^\x00-\x7F]+', ' ', the_text)
    return [w.lower() for w in the_text.split()]

rawDescription: What is the fastest, most error-free method of extracting and cleaning the HTML body text in Python?


rawDescription: FNV1A_64 don't match

description: FNV1A_64 don't match


code:
get_avg = lambda xs, attr: sum(x[attr] for x in xs) / len(xs)
avg_review = get_avg(books, "rw")
avg_rating = get_avg(books, "rg")

rawDescription: Can I do a reduce on a list comprehension into two lists, based on two values?

description: Do a reduce on a list comprehension into two lists, based on two values


code: '    a    b  c \t\n\n   '.split()

rawDescription: What are the equivalents of .split() and .rstrip() for a tuple?


code:
def files_and_subdirectories(root_path):
    files = []
    directories = []
    for f in os.listdir(root_path):
        if os.path.isfile(f):
            files.append(f)
        elif os.path.isdir(f):
            directories.append(f)
    return directories, files

rawDescription: save os.walk() in variable

description: Save os.walk() in variable


code:
#!/usr/bin/env python
import csv

names = ['a','b','c','d']
matrix = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]

with open('test.csv', 'a') as csvfile:
    writer = csv.writer(csvfile, dialect='excel')
    for name, matrix_row in zip(names, matrix):
        output_row = [name]
        output_row.extend(matrix_row)
        writer.writerow(output_row)

rawDescription: Python csv writer: write a string in front of an array, all in individual columns


code: brutedata = {'postdata[{}]'.format(i): v for i, v in enumerate(itemlist)}

rawDescription: How to call all list items in a list based on item count

description: Call all list items in a list based on item count


code:
def yesno():
    answer = raw_input("(Y/N) > ").upper()
    if answer == "Y":
       return True
    elif answer == "N":
       return False
    else:
       return yesno()     # CHANGE IN THIS LINE.

if yesno():
    print("Yes")
else:
    print("No")

rawDescription: Function Recursion

description: Function Recursion


code:
x_coords = [c[0] for c in x_y_pairs_to_activate]
y_coords = [c[1] for c in x_y_pairs_to_activate]
grid[x_coords, y_coords] = 1

rawDescription: How can I convert a list of tuples into a mask?

description: Convert a list of tuples into a mask


code:
fa = lambda: a**3-a-2
fb = lambda: b**3-b-2
fc = lambda: c**3-c-2

rawDescription: Python Variables and Equations

description: Python Variables and Equations


code: df.groupby('A').filter(lambda x: (x['B'] == 't').sum() == 0)

rawDescription: gropuby and remove specified groups in pandas DataFrame

description: Gropuby and remove specified groups in pandas DataFrame


code:
def render(self, request):
    request.setResponseCode(...)
    return ""

rawDescription: Override all default resources / responses from Twisted.web


code:
class Team(models.Model):
    players = models.ManyToManyField(Player)
    team_name = models.CharField(max_length=100)

rawDescription: Django: How to write groups and where those groups live?


rawDescription: PyQt4 does not redirect me to the next page


code:
import pymel.core as pm
pm.xform(item, my_new_pymel_matrix)

rawDescription: Maya Python API Scaling a matrix about another matrix


code:
str(dt.date())
str(dt.time())

rawDescription: Python Date / Time Regular Expression

description: Python Date / Time Regular Expression


code:
import sys
[infile, outfile] = sys.argv[1:]

with open(infile) as inf:
    with open(outfile) as outf:
        for l in inf:
            outf.write(','.join(l.split('\t')).replace(',,',',n.a.,'))

rawDescription: count multiple tabs tsv file

description: Count multiple tabs tsv file


code:
MIDDLEWARE_CLASSES = (
    #...
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    #...
)

rawDescription: Get the user object from session

description: Get the user object from session


code:
search     = SphinxSearch(
                index    = 'trial_data trial_datastemmed',
                weights  = {'name': 100,},
                mode     = 'SPH_MATCH_ALL',
                rankmode = 'SPH_RANK_BM25',
                sortmode = 'SPH_SORT_RELEVANCE', # this was added
                )

rawDescription: Search app in Django

description: Search app in Django


rawDescription: Python - removing xml tag in an element

description: Python - removing xml tag in an element


code:
import csv

with open('log.csv') as f_input:
    csv_input = csv.reader(f_input)
    headings = next(csv_input)

    country = ''
    f_output = None

    for cols in csv_input:
        if country != cols[2]:
            country = cols[2]

            if f_output:
                f_output.close()

            f_output = open(country + ".csv", "wb")
            csv_output = csv.writer(f_output)
            csv_output.writerow(headings)

        csv_output.writerow(cols)

    f_output.close()

rawDescription: Reading csv and writing to new csv based up on criteria in python


code:
df1 = pd.DataFrame(np.reshape(df.values,(3,5)))
df1['Index'] = '2010'
df1.set_index('Index',append=True,inplace=True)
df1 = df1.reorder_levels(['Index', None])

rawDescription: Reshape (stack) pandas dataframe based on predefined number of rows


code:
def get_percentiles_from_box_plots(bp):
    percentiles = []
    for i in range(len(bp['boxes'])):
        percentiles.append((bp['caps'][2*i].get_ydata()[0],
                           bp['boxes'][i].get_ydata()[0],
                           bp['medians'][i].get_ydata()[0],
                           bp['boxes'][i].get_ydata()[2],
                           bp['caps'][2*i + 1].get_ydata()[0],
                           (bp['fliers'][i].get_xdata(),
                            bp['fliers'][i].get_ydata())))
    return percentiles

rawDescription: Is it possible to draw a matplotlib boxplot given the percentile values instead of the original inputs?


code:
def rotations12(polycube):
    for i in range(3):
        polycube = numpy.transpose(polycube, (1, 2, 0))
        for angle in range(4):
            polycube = numpy.rot90(polycube)
            yield polycube

rawDescription: How to calculate all 24 rotations of 3d array?

description: Calculate all 24 rotations of 3d array


code:
groups = itertools.groupby(initial, operator.itemgetter('query'))
print([{"query": key, "results": list(group)} for key, group in groups])

rawDescription: Correct use of a fold or reduce function to long-to-wide data in python or javascript?


code:
n=input()
l = list(range(1, n))
step = 2
while step <= len(l):
    l = [num for ind, num in enumerate(l) if (ind + 1) % step != 0]
    step += 1
print(l)

rawDescription: Performance issue with Python list operations


code:
tasks = [
(GPIO_nek, GPIO.LOW, interval1),
(GPIO_schouder, GPIO.LOW, interval1),
(GPIO_nek, GPIO.HIGH, interval1),
(GPIO_rug1, GPIO.LOW, interval2),
(GPIO_schouder, GPIO.HIGH, 0) ]

for pin, level, interval in tasks * 20:  # Above you ran it 20 times, this notation keeps it in a single loop to break our o
    if not done:
        GPIO.digitalWrite(pin, level)
        timer.wait(interval)
    else:
        timer.clear()
        break

rawDescription: Raspberry Pi Python pause a loop sequence, when button pushed


code:
M = np.arange(m)[:,None]
N = np.arange(n)[None,:]

rawDescription: Copy numpy array from one (2-D) to another (3-D)


code:
my_dict[range(1,6)] = 'apple'
n = random.randint(1, 5)

for key in my_dict:
    if n in key:
        print(my_dict[key])

rawDescription: Assign a Range of Numbers to a Single Key with Dictionaries


code:
import numpy as np
bins = [1, 33, 66, 99, 199, np.inf]

rawDescription: python pandas dataframe index match

description: Python pandas dataframe index match


code: cur.execute("""SELECT * FROM table name WHERE user=%s AND pass=%s""", ('therightuser', 'therightpass'))

rawDescription: Pulling entry from MySQLdb in Python

description: Pulling entry from MySQLdb in Python


rawDescription: Python Pandas: How to get the row names from index of a dataframe?


code: requests.post('http://example.com/welcome', data={'password': SOME_PASSWORD}, params={'user': SOME_USERNAME})

rawDescription: How to send a post request with data using python requests module?

description: Send a post request with data using python requests module


code:
from collections import defaultdict

Data = defaultdict(dict)
Data[day1][e1] = 4

rawDescription: Assign Nested Keys and Values in Dictionaries


code:
Data3 = 8
Data4 = 7
Data5 = 5
Data6 = 6

rawDescription: Compare two text files to find differences and output them to a new text file


code:
with open('output_file', 'w') as f:
    for city, values in d.items():
       f.write('{} {}\n'.format(city, ' '.join(values)))

rawDescription: Python: append last word from lines in input file to to end of lines of output file


code:
l = []
for r in range(10):
    def make_foo(r):
        def foo():
            return r
        return foo
    l.append(make_foo(r))

for f in l:
    print(f())

rawDescription: Is there a Pythonic way to close over a loop variable?


rawDescription: Pass an array in python odeint

description: Pass an array in python odeint


code:
selection = raw_input("Enter your selection:")
if int(selection) == 1:
    Random(100)
elif int(selection) == 2:
    Random(1000)
elif int(selection) == 3:
    Random(10000)
elif int(selection) == 4:
    Random(100000)
elif int(selection) == 5:
    exit()

rawDescription: Python Raspberry PI Guessing Game(Function call not working)


code: CFG["AlwOnTop"] = not CFG["AlwOnTop"]

rawDescription: Simplify the changing of this binary variable


code:
import ctypes
libc = ctypes.cdll.LoadLibrary("libc.so.6")
libc.strtof
libc.strtof('1.234', None)
libc.strtof.restype = ctypes.c_float
libc.strtof('1.234', None)
type(libc.strtof('1.234', None))

rawDescription: C# Return Type Issue

description: C# Return Type Issue


code:
#        PLOTS
# New - Find peak of spectrum - Code from above
mY = np.abs(Y) # Find magnitude
peakY = np.max(mY) # Find max peak
locY = np.argmax(mY) # Find its location
frqY = frq[locY] # Get the actual frequency value

# Code from before
plt.subplot(2,1,1)
plt.plot(frq,abs(Y),'r') # plotting the spectrum

# New - Plot the max point
plt.plot(frqY, peakY, 'b.', markersize=18)

# New - Make title reflecting peak information
plt.title('Peak value: %f, Location: %f Hz' % (peakY, frqY))

# Rest of the code is the same
plt.xlabel('Freq (Hz)')
plt.ylabel('|Y(freq)|')
plt.grid('on')
plt.subplot(2,1,2)
plt.plot(x,y)
plt.xlabel('Time (ms)')
plt.ylabel('Angle (degrees)')
plt.grid('on')
plt.show()

rawDescription: Print highest peak value of the frequency domain plot


code:
result = df.apply(
    lambda row: (do_something(row), do_something_else(row)),
    axis=1)

rawDescription: Getting specific list element from a series


code:
def encrypt(s, n):
    """Runs string s through n rounds of encryption"""
    for _ in range(n):
        s = some_encryption_method(s)
    return s

def decrypt(s, n):
    """Runs string s through n rounds of decryption"""
    for _ in range(n):
        s = some_decryption_method(s)
    return s

rawDescription: Python: How to run two loops simultaneously and pass iterative arguments to them?


code: return HttpResponse("a string: {}".format(val))

rawDescription: How to return both string and value within HttpResponse?

description: Return both string and value within HttpResponse


code:
def foo():
    nums=[1,2,3]  # create a list and give it a name. nums contains a reference to the list
    bar(nums)     # call the method bar, passing it the reference to that list
    print(nums)   # print the list.

rawDescription: Python local variable being changed by another method


code:
# Choose what to do
choice = raw_input("Write what you want do do: add, subtract, multiply or divide")
if choice == 'add':
    add()

rawDescription: Making selections linked to definitions in python


rawDescription: Django admin model plural mode global settings, not adding suffix 's'


code:
class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

rawDescription: How to add parameters to flask-restful in python?

description: Add parameters to flask-restful in python


code:
def mergesort(list):
    if len(list) < 2:
        return list
    middle = len(list) / 2
    left = mergesort(list[:middle])
    right = mergesort(list[middle:])
    return merge(left, right)

rawDescription: merge sort implementation to sort by string length - python

description: Merge sort implementation to sort by string length - python


code: for var in [value]: pass

rawDescription: Counting from 1 to infinity without assignment


code:
def __init__(self, *args, **kwargs):
   visible = kwargs.pop('visible', False)
   super().__init__(*args, **kwargs)

rawDescription: Pythonic way to check if a variable was passed as kwargs?


code:
sentiment_analyzer.analyze('the not best')
Sentiment(polarity=-0.5, subjectivity=0.3)

rawDescription: Why is not TextBlob using / detecting the negation?


code:
str = "http://farm6.static.flickr.com/5149/5684108566_aed8b9b52d_s.jpg"
str = str.replace("_s","_m")

rawDescription: python search and replace operation

description: Python search and replace operation


code:
IPv4Pool.objects.annotate(available_ips=Count('ip_ranges'),
                          num_subscribers=Count('subscribers'),
                 ).filter(num_subscribers__lt=F('available_ips'))

rawDescription: Field calculated from Foreign Keys, need to save twice?


rawDescription: How can I solve multivariable linear equation in python?

description: Solve multivariable linear equation in python


code:
posts.append({
        'title': feed['entries'][i].title,
        'summary': feed['entries'][i].summary,
        'link': feed['entries'][i].link,
        'content': feed['entries'][i].content,
        'date': published,
        'image_url': image_url,
    })

rawDescription: I would like to catch the image from RSS feed


code:
def get_rows():
    db.things.category.represent = lambda v: v.name
    fields = ['id','name','category','price','owner']
    rows = []
    page = int(request.vars.page)
    pagesize = int(request.vars.rows)
    limitby = (page * pagesize - pagesize,page * pagesize)
    orderby = db.things[request.vars.sidx]
    if request.vars.sord == 'desc': orderby = ~orderby
    for r in db(db.things.id>0).select(limitby=limitby,orderby=orderby):
        vals = []
        for f in fields:
            rep = db.things[f].represent
            if rep:
                vals.append(rep(r[f]))
            else:
                vals.append(r[f])
        rows.append(dict(id=r.id,cell=vals))
    total = db(db.things.id>0).count()
    pages = int(total/pagesize)
    #if total % pagesize == 0: pages -= 1
    data = dict(total=pages,page=page,rows=rows)
    return data

rawDescription: does anyone have any examples of using jqGrid with twisted / python

description: Does anyone have any examples of using jqGrid with twisted / python


code: soup.find('td', text='Giraffe')

rawDescription: BeautufulSoup 4, findNext() function

description: BeautufulSoup 4, findNext() function


code:
# this is inside your function:
t,x,y = 0,1,2  # I don't know what your actual values are..
lookup = {'t': t, 'x': x, 'y': y}  # make this inside your function
tuple_ = tuple(lookup[k] for k in order.split(','))
tuple_

rawDescription: eval evaluates to a tuple

description: Eval evaluates to a tuple


rawDescription: python reg ex to include missing commas

description: Python reg ex to include missing commas


code:
words = [u'shift', u'magnetic', u'system', u'magnetic sensor', u'phase shift', u'phase', u'output', u'sensor', u'sensing', u'sensor system']
remove_comprising(words)

rawDescription: How to remove inception words in list?

description: Remove inception words in list


code:
import csv
import math

f = open('citydata.csv')

csv_f = csv.reader(f)
content = [row for row in csv_f]

for row in content[1:]:
    x1 = float(row[2])
    x2 = float(row[3])
    for rowOther in content[1:]:
        y1 = float(rowOther[2])
        y2 = float(rowOther[3])

        answer = (x1-(math.pow(x2,2))) - (y1-(math.pow(y2,2)))

        print(answer)

rawDescription: Manipulating rows of csv file in python

description: Manipulating rows of csv file in python


code:
import random
new_bool = random.choice([True, False])

# This works because the sublists are shared (obj=ref) between the two lists.
for e in list_fn1:
    e[BOOL_VALUE] = new_value

# This is the hard way:
for e in db:
    if e[FILE_NAME] == "file_name1":
        e[BOOL_VALUE] = new_Value

rawDescription: Simple table manipulation using python

description: Simple table manipulation using python


code:
def _login_check(f):
    @wraps(f)
    def wrapper(self):
        if self.log_in():
            return f(self)
        else:
            raise MyError('Not Logged In')
    return wrapper

rawDescription: Python class function not returning variable


code:
refs = lsremote('https://github.com/gitpython-developers/GitPython.git')
refs['HEAD']

rawDescription: `git ls-remote` in GitPython

description: `git ls-remote` in GitPython


code:
def count(mylist):
    newlist = []
    for i in mylist:
        stor = False
        for j in newlist:
            if j == i:
                stor = True
                break
        if not stor:
            newlist.append(i)
    return len(newlist)

rawDescription: Count different numbers in list python

description: Count different numbers in list python


rawDescription: Python netcraft API or replacement library


code:
def f(x,y):
    return np.sin(x)
x = y = np.arange(-3,3,.05)
X, Y = np.meshgrid(x, y)
zs = np.array([f(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
xy_pairs = np.array([str(x)+','+str(y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
xy_pairs = xy_pairs.reshape(X.shape)

gy,gx = np.gradient(Z,.05,.05)

rawDescription: Gradient calculation with python

description: Gradient calculation with python


code:
import wx
import wx.grid as gridlib

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

    #----------------------------------------------------------------------
    def __init__(self, parent):
        """Constructor"""
        wx.Panel.__init__(self, parent=parent)
        txt = wx.TextCtrl(self)
        button =wx.Button(self, label="Save", pos=(200, 325))
        button.Bind(wx.EVT_BUTTON, parent.onSwitchPanels)

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

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

        grid = gridlib.Grid(self)
        grid.CreateGrid(25,12)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(grid, 0, wx.EXPAND)
        self.SetSizer(sizer)

########################################################################
class MyForm(wx.Frame):

    #----------------------------------------------------------------------
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY,
                          "Panel Switcher Tutorial",
                          size=(800,600))

        self.panel_one = PanelOne(self)
        self.panel_two = PanelTwo(self)
        self.panel_two.Hide()

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

        menubar = wx.MenuBar()
        fileMenu = wx.Menu()
        switch_panels_menu_item = fileMenu.Append(wx.ID_ANY,
                                                  "Switch Panels",
                                                  "Some text")
        self.Bind(wx.EVT_MENU, self.onSwitchPanels,
                  switch_panels_menu_item)
        menubar.Append(fileMenu, '&File')
        self.SetMenuBar(menubar)

    #----------------------------------------------------------------------
    def onSwitchPanels(self, event):

        if self.panel_one.IsShown():
           self.SetTitle("Panel Two Showing")
           self.panel_one.Hide()
           self.panel_two.Show()
        else:
           self.SetTitle("Panel One Showing")
           self.panel_one.Show()
           self.panel_two.Hide()
        self.Layout()

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

rawDescription: Change panel with button wxpython

description: Change panel with button wxpython


rawDescription: Best way to strip punctuation from a string in Python

description: Strip punctuation from a string in Python


code:
for i in range(len(a)):
    x = a[i]
    x += 1

rawDescription: Grasping the basics of in-place operations


code:
for i in range(100):
    a_function()

rawDescription: Repeating a part of code in python 3.4.4


code:
df.loc[:,'test'] = Series(someValues,index=pd.MultiIndex.from_tuples([(0,10),(0,11),(1,10),(1,11),(1,14)]))
df

rawDescription: Set values of a column with numpy array

description: Set values of a column with numpy array


code:
[c for c in col_names if all(f not in c for f in filter_array)]
[c for c in col_names if not any(f in c for f in filter_array)]

rawDescription: Pythonic way of filtering out a list of strings from another list of strings


code:
df1 = df1.merge(df2[['Start Date', 'End Date', 'kWh']],
                how='left', left_on='START DATE', right_on='Start Date')

rawDescription: How to find the number of days between two dates for dataframe manipulation

description: Find the number of days between two dates for dataframe manipulation


code: new_array[np.array([y.size>0 for y in new_array])]

rawDescription: remove empty numpy array

description: Remove empty numpy array


code:
recepient = "user1@hotmailcom,user2@hotmail.com"
msg['To'] = recepient

rawDescription: Provide multiple email recepients in python script


code:
import time

timetup = time.strptime(inputstring, '%a %d %b %Y %I:%M %p %Z')
milliseconds = time.mktime(timetup) * 1000

rawDescription: Is there a built-in function or library that converts UTC time to milliseconds in Python?


code:
from bitstring import BitArray
s = BitArray('0b11011')
s += '0b100'
s += 'uint:5=9'
s += [0, 1, 1, 0, 1]
...
s.tobytes()

rawDescription: How to pack arbitrary bit sequence in Python?

description: Pack arbitrary bit sequence in Python


code: df[(df.Name == "ALEX") | (df.Name == "KIM")]

rawDescription: Using 'or' in a Dataframe

description: Using 'or' in a Dataframe


code: list(set( val for dic in d for val in dic.keys()))

rawDescription: Pandas: Reconstruct dataframe from strings of key:value pairs


code:
from django.test import TestCase
from models import SpecificModel

class TestData(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.test_item = SpecificModel.objects.create(data="some data")

rawDescription: Django: Keeping setUpTestData DRY

description: Django: Keeping setUpTestData DRY


code:
from django.http import HttpResponse

def some_view(request):
    if request.REQUEST.get('key') == 'value':
        if not request.user.is_authenticated():
            response = HttpResponse('Text to send if user hits Cancel button', status=401)
            response['WWW-Authenticate'] = 'Basic realm="My Realm'
            return response
        ...

rawDescription: Python/Django - HTTP authentication

description: Python/Django - HTTP authentication


code:
class DuplicatesPipeline(object):

    def __init__(self):
        self.ids_seen = set()

    def process_item(self, item, spider):
        if item['id'] in self.ids_seen:
            raise DropItem("Duplicate item found: %s" % item)
        else:
            self.ids_seen.add(item['id'])
            return item

rawDescription: Scrapy pipeline errors - list item usage


code:
import pickle

class Company(object):
    def __init__(self, name, value):
        self.name = name
        self.value = value

with open('company_data.pkl', 'wb') as output:
    company1 = Company('banana', 40)
    pickle.dump(company1, output, pickle.HIGHEST_PROTOCOL)

    company2 = Company('spam', 42)
    pickle.dump(company2, output, pickle.HIGHEST_PROTOCOL)

del company1
del company2

with open('company_data.pkl', 'rb') as input:
    company1 = pickle.load(input)
    print(company1.name)  # -> banana
    print(company1.value)  # -> 40

    company2 = pickle.load(input)
    print(company2.name) # -> spam
    print(company2.value)  # -> 42

rawDescription: Saving an Object (Data persistence in Python)


code:
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
  line.set_data([], [])
  return line,

# animation function.  This is called sequentially
def animate(i):
  x = np.linspace(0, 2, 1000)
  y = np.sin(2 * np.pi * (x - 0.01 * i))
  line.set_data(x, y)
  return line,

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                           frames=200, interval=20, blit=True)

anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

display_animation(anim)

rawDescription: Saving Animation with matplotlib?

description: Saving Animation with matplotlib


code: C = Cell(A)

rawDescription: Python copy and concatenate linked lists, preserve order


code:
from collections import Counter
from itertools import groupby
from operator import itemgetter

def ModeList(lst):
    counts = Counter(lst)
    grouped = groupby(counts.most_common(), itemgetter(1))
    return [i[0] for i in next(grouped)[1]]

ModeList( [2,4,6,8,6,8] )

rawDescription: Mode of a List - Python

description: Mode of a List - Python


code:
PROJECT_ROOT = os.path.dirname(__file__)
...
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')

rawDescription: Customize the Django settings.py file depending on the OS


code:
match = re.search(pattern, string)
if match:
   process(match)

rawDescription: Getting captured group in one line

description: Getting captured group in one line


code:
from scipy.spatial import distance
distance.euclidean((x0, y0), (x1, y1))

rawDescription: How to detect the nearest square to the image center points?

description: Detect the nearest square to the image center points


code:
import numpy as np

class Theta(np.recarray):
    ''' Defines a class for the parameters of a DDM model.

    '''
    def __new__(clc, *args, **kwargs):
        a = np.atleast_2d(np.array(*args, **kwargs))
        dtype = np.dtype([('v', '<f8'), ('a', '<f8'), ('w', '<f8')])
        r = np.recarray(shape=a.shape[0], dtype=dtype)
        r.v = a[:,0]
        r.a = a[:,1]
        r.w = a[:,2]
        return r.view(Theta)

r = Theta([[1,2,3],[1,2,3]])

rawDescription: Create view to recarray subclass

description: Create view to recarray subclass


rawDescription: Whats the best way to get the filesize?

description: Whats the best way to get the filesize


code:
# Unvectorized
def doACalculation(i, j):
    return i**2 + i*j + j

# Vectorized
def doACalculation(input):
    i, j = input
    return i**2 + i*j + j

# Vectorized, but with the original call signature
def doACalculation(i, j):
    return i**2 + i*j + j

rawDescription: Optimizing matrix writes in python/numpy


code:
def set_val(d, keys, val):
    reduce(lambda x,y: x[y], keys[:-1], d)[keys[-1]] = val

rawDescription: Pythonic way of accessing recursively nested dict


code:
fig, ax = plt.subplots()
marker = ax.scatter([0.2], [0.3], marker='+')

rawDescription: cross hairs in python animation

description: Cross hairs in python animation


rawDescription: Processing escaped url strings within json using python


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

from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms

class MagScale(mscale.ScaleBase):
    name = 'mag'

    def __init__(self, axis, **kwargs):
        mscale.ScaleBase.__init__(self)
        self.thresh = None #thresh

    def get_transform(self):
        return self.MagTransform(self.thresh)

    def set_default_locators_and_formatters(self, axis):
        pass

    class MagTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, thresh):
            mtransforms.Transform.__init__(self)
            self.thresh = thresh

        def transform_non_affine(self, mag):
            return 10**((np.array(mag) -1)/(-2.5))

        def inverted(self):
            return MagScale.InvertedMagTransform(self.thresh)

    class InvertedMagTransform(mtransforms.Transform):
        input_dims = 1
        output_dims = 1
        is_separable = True

        def __init__(self, thresh):
            mtransforms.Transform.__init__(self)
            self.thresh = thresh

        def transform_non_affine(self, flux):
            return -2.5 * np.log10(np.array(flux)) + 1.

        def inverted(self):
            return MagScale.MagTransform(self.thresh)

def flux_to_mag(flux):
    return  -2.5 * np.log10(flux) + 1

mscale.register_scale(MagScale)

rawDescription: Two corresponding y-axis

description: Two corresponding y-axis


code:
if minorallelefreq[x] <= int(0.1):
    minprop = minprop + 1
if minorallelefreq[x] > 0.1 and minorallelefreq[x] <= 0.2:
    minprop1 = minprop1 + 1

rawDescription: Why does the following loop keep returning me results of 0?


code:
def get_crypto_path():
    '''Auto import sometimes fails on linux'''
    import Crypto
    crypto_path = Crypto.__path__[0]
    return crypto_path

rawDescription: Pyinstaller not correclty importing pycripto... sometimes


code:
length = int(input("What is the length of tbe room you're trying to carpet?: "))
width = int(input("What is the width of tbe room you're trying to carpet?: "))
cost = int(input("What is the cost per square yard of tbe room you're trying to carpet?: "))

def carpet_cost(l,w,c):
    total_cost = ((l * w) / 3) * c
    print('The cost to carpet this room will be $', format(total_cost, ',.2f'))

carpet_cost(length,width,cost)

rawDescription: Beginner: Using a void function to calculate carpet cost in Python?


code:
if tag is Comment:
    file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))

rawDescription: How to output CDATA using ElementTree

description: Output CDATA using ElementTree


rawDescription: Plotting ticks on the x axis with positive and negative values, in strange order -Python


code:
encoded = '{"company_code": "ha", "from-date": "", "to-date": "", "ledger_type": "CLNT", "cost_center": "ALL", "margin": "wtmg"}'
decoded = json.loads(encoded)
decoded['company_code']

rawDescription: Not able to parse a json post from javascript in Python


code:
with open('myfile.txt', 'rb+') as f:
    last_pos = 0
    for line_number, line in enumerate(f):
        if is_the_right_line(line):
            f.seek(last_pos)
            f.write(new_line)
        last_pos = f.tell()

rawDescription: python replace random line in large file

description: Python replace random line in large file


code:
from datetime import timedelta
end = start + timedelta(1)
end

rawDescription: Determine start and end time of current day (UTC -> EST -> UTC) ; Python


code:
def chop_char(some_string):
    try:
        # determine if the second to last character is upper case
        if some_string[-2].istitle() and not some_string[-1].istitle():
            return some_string[:-1] # slice off the last character
    except IndexError:
        # string isn't long enough to have a 2nd to last char (i.e. it's only 1 character)
        pass
    return some_string

rawDescription: regular expression: chopping last character if second last is upper case?

description: Regular expression: chopping last character if second last is upper case


code:
pretty_time(3600)
pretty_time(3500)

rawDescription: Calculate the elapsed time in python

description: Calculate the elapsed time in python


rawDescription: Python: Round time to the nearest second and minute


code:
with codecs.open("testcodec.txt", "r","utf-8") as f3:
    s = f3.read()

# modify s here

with codecs.open("testcodec.txt", "w","utf-8") as f3:
    f3.write(s)

rawDescription: Which of those encoding methods is the most reliable one?


rawDescription: Pandas - count groupBy results

description: Pandas - count groupBy results


rawDescription: How to return a number as a binary string with a set number of bits in python

description: Return a number as a binary string with a set number of bits in python


rawDescription: python - iterate through list whose elements have variable length

description: Python - iterate through list whose elements have variable length


rawDescription: Tkinter canvas refreshing

description: Tkinter canvas refreshing


rawDescription: Markers not created after passing JSON

description: Markers not created after passing JSON


code:
df_old['source'] = 'old'
df_new['source'] = 'new'

rawDescription: Merging dataframes based on Time

description: Merging dataframes based on Time


code:
import BeautifulSoup
soup = BeautifulSoup.BeautifulSoup('
 ...
</html')
soup.find("div", {"id": "articlebody"})

rawDescription: Beautiful Soup and extracting a div and its contents by ID


code:
class Proxy(object):
    def __init__(self, object_a):
        self._object_a = object_a

    def decorateEnterExit(self, obj, f):
        def inner(*args, **kwargs):
            with obj as _:
                return f(*args, **kwargs)
        return inner

    def __getattribute__(self, name):
        obj = object.__getattribute__(self, '_object_a')
        dee = object.__getattribute__(self, 'decorateEnterExit')
        return dee(obj, getattr(obj, name))

rawDescription: Proxy pattern in Python

description: Proxy pattern in Python


code:
import re
response = """jsonFlickrApi({ "photo": { "id": "8566959299", "secret": "141af38562", "server": "8233", "farm": 9, "camera": "Apple iPhone 4S",
    "exif": [
      { "tagspace": "JFIF", "tagspaceid": 0, "tag": "JFIFVersion", "label": "JFIFVersion",
        "raw": { "_content": 1.01 } },
      { "tagspace": "JFIF", "tagspaceid": 0, "tag": "ResolutionUnit", "label": "Resolution Unit",
        "raw": { "_content": "inches" } },
      { "tagspace": "JFIF", "tagspaceid": 0, "tag": "XResolution", "label": "X-Resolution",
        "raw": { "_content": 72 },
        "clean": { "_content": "72 dpi" } },
      { "tagspace": "JFIF", "tagspaceid": 0, "tag": "YResolution", "label": "Y-Resolution",
        "raw": { "_content": 72 },
        "clean": { "_content": "72 dpi" } },
      { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLatitudeRef", "label": "GPS Latitude Ref",
        "raw": { "_content": "North" } },
      { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLatitude", "label": "GPS Latitude",
        "raw": { "_content": "39 deg 56' 44.40\"" },
        "clean": { "_content": "39 deg 56' 44.40\" N" } },
      { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLongitudeRef", "label": "GPS Longitude Ref",
        "raw": { "_content": "East" } },
      { "tagspace": "GPS", "tagspaceid": 0, "tag": "GPSLongitude", "label": "GPS Longitude",
        "raw": { "_content": "116 deg 16' 10.20\"" },
        "clean": { "_content": "116 deg 16' 10.20\" E" } }
    ] }, "stat": "ok" })"""
quoted_resp = re.sub('deg ([^"]+)"', r'deg \1\\"', response[14:-1])

rawDescription: parse special json format with python

description: Parse special json format with python


code:
import lxml.etree as ET
import os

filename = 'data.xml'
total_size = os.path.getsize(filename)
with open(filename, 'r') as f:
    context = ET.iterparse(f, events=('end', ), tag='Record')
    for event, elem in context:
        print(event, elem, float(f.tell())/total_size)

rawDescription: Iterating XML with lxml in Python: how to know how much of the input file has been read?


code:
import sys, csv

with open(sys.argv[1]) as f:
    lst = list(csv.reader(f))

rawDescription: Create list of tuples (in a more elegant way)


rawDescription: Split list of datetime objects into keys(date) and values(times)


code:
import Tkinter as tk
from contextlib import contextmanager

@contextmanager
def temp_change(widget, **kargs):
    old_values = {key:widget.cget(key) for key in kargs}
    widget.config(**kargs)
    try:
        yield #wait for `with` block to finish executing...
    finally:
        widget.config(**old_values)

window = tk.Tk()
var = tk.StringVar()
def validate(*args):
    print("Validation took place")
    return True
entry = tk.Entry(validate="focusin", validatecommand=validate)
print("Entry created. Associating textvariable")
entry.config(textvariable=var)
print("textvariable associated. Changing value")

with temp_change(entry, validate="none"):
    var.set("Text")

print("Value changed")
entry.pack()
tk.mainloop()

rawDescription: Preventing a tkinter Entry from gaining focus when its associated StringVar changes


rawDescription: Maximum and minimum caps for list values in Python


code:
import commands

def get_free_mem(node_name):
    sys_output = commands.getoutput('ssh %s \'free -m\'' % node_name)
    free_memory = sys_output.split()[9]
    return int(free_memory)

free_list = [get_free_mem(n) for n in node_names]
node_free_mem = dict(zip(node_names, free_list))

rawDescription: Python: Associating Function Output to Strings, then Combining into Dictionary


code:
import shutil

with open(filePath, 'r') as f, open('new_' + filePath, 'w') as output:
    for line in f:
        n = next(f)
        if n != '0\n':
            output.write(line+n)

shutil.move("new_" + filePath, filePath)

rawDescription: delete lines from file in python

description: Delete lines from file in python


code:
num = 127
order = len(str(num))
print(order) # prints 3

rawDescription: Getting the number of digits (Python)

description: Getting the number of digits (Python)


rawDescription: Trying to parse string and create new columns in data frame in Python pandas


code:
class Sentence(object):
    def __init__(self, the_sentence):
        self.the_string = the_sentence

sentence = Sentence("This is a sentence.")

rawDescription: Storing a string into a property

description: Storing a string into a property


code:
tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]
[v for t in tup_Before for v in t]
from itertools import chain
list(chain.from_iterable(tup_Before))

rawDescription: Flattening a list of tuples

description: Flattening a list of tuples


code:
def closest_node(points, datafield):
    mytree = scipy.spatial.cKDTree(datafield)
    dist, indexes = mytree.query(points)
    return indexes

rawDescription: Finding nearest xy-point in numpy array and second nearest with condition


code:
import java.io.FileInputStream;
import java.io.InputStream;
import net.razorvine.pickle.Unpickler;

rawDescription: Read python pickle data stream in Android


code:
footer = driver.find_element_by_tag_name("footer")
for _ in range(8):
    driver.execute_script("arguments[0].scrollIntoView();", footer)
    time.sleep(1)

rawDescription: Python Selenium press down arrow to dispay all page contents


code:
import logging
logger = logging.getLogger(__name__)

def save():
    logger.debug('Starting save')
    ...
    logger.debug('Exiting save')

rawDescription: Distributing tasks to modules in python

description: Distributing tasks to modules in python


rawDescription: Searching and counting dictionary key value pairs


code: r'FIRMWARE_VERSION =(".*")'

rawDescription: Find string in log files and return extra characters


code:
class Person(ndb.Model):
    @property
    def guilds(self):
        return Guild.query().filter(Guild.members == self.key)

class Guild(ndb.Model):
    members = ndb.KeyProperty(kind="Person", repeated=True)

    def add_person(self, person):
        self.members.append(person.key)
        self.put()

rawDescription: Many-To-Many Relationship in ndb

description: Many-To-Many Relationship in ndb


code:
import string

class PluralFormattter(string.Formatter):
    def get_value(self, key, args, kwargs):
        if isinstance(key, int):
            return args[key]
        if key in kwargs:
            return kwargs[key]
        if '(' in key and key.endswith(')'):
            key, rest = key.split('(', 1)
            value = kwargs[key]
            suffix = rest.rstrip(')').split(',')
            if len(suffix) == 1:
                suffix.insert(0, '')
            return suffix[0] if value <= 1 else suffix[1]
        else:
            raise KeyError(key)

data = {'tree': 1, 'bush': 2, 'flower': 3, 'cactus': 0}
formatter = PluralFormattter()
fmt = "{tree} tree{tree(s)}, {bush} bush{bush(es)}, {flower} flower{flower(s)}, {cactus} cact{cactus(i,us)}"
print(formatter.format(fmt, **data))

rawDescription: Plural String Formatting

description: Plural String Formatting


code: np.mean([misc.imread(f).astype(np.float32, copy = False) for f in files], axis = 0)

rawDescription: Averaged array calculation using numpy in Python


code: func(type='Event')

rawDescription: Converting Python dict to kwargs?

description: Converting Python dict to kwargs


code:
import pandas as pd
import xml.etree.ElementTree as ET

def iter_docs(author):
    author_attr = author.attrib
    for doc in author.iterfind('.//document'):
        doc_dict = author_attr.copy()
        doc_dict.update(doc.attrib)
        doc_dict['data'] = doc.text
        yield doc_dict

xml_data='''\
<author type="XXX" language="EN" gender="xx" feature="xx" web="foobar.com">
    <documents count="N">
        <document KEY="e95a9a6c790ecb95e46cf15bee517651" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="bc360cfbafc39970587547215162f0db" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="19e71144c50a8b9160b3f0955e906fce" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="21d4af9021a174f61b884606c74d9e42" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="28a45eb2460899763d709ca00ddbb665" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="a0c0712a6a351f85d9f5757e9fff8946" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="626726ba8d34d15d02b6d043c55fe691" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="2cb473e0f102e2e4a40aa3006e412ae4" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...] [...]
]]>
        </document>
    </documents>
</author>
'''

etree = ET.fromstring(xml_data) #create an ElementTree object
doc_df = pd.DataFrame(list(iter_docs(etree)))

rawDescription: How to convert an XML file to nice pandas dataframe?

description: Convert an XML file to nice pandas dataframe


rawDescription: DNA find all matching items from a list in a string (python 2.7)


code:
class Character(pygame.sprite.Sprite):
    def __init__(self, **kwargs):
        super(Character, self).__init__()
        for key, value in kwargs.items():
            setattr(self, key, value)

rawDescription: How to Create Instance Attributes By Lopping Over __init__ Arguments?


rawDescription: Transform a 3 columns (x, y, result) Python Pandas DataFrame to a DataFrame of result values with x (unique) as row and y (unique) as column


code: PlayerX += 10

rawDescription: Issues with movement in pygame

description: Issues with movement in pygame


code:
url = 'http://ratings.food.gov.uk/QuickSearch.aspx?q=po30'
br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
br.open(url)
response = br.response().read()

rawDescription: Screenscaping aspx with Python Mechanize - Javascript form submission


code:
from scrapy.item import Item, Field

class DoctorsItem(Item):
    doctor_name = Field()
    qualification = Field()
    membership = Field()
    visiting_hospitals = Field()
    phone = Field()
    consulting_hours = Field()
    specialist_in = Field()

rawDescription: Webscraping from directory of HTML files using BS4 and python


code:
def main() :
    # keep reference to threads
    threads = [threading.Thread(target=run) for _ in range(20)]
    # start all threads
    for t in threads:
        t.start()

    #20 jobs are put in the queue
    for x in range(1,21):
        q.put(x)

    for x in range(20):
        # stop all threads after tasks are done
        q.put('stop')

    # waits until queue is empty and then continues
    q.join()

    # join all threads
    for t in threads:
        t.join()

rawDescription: The correct implementation of queue.Queue when multithreading in Python


code:
def test(a, b, c):
    try:
        return a + b + c
    finally:
        pass # do whatever you want

rawDescription: Can I use finally statement with def statement?

description: Use finally statement with def statement


code: ssn = Element('SessionID', ns=ssnns).setText('123').addPrefix(p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')

rawDescription: How to pass SOAP headers into python SUDS that are not defined in WSDL file

description: Pass SOAP headers into python SUDS that are not defined in WSDL file


rawDescription: ZMQ Python Request Reply Broker for Addressed Asynchronous Requests


code:
previous = None
for item in my_list:
    if previous is None:
        previous = item
        continue
    # do something...

rawDescription: Pythonic approach to zipping items in a list


code:
from collections import Mapping
isinstance({}, Mapping)
isinstance((), Mapping)

rawDescription: How to test if object is a mapping (supports **O usage)

description: Test if object is a mapping (supports **O usage)


code:
def checkall(xs):
    for j, x in enumerate(xs):
        if abs(x) > (2 if j % 2 else 1):
            return -1
    return 1
cons = (checkall,)

rawDescription: Python: how to create many constraints for fmin_cobyla optimization using lambda functions


code:
if form.validate_on_submit():
    if current_user.get_id():
        session['new_gift_request'] = GiftRequest(
            current_user.id,
            form.giftee_name.data,
            form.giftee_age.data,
            int(form.giftee_sex.data),
            form.event.data,
            form.event_date.data,
            float(form.budget.data))

rawDescription: How to do login at end of other form submission in Flask?

description: Do login at end of other form submission in Flask


code:
RUNNING_MODE = "production"  # could also be "development", set manually

if ENVIRONMENT == "production":
    from production import *
elif ENVIRONMENT == "development":
    from development import *

rawDescription: Toggle between production and development


code:
# Slow, inefficient example
while len(arr) > 1:
  arr[:2] = some_operation(arr[0], arr[1])

rawDescription: operate through subarrays of an array recursively merging them (python)

description: Operate through subarrays of an array recursively merging them (python)


rawDescription: How to create a dictionary from a dictionary in python?

description: Create a dictionary from a dictionary in python


code:
words = sc.textFile("README.md")
def mapper(line):
    for word in line.split():
        yield (word, 1)
words.flatMap(mapper).take(4)
counts = words.flatMap(mapper).reduceByKey(lambda x, y: x + y)
counts.take(5)

rawDescription: List (or iterator) of tuples returned by MAP (PySpark)


code:
import random

population = list(range(100))

# Shuffle population so the ordering is random.
random.shuffle(population)

for sample_size in [1, 5, 10]:
    sample = population[-sample_size:]
    population[-sample_size:] = []
    print(sample)
    # [79]
    # [66, 89, 81, 0, 38]
    # [18, 39, 90, 36, 11, 32, 63, 65, 72, 67]

rawDescription: Selection without replacement - by mutating the list


code: ar = map(int, input().strip().split())

rawDescription: How do i take formatted input in python?

description: Take formatted input in python


rawDescription: Django: Extending Querysets / Connect multiple filters with OR


code: from __future__ import with_statement

rawDescription: Reading binary file in Python and looping over each byte


code:
import os as oops
'oops' in sys.modules

rawDescription: Python module check if

description: Python module check if


code: return ProductParts.gql('WHERE __key__ IN :key', key = self.defaultParts).fetch(1000)

rawDescription: Loading datasets from datastore and merge into single dictionary. Resource problem


code: {"UP": None, "DOWN": None, "RIGHT": None, "LEFT": None}

rawDescription: global varriable doesn't change

description: Global varriable doesn't change


code: summation = lambda: sum(n * (n + 1) / 2 for n in range(6))

rawDescription: Lambdas and sums Python

description: Lambdas and sums Python


code:
# np.where returns a tuple of index arrays, one per dimension
arr[np.where(mask)[0][-1]] = 100

print(repr(arr))
# array([  0,   1,   2, 100,   4])

rawDescription: Change n-th entry of NumPy array that fulfills condition


code: ordered_keys = ('z', 'y', 'e', 'x', 'w') # possible keys, in desired order

rawDescription: How to order xml element attributes in Python?

description: Order xml element attributes in Python


code:
import itertools
m = ["{0:02x}".format(i) for i in xrange(256)]
my_list = [m[i] + m[j] + m[k] for i,j,k
        in itertools.product(xrange(53,256), xrange(0,208), xrange(0,208))]

rawDescription: Create a list of hex codes given an Rgb range


code:
def checkpair (a,b,l):
    for x in l:
        if (a,b) == (x[2],x[0]):
            l.remove(x)

rawDescription: How do to fuzzy matching on excel file using Pandas?


rawDescription: Returning millisecond representation of datetime in python


code:
from tags_input import admin as tags_input_admin

class CategoryAdmin(tags_input_admin.TagsInputAdmin):
    list_display = ['name']

rawDescription: Using `raw_id_fields` to select related objects in the admin


rawDescription: Convert row to column header for Pandas DataFrame,


rawDescription: How can I write a csv file with multiple header lines with pandas to_csv()?

description: Write a csv file with multiple header lines with pandas to_csv()


code:
max64 = 0xffffffffffffffff
max64

rawDescription: make long integer in python 2 compatible in python 3

description: Make long integer in python 2 compatible in python 3


code:
d=OrderedDict((("fruit", "banana"), ("drinks", 'water'), ("animal", "cat")))
d.keys().index('animal')

rawDescription: How to know the position of items in a Python's ordered dictionary

description: Know the position of items in a Python's ordered dictionary


code:
from scipy.sparse import csr_matrix
x1 = csr_matrix([[1, 2], [3, 4]])
x2 = csr_matrix([1/2, 1/3])
print(x1.multiply(x2).todense())

rawDescription: General Matrix computation in Python, TF-IDF


rawDescription: What does the [0]*x syntax do in Python?

description: What does the [0]*x syntax do in Python


code: [[] for dummy in range(100)]

rawDescription: How to initialize a list to a certain value in Python

description: Initialize a list to a certain value in Python


code:
import re
import json

from bs4 import BeautifulSoup
import requests

url='http://ws.bursamalaysia.com/market/listed-companies/company-announcements/announcements_listing_f.html?_=1449326650932&callback=jQuery16208050466175191104_1449326525662&page_category=company&category=FA&sub_category=all&all_gm=&alphabetical=All&board=&sector=&date_from=&date_to=&company=5218&page=&testing='
pat = re.compile(r'\(\s*(\{[\s,\w,\W]*\})\s*\)')

r = requests.get(url)
js_obj = json.loads(pat.search(r.text).group(1))

soup = BeautifulSoup(js_obj.get('html'), 'lxml')

links = map(lambda a: a.get('href'), soup.find_all('a'))

for link in links:
    print(link)

rawDescription: Unable to do scraping href on jquery object


code:
import httplib2
import pprint

from apiclient.discovery import build
from oauth2client.client import SignedJwtAssertionCredentials

# Get the private key from the Google supplied private key file.
f = file("your_private_key_file.p12", "rb")
key = f.read()
f.close()

# Create the JWT
credentials = SignedJwtAssertionCredentials(
  "xxxxxxxxxx@developer.gserviceaccount.com", key,
  scope="https://www.googleapis.com/auth/calendar"
)

# Create an authorized http instance
http = httplib2.Http()
http = credentials.authorize(http)

# Create a service call to the calendar API
service = build("calendar", "v3", http=http)

# List all calendars.
lists = service.calendarList().list(pageToken=None).execute(http=http)
pprint.pprint(lists)

rawDescription: Sample of Server to Server authentication using OAuth 2.0 with Google API's


rawDescription: Python regex extract MAC addresses from string


code:
print('ID | cat1 | cat2 | cat3 | cat4 | cat5')
for line in table:
    print(' | '.join(line))

rawDescription: Create indicator list

description: Create indicator list


code:
a = "Hello","goodbye"  #Look Ma!  No Parenthesis!
print (type(a)) #<type 'tuple'>
a = ("Hello")
print (type(a)) #<type 'str'>
a = ("Hello",)
print (type(a)) #<type 'tuple'>
a = "Hello",
print (type(a)) #<type 'tuple'>

rawDescription: How to properly convert list of one element to a tuple with one element

description: Properly convert list of one element to a tuple with one element


code:
def hex(s):
    _hexer = "0123456789ABCDEF"
    return sum([_hexer.find(var) * 16 ** i for i, var in enumerate(reversed(s.upper()))])

rawDescription: Writing a function to convert hex to decimal


code:
allletters = set(list('abcdefghijklmnopqrstuvwxyz'))
while( len(usedletters) != len(allletters) ):
    guessedletter = raw_input("pick a letter")
    allletters.difference_update(guessedletter)

rawDescription: letter/word guessing game in python

description: Letter/word guessing game in python


code:
import matplotlib.pyplot as plt

line, = plt.plot([1,5,2,4], '-')
line.set_dashes([8, 4, 2, 4, 2, 4])
plt.show()

rawDescription: python matplotlib dash-dot-dot - how to?

description: Python matplotlib dash-dot-dot - how to


rawDescription: Using "tornado.httpclient" fetch "POST https" site get "HTTPError: HTTP 599"


code:
def get_selection_manual(self, event):
    self.span = matplotlib.widgets.SpanSelector(self.ax, \
        self.process_selection_manual, "horizontal", \
        rectprops=dict(alpha=0.5, facecolor="red"))

rawDescription: wxPython and matplotlib.widgets

description: WxPython and matplotlib.widgets


code:
import csv
from collections import defaultdict

d_entries = defaultdict(list)

with open('fileTwo.csv', 'r') as f_fileTwo:
    csv_fileTwo = csv.reader(f_fileTwo)
    header_fileTwo = next(csv_fileTwo)
    for cols in csv_fileTwo:
        d_entries[cols[0]].append([cols[0], ''] + cols[1:])

with open('fileOne.csv', 'r') as f_fileOne, open('result.csv', 'w', newline='') as f_result:
    csv_fileOne = csv.reader(f_fileOne)
    csv_result = csv.writer(f_result)
    header_fileOne = next(csv_fileOne)
    csv_result.writerow(header_fileOne)

    for cols in csv_fileOne:
        if cols[0] in d_entries:
            csv_result.writerows(d_entries.pop(cols[0]))
        csv_result.writerow(cols)

rawDescription: How to merge two CSV files by Python based on the common information in both files?

description: Merge two CSV files by Python based on the common information in both files


code:
from functools import wraps

def live_doc(func):
    template = func.__doc__
    @wraps(func)
    def wrapper(*args, **kwargs):
        ret_val = func(*args, **kwargs)
        args_pretty = ", ".join(repr(a) for a in args)
        kw_pretty = ", ".join("%s=%r" % (k, v) for k, v in kwargs.items())
        signature = ", ".join(x for x in (args_pretty, kw_pretty) if x)
        name =  func.__name__
        wrapper.__doc__ = template % locals()
        return ret_val
    return wrapper

@live_doc
def f(x, y):
    """%(name)s was called with %(signature)s and returned %(ret_val)r."""
    return x + len(y)

rawDescription: How to define a decorator that will provide an interpolated doc string for a function/method call

description: Define a decorator that will provide an interpolated doc string for a function/method call


code: ts.groupby(lambda x : x.date()).sum().plot(rot=30, style='x-', kind='bar')

rawDescription: matplotlib time vs date

description: Matplotlib time vs date


code:
import matplotlib.pyplot as plt

plt.savefig('image.png') # save to png
plt.savefig('image.pdf') # save to pdf

rawDescription: Python pandas.io.data save plot?

description: Python pandas.io.data save plot


rawDescription: Read 2 lines of a file into a dataframe with two columns using pandas read_csv()


code:
def factorial(n):
    """Return the factorial of n, an exact integer >= 0.

    >>> [factorial(n) for n in range(6)]
    [1, 1, 2, 6, 24, 120]
    >>> factorial(30)
    265252859812191058636308480000000
    >>> factorial(-1)
    Traceback (most recent call last):
        ...
    ValueError: n must be >= 0

    Factorials of floats are OK, but the float must be an exact integer:
    >>> factorial(30.1)
    Traceback (most recent call last):
        ...
    ValueError: n must be exact integer
    >>> factorial(30.0)
    265252859812191058636308480000000

    It must also not be ridiculously large:
    >>> factorial(1e100)
    Traceback (most recent call last):
        ...
    OverflowError: n too large
    """

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

rawDescription: Best way to develop a programme without using reload

description: Develop a programme without using reload


code: [''.join(p) for p in product(*poss)]

rawDescription: Creating all combinations of a string given character values from a dictionary in python


code:
print(1)
print(2)
print(3)
toto = 5

rawDescription: Python 2 How to debug code injected by the exec block


rawDescription: python sort lists from 1 list based on date elements

description: Python sort lists from 1 list based on date elements