code: import pyFileName # without extension .py

rawDescription: Is there a way to import an embedded python script into IronPython as a python module?


code:
counts = np.sum(binary_image<binary_image.max()/2., axis=1)

plt.plot(counts)

rawDescription: Plot number of black pixels per row using python


rawDescription: If without else - Python lists

description: If without else - Python lists


rawDescription: suppress warnings in rpy2

description: Suppress warnings in rpy2


code:
list_of_dict = []
for key, value in nested_dict.items():
    for key1, value1 in value.items():
        for key2,value2 in value1.items():
            list_of_dict.append({'A':key,'B':key1,'C':key2,'D':value2})

df = pd.DataFrame(list_of_dict)

rawDescription: Converting dictionary of dictionary of dictionary to pandas data frame


code:
class MyClass(object):
    def __init__(self):
        self.level = 0
    def inclev(self):
        self.level += 1
    def declev(self):
        self.level -= 1

    __enter__ = inclev  # For __enter__, just alias inclev, no need for wrapper
    def __exit__(self, exc_type, exc_value, traceback):
        self.declev()

rawDescription: Context manager inside a class instance

description: Context manager inside a class instance


code:
import regex
p = regex.compile(r"\p{Lu}")
if p.match("Żółw"):
    print("Capitalized!")

rawDescription: Python regex for unicode capitalized words


code:
class Product(ndb.model):
    tags = ndb.StringProperty(repeated=True)
    name = ndb.StringProperty()

rawDescription: Hierarchical Tags in Google App Engine ndb


rawDescription: Fits image input to a range in plot - Python


rawDescription: What does Python mean by printing "[...]" for an object reference?


code:
def x(data):
    return True if data%3==0 else False
def y(data):
    return True if data%5==0 else False

rawDescription: Logical and of two functions

description: Logical and of two functions


code: FFT_out = np.hstack((FFT_out, block))

rawDescription: Trying to get Python to concatenate generated column vectors to form a two dimensional array. It's not working


code: days = ["NOTADAY", "sunday", "NOTADAY", "NOTADAY", "NOTADAY", "NOTADAY"]

rawDescription: Comparing string lists to find missing value of sequence


code:
from PyQt4 import QtGui, QtCore

class MainWindow(QtGui.QMainWindow):

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

        w = QtGui.QWidget() # container widget

        btn = QtGui.QPushButton(w)
        btn.move(100,100)
        btn.setStyleSheet("border-image: url('somepicture.png');")

        self.setCentralWidget(w) # add the container widget to the QMainWindow
        self.show()

app = QtGui.QApplication([])
window = MainWindow()

app.exec_()

rawDescription: PyQt: How can i set stylesheet contents on scaled mode?


code:
from shapely.ops import unary_union, polygonize
boundary = GeoDataFrame.from_file('your_geojson')
# Assuming you have a boundary as linestring, transform it to a Polygon:
mask_geom = unary_union([i for i in polygonize(boundary.geometry)])
# Then compute the intersection:
gdf.geometry = gdf.geometry.intersection(mask_geom)

rawDescription: Contour plot data (lat,lon,value) within boundaries and export GeoJSON


rawDescription: Splitting a string into consecutive counts?


code:
l = []
l.append('myVarName')
l.append('anotherVarName')

rawDescription: Equivalent of "genvarname" in Python

description: Equivalent of "genvarname" in Python


code:
def mix_lists(l1, l2):
    """ Mix two lists evenly, generating the elements of the mixed list. """
    m, n = len(l1), len(l2)
    for i in range(m + n):
        q, r = divmod(i * n, m + n)
        yield l1[i - q] if r < m else l2[q]

rawDescription: Homogeneous mix of two lists

description: Homogeneous mix of two lists


code:
url = "http://www.pasion.com/amistad/"
from selenium import webdriver
dr = webdriver.PhantomJS()
dr.get(url)
dr.find_element_by_xpath("//a[@href='javascript:muestradulto()']").click()
print("EL BUSCANUNCIOS" in dr.page_source)

rawDescription: BeautifulSoup: scrape HTML only accessible after clicking "Accept" in the same URL


rawDescription: compare similar items nested in a list, and removing them

description: Compare similar items nested in a list, and removing them


code:
import example
spams = example.get_spams()
for index, spam in enumerate(spams):
    spams[index].perform()
    spam.perform()

rawDescription: How to return a std::vector<const T*> to python?

description: Return a std::vector<const T*> to python


code: self.player.rect.x -= 5

rawDescription: Trying to make a "solid" block in pygame but it doesnt work


code:
class LaserData(Structure):
    _pack_ = 1
    _fields_ = (('time',      c_uint),
                ('judgement', c_byte),
                ('meas_info', c_byte * 3),
                ('data',      c_float))

rawDescription: How to interpret a integer as a float

description: Interpret a integer as a float


rawDescription: Pandas: Generate Sequential Timestamp with Jump


code:
with open("output.csv", 'wb') as f:
    writer = csv.writer(f, delimiter=';')
    for row in output_rows:
        writer.writerow(row)

rawDescription: CSV files and Python

description: CSV files and Python


code: Location = [0, 2, 4]

rawDescription: Append index of items in one list to another in Python 2.7


code: if distance <= 2: return

rawDescription: Python - PyGame - Learning vectors/animation


code:
in_both = df1["AuthorId"].isin(df2["AuthorId"])
in_both.value_counts()
in_both.head(5)

rawDescription: How to search the elements in a column of a csv in a column of another csv file using python?

description: Search the elements in a column of a csv in a column of another csv file using python


code:
now_et = et.normalize(et.localize(now))
now_ct = ct.normalize(now_et.astimezone(ct))
now_mt = mt.normalize(now_et.astimezone(mt))
now_pt = pt.normalize(now_et.astimezone(pt))

rawDescription: Python - Convert time to different time zone with am/pm


code:
...
url(r'^/some/path/report$', file_load_view),
...

rawDescription: Export a template information into an Excel and then download it in django


rawDescription: How to parse a list of list of floats in python?

description: Parse a list of list of floats in python


code: yield comb(S.replace('?','0',1))

rawDescription: Replace a character with multiple characters using Python


code:
with open(sys.argv[1], 'r') as f:
    do_something_with(f)

rawDescription: Running python from windows command prompt on many files


code:
# First we create a RDD in order to create a dataFrame:
rdd = sc.parallelize([('u1', 1, [1 ,2, 3]), ('u1', 4, [1, 2, 3])])
df = rdd.toDF(['user', 'item', 'fav_items'])
# Print dataFrame
df.show()

# We make an user define function that receives two columns and do operation
function = udf(lambda item, items: 1 if item in items else 0, IntegerType())

df.select('user', 'item', 'fav_items', function(col('item'), col('fav_items')).alias('result')).show()

rawDescription: Adding column to PySpark DataFrame depending on whether column value is in another column


code:
domains = []
for matching in matchings:
    if matching['id'] == the_id:
        domains.append(matching['domain'])

rawDescription: What's the most efficient way to access sibling dictionary value in a Python dict?


code:
from matplotlib_venn import venn2
from matplotlib.cbook import flatten
from matplotlib import pyplot as plt
import numpy as np

figure, axes = plt.subplots(2, 3, figsize=(11.69,5.5))

BSL_20=(313,10,76)
BSL_40=(384,17,150)
BSL_100=(665,8,378)
BSL_100CC=(860,23,879)
BSL_200=(585,17,758)

data = [BSL_20, BSL_40, BSL_100, BSL_100CC, BSL_200]
max_area = max(map(sum, data))

def set_venn_scale(vd, ax, true_area, reference_area=max_area):
    sx = np.sqrt(float(reference_area)/true_area)
    sy = max(vd.radii)*1.3
    ax.set_xlim(-sx, sx)
    ax.set_ylim(-sy, sy)

for a, d in zip(flatten(axes), data):
    vd = venn2(d, set_labels = ('150mm at 50%', '400mm at 25%'), ax=a)
    set_venn_scale(vd, a, sum(d))

axes[1,2].axis('off')
figure.tight_layout(pad=0.1)
plt.show()

rawDescription: Matplotlib_Venn, Multiple Venn diagrams same scale


code: return redirect('result')

rawDescription: django- How to filter the database based on the submitted form data

description: Django- How to filter the database based on the submitted form data


rawDescription: Request from different Country IP

description: Request from different Country IP


code:
values = str(z).translate(None,"([]){},\"'").split()
output = '\n'.join('\t'.join(x for x in g if x) for g in grouper(4, values))

rawDescription: write a new line text file python every 4 tabs

description: Write a new line text file python every 4 tabs


code: uniformity = lambda x : 1 - 0.5*sum( abs(x - np.average(x)) )/(len(x)*np.average(x))

rawDescription: Does NumPy have a Uniformity function?

description: Does NumPy have a Uniformity function


code:
import Tkinter as tk
import ttk

class Tab1(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        tk.Label(self, text="Test label1").pack()

class Tab2(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        tk.Label(self, text="Test label2").pack()

class Tab3(tk.Frame):
    def __init__(self, root):
        tk.Frame.__init__(self, root)
        self.viewKeysCanvas = tk.Canvas(self)
        self.viewKeysGroup = tk.Frame(self.viewKeysCanvas)
        self.viewKeysScrollbar = tk.Scrollbar(self, orient="vertical",
                                command=self.viewKeysCanvas.yview)
        self.viewKeysCanvas.configure(yscrollcommand=self.viewKeysScrollbar.set)
        self.viewKeysScrollbar.pack(side="right", fill="y")
        self.viewKeysCanvas.pack(fill="both", expand=True)
        self.viewKeysCanvas.create_window(0, 0, window=self.viewKeysGroup, anchor="nw")
        self.viewKeysGroup.bind("<Configure>", self.on_frame_configure)
        self.populate()

    def populate(self):
        for x in range(0, 9):
            aKeyGroup = tk.LabelFrame(self.viewKeysGroup, text="number: " + str(x))
            buttonFrame = tk.Frame(aKeyGroup)
            tk.Button(buttonFrame, text="Action 1").pack(padx=10, side="left")
            tk.Button(buttonFrame, text="Action 2").pack(padx=10, side="left")
            tk.Label(aKeyGroup, text="Public key: ").pack(side="top")
            tk.Label(aKeyGroup, text="Private key: ").pack(side="top")
            buttonFrame.pack(padx=10, pady=10)
            aKeyGroup.pack()

    def on_frame_configure(self, event):
        """Reset the scroll region to encompass the inner frame"""
        self.viewKeysCanvas.configure(scrollregion=self.viewKeysCanvas.bbox("all"))

root = tk.Tk()
sizex, sizey, posx, posy = 800, 500, 100, 100
root.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy))
root.title('Scroll Test')

note = ttk.Notebook(root)
tab1 = Tab1(note)
tab2 = Tab2(note)
tab3 = Tab3(note)

note.add(tab1, text="Test tab 1")
note.add(tab2, text="Test tab 2")
note.add(tab3, text="Test tab 3")

note.pack(expand=True, fill="both")
root.mainloop()

rawDescription: Why isn't my tkinter scrollbar working?

description: Why isn't my tkinter scrollbar working


rawDescription: Can anyone explain to me what a two-level dictionary is in Python


code:
bulk = hdd.initialize_ordered_bulk_op()
for product, product_id in data:
    hdd.find({'_id': product_id}).update({'$set': {'Speed': products['Speed'],
                                                   'capacity': products['capacity'],
                                                   'format': products['format']}})
bulk.execute()

rawDescription: PyMongo update multiple records with multiple data


rawDescription: writing to CSV in python

description: Writing to CSV in python


code:
def callback(self):
    self.my_button.config(state=tk.DISABLED)
    self.root.after(200, lambda: self.my_button.config(state=tk.NORMAL))
    # other actions

rawDescription: Prevent a function being called twice when a user double-clicks a button?


