code:
import json
from json.encoder import encode_basestring_ascii ,encode_basestring,FLOAT_REPR,INFINITY,c_make_encoder
class JsonSpecialKey(object):
    def __init__(self, data):
        self.data = data
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
        _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
        ## HACK: hand-optimized bytecode; turn globals into locals
        ValueError=ValueError,
        dict=dict,
        float=float,
        id=id,
        int=int,
        isinstance=isinstance,
        list=list,
        str=str,
        tuple=tuple,
    ):

    if _indent is not None and not isinstance(_indent, str):
        _indent = ' ' * _indent

    def _iterencode_list(lst, _current_indent_level):
        if not lst:
            yield '[]'
            return
        if markers is not None:
            markerid = id(lst)
            if markerid in markers:
                raise ValueError("Circular reference detected")
            markers[markerid] = lst
        buf = '['
        if _indent is not None:
            _current_indent_level += 1
            newline_indent = '\n' + _indent * _current_indent_level
            separator = _item_separator + newline_indent
            buf += newline_indent
        else:
            newline_indent = None
            separator = _item_separator
        first = True
        for value in lst:
            if first:
                first = False
            else:
                buf = separator
            if isinstance(value, str):
                yield buf + _encoder(value)
            elif value is None:
                yield buf + 'null'
            elif value is True:
                yield buf + 'true'
            elif value is False:
                yield buf + 'false'
            elif isinstance(value, int):
                yield buf + str(value)
            elif isinstance(value, float):
                yield buf + _floatstr(value)
            elif isinstance(value, JsonSpecialKey):
                yield buf + value.data

            else:
                yield buf
                if isinstance(value, (list, tuple)):
                    chunks = _iterencode_list(value, _current_indent_level)
                elif isinstance(value, dict):
                    chunks = _iterencode_dict(value, _current_indent_level)
                else:
                    chunks = _iterencode(value, _current_indent_level)
                for chunk in chunks:
                    yield chunk
        if newline_indent is not None:
            _current_indent_level -= 1
            yield '\n' + _indent * _current_indent_level
        yield ']'
        if markers is not None:
            del markers[markerid]

    def _iterencode_dict(dct, _current_indent_level):
        if not dct:
            yield '{}'
            return
        if markers is not None:
            markerid = id(dct)
            if markerid in markers:
                raise ValueError("Circular reference detected")
            markers[markerid] = dct
        yield '{'
        if _indent is not None:
            _current_indent_level += 1
            newline_indent = '\n' + _indent * _current_indent_level
            item_separator = _item_separator + newline_indent
            yield newline_indent
        else:
            newline_indent = None
            item_separator = _item_separator
        first = True
        if _sort_keys:
            items = sorted(dct.items(), key=lambda kv: kv[0])
        else:
            items = dct.items()
        for key, value in items:
            if isinstance(key, str):
                pass
            # JavaScript is weakly typed for these, so it makes sense to
            # also allow them.  Many encoders seem to do something like this.
            elif isinstance(key, float):
                key = _floatstr(key)
            elif key is True:
                key = 'true'
            elif key is False:
                key = 'false'
            elif key is None:
                key = 'null'
            elif isinstance(key, int):
                key = str(key)
            elif _skipkeys:
                continue
            else:
                raise TypeError("key " + repr(key) + " is not a string")
            if first:
                first = False
            else:
                yield item_separator
            yield _encoder(key)
            yield _key_separator
            if isinstance(value, str):
                yield _encoder(value)
            elif value is None:
                yield 'null'
            elif value is True:
                yield 'true'
            elif value is False:
                yield 'false'
            elif isinstance(value, int):
                yield str(value)
            elif isinstance(value, float):
                yield _floatstr(value)
            elif isinstance(value, JsonSpecialKey):
                yield value.data
            else:
                if isinstance(value, (list, tuple)):
                    chunks = _iterencode_list(value, _current_indent_level)
                elif isinstance(value, dict):
                    chunks = _iterencode_dict(value, _current_indent_level)
                else:
                    chunks = _iterencode(value, _current_indent_level)
                for chunk in chunks:
                    yield chunk
        if newline_indent is not None:
            _current_indent_level -= 1
            yield '\n' + _indent * _current_indent_level
        yield '}'
        if markers is not None:
            del markers[markerid]

    def _iterencode(o, _current_indent_level):
        if isinstance(o, str):
            yield _encoder(o)
        elif o is None:
            yield 'null'
        elif o is True:
            yield 'true'
        elif o is False:
            yield 'false'
        elif isinstance(o, int):
            yield str(o)
        elif isinstance(o, float):
            yield _floatstr(o)
        elif isinstance(o, JsonSpecialKey):
            yield o.data
        elif isinstance(o, (list, tuple)):
            for chunk in _iterencode_list(o, _current_indent_level):
                yield chunk
        elif isinstance(o, dict):
            for chunk in _iterencode_dict(o, _current_indent_level):
                yield chunk
        else:
            if markers is not None:
                markerid = id(o)
                if markerid in markers:
                    raise ValueError("Circular reference detected")
                markers[markerid] = o
            o = _default(o)
            for chunk in _iterencode(o, _current_indent_level):
                yield chunk
            if markers is not None:
                del markers[markerid]
    return _iterencode
class JsonSpecialEncoder(json.JSONEncoder):

     def iterencode(self, o, _one_shot=False):
        """Encode the given object and yield each string
        representation as available.

        For example::

            for chunk in JSONEncoder().iterencode(bigobject):
                mysocket.write(chunk)

        """
        if self.check_circular:
            markers = {}
        else:
            markers = None
        if self.ensure_ascii:
            _encoder = encode_basestring_ascii
        else:
            _encoder = encode_basestring
        def floatstr(o, allow_nan=self.allow_nan,
                _repr=FLOAT_REPR, _inf=INFINITY, _neginf=-INFINITY):
            # Check for specials.  Note that this type of test is processor
            # and/or platform-specific, so do tests which don't depend on the
            # internals.

            if o != o:
                text = 'NaN'
            elif o == _inf:
                text = 'Infinity'
            elif o == _neginf:
                text = '-Infinity'
            else:
                return _repr(o)

            if not allow_nan:
                raise ValueError(
                    "Out of range float values are not JSON compliant: " +
                    repr(o))

            return text

        _iterencode = _make_iterencode(
            markers, self.default, _encoder, self.indent, floatstr,
            self.key_separator, self.item_separator, self.sort_keys,
            self.skipkeys, _one_shot)
        return _iterencode(o, 0)
d = {'testKey':JsonSpecialKey('function() {alert(123);}')}
print (json.dumps(d, cls=JsonSpecialEncoder, ensure_ascii=False, indent=4))

rawDescription: customise simplejson output

description: Customise simplejson output


code:
for idx in range(4, 31):
    cycle = cycles[str(idx)]
    output_rows(cycles['rows'])

rawDescription: Need help to sort processed mdb file in Python on Linux machine


code: import my_module.vX_Y as my_module

rawDescription: Supporting multiple Python module versions (with the same version of Python)


code:
def class_factory(classname):
    base_class = getattr(tk, classname)

    def __init__(self, parent, **kwargs):
        objparams, packparams = dispatch_parameters(self, **kwargs)
        base_class.__init__(self, parent, objparams)
        self.pack(packparams)

    return type(classname, (base_class, object), {'__init__': __init__})

for classname in ["Frame", "Label"]:
    globals()[classname] = class_factory(classname)

rawDescription: Building class names from a list of strings


code:
import itertools

[list(group) for key, group in itertools.groupby(my_list, key=lambda v: v[:3])]

rawDescription: Python: New list grouping repeated elements from existing list


code: readtoint('\xfe\xff\xff\xff')

rawDescription: Reading negative values from a file in python


code:
ctypes.windll.WINMM.mciSendStringW(u"open D: type cdaudio alias d_drive", None, 0, None)
ctypes.windll.WINMM.mciSendStringW(u"set d_drive door open", None, 0, None)

rawDescription: How to eject CD using WMI and Python?

description: Eject CD using WMI and Python


code: [abs(a -b) for a, b in combinations(intList, 2)]

rawDescription: Getting difference from all possible pairs from a list Python


BRANCH

value: foo

rawDescription: Python request similar to my unix curl script


rawDescription: Boolean indexing of 2D ndarray based on row comparison


code:
class Uncertain:
  def __init__(self, x, delta=0):
    self.delta = delta
    self.x = x
  def __pow__(self, other):
    return Uncertain(
      self.x**other.x,
      Uncertain._propagate_power(self, other)
    )
  @staticmethod
  def _propagate_power(A, B):
    return math.sqrt(
      ((B.x*(A.x**(B.x-1)))**2)*A.delta*A.delta +
      (((A.x**B.x)*math.log(B.x))**2)*B.delta*B.delta
    )

rawDescription: Difference between the built-in pow() and math.pow() for floats, in Python?


code:
import collections

d = collections.defaultdict(list)
for sub in a:
    d[sub[0]].append(sub)

rawDescription: Python - split list of lists by value

description: Python - split list of lists by value


code:
handle = Entrez.efetch(db="gene",
                       id="10555",
                       rettype="gene_table",
                       retmode="text")

rawDescription: Biopython Retrieving protein transcripts for a protein coding gene


rawDescription: Remove all lists of multiple sets where the specific index is same


code: T.index = T.index.time

rawDescription: Get time of month in pandas

description: Get time of month in pandas


rawDescription: Pyramid / SQLAlchemy trouble with joined models


code:
import trac.web.main
env = {'trac.env_parent_dir':
       '/home/manu/tmp'}
trac.web.main.get_environments(env)

rawDescription: Getting a listing of Trac projects in Python


code:
import tkinter
import tempfile

ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
    b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
    b'\x08\x00\x00\x00\x00\x00@\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64

_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
    icon_file.write(ICON)

tk = tkinter.Tk()
tk.title("rename")

tknewwindow = tkinter.Toplevel(tk)
tknewwindow.title("rename1")
tknewwindow.iconbitmap(default=ICON_PATH)

label = tkinter.Label(tknewwindow, text="Window with transparent icon.")
label.pack()

tk.mainloop()

rawDescription: Removing TK from Window Title Python tkinter


rawDescription: How to delete object in a dict by reference from another variable

description: Delete object in a dict by reference from another variable


code:
# TCP client example
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("localhost", 7000))
while 1:
    data = input( "SEND( TYPE q or Q to Quit):" )
    if (data != 'Q' and data != 'q'):
        my_bytes = bytearray()
        for c in data:
            my_bytes.append(ord(c))
        client_socket.send(my_bytes)
    else:
        my_bytes = bytearray()
        my_bytes.append(ord(data))
        client_socket.send(my_bytes)
##      client_socket.shutdown(socket.SHUT_RDWR)
        client_socket.close()
        break;

rawDescription: Python 3: Server socket not closing properly, infinite loop of blank messages received


code:
with open('input_data.txt') as file_i:
     data = file_i.read()

for name, count in numbers.iteritems():
    result = re.search(r'\|{}\n(.*?)(>|$)'.format(name), s, re.S)
    if result:
        data_original = result.group(1)
        stripped_data = data_original[:count]
        data = data.replace(data_original, stripped_data)
with open('input_new.txt', 'w') as f:
    f.write(data)

rawDescription: Length cutting through file handling

description: Length cutting through file handling


code:
{(u'sid(s1).', u'sentence1', 'sentence1_info'): ['sid(s1).',
                                                 'Satz1',
                                                 'Staz1_info'],
 (u'sid(s2).', u'sentence2', 'sentence2_info'): ['sid(s2).',
                                                 'Satz2',
                                                 'Staz2_info']}

rawDescription: Combine two lists of lists into a dictionary python


