code:
def foldersSave(self):
    folders = QtCore.QStringList()
    foldersnum = self.configDialog.FolderLIST.count()
    if foldersnum:
        for i in range(foldersnum):
            print (i, " position is saved: ", self.configDialog.FolderLIST.item(i).text())
            folders.append(self.configDialog.FolderLIST.item(i).text())
        return folders
    return None

rawDescription: How to save and load QListWidjet contents to/from QSetting with PyQt4?

description: Save and load QListWidjet contents to/from QSetting with PyQt4


code:
class DeviceSerializer(serializers.ModelSerializer):
    logs_url = serializer.SerializerMethodField()

    def get_logs_url(self, device):
        return self.context['request'].build_absolute_uri(device.get_logs_url())

rawDescription: Django rest frameworok

description: Django rest frameworok


rawDescription: Running unit tests with Nose inside a Python environment such as Autodesk Maya?


code:
class Book(models.Model):
    name = models.CharField(max_length=100)
    author = models.ForeignKey(settings.AUTH_USER_MODEL)

rawDescription: Django - 'Created by'-Field

description: Django - 'Created by'-Field


code:
rows = json.loads(x)
with open('test.csv', 'wb+') as f:
    dict_writer = csv.DictWriter(f, fieldnames=['longitude', 'latitude'])
    dict_writer.writeheader()
    dict_writer.writerows(rows)

rawDescription: Convert JSON to CSV using Python (Idle)

description: Convert JSON to CSV using Python (Idle)


code:
pos_values = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date >= 0]
neg_values = df.prediction_at_ohlcv_end_date[df.prediction_at_ohlcv_end_date < 0]

rawDescription: Separating positive and negative values of pandas DataFrame


rawDescription: How do I pass a Python Variable to Bash?

description: Pass a Python Variable to Bash


code:
import configuration as cf

def main(host, pnum, num, serv, data, **kwargs):
    intermediate_function(
        host, pnum, num, 'other', 'params', 'here'
    )

def intermediate_function(host, pnum, num, *args):
    pass

# Now, you can call this function, with your
# dictionary as keyword arguments
if __name__ == '__main__':
    main(**cf.constants)

rawDescription: Organizing code for Testing with Constants from a Configuration File


code:
def gen(maxlen):
    pattern = "{{:0{}b}}".format(maxlen)
    for i in range(0, 2**maxlen, 2):
        s = pattern.format(i) # not ideal, because we always format to test for "11"
        if "11" not in s:
            yield s

rawDescription: Generate all strings of length X that end with '0' and have no adjacent '1's


code:
X2 = vectorizer.transform(documents2)
X = np.vstack((X, X2))
model.fit(X) # optimally you would start from the previous solution, but sklearn does not yet support it

rawDescription: Adding feature to k-means

description: Adding feature to k-means


code:
p1, = plt.plot(time_model, rv_model_primary, 'k-')
p2, = plt.plot(time_model_sec, rv_model_secondary, 'k--')
p3, = plt.plot(time_obs, rv_obs_primary, 'bo')
p4, = plt.plot(time_obs_apg, rv_obs_primary_apg, 'ro')
p5, = plt.plot(time_obs_apg_sec, rv_obs_secondary_apg, 'rs')

rawDescription: Two unique marker symbols for one legend


code:
f = open("output.txt", 'w')
buf = []
show = False
for line in lines:
    if line.startswith('Table'):
        if show:
            f.writelines(buf)
        buf = []
        show = True
    buf.append(line)
    if line.find('failed 0') >= 0:
        show = False
if show:
    f.writelines(buf)
f.close()

rawDescription: Script/regex for log file editing

description: Script/regex for log file editing


code: square_list = [i**2 for i in range(1,6)]

rawDescription: what do the brackets mean around this python line?

description: What do the brackets mean around this python line


code:
def integers():
    i = 0
    while True:
        yield i

rawDescription: Is there a Python idiom for evaluating a list of functions/expressions with short-circuiting?


code:
def prefetch_refprops(entities, *props):
    """Dereference Reference Properties to reduce Gets.  See:
    http://blog.notdot.net/2010/01/ReferenceProperty-prefetching-in-App-Engine
    """
    fields = [(entity, prop) for entity in entities for prop in props]
    ref_keys = [prop.get_value_for_datastore(x) for x, prop in fields]
    ref_entities = dict((x.key(), x) for x in db.get(set(ref_keys)))
    for (entity, prop), ref_key in zip(fields, ref_keys):
        prop.__set__(entity, ref_entities[ref_key])
    return entities

rawDescription: List of References in Google App Engine for Python


code:
spectra_set = set((str(spectraItem[0]), str(spectraItem[25])) for spectraItem in spectraFinal)

returnList = []
for r120item in r120Final:
    if (r120item[2].strip(), r120item[10]) not in spectra_set:
       returnList.append(r120item)

rawDescription: Nested for loop to search 2 lists

description: Nested for loop to search 2 lists


code:
av = a.view(np.complex)
_,inv = np.unique(av,return_inverse=True)

rawDescription: Indexing the unique rows of an array

description: Indexing the unique rows of an array


code:
data=''',,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo,
'''.splitlines()
rdr= csv.reader( data )
row= rdr.next()
row
row[:6] + [ row[6]+row[7]+row[8] ] +  row[9:]

rawDescription: How can I merge fields in a CSV string using Python?

description: Merge fields in a CSV string using Python


code:
def pickdict(d,*names):
    "picks some values from a dict"
    return {n:d[n] for n in names}

class Obj(object):
    "example inserting some named args as instance attributes"
    def __init__(self, arg1, arg2=4):
        self.__dict__.update(pickdict(locals(),'arg1','arg2'))

rawDescription: Is it possible get a dictionary of passed in parameters similar to kwargs(python)?


rawDescription: Why list created by code does not include values greater than 99,999 (Python)


code:
results = dict((tuple(span.attrs['class']), span.text) for td in soup.find_all('td', {'class': 'section'}) for span in td.find_all('span'))
results

rawDescription: BeautifulSoup: Extracting Value from Children nodes


code:
import email

message = email.message_from_string(text)
to_headers = message.get_all('to')
addresses = email.utils.getaddresses(to_headers)

rawDescription: Ignore strings which do not completely match regex?


code:
activity_set = Activity.objects.raw("""
 SELECT
   myapp_activity.* from myapp_activity, myapp_user
 WHERE
   myapp_activity.user_id=myapp_user.user_id
   and myapp_activity.date - myapp_user.install_time > '2 days'
""")

rawDescription: Check ID across tables using Django Queryset


code:
avg_values = ['temperature', 'no2', 'co', 'humidity']
average_value = entries_for_period.aggregate(*[Avg(x) for x in avg_values])
return {x:average_value['%s__avg' % x] for x in avg_values}

rawDescription: How to aggregate data in django?

description: Aggregate data in django


code: ' '.join(names)

rawDescription: Use of a deprecated module 'string'

description: Use of a deprecated module 'string'


code: [{r["section"]: r["title"]} for r in listofdict]

rawDescription: Difference between Python dictionary comprehension and loop


code:
def getFromDict(dataDict, mapList):
    return reduce(lambda d, k: d[k], mapList, dataDict)

rawDescription: Access python nested dictionary items via a list of keys


code:
import threading

class Java:
   cout = 0
   lock = threading.RLock()

   def increment():
       with Java.lock:
           Java.cout += 1

rawDescription: python lock method annotation

description: Python lock method annotation


code:
response = render(request, 'command.html', {'result': request.META.items()})
response.set_cookie('cookie_name', 'cookie_value')
return response

rawDescription: Why I can not get cookies from requests.get


rawDescription: Regular expressions from a list previously specified


code:
idinfo = root[0]

#Create keyworks element
keywords = ET.SubElement(idinfo, "keywords")
tree.write(tempXmlExportPath)

#Create theme child
theme = ET.SubElement(keywords, "theme")
tree.write(tempXmlExportPath)

#Create themekt and themekey grandchildren/insert tag info
themekt = ET.SubElement(theme, "themekt")
tree.write(tempXmlExportPath)
for tag in tags: #tags list from your dictionary
    themekey = ET.SubElement(theme, "themekey")
    themekey.text = tag
    tree.write(tempXmlExportPath)

rawDescription: updating metadata for feature classes programatically using arcpy

description: Updating metadata for feature classes programatically using arcpy


rawDescription: supress scientific notation when writing python floats to files

description: Supress scientific notation when writing python floats to files


code: d = as_strided(a, strides=(a.strides[1], a.strides[3], a.strides[0] + a.strides[2]), shape=(3, 3, 7))

rawDescription: Modifying diagonals in multidimensional numpy arrays


code:
numAndSize = re.compile(r'(\d+)[xX](\d+(?:\.\d+)?)')
numAndSize.findall("Product:A,2x3.5gallonbottles")

rawDescription: Odd behavior with Python regular expressions - findall only finds the "()?" portion


code:
Z = np.arange(N**3).reshape(N,N,-1)
np.dot(X,A) + np.dot(W,B)[:,None] + np.dot(Z, G)

rawDescription: Compute each element of matrix

description: Compute each element of matrix


code:
def __call__(self, event):
    stop_chaining = False
    if self.pevent is not None:
        # By default methods return None so we set as guideline
        # that methods asking for stop chaining must explicitly
        # return non None or non False values, otherwise the default
        # behavior will be to accept chain call to the corresponding
        # local method.
        stop_chaining = self.pevent(event)
    if not stop_chaining:
        return _ProcessEvent.__call__(self, event)

rawDescription: python pyinotify to monitor the specified suffix files in a dir

description: Python pyinotify to monitor the specified suffix files in a dir


code:
def lingregress(data):
    x_name = data.columns[0]
    y_name = data.columns[1]
    x = data[x_name]
    y = data[y_name]
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
    r_sq = r_value ** 2

    plt.scatter(x,y)
    plt.xlabel(x_name)
    plt.ylabel(y_name)
    plt.title('{x_name} vs. {y_name}'.format(x_name=x_name, y_name=y_name))
    plt.plot(x,intercept + slope * x,c='r')

    print('The slope is %.2f with R squared of %.2f' % (slope, r_sq))

lingregress(data)

rawDescription: Set matplotlib plot axis to be the dataframe column name


code:
@contextmanager
def wait_for_new_window(driver, timeout=10):
    handles_before = driver.window_handles
    yield
    WebDriverWait(driver, timeout).until(
        lambda driver: len(handles_before) != len(driver.window_handles))

rawDescription: Python. Selenium. How to wait for new window opens?


code:
class YouForm(forms.Form):
    # Everything as before.
    ...

    def clean(self):
       """ This is the form's clean method, not a particular field's clean method """
       cleaned_data = self.cleaned_data

       account = cleaned_data.get("account")
       is_master = cleaned_data.get("is_master")
       username = cleaned_data.get("username")

       if AccountAdmin.objects.filter(account=account, is_master=is_master).count() > 0:
           del cleaned_data["account"]
           del cleaned_data["is_master"]
           raise forms.ValidationError("Account and is_master combination already exists.")

       if AccountAdmin.objects.filter(account=account, username=username).count() > 0:
           del cleaned_data["account"]
           del cleaned_data["username"]
           raise forms.ValidationError("Account and username combination already exists.")

    # Always return the full collection of cleaned data.
    return cleaned_data

rawDescription: Django: How do I validate unique_together from within the model


code:
for rows in data.itertuples():
    r = int(rows[0]) + 1
    for c, i in enumerate(rows):
        #skip the first value
        if c == 0:
            continue
        #do whatever here

rawDescription: for loop after specific index with python not working

description: For loop after specific index with python not working


code:
reshaped.sort_values(by=['trader', 'stock','day'], inplace=True)
reshaped['cumq']=reshaped.groupby(['trader', 'stock']).delta.cumsum()
reshaped.loc[ reshaped.cumq == 0, '_spell' ] = 1
reshaped['_spell'] = reshaped.groupby(['trader','stock'])['_spell'].cumsum()
reshaped['_spell'] = reshaped.groupby(['trader','stock'])['_spell'].bfill().fillna(0)