code:
class Add(Operator):
    def __new__(cls, left, right):
        if left == right:
            return Mul(2, left)
        return Operator.__new__(cls)
    ...

rawDescription: How does sympy work? How does it interact with the interactive Python shell, and how does the interactive Python shell work?


code: print(tweet_text, file=write_file)

rawDescription: Extracting only tweets of a particular # hastag


code: regex.sub(r'[A-Z]\p{L}+\s*', ' #NE# ', the_rest)

rawDescription: How to Include accented words in regex

description: Include accented words in regex


rawDescription: I don't understand the operation here: for index, item in enumerate(choices):


code: words = words1 | words2

rawDescription: Extend or Append for String in method

description: Extend or Append for String in method


code: DFGrouped = df2.groupby(lambda x: 'Group 1' if df2.X[x] == 'A' else 'Group 2')

rawDescription: Pandas GroupBy by Element and everything else


code:
def feetConverter(number):
    tempInchValue, feetValue = math.modf(int(number) * 0.03281)
    return (feetValue,inchConverter(tempInchValue))

rawDescription: Centimeter to Feet converter in Python

description: Centimeter to Feet converter in Python


rawDescription: How to update a Tix.ComboBox's text?

description: Update a Tix.ComboBox's text


code: timeArray = [i*deltaTime for i in range(1000)]

rawDescription: Confused with arrays in python

description: Confused with arrays in python


rawDescription: Dividing all but first element of a matrix


code:
def rename_dup(col):
    ans = []
    counter = 1
    for c in col:
        if c.startswith('Weight (LB)'):
            ans.append(c + str(counter))
            counter += 1
        else:
            ans.append(c)

    return ans

df.columns = rename_dup(df.columns)

rawDescription: Access column in data frame that shares a name with other columns


code:
def nesting(level):
    ret = 'value'
    for l in range(level, 0, -1):
        ret = {'key%d' % l: ret}
    return ret

rawDescription: dynamically nesting a python dictionary

description: Dynamically nesting a python dictionary


code:
Example
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.cElementTree as etree

en2jp = {u"State": u"州", u"City": u"都市", u"Town": u"町"} # English -> Japanese

tree = etree.parse(filename)
for field in tree.iterfind('.//Fields/Field'):
    name, alias = [field.find(tag) for tag in ['Name', 'AliasName']]
    if name is None or name.text is None or alias is None: continue
    alias.text = en2jp.get(name.text.strip(), alias.text)
tree.write('output.xml', encoding='utf-8')

rawDescription: Replace multiple texts with their corresponding texts in XML using Python


code:
@render_to('category.html')
def category_view(request, slug):
    return {'cat':Category.objects.get(slug=slug)}

rawDescription: URLs stored in database for Django site

description: URLs stored in database for Django site


code: ts = ts.ix[ts.index.indexer_between_time(time(7), time(18))]

rawDescription: Mask timeseries outside business hours

description: Mask timeseries outside business hours


code:
def dot2d(a):
    aa=[dot1d(x,y) for x,y in itertools.product(a,a)]
    return [aa[i::len(a)] for i in range(len(a))]

rawDescription: Pythonic way of calculating A x A' (without numpy)


rawDescription: python: How to compare values in a list by row?

description: Python: How to compare values in a list by row


code:
def fast_inv_sqrt(x):
    x = x.astype('float32')
    x2 = x * 0.5;
    y = x.view(dtype='int32')
    y = 0x5f3759df - np.right_shift(y, 1)
    y = y.view(dtype='float32')
    y  = y * ( 1.5 - ( x2 * y * y ) )
    return y

rawDescription: Bit hack with NumPy

description: Bit hack with NumPy


code:
dataset = pd.DataFrame(np.random.rand(1000,3), columns=["A", "B","C"])

weightspace = np.exp(np.linspace(len(dataset), 0, num=len(dataset))*-0.05)
def rollingsum(array):
    weights = weightspace[0-len(array):]
    # Convolve the array and the weights to obtain the result
    a = np.dot(array, weights).sum()
    return a

a = pd.expanding_apply(dataset, rollingsum)

rawDescription: Exponential Decay on Python Pandas DataFrame


code:
d = missingdict()
d['foo']
d

rawDescription: Python defaultdict that does not insert missing values


code: np.in1d(arr1, arr2)

rawDescription: boolean indexing from a subset of a list in python

description: Boolean indexing from a subset of a list in python


code:
s1 = pd.Series(list1)
s2 = pd.Series(list2)
s1.where(s1 != '', s2)

rawDescription: Python: merge lists or data frames and overwrite missing values


code: a = A('firstnode')

rawDescription: Python dynamically generate dependencies between class instances


code: map(sum, zip(A, B))

rawDescription: Python Add Elements of a List (or Set, or whatever Data Type is appropriate)


code: f1_b = list(map(lambda x: list(map(lambda t: t.strip(), x.split(',', 1))), lst))

rawDescription: Nested maps in Python 3

description: Nested maps in Python 3


code:
import Queue
import threading

def serialize(q):
  """runs a serializer on queue q: put [-1]*4 on q to terminate."""
  while True:
    # get output-queue for result, a callable, its args and kwds
    out_q, tocall, args, kwds = q.get()
    if out_q == -1:
      return
    result = tocall(*args, **kwds)
    out_q.put(result)

class WrapCall(object):
  """Wraps a callable to serialize calls to it."""

  def __init__(self, inq, ouq, tocall):
    self.inq = inq
    self.ouq = ouq
    self.tocall = tocall

  def __call__(self, *a, **k):
    self.inq.put((self.ouq, self.tocall, a, k))
    if self.ouq is None:
      return None
    return self.ouq.get()

class WrapObj(object):
  """Wraps any object to serialize all calls to its methods."""

  def __init__(self, obj):
    self._o = obj
    self._q = Queue.Queue()
    t = threading.Thread(target=serialize, args=(self._q,))
    t.setDaemon(True)
    t.start()
    self.t = t

  def __getattr__(self, n):
    """Wraps methods of self.w into an appropriate WrapCall instance."""
    towrap = getattr(self._o, n)
    if not callable(towrap):
      raise TypeError('Cannot wrap noncallable attribute %r (type: %s)'
                       % (n, type(towrap)))
    q = Queue.Queue()
    return WrapCall(self._q, q, towrap)

  def WrapperWait(self):
    """Return only when self.t has served all pending requests."""
    q = Queue.Queue()
    w = WrapCall(self.__q, q, lambda: None)
    return w()

rawDescription: Queuing methods to be run on an object by different threads in Python


code: mdict[manufacturer]

rawDescription: Django how to validate requested URL against a choices field?


code: percent_true = table.ix[:-1, ['percent_true']]

rawDescription: Pandas Column Calculations in PivotTable


code:
import json

def append(filename, obj):
    with open(filename, 'rb') as f:
        data = json.load(f, encoding='utf-8')
    data.append(obj)
    with open(filename, 'wb') as f:
        json.dump(data, f, encoding='utf-8')

rawDescription: Python update json file

description: Python update json file


rawDescription: python change str to hex, NOT CONVERTING

description: Python change str to hex, NOT CONVERTING


code:
import sys
sys.modules[module_name] = module

rawDescription: python importing code from a string

description: Python importing code from a string


rawDescription: Random Forest not working in opencv python (cv2)


code: 'sdne reven taht gnos eht si siht'

rawDescription: How do I loop a set of strings in reverse in Python?

description: Loop a set of strings in reverse in Python


code:
['http://adserver.adtech.de/addyn/3.0/1602/5506153/0/6490/ADTECH;loc=700;target=_blank;grp=[group]',
 'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js',
 'http://tags.expo9.exponential.com/tags/MarunadanMalayalicom/ROS/tags.js',
 'http://js.genieessp.com/t/057/794/a1057794.js',
 'http://ib.adnxs.com/ttj?id=5620689&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]',
 'http://ib.adnxs.com/ttj?id=5531763',
 'http://advs.adgorithms.com/ttj?id=3279193&cb=[CACHEBUSTER]&pubclick=[INSERT_CLICK_TAG]',
 'http://xp2.zedo.com/jsc/xp2/fo.js',
 'http://www.marunadanmalayali.com/js/mnmads.js',
 'http://www.marunadanmalayali.com/js/jquery-2.1.0.min.js',
 'http://www.marunadanmalayali.com/js/jquery.hoverIntent.minified.js',
 'http://www.marunadanmalayali.com/js/jquery.dcmegamenu.1.3.3.js',
 'http://www.marunadanmalayali.com/js/jquery.cookie.js',
 'http://www.marunadanmalayali.com/js/swanalekha-ml.js',
 'http://www.marunadanmalayali.com/js/marunadan.js?r=1875',
 'http://www.marunadanmalayali.com/js/taboola_home.js',
 'http://d8.zedo.com/jsc/d8/fo.js']

rawDescription: Get all the javascript file name and its contents in python perfectly


rawDescription: PyQt5 does not change gifs

description: PyQt5 does not change gifs


code:
import platform
from distutils.version import StrictVersion

utility1 = None
def init_module():
    global utility1 # declare it global to modify it
    print('Importing helper module...')

    os_version, _, _ = platform.mac_ver()

    if StrictVersion(os_version) < StrictVersion('10.10'):
        utility1 = 'utility 1 for 10.9 and below'
    else:
        utility1 = 'utility 1 for 10.10 and above'

init_module() #Call the init function when importing the module

def run_utility1():
    return 'Running ' + utility1

rawDescription: Testing branches in module-level code in python


code:
#... Stuff as before
intersection = set.intersection(*sets)
reference_to_first = next( (x for x in lists[0] if tuple(x) in intersection), None )

rawDescription: python - Common lists among lists in a list

description: Python - Common lists among lists in a list


code: f = lambda x: F2(*x)

rawDescription: Use optimize.minimize from scipy with 2 variables and interpolated function


code:
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return

if __name__ == "__main__":
    MyFrame().mainloop()

rawDescription: filedialog, tkinter and opening files

description: Filedialog, tkinter and opening files


code:
def orderedPossibleSplits(value, validIncrements):
    ret = []
    splits = possibleSplits(value, validIncrements)
    for value in splits:
        value.sort()
        if value not in ret:
            ret.append(value)
    return ret

rawDescription: How to break down a number with another from list?

description: Break down a number with another from list


rawDescription: How to construct a TimeGrouper with a DateOffset?

description: Construct a TimeGrouper with a DateOffset


code:
CELERYBEAT_SCHEDULE['---'] = {
        'task': ...,
        'schedule': ...,
        'args': (),
        'options': {
            # Do not run the task if it starts 30 minutes after it is
            # scheduled. This is useful if the Celery workers go down,
            # celerybeat will keep adding tasks to the queue.
            'expires': 1800
        }
    }

rawDescription: Why does Celery revoke all scheduled tasks and discard them?


rawDescription: How should a certain percentage of evenly-distributed elements of a Python list be extracted?


rawDescription: Python expandtabs string operation

description: Python expandtabs string operation


code:
class MyClass(object):

    cache = {}

    @classmethod
    def test_func(cls, x):
        try:
            return cls.cache[x]
        except KeyError:
            cls.cache[x] = "CACHE STORE"
            return cls.cache[x]

rawDescription: Have exception hit two except blocks in python


code: df

rawDescription: Pandas expand json field across records

description: Pandas expand json field across records


code:
list1= ...
list2 = ...
for a in list1:
 for b in list2:
  list3=[c[1]/d[1] for c in a for d in b]
  list3function()

rawDescription: Processing list comprehension output element-by-element


code: np.cov(data, rowvar=False)

rawDescription: Build in function for computing covariance


rawDescription: Pandas: How can I use the apply() function for a single column?


code:
# first text draw normally

text_1 = self.font.render(message_1, True, color)
text_1_rect = text_1.get_rect()

# second text

