Popular recipes tagged "meta:loc=39"http://code.activestate.com/recipes/tags/meta:loc=39/2017-05-06T20:53:54-07:00ActiveState Code RecipesPython-C-Interface: Check whether a given dictionary contains only valid keys (C)
2017-05-06T20:53:54-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580799-python-c-interface-check-whether-a-given-dictionar/
<p style="color: grey">
C
recipe 580799
by <a href="/recipes/users/4193772/">Jorj X. McKie</a>
(<a href="/recipes/tags/c_interface/">c_interface</a>, <a href="/recipes/tags/python/">python</a>).
</p>
<p>This function is given a Python dictioanry and a list of string / unicode values. It will check whether all dictionary keys occur in this list and will return 1 (true) or 0 (false).</p>
Python add/set attributes to list (Python)
2015-09-29T16:28:46-07:00webby1111http://code.activestate.com/recipes/users/4192908/http://code.activestate.com/recipes/579103-python-addset-attributes-to-list/
<p style="color: grey">
Python
recipe 579103
by <a href="/recipes/users/4192908/">webby1111</a>
(<a href="/recipes/tags/attributes/">attributes</a>, <a href="/recipes/tags/class/">class</a>, <a href="/recipes/tags/dictionary/">dictionary</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/subclass/">subclass</a>).
Revision 3.
</p>
<h4 id="python-attribute-listhttpsgithubcomwebby1111python-attribute-list"><a href="https://github.com/webby1111/Python-Attribute-List">Python Attribute List</a></h4>
<p>Add/set attributes to python lists.</p>
<p>A google search for "add attributes to python lists" yields no good stackoverflow answer,
hence the need for this.</p>
<p>Useful for machine learning stuff where you need labeled feature vectors. </p>
<p>This technique can be easily adapted for other built-ins (e.g. int).</p>
<h5 id="the-problem">The Problem</h5>
<pre class="prettyprint"><code>a = [1, 2, 4, 8]
a.x = "Hey!" # AttributeError: 'list' object has no attribute 'x'
</code></pre>
<h5 id="the-solution">The Solution</h5>
<pre class="prettyprint"><code>a = L(1, 2, 4, 8)
a.x = "Hey!"
print a # [1, 2, 4, 8]
print a.x # "Hey!"
print len(a) # 4
# You can also do these:
a = L( 1, 2, 4, 8 , x="Hey!" ) # [1, 2, 4, 8]
a = L( 1, 2, 4, 8 )( x="Hey!" ) # [1, 2, 4, 8]
a = L( [1, 2, 4, 8] , x="Hey!" ) # [1, 2, 4, 8]
a = L( {1, 2, 4, 8} , x="Hey!" ) # [1, 2, 4, 8]
a = L( [2 ** b for b in range(4)] , x="Hey!" ) # [1, 2, 4, 8]
a = L( (2 ** b for b in range(4)) , x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ** b for b in range(4) )( x="Hey!" ) # [1, 2, 4, 8]
a = L( 2 ) # [2]
</code></pre>
Jump (Batch)
2013-08-08T09:18:31-07:00greg zakharovhttp://code.activestate.com/recipes/users/4184115/http://code.activestate.com/recipes/578627-jump/
<p style="color: grey">
Batch
recipe 578627
by <a href="/recipes/users/4184115/">greg zakharov</a>
(<a href="/recipes/tags/dirjump/">dirjump</a>, <a href="/recipes/tags/jscript/">jscript</a>, <a href="/recipes/tags/regjump/">regjump</a>).
</p>
<p>How does it work? Just input registry key or folder path after script name. Note that script works well on WinXP and has not been tested on higher Win systems. Also you should know that if regedit has been launched then when you trying access another key it always starts with another window of regedit. Explorer has the same behaviour with this script. You can jump to HKCR, HKCU and HKLM branches but if you need more, please edit script manually :) For folders jump you should input full or relative path. For example: jump \doc or jump . or jump E:\fotos</p>
Peek at Python value stack (Python)
2013-01-08T22:15:21-08:00Dima Tisnekhttp://code.activestate.com/recipes/users/4068698/http://code.activestate.com/recipes/578412-peek-at-python-value-stack/
<p style="color: grey">
Python
recipe 578412
by <a href="/recipes/users/4068698/">Dima Tisnek</a>
(<a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/stack/">stack</a>).
</p>
<p>Poking at value stack, a.k.a. evaluation stack is not allowed in Python, however everything is doable with ctypes.</p>
<p>I think this could be useful in debugging complex statements.</p>
Saving a Tkinter canvas image or animation using PIL (Python)
2012-03-05T04:09:00-08:00J W Jhttp://code.activestate.com/recipes/users/4181154/http://code.activestate.com/recipes/578063-saving-a-tkinter-canvas-image-or-animation-using-p/
<p style="color: grey">
Python
recipe 578063
by <a href="/recipes/users/4181154/">J W J</a>
(<a href="/recipes/tags/borderless/">borderless</a>, <a href="/recipes/tags/canvas_save/">canvas_save</a>, <a href="/recipes/tags/imagegrab/">imagegrab</a>).
Revision 2.
</p>
<p>Demonstrates saving an animation done on Tkinter canvas as a series of jpeg images</p>
Multidimensional arrays (Ruby)
2012-11-19T08:43:11-08:00greg zakharovhttp://code.activestate.com/recipes/users/4184115/http://code.activestate.com/recipes/578338-multidimensional-arrays/
<p style="color: grey">
Ruby
recipe 578338
by <a href="/recipes/users/4184115/">greg zakharov</a>
(<a href="/recipes/tags/array/">array</a>, <a href="/recipes/tags/ironruby/">ironruby</a>, <a href="/recipes/tags/multidimensional/">multidimensional</a>).
</p>
<p>The next example shows how to create rectangular and jagged arrays.</p>
FeatureClassRandomizer (Python)
2012-08-07T15:35:23-07:00Dale Lindemanhttp://code.activestate.com/recipes/users/4183096/http://code.activestate.com/recipes/578237-featureclassrandomizer/
<p style="color: grey">
Python
recipe 578237
by <a href="/recipes/users/4183096/">Dale Lindeman</a>
(<a href="/recipes/tags/randomization/">randomization</a>, <a href="/recipes/tags/random_number/">random_number</a>).
</p>
<p>Generates a randomized list of unique IDs and iteratively assigns values to features in a featureclass.</p>
Python Viewer (Python)
2012-07-02T22:29:27-07:00Stephen Chappellhttp://code.activestate.com/recipes/users/2608421/http://code.activestate.com/recipes/578181-python-viewer/
<p style="color: grey">
Python
recipe 578181
by <a href="/recipes/users/2608421/">Stephen Chappell</a>
(<a href="/recipes/tags/archive/">archive</a>, <a href="/recipes/tags/cgi/">cgi</a>, <a href="/recipes/tags/old/">old</a>, <a href="/recipes/tags/viewer/">viewer</a>).
</p>
<p>This was a CGI experiment from many years ago for viewing Python files on a server. This is committed for archival to be run under Python 2.5 or later versions.</p>
subtract or add a month to a datetime.date or datetime.datetime (Python)
2010-06-25T18:41:19-07:00Trent Mickhttp://code.activestate.com/recipes/users/4173505/http://code.activestate.com/recipes/577274-subtract-or-add-a-month-to-a-datetimedate-or-datet/
<p style="color: grey">
Python
recipe 577274
by <a href="/recipes/users/4173505/">Trent Mick</a>
(<a href="/recipes/tags/date/">date</a>, <a href="/recipes/tags/datetime/">datetime</a>, <a href="/recipes/tags/month/">month</a>).
</p>
<p>Adding or subtracting a month to a Python <code>datetime.date</code> or <code>datetime.datetime</code> is a little bit of a pain. Here is the code I use for that. These functions return the same datetime type as given. They preserve time of day data (if that is at all important to you).</p>
<p>See also: </p>
<ul>
<li><a href="http://code.activestate.com/recipes/476197/">Recipe 476197</a>: First / Last Day of the Month.</li>
<li><a href="http://packages.python.org/MonthDelta/">monthdelta module</a></li>
</ul>
Flattening an arbitrarily deep list (or any iterator) (Python)
2012-04-03T17:13:35-07:00Garretthttp://code.activestate.com/recipes/users/4181290/http://code.activestate.com/recipes/578092-flattening-an-arbitrarily-deep-list-or-any-iterato/
<p style="color: grey">
Python
recipe 578092
by <a href="/recipes/users/4181290/">Garrett</a>
(<a href="/recipes/tags/flatten/">flatten</a>, <a href="/recipes/tags/iterator/">iterator</a>, <a href="/recipes/tags/itertools/">itertools</a>, <a href="/recipes/tags/list/">list</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/tuple/">tuple</a>).
Revision 6.
</p>
<p>What if you had a list like this: [1, -10, [1,2,[3,4]], xrange(200)], and you just wanted to go through each element in order (wanted it to return a simple list of [1,-10,1,2,3,4,1,2,3,4...199])</p>
<p>I've seen a couple of attempts to flatten arbitrarily deep lists. Many of them involve recursion, like this one: <a href="http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html" rel="nofollow">http://rightfootin.blogspot.com/2006/09/more-on-python-flatten.html</a></p>
<p>Recursion is generally considered non-pythonic (at least to my knowledge), so I have used one which just involves simple iterators instead. Also, recursion will fail if the list is too deep (so it wouldn't really be arbitrary, would it?).</p>
Using IviScope Instrument driver with Python (Python)
2012-03-29T17:17:26-07:00Pierre Cladéhttp://code.activestate.com/recipes/users/4181504/http://code.activestate.com/recipes/578089-using-iviscope-instrument-driver-with-python/
<p style="color: grey">
Python
recipe 578089
by <a href="/recipes/users/4181504/">Pierre Cladé</a>
.
</p>
<p>This recipe shows how to use the IVI-COM interface of a scope. The example is based on a Tektronix scope using the tkdpo2k3k4k driver. Two examples are given : the first using the IviScope interface (limited interface to the scope, but with full compatibility) and the Tkdpo2k3k4k interface (specific to Tektronix).</p>
For Characters in a String, Replace with Character (Python)
2012-03-23T20:44:23-07:00Andrew Yurisichhttp://code.activestate.com/recipes/users/4180867/http://code.activestate.com/recipes/578086-for-characters-in-a-string-replace-with-character/
<p style="color: grey">
Python
recipe 578086
by <a href="/recipes/users/4180867/">Andrew Yurisich</a>
(<a href="/recipes/tags/character/">character</a>, <a href="/recipes/tags/replace/">replace</a>, <a href="/recipes/tags/substitute/">substitute</a>, <a href="/recipes/tags/text/">text</a>).
Revision 9.
</p>
<p>Useful if you need to replace many different characters with all of the same character. Can accept an unlimited number of request to replace.</p>
<p>Does not work with words, only characters. You can, however, replace single characters with words. I may go back and re-implement it using tuples for the keys, but this would make searching the text for any matches pretty expensive, I'd imagine. At that point, it's mostly a job for a regex, and those tools already exist.</p>
Lazy Dynamic Binding on Classes (You'll Never Go Back) (Python)
2011-08-12T23:42:27-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577745-lazy-dynamic-binding-on-classes-youll-never-go-bac/
<p style="color: grey">
Python
recipe 577745
by <a href="/recipes/users/4177816/">Eric Snow</a>
(<a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/decorators/">decorators</a>, <a href="/recipes/tags/descriptor/">descriptor</a>, <a href="/recipes/tags/descriptors/">descriptors</a>).
Revision 4.
</p>
<p>This recipe provides a descriptor class and a decorator to make the deferred binding. Before the first access to that name, the __dict__ of the class will have the descriptor object. After that first access it will have whatever was returned by the first access.</p>
<p>One big advantage of deferring the binding is that the class object will be available at that time and can be passed to the object. During normal class creation the class body is exec'd before the class object is created, so the objects bound there can't be passed the class.</p>
<p><a href="http://code.activestate.com/recipes/577746/">Recipe #577746</a> provides a concrete example of how the deferred_binder can be used.</p>
Change a Function's Closure! (Python)
2011-08-12T23:25:55-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577760-change-a-functions-closure/
<p style="color: grey">
Python
recipe 577760
by <a href="/recipes/users/4177816/">Eric Snow</a>
(<a href="/recipes/tags/closure/">closure</a>, <a href="/recipes/tags/function/">function</a>).
Revision 2.
</p>
<p>This is a hack to get around the read-only nature of __closure__ on function objects. Watch your step!</p>
Logging asserts (Python)
2010-03-01T03:22:43-08:00d.schlabinghttp://code.activestate.com/recipes/users/4168903/http://code.activestate.com/recipes/577074-logging-asserts/
<p style="color: grey">
Python
recipe 577074
by <a href="/recipes/users/4168903/">d.schlabing</a>
(<a href="/recipes/tags/logging/">logging</a>).
Revision 2.
</p>
<p>This tries to marry assert statements with logging. If you use asserts together with logging and the script stops because an assertion is not fulfilled, you will not find any information about this in the logs.
Unless you do something like this:</p>
<pre class="prettyprint"><code>meal = ["eggs", "bacon", "spam"]
try:
assert "spam" not in meal, "But I don't like spam!"
except AssertionError:
log.exception("But I don't like spam!")
raise
</code></pre>
<p>With the proposed recipe a somewhat similar behaviour can be achieved by:</p>
<pre class="prettyprint"><code>log_assert("spam" not in meal, "But I don't like spam!")
</code></pre>
Chaotic Function Analysis Graph (Python)
2010-12-10T03:31:50-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/577487-chaotic-function-analysis-graph/
<p style="color: grey">
Python
recipe 577487
by <a href="/recipes/users/4172570/">FB36</a>
(<a href="/recipes/tags/chaos/">chaos</a>, <a href="/recipes/tags/graph/">graph</a>, <a href="/recipes/tags/graphics/">graphics</a>, <a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>).
Revision 2.
</p>
<p>There are 3 chaotic functions to graph as examples.</p>
<p>Graph of function (0) is a curve.
Graph of function (1) is a group of lines.
(Both are Xn+1 = f(Xn) type functions.)</p>
<p>Graph of function (2) on the other hand is a plane.
(It is Xn+1 = f(Xn, Xn-1) type function.)</p>
<p>These mean there is a simple relationship between the
previous and next X values in (0) and (1). (Next X value can always be predicted from the previous X value by using the graph of the function w/o knowing the function itself.)
But (2) does not have a discernible relationship. (No prediction possible!)
So (2) is clearly more chaotic than others.
(I think it could be used as a Pseudo-Random Number Generator (PRNG).)</p>
transform command line arguments to args and kwargs for a method call (Python)
2010-03-21T22:41:42-07:00Trent Mickhttp://code.activestate.com/recipes/users/4173505/http://code.activestate.com/recipes/577122-transform-command-line-arguments-to-args-and-kwarg/
<p style="color: grey">
Python
recipe 577122
by <a href="/recipes/users/4173505/">Trent Mick</a>
(<a href="/recipes/tags/argv/">argv</a>, <a href="/recipes/tags/cli/">cli</a>, <a href="/recipes/tags/json/">json</a>).
Revision 2.
</p>
<p>For many of my Python modules I find it convenient to provide a small <code>if __name__ == "__main__": ...</code> block to be able to call individual methods from the command line. This requires some kind of translation of command-line string arguments to <code>args</code> and <code>kwargs</code> for the method call. This recipe uses a few conventions to do that:</p>
<ul>
<li>the first argument is the method name</li>
<li>positional args are positional (duh)</li>
<li>"key=value" is a keyword argument</li>
<li>an attempt is made to interpret arguments as JSON to allow specifying types other than string</li>
</ul>
simple state machine implementation (Python)
2010-07-15T17:54:17-07:00David Klaffenbachhttp://code.activestate.com/recipes/users/2007923/http://code.activestate.com/recipes/577308-simple-state-machine-implementation/
<p style="color: grey">
Python
recipe 577308
by <a href="/recipes/users/2007923/">David Klaffenbach</a>
(<a href="/recipes/tags/machine/">machine</a>, <a href="/recipes/tags/state/">state</a>).
</p>
<p>A very simple idiom for implementing a state machine.</p>
dfs and bfs graph traversal (Python)
2013-06-28T09:59:38-07:00bruce wernickhttp://code.activestate.com/recipes/users/4169952/http://code.activestate.com/recipes/576723-dfs-and-bfs-graph-traversal/
<p style="color: grey">
Python
recipe 576723
by <a href="/recipes/users/4169952/">bruce wernick</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/graph/">graph</a>).
</p>
<p>Very simple depth first search and breath first graph traversal. This is based on the find_path written by Guido van Rossum.</p>
RC4, ARC4, ARCFOUR algorithm (Python)
2009-05-03T09:45:59-07:00Thimo Kraemerhttp://code.activestate.com/recipes/users/4169283/http://code.activestate.com/recipes/576736-rc4-arc4-arcfour-algorithm/
<p style="color: grey">
Python
recipe 576736
by <a href="/recipes/users/4169283/">Thimo Kraemer</a>
(<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/encryption/">encryption</a>, <a href="/recipes/tags/text/">text</a>).
Revision 5.
</p>
<p>RC4 generates a pseudorandom stream of bits (a keystream) which, for encryption, is combined with the plaintext using bit-wise exclusive-or; decryption is performed the same way (since exclusive-or is a symmetric operation).</p>
<p>(see <a href="http://en.wikipedia.org/wiki/RC4">http://en.wikipedia.org/wiki/RC4</a>)</p>