rawDescription: how to speed-up a very slow pandas apply function?

description: Speed-up a very slow pandas apply function


code: {(x[0], x[1]): x for x in L}.values()

rawDescription: Removing Duplicates from Nested List Based on First 2 Elements


rawDescription: Multiple IF conditions in a python list comprehension


code:
import numpy as np
import scipy.stats as st

def gkern(kernlen=21, nsig=3):
    """Returns a 2D Gaussian kernel array."""

    interval = (2*nsig+1.)/(kernlen)
    x = np.linspace(-nsig-interval/2., nsig+interval/2., kernlen+1)
    kern1d = np.diff(st.norm.cdf(x))
    kernel_raw = np.sqrt(np.outer(kern1d, kern1d))
    kernel = kernel_raw/kernel_raw.sum()
    return kernel

rawDescription: How to calculate a Gaussian kernel matrix efficiently in numpy?

description: Calculate a Gaussian kernel matrix efficiently in numpy


code: time, data = np.genfromtxt('./temp.csv', delimiter=',').transpose()

rawDescription: Use numpy to read a two-column csv file

description: Use numpy to read a two-column csv file


rawDescription: How to see signals from QWidgets inside dynamically created QTabWidget pages?

description: See signals from QWidgets inside dynamically created QTabWidget pages


code:
while True:
     do_stuff()      # this line gets executed at least once
     if condition:
         break

rawDescription: Is there a specific way of creating a REPEAT_UNTIL loop in python?


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

row = ['a','b','c']
col = ['A','B','C','D']

data = [[(i+j, round(np.random.uniform(0, 1), 4)) for j in col] for i in row]
df = pd.DataFrame(data, index=row, columns=col)
print(df)

rawDescription: Python: Pandas DataFrame for tuples

description: Python: Pandas DataFrame for tuples


code:
tmp = x[2]
y = tmp[:]  # this only makes a copy, does nothing else

rawDescription: Why doesn't the Python 2D array index order matter when used with colon ( : )


code:
self.menu_left.grid(row=0, column=0, rowspan=2, sticky="nsew")
self.some_title_frame.grid(row=0, column=1, sticky="ew")
self.canvas_area.grid(row=1, column=1, sticky="nsew")
# you don't have a status bar in the example code, but if you
# did, this is where you would put it
# self.status_frame.grid(row=2, column=0, columnspan=2, sticky="ew")

rawDescription: Tkinter: grid or pack inside a grid?

description: Tkinter: grid or pack inside a grid


rawDescription: Python regex partial extract

description: Python regex partial extract


code:
import numpy as np
import scipy.linalg as SL
import matplotlib.pyplot as plt

Pxx = np.genfromtxt('mBtasJLD.txt')
U, s, Vh = SL.svd(Pxx, full_matrices=False)
assert np.allclose(Pxx, np.dot(U, np.dot(np.diag(s), Vh)))

s[2:] = 0
new_a = np.dot(U, np.dot(np.diag(s), Vh))
print(new_a)
plt.plot(new_a)
plt.show()

rawDescription: SVD - Matrix transformation Python

description: SVD - Matrix transformation Python


code: my.func(a, b, c, my.MULTLINE, my.IGNORECASE)

rawDescription: Python: passing flags to functions

description: Python: passing flags to functions


rawDescription: Sorted Word frequency count using python


code: finalPass = extra[len(initialPass)] + finalPass + "{0:04b}".format(len(initialPass))

rawDescription: Better replacement for a huge "if x==2 / if x==3 / if x==4" chain adding prefixes and suffixes?


code:
p = subprocess.Popen(["head", "-n", "1"], stdin=subprocess.PIPE)
p.communicate('first\nsecond')

rawDescription: How do I pass a string into subprocess.Popen in Python 2?

description: Pass a string into subprocess.Popen in Python 2


code:
import sys
import os
path = os.path.dirname(sys.modules[__name__].__file__)
path = os.path.join(path, '..')
sys.path.insert(0, path)
from myprog import function_you_referenced_from_init_file

rawDescription: Using module's own objects in __main__.py


code:
class Person(object):
    name = ""
    age  = ""
    addresses = []

rawDescription: Python OOP: How do I link multiple classes objects to one object


code:
if request.user.is_authenticated():
    if request.method == 'POST':
        form = PersonEditForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('/success/'))

    else:
        form = PersonEditForm(instance=request.user, initial={'username': request.user.username})

    return render_to_response(template_name, {"form": form },
                          context_instance = RequestContext(request))

rawDescription: Clean django user.username

description: Clean django user.username


code:
if 'script_name' not in attrs:
    attrs['script_name'] = os.path.basename(sys.argv[0])
if 'script_args' not in attrs:
    attrs['script_args'] = sys.argv[1:]

rawDescription: Directly call distutils' or setuptools' setup() function with command name/options, without parsing the command line?


rawDescription: Remove tuples in a 2D numpy array that satisfy 2 conditions


code:
import subprocess

subprocess.call(['C:\\Temp\\a b c\\Notepad.exe', 'C:\\test.txt'])

rawDescription: How to run/execute exe file in python?

description: Run/execute exe file in python


code:
make_pattern("n n bacon n")
re.findall(make_pattern("n n bacon n"), "spam spam eggs bacon and spam")

rawDescription: Group m groups with regex

description: Group m groups with regex


code:
import csv
import numpy as np

# Pull in all the raw data.
raw = np.fromfile('TEMPO3.2F-0215_s00116.dat', np.float64)

# Throw away the nan entries.
raw = raw[1::2]

# Reshape and take the transpose to manipulate it into the
# same shape as your CSV. The conversion to integer is also
# so the CSV file is the same.
data = raw.reshape((6, -1)).T.astype('int')

# Dump it out to a CSV.
with open('test.csv', 'w') as f:
    w = csv.writer(f)
    w.writerows(data)

rawDescription: Equivalent of Matlab's fread() 'float64' in Python


rawDescription: How to parse this json in Python

description: Parse this json in Python


rawDescription: Substract two Pandas Dataframes

description: Substract two Pandas Dataframes


rawDescription: Multiple dot syntax in python and matplotlib


rawDescription: NLTK: can I add terminal to grammar that is already generated


code:
keyarray = np.array(['S','M','L','XL'])
data = np.array([[0,2,1], [1,3,2]])
keyarray[data]

rawDescription: Replace values of a numpy array by values from another numpy array


code:
from bs4 import BeautifulSoup

soup = BeautifulSoup(html)
matched = soup.select('#__VIEWSTATE')
if matched:
    value = matched[0].get('value')

rawDescription: Python find value of view state given source


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

# initialize parsing from Bytes buffer
from io import BytesIO
xmlDocument = BytesIO(xmlDocument.encode('utf-8'))

# initialize dictionaries storing the information to each type of row
messageRow, streetRow, linkRow = {}, {}, {}

# initialize list that stores the single dataframe rows
listOfRows = []

# read the xml file line by line and throw signal when specific tags start or end
for event, element in ET.iterparse(xmlDocument, events=('start', 'end')):

    ##########
    # get all information on the current message and store in the appropriate dictionary
    ##########

    # get current message's id attribute
    if event == 'start' and element.tag == 'Message':
        messageRow = {} # re-initialize the dictionary for the current row
        messageRow['messageId'] = element.get('id')

    # get current message's status
    if event == 'end' and element.tag == 'status':
        messageRow['status'] = element.text

    # get current message's priority
    if event == 'end' and element.tag == 'priority':
        messageRow['priority'] = element.text

    # when no more information on the current message is expected, append it to the list of rows
    if event == 'end' and element.tag == 'priority':
        listOfRows.append(messageRow)

    ##########
    # get all information on the current street and store in row dictionary
    ##########

    if event == 'end' and element.tag == 'name':
        streetRow = {} # re-initialize the dictionary for the current street row
        streetRow['streetName'] = element.text

    if event == 'end' and element.tag == 'length':
        streetRow['streetLength'] = element.text

    # when no more information on the current street is expected, append it to the list of rows
    if event == 'end' and element.tag == 'length':

        # link the street to the message it belongs to, then append
        streetRow['messageId'] = messageRow['messageId']
        listOfRows.append(streetRow)

    ##########
    # get all information on the current link and store in row dictionary
    ##########

    if event == 'end' and element.tag == 'id':
        linkRow = {} # re-initialize the dictionary for the current link row
        linkRow['linkId'] = element.text

    if event == 'end' and element.tag == 'direction':
        linkRow['direction'] = element.text

    # when no more information on the current link is expected, append it to the list of rows
    if event == 'end' and element.tag == 'direction':

        # link the link to the message it belongs to, then append
        linkRow['messageId'] = messageRow['messageId']
        listOfRows.append(linkRow)

rawDescription: Read hierarchical (tree-like) XML into a pandas dataframe, preserving hierarchy


code:
site_info = Siteinfo.objects.get(makesite__sitename=site, description=name) # only 1 query
site_info.description = "new description"
site_info.save()

rawDescription: How to delete a many to many object without deleting all objects within the relationship?

description: Delete a many to many object without deleting all objects within the relationship


rawDescription: List comprehension to create list of strings from two lists


rawDescription: accessing value of a python @property

description: Accessing value of a python @property


rawDescription: Python: How do I format a date in Jinja2?


code:
s = ['6','5','7','7','6']
with open('test.csv', 'wb') as test_file:
   test_file.write("\n".join(s) + "\n")

rawDescription: Writing output in first column of csv

description: Writing output in first column of csv


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

class QtSingleApplication(QApplication):

    messageReceived = Signal(unicode)

    def __init__(self, id, *argv):

        super(QtSingleApplication, self).__init__(*argv)
        self._id = id
        self._activationWindow = None
        self._activateOnMessage = False

        # Is there another instance running?
        self._outSocket = QLocalSocket()
        self._outSocket.connectToServer(self._id)
        self._isRunning = self._outSocket.waitForConnected()

        if self._isRunning:
            # Yes, there is.
            self._outStream = QTextStream(self._outSocket)
            self._outStream.setCodec('UTF-8')
        else:
            # No, there isn't.
            self._outSocket = None
            self._outStream = None
            self._inSocket = None
            self._inStream = None
            self._server = QLocalServer()
            self._server.listen(self._id)
            self._server.newConnection.connect(self._onNewConnection)

    def isRunning(self):
        return self._isRunning

    def id(self):
        return self._id

    def activationWindow(self):
        return self._activationWindow

    def setActivationWindow(self, activationWindow, activateOnMessage = True):
        self._activationWindow = activationWindow
        self._activateOnMessage = activateOnMessage

    def activateWindow(self):
        if not self._activationWindow:
            return
        self._activationWindow.setWindowState(
            self._activationWindow.windowState() & ~Qt.WindowMinimized)
        self._activationWindow.raise_()
        self._activationWindow.activateWindow()

    def sendMessage(self, msg):
        if not self._outStream:
            return False
        self._outStream << msg << '\n'
        self._outStream.flush()
        return self._outSocket.waitForBytesWritten()

    def _onNewConnection(self):
        if self._inSocket:
            self._inSocket.readyRead.disconnect(self._onReadyRead)
        self._inSocket = self._server.nextPendingConnection()
        if not self._inSocket:
            return
        self._inStream = QTextStream(self._inSocket)
        self._inStream.setCodec('UTF-8')
        self._inSocket.readyRead.connect(self._onReadyRead)
        if self._activateOnMessage:
            self.activateWindow()

    def _onReadyRead(self):
        while True:
            msg = self._inStream.readLine()
            if not msg: break
            self.messageReceived.emit(msg)

rawDescription: QtSingleApplication for PySide or PyQt

description: QtSingleApplication for PySide or PyQt


code:
for tweet in tweets: #contains list of dictionaries
    text = tweet.get('text')
    if text is not None:
        matches = re.findall(r"#(\w+)", text)
        # Test whether any matches were found
        if matches:
            tweet_text.append(matches)