text_2 = self.font.render(message_2, True, color)
text_2_rect = text_2.get_rect()

text_2_rect.right = text_1_rect.right # align to right side of first text

rawDescription: Pygame Text Anchor Right

description: Pygame Text Anchor Right


code: import datetime as dt

rawDescription: numpy - Python - Selectively import parts of the .txt file

description: Numpy - Python - Selectively import parts of the .txt file


code:
def comment_count(self):
    return self.comment_set.count()

rawDescription: should I use if statement in django template, although I'm using it in models.py

description: Should I use if statement in django template, although I'm using it in models.py


code:
import numpy as np
A = np.random.random(5)
R = np.column_stack([A,np.ones(len(A))])
k = np.random.random()
m0 = np.random.random()
M = R.dot([k,m0])

(k_inferred, m0_inferred), residuals, rank, s = np.linalg.lstsq(R, M)

assert np.allclose(m0, m0_inferred)
assert np.allclose(k, k_inferred)

rawDescription: Inverse of numpy.dot

description: Inverse of numpy.dot


code:
fl = open("1.txt", "r")
obj = pickle.load(fl)

rawDescription: Define object from text file

description: Define object from text file


code:
def _declarative_constructor(self, **kwargs):
    """A simple constructor that allows initialization from kwargs.

    Sets attributes on the constructed instance using the names and
    values in ``kwargs``.

    Only keys that are present as
    attributes of the instance's class are allowed. These could be,
    for example, any mapped columns or relationships.
    """
    cls_ = type(self)
    for k in kwargs:
        if not hasattr(cls_, k):
            raise TypeError(
                "%r is an invalid keyword argument for %s" %
                (k, cls_.__name__))
        setattr(self, k, kwargs[k])

rawDescription: Is there a shortcut for creating __init__ functions based on class attributes?


code:
yourDict = {'a':1, 'b':{'c':1, 'd': {'b':1}}}
indexList=['a']
reduce(lambda d,i:d[i], indexList[:-1], yourDict)[indexList[-1]] = "test"
yourDict

rawDescription: Python change an array's value from array index


code:
import wx
import cPickle

class MyListCtrl(wx.ListCtrl):

    def __init__(self, *args, **kwargs):
        wx.ListCtrl.__init__(self, *args, **kwargs)
        self.config = wx.Config("MykoolApp")

        self.fillist()

    def filllist(self):
         # load rows and check for error too, if no data
        data = self.config.Read("list_cntrl_data")
        rowList = cPickle.loads(data)

        for row in rowList:
            # add this row to list cntrl
            pass

    def savelist(self):
        rows = []
        for row in self:
            # add data to rows
            pass

        data =  cPickle.dumps(rows)
        self.config.Write("list_cntrl_data", data)

    def onchange(self):
        """
        on changes to list e.g. add delete call save list
        """
        self.savelist()

rawDescription: wxPython - Save Items in ListCtrl

description: WxPython - Save Items in ListCtrl


code:
def runInParallel(*fns):
  proc = []
  for fn in fns:
    p = Process(target=fn)
    p.start()
    proc.append(p)
  for p in proc:
    p.join()

runInParallel(func1, func2)

rawDescription: Python: How can I run python functions in parallel?


code:
def convertToList (matrix):
    list = [ y for x in matrix for y in x]
    return list

rawDescription: How can I use a Matrix as a dataset on PyBran?

description: Use a Matrix as a dataset on PyBran


rawDescription: Separating file extensions using python os.path module


rawDescription: Accepting top rows in pandas dataframe based on grouping


code:
mat = []

def test_append():
    for i in range(10):
        #mat += [i]
        mat.append(i)

def test_iadd():
    for i in range(10):
        mat += [i]

test_append()
print(mat)
test_iadd()
print(mat)

rawDescription: Why is list.append(x) more efficient than list += l[x]?


code:
True
False

rawDescription: Ellipses when converting list of numpy arrays to string in python 3


rawDescription: Is time.mktime timezone free in python?

description: Is time.mktime timezone free in python


code:
b = [1, 2, 2, 2, 0, 0, 1, 2, 2, 2, 2, 0, 1, 2, 0]
b = map(str, b)

c = []
for x in b:
    # if it's a '1', create a new {key:list} dict
    if x == '1':
        c.append({x: []})
        k = x
        continue
    # if it's a '2', append it to the last added list
    # make sure to check that 'c' is not empty
    if x == '2' and c:
        c[-1][k].append(x)

rawDescription: Converting list items to dictionary using lists items


code:
class MyClass:
    def __init__(self, count = 10):
        count -= 1
        if count:
           # the first child gets the value 9.
           # the second gets 8.
           # when the count gets to 0, stop!
           self.child = MyClass(count)

rawDescription: create instance of a class in the same class's definition in python

description: Create instance of a class in the same class's definition in python


code:
def three_tokens(s):
    tokens = s.split('-', 2)
    tokens.extend([''] * (3 - len(tokens)))
    return tokens

rawDescription: Concise way to split a string into a list of fixed number of tokens


code:
def unique_mapping(mappings):
    return dict((m['id'], m) for m in mappings).values()

rawDescription: Extracting unique items from a list of mappings


rawDescription: How can I do strtok()-type parsing in Python?

description: Do strtok()-type parsing in Python


rawDescription: Way of easily finding the average of every nth element over a window of size k in a pandas.Series? (not the rolling mean)


code:
from datetime import timedelta, datetime
def relative_date(reference, weekday, timevalue):
    hour, minute = divmod(timevalue, 1)
    minute *= 60
    days = reference.weekday() - weekday
    return (reference - timedelta(days=days)).replace(
        hour=int(hour), minute=int(minute), second=0, microsecond=0)

relative_date(datetime.now(), 4, 9.5)
relative_date(datetime.now() - timedelta(days=30), 6, 11.75)

rawDescription: Python construct datetime having weekday with other time parameters


code:
Doc.VAR = val
Doc.VAR2 = val2
Doc.save()

rawDescription: How to update from json a Mongoengine DynamicDocument

description: Update from json a Mongoengine DynamicDocument


code:
n_atoms = 4
atoms_x = np.random.uniform(0, 10, n_atoms)
atoms_y = np.random.uniform(0, 10, n_atoms)
atoms_al = np.random.uniform(0, 10, n_atoms)

for x, y, al in zip(atoms_x, atoms_y, atoms_al):
    r = np.sqrt((x - pixel_x)**2 + (y - pixel_y)**2)
    single_image = fmax * np.exp(-al * r)
    image += single_image

rawDescription: Issues with isolating color channels in Pylab


rawDescription: Filtering QuerySet based on captured URL parameters in Django?


rawDescription: python pandas - map using 2 columns as reference

description: Python pandas - map using 2 columns as reference


rawDescription: Python .count: Can't find correct syntax to count \n


rawDescription: Python etag/last modified not working; how to get latest rss


code:
from itertools import chain
from collections import defaultdict

def calculate_length(ind):
    # We want to transform this first into a dict of {doc_id:[tl_idf_a,...]}
    # First we transform it into a generator of ([doc_id,tl_idf],...)
    tf_gen  = chain.from_iterable(ind.itervalues())
    # which we then use to generate our transformed dictionary
    tf_dict = defaultdict(list)
    for doc_id, tl_idf in tf_gen:
        tf_dict[doc_id].append(tl_idf)
    # Now we proceed mostly as before, but we can just do it in one line
    return dict((doc_id, sqrt(sum(tl_idfs**2 for tl_idfs in tl_idfs))) for doc_id, tl_idfs in tf_dict.iteritems())

rawDescription: for information retrieval course using python, accessing given tf-idf weight

description: For information retrieval course using python, accessing given tf-idf weight


code:
module = __import__("foo")
obj = getattr(module, "bar")

rawDescription: Is there a way to import an object from python module programatically?


code: df = pd.read_csv('yourfile.csv', parse_dates=['time_x','time_y'])

rawDescription: How to create a new column based on time difference of two columns in Pandas?

description: Create a new column based on time difference of two columns in Pandas


rawDescription: How to configure the webserver to server a particular page as the default page?

description: Configure the webserver to server a particular page as the default page


code:
def save_book(request):
 if request.POST:
   book_name       = request.GET.get('book_name')
   author_name   = request.GET.get('author_name')
   publisher_name = request.GET.get('publisher_name')
   Book.object.creat(book_name, author_name,publisher_name)

rawDescription: Get value from an html templates and store it in mysql db through django without using form


code: sparql.method = 'POST'

rawDescription: INSERT/DELETE/UPDATE query using SPARQLWrapper


code:
from collective.documentviewer.settings import Base
class CustomSettings(Base):
    implements(IEnhancedDocumentViewerSchema)
    use_interface = IEnhancedDocumentViewerSchema

rawDescription: Plone - Override Zope Schema fields

description: Plone - Override Zope Schema fields


code:
regfield=np.zeros(3,dtype=dt1)
regfield
regfield[0]=('field1',1,10)
regfield[1]=('field2',2,20)
regfield[2]=('field3',3,30)

rawDescription: Placing a numpy record array inside another record array python


code:
import bs4

content = '''
And one
And two
And three
And four
And five
'''

soup = bs4.BeautifulSoup(content)
filtered_soup = soup.find_all("span", {"class":["text", "indent-1"]})
line_list = [line for line in filtered_soup]

rawDescription: Combine items in a list until an item containing specific text is found?


code:
from PIL import Image
import numpy as np

sample_img = Image.open('sample.png')
rescaled = 255 * np.asarray(sample_img)/2**16
img = Image.fromarray(np.uint8(rescaled))

rawDescription: Python image conversion

description: Python image conversion


code:
y = 1
f = lambda x: x + y
f(1)
y = 2
f(1)

rawDescription: Assign variable to local scope of function in Python


code:
plt.plot(x1, raw)
plt.plot(x2, smooth)

rawDescription: Plotting two different arrays of different lengths


code:
if __name__ == '__main__':
    class Test(ctypes.Structure):
        _fields_ = (('x', ctypes.c_int),
                    ('y', ctypes.c_void_p),
                    ('_string', ctypes.c_char_p))
        string = UTF16LEField('_string')

    print('test 1: structure field')
    t = Test()
    t.string = u'eggs and spam'
    print(t.string)

    print('test 2: parameter and result')
    result = None

    @ctypes.CFUNCTYPE(c_utf16le_p, c_utf16le_p)
    def testfun(string):
        global result
        print('parameter: %s' % string.value)
        # callbacks leak memory except for simple return
        # values such as an integer address, so return the
        # address of a global variable.
        result = c_utf16le_p(string.value + u' and eggs')
        return ctypes.c_void_p.from_buffer(result).value

    print('result: %s' % testfun(u'spam'))

rawDescription: How to work with UTF-16 in python ctypes?

description: Work with UTF-16 in python ctypes


code:
{'archiver': ['ar', '-cr'],
 'compiler': ['gcc', '-O', '-Wall'],
 'compiler_cxx': ['g++', '-O', '-Wall'],
 'compiler_so': ['gcc', '-mdll', '-O', '-Wall'],
 'dll_libraries': None,
 'dllwrap_version': None,
 'dry_run': 0,
 'force': 0,
 'gcc_version': LooseVersion ('4.2.1'),
 'include_dirs': [],
 'ld_version': None,
 'libraries': [],
 'library_dirs': [],
 'linker_dll': 'dllwrap',
 'linker_exe': ['gcc'],
 'linker_so': ['dllwrap', '-mdll', '-static'],
 'macros': [],
 'objects': [],
 'output_dir': None,
 'preprocessor': None,
 'ranlib': ['ranlib'],
 'runtime_library_dirs': [],
 'verbose': 0}

rawDescription: Get the commands distutils passes to the compiler


code:
# add data
u1, u2, u3, u4 = _users = [
    users(userName=_un)
    for _un in ('Alex', 'Carlos', 'Sara', 'Jack')
]
u1.friends.append(u2)
u1.friends.append(u3)
u2.friends.append(u4)
u3.friends.append(u1)