code:
wolf
wolf
cat
blume
eisenbahn

rawDescription: Python: 'before' and 'after' for multiprocessing workers


code: module = __import__(module_name)

rawDescription: is it possible to import file if the file name is in variable?

description: Is it possible to import file if the file name is in variable


code:
from operator import attrgetter
from functools import partial

valget = attrgetter('value')

maxval = partial(max, key=valget)
minval = partial(max, key=valget)
sortedval = partial(sorted, key=valget)
sortval = partial(list.sort, key=valget)

rawDescription: Is there a way to override the "key" function for list.max() and list.sort() in the class of the list items?


code:
d = {}
for i, (key, group) in enumerate(itertools.groupby(x)):
    runlength = len(list(group))
    if runlength > d.get(key, (None, 0))[1]:
        d[key] = (i, runlength)
x = ''.join(sorted(d, key=d.__getitem__))

rawDescription: How to remove duplicate characters in a string and print according to the longest occurrence

description: Remove duplicate characters in a string and print according to the longest occurrence


rawDescription: Common xlabel/ylabel for matplotlib subplots


code:
fuzzy_regex = re.compile(r'^(\D*)(.*)$')
(before_numbers, part_with_numbers) = fuzzy_regex.search(input_string).groups()
# Analyze before_numbers to see what kind of room, etc.
# Analyze part_with_numbers to see square footage, etc.

rawDescription: Parsing text with regex in Python: determine match order and mapping value to object type?


code:
import pickle
... # other imports and stuff
custom_sent_tokenizer = PunktSentenceTokenizer(train_text)
pickle.dump(custom_sent_tokenizer, open( "save.p", "wb" ))

rawDescription: NLTK PunktSequenceTokenizer return type or a way to use it faster in an iterative function?


code:
from lxml import etree

content = '''

<root>

            content from table 1

            content from table 2

</root>'''

root = etree.fromstring(content)
table_one = root.xpath('table[@id="table-one"]')

# this will select all td elements in the entire XML document (so two elements)
all_td_elements = table_one.xpath('//td')

# this will just select the single sub-element because of the period
just_sub_td_elements = table_one.xpath('.//td')

rawDescription: find all tr in a table element with xpath?

description: Find all tr in a table element with xpath


code:
np.random.seed(123)
df=pd.DataFrame({ 'date':np.random.choice(pd.date_range('2015-1-1',periods=300),20),
                  'id':np.random.randint(1,4,20) })
df=df.sort(['id','date'])

rawDescription: Python (Pandas) updating previous x rows within specified condition


code: single = single.reshape((-1, 4))

rawDescription: Python: How to perform division according to its representation?


rawDescription: How to order a dictionary within a list by alphabetical order and highest number

description: Order a dictionary within a list by alphabetical order and highest number


rawDescription: Inheritance and Slicing, making it the child type


code: from itertools import permutations

rawDescription: Permutations of a string with two distinct characters (60 of one value and 20 of another)


code:
import numpy as np
import itertools as IT

def using_intermediate_list(g):
    lst = list(g)
    y = np.fromiter((x[0] for x in lst), float, len(lst))
    y2 = np.fromiter((x[1] for x in lst), float, len(lst))
    return y, y2

def using_slices(g):
    y = np.fromiter(IT.chain.from_iterable(g), dtype=float)
    y, y2 = y[::2], y[1::2]
    return y, y2

def using_slices_contiguous(g):
    y = np.fromiter(IT.chain.from_iterable(g), dtype=float)
    y, y2 = y[::2], y[1::2]
    y = np.ascontiguousarray(y)
    y2 = np.ascontiguousarray(y2)
    return y, y2

def using_array(g):
    y = np.array(list(g))
    y, y2 = y[:, 0], y[:, 1]
    return y, y2

rawDescription: Numpy create two arrays using fromiter simultaneously


code:
class StreamingXMLParsingHTTPClient(HTTPPageGetter):
    def connectionMade(self):
        HTTPPageGetter.connectionMade(self)
        self._parser = make_parser()

    def handleResponsePart(self, bytes):
        self._parser.feed(bytes)

    def handleResponseEnd(self):
        self._parser.feed('', True)
        self.handleResponse(None) # Whatever you pass to handleResponse will be the result of the Deferred below.

factory = HTTPClientFactory(url)
factory.protocol = StreamingXMLParsingHTTPClient
reactor.connectTCP(host, port, factory)
d = factory.deferred
# d fires when the response is completely received

rawDescription: How do I fetch an XML document and parse it with Python twisted?

description: Fetch an XML document and parse it with Python twisted


code:
by_week = numpy.reshape(visitors, (7, -1))
weekly = numpy.sum( by_week, axis = 1)

rawDescription: Find the sum of subsets of a list in python


code:
from datetime import datetime
from openerp import tools

start_date = datetime.strptime("1995-03-13", tools.DEFAULT_SERVER_DATE_FORMAT)
end_date = datetime.strptime("1995-03-19", tools.DEFAULT_SERVER_DATE_FORMAT)

delta = d1 - d0
print(delta.days)

rawDescription: How to get a count of days between two dates in Openerp

description: Get a count of days between two dates in Openerp


code:
class B:
    def __init__(self, person_names):
        self.objs = []  # list to contain objs
        for name in person_names:
            self.objs.append(A(name))  # create class A object and add to list

rawDescription: Python 2.7 : How to use objects of one class in another class?


code:
cat1.txt
cat2.txt

rawDescription: Dictionary python trouble

description: Dictionary python trouble


code:
payload = json.loads(cmd.payload)
buttonPushed = payload["buttonPushed"]

rawDescription: IoT Python app with a Raspberry Pi and Bluemix: Pushing the button doesn't work


code: setattr(Person, '__mro__', (Person, Friendly, object))

rawDescription: How to dynamically change base class of instances at runtime?

description: Dynamically change base class of instances at runtime


code:
#urls.py
from appname.views import some_view

urlpatterns = patterns('',
    url(r'^schedule/addbid/(?P<id>\d+)$', some_view),
    ...
)

rawDescription: Create django object using a view with no form


code:
standardDeduction = 6300
personalExemption = 4000
no_tax = standardDeduction + personalExemption

total =  float(input("Please enter your Winning amount: "))

taxable = total - no_tax
total_tax = 0.0

if taxable > 0: # brackets 1
    amount = 9225 # - 0
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.1
    taxable -= amount

if taxable > 0: # brackets 2
    amount = 37450 - 9225
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.15
    taxable -= amount

if taxable > 0: # brackets 3
    amount = 90750 - 37450
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.25
    taxable -= amount

if taxable > 0: # brackets 4
    amount = 189300 - 90750
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.28
    taxable -= amount

if taxable > 0: # brackets 5
    amount = 411500 - 189300
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.33
    taxable -= amount

if taxable > 0: # brackets 6
    amount = 413200 - 411500
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.35
    taxable -= amount

if taxable > 0: # brackets 7
    amount = 413200
    if taxable <= amount:
        amount = taxable
    total_tax += amount * 0.396
    taxable -= amount

if total > 0:
    print("you win",total,"and you have to paid",total_tax,"in tax")
else:
    print("Invalid winnings input")

rawDescription: Powerball winnings using if else statements in python


code:
d = MyData()
d.f() # prints out your expected result

rawDescription: how to pass self to function inside python dictionary

description: Pass self to function inside python dictionary


code:
with open("test.txt") as f:
    # itertools.imap python2
    f = map(str.rstrip, f)
    for line in f:
        if line == "***a":
            print("")
            for line in f:
                if line == "---a":
                    break
                print(line)

rawDescription: printing lines between start and end point

description: Printing lines between start and end point


code:
outside
inside
inside

rawDescription: Data structure in python containing shapes corners and centroids


rawDescription: numpy divide row by row sum

description: Numpy divide row by row sum


rawDescription: gematria function - processing a text according to numerical values

description: Gematria function - processing a text according to numerical values


code: callback = partial(span_selected, coordinate)

rawDescription: Python alternative to Javascript function.bind()?


rawDescription: choose lines from a file using a certain condition

description: Choose lines from a file using a certain condition


rawDescription: Encode and assemble multiple features in PySpark


code: x = int(x) if x else None

rawDescription: Semantic way to check if variable is None


code:
import bottle

class App(object):
    def __init__(self,param):
        self.param   = param

    def index1(self):
        return("I'm 1 | self.param = %s" % self.param)

myapp = App(param='some param')
bottle.route("/1")(myapp.index1)

rawDescription: Bottle framework and OOP, using method instead of function


rawDescription: Sorting names containing numbers

description: Sorting names containing numbers


code:
class SocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        logging.info('Client IP:' + self.request.remote_ip)

rawDescription: How do I get the client IP of a Tornado request from the WebSocket Handler?

description: Get the client IP of a Tornado request from the WebSocket Handler


code:
for item in g_d4:
    links_2=soup.find_all('a', href=re.compile('^http://www.barneys.com/barneys-new-york/men/'))
    pattern_2=re.compile("clothing/(\w+)")
    for link in links_2:
        match_1=pattern_2.search(link["href"])
        if match_1:
            print(match_1.group(1))
            break

rawDescription: Print just first output line

description: Print just first output line


code:
def plotSomething(x,y):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xscale("log", nonposx='clip')
    ax.set_yscale("log", nonposy='clip')
    ax.scatter(x,y)
    return fig

rawDescription: plotting with matplotlib from a module

description: Plotting with matplotlib from a module


code: app = QtGui.QApplication(sys.argv)

rawDescription: PyQt4 jpeg/jpg unsupported image format

description: PyQt4 jpeg/jpg unsupported image format


rawDescription: Delete newline / return carriage in file output


code:
import numpy as np
from pprint import pprint

arrayholder = {'test_array':np.array([1, 2, 3])}
pprint(arrayholder['test_array'])

rawDescription: Can't append global NumPy array from other module


code: loss = ((X_train - X_projected) ** 2).mean()

rawDescription: PCA projecting and reconstruction in Scikit


rawDescription: reassigning expanded recarray field

description: Reassigning expanded recarray field


code:
data_blocks = []

buf = data.file.read(8192)
while buf:
    data_blocks.append(buf)
    buf = data.file.read(8192)

data = ''.join(data_blocks)

rawDescription: Python bottle - How to upload media files without DOSing the server


rawDescription: wx.lib.pubsub: How to change the value in a timer

description: Wx.lib.pubsub: How to change the value in a timer


code: lambda *outer: lambda *inner: tuple(map(sum, zip(outer, inner)))

rawDescription: How can I supply two arbitrary number of arguments to a lambda expression in python?

description: Supply two arbitrary number of arguments to a lambda expression in python


code:
# last value returned by decorated function is accessible as 'last' attribute
def save_last(f):
    def w(*args, **kwargs): # w is the 'wrapper' function
        w.last=f(*args, **kwargs)
        return w.last
    return w

rawDescription: How to avoid defining a variable to hold a function result which might be needed only once

description: Avoid defining a variable to hold a function result which might be needed only once


code:
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

#-- Set axis spines at 0
for spine in ['left', 'bottom']:
    ax.spines[spine].set_position('zero')

# Hide the other spines...
for spine in ['right', 'top']:
    ax.spines[spine].set_color('none')

#-- Decorate the spins
arrow_length = 20 # In points