rawDescription: Iterating over list and appending value to new list


code: title = getattr(soup.find("h1", "article-title"), "string", "none")

rawDescription: Python - safe & elegant way to set a variable from function that may return None


code:
import pympler.asizeof
pympler.asizeof.asizeof(w)
pympler.asizeof.asizeof(n)

rawDescription: Python: How does inheritance of __slots__ in subclasses actually work?


code:
import nonedict
foo = nonedict.NoneDict()

rawDescription: Classes Inside Modules

description: Classes Inside Modules


code:
timeit.timeit('way1(listOfRandomInts,dictionaryOfRandomInts)', setup=setup, number=1000)
timeit.timeit('way6(listOfRandomInts,dictionaryOfRandomInts)', setup=setup, number=1000)

rawDescription: Finding all keys in a dictionary from a given list QUICKLY


code: print("The length of '", word,"' is ", word_length, sep = '')

rawDescription: How do I include quotation marks in a print statement if I am using a variable

description: Include quotation marks in a print statement if I am using a variable


code:
efg
egf
xyz
abc

rawDescription: Python how to find out the unique elements in a text file and output in another text file


code:
import Tkinter
root = Tkinter.Tk()
for i in xrange(times):
    Tkinter.Label(root, image=image).pack()
root.mainloop() # Start the GUI

rawDescription: Add images dynamically based on random number


code:
def create_detail_url(url_string, view_method_name, view_name):
    url_string = r"^(?P<resource_name>%s)/(?P<%s>.*?)" + url_string + r"%s$"
    url_string = url_string % (self._meta.resource_name, self._meta.detail_uri_name, trailing_slash())
    return url(url_string, self.wrap_view(view_method_name), name="api_" + view_name)

rawDescription: How does tastypie handle comlex url?

description: How does tastypie handle comlex url


code:
dfs = pd.read_sql(..., chunksize=100000)
for df in dfs:
    clean_df = ...
    clean_df.to_sql(..., if_exists='append')

rawDescription: Looking for a python datastructure for cleaning/annotating large datasets


code:
def other_entry1(self, selection, row):
    if selection == "Other":
        var = StringVar()
        Entry(self.frame1, textvariable=var).grid(row=row, column=6)

#Calling it as part of an optionMenu
self.e33 = OptionMenu(self.frame1, self.ea_tf, *fixtures, command=lambda selection:self.other_entry1(selection,15))

rawDescription: What's the difference between these two functions in Tkinter?


code:
import wx

class MyForm(wx.Frame):

    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Tutorial")

        # create the main sizer
        self.mainSizer = wx.BoxSizer(wx.VERTICAL)

        # Add a panel so it looks the correct on all platforms
        self.panel = wx.Panel(self, wx.ID_ANY)

        lbls = ["labelOne", "lblTwo", "lblThree"]
        for lbl in lbls:
            self.buildLayout(lbl)
        self.panel.SetSizer(self.mainSizer)

    #----------------------------------------------------------------------
    def buildLayout(self, text):
        """"""
        lblSize = (60,-1)
        lbl = wx.StaticText(self.panel, label=text, size=lblSize)
        txt = wx.TextCtrl(self.panel)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(lbl, 0, wx.ALL|wx.ALIGN_LEFT, 5)
        sizer.Add(txt, 0, wx.ALL, 5)
        self.mainSizer.Add(sizer)

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

rawDescription: wxPython GUI BoxSizers

description: WxPython GUI BoxSizers


code: df.C.values - np.vstack(df.C.values)

rawDescription: Creating matrix from dataframe

description: Creating matrix from dataframe


code:
for plotname, ((x, y, marker), kwargs) in plots.items():
    plt.plot(y, x, marker, label=plotname, **kwargs)

rawDescription: Exchange the x axis for the y axis in python


rawDescription: Python: dumping dictionaries to columns of a csv file in a table-like format


code:
import pygame
from pygame.locals import *

def display(str):
    text = font.render(str, True, (255, 255, 255), (159, 182, 205))
    textRect = text.get_rect()
    textRect.centerx = screen.get_rect().centerx
    textRect.centery = screen.get_rect().centery

    screen.blit(text, textRect)
    pygame.display.update()

pygame.init()
screen = pygame.display.set_mode( (640,480) )
pygame.display.set_caption('Python numbers')
screen.fill((159, 182, 205))

font = pygame.font.Font(None, 17)

num = 0
done = False
while not done:
    display( str(num) )
    num += 1

    pygame.event.pump()
    keys = pygame.key.get_pressed()
    if keys[K_ESCAPE]:
        done = True

rawDescription: Python nonblocking console input

description: Python nonblocking console input


rawDescription: Passing a Variable from Python script to tcl shell


code:
def make_great(l):
    l[:] = ['The great ' + magician for magician in l]

rawDescription: Modifying a list in python by passing it to a function


code: ord(X)

rawDescription: What's the meaning of \'$char in bash?

description: What's the meaning of \'$char in bash


rawDescription: How can I find the credit card balance regarding my code?

description: Find the credit card balance regarding my code


rawDescription: Python: how to convert utf-8 code string back to string?


code:
fp = open(filename, "rb")
data = fp.read()
fp.close()

fp = open(jpegfilename, "wb")
fp.write(data[6:-1])
fp.close()

rawDescription: Best way to remove first 6 bytes, and very last byte. Python

description: Remove first 6 bytes, and very last byte. Python


code:
def percentage(t):
    return between(1,3)(subf.ix[(t-60 < subf['Time']) & (subf['Time'] <= t), 'Value'])

rawDescription: Customizing rolling_apply function in Python pandas


code: positions = zip(*np.where(test2D > 5000.))

rawDescription: Getting positions of specific values of 2d array


code:
import mechanize

br = mechanize.Browser()
url = 'http://www.canadapost.ca/cpotools/apps/track/personal/findByTrackNumber'
response = br.open(url)
br.select_form('tapByTrackSearch:trackSearch')
br.form['tapByTrackSearch:trackSearch:trackNumbers'] = 'LM920347139CN'
response = br.submit()
html = response.read()

rawDescription: about redirect in python crawling and extracting data from a webpage

description: About redirect in python crawling and extracting data from a webpage


code:
import re
key_pat = re.compile(r"^(\D+)(\d+)$")
def key(item):
    m = key_pat.match(item)
    return m.group(1), int(m.group(2))

rawDescription: python sort strings with digits at the end

description: Python sort strings with digits at the end


code:
# Don't use this unless somelist contains unhashable items
import collections
somelist = list('ABRACADABRA')
seen = []
dups = collections.defaultdict(list)
for i, item in enumerate(somelist):
    for j, orig in enumerate(seen):
        if item == orig:
            dups[j].append(i)
            break
    else:
        seen.append(item)
print([(seen[key], val) for key, val in dups.iteritems()])

rawDescription: Find index of item with duplicates

description: Find index of item with duplicates


rawDescription: Change the value of a list's element

description: Change the value of a list's element


code:
my_list = [2,9,10,15,21,30,33,45]
filter(lambda x: x % 3 == 0, my_list)
list(filter(lambda x: x % 3 == 0, my_list))

rawDescription: Lambda Within Filter Function?

description: Lambda Within Filter Function


rawDescription: Reading and running a mathematical expression in Python


code:
np.random.seed(1234)
arr = np.random.randn(100).reshape(100,1)
df = pd.DataFrame(arr, columns=['prob'])
pd.cut(df.prob, 5).value_counts()

rawDescription: sorting the quintile output from qcut in pandas python

description: Sorting the quintile output from qcut in pandas python


rawDescription: How to automatically get port no. of a hardware in python serial communcation?

description: Automatically get port no. of a hardware in python serial communcation


code:
nonechar = 'N'
spacechar = '_'

solution = [[6], [0, 7], [None, 3, None, 8], [2, 5, None, 9], [1, None, 4, None, None, None], [None, None, None, 4],[None, 3]]

for i in range(1, len(solution)):
    for j in range(len(solution[i-1])):
        if (solution[i-1][j] == None):
            solution[i].insert(2*j, None)
            solution[i].insert(2*j+1, None)
N = len(solution[-1]) * 2 - 1
offset = (N - 1) / 2
spacing = 0
for i in range(len(solution)):
    line = spacechar * int(offset)
    for j in range(len(solution[i])):
        if (solution[i][j] == None):
            line += nonechar
        else:
            line += str(solution[i][j])
        if (j != len(solution[i]) - 1):
            line += spacechar * int(spacing)
    line += spacechar * int(offset)
    print(line)
    spacing = offset
    offset = (offset - 1) / 2

rawDescription: Print a Pretty Tree

description: Print a Pretty Tree


code:
from celery import current_task

def send_email(fun):

    @wraps(fun)
    def outer(*args, **kwargs):
        print('decorated and task is: %r' % (current_task, ))
        return fun(*args, **kwargs)

@task
@send_email
def any_function():
    print('inside the function')

rawDescription: Decorator after @task decorator in celery


code:
def main(args):
    ...

main(sys.argv)

rawDescription: Use *args without putting the arguments into a tuple?


code:
def func(matchobj):
    return 'aaa_' if matchobj.group(0) == 'sss_' else 'bbb_'

def dic_gen(exc):
    param_errors = {re.sub(r'(sss_)|(ttt_)', func, err.name):
                       err.address for err in exc.errors}
    param_errors["status"] = "ERROR"
    return param_errors

rawDescription: replace string if regex matched and replace with something else it matches some other regex

description: Replace string if regex matched and replace with something else it matches some other regex


code:
import datetime
import time
from datetime import datetime as dt

rawDescription: Why am I getting TypeError: 'module' object is not callable in python?


code: self.Bind(wx.EVT_MOVE, self.OnMove)

rawDescription: wxPython, Triggering an Event While Dragging

description: WxPython, Triggering an Event While Dragging


code:
from collections import defaultdict

class _defaultdict(defaultdict):
    def __add__(self, other):
        return other

def CountTree():
    return _defaultdict(CountTree)

rawDescription: More Pythonic way of counting things in a heavily nested defaultdict


code: o.b.text = 'newtext'

rawDescription: replacing node text using lxml.objectify while preserving attributes

description: Replacing node text using lxml.objectify while preserving attributes


code:
from operator import itemgetter

with open("scores.txt") as f:
    lst = [i.rstrip("\n")[1:-1].split(", ") for i in f.readlines()]

for i in lst:
    i[1] = float(i[1])
    i[0] = i[0][2:-1]

lst.sort(key=itemgetter(1), reverse=True)

rawDescription: Reading a file to a dictionary and trying to rank


code:
{'image-XXX.png': ['image-000001.png', 'image-000002.png'],
 'XXX_sequence.png': ['001_sequence.png', '002_sequence.png']}

rawDescription: How to identify files that have increasing numbers and a similar form of filename?

description: Identify files that have increasing numbers and a similar form of filename


code:
[
 0,     # x is 0, x%4 is 0, so g(x) becomes (lambda x:x*1)(0) or 0*1
 1,     # x is 1, x%4 is 1, so g(x) becomes (lambda x:x*x)(1) or 1*1
 8,     # x is 2, x%4 is 2, so g(x) becomes (lambda x:x*x*x)(2) or 2*2*2
 42,    # x is 3, x%4 is 3, so g(x) becomes (lambda x:42)(3) or 42
 4,     # x is 4, x%4 is 0, so g(x) becomes (lambda x:x*1)(4) or 4*1
 25,    # x is 5, x%4 is 1, so g(x) becomes (lambda x:x*x)(5) or 5*5
 216,   # x is 6, x%4 is 2, so g(x) becomes (lambda x:x*x*x)(6) or 6*6*6
 42,    # x is 7, x%4 is 3, so g(x) becomes (lambda x:42)(7) or 42
 8,     # x is 8, x%4 is 0, so g(x) becomes (lambda x:x*1)(8) or 8*1
 81,    # x is 9, x%4 is 1, so g(x) becomes (lambda x:x*x)(9) or 9*9
 1000,  # x is 10, x%4 is 2, so g(x) becomes (lambda x:x*x*x)(10) or 10*10*10
 42     # x is 11, x%4 is 3, so g(x) becomes (lambda x:42)(11) or 42
]