u1.best_friend = u2
u2.best_friend = u1
db.session.add_all(_users)
db.session.commit()

rawDescription: Build Model.query of a related model

description: Build Model.query of a related model


code:
# array of outputs, with dimensions (n_outputs, p1, p2, p3, p4, p5)
print(sorted_output.shape)
# (3, 2, 3, 4, 5, 6)

# the first output variable whilst holding the first 4 simulation parameters
# constant at 0:
print(sorted_output[0, 0, 0, 0, 0, :])
# [ 0  3  6  9 12 15]

rawDescription: Reorganizing an MxN 2D array of datapoints into an N-dimensional array


code:
df = df.swaplevel(0,1)
df

rawDescription: MultiIndexing in pandas based on column conditions


code: max_ = items[0][1]

rawDescription: Selecting all top words in Python list using Counter


code: parents = [None, None, None]

rawDescription: Traversing a Graph in Breadth First in Python Using a List of List


code:
ab
e
e

rawDescription: Extract letters from a string using the position


code: df1['label'] = 'df1'

rawDescription: splitting and concatenating dataframes in Python pandas for plotting with rpy2

description: Splitting and concatenating dataframes in Python pandas for plotting with rpy2


code:
def in_group_a(user):
    return user.groups.filter(name="Group A").exists()

def in_group_b(user):
    return user.groups.filter(name="Group B").exists()

@user_passes_test(in_group_a)
def app1_view(request):
    ...

@user_passes_test(in_group_b)
def app2_view(request):
    ...

rawDescription: Django: Can we set permission to use an app?


rawDescription: Algorithm to generate spanning set

description: Algorithm to generate spanning set


code:
d = { 'a': 'x', 'b': 'y', 'c': 'z' }
for i, (key, value) in enumerate(d.iteritems()):
    print (i, key, value)

rawDescription: Multiple assignment semantics

description: Multiple assignment semantics


rawDescription: How to add elements individually in tuple?

description: Add elements individually in tuple


code:
return any(
    (board[each[0]] == board[each[1]] and board[each[1]]== board[each[2]])
    for each in win_comb)

rawDescription: Tic-tac-toe win detection system-Python

description: Tic-tac-toe win detection system-Python


code:
#Import Tkinter
from Tkinter import *
#define master
master = Tk()
#Vertical (y) Scroll Bar
scroll = Scrollbar(master)
scroll.pack(side=RIGHT, fill=Y)
#Text Widget
eula = Text(master, wrap=NONE, yscrollcommand=scroll.set)
eula.insert("1.0", "text")
eula.pack(side="left")
#Configure the scrollbars
scroll.config(command=eula.yview)
mainloop()

rawDescription: Python scrollbar on text widget

description: Python scrollbar on text widget


rawDescription: in NetworkX cannot save a graph as jpg or png file

description: In NetworkX cannot save a graph as jpg or png file


code:
unduped_dict = merge_buffers(dupes)
unduped_list = []
for key in unduped_dict:
    item = {'name1': key[0], 'len1': key[1], 'buffer': '/'.join(unduped_dict[key]) }
    unduped_list.append( item )

rawDescription: python filter out pseudo-duplicates by merging the differing values

description: Python filter out pseudo-duplicates by merging the differing values


code:
(int) == (int)
('str') == ('str')
(FK or PK) == (int)
(FK or PK) == (FK or PK)

rawDescription: Comparing two identical elements in Django doesn't seem to work


code:
def uniformCostSearch(problem):
    # An empty list to store already expanded states
    closed = []
    fringe = PriorityQueue()
    fringe.push((problem.getStartState(), 0, []), 0)

    while not fringe.isEmpty():
        node, cost, directions = fringe.pop()

        if problem.isGoalState(node):
            return directions

        if not (node in closed):
            closed.append(node)

            for node, direction, step_cost in problem.getSuccessors(node):
                fringe.push((node, cost + step_cost, directions + [direction]),
                            cost + step_cost)

    if fringe.isEmpty():
        return []

rawDescription: Why is my A* Search returning the same expanded space as my UniformCostSearch?


code: devices = map(InputDevice, readers.split(','))

rawDescription: Parameters of a function in python

description: Parameters of a function in python


code: invert = OD(map(reversed, attributes.items()))

rawDescription: Reverse AND inverse python3.x OrderedDict efficiently


code:
numberplate = 'AB12 XYZ'
for character in numberplate:
    print(character.isdigit())

rawDescription: (Python 2.7) Data validation using try not working as expected


code:
for key in begin:
    begin[key] = [item for item in begin[key] if item != 'nope']

rawDescription: removing a certain element from a list in a dictionary's value

description: Removing a certain element from a list in a dictionary's value


code:
uniq_inds = order[uniq_mask]
inv_idx = np.zeros_like(order)
inv_idx[order] = np.cumsum(uniq_mask) - 1

rawDescription: Summing and removing repeated elements of Numpy Arrays


code:
_str='The lorry ran  into the mad man  before turning over'
_str.split('  ')

rawDescription: Splitting a string only on multiple white spaces using python


code:
from StringIO import StringIO
buff = StringIO("")

rawDescription: Python equivalent to curls --form: Create multipart form-data post request with data in "form" parameter


code:
class Base(object):
    def f(self):
        pass

    def g(self):
        pass

    FXN = {
        1 : "f",
        2 : "g",
    }

for base in receive_some_bases():
    getattr(base, base.FXN[1])()
    getattr(base, base.FXN[2])()

rawDescription: python: Function pointer breaks polymorphism

description: Python: Function pointer breaks polymorphism


code:
from timeit import timeit
a = ['rzz2', 'rzz3']
b = 'rzz2'
timeit('a[0] if a[0] != b else a[1]', 'from __main__ import a, b')
timeit('a[1 - a.index(b)]', 'from __main__ import a, b')
timeit('{b}.symmetric_difference(a)', 'from __main__ import a, b')
timeit('[i for i in a if i!=b][0]', 'from __main__ import a, b')

rawDescription: Comparing and substitution of opposite

description: Comparing and substitution of opposite


code:
import os
import traceback
from glob import glob
from subprocess import Popen, PIPE
from threading import Timer

os.chdir("/home/mls/dir") #XXX assume mlts is a typo in the question
for filename in glob(b"*.MTS"):
    print("Performing calculations on {filename!r}...".format(**vars()))
    try:
        os.remove("mts_tbl.txt")
    except OSError:
        pass # ignore
    try:
        p = Popen(["run_command.command", "-f", "a"], stdin=PIPE) #XXX no cwd
        t = Timer(3, p.kill)
        t.start()
        p.communicate(input=b"\n".join([b"1", filename,
                b"8\nalloy-liquid\n0\nx\n5\n4\n-1.6\n4\n1\n0"]))
        t.cancel()
    except Exception:
        traceback.print_exc()

rawDescription: Setting a timeout during a loop in Python?


code:
import os
from multiprocessing import Pool

print(os.getpid(), 'parent')

def func(i):
    print(os.getpid(), 'first', end=" | ")
    if 'func' in globals():
        print(globals()['func'], end=" | ")
    else:
        print("no func in globals", end=" | ")
    if 'func2' in globals():
        print(globals()['func2'])
    else:
        print("no func2 in globals")

print('------ map-1')
pool1 = Pool(2)
pool1.map(func, range(2))         #map-1

def func(i):
    print(os.getpid(), 'second', end=" | ")
    if 'func' in globals():
        print(globals()['func'], end=" | ")
    else:
        print("no func in globals", end=" | ")
    if 'func2' in globals():
        print(globals()['func2'])
    else:
        print("no func2 in globals")
func2 = func

print('------ map-2')
pool1.map(func,  range(2))        #map-2
print('------ map-3')
pool1.map(func2,  range(2))       #map-3

pool2 = Pool(2)
print('------ map-4')
pool2.map(func,   range(2))       #map-4
print('------ map-5')
pool2.map(func2,  range(2))       #map-5

rawDescription: Python multiprocessing Pool Interaction With Namespace At Creation


code:
import sys
from PyQt4 import QtCore, QtGui
import numpy as np
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as    NavigationToolbar
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

class Window(QtGui.QMainWindow):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        self.resize(900,600)

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

        layout = QtGui.QHBoxLayout()
        Right = QtGui.QVBoxLayout()
        Left = QtGui.QVBoxLayout()
        spacer = QtGui.QSpacerItem(20,40)
        spacer2 = QtGui.QSpacerItem(10,40)

        font = QtGui.QFont()
        font.setFamily("Rod")
        font.setPointSize(23)
        font2 = QtGui.QFont()
        font2.setFamily("Rod")
        font2.setPointSize(18)
        font3 = QtGui.QFont()
        font3.setFamily("Rod")
        font3.setPointSize(13)

        #Plotting Methods from Matplotlib
        self.figure = plt.figure()
        self.canvas = FigureCanvas(self.figure)
        self.canvas.setMaximumHeight(525)
        self.canvas.setMaximumHeight(725)
        self.toolbar = NavigationToolbar(self.canvas, self)

        #Labels
        self.label = QtGui.QLabel(self)
        self.label.setFont(font)
        self.label.setText("  Welcome to PPMS Data Analyser")
        self.label.setMaximumSize(625,30)

        label2 = QtGui.QLabel(self)
        label2.setFont(font2)
        label2.setText("Select Plot:")

        x_label = QtGui.QLabel(self)
        x_label.setFont(font3)
        x_label.setText("x axis:")

        y_label = QtGui.QLabel(self)
        y_label.setFont(font3)
        y_label.setText("y axis:")

        #Push Buttons
        fileSelect = QtGui.QPushButton('Select File')
        fileSelect.setMaximumSize(70,25)
        fileSelect.clicked.connect(self.plot)
        goPlot = QtGui.QPushButton('Plot')
        goPlot.setMaximumSize(60,20)
        goPlot.clicked.connect(self.plot)

        # x axis radio buttons
        groupBox = QtGui.QGroupBox()
        radio1 = QtGui.QRadioButton("Time")
        radio2 = QtGui.QRadioButton("Delta T")
        radio3 = QtGui.QRadioButton("Delta V")
        radioa = QtGui.QRadioButton("Hot Side Temp")
        radiob = QtGui.QRadioButton("Cold Side Temp")
        radioc = QtGui.QRadioButton("System Temp")
        radio2.setChecked(True)

        # Vertically aligns these buttons
        vbox = QtGui.QVBoxLayout()
        vbox.addWidget(x_label)
        vbox.addWidget(radio1)
        vbox.addWidget(radio2)
        vbox.addWidget(radio3)
        vbox.addWidget(radioa)
        vbox.addWidget(radiob)
        vbox.addWidget(radioc)
        vbox.addStretch(1)
        groupBox.setLayout(vbox)

        # y axis radio buttons
        groupBox2 = QtGui.QGroupBox()
        radio12 = QtGui.QRadioButton("Time")
        radio22 = QtGui.QRadioButton("Delta T")
        radio32 = QtGui.QRadioButton("Delta V")
        radioa2 = QtGui.QRadioButton("Hot Side Temp")
        radiob2 = QtGui.QRadioButton("Cold Side Temp")
        radioc2 = QtGui.QRadioButton("System Temp")
        radio32.setChecked(True)

        # Vertically aligns these buttons
        vbox2 = QtGui.QVBoxLayout()
        vbox2.addWidget(y_label)
        vbox2.addWidget(radio12)
        vbox2.addWidget(radio22)
        vbox2.addWidget(radio32)
        vbox2.addWidget(radioa2)
        vbox2.addWidget(radiob2)
        vbox2.addWidget(radioc2)
        vbox2.addStretch(1)
        groupBox2.setLayout(vbox2)

        #Box for 2 radio boxes
        hbox0 = QtGui.QHBoxLayout()
        hbox0.addWidget(groupBox)
        hbox0.addWidget(groupBox2)
        hbox0.addStretch(0)

        Left.addWidget(self.label)
        Left.addWidget(self.canvas)
        Left.addWidget(self.toolbar)
        Right.addItem(spacer)
        Right.addWidget(fileSelect)
        Right.addItem(spacer)
        Right.addWidget(label2)
        Right.addLayout(hbox0)
        Right.addWidget(goPlot)
        #Right.addLayout(hbox0)

        layout.addLayout(Left)
        layout.addLayout(Right)

        self.central_widget.setLayout(layout)

    def plot(self):
        ax = self.figure.add_subplot(111)
        ax.hold(False)
        ax.plot([1,2],[3,4])
        plt.grid()
        plt.title('Test Plot')
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.setWindowTitle('PPMS Seebeck Calculator')
    main.show()

    sys.exit(app.exec_())