# X-axis arrow
ax.annotate('X', xy=(1, 0), xycoords=('axes fraction', 'data'),
            xytext=(arrow_length, 0), textcoords='offset points',
            ha='left', va='center',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

# Y-axis arrow
ax.annotate('Y', xy=(0, 1), xycoords=('data', 'axes fraction'),
            xytext=(0, arrow_length), textcoords='offset points',
            ha='center', va='bottom',
            arrowprops=dict(arrowstyle='<|-', fc='black'))

#-- Plot
ax.axis([-4, 10, -4, 10])
ax.grid()

plt.show()

rawDescription: how to move axes labels to near the arrows in matplotlib

description: Move axes labels to near the arrows in matplotlib


code:
A = pnts.T
R = np.square(A - np.roll(A, -2, axis=0))
S = R[0::2] + R[1::2] # 1000x3 squares of distances
np.logical_and(S[0] == S[1], S[1] == S[2]) # 1000 True/False results

rawDescription: I am using a numpy array of randomly generated ordered pairs, I need to determin if the ordered pairs are different types of triangles


code:
Mat = np.arange(16).reshape(4,4)
sub = Mat[2:,:2]
Mat
sub

rawDescription: numpy ndarray indexing - retrieving indexes from tuple

description: Numpy ndarray indexing - retrieving indexes from tuple


code:
a,b,c,d = str(input('>> '))
1234
a
b
c
d

rawDescription: Get 4x4 matrix input in multiple lines in Python


code:
cmd = 'some command create name'
for i in range(4):
    name = 'ARRAY_456_%d' % i # will create ARRAY_456_0, ...
    localdevice = cmd('%(cmd)s %(name)s' % dict(cmd=cmd, name=name)) # will merge the command with the name using keywords

rawDescription: Would I be able to run a cmd python command with a name that is generated by a list?


code:
col = 'foo'
val = 'bar'
kwargs = {col: bar}

some_function(**kwargs)

rawDescription: Can I use the value of a variable as a parameter name for a function?

description: Use the value of a variable as a parameter name for a function


code:
from django.shortcuts import render

def search(request):
    if 'q_word' in request:
        searchTerm = request.GET['q_word']

    found_bills = Bill.objects.filter(name__icontains = searchTerm)
    page = request.GET.get('page')
    paginator = Paginator(found_bills,25)
    try:
        current_page = paginator.page(page)
    except PageNotAnInteger:
        current_page = paginator.page(1)
    except (EmptyPage, InvalidPage):
        current_page = paginator.page(paginator.num_pages)
    # bills_list = list(current_page.object_list) - not needed
    return render(request,
                  'results.html',{"results":current_page,"term": searchTerm})

rawDescription: How to describe URL in Django - still need an answer

description: Describe URL in Django - still need an answer


code:
# parse from URL
etree.parse("http://example.com/somefile.xml")

rawDescription: Parsing XML from API response

description: Parsing XML from API response


code:
from datetime import datetime, timezone

import ephem

now = datetime.now(timezone.utc)
Vancouver = ephem.Observer()
Vancouver.lat = '49.2878'
Vancouver.horizon = 0
Vancouver.lon = '-123.0502'
Vancouver.elevation = 80
Vancouver.date = now
sun = ephem.Sun(Vancouver)

print("sunrise is at", ephem.localtime(Vancouver.next_rising(sun)))
print("sunset is going to be at ",
      ephem.localtime(Vancouver.next_setting(sun)))
print("now is ",now.astimezone())

rawDescription: localtime not actually giving localtime

description: Localtime not actually giving localtime


code:
values = [
    [['a','b','c'], 1],
    [['a','b','d'], 2],
    [['a','e','f'], 3]]

result = {}
for keys, value in values:
    add_nested(result, keys, value)
print(result)

rawDescription: Python list to nested keys

description: Python list to nested keys


code: self.parameter = args['parameter']

rawDescription: How to pass args to an instance of sublime_plugin.WindowCommand?

description: Pass args to an instance of sublime_plugin.WindowCommand


code:
import csv
with open('some.csv', newline='', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

rawDescription: Write bytes literal with undefined character to CSV file (Python 3)


code:
mystr = 'cathy is a singer on fridays'
x = mystr.split()
" ".join(x[:3] + ["dancer"] + x[4:])

rawDescription: Should I be using regex in Python

description: Should I be using regex in Python


code:
import re
re.sub('g+', 'g', 'omgggg')
re.sub('l+', 'l', 'lollll')

rawDescription: Regex to match 'lol' to 'lolllll' and 'omg' to 'omggg', etc


code:
# yourapp/admin.py
from django.contrib.admin import site, ModelAdmin
from yourapp.models import Pizza
from yourapp.forms import PizzaForm

class PizzaAdmin(ModelAdmin):
  form = PizzaForm

site.register(Pizza, PizzaAdmin)

rawDescription: Django ModelForm for Many-to-Many fields


code:
import random

def obsfucate_function(default):
    if random.random() < 0.1:
        # 10% chance the default is picked
        return default
    return random.choice('!%&*#@')

rawDescription: Return original value, python

description: Return original value, python


code: "some stuff here: %s" % var

rawDescription: Hi, I'm new to SQL/python, could someone please help me with searching databases using python commands, thanks :)


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

fig, ax = plt.subplots()
im = ax.imshow(np.random.random((10, 10)), cmap='gist_earth')
cbar = fig.colorbar(im)
cbar.set_label('Test', y=1.0, ha='right')
plt.show()

rawDescription: How to move a colorbar label downward?

description: Move a colorbar label downward


code:
def tupleToDict(listOfList):
    q = [listOfList]
    while q:
        l = q.pop()
        yield getItems(l)
        for nestedList in listOfList:
            q += getAllNestedItems(nestedList)

rawDescription: How can I return values in a recursive function without stopping the recursion?

description: Return values in a recursive function without stopping the recursion


rawDescription: how to create a transparent rectangle responding to click event in Tkinter

description: Create a transparent rectangle responding to click event in Tkinter


code:
dict.fromkeys(itertools.combinations(items, 2), 0)
dict.fromkeys(itertools.combinations(items, 3), 0)

rawDescription: Dictionary whose key is independent on the order of elements it contains


code:
import datetime as dt
...

# IF DATES ARE REGULAR COLUMNS
seasonal_component['Date'] = pd.to_datetime(seasonal_component['Date'])
seasonal_component['Month'] = seasonal_component['Date'].dt.month

predict_df['Date'] = pd.to_datetime(predict_df['Date'])
predict_df['Month'] = predict_df['Date'].dt.month

# IF DATES ARE INDICES
seasonal_component.index = pd.to_datetime(seasonal_component.index)
seasonal_component['Month'] = seasonal_component.index.month

predict_df.index = pd.to_datetime(predict_df.index)
predict_df['Month'] = predict_df.index.month

rawDescription: Python/Pandas - Sum dataframe items if indexes have the same month


code: array([ True, False,  True], dtype=bool)

rawDescription: Join two pandas series by values

description: Join two pandas series by values


rawDescription: How to generate random numbers that are unique forever in python

description: Generate random numbers that are unique forever in python


code:
series = areas['Com']
series

rawDescription: Pandas: join with outer product

description: Pandas: join with outer product


rawDescription: how to compute a new column based on the values of other columns in pandas - python

description: Compute a new column based on the values of other columns in pandas - python


code: Cell = collections.namedtuple(["row", "col"])

rawDescription: Game of LIfe Hashing Python

description: Game of LIfe Hashing Python


code: domain = a.partition('@')[2]

rawDescription: Python: Using split on a string and returning a tuple?


code: line = line.strip('\r\n')

rawDescription: Stripping \r\n from a line

description: Stripping \r\n from a line


code:
known_commands = {
    "boo" : "SURPRISE!",
    "xyzzy" : xyzzy,
}

rawDescription: random.choice([x, y, z]) in python, why doesn't the seed change?

description: Random.choice([x, y, z]) in python, why doesn't the seed change


rawDescription: Getting the class name of an instance in Python


code:
def getHeader(filename):
     import csv
     headername = None
     charList = ['a', 'b', 'c', 'd', 'e', 'A', 'B', 'C', 'D', 'E', 'F']
     headercsv = open(filename, 'r', newline = '')
     headerreader = csv.reader(headercsv, delimiter = ',')
     for row in headerreader:
         if row[0][0] in charList:
              headername = row

     headercsv.close()
     return headername

rawDescription: Python - Using encapsulation/functions to modify a variable and pass it to the current namespace


code: rows = csv.reader(YourFile, dialect='excel')

rawDescription: load cvs file in matrix python

description: Load cvs file in matrix python


code:
bulk = collection.initialize_unordered_bulk_op()
count = 0
for document in collection.find():
    unset_op = dict(zip_longest(set(document.keys()).difference(fields), [''], fill_value=''))
    bulk.find({'_id': document['_id']}).update_one({'$unset': unset_op})
    count = count + 1
    if count % 1000 == 0:
        bulk.execute()
        bulk = collection.initialize_unordered_bulk_op()
    if count > 0:
        bulk.execute()

rawDescription: How to unset all fields except some known fields?

description: Unset all fields except some known fields


code:
data = ((1,'Tim'),(4,'Struppi'),(5,'Nami'),(6,'Luffy'))
object_list = [ CharInStageList(*x) for x in data ]

rawDescription: How to add Objects to Class with a loop in Python?

description: Add Objects to Class with a loop in Python


code:
book = ...  # get book instance

chapter = (
    session.query(Chapter)
    .with_parent(book)
    .filter(Chapter.name == "57th Arabian Tale")
    .one()
)

rawDescription: How do you query a one-to-many relationship in an SQLAlchemy object instance?

description: Query a one-to-many relationship in an SQLAlchemy object instance


code:
import numpy

# just some 2D arrays with shape (10,20)
a1 = numpy.ones((10,20))
a2 = 2* numpy.ones((10,20))
a3 = 3* numpy.ones((10,20))

# creating 3D array with shape (3,10,20)
b = numpy.array((a1,a2,a3))

rawDescription: Constructing 3D array from base 2D array - Numpy


code: from __future__ import division

rawDescription: Why do I lose precision while multiplying and dividing whole ints?


code:
class Version(univ.Integer):
    namedValues = namedval.NamedValues(('v1', 0), ('v2', 1), ('v3', 2))

rawDescription: pyasn1 and strange mismatch when setting component

description: Pyasn1 and strange mismatch when setting component


code:
for a in alphabet:
    master_dict[a] = tally.copy()

rawDescription: Sub-dictionary erroneously repeated throughout dictionary?


code:
def edit_account(request, acc_id=None):
    if acc_id:
        f = Account.objects.get(pk=acc_id)
    else:
        f = None

    if request.method == 'POST': # If the form has been submitted...
        form = AccountForm(request.POST, request.FILES, instance=f) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            form.save()
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = AccountForm(instance=f) # An unbound form

    return render_to_response('account_form.html', {
        'form': form,
    })

rawDescription: Editing the Form in Django creates new instance


rawDescription: List of numbers

description: List of numbers


code:
from sympy import simplify
simplify(lag_L([1,2,3],[1,4,9]))

rawDescription: Generating a string with python using loops with logic conditions issues against join function alternative?


code:
_Ace = collections.namedtuple('_Ace',
            'ace_type flags mask mapped_mask sid trustee')

class Ace(_Ace):
    def __new__(cls, ace_type, flags, mask, sid, trustee):
        mapped_mask = cls._map_generic(mask)
        return super(Ace, cls).__new__(cls, ace_type, flags,
                                       mask, mapped_mask, sid, trustee)

    @staticmethod
    def _map_generic(mask):
        if mask & GENERIC_READ:
            mask = (mask & ~GENERIC_READ) | FILE_GENERIC_READ
        if mask & GENERIC_WRITE:
            mask = (mask & ~GENERIC_WRITE) | FILE_GENERIC_WRITE
        if mask & GENERIC_EXECUTE:
            mask = (mask & ~GENERIC_EXECUTE) | FILE_GENERIC_EXECUTE
        if mask & GENERIC_ALL:
            mask = (mask & ~GENERIC_ALL) | FILE_ALL_ACCESS
        return mask

    def inherited(self):         # I
        return bool(self.flags & INHERITED_ACE)
    def object_inherit(self):    # OI
        return bool(self.flags & OBJECT_INHERIT_ACE)
    def container_inherit(self): # CI
        return bool(self.flags & CONTAINER_INHERIT_ACE)
    def inherit_only(self):      # IO
        return bool(self.flags & INHERIT_ONLY_ACE)
    def no_propagate(self):      # NP
        return bool(self.flags & NO_PROPAGATE_INHERIT_ACE)

    def no_access(self):         # N
        return self.mapped_mask == 0
    def full_access(self):       # F
        return self.mapped_mask == FILE_ALL_ACCESS
    def modify_access(self):     # M
        return self.mapped_mask == FILE_MODIIFY_ACCESS
    def read_exec_access(self):  # RX
        return self.mapped_mask == FILE_READ_EXEC_ACCESS
    def read_only_access(self):  # R
        return self.mapped_mask == FILE_GENERIC_READ
    def write_only_access(self): # W
        return self.mapped_mask == FILE_GENERIC_WRITE
    def delete_access(self):     # D
        return self.mapped_mask == FILE_DELETE_ACCESS

    def get_file_rights(self):
        if self.no_access(): return ['N']
        if self.full_access(): return ['F']
        if self.modify_access(): return ['M']
        if self.read_exec_access(): return ['RX']
        if self.read_only_access(): return ['R']
        if self.write_only_access(): return ['W']
        if self.delete_access(): return ['D']
        rights = []
        for right, name in ((DELETE, 'DE'), (READ_CONTROL, 'RC'),
                            (WRITE_DAC, 'WDAC'), (WRITE_OWNER, 'WO'),
                            (SYNCHRONIZE, 'S'),
                            (ACCESS_SYSTEM_SECURITY, 'AS'),
                            (GENERIC_READ, 'GR'), (GENERIC_WRITE, 'GW'),
                            (GENERIC_EXECUTE, 'GE'), (GENERIC_ALL, 'GA'),
                            (FILE_READ_DATA, 'RD'), (FILE_WRITE_DATA, 'WD'),
                            (FILE_APPEND_DATA, 'AD'), (FILE_READ_EA, 'REA'),
                            (FILE_WRITE_EA, 'WEA'), (FILE_EXECUTE, 'X'),
                            (FILE_DELETE_CHILD, 'DC'),
                            (FILE_READ_ATTRIBUTES, 'RA'),
                            (FILE_WRITE_ATTRIBUTES, 'WA')):
            if self.mask & right:
                rights.append(name)
        return rights

    def granted_access(self, mask):
        return bool(self.mapped_mask & self._map_generic(mask))

    def __str__(self):
        trustee = self.trustee if self.trustee else self.sid
        access = []
        if self.ace_type == ACCESS_DENIED_ACE_TYPE:
            access.append('(DENY)')
        elif self.ace_type == SYSTEM_AUDIT_ACE_TYPE:
            access.append('(AUDIT)')
        if self.inherited(): access.append('(I)')
        if self.object_inherit(): access.append('(OI)')
        if self.container_inherit(): access.append('(CI)')
        if self.inherit_only(): access.append('(IO)')
        if self.no_propagate(): acccess.append('(NP)')
        access.append('(%s)' % ','.join(self.get_file_rights()))
        return '%s:%s' % (trustee, ''.join(access))

_FileSecurity = collections.namedtuple('_FileSecurity',
                        'path owner_permissions owner group '
                        'owner_sid group_sid flags dacl sacl')

class FileSecurity(_FileSecurity):
    def __str__(self):
        owner = self.owner if self.owner else self.owner_sid
        group = self.group if self.group else self.group_sid
        items = ['Path:  %s' % self.path,
                 'Owner: %s' % owner,
                 'Group: %s' % group]
        if self.dacl:
            items += ['DACL:  %s' %
                      '\n       '.join(str(x) for x in self.dacl)]
        if self.sacl:
            items += ['SACL:  %s' %
                      '\n       '.join(str(x) for x in self.sacl)]
        return '\n'.join(items)

rawDescription: Python - Get windows folder ACL permissions


code:
def result():
    response.content_type='application/json'
    return data

rawDescription: jsonify/pretty-print JSON for Bottle

description: Jsonify/pretty-print JSON for Bottle


code:
def n(x, m={0:'0'}):
    if x not in m:
        lX = x
        if x > 9:
            lX = str(x)
            #Take the integer like 123, format it and swap
            #it but share the last character. i.e. 123 -> 12321
            lX = '{}{}'.format(x,lX[::-1][1:])

        m[x] = '{0}{1}{0}'.format(n(x-1), lX)
    return m[x]

rawDescription: Recursive pattern to take input integer and return palindrome


code:
import csv

writer = csv.writer(some_file_object)

for row in cursor:
    # the csv module can't handle unicode, so encode the strings
    row = [item.encode('utf-8') if isinstance(item, basestring) else item
                                                                for item in data]
    writer.writerow(row)

rawDescription: How to convert sqlite3 data to Json format and CSV format

description: Convert sqlite3 data to Json format and CSV format


code: result = [foo for bar in baz]

rawDescription: Understanding Python List Comprehension equivalent


code: re.sub('\d+', lambda x:x.group().zfill(padding), s)

rawDescription: How to pad all the numbers in a string

description: Pad all the numbers in a string


code:
# instead of all = [row + [item number ...

seen = set()
all = []

for row in mobilesitemap:
    item_no = row[1]
    if item_no in item_number_mapping:
        all.append(row + [item_number_mapping[item_no]])
        seen.add(item_no)
# after this for loop, `all` is identical to the list comp version
unmatched_items = [item_number_mapping[item_num] for item_num in
                   set(item_number_mapping.keys()) - seen]

rawDescription: CSV if row contains string append row

description: CSV if row contains string append row


code:
strs='the quick brown fox'
strs.replace('quick brown','')
" ".join(strs.replace('quick brown','').split())

rawDescription: Removing words from a string

description: Removing words from a string


code:
person = [[], ['savings', 100.00]]
hubby = list(person)
wifey = list(person)

rawDescription: Is this a mistake of the core python programming,2nd editon?


code:
import re

raw_patterns = [r'aaa', r'bbb', r'ccc']
patterns = [re.compile(p) for p in raw_patterns]

names = "foo", "bar"

for name in names:
    with open(name + ".log", "r") as in_fp, open(name + "_temp.log", "w") as temp:
        for line in in_fp:
            if not any(patt.match(line) for patt in patterns):
                temp.write(line)

rawDescription: Algorithm to compare two files in Python


code:
import os.path
import some_module

here = os.path.dirname(some_module.__file__)
app = get_app(os.path.join(here, 'testing.ini'))

rawDescription: Writing doctests for pyramid web app which depend on settings in ini file


code:
num_letter_in_words = dict([(match, len([word for word in gutenberg.words(fileid)
                                      if match in word])) for match in matches])
#from the same text gives:
{'a': 50043, 'and': 5257, 'ccc': 0, 'bb': 52}

rawDescription: How to find occurrences of list of letters efficiently with NLTK in Python?

description: Find occurrences of list of letters efficiently with NLTK in Python


code:
import logging

logging.basicConfig(level=logging.DEBUG)

log = logging.getLogger("MyLog")
log.setLevel(logging.DEBUG)
log.info("hello")
log.debug("world")

rawDescription: Python logging, supressing output

description: Python logging, supressing output


code: cList1 = [line.rstrip('\n') for line in f]

rawDescription: readlines not reading the last line of the file in python

description: Readlines not reading the last line of the file in python


code: ['Brad/files/pdf/abc.pdf', 'Brad/files/pdf/abc2.pdf', 'Brad/files/pdf/abc3.pdf', 'Brad/files/pdf/abc4.pdf']

rawDescription: How can I get a list of all file names having same prefix on Amazon S3?

description: Get a list of all file names having same prefix on Amazon S3


code:
import datetime
def addDateTimeResults(tokens):
    dtfields = map(int, (tokens[fld] for fld in "year month day hour min sec".split()))
    # adjust 2-digit year for 21st century
    dtfields[0] += 2000
    tokens['datetime'] = datetime.datetime(*dtfields)

rawDescription: How to group tokens placed in different positions using pyparsing?

description: Group tokens placed in different positions using pyparsing


rawDescription: Python, write json / dictionary objects to a file iteratively (one at a time)


code:
inputstring = "There is' 'some' Text', and' EXTRACT ME'a'n'd' even' more' 't'ext"
inputstring.split("'", 5)[-1].rsplit("'", 8)[0]

rawDescription: Get substring by parsing from both directions


code: item_dict = dict((k,int(v)) for k,v in (i.rsplit(':') for i in item))

rawDescription: Find an entry in a list based on a partial string


rawDescription: Given the name of a positional parameter to a function, can the parameter's position be determined?


code:
import time

def make_http_connection(*args, **kwargs):
    while True: # make new http connections
        h = http.client.HTTPConnection(*args, **kwargs)
        while True: # make multiple requests using a single connection
            try:
                h.request('GET', '/') # send request; make conn. on the first run
                response = h.getresponse()
                while True: # read response slooowly
                    b = response.read(1) # read 1 byte
                    if not b:
                       break
                    time.sleep(60) # wait a minute before reading next byte
                    #note: the whole minute might pass before we notice that
                    #  the server has closed the connection already
            except Exception:
                break # make new connection on any error

rawDescription: Persistence of urllib.request connections to a HTTP server


code:
from Tkinter import *

window = Tk()
window.geometry("680x500")

Label(window, text="Top label").pack()

frame = Frame(window)
frame.pack()

listNodes = Listbox(frame, width=20, height=20, font=("Helvetica", 12))
listNodes.pack(side="left", fill="y")

scrollbar = Scrollbar(frame, orient="vertical")
scrollbar.config(command=listNodes.yview)
scrollbar.pack(side="right", fill="y")

listNodes.config(yscrollcommand=scrollbar.set)

for x in range(100):
    listNodes.insert(END, str(x))

Label(window, text="Bottom label").pack()

master.mainloop()

rawDescription: Python Tkinter: Attach scrollbar to listbox as opposed to window


code:
rx = re.compile('^.{8,}$')
#                  ^^^^ {8,} means 8 or more.
result = [w for w in vocab if rx.match(w)]

rawDescription: Regular expression matching anything greater than eight letters in length, in Python


code:
def add_padding(img, pad_l, pad_t, pad_r, pad_b):
    height, width = img.shape
    #Adding padding to the left side.
    pad_left = np.zeros((height, pad_l), dtype = np.int)
    img = np.concatenate((pad_left, img), axis = 1)

    #Adding padding to the top.
    pad_up = np.zeros((pad_t, pad_l + width))
    img = np.concatenate((pad_up, img), axis = 0)

    #Adding padding to the right.
    pad_right = np.zeros((height + pad_t, pad_r))
    img = np.concatenate((img, pad_right), axis = 1)

    #Adding padding to the bottom
    pad_bottom = np.zeros((pad_b, pad_l + width + pad_r))
    img = np.concatenate((img, pad_bottom), axis = 0)

    return img

cropped_image = img[y1:y2, x1:x2]
padded_image = add_padding(cropped_image, 20, 20, 20, 20)

rawDescription: Python: Center array image

description: Python: Center array image


code:
class MustBeMixed(object):
    def __init__(self):
        if self.__class__ == MustBeMixed:
            raise TypeError
MustBeMixed()

rawDescription: In Python 3, how to prevent direct creation of a mixin class?


code:
with open('pp.txt') as f:
 inp = f.read()

res = float(int(inp,16))
res

rawDescription: Python: extract MSB and LSB than convert in float


code:
mask_0 = pd.isnull(df).all(axis=1)
mask_0

rawDescription: Fill NaN in candlestick OHLCV data

description: Fill NaN in candlestick OHLCV data


code:
import functools

# http://stackoverflow.com/a/28961925/321973
def property_if_None_generator(f, cached=False):
    @functools.wraps(f)
    def wrapped(self):
        value = self.__getattribute__('_' + f.__name__)
        if value is not None:
            return value
        else:
            return f(self)
    if cached:
        wrapped = functools.lru_cache()(wrapped)
    return property(wrapped)

property_if_None = lambda f: property_if_None_generator(f, cached=False)
cached_property_if_None = lambda f: property_if_None_generator(f, cached=True)

rawDescription: How to have a decorator return a (cached) property iff it was previously None?

description: Have a decorator return a (cached) property iff it was previously None


code:
def GetSelections(*args, **kwargs):
    """GetSelections(self) -> DataViewItemArray"""
    return _dataview.DataViewCtrl_GetSelections(*args, **kwargs)

rawDescription: wxPython | wxDataViewListCtrl get all selected rows/items

description: WxPython | wxDataViewListCtrl get all selected rows/items


code:
for key in mydict.keys():
    if key == bad_value:
        del mydict[key]

rawDescription: python - recursively deleting dict keys?

description: Python - recursively deleting dict keys


code:
class Spider(...):
    handle_httpstatus_list = [500, 502]

rawDescription: Scrapy: catch responses with specific HTTP server codes


rawDescription: Is there a good reference list for the names of the genericsetup import steps


code:
def update_status(some_item_haver, new_status):
    for item in some_item_haver.items:
        item.update_status(new_status)

rawDescription: Python: is using decorator to change method arguments a bad thing?


rawDescription: How do I perform math operations on dates and sort them in Python?

description: Perform math operations on dates and sort them in Python


code:
@staticmethod
def merge(line):
    return ([x for x in line if x] + ([0] * len(line)))[:len(line)]

rawDescription: Unsure how to use List Comprehension on a loop


code:
import sys
# parse command line
if file_name_given:
    inf = open(file_name_given)
else:
    inf = sys.stdin

rawDescription: Read from File, or STDIN

description: Read from File, or STDIN


code:
name
Kazakhstan
Ukraine

rawDescription: Convert Country Names to Country Code using Python DictReader/DictWriter


code: newsdata = urllib2.urlopen('https://www.google.com/finance/kd?output=json&keydevs=1&recnews=0&cid=' + cid)

rawDescription: Fetch News Data from right Scrollbar using Beautifulsoup


code:
with open("test1") as tsvfile, open("out","w") as  t:
    tsvreader = csv.reader(tsvfile, delimiter="\t")
    temp = csv.writer(t,delimiter="\t")
    for row in tsvreader:
        row[4] = row[4].strip(exclude)
        temp.writerow(row)

rawDescription: python how to read a tsv file, clean it and save as new file?

description: Python how to read a tsv file, clean it and save as new file


code:
for strong in soup.find_all('strong', lambda x: x and len(x.parent) == 1):
    strong.name = 'h1'

rawDescription: Replace <strong> tag with h2 tag

description: Replace <strong> tag with h2 tag


code:
dmg_INT_mult = 0.9
dmg_AGI_mult = 1.2
dmg_STR_mult = 1.2
dmg_INT_add = -.5
dmg_AGI_add = 0
dmg_STR_add = 0
dmg_overall_mult = 0.1667
dmg_overall_add = 0

rawDescription: Safely parsing user defined equations in Python 3 without eval


code: item["code"] = "{}-{}-{}".format(item["country"], item["region"], item["location"])

rawDescription: concatenating scraped data in scrapy

description: Concatenating scraped data in scrapy


rawDescription: Break out of a Python after loop using a messagebox


rawDescription: Python: print unicode string stored as a variable


code:
rdd.map(lambda x: (float(x), )).toDF(["x"]).registerTempTable("df")

sqlContext.sql("SELECT percentile_approx(x, 0.5) FROM df")

rawDescription: How to find median using Spark

description: Find median using Spark


code:
newcols = df.columns.str.replace(r'\.S_.*','.S_HOLIDAY').unique().tolist()
newcols

rawDescription: Creating new dataframe columns from existing dataframe column names


code:
# whiten them
z = whiten(z)

rawDescription: Using scipy's kmeans2 function in python


code:
next_rows = [[td.get_text(strip=True).encode("utf-8") for td in row('td')]
             for row in headers.find_next_siblings("tr")]

pattern = re.compile(r'^[\d,]+$')
data = [[item for item in l if pattern.match(item)] for l in next_rows]
data = [l for l in data if l]

with open('/home/kwal0203/Desktop/Apple.csv', 'a') as csvfile:
    writer = csv.writer(csvfile, delimiter="|")
    writer.writerows(data)

rawDescription: Using the `.find_next_siblings` function in Beautiful Soup


rawDescription: Python regex matching pattern not surrounded by double quotes


code:
graph = facebook.GraphAPI(fb_user["access_token"])
profile = graph.get_object("me")
user_email = profile["email"]

rawDescription: Integrate facebook login in google app engine with python


code: unique = pd.unique(df[field])

rawDescription: python pandas dataframe unique values appending 'L' to data values

description: Python pandas dataframe unique values appending 'L' to data values


code:
pattern='First name'
[s for s in mylist if re.search(r'\b{}\b'.format(pattern),s)]

rawDescription: Python - Search a list item that contains a string (match case)


code:
def fizz_count(x):
    return x.count('fizz')

rawDescription: python list as function parameter

description: Python list as function parameter


rawDescription: Use pandas (and glob?) to merge numerous (csv) data text files from a directory.


rawDescription: XPath for sub-element's text value in lxml


code:
s=[b'GATC',b'CTAG']
for t in s:
 for c in t:
  print(t,c)

rawDescription: Python 3.4 dictionary output different from python 2.7


code:
with open('/path/to/json_file') as f:
    data = f.read()
url = 'http://mysurl.org'
headers = {'content-type': 'application/json'}
r = requests.post(url, data=data, headers=headers)

rawDescription: python post request json

description: Python post request json


code:
import xml.etree.ElementTree as ET
root = ET.fromstring(raw)
node = root.find(".//hudson.model.StringParameterDefinition")
node.find(".//defaultValue").text = node.find(".//name").text

rawDescription: How to modify a tag text value based on its sibling tag text value in xml with python?

description: Modify a tag text value based on its sibling tag text value in xml with python


code:
def unique_rand():
    for _ in range(5):
        ...
    raise ValueError('Too many attempts to generate the code')

rawDescription: Django unique random as a default value

description: Django unique random as a default value


code:
results = [] # A list of the results that
             # that we will get in the while loop
i=0
x=0
n=0

while x < len(round1):
    n +=1
    results.append(' '.join(map(str,
                                ['match number',
                                n,
                                ':' ,
                                round1[x],
                                scoretop[i],
                                'VS','team:',
                                round1[x+1],scorebottom[i],"\n"])))
    x=x+2
    i=i+1

rawDescription: Python-saving while loop results

description: Python-saving while loop results


code:
from collections import defaultdict

d=defaultdict(list)

dom = parseString(data)
macro=dom.getElementsByTagName('macro')
for node in macro:
    id_name=node.getElementsByTagName('id')[0].toxml()
    id_data=id_name.replace('<id>','').replace('</id>','')
    print (id_data)
    cl_name=node.getElementsByTagName('cl2')[0].toxml()
    cl_data=cl_name.replace('<cl2>','').replace('</cl2>','')
    print (cl_data)
    d[id_data].append(cl_data)

rawDescription: Python: Put values of variables into a new dictionary


code:
mergedgroupdict('(?P<b>.b.)|(?P<i>.i.)', 'abcdefghijk')
mergedgroupdict('(?P<b>.b.)|(?P<i>.i.)', 'abcdefghijk'[::-1])

rawDescription: Possible to retrieve an arbitrary unordered set of named groups in one swoop with Python's re module?


code:
from itertools import chain
from nltk.corpus import wordnet as wn
from difflib import get_close_matches as gcm
possible_adjectives = [k.name for k in chain(*[j.pertainyms() for j in chain(*[i.lemmas for i in wn.synsets('terribly')])])]
gcm('terribly',possible_adjectives)

rawDescription: Getting adjective from an adverb in nltk or other NLP library


code:
myList = [4, 4, 9, 12]

if not any(isPrime(x) for x in myList):
    print("The list did not contain a prime")

rawDescription: "exists" keyword in Python?

description: "exists" keyword in Python


code:
def parse_file(filename):
    f = open(filename, 'rb')
    data = f.read()
    f.close()

    soup = BeautifulSoup(data,features="lxml", from_encoding='utf-8')

    # parse file here

    db_record = MyDBRecord(parsed_data)

    session = get_session() # see below
    session.add(db_record)
    session.commit()

pool = mp.Pool(processes=8)

pool.map(parse_file, ['my_dir/' + filename for filename in os.listdir("my_dir")])

rawDescription: Python multiprocessing pool hangs on map call


code:
import win32serviceutil
serviceName = "openerpservice"
win32serviceutil.StartService(serviceName)

rawDescription: how to create windows services by using python for openerp?

description: Create windows services by using python for openerp


code:
class Torrent(object):
    def __init__(self, fields):
        self.fields = fields #Fields could be ('field1', 'field2')

    def save(self):
        for field in self.fields:
            self.store_to_db(field, getattr(self, field))

rawDescription: change __slots__ dynamically

description: Change __slots__ dynamically


code:
parser.add_argument("-p", "--parameter", type=str, default=None, nargs='+',
                    help="some option",
                    choices=allValues.keys(),
                    metavar='PARAMETER'
                    )

rawDescription: Python: don't display 'choices' with argparse


code:
arb = 4
dicts = [{} for _ in range(arb)]
print(dicts)

rawDescription: How to create an arbitrary number of dictionaries/lists (with different names) in python?

description: Create an arbitrary number of dictionaries/lists (with different names) in python


rawDescription: wxpython button event running before click

description: Wxpython button event running before click


code:
from itertools import tee, islice, izip_longest

data = [1, 2, 3, 4, 5, 6]
iters = [islice(it, n, None) for n, it in enumerate(tee(data, 3))]
res = list(izip_longest(*iters))
# [(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, None), (6, None, None)]

rawDescription: How to loop n items at a time but not stepping only 1 each time? python

description: Loop n items at a time but not stepping only 1 each time? python


code:
people_closer_to_ret = min(people_list,
                           key=lambda people: people.get_remaining_years()),

rawDescription: Python - argmin / argmax for member function


code:
type(g1)
g1.index

rawDescription: Converting a Pandas GroupBy object to DataFrame


code:
ss = ShuffleSplit(X.shape[0], n_iterations=100, test_fraction=0.1,
    random_state=42)

rawDescription: 10*10 fold cross validation in scikit-learn?


rawDescription: How to replace only the first n elements in a numpy array that are larger than a certain value?

description: Replace only the first n elements in a numpy array that are larger than a certain value


rawDescription: Pandas: Generate a histogram/pivot against timeseries data


code:
from collections import Counter
words = Counter('spam ham eggs baz foo bar baz spam ham eggs spam spam bacon eggs ham spam spam spam eggs ham'.split())
words.most_common(3)

rawDescription: Python counter key value

description: Python counter key value


code:
for k in range(10):
    a[k] = td[:]

rawDescription: Changing One dict value changes all values


rawDescription: How to run python in different directory?

description: Run python in different directory


rawDescription: Pandas dataframe get first row of each group


code:
class Post(models.Model):
    user = models.ForeignKey(Profile, related_name='posts')

class Comments(models.Model):
    user = models.ForeignKey(Profile, related_name='comments')
    post = models.ForeignKey(Post, related_name='comments')

class Likes(models.Model):
    user = models.ForeignKey(Profile, related_name='likes')
    post = models.ForeignKey(Post, related_name='likes' )

rawDescription: Django extras() - Logic/algorithm

description: Django extras() - Logic/algorithm


code: fh1, fh2, fh3 = [open(fh.name) for i in range(3)]

rawDescription: Is there a way to shallow copy an existing file-object?


code:
self.server = win32com.client.gencache.EnsureDispatch(driver)
# I can now call the methods on the server object like so....
new_group = self.server.OPCGroups.Add(group)

self._events[group] = win32com.client.WithEvents(
    new_group, GroupEvent)

rawDescription: Register Event callbacks with pywin32

description: Register Event callbacks with pywin32


code: frozenfunc(a='theupdatedvalue')

rawDescription: Freezing Function Arguments

description: Freezing Function Arguments


code:
def per(l):
    if len(l) == 1:
        return [l]
    return [[l[i]] + p for i in range(len(l))for p in per(l[:i] + l [i+1:])]

rawDescription: Permutations in python without libraries


code:
len(l) > 0
len(l)

rawDescription: Python, how to implement a list subclass that evaluates as False if its items evaluate False?


code:
loc_to_incl_sorted = locations_to_include.take(sorted_dist_idcs)
sorted_dist_idcs_to_incl = sorted_dist_idcs[loc_to_incl_sorted]

required_idcs = sorted_dist_idcs_to_incl[:number_required]
selected_data = testdata.take(required_idcs)
selected_alternates = alternatedata.take(required_idcs)

rawDescription: python - combining argsort with masking to get nearest values in moving window

description: Python - combining argsort with masking to get nearest values in moving window


rawDescription: How to set first column to a constant value of an empty np.zeros numPy matrix?

description: Set first column to a constant value of an empty np.zeros numPy matrix


code:
if last_key and tot_cnt > 1:
    sys.stdout.write("%s\t%s\n" % (last_key, tot_cnt))

rawDescription: How to get the Reducer to emit only duplicates

description: Get the Reducer to emit only duplicates


rawDescription: Nested list into a hierarchical dict

description: Nested list into a hierarchical dict


code:
ctypes.c_int * 10
ctypes.c_int * 100

rawDescription: What does (ctypes.c_int * len(x))(*x) do?


code:
import re
def split_it(s):
    pieces = re.split(r'\.(?=\d+,\d+\.)', s)
    pieces[-1:] = pieces[-1].rsplit('.', 1) # split off extension
    return pieces

rawDescription: Python/Regex - Match .#,#. in String

description: Python/Regex - Match .#,#. in String


rawDescription: How does CPython match variables to values?


code: zip(*[a_list[i:] for i in range(3)]) #3 (or 2, 4, 5, etc)is the length of step

rawDescription: Python-How to create a list of N elements from a given list


code:
grouped_dates = [[d, len(list(g))] for d,g in itertools.groupby(list_of_dates, lambda k: k.date())]
dates, counts = grouped_dates.transpose()
counts = counts.cumsum()
step(dates, counts)

rawDescription: Plotting a cumulative graph of python datetimes


code: df = df.set_index('Date')

rawDescription: Using pandas to plot data

description: Using pandas to plot data


code: iconPathName = "C:\myfolder\myicon.ico"

rawDescription: Multiple WindowsBaloonTip / TrayTip Notifications?


code:
def query(data):
    formdata = get_fields()
    formdata.update({
        'ctl00$MainContent$ddRecordsPerPage':'25',
    }) # Hardcode some <select> value
    formdata.update(data)
    res = requests.post(URL, formdata)
    if res.ok:
        page = etree.HTML(res.text)
        return page.xpath('//table[@id="MainContent_SearchControl_grdSearchResultsEntity"]//tr')

rawDescription: How to start a query from a static website?

description: Start a query from a static website


code:
def count_var(word):
    d = defaultdict(int)
    for val in word:
        if val != ' ':  # exclude spaces
            d[val]+=1
    return d

rawDescription: default dict counts for spaces in python

description: Default dict counts for spaces in python


code:
for line in f:
    if line.strip():
        print(line)

rawDescription: Removing all but one newline character from text file using python


rawDescription: How to iterate through a list of strings with different lengths?

description: Iterate through a list of strings with different lengths


rawDescription: How can I plot this data?

description: Plot this data


code:
import win32api
import win32con

win32api.WinExec(
    '{0}\\control.exe Inetcpl.cpl'.format(win32api.GetSystemDirectory()),
    win32con.SW_NORMAL
)

# or

win32api.WinExec('control.exe Inetcpl.cpl', win32con.SW_NORMAL)

rawDescription: How to open Control Panel in python using win32 extension

description: Open Control Panel in python using win32 extension


code:
def inplace_add_concatenation(s):
    res = ''
    for c in s:
        res += c

def str_join_concatenation(s):
    ''.join(s)

rawDescription: python list comprehension vs +=

description: Python list comprehension vs +=


code:
from datetime import datetime
date_format = "%Y-%m-%d %H:%M:%S"
df['datetime'] = [datetime.strptime(dt, date_format) for dt in df['date']]
df['quarter'] = [dt.quarter for dt in df['datetime']]

rawDescription: How can I subset a data frame based on dates, when my dates column is not the index in Python?

description: Subset a data frame based on dates, when my dates column is not the index in Python


code:
T = len(teamlist) + 1
[(i,j) for i in range(T) for j in range(T) if i<j]

rawDescription: Generate pairings within World Cup tournament groups


code:
def a():
    print(a)
a()

rawDescription: Python - Using function in parent from child


code:
import graph_tool.all as gt
g = gt.Graph()

# Initialize property foo with False value
g.vp['foo'] = g.new_vertex_property('bool')

# How many vertices satisfy property foo
sum(g.vp['foo'].a)

rawDescription: Setting default property value in graph_tool


code:
# less transparent
ax1.bar3d(xpos, ypos, zpos, dx , dy ,dz,  color = '#ff0080', alpha = 0.3)
# use dz2, fully opaque, and bluish
ax1.bar3d(xpos, ypos, zpos, dx , dy ,dz2,  color = '#008080', alpha = 1)

rawDescription: Is it possible to superimpose 3-d bar charts in matplotlib?


code:
def ireduce(f, state, it):
    for x in it:
        state = f(state, x)
        yield state

rawDescription: Python list comprehension

description: Python list comprehension


code:
from random import choice
a = [1,2,3]
b = [9]
c = [5,6]
d = [11,12,4]

l=a+b+c+d #ordered candidates

def select():
    e=set(l)
    for s in (a,b,c,d,e,e):              # 4 forced choices and 2 frees.
        e.remove(choice(tuple(s)))       # sets have no index.
    return [x for x in l if x not in e]

rawDescription: How to randomly pick numbers from ranked groups in python, to create a list of specific length

description: Randomly pick numbers from ranked groups in python, to create a list of specific length


code:
for i,j in enumerate(m):
  print ('group {}:{}'.format(i," & ".join([i for i in j if i])))

rawDescription: Regex to extract multiline hash comments


rawDescription: Query HDF5 in Pandas

description: Query HDF5 in Pandas


code:
def some_func():
    return map(other_func, re.finditer(regex, string))

rawDescription: Apply function for objects from "yield from" in python


code:
expression = '{a}*{b}'
values = {'a': 10, 'b': 20, 'c': 30}
expression.format(**values)

rawDescription: Python compiled eval?

description: Python compiled eval


code:
new_file=os.path.splitext(path)[0]+".MOV"
new_file=new_file.split('/',2)
new_file = '/'.join([new_file[0],"newdirectory",new_file[2]])

rawDescription: Fastest way to replace elements of a file's path and extension?


code: {char:i for char,i in zip(ascii_lowercase, range(1,27))}

rawDescription: Iterating over a list while incrementing another variable at the same time


code:
user = User()
get_model_dict(user)

rawDescription: How to get column and values dictionary in SQLAlchemy model?

description: Get column and values dictionary in SQLAlchemy model


code:
import pandas as pd
import numpy as np
import datetime
import collections

d = {'id' : ['4573', '4573', '4573', '958245','958245','958245'] \
 ,'revenue' : np.random.uniform(size=6),'cost' : np.random.uniform(size=6)}
e = ['2014-03-01','2014-04-01','2014-05-01','2014-05-01','2015-03-01','2015-02-01']

dateindex = [datetime.datetime.strptime(a, '%Y-%m-%d') for a in e]

df = pd.DataFrame(d)
df.index = dateindex

#create basic function
def Func(Cost,Revenue):
    if Revenue > Cost > 0:
        return 'A'
    elif  Cost>Revenue>0 :
        return 'B'
    elif Revenue > 0 > Cost:
        return 'C'
    elif Revenue == 0 and Cost > 0:
        return 'D'

#create a function to use on df
def Func_df(df):
    cases_list =  [Func(x,y) for x,y in zip(df.cost.values,df.revenue.values)]
    return collections.Counter(cases_list)

df.groupby('id').apply(Func_df)

rawDescription: comparing two columns within same dataframe and computing statistics from comparison

description: Comparing two columns within same dataframe and computing statistics from comparison


code:
s = "5-9-90-15"    # fails with the third number
vals = [int(x) for x in s.split('-')]
all(x > L and x < U for x, L, U in zip(vals, lb, ub))

rawDescription: Using Python re.search to find range of numbers


code:
import pandas as pd
import numpy as np

np.random.seed(5)
strings = list('AB')
data = [strings[i] for i in np.random.randint(0, 2, 15)]
index = pd.date_range('2/2/2012', periods=15, freq='T')
dfm = pd.DataFrame(data={'event': data}, index=index)

begin = dfm.loc[dfm['event'] == 'A'].index
cutoffs = dfm.loc[dfm['event'] == 'B'].index

idx = cutoffs.searchsorted(begin)
mask = idx < len(cutoffs)
idx = idx[mask]
begin = begin[mask]
end = cutoffs[idx]

result = pd.DataFrame({'begin':begin, 'end':end})

rawDescription: Time between events (pandas)

description: Time between events (pandas)


code:
class Fruit(object):
    def __init__(self, name, colour, shape):
        self.name = name
        self.colour = colour
        self.shape = shape

rawDescription: Python List as variable name

description: Python List as variable name


code:
name = 'John'
string = 'hello %s! You owe 10%%.' % (name)
string

rawDescription: Python Using (%s) in a string that slo contains a (%)?


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

fig, ( ax1, ax2, ax3 , ax4) = plt.subplots( figsize=(18.0, 11.0) , nrows=4, ncols=1)

## some fake stand-alone data
days = 365 * 5
dates = [datetime.datetime(2000, 1, 1, 0, 0) + datetime.timedelta( day - 1) for day in range(days)]
data_series = np.random.rand( days )
data_series2 = [np.sin(x * 2 * np.pi / 365 ) + np.random.rand(1) * 0.1 for x in range( days ) ]

######  Plots made up temperatures
ax4.set_frame_on(False)
ax4.plot_date( dates , data_series2 , color="black", ls="solid", lw=2, ms=0 )

# I move the subplot_adjust here before you create ax5
fig.subplots_adjust(right=0.8)

# Now on the same plot try to add som precipitation as a plot
ax5 = fig.add_axes(ax4.get_position() , frameon=True, zorder = -10.0)
ax5.bar( dates, data_series, edgecolor="blue", zorder = -10.0 )
ax5.xaxis_date()

# gets rid of bar-plot labels
ax5.set_xticks([]); ax5.set_yticks([])

plt.show()

rawDescription: What is subplot_adjust() doing to pyplot axes?


code:
keys_to_copy = ['sword']
inventory.update(((key, chest[key]) for key in keys_to_copy))
inventory

rawDescription: Adding items to dictionary from a dictionary


code:
def players(request):
    players_in_team_one = Player.objects.filter(Team__pk = 1)
    return render_to_response('players.html', {'players': players_in_team_one})

rawDescription: Django Views Join Models Using Foreign Key


code:
import urllib2

response = urllib2.urlopen(theurl)
with open(local_filename, 'w') as dl:
    dl.write(response.read())

rawDescription: Python: How to suppress the output of os.system


code:
from __future__ import division
import os
import zipfile
import threading
import time
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.network.urlrequest import UrlRequest

ZIP_URL = 'https://www.python.org/ftp/python/3.5.1/python-3.5.1-embed-win32.zip'
ZIP_FILENAME = 'Python351.zip'

kv_string = """
<RootWidget>
    BoxLayout:
        orientation: "vertical"
        Button:
            id: download_button
            text: "Download content"
            on_press: self.parent.parent.download_content()
        ProgressBar:
            id: download_progress_bar
            max: 1
            value: 0
"""

Builder.load_string(kv_string)

class RootWidget(BoxLayout):

    stop = threading.Event()

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)

    def download_content(self):
        self.ids["download_button"].disabled = True
        req = UrlRequest(ZIP_URL, on_progress=self.update_progress,
                         chunk_size=1024, on_success=self.unzip_content,
                         file_path=ZIP_FILENAME)

    def update_progress(self, request, current_size, total_size):
        self.ids['download_progress_bar'].value = current_size / total_size

    def unzip_content(self, req, result):
        threading.Thread(target=self.unzip_thread).start()

    def unzip_thread(self):
        print("Unzipping file")
        fh = open(ZIP_FILENAME, 'rb')
        z = zipfile.ZipFile(fh)
        ZIP_EXTRACT_FOLDER = ZIP_FILENAME + '_extracted'
        if not os.path.exists(ZIP_EXTRACT_FOLDER):
            os.makedirs(ZIP_EXTRACT_FOLDER)
        z.extractall(ZIP_EXTRACT_FOLDER)
        fh.close()
        os.remove(ZIP_FILENAME)
        time.sleep(4) # DEBUG: stretch out the unzip method to test threading

        print("Done")

class MyApp(App):

    def on_stop(self):
        # The Kivy event loop is about to stop, set a stop signal;
        # otherwise the app window will close, but the Python process will
        # keep running until all secondary threads exit.
        self.root.stop.set()

    def build(self):
        return RootWidget()

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

rawDescription: Download file with Kivy app without locking event loop


code:
# To save the slice `df.iloc[1:, :]` to disk:
filename = '/tmp/test.h5'
with pd.HDFStore(filename) as store:
    store['mydata'] = df.iloc[1:, :]

# To load the DataFrame from disk:
with pd.get_store(filename) as store:
    newdf2 = store['mydata']
    print(newdf2.dtypes)
    print(newdf2)

rawDescription: Can't set appropriate dtypes reading from a Numpy array


code:
fruit_list = ['apple', 'banana', 'peach', 'plum', 'pineapple', 'kiwi']
fruit = re.compile('|'.join(fruit_list))

rawDescription: how to do re.compile() with a list in python

description: Do re.compile() with a list in python


code:
((name, position, emp_id, tasks)
for (name, position, emp_id), (position2, tasks)
in itertools.product(ListA, ListB)
if position == position2)

rawDescription: Combine two lists based on a column

description: Combine two lists based on a column


code: payments_form = PaymentsForm(10)

rawDescription: Django - Repeating a form field n times in one form


code:
import subprocess
process=subprocess.Popen((os.getcwd() + "/3rd_party_binary","--subprocess"))
process.poll() # is running?

rawDescription: Executable path to Mac App

description: Executable path to Mac App


code:
render(request,
              'my_page.html',
              {'my_form': my_form1})

rawDescription: Django form names

description: Django form names


code:
text = "fox The quick brown fox jumps over the fox! lazy dog. fox!."
links = {'fox': [], 'dog': []}

from string import punctuation
def yield_words(s,d):
    i = 0
    for ele in s.split(" "):
        tot = len(ele) + 1
        ele = ele.rstrip(punctuation)
        ln = len(ele)
        if ele in d:
            d[ele].append((i, ln + i))
        i += tot
    return d

rawDescription: Positions of substrings in string

description: Positions of substrings in string


code:
freq = df_onegram.set_index(['onegram'])['frequency']
sum_freq_onegrams = df_multigram['multigram'].str.split().apply(
    lambda x: pd.Series(x).map(freq).sum())

rawDescription: Break pandas DataFrame column into multiple pieces and combine with other DataFrame


code:
import re

uriList = [
        'sip:192.1.2.3',
        'sip:123@192.1.2.3',
        'sip:192.1.2.3:5060',
        'sip:123@[2620:0:2ef0:7070:250:60ff:fe03:32b7]',
        'sip:[2620:0:2ef0:7070:250:60ff:fe03:32b7]',
        'sip:[2620:0:2ef0:7070:250:60ff:fe03:32b7]:5060',
        'sips:support@voip.example.com',
        'sip:22444032@voip.example.com:6000',
        'sip:support:pass@212.123.1.213',
        'sip:support:pass@212.123.1.213;urlparams=test',
        'sip:support:pass@212.123.1.213?auth=basic',
        'sip:support:pass@212.123.1.213;urlparams=test?auth=basic',
        ]

mPattern = re.compile(
                        '(?P<scheme>\w+):' #Scheme
                        +'(?:(?P<user>[\w\.]+):?(?P<password>[\w\.]+)?@)?' #User:Password
                        +'\[?(?P<host>' #Begin group host
                            +'(?:\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})|' #IPv4 address Host Or
                            +'(?:(?:[0-9a-fA-F]{1,4}):){7}[0-9a-fA-F]{1,4}|' #IPv6 address Host Or
                            +'(?:(?:[0-9A-Za-z]+\.)+[0-9A-Za-z]+)'#Hostname string
                        +')\]?:?' #End group host
                        +'(?P<port>\d{1,6})?' #port
                        +'(?:\;(?P<params>[^\?]*))?' # parameters
                        +'(?:\?(?P<headers>.*))?' # headers
                        )
groupNamesList = ['scheme', 'user', 'password', 'host', 'port', 'params', 'headers'] #List of group Names

for uri in uriList: #iterate through the list of uri
    mObject = mPattern.search(uri) #pattern search
    if mObject: #if you find a match
        groupStrings = [mObject.group(groupName) if mObject.group(groupName) else '' for groupName in groupNamesList] #extract your groupStrings
        print('Scheme: {0}, User: {1}, Password: {2}, Host: {3}, Port: {4}, Params: {5}, Headers: {6}'.format(*groupStrings)) #print groupStrings

rawDescription: Python Regular Expression for SIP URI variables? [SOLVED]


code:
#...
self.new_stats[tour].setdefault(pname,{}).setdefault(y,{}).setdefault(cat,{})[prop] = val
#...

rawDescription: How to clean up deeply nested dictionary access?

description: Clean up deeply nested dictionary access


code: df['new_field'] = np.where(df['field1'] > 0, df['field2'], 0)

rawDescription: Python pandas: banal apply statements incredibly slow


code: yield Request(url, method="HEAD", callback=self.callback)

rawDescription: Scrapy - getting the the file size and type from a URL without downloading the file?


code:
li = [(1, 2), (1, 3), (2, 3)]
map(sum, li)
type(map(sum, li))
list(map(sum, li))

rawDescription: Sum of elements stored inside a tuple

description: Sum of elements stored inside a tuple


rawDescription: How to use bisect to search in a compute-when-need array

description: Use bisect to search in a compute-when-need array


rawDescription: Doubling the matrix in numpy

description: Doubling the matrix in numpy


code:
import threading, time

def askForInput(arg):
    arg.append("some ID")
    time.sleep(2)

def main():
    print("starting time: {}".format(time.asctime()))
    my_input = []  # want an argument we can mutate
    thr = threading.Thread(target=askForInput, args=(my_input,))
    thr.start()
    thr.join()  # will wait here
    lookupID = my_input[0]
    print("ending time: {}".format(time.asctime()))
    print("Result back from async call: {}".format(lookupID))

if __name__ == '__main__':
    main()

rawDescription: Refactoring legacy synchronous Python code


rawDescription: Mixed usage of UTF-8 and ASCII encodings?


code: newBuf[i] = xorPad[(i + baseByteTableIndex) & 2047]

rawDescription: Can't reproduce working C bitwise encoding function in Python


code: print("['"+"', '".join(item for item in test_list) + "']")

rawDescription: Python list items encoding

description: Python list items encoding


rawDescription: Counter with filter or subtract or similar


rawDescription: How can I get 2.x-like sorting behaviour in Python 3.x?

description: Get 2.x-like sorting behaviour in Python 3.x


code:
import numpy as np

def bar():
    """Return 3x3 square array."""
    return np.arange(9).reshape(3, 3)

rawDescription: Delete modules to clean namespace?

description: Delete modules to clean namespace


code:
def findblock( lines, start='The text I want is set off by something distinctive',
                      stop='The end is also identifiable by something distinctive'):
    for line in lines:
        inblock = False
        if line==start:
            inblock=True
        if line==stop:
            inblock=False # or return mb?
        if inblock:
            yield line

themasterlist = [list(findblock( file )) for file in files]

rawDescription: How can I focus on a subset of a list in python

description: Focus on a subset of a list in python


code: cols_to_use = df2.columns - df.columns

rawDescription: Pandas Merge - How to avoid duplicating columns


code:
import numpy as np
from sklearn.ensemble import RandomForestRegressor as RFR

# Create a random number generator so this example is repeatable
rs = np.random.RandomState(seed=1234)

# create 100 fake input variables with 10 features each
X = rs.rand(100, 10)
# create 100 fake response variables
Y = rs.rand(100)

rfr = RFR(random_state=rs)
rfr.fit(X, Y)

fi = rfr.feature_importances_
# argsort the feature importances and reverse to get order of decreasing importance
indices = argsort(fi)[::-1]

rawDescription: Python Slicing Numpy Array according to feature_importances_


code:
class Genre(models.Model):
    ...
    class Meta:
        app_label = _(u'films') #app's name
        ...

rawDescription: When to split sub-apps into new apps

description: When to split sub-apps into new apps


code:
def shutdown():
    if config.SHUTDOWN_ALLOWED:
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
            raise RuntimeError('Not running with the Werkzeug Server')
        func()

        return 'Server shutting down...'

rawDescription: Running flask server, nosetests and coverage


rawDescription: splitting one csv into multiple files in python

description: Splitting one csv into multiple files in python


code:
filelist = ['book1.csv','book2.csv','book3.csv','book4.csv']
openfiles = []
for filename in filelist:
    openfiles.append(open(filename,'rb'))

# Use first file in the list as the master
# All files must have same number of lines (or greater)
masterfile = openfiles.pop(0)

with (open('output.csv','w')) as outputfile:
    for line in masterfile:
        outputlist = [line.strip()]
        for openfile in openfiles:
            outputlist.append(openfile.readline().strip())
        outputfile.write(str.join(',', outputlist)+'\n')

masterfile.close()
for openfile in openfiles:
    openfile.close()

rawDescription: Python combine rows from different files into one data file


code: [self.x, self.y][x]=y

rawDescription: __setitem__ implementation in Python for Point(x,y) class


code: d = {k: v for k in dicts[0] for v in [sum(d[k] for d in dicts)]}

rawDescription: Sum corresponding elements of multiple python dictionaries


code: r'artistName:Axwell /\\ Ingrosso'

rawDescription: Escaping backslash in Python requests

description: Escaping backslash in Python requests


code:
import itertools
lst = [(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (3, 'e')]
lst.sort(key=lambda x: x[0])
new_lst = [list(v) for k,v in itertools.groupby(lst,key=lambda x:x[0])]
new_lst

rawDescription: Python tuple list

description: Python tuple list


code: "Hello" "World"

rawDescription: Why does Python's print function act this way?


code: type(d.ix[0, 'Prize_Pool'])

rawDescription: Python data wrangling issues

description: Python data wrangling issues


code:
hits = []
for idx, first_dic in enumerate(set_of_pk_values[:-1]):
    hits += (first_dic['someKey'], filter(lambda dic: dic['someKey'] == first_dic['someKey'], set_of_pk_values[idx:1]) )

rawDescription: Python Nested For Loop Array Comparison - Possibility of Optimization?


rawDescription: GTK - How to style a button in headerbar?


rawDescription: python strip function is not giving expected output

description: Python strip function is not giving expected output


rawDescription: Merge two or more lists with given order of merging


code:
even = range(1,10,2)
even
odd = range(1,10,2)
odd
tens = range(0,101,10)
tens

rawDescription: Variables and Assign range to it in Python


code:
# Get sorting indices for reference
sort_idx = np.argsort(reference)

# Sort reference and get searchsorted indices for data in reference
pos = np.searchsorted(reference[sort_idx], data, side='left')

# Change pos indices based on sorted indices for reference
out = np.argsort(reference)[pos]

rawDescription: Classify elements of a numpy array using a second array as reference


rawDescription: How do I test a django database schema?

description: Test a django database schema


code:
for l in content:
    rep = l.strip('"').replace(',','')
    words = rep.split()
    loc = words[-1]
    uni = ' '.join(words[:-1])
    print(uni, loc)

rawDescription: how to get string values using index method in Python

description: Get string values using index method in Python


code:
from __future__ import print_function

df = pd.read_csv('f123_dates.csv', index_col=0, parse_dates=[0, 1],
                 delim_whitespace=True)
df2 = df.groupby([df.index, df.Time.dt.hour]).agg(['mean','sum'])
df3 = df2.reset_index()
df3.columns = [' '.join(col).strip() for col in df3.columns.values]
print(df3.to_csv(columns=df3.columns, index=False))

rawDescription: How to groupby two fields in pandas?

description: Groupby two fields in pandas


code: obj.location = location_dict[i]

rawDescription: more efficient Python scripting in Blender3D

description: More efficient Python scripting in Blender3D


rawDescription: Difficulty in finding the Region names in AWS rds


rawDescription: Creating a lib directory in Google App Engine and adding it to sys.path


code:
I,J = np.where(mask)
valid_dst = dst[mask]

rawDescription: Python how to loop through an array in numpy at C speed and store some positions


rawDescription: Convert pandas json for highstock data format in a angularjs controller


rawDescription: For loop troubleshooting

description: For loop troubleshooting


code:
def AcumulacionCelda(x,y):
    if Acum[x, y] != NoData:
        return
    Acum[x, y] = 1
    d = {(-1, -1):  4,
         (-1, 0) :  5,
         (-1, 1) :  6,
         (0, -1) :  3,
         (0, 0)  : 'dummy',
         (0, 1)  :  7,
         (1, -1) :  2,
         (1, 0)  :  1,
         (1, 1)  :  8}
    keys = tuple(product(range(-1,2), range(-1,2)))[::-1]
    queue = [('Loop', (x, y), list(keys))]

    while queue:
        instruction, coords, directions = queue.pop()
        x, y = coords
        if instruction == 'Loop':
            while directions:
                m, n = directions.pop()
                if Direcciones[x+m, y+n] == d[m, n]:
                    queue.append(('Loop', (x, y), directions))
                    queue.append(('Add', (x, y), (m, n)))
                    if Acum[x+m, y+n] == NoData:
                        Acum[x+m, y+n] = 1
                        queue.append(('Loop', (x+m, y+n), list(keys)))
                    break
        elif instruction == 'Add':
            m, n = directions
            Acum[x, y] += Acum[x+m, y+n]

rawDescription: Convert a recursive function into Non recursive in Python


code:
TableA
- id
- field1
- field2
- field3

TableB
- id
- field4
- field5
- field6

rawDescription: Connecting a one to many with three tables?


code:
x, y = m(lon, lat)
x1, y1 = m(lon+u, lat+v)
u_map, v_map = x1-x, y1-y

rawDescription: How can I rotate vectors onto a Basemap map projection?

description: Rotate vectors onto a Basemap map projection


code:
L = ['abc','def','ghi']

with open('outfile.txt', 'w') as outfile:
    for e in L:
        print (e, file=outfile)

rawDescription: Write data retrieved from for loop

description: Write data retrieved from for loop


rawDescription: Is there a dedicated milli-sec precision timestamp data structure in python pandas?


code:
# Do this when using PyMEL for your UI code
import pymel.core as pm

# ...

with pm.rowColumnLayout( numberOfColumns = 5 ):
    pm.text( label="", width = 1 )
    pm.text( label="Column 1", enable = False, width = 250 )
    pm.text( label="", width = 1 )
    pm.text( label="Column 2", enable = False, width = 250 )
    pm.text( label="", width = 1 )

    pm.text( label="" )

    with pm.rowColumnLayout( numberOfColumns = 4 ):
        pm.text( label="   Input data:", align="left" )
        pm.text( label="" )
        pm.text( label="" )
        pm.text( label="" )
        pm.textField( text = "Text here" )
        pm.text( label="" )
        pm.text( label="" )
        pm.text( label="" )

    pm.text( label="" )
    with pm.rowColumnLayout( numberOfColumns = 4 ):
        with pm.rowColumnLayout( numberOfColumns = 5 ):
            pm.radioButton( label = "Read file from path", width = 100 )
            pm.text( label="" )
            pm.button( label = "Browse" )
            pm.text( label="" )
            pm.button( label = "Validate" )

        pm.text( label="" )
        pm.text( label="" )
        pm.text( label="" )

rawDescription: Is there a way to indent Python without affecting the code


code:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

def multipage(filename, figs=None, dpi=200):
    pp = PdfPages(filename)
    if figs is None:
        figs = [plt.figure(n) for n in plt.get_fignums()]
    for fig in figs:
        fig.savefig(pp, format='pdf')
    pp.close()

rawDescription: Saving all open matplotlib figures in one file at once


rawDescription: Find duplicates in a list of lists with tuples


code:
key,val = line.split("=", 1)
constantsMap[key] = val

rawDescription: Using a list as key-value pair to be inserted


code:
def get_key_or_val_itms(dct, wanted):
    # dict as [(key, val), (key2, val2), ...]
    tpldct = dct.items()
    # find tuples, where either key or val equals `wanted` value
    # first make function, which detects, the tuple we search for

    def tuple_wanted(tpl):
        return wanted in tpl
    # now use it to filter only what we search for
    restpldct = filter(tuple_wanted, tpldct)
    # finally, turn the result into dict
    return dict(restpldct)

rawDescription: Python - using dictionary to count keys and values


rawDescription: How to convert PlayJSON list to Scala Map (complex)?

description: Convert PlayJSON list to Scala Map (complex)


code: sorted( ((v,k) for k,v in d.iteritems()), reverse=True)

rawDescription: Print a dict sorted by values

description: Print a dict sorted by values


code:
vals = parameter.values()
product(vals[0], vals[1], vals[2], ..., vals[len(vals)])

rawDescription: How to write a recursion function for all the possible parameter combinations in python

description: Write a recursion function for all the possible parameter combinations in python


code:
from clip import write_to_clipboard
try:
    while True:
        write_to_clipboard(raw_input())
except KeyboardInterrupt:
    pass

rawDescription: How do I use Tkinter and allow my application to keep the focus?

description: Use Tkinter and allow my application to keep the focus


code:
pivot_table = unified_df.pivot_table(index=['id', 'contact_id'],
                                     columns='question',
                                     values='response_answer',
                                     aggfunc=lambda x: ' '.join(x))

rawDescription: Pivoting a Pandas Dataframe containing strings - 'No numeric types to aggregate' error


code:
prepos = ["foo", "bar", "baz"]
p = re.compile(r"\b(" + "|".join(prepos) + r")\b")
p.sub("---", "foo XfooX bar YbarY baz ZbazZ")
# => '--- XfooX --- YbarY --- ZbazZ'

rawDescription: How to use \b or ^ alongwith pattern to replace complete word?

description: Use \b or ^ alongwith pattern to replace complete word


code:
def test_conditions(obj, a=5, b=None):
    if obj.a <= a:
        return False
    if b is not None and obj.b <= b:
        return False
    return True

rawDescription: Python - adding conditions in if only they are specified (domain)?


code:
d1 = { 'a':1, 'b':2, 'c': 3}
d2 = { 'b':2 ,'c':3, 'd': 1}
result = []

result += [ { 'key': key, 'value': d1[key] } for key in d1 ]
result += [ { 'key': key, 'value': d2[key] } for key in d2 ]

rawDescription: Merging of two dictionaries

description: Merging of two dictionaries


code:
def search_sequence_numpy(arr,seq):
    """ Find sequence in an array using NumPy only.

    Parameters
    ----------
    arr    : input 1D array
    seq    : input 1D array

    Output
    ------
    Output : 1D Array of indices in the input array that satisfy the
    matching of input sequence in the input array.
    In case of no match, empty list is returned.
    """

    # Store sizes of input array and sequence
    Na, Nseq = arr.size, seq.size

    # Range of sequence
    r_seq = np.arange(Nseq)

    # Create 2D array of sliding indices across entire length of input array.
    # Match up with the input sequence & get the matching starting indices.
    M = (arr[np.arange(Na-Nseq+1)[:,None] + r_seq] == seq).all(1)

    # Get the range of those indices as final output
    if M.any>0:
        return np.where(np.convolve(M,np.ones((Nseq),dtype=int))>0)[0]
    else:
        return []         # No match found

rawDescription: Searching a sequence in a NumPy array

description: Searching a sequence in a NumPy array


code:
import numpy as np

a = np.loadtxt("test.txt")

odd = []
even = []

for ele in a:
    if ele % 2 == 0:
        even.append(ele)
    else:
        odd.append(ele)

rawDescription: Separate odd and even numbers into different output files


rawDescription: Create an icon in memory with win32 in python


code:
frame.reindex(list(product(*map(tuple, frame.index.levels)))).values\
     .reshape(map(len, frame.index.levels))

rawDescription: Transform Pandas DataFrame with n-level hierarchical index into n-D Numpy array


code:
import sys

arg1,arg2 = sys.argv[1:3]

myfunc(arg1,arg2)

rawDescription: Passing variables when invoking a Python script


code:
import numpy as np
arr = np.arange(8).reshape(2, 2, 2)
arr
arr*arr

rawDescription: How to make a matrix of arrays in numpy?

description: Make a matrix of arrays in numpy


code:
sql = '''
    SELECT date, price
    FROM prices
    WHERE date IN ({s})
        AND id = ?'''.format(s={','.join(['?']*len(dates))})
curs.execute(sql,dates + [id])

rawDescription: Query Sqlite for multiple arguments at once and handling missing values


code:
import numpy
x = numpy.array((1.5,), dtype=numpy.double)
x[0]
x.dtype=numpy.dtype("uint64")
x[0]
hex(x[0])

rawDescription: Copying internal formats float64 uint64

description: Copying internal formats float64 uint64


code:
f = open("/tmp/out", "r")
fd = f.fileno()
fcntl.fcntl(fd, fcntl.F_SETFL, flag | os.O_NONBLOCK)

rawDescription: python Non-block read file

description: Python Non-block read file