rawDescription: Python lambda in lambda

description: Python lambda in lambda


code:
def moddiv(a, b, n):
    binv = modinv(b, n)
    if not binv:
        return None
    return a * binv % n

rawDescription: Modular inverse calculation stuck

description: Modular inverse calculation stuck


code: row_width = (width + 7) // 8

rawDescription: Calculating pixel in array

description: Calculating pixel in array


code:
@contextlib.contextmanager
def freeing(value):
    try:
        yield value
    finally:
        libc.free(value)

rawDescription: Memory leaks in Python when using an external C DLL


code: newdf['new_col'] = newdf.reset_index().groupby('id').date.transform( lambda ii: ii == ii.max())

rawDescription: Generating new time series index from existing data set in Pandas


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

# imaginary csv file. pretend that we do not know the column order.
Header = [u'col1', u'col2']
Line1 = [u'A',u'X']
Line2 = [u'B',u'Y']
fileLines = [Line1,Line2]

# dicts to translate lines
D1a = {u'A':u'a'}
D1b = {u'B':u'b'}
D2 = {u'X':u'x',u'Y':u'y'}

# dict to correspond header names with the correct dictionary
refD = {u'col1':[D1a,D1b],u'col2':[D2]}

# now let's have some fun...

for line in fileLines:
    for i, (param, word) in enumerate(zip(Header, line)):
        for minitranslator in refD[param]:
            if word in minitranslator:
                line[i] = minitranslator[word]

rawDescription: Find and replace in CSV files with Python


code:
class MyWindowClass(QMainWindow):
    def __init__(self):
        ...
        self.ui = Ui_LEDController()
        self.ui.setupUi(self)

rawDescription: Overriding QMainWindow methods in PyQt from QtCreator


code:
new_dict = {}
for key, value in dict2.items():
    if key not in dict1:
        new_dict[key] = value

rawDescription: python3 + Set function: how to get key and values from dictionary performing set operation

description: Python3 + Set function: how to get key and values from dictionary performing set operation


code:
{12: {'charcount': 25, 'longword': 1},
 13: {'charcount': 38, 'longword': 1}}

rawDescription: Multi dictionaries - For all identical keys, do some aggregation


code:
import numpy as np
import pandas as pd

df = sqlContext.createDataFrame(pd.DataFrame({
    "x1": np.random.random(1000),
    "x2": np.random.choice(3, 1000),
    "x4": np.random.choice(5, 1000)
}))

rawDescription: How can I declare a Column as a categorical feature in a DataFrame for use in ml

description: Declare a Column as a categorical feature in a DataFrame for use in ml


code:
import json

class Script(object):
    def __init__(self, name, version, dependency_list):
        self.name = name
        self.version = version
        self.dependency_list = self.parse_dependencies(dependency_list)

    def parse_dependencies(self, dep_list):
        """
        Take our dependency list and turn it into a list of Dependency objects.
        """
        dependency_list = []
        for i in xrange(0, len(dep_list), 2):
            d = Dependency(dep_list[i], dep_list[i+1])
            dependency_list.append(d)
        return dependency_list

    def output_to_json(self):
        """
        Output our self to a dict that can be used in a json.dumps()
        """
        context = {
            'name': self.name,
            'version': self.version,
            'dependencies': [c.output_to_json() for c in self.dependency_list]
        }
        return context

class Dependency(object):
    def __init__(self, name, version):
        self.name = name
        self.version = version

    def output_to_json(self):
        context = {
            'name': self.name,
            'version': self.version
        }
        return context

def make_classes_from_list(list_of_scripts):
    """
    Take your list of numbers and turn it into a list of Script
    and Dependency objects.
    """
    output = []
    for i in xrange(0, len(list_of_scripts), 3):
        s = Script(list_of_scripts[i], list_of_scripts[i+1], list_of_scripts[i+2])
        output.append(s)
    return output

listOfScripts = [20, 3, [39, 2, 30, 4], 21, 4, [65, 9, 12, 5]]
list_of_script_objects = make_classes_from_list(listOfScripts)

print(json.dumps([x.output_to_json() for x in list_of_script_objects]))

rawDescription: Python objects in list as JSON

description: Python objects in list as JSON


code:
class Player(object):
    def __init__(self, name, score):
        self.name = name
        self.score = score
    def __repr__(self):
       return "<Player('%s','%s')>" % (self.name, self.score)

rawDescription: Dynamic Table Creation and ORM mapping in SqlAlchemy


code:
import urlparse
s = 'access_token=159565124071460|2.D98PLonBwOyYWlLMhMyNqA__.3600.1286373600-517705339|bFRH8d2SAeV-PpPUhbRkahcERfw&expires=4375'
urlparse.parse_qs(s)

rawDescription: Parsing facebook oauth access_token string


code:
import cgi

text = results[i]["Teaser"] # the text that you want to put into textarea
html_safe_text = cgi.escape(text) # < > & -> < > &
textarea_html = u"<textarea>{}</textarea>".format(html_safe_text)

rawDescription: How to store multiline text in html textarea from python?

description: Store multiline text in html textarea from python


code: myjsonstring = json.dumps(data)

rawDescription: Manipulating JSON data, when keys may be missing, in Python


code:
from kivy.lang import Builder
from kivy.base import runTouchApp
from kivy.uix.boxlayout import BoxLayout
Builder.load_string('''
<Test>:
    TabbedPanelHeader
        color: (0,0,1,1)
        text:'blaaaaaaa'
        background_color: (0, 0, 1, 1)
        background_normal: ''
''')
class Test(BoxLayout):pass
runTouchApp(Test())

rawDescription: Changing color TabbedPannelHeader in Kivy


rawDescription: How to convert tree-form tuples to matrix-form tuples?

description: Convert tree-form tuples to matrix-form tuples


code:
from scipy.weave import inline, converters

_code = open("outline.c", "r").read()

def outline(data, every):
    width, height = data.shape
    return inline(_code, ['data', 'width', 'height', 'every'], type_converters=converters.blitz)

rawDescription: numpy binary raster image to polygon transformation

description: Numpy binary raster image to polygon transformation


code: soup.select("span > a.link_to_img")

rawDescription: Python BeautifulSoupe4: How to get link from anchor tag without duplicate


code:
from pyspark.sql.window import Window
from pyspark.sql.functions import col, row_number

w = Window.partitionBy("person").orderBy(col("year").desc())
df.withColumn("ranking", row_number().over(w))

rawDescription: Data shuffle for Hive and Spark window function


code:
d = {}
for k1,k2,v in List:
     d[(k1,k2)] = v

rawDescription: Python create nested dictionary from list with nested tuples


code:
maxlog=int(np.ceil( np.log10(vmax) ))
minlog=int(np.ceil( np.log10(-vmin) ))

rawDescription: Equidistant ticks on colorbar using SymLogNorm in matplotlib


code:
class Foo(models.Model):
    col1 = models.TextField(primary_key=True)

    class Meta:
        db_table = 'user1.table1'

rawDescription: Can we query multiple tables across multiple oracle users and tabularize the rows in Django's Admin UI


code:
from itertools import groupby

# this just sets up some byte strings to use, Python 2.x version is below
# instead of this you would use f1 = open('some_file', 'rb').read()
f1 = bytes(int(b, 16) for b in 'FF FF FF FF 00 00 00 00 FF FF 44 43 42 41 FF FF'.split())
f2 = bytes(int(b, 16) for b in '41 42 43 44 00 00 00 00 44 43 42 41 40 39 38 37'.split())

matches = []
for k, g in groupby(range(min(len(f1), len(f2))), key=lambda i: f1[i] == f2[i]):
    if k:
        pos = next(g)
        length = len(list(g)) + 1
        matches.append((pos, length))

rawDescription: Diffing Binary Files In Python

description: Diffing Binary Files In Python


code: hell.brick_list = [Brick(start_pos=pos) for pos in lister]

rawDescription: Accessing attributes of a list of objects in python


rawDescription: Convert decimal int to little endian string ('\x##\x##...')


code:
def handle_operation(operation, some_param):
    klass = operation.klass
    dictionary = klass()
    fn = getattr(dictionary, operation.value)
    fn(some_param)

rawDescription: Refactoring if statements in python

description: Refactoring if statements in python


code:
for i, (key, value) in enumerate(d.items()):
    print(i, key, value)

rawDescription: What is the most pythonic way to iterate over OrderedDict


code:
df = pd.DataFrame({"A": np.random.random(1000), "B": np.arange(1000) % 4})
some_float = 0.6
abs_tol = 0.001
df[(df.A - some_float).abs() < abs_tol]

rawDescription: Using python/pandas to search dataframe rows containing both a user-specified integer and approximated float value


code:
import numpy as np
import matplotlib.image as mpimg
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

img = mpimg.imread('Paw03.png')
pixels = img.shape[0]*img.shape[1]
channels = 3
data = np.reshape(img[:, :, :channels], (pixels, channels))

histo_rgb, _ = np.histogramdd(data, bins=256)
r, g, b = np.nonzero(histo_rgb)

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter3D(r, g, b)
ax.set_xlabel('Red')
ax.set_ylabel('Green')
ax.set_zlabel('Blue')
plt.title('RGB colors')
plt.show()

rawDescription: How to extract RGB from a image and plot only RG as a graph? R for X and G for Y

description: Extract RGB from a image and plot only RG as a graph? R for X and G for Y


code:
def reverse(word):
    word_list = []
    for i in range(len(word)-1, -1, -1):
        word_list.append(word[i])
    return "".join(word_list)

def reverse(word):
    return "".join(word[i] for i in range(len(word)-1, -1, -1))

rawDescription: Reverse String Function in Python (Primitive Steps)


rawDescription: Does python have any direct appoach to compare two .txt files?


code:
from numpy import zeros, newaxis
a = zeros((6, 8))
a.shape
b = a[:, :, newaxis]
b.shape

rawDescription: How to make a 2d numpy array a 3d array?

description: Make a 2d numpy array a 3d array


code:
emoticons = {}
for line in open('data/emoticons.txt').xreadlines():
        symbol, value = line.split('\t')
        emoticons[str(symbol)] = int(value)

rawDescription: translate by replacing words inside existing text

description: Translate by replacing words inside existing text


code:
alist = [(0.7897897,'this is a foo bar sentence'),
(0.653234, 'this is a foo bar sentence'),
(0.353234, 'this is a foo bar sentence'),
(0.325345, 'this is not really a foo bar'),
(0.323234, 'this is a foo bar sentence'),]

blist = [(0.64637,'this is a foo bar sentence'),
(0.534234, 'i am going to foo bar this sentence'),
(0.453234, 'this is a foo bar sentence'),
(0.323445, 'this is not really a foo bar')]

bdict = {k:v for v,k in reversed(blist)}
clist = []
cset = set()
for v,k in alist:
   if k not in cset:
      b = bdict.get(k, None)
      if b is not None:
        clist.append((v * b, k))
        cset.add(k)
print(clist)

rawDescription: How to optimize the combination of 2 lists of tuples and remove their duplicates?

description: Optimize the combination of 2 lists of tuples and remove their duplicates


code:
#! /usr/bin/env python3
import socket, select

def main():
    a = [socket.socket(socket.AF_INET, socket.SOCK_STREAM)]     # socket array
    a[0].bind(('', 8989))
    a[0].listen(5)
    while True:
        for b in select.select(a, [], [])[0]:                   # ready socket
            if b is a[0]:
                a.append(b.accept()[0])
            else:
                try:
                    c = b.recv(1 << 12)                         # sent message
                except socket.error:
                    b.shutdown(socket.SHUT_RDWR)
                    b.close()
                    a.remove(b)
                else:
                    for d in (d for d in a[1:] if d is not b):  # message sink
                        d.sendall(c)