rawDescription: Change my Qdialog to QMainWindow

description: Change my Qdialog to QMainWindow


code:
def create_query(**kwargs):
    query_string = """
         'WhoId':'{who_id}',
         'Subject':'{subject}',
         'Description':'{description}',
         ...
         """.format(**kwargs)
    print(query_string)

rawDescription: Auto format arguments to string

description: Auto format arguments to string


rawDescription: Numpy.select from 3D array

description: Numpy.select from 3D array


rawDescription: How to do simultaneous combinations in python? (itertools)

description: Do simultaneous combinations in python? (itertools)


code:
def t_area(x, y, surface, dx):
    # I assume numx == x.shape[0]. If not, pass it as an extra argument.
    tri_area = np.zeros(x.shape, dtype=float)

    ap = np.zeros((3,), dtype=float)
    bp = np.zeros_like(ap)
    cp = np.zeros_like(ap)
    dp = np.zeros_like(ap)

    for ii in range(x.shape[0]-1): # do you really want range(numx-1) or just range(numx)?
        for jj in range(x.shape[1]-1):
            xp = x[ii,jj]
            yp = y[ii,jj]
            zp = surface[ii,jj]
            ap[:] = (xp, yp, zp)

            # get `bp`, `cp` and `dp` in a similar manner and compute `tri_area[ii,jj]`

rawDescription: More efficient way to loop?

description: More efficient way to loop


code: df = pd.read_csv('file_name.csv', ..., dtype={'column5': object})

rawDescription: Create new column in panda data frame

description: Create new column in panda data frame


code: dic2 = {key: [{k: v} for sublist in value for k, v in sublist] for key, value in dic1.items()}

rawDescription: Converting a nested tuples into nested dictionaries


code: result

rawDescription: create a list of dictionaries with randomised elements from two lists - python

description: Create a list of dictionaries with randomised elements from two lists - python


rawDescription: How To Hide Tkinter python Gui

description: How To Hide Tkinter python Gui


code:
number = 444
full_links = ["www.google.es", "wwww.stackoverflow.com"]

for i in xrange(len(full_links)):
    full_links[i] = full_links[i][:3] + str(number) + full_links[i][3:]

rawDescription: Insert a character into a url

description: Insert a character into a url


code:
@gen.coroutine
def post(self):
    ...
    yield self._send_parking_spots_request(data)  # wait (without blocking the event loop) until the method is done
    self.finish()

@gen.coroutine
def _send_parking_spots_request(self, data):

    msg = Message()
    msg.set_body(json.dumps(data))
    yield gen.Task(write_msg, self._sqs_send_queue, msg)

def write_msg(queue, msg, callback=None):
    yield queue.write(msg, callback=callback)  # This has to do non-blocking I/O.

rawDescription: Correct use of coroutine in Tornado web server


rawDescription: python: list comp fill data conditionally

description: Python: list comp fill data conditionally


code:
# Test the Collatz conjecture:
# http://en.wikipedia.org/wiki/Collatz_conjecture
import profile

# Python 2/3 compatibility shim
import sys
if sys.hexversion >= 0x3000000:
    # Python 3.x
    inp = input
    rng = range
else:
    # Python 2.x
    inp = raw_input
    rng = xrange

# cache of already-seen values
seen = set([1])

def test(n):
    visited = set()
    while True:
        if n in seen:             # Ran into an already-seen chain that goes to 1
            seen.update(visited)
            return len(visited)
        elif n in visited:        # Closed loop! this should never happen
            print('Loop found at n = {}'.format(n))
            return None
        else:
            visited.add(n)

        if n % 2:         # n is odd?
            n = 3*n + 1
        else:
            n //= 2

def do_profile(upto=1000000):
    prof = profile.Profile()
    prof.run('for n in rng(2, {}): test(n)'.format(upto))
    prof.print_stats()

def main():
    while True:
        try:
            n = int(inp('Enter a number to test (or x to exit): '))
        except ValueError:
            break

        res = test(n)
        if res is None:
            print("Well, that's odd...")
        else:
            print("Chain terminated after {} values were tested".format(res))

if __name__=="__main__":
    main()

rawDescription: Python is not recognizing my variables, but instead replacing them with zero


code:
df = pd.DataFrame({'origin': list('aabbccdd'), 'destination': ['d1', 'd2'] * 4, 'distance': np.arange(8)})
df
df.pivot('origin', 'destination', 'distance')

rawDescription: Having trouble with lists and matrix using xlrd and python


code:
import wx
from matplotlib import pyplot as plt
from io import BytesIO
thisApp = wx.App(redirect=False)

def saveSnapshot(dcSource):
    size = dcSource.Size
    bmp = wx.EmptyBitmap(size.width, size.height)
    memDC = wx.MemoryDC()
    memDC.SelectObject(bmp)
    memDC.Blit( 0, 0, size.width, size.height, dcSource, 0, 0)
    memDC.SelectObject(wx.NullBitmap)
    img = bmp.ConvertToImage()
    bio = BytesIO()
    bs = wx.OutputStream(bio)
    img.SaveStream(bs, wx.BITMAP_TYPE_PNG)
    bio.seek(0) #rewind stream
    plt.imshow(plt.imread(bio))
    plt.show()

saveSnapshot(wx.ScreenDC())

rawDescription: how to directly convert wxpython image to pyplot image without saving

description: Directly convert wxpython image to pyplot image without saving


code:
import sys, json, ast
data = ast.literal_eval(sys.stdin.read())
print(json.dumps(data))

rawDescription: Parsing Python list with PHP

description: Parsing Python list with PHP


code:
# noinspection PyUnusedLocal
unused_thing = something()

rawDescription: Explicitly declaring variable as unused in Python/PyCharm


code:
import sys
sys.path.add("ur file path")
import foo

rawDescription: How to run a module developed in Eclipse in a Python interactive prompt?

description: Run a module developed in Eclipse in a Python interactive prompt


code:
self.label = tk.Label(frameLabel, ...)

# ...

new = self.queue.get()
self.label.config(text=new)

rawDescription: converting code from Tkinter TEXT to Tkinter LABEL

description: Converting code from Tkinter TEXT to Tkinter LABEL


rawDescription: Python string text to set of points

description: Python string text to set of points


code:
import string
pool = string.ascii_letters + string.digits + '!@#$%&*()_'

rawDescription: Password Validating Program

description: Password Validating Program


code:
import os
from contextlib import contextmanager

@contextmanager
def suppress_output(fd):
    """
    Suppress output to the given ``fd``::

       with suppress_fd(sys.stderr):
           # in this block any output to standard error is suppressed

    ``fd`` is an integral file descriptor, or any object with a ``fileno()``
    method.
    """
    if hasattr(fd, 'fileno'):
        # we were given a file-like object with an underlying fd
        if hasattr(fd, 'flush'):
            # flush Python-side buffers before redirecting
            fd.flush()
        # get the fd to redirect
        fd = fd.fileno()

    # duplicate the file descriptor to restore it eventually
    oldfd = os.dup(fd)
    try:
        # open the trash can
        devnull = os.open(os.devnull, os.O_WRONLY)
        try:
            # point the file descriptor to the trash can
            os.dup2(devnull, fd)
        finally:
            # close the old trash can descriptor, we don't need it anymore
            # since the fd now points to the trash can
            os.close(devnull)
        # enter the callers block
        yield
        # restore the file descriptor
        os.dup2(oldfd, fd)
    finally:
        # close the duplicated copy of the original fd, we don't need it
        # anymore now that fd is restored
        os.close(oldfd)

rawDescription: GTK errors when importing pynotify

description: GTK errors when importing pynotify


rawDescription: Convert string of 0s and 1s to byte in Python


rawDescription: Regular expression matching [^a-z] or $

description: Regular expression matching [^a-z] or $


code:
def test_root_route(self):
    resp = self.client.get('/', headers={'Cookie': 'accountId=test'})
    self.assert_template_used('index.html')

rawDescription: Flask-Testing: issues with session management with unittests


code:
@models.signals.m2m_changed(sender=MyModel.second_m2m.through)
def duplicate_other_on_this_if_empty(sender, instance, action, reverse, model, pk_set, **kwargs):
    # just before adding a possibly empty set in "second_m2m", check and populate.
    if action == 'pre_add' and not pk_set:
        pk_set.update(instance.first_m2m.values_list('pk', flat=True))

rawDescription: Django many-to-many field copy

description: Django many-to-many field copy


code:
def handle(self):
    close = 0
    while not close:
        _data = self.request.recv(1024)
        if not _data:
            # EOF, client closed, just return
            return
        Utils.log("Received from %s: %s" % (self.client_address, _data))
        self.request.send('got %d bytes\r\n' % len(_data))
        if 'quit' in _data:
            close = 1

rawDescription: TCP server is closing connections

description: TCP server is closing connections


rawDescription: Grouping values in pandas into on index

description: Grouping values in pandas into on index


code: for ip, (mac, t) in database['PC1'][3].items(): print(mac, ip)

rawDescription: How to access particular element of tuples which are inside a nested dictionary Python

description: Access particular element of tuples which are inside a nested dictionary Python


code: a = UserInput("foo", "whatever", "is", "needed", "here")

rawDescription: Applying the @staticmethod, python3

description: Applying the @staticmethod, python3


code: sublist = [ob for ob in larger_list if all(getattr(ob, attr) == 'some test string' for attr in list_of_attributes)]

rawDescription: Check for multiple attribute matches in an array of objects


rawDescription: python sort with adjacent difference

description: Python sort with adjacent difference


code:
class NullHandler(logging.Handler):
    def emit(self, record):
        pass

rawDescription: Only print when run as script?

description: Only print when run as script


code:
mask = df['Phrase'].str.match(r'\A[\w-]+\Z')
df[mask]

rawDescription: Keep only sentences with a single word in Pandas DatFrame


code: url[:8] + access_token() + '@' + url[8:]

rawDescription: Cleaner way to use re.sub

description: Cleaner way to use re.sub


rawDescription: Python PEP3101: Why the field_spec is not passed to the __format__ function?


code: stream = [x.replace('\t','') for x in stream]

rawDescription: Delete tab character from config files

description: Delete tab character from config files


code:
from celery import shared_task
from celery.exceptions import Ignore
from celery.utils.log import get_task_logger
from .models import task_canceled
logger = get_task_logger(__name__)

@shared_task
def my_task():
    if task_canceled(my_task.request.id):
        raise Ignore
    logger.info("Doing my stuff")

rawDescription: Celery revoke task before execute using django database


code:
def sentence():
    return ' '.join([rnd(nouns).capitalize(), rnd(adverbs), rnd(verbs)+'.'])

rawDescription: Trying to output to file as well as printing to screen inside a for loop


rawDescription: python lxml inkscape namespace tags

description: Python lxml inkscape namespace tags


code:
import csv
from collections import OrderedDict
d = OrderedDict()
d["p1"] = [.1,.2,.3,.4]
d["p2"] = [.4,.3,.2,.1]
d["p3"] = [.5,.6,.7,.8]