if __name__ == '__main__':
    main()

rawDescription: Send/sync variable/text over LAN in Python 3


rawDescription: Flask and jinja2 include tag

description: Flask and jinja2 include tag


code: s.translate(None, r"()\"'")

rawDescription: Strip Specific Punctuation in Python 2.x


code: hourly_readings[hour] = tuple(map(sum, zip(hourly_readings[hour], reading)))

rawDescription: How do I easily manipulate a timestamp key in a Python dictionary?

description: Easily manipulate a timestamp key in a Python dictionary


code:
# TESTED

# Compile this only once to save time
pat = re.compile(r'''
    (?mx)                                  # multi-line, verbose
    (?:Matches:\s*\d+\s*\(([\d\.]+)\s*%\)) # "Matches: 300 (43.2%)"
    |
    (?:Score:\s*(\d+))                     # "Score: 4000"
''')
def get_values_from_file(filename):
    with open(filename) as f:
        values, scores = zip(*pat.findall(f.read()))
    values = [float(value) for value in values if value]
    scores = [float(score) for score in scores if score]
    return scores, values

rawDescription: Comparing multiple file items using re

description: Comparing multiple file items using re


code:
id(x)
id(y)
x is y

rawDescription: Equal strings auto updating (List object reference)


code:
def get_value(mapping, keys):
    return reduce(dict.get, keys, mapping)

rawDescription: Get a value from multidimensional, with variable number of dimensions, dictionary in python


code:
import csv
import io

s = u'''text,text,text,11/03/12,text,text,text,UniqueNameClass1,text,text
text,text,text,11/03/12,text,text,text,UniqueNameClass2,text,text
text,text,text,10/03/12,text,text,text,UniqueNameClass3,text,text
text,text,text,12/03/12,text,text,text,UniqueNameClass1,text,text
text,text,text,10/03/12,text,text,text,UniqueNameClass2,text,text
text,text,text,10/03/12,text,text,text,UniqueNameClass5,text,text'''

data = list(csv.reader(io.StringIO(s)))
data.sort(key=lambda row: (row[3], row[7]))
print(u'\n'.join(u','.join(row) for row in data))

rawDescription: Sorting data by class for each date

description: Sorting data by class for each date


code: Y, X = np.ogrid[0:angle.shape[0], 0:angle.shape[1]]

rawDescription: numpy 2d array (coordinates) need to assign into 3D array, to some particular bin

description: Numpy 2d array (coordinates) need to assign into 3D array, to some particular bin


rawDescription: Nested list comprehension in Python

description: Nested list comprehension in Python


rawDescription: Scrape information from challenging website with no guiding HTML structure


code:
for idx, a, b, c in izip(count(), A, B, C):
  ...

rawDescription: Is there a way to have parallel for-each loops?


code: pip2 --version

rawDescription: how to run pip for python 3 and python 2

description: Run pip for python 3 and python 2


code:
import urllib2
from bs4 import BeautifulSoup

url = "http://www.presidency.ucsb.edu/ws/index.php?pid=99556"

data = BeautifulSoup(urllib2.urlopen(url), 'html.parser')
data.find("span", class_="displaytext").text

rawDescription: BeautifulSoup Cannot Find Tag

description: BeautifulSoup Cannot Find Tag


code:
import Tkinter
from Tkinter import Tk, Frame, Menu
from Tkinter import IntVar, BOTH
class App(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Test")
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        menubar.add_cascade(label="Discrepancy", menu=fileMenu)
        fileMenu.add_command(label="View current case", command=self.view)
        fileMenu.add_command(label="OK Process", command=self.OK)

        self.var = IntVar()

        self.view_label1 = Tkinter.Label(self, text="RMA", relief=Tkinter.RIDGE)
        self.view_label2 = Tkinter.Label(self, text="SN", relief=Tkinter.RIDGE)

        self.ok_label1 = Tkinter.Label(self,text="RMA")
        self.ok_label2 = Tkinter.Label(self, text="SN")

        self.ok_entry1 = Tkinter.Entry(self, width=50)
        self.ok_entry2 = Tkinter.Entry(self, width=50)

        self.pack(fill=BOTH, expand=1)

    def view(self):
        self.ok_label1.grid_forget()
        self.ok_label2.grid_forget()
        self.ok_entry1.grid_forget()
        self.ok_entry2.grid_forget()

        self.view_label1.grid(row=0, column=0, sticky=Tkinter.W)
        self.view_label2.grid(row=0, column=1, sticky=Tkinter.W)

    def OK(self):
        self.view_label1.grid_forget()
        self.view_label2.grid_forget()

        self.ok_label1.grid(row=0)
        self.ok_label2.grid(row=1)
        self.ok_entry1.grid(row=0, column=1, pady=4)
        self.ok_entry2.grid(row=1, column=1, pady=4)

def main():

    root = Tk()
    root.geometry("1280x720")
    app = App(root)
    root.mainloop()

if __name__ == '__main__':
    main()

rawDescription: Avoid screen overlap in Tkinter

description: Avoid screen overlap in Tkinter


rawDescription: Python regex split but put end part of regex match back into string?


code:
import pandas as pd
import string
import numpy as np
np.random.seed(1234)
pd.set_option('max_rows',10)

rawDescription: pandas and category replacement

description: Pandas and category replacement


code:
def sine(freq):
    phase = 0.0
    while True:
        yield math.sin(phase)
        phase += samplerate/freq

rawDescription: Efficiency of python generators

description: Efficiency of python generators


rawDescription: Using Cython To Link Python To A Shared Library


code:
User_id = []
User_email = []

rawDescription: double assign in python results in identical lists even when different operation is done. Why?

description: Double assign in python results in identical lists even when different operation is done. Why


rawDescription: Replacing string elements of a pandas DataFrame with integers


code: b = eval('a.'+element[3])

rawDescription: is there a way to avoid eval() to accomplish dynamic dispatch of a function specified in a list in python

description: Is there a way to avoid eval() to accomplish dynamic dispatch of a function specified in a list in python


rawDescription: Which regex is more efficient?

description: Which regex is more efficient


code: json.dumps(locals(), default=repr)

rawDescription: How to dump all the variables in a file?

description: Dump all the variables in a file


code:
import time

start_time = time.time()
duration_s = sndfile.frames / sndfile.samplerate

while 1:
    elapsed_time = time.time() - start_time
    current_location = elapsed_time / float(duration_s)
    if current_location >= 1:
         break
    time.sleep(.01)

rawDescription: Python module for playing sound data with progress bar?


code:
class getAllTagsDetailSerializer(serializers.ModelSerializer):
    tagStores = serializers.Field(source='getAllStoreNames')

    class Meta:
        model = tags
        fields = ('tagStores')

rawDescription: backward many to many Django query

description: Backward many to many Django query


code: n = Neuron(apical_bifibrications="special value")

rawDescription: Class with too many parameters: better design strategy?


code: splitloc = [i for i, e in enumerate(signchange) if e != 0]

rawDescription: Python, split array by gradient of dataset


rawDescription: Equivalent of count list function in numpy array


code:
sentence = 'I am called bob. What is your name?'
punc = ('!', '"', '£', '$', '%', '^', '&', '*', '(', ')', '¬', '`', '{', '}', '~', '@', ':', '?', '>', '<', ',', '.', '/', ';', '#', ']', '[', '/', '*')

sentence = list(sentence)
Dictionary = {}

for i, p in enumerate(sentence): # enumerate() returns an iterable in (index, value) format
    if p in punc:
        if p in Dictionary:
            Dictionary[p].append(i)
        else:
            Dictionary[p] = [i]

print(Dictionary) # => {'?': [34], '.': [15]}

rawDescription: How to remove punctuation from a string and remember the position of it from the string

description: Remove punctuation from a string and remember the position of it from the string


rawDescription: compare paranthesis in python

description: Compare paranthesis in python


rawDescription: How can I select values along an axis of an nD array with an (n-1)D array of indices of that axis?

description: Select values along an axis of an nD array with an (n-1)D array of indices of that axis


code:
import multiprocessing as MP
from sys import exc_info
from time import clock

DEFAULT_TIMEOUT = 60

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

def timeout(limit=None):
    if limit is None:
        limit = DEFAULT_TIMEOUT
    if limit <= 0:
        raise ValueError()
    def wrapper(function):
        return _Timeout(function, limit)
    return wrapper

class TimeoutError(Exception): pass

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

def _target(queue, function, *args, **kwargs):
    try:
        queue.put((True, function(*args, **kwargs)))
    except:
        queue.put((False, exc_info()[1]))

class _Timeout:

    def __init__(self, function, limit):
        self.__limit = limit
        self.__function = function
        self.__timeout = clock()
        self.__process = MP.Process()
        self.__queue = MP.Queue()

    def __call__(self, *args, **kwargs):
        self.cancel()
        self.__queue = MP.Queue(1)
        args = (self.__queue, self.__function) + args
        self.__process = MP.Process(target=_target, args=args, kwargs=kwargs)
        self.__process.daemon = True
        self.__process.start()
        self.__timeout = self.__limit + clock()

    def cancel(self):
        if self.__process.is_alive():
            self.__process.terminate()

    @property
    def ready(self):
        if self.__queue.full():
            return True
        elif not self.__queue.empty():
            return True
        elif self.__timeout < clock():
            self.cancel()
        else:
            return False

    @property
    def value(self):
        if self.ready is True:
            flag, load = self.__queue.get()
            if flag:
                return load
            raise load
        raise TimeoutError()

    def __get_limit(self):
        return self.__limit

    def __set_limit(self, value):
        if value <= 0:
            raise ValueError()
        self.__limit = value

    limit = property(__get_limit, __set_limit)

rawDescription: Start python Process with output and timeout


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

x, y = np.mgrid[-100:100,-100:100]
x /= 10.
y /= 10.
r = np.sqrt(x*x+y*y)
z = 10*np.sin(r)/(r+0.01)
levels = [-4, -3, -2, -1, 1, 2, 3, 4]
plt.contourf(x, y, z, levels=levels, extend='both', cmap=cm.jet)
levels = [-1, 1]
plt.contourf(x, y, z, levels=levels, colors='w')
plt.savefig('contours.png')

rawDescription: Python matplotlib change color of specified value in contourf plot using colormap


rawDescription: how do I .decode('string-escape') in Python3?

description: .decode('string-escape') in Python3


code: [tuple(d.get(x,x) for x in li[0])]

rawDescription: Finding and Replacing all Values inside of entries within a List


code: img = client.images.get(IMAGE_ID)

rawDescription: Openstack python API: how to download image from glance using the python api


rawDescription: Google App Engine: Using cron to expire (or 'unpublish') entities


code:
import re

reg = re.compile(r'(?P<indent>\s*)("""|\'\'\'|blockquote:)(\((?P<type>\w*)\s*(["\'](?P<citation>.+?)["\'])?\s*(\((?P<format>\w+?)\))?(?P<other>.+?)?\))?')

s2 = '             """(book "Moby Dick" (MLA))'

m2 = reg.match(s2)
m2.groupdict()

s3 = '             """(book "Moby Dick")'
m3 = reg.match(s3)

m3.groupdict()

rawDescription: Different parts of regex matching same text depending on what comes afterwards


code:
b_to_a = np.argsort(a_to_b)
print(np.all(B[b_to_a] == A))
# True

rawDescription: Finding a set of indices that maps the rows of one NumPy ndarray to another


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

# Generate data:
N = 10
x = np.linspace(0, 1, N)
y = np.linspace(0, 1, N)
x, y = np.meshgrid(x, y)
colors = np.random.rand(N, N) # colors for each x,y

# Plot
circle_size = 200
cmap = matplotlib.cm.viridis # replace with your favourite colormap
fig, ax = plt.subplots(figsize=(4, 4))
s = ax.scatter(x, y, s=circle_size, c=colors, cmap=cmap)

# Prettify
ax.axis("tight")
fig.colorbar(s)

plt.show()

rawDescription: Dynamic marker colour in matplotlib

description: Dynamic marker colour in matplotlib


rawDescription: How to initialize NumPy array with different default value for each column?

description: Initialize NumPy array with different default value for each column


code:
from string import maketrans
trs = maketrans(''.join(old_chars), ''.join(new_chars))

rawDescription: Replacing multiple characters from an element in a list,


code:
def completedefault(self, *ignored):
        # Set the autocomplete preferences
        readline.set_completer_delims(' \t\n;')
        readline.parse_and_bind("tab: complete")
        readline.set_completer(complete)

rawDescription: Cmd module '~' completion

description: Cmd module '~' completion


code:
def BuildWalls(self):
    numWalls = 0
    directions = [ [GPacW.Left, GPacW.Right], [GPacW.Up, GPacW.Down] ]
    start = [ random.randint(0, self.Height), random.randint(0, self.Width) ]
    length = 0
    horizontalOrVertical = random.randint(0, 1)
    direction = random.randint(0, 1)
    d = directions[horizontalOrVertical][direction]
    intersected = False
    while (numWalls < self.Walls):
        while (start == [0, 0] or start == [self.Height, self.Width] or self.Intersects(start, d)):
            start = [ random.randint(0, self.Height), random.randint(0, self.Width) ]
        if (length == 0):
            horizontalOrVertical = not horizontalOrVertical
            direction = random.randint(0, 1)
            length = random.randint(3, min(self.Height, self.Width))
            d = directions[horizontalOrVertical][direction]
        if (self.WallSpaces[ start[0] ] & (1 << start[1] ) == 0):
            self.WallSpaces[ start[0] ] |= 1 << start[1]
            numWalls += 1
            length -= 1
        if (0 <= (start[0] + d[0]) <= self.Height and 0 <= (start[1] + d[1]) <= self.Width):
            start[0] += d[0]
            start[1] += d[1]
        else:
            start = [0,0]
        if (self.Intersects(start, d)):
            if (intersected):
                intersected = False
                start = [0,0]
                length = 0
            else:
                intersected = True
    return

rawDescription: Find enclosed spaces in array

description: Find enclosed spaces in array


code:
@admin.site.register(ModelOne, ModelTwo)
class AdminModel(admin.ModelAdmin):

    def get_actions(self, request):
        actions = super(AdminModel, self).get_actions(request)
        if not request.user.is_superuser:
            if 'delete_selected' in actions:
                del actions['delete_selected']
        else:
            self.actions.append(make_published)
            self.actions.append(make_unpublished)
        return actions

rawDescription: Django: Admin action choices

description: Django: Admin action choices


code:
Food
Person
Food
Vehicle
Food

rawDescription: Python - reading complex lines of text into dictionary


rawDescription: Making a grid with curses from a dictionary of flat tuples


code:
import numpy as np
arr=np.loadtxt('column.txt')
arr
arr.shape
arr=arr.reshape(6,1)
arr

rawDescription: Problems on how to transpose single column data in python


code:
results = [span.text for td in soup.find_all('td', {'class': 'section'}) for span in td.find_all('span')]
results

rawDescription: BeautifulSoup: Extracting Value from Children nodes


code:
with open('outfile.dat','w') as f:
   f.write(header)
   #If you used a frozenset in the first part, you might want to do something like:
   #for k in sorted(map(sorted,data.keys())):
   for k in sorted(data.keys()):
       col1,col2 = k
       col3_data,col4_data = data[k]
       col3_data = ','.join(col3_data) #join the list
       col3_data = set(int(x) for x in col3_data.split(',')) #make unique integers
       col3_str = ','.join(map(str,sorted(col3_data)))       #sort, convert to strings and join with ','
       col4_data = ','.join(col4_data)  #join the list
       col4_data = sorted(set(col4_data.split(',')))  #make unique and sort
       f.write('{0}\t{1}\t{2}\t{3}\n'.format(col1,col2,col3_str,','.join(col4_data)))

rawDescription: Based on the values in two columns merge values in other columns


code:
def calc_bytes_per_row(width, bytes_per_pixel):
    res = width * bytes_per_pixel
    if res % 4 != 0:
        res += 4 - res % 4
    return res

def calc_row_offsets(pixel_array_offset, bmp_width, bmp_height, x, y, row_width):
    if x + row_width > bmp_width:
        raise ValueError("This is only for calculating offsets within a row")

    bytes_per_row = calc_bytes_per_row(bmp_width, 3)
    whole_row_offset = pixel_array_offset + bytes_per_row * (bmp_height - y - 1)
    start_row_offset = whole_row_offset + x * 3
    end_row_offset = start_row_offset + row_width * 3
    return (start_row_offset, end_row_offset)

rawDescription: Load just part of an image in python

description: Load just part of an image in python


code:
def heirarchy(data, separator=","):
  for p, x in eachWithPrefix(x.split(separator) if separator else list(x) for x in data):
    s = separator.join(x)
    c = separator.join(x[:p])
    yield ' '*len(c) + s[len(c):]

rawDescription: How to group strings with similar beginnings in a sorted list?

description: Group strings with similar beginnings in a sorted list


code: templist_index = templist.index(name+"\n") # "foo" -> "foo\n"

rawDescription: Removing data from a list from a raw_input variable


code:
import pygtk
pygtk.require('2.0')
import gtk
import gobject
import time

class ProgressBar(object):
    def __init__(self):
        self.val = 0
        self.scale = gtk.HScale()
        self.scale.set_range(0, 100)
        self.scale.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.scale.set_value(self.val)
        gobject.timeout_add(100, self.timeout)
    def timeout(self):
        self.val += 1
        # time.sleep(1)
        self.scale.set_value(self.val)
        return True

def demo_timeout_add():
    # http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp
    # http://stackoverflow.com/a/497313/190597
    win = gtk.Window()
    win.set_default_size(300, 50)
    win.connect("destroy", gtk.main_quit)
    bar = ProgressBar()
    win.add(bar.scale)
    win.show_all()
    gtk.main()

demo_timeout_add()

rawDescription: How to display continuous data in a py-gtk window?

description: Display continuous data in a py-gtk window


rawDescription: Django - Settings and Accessing Session Variables in Different Generic Views


code:
cutoff = 100
mat1 = original_matrix[:cutoff]
mat2 = original_matrix[cutoff:]

rawDescription: Sparse matrix manipulation

description: Sparse matrix manipulation


code: list3 = [sum(i) for i in zip(list1, list2)]

rawDescription: Python: joining 2 lists of the same size


code:
@tracelog(logger)
def somefunc():
    print('running somefunc')

rawDescription: Python : Automatic debug logs when control goes inside/outside function


code:
from collections import defaultdict
d = defaultdict(dict)
for k, v in mydictionary.items():
    for ik, iv in v.items():
            d[ik][k] = iv

rawDescription: What is an efficient way to exchange the order of keys in nested dictionaries in Python?


code:
class ListSlice(ROListSlice):

    def __setitem__(self, i, v):
        self.alist[self.adj(i)] = v

    def __delitem__(self, i, v):
        del self.alist[self.adj(i)]
        self.alen -= 1

    def insert(self, i, v):
        self.alist.insert(self.adj(i), v)
        self.alen += 1

rawDescription: Can I create a "view" on a Python list?

description: Create a "view" on a Python list


code: df1, df2 = df1.align(df2)

rawDescription: Match rows and columns of two DataFrames


code: df.loc[:, df.columns - ['col_n']]

rawDescription: pandas get all columms without one

description: Pandas get all columms without one


code:
for sublist in wordlist:
    if word == sublist[0]:  # compare directly with the relevant part of the sublist
        sublist[2] += 1
        break  # we only will match at most once, so break after finding one
else:    # this clause is run if no break was hit
    wordlist.append([word, linenum, 1])

rawDescription: Use 'in' in an array of arrays

description: Use 'in' in an array of arrays


code:
def f(x, y):
    retval1 = x + y
    retval2 = x * y
    return retval1, retval2

rawDescription: how to return multiple values from a function and use that in somewhere else in python programme

description: Return multiple values from a function and use that in somewhere else in python programme


code:
a=raw_input()
type(a)

rawDescription: Alarm will not be triggered in Python 2.7 program


rawDescription: Python - group by multiple columns

description: Python - group by multiple columns


code:
def swept_range(start, stop, step=1, sweep=1):
    return [i for i in range(start, stop) if not 0 < i % sweep < step]

rawDescription: Python: Create a range of ordered numbers skipping the inverse of every Nth through Nth+D number


rawDescription: Generic way to get primary key from declaratively defined instance in SQLAlchemy


code:
m = imaplib.IMAP4_SSL("imap.gmail.com")
m.login(user, pwd)

rawDescription: Extract information from Gmail with Python


code:
from pylab import cross,dot,inv

def rot(U,V):
    W=cross(U,V)
    A=np.array([U,W,cross(U,W)]).T
    B=np.array([V,W,cross(V,W)]).T
    return dot(B,inv(A))

rawDescription: Create a rotation matrix from 2 normals

description: Create a rotation matrix from 2 normals


code:
while i > 0:
    print("do something")
    n = n >> 1 # shift right, divide by 2

rawDescription: Python: How to create a C type for loop for a geometrical progression?


code:
from itertools import groupby

def f(lst):
    if_empty = ('ignored_key', ())
    k, v = next(groupby(lst), if_empty)
    return sum(1 for _ in v)

f(x1)
f(x2)
f(x3)
f([])

rawDescription: Finding the amount of equal elements in the beginning of a list


code: total = abs(x[movie]-y[movie])

rawDescription: Manhattan Distance Recommending system Python


code: df[df.C > df.H.shift(2)]

rawDescription: Filter numpy array by comparing elements to elements in prior row without looping


code: print("The value of {} is {}".format("foo", 5))

rawDescription: Please provide an example of the .format() function where the index field is left blank


code:
memberdef_list = [elem for elem in from_cache(classname, 'memberdefs')
                  if elem.argsstring != '[]' and
                     'std::string' in null2string(elem.vartype)]

rawDescription: Pythonic Style for Multiline List Comprehension


code: return [q.get() for _ in xrange(len(job_list))]

rawDescription: Thread/Queue hanging issue

description: Thread/Queue hanging issue


code:
class DeviceSerializer(serializers.ModelSerializer):
    ...
    logs_url = serializers.CharField(source='get_logs_url', read_only=True)

rawDescription: Django rest frameworok

description: Django rest frameworok


code:
def __getattr__(self, attr):
    try:
        return getattr(self.backend, attr)
    except:
        raise AttributeError('No attribute named ' + attr)

rawDescription: Pythonic Way to set Multiple Properties Based on another class


code: [x.myvar1 for x in myarray2]

rawDescription: Handling attributes of a class within a numpy array


rawDescription: pandas change a specific column value of duplicate rows

description: Pandas change a specific column value of duplicate rows


code: zip('george', 'cat')

rawDescription: enumerate is iterating of letters of strings in a list instead of elements

description: Enumerate is iterating of letters of strings in a list instead of elements


rawDescription: Numpy dot in a for loop

description: Numpy dot in a for loop


code:
import os, re
mylist = ["A01B02_0123_A333.01234321.ari", "A01B02_0123_A333.01234322.ari", "A01B02_0123_A333.01234323.ari", "A01B02_0123_A333.01234324.ari", "A01B02_0123_A333.01234325.ari", "A01B02_0123_A333.01234326.ari", "A01B02_0123_A333.01234327.ari", "A01B02_0123_A333.01234328.ari", "A01B02_0123_A333.01234329.ari", "A01B02_0123_A333.01234330.ari", "A01B02_0123_A333.01234331.ari", "A02B03_0123_A444.0052.ari", "bus_v01.1001.tif", "bus_v01.1002.tif", "bus_v01.1003.tif", "bus_v02.1001.tif", "bus_v02.1002.tif", "bus_v02.1003.tif", "elementA_1001.jpg", "elementA_1002.jpg", "elementA_1003.jpg", "elementB_1001.jpg", "elementB_1002.jpg", "elementB_1003.jpg"]

def digitgroups(files):
    padding_expr = re.compile("\d+")
    lastfile = ""
    sequence_index = 0

    for f in files:
        if f.endswith((".dpx", ".ari", ".jpg", ".tif")):
            match = re.findall(padding_expr, f)[::-1]
            lastmatch = re.findall(padding_expr, lastfile)[::-1]

            if len(match) == len(lastmatch) and f is not lastfile:
                for i in range (0, len(match)):
                    digit_difference = int(lastmatch[i])-int(match[i])
                    if not digit_difference == 0:
                        if digit_difference == -1 or digit_difference == 1 and os.path.splitext(f)[-1] is os.path.splitext(l)[-1]:
                            print(f, "a is part of sequence {0}".format(sequence_index))
                        elif digit_difference < -1 or digit_difference > 1:
                            sequence_index += 1

                        break
            else:
                print(f, "a is part of sequence {0}".format(sequence_index))
            lastfile = f

digitgroups(mylist)

rawDescription: python image sequence loop issue

description: Python image sequence loop issue


code:
codebook = np.load('codebook.npy') # Template vectors for each paw
average_paw = np.load('average_paw.npy')
basis_stds = np.load('basis_stds.npy') # Needed to "whiten" the dataset...
basis_vecs = np.load('basis_vecs.npy')
paw_code = {0:'LF', 1:'RH', 2:'RF', 3:'LH'}
def classify(paw):
    paw = paw.flatten()
    paw -= average_paw
    scores = paw.dot(basis_vecs) / basis_stds
    diff = codebook - scores
    diff *= diff
    diff = np.sqrt(diff.sum(axis=1))
    return paw_code[diff.argmin()]

rawDescription: How to sort my paws?

description: Sort my paws


code:
pictures = ['abc.jpg', 'abc.gif', 'abc.png', 'cde.jpg']
[pic for pic in pictures if pic.endswith('jpg')]

rawDescription: Python - FOR loop to remove list items by file extension


code: wood = itertools.count().next()

rawDescription: How to make an action happen every minute in Python

description: Make an action happen every minute in Python


code:
class IntMathMixin:
    def __add__(self, other):
        return type(self)(int(self).__add__(int(other)))
    # ... analog for the others

rawDescription: subclassing int to attain a Hex representation

description: Subclassing int to attain a Hex representation


code:
prices
prices.asof(amounts.index)
prices.asof(amounts.index) * amounts

rawDescription: What representation should I use in Pandas for data valid throughout an interval?


code:
import main.readyScripts
import dev.inProgress

rawDescription: Relative import from current file

description: Relative import from current file


code:
import pygame
import math
import random
from collections import namedtuple
from itertools import cycle

def magnitude(v):
    return math.sqrt(sum(v[i]*v[i] for i in range(len(v))))

def add(u, v):
    return [(a+b) for (a, b) in zip(u, v)]

def sub(u, v):
    return [(a-b) for (a, b) in zip(u, v)]

def dot(u, v):
    return sum((a*b) for a, b in zip(u, v))

def normalize(v):
    vmag = magnitude(v)
    return [ v[i]/vmag  for i in range(len(v)) ]

def length(v):
  return math.sqrt(dot(v, v))

def angle(v1, v2):
  return math.acos(dot(v1, v2) / (length(v1) * length(v2)))

class Cell(object):

    id = 0

    def __init__(self, pos, color, speed, size, controller):
        self.x, self.y = pos
        self.speed = speed
        self.color = color
        self.size = size
        self.target_vector = [0, 0]
        self.controller = controller
        Cell.id += 1
        self.id = Cell.id

    @property
    def pos(self):
        return self.x, self.y

    @property
    def int_pos(self):
        return [int(v) for v in self.pos]

    @property
    def int_size(self):
        return int(self.size)

    def update(self, surroundings):

        if self.size > 6:
            self.size *= 0.999

        eatting = [c for c in surroundings if can_a_eat_b(self, c)]
        for c in eatting:
            self.size += int(c.size / 2.5)

        if self.speed == 0: return eatting
        self.target_vector = self.controller(self, surroundings)
        if length(self.target_vector ) < 1: return eatting
        move_vector = [c * self.speed for c in normalize(self.target_vector)]
        self.x, self.y = add(self.pos, move_vector)
        return eatting

    def draw(self, s):
        pygame.draw.circle(s, self.color, self.int_pos, self.int_size)
        if not str(self.id).startswith('Food'):
            s.blit(write(str(self.id)), add(self.int_pos, (5, 5)))

def can_a_eat_b(a, b):
    return a.id != b.id and a.size > b.size and length(sub(a.pos, b.pos)) <= a.size + b.size

def player_controller(cell, surroundings):
    return sub(pygame.mouse.get_pos(), cell.pos)

colors = [c for c in pygame.color.THECOLORS.values()]
def rand_color():
    return random.choice(colors)

def rand_pos(rect):
    return random.randint(0, rect.width), random.randint(0, rect.height)

def food_controller(cell, surroundings):
    return (0, 0)

def food_factory(rect):
    cell = Cell(rand_pos(rect), rand_color(), 0, 5, food_controller)
    cell.id = 'Food' + str(cell.id)
    return cell

def ai_controller(cell, surroundings):
    targets = [(c, length(sub(cell.pos, c.pos))) for c in surroundings if c.size < cell.size and cell.id != c.id]
    targets_sorted = sorted(targets, key=lambda i: i[1])

    if targets_sorted:
        return sub(targets_sorted[0][0].pos, cell.pos)

    return (0, 0)

def ai_factory(rect):
    return Cell(rand_pos(rect), rand_color(), 0.7, 6, ai_controller)

Info = namedtuple('Info', ['size', 'pos', 'id'])

MENU, RUNNING = 0, 1

font = None
def write(text):
    return font.render(text, True, (0, 0, 0))

def main():
    state = MENU
    pygame.init()
    global font
    font = pygame.font.SysFont('Consolas', 17)
    s = pygame.display.set_mode((800, 600))
    s_rect = s.get_rect()
    c = pygame.time.Clock()
    CREATEFOOD = pygame.USEREVENT + 1
    CREATEAI = pygame.USEREVENT + 2
    pygame.time.set_timer(CREATEFOOD, 1000)
    pygame.time.set_timer(CREATEAI, 3000)

    marquee = cycle(range(800))

    player = None
    for _ in range(10): pygame.event.post(pygame.event.Event(CREATEFOOD))
    for _ in range(4): pygame.event.post(pygame.event.Event(CREATEAI))

    actors = []

    while True:

        for e in pygame.event.get():
            if e.type == pygame.QUIT: return
            if e.type == CREATEFOOD: actors.append(food_factory(s_rect))
            if e.type == CREATEAI: actors.append(ai_factory(s_rect))
            if state == MENU:
                if e.type == pygame.MOUSEBUTTONUP:
                    player = Cell((200, 200), rand_color(), 0.7, 6, player_controller)
                    actors.append(player)
                    player.id = 'Player'
                    state = RUNNING

        surroundings = [Info(c.size, c.int_pos, c.id) for c in actors]
        killed = []
        for ar in actors:
            for eaten in ar.update(surroundings):
                killed.append(eaten)

        actors = [a for a in actors if not a.id in [k.id for k in killed]]

        s.fill((255, 255, 255))

        for ar in actors:
            ar.draw(s)

        if state == MENU:
            s.blit(write('Click anywhere to start'), (next(marquee), 300))

        pygame.display.flip()
        c.tick(60)

if __name__ == '__main__':
    main()

rawDescription: Pygame: Initial menu leading up to game loop


code:
from tkinter import *
from tkinter.ttk import *
style = Style()
style.theme_use('default') # select the Unix theme
style.layout("TFrame")

rawDescription: Padding specified in style ignored by Ttk Frame


code:
import random
random.randint(0, 1)
random.randint(0, 1)

rawDescription: List index out of range and random number to choose an item in list


code:
def foo(): pass
foo.x = 1
foo.x

rawDescription: Why is a line in this python function necessary? (memoized recursion)


code:
def _flatten(foo):
    try:
        for item in foo:
            yield from flatten(foo)
    except TypeError:
        yield foo

def flatten(foo):
    for item in foo:
        yield from _flatten(foo)

def first_scalar(foo):
    return next(flatten(foo))

rawDescription: Python: Get first element of list potentially containing sublists


code:
from collections import OrderedDict
OrderedDict.fromkeys(['a', 'b', 'c', 'c', 'a', 'd', 'p', 'p']).keys()

rawDescription: How to delete duplicate values in a list?

description: Delete duplicate values in a list


code:
## Subnet number?
mask.network
## RFC 1918 space?
mask.is_private
 ## The subnet broadcast address
mask.broadcast
mask.iterhosts()

rawDescription: Get IP Mask from IP Address and Mask Length in Python


code:
studentDatabase = collections.namedtuple("student", "id name roll_no phone email")

DATABASE = {1: studentDatabase(1, 'Mayukh Sarkar', 9, '555-2312', 'mayukh2012@hotmail,com'),
            2: studentDatabase(2, 'Alisha Sengupta', 7, '555-1345', 'alisha@gmail.com')}

rawDescription: How can I pass the optional parameter of a namedtuple in a function

description: Pass the optional parameter of a namedtuple in a function


code:
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
)

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    os.path.join(PROJECT_DIR, 'templates'),
)