with open("out.csv","w") as f:
    wr = csv.writer(f)
    wr.writerow(list(d))
    wr.writerows(zip(*d.values()))

rawDescription: Dump a Python dictionary with array value inside to CSV


code:
import random
random.seed()
sources = ['Prone', 'Supine', 'Halfway', 'HalfInv']
copy1 = sources * 4
copy2 = sources * 4
copy1 == copy2
random.shuffle(copy1)
random.shuffle(copy2)
copy1 == copy2
copy1
copy2

rawDescription: how do I export my lists into an excel compatible file?

description: Export my lists into an excel compatible file


code:
indices_to_delete = set(indices_to_delete)
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]

rawDescription: deleting multiple elements without updating till the end

description: Deleting multiple elements without updating till the end


code: [[indices[i] for i in sub] for sub in List2]

rawDescription: Replacing elements in a list with the indices of a list containing all unique elements


rawDescription: garbage printing value of a key-value pair in python

description: Garbage printing value of a key-value pair in python


code:
import logging

logger = logging.getLogger('foo')

def stream_reader(stream):
    while True:
        line = stream.readline()
        logger.debug('%s', line.strip())

rawDescription: subprocess stdout/stderr to finite size logfile

description: Subprocess stdout/stderr to finite size logfile


code:
a = np.random.random((5, 5))
a *= np.tri(*a.shape, k=2)
a

rawDescription: How to fill upper triangle of numpy array with zeros in place?

description: Fill upper triangle of numpy array with zeros in place


rawDescription: Python - alternating lists

description: Python - alternating lists


code:
from pyspark.sql.functions import max

((_, c), ) = (maxs
    .groupBy(col("maxs")["col"].alias("col"))
    .count()
    .agg(max(struct(col("count"), col("col"))))
    .first())

df.select(c)

rawDescription: Comparing columns in Pyspark

description: Comparing columns in Pyspark


code:
import logging
class MyClass():
    def __init__(self):
        logging.debug("Debug message")
        logging.info("Info message")

rawDescription: Python logging in multiple modules

description: Python logging in multiple modules


code:
def load():
    try:
        f = shelve.open("save.bin")
        return f['player'], f['blocks']
    except KeyError:
        return None
    finally:
        f.close()

rawDescription: Save a list of objects on exit of pygame game


code:
# Generic class definition
class Generic (object):
    value = None
    @classmethod
    def val(cls):
        return int(cls.value)

# Top level class
TopLevelClass = type('TopLevelClass',
                     (Generic, ), {})

lines = ["A B C 42",
         "A B D 43"]

for line in lines:
    # Parse the line
    path = line.split()[:-1]
    value = line.split()[-1]
    # Create the classes
    current = TopLevelClass
    for x in path:
        if hasattr(current,x):
            current = getattr(current,x)
        else:
            cls = type(x, (Generic, ), {})
            setattr(current,x,cls)
            current = cls
    # Apply value
    setattr(cls,'value',value)

# Test
print(TopLevelClass.A.B.C.val())
print(TopLevelClass.A.B.D.val())

rawDescription: Dynamically create inheriting object with name from external source


code:
something = {'a': Foo.bam, 'b': { 'c': Foo.bar}}
something
json.dumps(something)

rawDescription: Django API passing class/field names, not values associated with them


code:
pairs = [('', 'noreply@bookfresh.com'), ('Andrea', 'andrea@aaa.com'), ('Your Book', 'noreply@bookfresh.com')]

data = {}
for name, email in pairs:
    if email not in data:
        data[email] = []
    data[email].append(name)

output = [(email, max(data[email], key=len)) for email in data]

rawDescription: Python3 Uniquify list of tuples based on only one of the values of the index


rawDescription: Python: Dictionary with 3 items

description: Python: Dictionary with 3 items


rawDescription: Argparse optional positional arguments?

description: Argparse optional positional arguments


code:
N=2

sum([pair[0] for pair in list_of_pairs[0:N+1]])

rawDescription: Summing the first value in each tuple in a list over a specific range in Python


code:
num.acquire() # get the lock
# do stuff
num.release() # don't forget to release it

rawDescription: Share a class variable across multiple processes in python


rawDescription: python regex to split by comma or space (but leave strings as it is)

description: Python regex to split by comma or space (but leave strings as it is)


rawDescription: Automatic (whisker-sensitive) ylim in boxplots


code: re.sub('Aw, man...', 'Match found.', 'Aw, manatee.')

rawDescription: How can I replace substrings without replacing all at the same time? Python

description: Replace substrings without replacing all at the same time? Python


code:
import couchdb.design
import inflection

DESIGN_NAME="version"

class CurrentVersion(couchdb.design.ViewDefinition):
    def __init__(self):

        map_fun = self.__class__.map

        if hasattr(self.__class__, "reduce"):
            reduce_fun = self.__class__.reduce
        else:
            reduce_fun = None

        super_args = (DESIGN_NAME,
                      inflection.underscore(self.__class__.__name__),
                      map_fun,
                      reduce_fun,
                      'python')

        super(CurrentVersion, self).__init__(*super_args)

    @staticmethod
    def map(doc):
        if 'version_key' in doc and 'created_ts' in doc:
            yield (doc['version_key'], [doc['_id'], doc['created_ts']])

    @staticmethod
    def reduce(keys, values, rereduce):
        max_index = 0

        for index, value in enumerate(values):
            if value[1] > values[max_index][1]:
                max_index = index

        return values[max_index]

rawDescription: Recommended approach for loading CouchDB design documents in Python?


rawDescription: Selecting the first index after a certain timestamp with a pandas TimeSeries


code:
import os

matches = []
for dirpath, dirnames, filenames in os.walk(os.path.expanduser('~/x/y')):
    matches.extend(os.path.join(dirpath, x) for x in dirnames + filenames)

rawDescription: equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure?

description: Equivalent to the find coreutil command in python 3 for recursively returning all files and folders in a directory structure


code: [i[2] for i in aa]

rawDescription: new list from specific index of multidimension list?

description: New list from specific index of multidimension list


rawDescription: How to Merge and Format Lists

description: Merge and Format Lists


code:
# Method of the Element(Node) class.
def writexml(self, writer, indent="", addindent="", newl=""):
    # [snip]
    if self.childNodes:
        writer.write(">%s"%(newl))
        for node in self.childNodes:
            node.writexml(writer,indent+addindent,addindent,newl)
        writer.write("%s</%s>%s" % (indent,self.tagName,newl))
    else:
        writer.write("/>%s"%(newl))

rawDescription: Empty XML element handling in Python

description: Empty XML element handling in Python


code:
step = +1 if x < y else -1 # or use that 'or' expression
range(x, y + step, step)

rawDescription: python for loop increasing or decreasing

description: Python for loop increasing or decreasing


rawDescription: Changing the value of a variable stored in a dictionary


code:
style = '<style>.right_aligned_df td { text-align: right; }</style>'
HTML(style + df.to_html(formatters=frmt, classes='right_aligned_df'))

rawDescription: How to format IPython html display of Pandas dataframe?

description: Format IPython html display of Pandas dataframe


code:
def count():
    c = 0
    with open("xxx.txt","r") as file:
        for line in file:
            for ch in line:
                if 'a' <= ch <= 'z' or 'A' <= ch <= 'Z':
                    c += 1
    return c

rawDescription: acount total number of letter ONLY alphabet

description: Acount total number of letter ONLY alphabet


code:
import sleekxmpp
import logging

logging.basicConfig(level=logging.DEBUG)

class SendMsgBot(sleekxmpp.ClientXMPP):
    def init(self, jid, recipient, message):
        sleekxmpp.ClientXMPP.__init__(self, jid, 'ignore')
        # The message we wish to send, and the JID that
        # will receive it.
        self.recipient = recipient
        self.msg = message
        # The session_start event will be triggered when
        # the bot establishes its connection with the server
        # and the XML streams are ready for use. We want to
        # listen for this event so that we we can initialize
        # our roster.
        self.add_event_handler("session_start", self.start, threaded=True)
    def start(self, event):
        self.send_presence()
        self.get_roster()
        self.send_message(mto=self.recipient, mbody=self.msg, mtype='chat')
        # Using wait=True ensures that the send queue will be
        #emptied before ending the session.
        self.disconnect(wait=True)

rawDescription: Send a Facebook Message with XMPP using Access Tokens in Python


code:
randomdir = random.choice([d for d in os.listdir(os.curdir)
                           if (not d.startswith(".")) and os.path.isdir(d)])

rawDescription: How to execute bash from within a python file?

description: Execute bash from within a python file


code:
my_list = [12,8,0,4,7,21,27,"O",29,3,"X","O","X","X"]
set(map(type, my_list))
set(map(type, my_list)) == {int, str}
set(map(type, my_list)) == {int}
set(map(type, my_list)) == {str}
my_list = [12,8,0,4,7,21,27]
set(map(type, my_list))
my_list = ["X", "O", "X", "X"]
set(map(type, my_list))
set(map(type, my_list)) == {str}

rawDescription: Does the list have any numbers?

description: Does the list have any numbers


code: p.reshape(4, 2, order='F')

rawDescription: numpy create 3D array from indexed list

description: Numpy create 3D array from indexed list


code: directions[direction.replace(" ","")]

rawDescription: global varriable doesn't change

description: Global varriable doesn't change


code:
def get_out_of_maya():
    try:
       import maya.commands as cmds
       cmds.file(new=True, force=True)
    except:
       pass
    os._exit(0)   # note underscore

import atexit
atexit.register(get_out_of_maya)

rawDescription: How to run pycharm unittests when standard lib is zipped?

description: Run pycharm unittests when standard lib is zipped


code:
def get_counts(sequence):
    counts = {}
    for x in sequence:
        if x in counts:
            counts[x] += 1
    else: #XXX wrong indentation
        counts[x] = 1 # it is run after the loop if there is no `break`
    return counts

rawDescription: Example from "Python for Data Analysis", Chapter 2


rawDescription: Read in an indexed color image in Python


code:
results = db.collection.inline_map_reduce(
    map,
    reduce,
    query={ "timestamp": { "$gte": startDate, "$lte": endDate } },
    finalize=finalize
)

rawDescription: Python sum values by daterange

description: Python sum values by daterange


code:
def dynamic_update(self):
    d = self._idle
    self._idle = False
    if d:
        #self.canvas.draw() #<--- Comment out to stop the redrawing during the Pan/Zoom
        self._idle = True

rawDescription: overriding matplotlib's panning tool (wx)

description: Overriding matplotlib's panning tool (wx)


code:
se = sqrt(se / 24)
z = (T - mn) / se
prob = 2. * distributions.norm.sf(abs(z))
return T, prob

rawDescription: One-sided Wilcoxon signed-rank test using scipy


code:
class T2(DeclarativeBase):
    __tablename__ = 't2'

    __table_args__ = {'mysql_engine': 'InnoDB'}

    id = Column(u'id', Integer, primary_key=True)
    name = Column('name', String(45))
    data = Column('data', String(45))

    def __init__ (self, name, data):
        self.name = name
        self.data = data

rawDescription: SQLAlchemy: filtering multiple column values in a subquery


code: ofs = l2 = np.random.choice(sample[:-1], size=n)+1

rawDescription: Numpy: Generate 2 sequences of n random numbers with no overlaps


code:
{'street': ' 1st street', 'name': 'jack', 'area': ' New York'}
{'street': ' 2nd street', 'name': 'sally', 'area': ' New York'}

rawDescription: Python adding headers to CSV

description: Python adding headers to CSV


code:
text.xview(Tkinter.MOVETO, x_pos)
text.yview(Tkinter.MOVETO, y_pos)

rawDescription: text widget returning cursor

description: Text widget returning cursor


rawDescription: Kivy - editing label when button clicked