rawDescription: Django: how do I redistribute a project/app that contains extendable HTML templates?


rawDescription: From a list of floats, how to keep only mantissa in Python?


rawDescription: How to compute huge numbers with python?

description: Compute huge numbers with python


code: os.system("C:\\FIOCheck\\xutil.exe  -i get phy " +HBEA + ">C:\\FIOCheck\\HBEAResult.txt")

rawDescription: os.system commands

description: Os.system commands


rawDescription: Python get value from input element with lxml xpath


code:
def set_path(someDict, path, value):
    for x in path[::-1]:
        value = {x: value}
    return deepupdate(someDict, value)

def deepupdate(original, update):
    for key, value in original.items():
        if not key in update:
            update[key] = value
        elif isinstance(value, dict):
            deepupdate(value, update[key])
    return update

person = {}
person = set_path(person, ['name'], 'Shalom')
person = set_path(person, ['address', 'city'], 'Toronto')
person = set_path(person, ['address', 'street'], 'Baddessa')

pprint(person)

rawDescription: Store path to dictionary value for setting value


code:
def dict_diff ( merge, lhs, rhs ):
    """Generic dictionary difference."""
    diff = {}
    for key in lhs.keys():
          # auto-merge for missing key on right-hand-side.
        if (not rhs.has_key(key)):
            diff[key] = lhs[key]
          # on collision, invoke custom merge function.
        elif (lhs[key] != rhs[key]):
            diff[key] = merge(lhs[key], rhs[key])
    for key in rhs.keys():
          # auto-merge for missing key on left-hand-side.
        if (not lhs.has_key(key)):
            diff[key] = rhs[key]
    return diff

def user_diff ( lhs, rhs ):
    """Merge dictionaries using value from right-hand-side on conflict."""
    merge = lambda l,r: r
    return dict_diff(merge, lhs, rhs)

import copy

def push ( x, k, v ):
    """Returns copy of dict `x` with key `k` set to `v`."""
    x = copy.copy(x); x[k] = v; return x

def pop ( x, k ):
    """Returns copy of dict `x` without key `k`."""
    x = copy.copy(x); del x[k]; return x

def special_diff ( lhs, rhs, k ):
      # transform list of dicts into 2 levels of dicts, 1st level index by k.
    lhs = dict([(D[k],pop(D,k)) for D in lhs])
    rhs = dict([(D[k],pop(D,k)) for D in rhs])
      # diff at the 1st level.
    c = dict_diff(user_diff, lhs, rhs)
      # transform to back to initial format.
    return [push(D,k,K) for (K,D) in c.items()]

rawDescription: How to compare two lists of dicts in Python?

description: Compare two lists of dicts in Python


rawDescription: How can i make the common function/view for servinf downloadble files in django python

description: Make the common function/view for servinf downloadble files in django python


code:
for i, b in enumerate(array):
    x = i*80 + 20  # <-- add 20 to shift by half the linewidth
    pygame.draw.line(screen, colour, (x, 400), (x, (400-b)), 40)

rawDescription: pygame draw function

description: Pygame draw function


code:
"""
This script retrieves an account's associated hardware objects

Important manual pages:
http://sldn.softlayer.com/reference/services/SoftLayer_Account/getHardware

License: http://sldn.softlayer.com/article/License
Author: SoftLayer Technologies, Inc. <sldn@softlayer.com>
"""
# So we can talk to the SoftLayer API:
import SoftLayer.API

# For nice debug output:
from pprint import pprint as pp

# Your SoftLayer username and api key
API_USERNAME = 'set me'
API_KEY = 'set me'

# Creates a new connection to the API service.
client = SoftLayer.API.Client(username=API_USERNAME,api_key=API_KEY)

try:
    hardwareObjects = client['SoftLayer_Account'].getHardware()
    pp(hardwareObjects)

except SoftLayer.SoftLayerAPIError as e:
        pp('Unable to get hardware objects faultCode=%s, faultString=%s'
            % (e.faultCode, e.faultString))

rawDescription: Softlayer Server_ID

description: Softlayer Server_ID


rawDescription: From Matlab to Python - Solve function

description: From Matlab to Python - Solve function


rawDescription: convert a dict to sorted dict in python

description: Convert a dict to sorted dict in python


code: MyAction(option_strings=[], dest='baz', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)

rawDescription: Neatly pass positional arguments as args and optional arguments as kwargs from argpase to a function


code:
from Bio import SeqIO
from random import sample
with open("foo.fasta") as f:
    seqs = SeqIO.parse(f, "fasta")
    samps = ((seq.name, seq.seq) for seq in  sample(list(seqs),2))
    for samp in samps:
        print(">{}\n{}".format(*samp))

rawDescription: How to randomly extract FASTA sequences using Python?

description: Randomly extract FASTA sequences using Python


code:
@some_decorator
def methodName(parameter):
    Class_Name.CONSTANT_VARIABLE = parameter

rawDescription: Basic Python method definitions

description: Basic Python method definitions


code:
a
update_globals({"a": 5})
a

rawDescription: How can I load all keys from a dict as local variables, a better aproach?

description: Load all keys from a dict as local variables, a better aproach


rawDescription: Best way of removing single newlines but keeping multiple newlines


code:
def yu(x): return 0
def make_new_yu(yu, i):
    def new_yu(x): return i + yu(x)
    return new_yu
for i in range(0, 5):
    yu = make_new_yu(yu, i)

rawDescription: Python: Lambda in a sum

description: Python: Lambda in a sum


code:
sgDict = {}
for elb in Elbs:
    Sgs = elb['SecurityGroups']
    for sg in Sgs:
        elbName = elb['LoadBalancerName']
        if sg in sgDict:
            elbList = sgDict[sg];
            elbList.append(elbName);
            sgDict[sg] = elbList;
        else:
            sgDict[sg] = [elbName]

rawDescription: How to get the resource for a given security group using python boto?

description: Get the resource for a given security group using python boto


code:
data = {
u'uuid1': {
    u'checked': False,
    u'deleted': False,
    u'last_change': u'2014-12-25 09:15:22.155000',
    u'text': u'Test.'
  },
u'uuid2': {
    u'checked': False,
    u'deleted': False,
    u'last_change': u'2014-12-25 09:15:22.155000',
    u'text': u'Test'
  }
}

order = [data['uuid2'], data['uuid2']]

rawDescription: How do I order dict by iterating list of uuids in django template language?

description: Order dict by iterating list of uuids in django template language


code:
def helper(k, g):
    r = len(g)
    address, lastname = k
    if r > 2:
        lastname = 'The {} Family'.format(lastname)
    elif r > 1:
        lastname = ' and '.join(g['Name']) + ', ' + lastname
    else:
        lastname = g['Name'].squeeze() + ' ' + lastname
    return (address, lastname)

grouped = df.groupby(['Address', 'Lastname'])

rawDescription: python pandas applying for loop and groupby function

description: Python pandas applying for loop and groupby function


rawDescription: Dynamic function docstring

description: Dynamic function docstring


rawDescription: Django filter on TimeField

description: Django filter on TimeField


code:
import dis
dis.dis(ds._isurl)
dis.dis(ds._isurl_staticmeth)

rawDescription: Why is `_isurl` an instance method rather than a static method of a numpy `DataSource`?


code:
np.fill_diagonal(a, -np.inf)
max_value = a.max()

rawDescription: Minimum of Numpy Array Ignoring Diagonal


code:
def foo(x, y=5):
   return x, y
foo(10)
foo.func_code.co_varnames
foo.func_defaults
foo.func_defaults = (7,)
foo(10)

rawDescription: Change default arguments of function in python


code:
def addOne(v):
    v['A'] += 1
    return v

df.apply(addOne, axis=1)

rawDescription: pandas DataFrame, how to apply function to a specific column?

description: Pandas DataFrame, how to apply function to a specific column


code: df = df.reindex(columns=sorted(df.columns, key=lambda x: x[::-1]))

rawDescription: Pandas: break categorical column to multiple columns


code:
from django.db import models
from .utils import STATES
class StateChoice(models.Model):
    state = forms.ChoiceField(choices=STATES)

rawDescription: How to read a data file containing survey form options into models.py

description: Read a data file containing survey form options into models.py


rawDescription: Can dictionary keys be forced to a particular order?


code:
dct = {'Test':'Math','results':[{'name':'Paul','score':78},{'name':'Ann','score':87},{'name':'John','score':82}]}

print(sum(d["score"] for d in dct["results"]))

rawDescription: How can I extract values from a list of tuples inside a dictionary?

description: Extract values from a list of tuples inside a dictionary


code:
def getCities():
    m1 = city('Mexico City', 'http://www.accuweather.com/en/mx/mexico-city/242560/daily-weather-forecast/242560?day=2')
    m3 = city('Veracruz', 'http://www.accuweather.com/en/mx/veracruz/236233/daily-weather-forecast/236233?day=2')
    m5 = city('Tampico', 'http://www.accuweather.com/en/mx/tampico/235985/daily-weather-forecast/235985?day=2')
    m7 = city('Nuevo Laredo', 'http://www.accuweather.com/en/mx/nuevo-laredo/235983/daily-weather-forecast/235983?day=2')
    m9 = city('Monterrey', 'http://www.accuweather.com/en/mx/monterrey/244681/daily-weather-forecast/244681?day=2')
    m11 = city('S. Luis Potosi', 'http://www.accuweather.com/en/mx/san-luis-potosi/245369/daily-weather-forecast/245369?day=2')
    m13 = city('Queretaro', 'http://www.accuweather.com/en/mx/queretaro/245027/daily-weather-forecast/245027?day=2')
    m15 = city('Laz. Cardenas', 'http://www.accuweather.com/en/mx/lazaro-cardenas/239054/daily-weather-forecast/239054?day=2')

    cities = []
    cities.append(m1)
    cities.append(m3)
    cities.append(m5)
    cities.append(m7)
    cities.append(m9)
    cities.append(m11)
    cities.append(m13)
    cities.append(m15)

    return cities

rawDescription: Writing a method that I can call in a separate script in python


code: from .blah import Foo

rawDescription: Python 3 NOT updating variables in a nested package (”recursive” relative imports used)


code: only_last_and_first = [d for d in L if 'firstname' in d and 'lastname' in d]

rawDescription: Get to nested dictionary in list

description: Get to nested dictionary in list


code:
sortkeys = dict((x[0], index) for index,x in enumerate(SortOrder))
SortedPairDict = sorted(PairDict.iteritems(),
                        key=lambda x: sortkeys[x[0][0]])

rawDescription: Reordering Dictionary based on specific order


code:
import numpy as np
a = np.random.rand(3, 4, 5)
b = np.random.rand(5, 6)
np.allclose(np.einsum('ikj,jl->ikl', a, b), np.dot(a, b))

rawDescription: Convert einsum computation to dot product to be used in Theano


rawDescription: Remove Python dict from JSON file response


code:
import os
from time import sleep
# other imports

while True:
    file1 = os.stat('file.txt') # initial file size
    file1_size = file1.st_size

    # your script here that collects and writes data (increase file size)
    sleep(1)
    file2 = os.stat('file.txt') # updated file size
    file2_size = file2.st_size
    comp = file2_size - file1_size # compares sizes
    if comp == 0:
        restart_program()
    else:
        sleep(5)

rawDescription: Monitoring if a file stopped writing in python


code: df.groupby('ID Number').apply(lambda x: x.to_csv(str(x.name) + '.csv'))

rawDescription: How to filter values by Column Name and then extract the rows that have the same value to another CSV file? Python/Pandas

description: Filter values by Column Name and then extract the rows that have the same value to another CSV file? Python/Pandas


rawDescription: What is a cell in the context of an interpreter or compiler?


code:
class slicingbuffer:
    def __init__ (self, source):
        self.source = source
    def __getitem__ (self, index):
        if not isinstance(index, slice):
            return buffer(self.source, index, 1)
        elif index.stop is None:
            return buffer(self.source, index.start)
        else:
            end = max(index.stop - index.start, 0)
            return buffer(self.source, index.start, end)

rawDescription: Is there a way to use a memoryview with regexes in Python 2?


code:
res = df.groupby(['a', 'b']).apply(lambda group: group.index.values)
res[1, 1]
res[2, 24]

rawDescription: find index of similar values

description: Find index of similar values


code:
def foo():
    if conditional():
        logger.info("<Conditional's meaning> happened, so we're not "
                    "setting up the interface.")

import dis
dis.dis(foo)

rawDescription: How to cleanly keep below 80-char width with long strings?

description: Cleanly keep below 80-char width with long strings


rawDescription: Functional conversion from dictionary to list


code: [x[1] for x in d.descr]

rawDescription: Parsing complex numpy dtypes (i.e. dtypes consisting of an array of tuples) into lists?


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

def bar_tops(x, y, width=0.8, align='center', ax=None, **kwargs):
    x = np.array(x)
    y = np.array(y)
    if align == 'center':
        left = x - 0.5 * width
        right = x + 0.5 * width
    elif align == 'edge':
        left = x
        right = x + width
    if ax == None:
        ax = plt.gca()
    ax.hlines(y, left, right, **kwargs)

rawDescription: Matplotlib Bar Customization

description: Matplotlib Bar Customization


code:
import subprocess
process = subprocess.Popen('pgrep firefox', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
my_pid, err = process.communicate()

rawDescription: How to check in Mac OSX with Python if a process is RUNNING or not

description: Check in Mac OSX with Python if a process is RUNNING or not


rawDescription: Python Compare overlap of multiple dictionaries of ranges


code:
from PyQt4.QtGui import QMainWindow
from Ui_MainWindow import Ui_MainWindow
from LoginDialog import LoginDialog
from LoginError import LoginError

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Show login dialog before anything else
        self._show_login_dialog()

        # Finish initializing the GUI
        self.ui.label.setText('Hello {}!'.format(self.user))
        self.ui.pushButton.clicked.connect(self._button_pushed)

    def _show_login_dialog(self):
        ld = LoginDialog(self)
        if ld.exec_() and ld.is_valid(): # If user pressed OK and entered a valid info
            self.user = ld.get_username()
        else:
            #User either cancelled the login dialog or didn't enter valid info
            raise LoginError

    def _button_pushed(self):
        self.ui.label.setText('{}, you pressed the button!'.format(self.user))

rawDescription: How to close a login dialog and show the main window (PyQt4)

description: Close a login dialog and show the main window (PyQt4)


code:
S = S.replace(" ", '')
if len(S) != 16 or not S.isdigit():
    return False

rawDescription: Credit card check exercise python

description: Credit card check exercise python