code:
c.executemany("insert into T (F1,F2) values (%s, %s)",
    [('a','b'),('c','d')])

rawDescription: How to use python mysqldb to insert many values at once

description: Use python mysqldb to insert many values at once


code:
locate('mypackage.model.base.BaseModel')
m = locate('mypackage.model.base.BaseModel')
m()

rawDescription: Lexical cast from string to type

description: Lexical cast from string to type


rawDescription: Beginner Python : How to save output in the same location and with a different name?


code:
import csv
from itertools import groupby

with open('my_data.csv') as ifile, open('my_out_data.csv', 'wb') as ofile:
    # Use the csv module to handle reading and writing of delimited files.
    reader = csv.reader(ifile)
    writer = csv.writer(ofile, delimiter='\t')
    # Skip info line
    next(reader)
    # Group datasets by the condition if len(row) > 0 or not, then filter
    # out all empty lines
    for group in (v for k, v in groupby(reader, lambda x: bool(len(x))) if k):
        test_data = list(group)
        # Write header
        writer.writerow([test_data[0][1]])
        # Write transposed data
        writer.writerows(zip(*test_data[1:]))
        # Write blank line
        writer.writerow([])

rawDescription: CSV parsing in Python

description: CSV parsing in Python


rawDescription: How to do a general "search bar" search across multiple SQLAlchemy models

description: Do a general "search bar" search across multiple SQLAlchemy models


code: counts = collections.Counter(words)

rawDescription: Python Duplicate words

description: Python Duplicate words


code: contains_all = two.keys() <= one.keys()

rawDescription: Python dictionnary items() method cost inside iterable


code:
from flask import Flask
from flask_restful import Api

app = Flask(__name__)
api = Api(app)

from myapi.resources.foo import Foo
from myapi.resources.bar import Bar
from myapi.resources.baz import Baz

api.add_resource(Foo, '/Foo', '/Foo/<str:id>')
api.add_resource(Bar, '/Bar', '/Bar/<str:id>')
api.add_resource(Baz, '/Baz', '/Baz/<str:id>')

rawDescription: How to access api.url_for in big Flask-Restful API

description: Access api.url_for in big Flask-Restful API


code:
guess = 't'
indices = [i for i, x in enumerate(word) if x == guess]
indices

rawDescription: Replace list object based on indexes of another list (Python)


rawDescription: Single Byte Multiplication in Python?

description: Single Byte Multiplication in Python


code:
while True:
    ...
    if cond:
        break

rawDescription: Repeat-Until loop in python or equivalent


code: drawCustom[bubble](p, 100, 100, "Hello world.")

rawDescription: Python: how to call a method coming from an array?


code: codigo_moneda = db.StringField(max_length=3, choices=codes.keys(), required = True)

rawDescription: how to return choices value in mongoengine stringfield

description: Return choices value in mongoengine stringfield


code:
from django.db import connections
from django.db.models import Case, IntegerField, Sum, When

conn = connections[Questionnaire.objects.db]

Questionnaire.objects.extra(
    select={
        'year': conn.ops.date_trunc_sql('year', 'register'),
        'month': conn.ops.date_trunc_sql('month', 'register'),
    }).values(
        'year', 'month'
    ).annotate(
        yes_count=Sum(
            Case(When(satisfaction=True, then=1),
                 output_field=IntegerField()),
        ),
        no_count=Sum(
            Case(When(satisfaction=False, then=1),
                 output_field=IntegerField()),
        )
    )

rawDescription: Count choices in django

description: Count choices in django


code:
import ctypes
d = ctypes.cdll.LoadLibrary('dll/path')
obj = d.createNativeObj()
d.callFunc(obj)

rawDescription: accessing ctypes returned object's methods

description: Accessing ctypes returned object's methods


code:
for runtimes in d.itervalues():
    runtimes.sort()

rawDescription: Generate set of API timings from CSV

description: Generate set of API timings from CSV


code:
from collections import defaultdict
d=defaultdict(list)
new=[i[:-1] for i in a]
d=defaultdict(list)
for i,j in enumerate(new):
   d[j].append(i)

d
d.items()

rawDescription: Python optimize how to find duplicate value and value index in a list


code:
dt = [] # list
dt = {} # or dictionary

rawDescription: How do I create a table in Python? [rewritten, was a bit unclear]

description: Create a table in Python? [rewritten, was a bit unclear]


code:
import requests
resp = requests.get(url)
resp.json()

rawDescription: Geocoding Strategies - Python 2.x to Python 3.x


code: total += abs(med - i)

rawDescription: Python: Unsorted/Sorted Lists Return Different Values?


code:
import sys, os

def gcd(a,b):
   k = 0
   if b > a:
      a, b = b, a
   while b > 0:
      a, b = b, a%b
      k += 1
   return k

def printgcd(name, a, b):
   f = open(name, "wt")
   s = ""
   for i in range(a, b + 1):
      s = "{}\t{}".format(s, i)
   f.write("{}\n".format(s))
   for i in range(a, b + 1):
      s = "{}".format(i)
      for j in range (a, b + 1):
         s = "{}\t{}".format(s, gcd(i, j))
      f.write("{}\n".format(s))
   f.close()

printgcd("gcd-1-6.txt", 1, 6)

rawDescription: Print (or output to file) table of number of steps for Euclid's algorithm


code:
class CombinedAPIView(APIView):
    def get(self, request):
        locations = Location.objects.all()
        countries = Country.objects.all()

        location_serializer = LocationSerializer(locations, many=True)
        country_serializer = CountrySerializer(countries, many=True)

        return Response({
            'countries': country_serializer.data,
            'locations': location_serializer.data
        })

rawDescription: How to get a response of multiple objects using rest_framework and Django

description: Get a response of multiple objects using rest_framework and Django


rawDescription: Create a list for values between certain occurences within a sequence . . . Python


code:
import itertools
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from matplotlib.collections import PatchCollection
import numpy as np

def main():
    azi = np.random.normal(20, 30, 100)
    z = np.cos(np.radians(azi + 45))

    plt.figure(figsize=(5,6))
    plt.subplot(111, projection='polar')
    coll = rose(azi, z=z, bidirectional=True)
    plt.xticks(np.radians(range(0, 360, 45)),
               ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'])
    plt.colorbar(coll, orientation='horizontal')
    plt.xlabel('A rose diagram colored by a second variable')
    plt.rgrids(range(5, 20, 5), angle=290)

    plt.show()

def rose(azimuths, z=None, ax=None, bins=30, bidirectional=False,
         color_by=np.mean, **kwargs):
    """Create a "rose" diagram (a.k.a. circular histogram).

    Parameters:
    -----------
        azimuths: sequence of numbers
            The observed azimuths in degrees.
        z: sequence of numbers (optional)
            A second, co-located variable to color the plotted rectangles by.
        ax: a matplotlib Axes (optional)
            The axes to plot on. Defaults to the current axes.
        bins: int or sequence of numbers (optional)
            The number of bins or a sequence of bin edges to use.
        bidirectional: boolean (optional)
            Whether or not to treat the observed azimuths as bi-directional
            measurements (i.e. if True, 0 and 180 are identical).
        color_by: function or string (optional)
            A function to reduce the binned z values with. Alternately, if the
            string "count" is passed in, the displayed bars will be colored by
            their y-value (the number of azimuths measurements in that bin).
        Additional keyword arguments are passed on to PatchCollection.

    Returns:
    --------
        A matplotlib PatchCollection
    """
    azimuths = np.asanyarray(azimuths)
    if color_by == 'count':
        z = np.ones_like(azimuths)
        color_by = np.sum
    if ax is None:
        ax = plt.gca()
    ax.set_theta_direction(-1)
    ax.set_theta_offset(np.radians(90))
    if bidirectional:
        other = azimuths + 180
        azimuths = np.concatenate([azimuths, other])
        if z is not None:
            z = np.concatenate([z, z])
    # Convert to 0-360, in case negative or >360 azimuths are passed in.
    azimuths[azimuths > 360] -= 360
    azimuths[azimuths < 0] += 360
    counts, edges = np.histogram(azimuths, range=[0, 360], bins=bins)
    if z is not None:
        idx = np.digitize(azimuths, edges)
        z = np.array([color_by(z[idx == i]) for i in range(1, idx.max() + 1)])
        z = np.ma.masked_invalid(z)
    edges = np.radians(edges)
    coll = colored_bar(edges[:-1], counts, z=z, width=np.diff(edges),
                       ax=ax, **kwargs)
    return coll

def colored_bar(left, height, z=None, width=0.8, bottom=0, ax=None, **kwargs):
    """A bar plot colored by a scalar sequence."""
    if ax is None:
        ax = plt.gca()
    width = itertools.cycle(np.atleast_1d(width))
    bottom = itertools.cycle(np.atleast_1d(bottom))
    rects = []
    for x, y, h, w in zip(left, bottom, height, width):
        rects.append(Rectangle((x,y), w, h))
    coll = PatchCollection(rects, array=z, **kwargs)
    ax.add_collection(coll)
    ax.autoscale()
    return coll

if __name__ == '__main__':
    main()

rawDescription: How would one add a colorbar to this example?


rawDescription: universal method for working with currency with no rounding, two decimal places, and thousands separators

description: Universal method for working with currency with no rounding, two decimal places, and thousands separators


code:
b_obj = A().build_b()
b_obj.foo, b_obj.bar

rawDescription: Is it possible to access parent class's members from a nested class in an aggregation


code:
starter = datetime.datetime(2015, 10, 21, 23, 29, tzinfo=pytz.utc)
print(to_timezone(starter, "America/Los_Angeles"))
# -> 2015-10-21 16:29:00-07:00

rawDescription: Creating a function with PYTZ's timezones


code: df.sum() - df

rawDescription: In Pandas, is there a way to divide a cell by all other cells in a column?


rawDescription: Preprocessing form data before using it

description: Preprocessing form data before using it


code:
assert np.allclose(psimaps_simp, psimaps_OP), "simplification failed"
assert np.allclose(psimaps_simp, psimaps_vec), "vectorization failed"

rawDescription: How to eliminate for-loop and use list comprehension when using numpy array?

description: Eliminate for-loop and use list comprehension when using numpy array


code:
fh = open( "heli.txt" );

heliList = []
for line in fh.readlines():
    y = [int(value) for value in line.split()] #added "int( )"
    heliList.append( y )

fh.close()

rawDescription: Adding parameters from a file into a list and then using the list


code:
from django.http import Http404

class UserProfileView(View):
    @method_decorator(login_required)
    def get(self, request, user):
        if request.user.username == user:
            profile = get_object_or_404(UserProfile, user=request.user)
            return render(request, 'accounts/profile.html', {'profile': profile})
        else:
            raise Http404

rawDescription: Username in URL for Django User Profile

description: Username in URL for Django User Profile


rawDescription: Python: take the content of a list and append it to another list


rawDescription: find element in list 1 that is in list 2

description: Find element in list 1 that is in list 2


rawDescription: How to sort a python list?

description: Sort a python list


code:
import urlparse
formdata = urlparse.parse_qs('ugq_no=2')
formdata
formdata['ugq_no']
formdata['ugq_no'][0]

rawDescription: How to get request.environ values in python?

description: Get request.environ values in python


code:
df = df.set_index('s.no')
pd.get_dummies(df.unstack()).sum(level=1)

rawDescription: Convert categorical data (in multiple columns) to binary data


rawDescription: how to write a script to edit a JSON file?

description: Write a script to edit a JSON file


code:
from lxml import etree

class SkipStartEndTarget:
    def __init__(self, *args, **kwargs):
        self.builder = etree.TreeBuilder()
        self.skip = False

    def start(self, tag, attrib, nsmap=None):
        if tag == 'start':
            self.skip = True
        if not self.skip:
            self.builder.start(tag, attrib, nsmap)

    def data(self, data):
        if not self.skip:
            self.builder.data(data)

    def comment(self, comment):
        if not self.skip:
            self.builder.comment(self)

    def pi(self, target, data):
        if not self.skip:
            self.builder.pi(target, data)

    def end(self, tag):
        if not self.skip:
            self.builder.end(tag)
        if tag == 'end':
            self.skip = False

    def close(self):
        self.skip = False
        return self.builder.close()

rawDescription: remove everything between 2 tags that span branches of an xml tree

description: Remove everything between 2 tags that span branches of an xml tree


code:
for article_image in ArticleImage.objects.all():
    article_image.set_article_background_color()

rawDescription: Django detect dominant color of an image


code:
def comboprint(self, widget, *data):
    # Widget = btn_new
    # data = [clicked_event, combobox1, combobox2]
    ...

rawDescription: How do I add additional arguments to button.connect in PyGTK?

description: Add additional arguments to button.connect in PyGTK


code:
class Camera(object):
    def __init__(self, camera_func, width, height):
        self.camera_func = camera_func
        self.state = Rect(0, 0, width, height)

    def apply(self, target):
        return target.rect.move(self.state.topleft)

    def update(self, target):
        self.state = self.camera_func(self.state, target.rect)

rawDescription: Add scrolling to a platformer in pygame

description: Add scrolling to a platformer in pygame


code:
siren = base64.b64decode('''
    <base64-encoded data>
    ''')
winsound.PlaySound(siren, winsound.SND_MEMORY)

rawDescription: How can I make a siren noise in Python?

description: Make a siren noise in Python


code:
row = i, degree[i], between[i], close[i], eigen[i]
centrality.append(row)

rawDescription: csv.writer and every value seperated by a comma, column seperated by "," - what am I missing?

description: Csv.writer and every value seperated by a comma, column seperated by "," - what am I missing


code:
def iteration(letters, numbers):
     # create iterator from numbers
    it = iter(numbers)
    # get every letter
    for x in letters:
        # either print in range passed or default range of 1
        for z in range(next(it, 1)):
            yield x

rawDescription: Continue until all iterators are done Python


code: Product.objects.all().filter_all_many_to_many('colors', red, blue) # red and blue being color instances

rawDescription: Django filter filter with lists

description: Django filter filter with lists


code:
mask = df['business'].apply(pd.Series).isin(restaurant_categories_list).sum(axis=1) > 0
print(df[(mask)])

rawDescription: Filter DataFrame rows that are lists

description: Filter DataFrame rows that are lists


code:
red:    6
green:  1
blue:   8

rawDescription: Numpy drawing from urn

description: Numpy drawing from urn


rawDescription: Strange Python memory usage with Scapy

description: Strange Python memory usage with Scapy


code:
# ...if hardcoding the script to source in your Python code
subprocess.Popen('source ./test.sh', shell=True)

# ...otherwise:
subprocess.Popen(['source "$@"', './test.sh'], shell=True)

rawDescription: Python's sh module - Running 'source' command


rawDescription: Splitting a string with delimiters and conditions


code:
logs = PrizeVerificationCodeSMSLog.objects.filter(winner__lucky_draw_id=id).order_by('-created_on')
winners = logs.select_related("winner")[:10]

rawDescription: Django models queries use join

description: Django models queries use join


rawDescription: How to repeat characters in Python without string concatenation?

description: Repeat characters in Python without string concatenation


code:
df=pd.DataFrame( { 'x':[0,0,.1,.2,0,0] } )
df2 = pd.rolling_sum(df,window=2)
df2

rawDescription: pandas.rolling_sum weird inaccuracy

description: Pandas.rolling_sum weird inaccuracy


rawDescription: Python and Beautiful Soup - Search for tag a, return following tag b's until tag A is found


code: it = iter(range(5, 9))      #Indexing not possible here

rawDescription: Confused by the enumerate() function in tutorials


code:
name = input("Tell me your name: ")
print("Your name is: " + name)

rawDescription: How to define a variable inside the print function?

description: Define a variable inside the print function


code:
class MutableList(Mutable, list):
    @classmethod
    def coerce(cls, key, value):
        if not isinstance(value, MutableList):
            if isinstance(value, list):
                return MutableList(value)
            value = Mutable.coerce(key, value)

        return value

    def __setitem__(self, key, value):
        old_value = list.__getitem__(self, key)
        for obj, key in self._parents.items():
            old_value._parents.pop(obj, None)

        list.__setitem__(self, key, value)
        for obj, key in self._parents.items():
            value._parents[obj] = key

        self.changed()

    def __getstate__(self):
        return list(self)

    def __setstate__(self, state):
        self[:] = state

rawDescription: PickleType with Mutable Tracking in SqlAlchemy


code: id = property(_get_id, _set_id)

rawDescription: Are accessors in Python ever justified?

description: Are accessors in Python ever justified


code: plt.rgrids([.3 * _ for _ in range(1, 17)])

rawDescription: Polar heatmaps in python

description: Polar heatmaps in python


code:
import timeit
timeit.timeit('foo()', 'def foo():\n\tglobals()["bar"] = 1',number=10000000)
timeit.timeit('foo()', 'def foo():\n\tglobal bar\n\tbar = 1',number=10000000)

rawDescription: Why would people use globals() to define variables


code:
urls={}
search = soup.find_all('a', href=True)
for x in range(len(search)):
    urls[x] = search[x]['href'] ##Result is: {0:firsturl, 1:secondurl, 2:thirdurl}
    ##and so on

rawDescription: Assigning the output of a for loop to a variable


code:
import numpy as np
df['rep'] = np.array(list(repeats(df['time'])))

rawDescription: Timeseries Resampling

description: Timeseries Resampling


rawDescription: Good practice default values

description: Good practice default values


code:
myre = re.compile(r'\[\d+\]')
newstring = myre.sub(replacement, yourstring)

rawDescription: find string with format '[number]' using regex

description: Find string with format '[number]' using regex


code:
from string import Formatter
import sys

if sys.version_info < (3,):
    int_type = (int, long)
else:
    int_type = (int)

class TrailingFormatter(Formatter):

    def vformat(self, *args):
        self._automatic = None
        return super(TrailingFormatter, self).vformat(*args)

    def get_value(self, key, args, kwargs):
        if key == '':
            if self._automatic is None:
                self._automatic = 0
            elif self._automatic == -1:
                raise ValueError("cannot switch from manual field specification "
                                 "to automatic field numbering")
            key = self._automatic
            self._automatic += 1
        elif isinstance(key, int_type):
            if self._automatic is None:
                self._automatic = -1
            elif self._automatic != -1:
                raise ValueError("cannot switch from automatic field numbering "
                                 "to manual field specification")
        return super(TrailingFormatter, self).get_value(key, args, kwargs)

    def format_field(self, value, spec):
        if len(spec) > 1 and spec[0] == 't':
            value = str(value) + spec[1]  # append the extra character
            spec = spec[2:]
        return super(TrailingFormatter, self).format_field(value, spec)

kf = TrailingFormatter()
w = 20
ch = ':'
x = dict(a_key=23, another_key=42)

for k in sorted(x):
    v = x[k]
    print(kf.format('{:t{}<{}} {}', k, ch, w, v))

rawDescription: Print string left aligned with fixed width and suffix


code: funcs = {'number_times_listened':['sum'], 'user_id':['count']}

rawDescription: Python/Pandas: Pivot table

description: Python/Pandas: Pivot table


code:
soup.find("span",{"data-caption":" Bed"})
soup.find("span",{"data-caption":" Bed"}).replace(' ', '')

rawDescription: BS4 grabbing the contents of a tag with an unusual attribute


code: inverse_PDF = 1/(PDF + delta)

rawDescription: Inverse Weighted Distribution

description: Inverse Weighted Distribution


code:
class PlyvelBatchWrite(object):
    def __init__(self, plv_dict):
        self.__batch = plv_dict._db.write_batch()
        self.__plvd = plv_dict

    def set(self, key, val):
        self.__batch.put(self.__plvd.serializer.pack(key), self.__plvd.serializer.pack(val))

    def delete(self, key):
        self.__batch.delete(self.__plvd.serializer.pack(key))

    def clear(self):
        self.__batch.clear()

    def commit(self):
        self.__batch.write()

class PlyvelDict(MutableMapping):
    def __init__(self, directory='', db=None, serializer_factory=None, cache_factory=None, **kwargs):
        self.__directory = directory
        ensure_directory(directory)
        if isinstance(db, str) or db is None:
            if db is None:
                # generate UUID
                db = str(uuid.uuid4())
            self.__db = db
            db = plyvel.DB(self.name(), **kwargs)
        else:
            self.__db = kwargs['db']
        self._db = db
        if serializer_factory:
            self.serializer = serializer_factory()
        else:
            self.serializer = None
        if cache_factory:
            self.__cache = cache_factory(self.__cache_miss, self.__cache_evict)
        else:
            self.__cache = None

    def name(self):
        full_path = os.path.join(self.__directory, self.__db)
        return full_path

    def __cache_miss(self, key):
        b_item = self._db.get(self.serializer.pack(key))
        if b_item is not None:
            return self.serializer.unpack(b_item)
        else:
            raise KeyError(key)

    def __cache_evict(self, key, val):
        self._db.put(self.serializer.pack(key), self.serializer.pack(val))

    def __copy__(self):
        return type(self)(self.__directory, self._db, type(self.serializer), type(self.__cache), db=self.__db)

    def __getitem__(self, key):
        return self.__cache[key]

    def __setitem__(self, key, value):
        if key in self.__cache:
            self.__cache[key] = value
        self.__write_to_db(key, value)

    def __write_to_db(self, key, value):
        self._db.put(self.serializer.pack(key), self.serializer.pack(value))

    def __delitem__(self, key):
        if key in self.__cache:
            del self.__cache[key]
        self._db.delete(self.serializer.pack(key))

    def __iter__(self):
        return self.iterkeys()

    def __keytransform__(self, key):
        return key

    def __len__(self):
        return self.count()

    def __del__(self):
        self.flush()
        if not self._db.closed:
            self._db.close()

    # improved methods
    def flush(self, write_to_db=False):
        if self.__cache:
            if write_to_db:
                batch = self.set_batch()
                for key, val in self.__cache.items():
                    batch.set(key, val)
                batch.commit()
            self.__cache.clear()

    def set_batch(self):
        return PlyvelBatchWrite(self)

    def iteritems(self):
        self.flush()
        for key, value in self._db.iterator(include_key=True, include_value=True):
            yield (self.serializer.unpack(key), self.serializer.unpack(value))

    def iterkeys(self):
        self.flush()
        for key in self._db.iterator(include_key=True, include_value=False):
            yield self.serializer.unpack(key)

    def itervalues(self):
        self.flush()
        for val in self._db.iterator(include_key=False, include_value=True):
            yield self.serializer.unpack(val)

    def keys(self):
        self.flush()
        # fixes default method which calls __len__
        return list(self.iterkeys())

    def values(self):
        self.flush()
        return list(self.itervalues())

    def has_key(self, key):
        return key in self

    def clear(self):
        self.flush()
        for k in self:
            del self[k]

    def count(self):
        self.flush()
        return sum(1 for key in self)

rawDescription: NetworkX extensibility for custom storage of nodes/edges


code:
def set_password(self, raw_password):
    import random
    algo = 'sha1'
    salt = get_hexdigest(algo, str(random.random()), str(random.random()))[:5]
    hsh = get_hexdigest(algo, salt, raw_password)
    self.password = '%s$%s$%s' % (algo, salt, hsh)

rawDescription: Python's safest method to store and retrieve passwords from a database


rawDescription: How to map a arabic character to english string using python

description: Map a arabic character to english string using python


rawDescription: Inverse Index comprehension

description: Inverse Index comprehension


code:
from string import upper
mylis=['this is test', 'another test']
map(upper, mylis)

rawDescription: Apply function to each element of a list