Popular recipes tagged "meta:loc=19"http://code.activestate.com/recipes/tags/meta:loc=19/2017-06-22T11:57:20-07:00ActiveState Code RecipesVariable Abbreviations (Python) 2017-06-22T11:57:20-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580807-variable-abbreviations/ <p style="color: grey"> Python recipe 580807 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/abbreviations/">abbreviations</a>, <a href="/recipes/tags/contextmanager/">contextmanager</a>, <a href="/recipes/tags/variables/">variables</a>, <a href="/recipes/tags/with/">with</a>). </p> <p>One sometimes has nice long speaking names vor variables, maybe things like <code>buildingList[foundIndex].height</code>, but would like to address these in a shorter fashion to be used within a formula or similar where lots of longs names tend to confuse any reader trying to understand the formula. Physicists use one-letter names for a reason.</p> <p>For this I wrote a small context provider which allows using short names instead of long ones:</p> <pre class="prettyprint"><code>with Abbr(h=buildingList[foundIndex].height, g=gravitationalConstant): fallTime = sqrt(2 * h / g) endSpeed = sqrt(2 * h * g) print("Fall time:", fallTime) print("End speed:", endSpeed) </code></pre> <p>For longer formulas this can reduce ugly multi-line expressions to clearly readable one-liners.</p> <p>One could use this:</p> <pre class="prettyprint"><code>h = buildingList[foundIndex].height g = gravitationalConstant fallTime = sqrt(2 * h / g) endSpeed = sqrt(2 * h * g) del g, h print("Fall time:", fallTime) print("End speed:", endSpeed) </code></pre> <p>to achieve the same result, but</p> <ul> <li>it would not look as clean and</li> <li>the context provider solves the typical issues like cleanup on exception etc.</li> </ul> <p>Just using local variables without cleanup (like above without the <code>del</code> statement) also is an option of course, but that would clutter the variable name space unnecessarily.</p> <p>CAVEATS: The implementation of <code>Abbr()</code> is a hack. If used as intended and described here, it should work just fine, though. But the hackish nature forces me to mention some things: Since at compile time the compiler decides that the <code>h</code> and <code>g</code> in the example must be global variables (because they aren't assigned in the function), it produces byte code accessing global variables. The context provider changes the global variable structure to fill the needs. (Overridden already existing global variables of the same name get restored properly at context exit.) This means some things:</p> <ul> <li>One cannot have a local variable of the same name in the frame surrounding the context manager.</li> <li>Existing global variables are changed during the time of the context manager; so using names like <code>sys</code> or <code>os</code> for abbreviations might be a bad idea due to side-effects.</li> </ul> File browser for tkinter using idle GUI library (Python) 2017-04-03T13:37:34-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580772-file-browser-for-tkinter-using-idle-gui-library/ <p style="color: grey"> Python recipe 580772 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/browser/">browser</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/idlelib/">idlelib</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). </p> <p>Idle is installed by default on windows.</p> <p>For Ubuntu, Linux Mint and Debian run:</p> <pre class="prettyprint"><code> sudo apt-get install idle-python2.7 </code></pre> <p>A tree structure is drawn on a Tkinter Canvas object. A tree item is an object with an icon and a text. The item maybe be expandable and/or editable. A tree item has two kind of icons: A normal icon and an icon when the item is selected. To create the tree structure, it's necessary to create a link between tree items, using a parent-child relationship. </p> <p>The canvas is built using a <em>idlelib.TreeWidget.ScrolledCanvas</em> class. The <em>frame</em> attribute of this object contains a <em>Frame</em> Tkinter widget prepared for scrolling. This frame allocates a Tkinter <em>Canvas</em> and Tkinter <em>Scrollbars</em>. This is the signature:</p> <pre class="prettyprint"><code> ScrolledCanvas(master, **options_for_the_tkinter_canvas) </code></pre> <p>It accepts exactly the same arguments than a <em>Canvas</em> widget.</p> <p>A tree item should be a subclass of <em>idlelib.TreeWidget.TreeItem</em>.</p> <p>The parent-child relationship between tree items is established using the <em>idlelib.TreeWidget.TreeNode</em> class.</p> <p>This is the signature for <strong>TreeNode(canvas, parent, item)</strong>:</p> <ul> <li><em>canvas</em> should be a <em>ScrolledCanvas</em> instance. </li> <li><em>parent</em> should be the parent item. Leave that to <em>None</em> to create a root node.</li> <li><em>item</em> should be the child item</li> </ul> <p><em>FileTreeItem</em> is a type of <em>TreeItem</em>. The only argument of a file tree item is a path.</p> <p>Here there is an example of a custom tree item:</p> <p><a href="https://code.activestate.com/recipes/579077-bookmarks-browser-for-firefox/" rel="nofollow">https://code.activestate.com/recipes/579077-bookmarks-browser-for-firefox/</a></p> <p>To create your own tree items, it's required to subclass <em>TreeItem</em>. These are the methods that should be overrided:</p> <ul> <li><em>GetText:</em> It should return the text string to display.</li> <li><em>GetLabelText:</em> It should return label text string to display in front of text (Optional).</li> <li><em>IsExpandable:</em> It should return a boolean indicating whether the istem is expandable</li> <li><em>IsEditable:</em> It should return a boolean indicating whether the item's text may be edited.</li> <li><em>SetText:</em> Get the text to change if the item is is editable</li> <li><em>GetIconName:</em> Return name of icon to be displayed normally (Icons should be included in <em>ICONDIR</em> directory)</li> <li><em>GetSelectedIconName:</em> Return name of icon to be displayed when selected (Icons should be included in <em>ICONDIR</em> directory).</li> <li><em>GetSubList:</em> It should return a list of child items (Optional. If not defined, the element is not expandable)</li> <li><em>OnDoubleClick:</em> Called on a double-click on the item. (Optional)</li> </ul> <p>Icons should be included in "Icons" subdirectory of path to idlelib library. If you want to use other path, just change <em>ICONDIR</em> variable to path to your icons:</p> <pre class="prettyprint"><code> import idlelib idlelib.ICONDIR = "Your path to your icons" </code></pre> <p>Run this to find the path to <em>idlelib</em> module:</p> <pre class="prettyprint"><code> python -c "import idlelib; print(idlelib.__file__)" </code></pre> Send and retrieve text to/from clipboard (Batch) 2016-05-27T09:56:56-07:00Antoni Gualhttp://code.activestate.com/recipes/users/4182514/http://code.activestate.com/recipes/580669-send-and-retrieve-text-tofrom-clipboard/ <p style="color: grey"> Batch recipe 580669 by <a href="/recipes/users/4182514/">Antoni Gual</a> (<a href="/recipes/tags/batch/">batch</a>, <a href="/recipes/tags/clipboard/">clipboard</a>). </p> <p>Sending uses the command line tool clip.exe that may not be available in Windows XP. There is no standard tool to retrieve from clipboard so I use javascript via mshta.</p> Apache::ReadConfig (Perl) 2015-11-17T00:14:45-08:00Roger Mbiama Assogohttp://code.activestate.com/recipes/users/4193133/http://code.activestate.com/recipes/579127-apachereadconfig/ <p style="color: grey"> Perl recipe 579127 by <a href="/recipes/users/4193133/">Roger Mbiama Assogo</a> (<a href="/recipes/tags/angosso_net/">angosso_net</a>). </p> <p>mod_perl defines a package called Apache::ReadConfig. Here it keeps all the variables that you define inside the &lt;Perl&gt; sections.</p> Converting numeric strings to integers (Python) 2015-08-04T20:08:29-07:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/579093-converting-numeric-strings-to-integers/ <p style="color: grey"> Python recipe 579093 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/formats/">formats</a>, <a href="/recipes/tags/numbers/">numbers</a>, <a href="/recipes/tags/numerical/">numerical</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/representation/">representation</a>). </p> <p>This recipe shows how to convert numeric strings into integers, i.e. it emulates the Python int() function - partially. It does not handle negative numbers, floating point numbers, or numbers in other bases than decimal. It is only meant as a simple demo of the steps by which a string containing an integer value, is converted into an actual integer, in Python (and similarly, in other languages).</p> Amazon SNS handler for the logging module (Python) 2014-11-06T17:32:26-08:00Andrea Corbellinihttp://code.activestate.com/recipes/users/4186880/http://code.activestate.com/recipes/578956-amazon-sns-handler-for-the-logging-module/ <p style="color: grey"> Python recipe 578956 by <a href="/recipes/users/4186880/">Andrea Corbellini</a> (<a href="/recipes/tags/aws/">aws</a>, <a href="/recipes/tags/logging/">logging</a>, <a href="/recipes/tags/sns/">sns</a>). Revision 2. </p> <p>This is a handler for the standard <a href="https://docs.python.org/library/logging.html">logging</a> module that sends notifications to the <a href="http://aws.amazon.com/sns/">Amazon Simple Notification Service</a>.</p> <p>You can use it like so:</p> <pre class="prettyprint"><code>logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d ' '%(thread)d %(message)s', }, 'simple': { 'format': '%(levelname)s %(message)s', }, }, 'handlers': { 'sns': { 'level': 'INFO', 'class': 'SNSHandler', 'formatter': 'verbose', 'topic_arn': 'YOUR SNS TOPIC ARN', }, }, 'loggers': { 'YOUR MODULE': { 'handlers': ['sns'], 'level': 'INFO', 'propagate': True, }, }, } </code></pre> Create PDF at the end of a Unix pipeline with PDFWriter (Python) 2013-12-22T22:19:00-08:00Vasudev Ramhttp://code.activestate.com/recipes/users/4173351/http://code.activestate.com/recipes/578794-create-pdf-at-the-end-of-a-unix-pipeline-with-pdfw/ <p style="color: grey"> Python recipe 578794 by <a href="/recipes/users/4173351/">Vasudev Ram</a> (<a href="/recipes/tags/commandline/">commandline</a>, <a href="/recipes/tags/linux/">linux</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pipelining/">pipelining</a>, <a href="/recipes/tags/reportlab/">reportlab</a>, <a href="/recipes/tags/unix/">unix</a>, <a href="/recipes/tags/xtopdf/">xtopdf</a>). </p> <p>This recipe shows how to create PDF output at the end of a Unix or Linux pipeline, after all the text processing required, is done by previous components of the pipeline (which can use any of the standard tools of Unix such as sed, grep, awk, etc., as well as custom programs that act as filters).</p> AsyncGetter (Python) 2013-06-01T18:20:15-07:00Nick Farohttp://code.activestate.com/recipes/users/4184363/http://code.activestate.com/recipes/578540-asyncgetter/ <p style="color: grey"> Python recipe 578540 by <a href="/recipes/users/4184363/">Nick Faro</a> (<a href="/recipes/tags/asynchronous/">asynchronous</a>, <a href="/recipes/tags/getting/">getting</a>). </p> <p>You specify it a 'get' function and it runs a thread and gets it for you. Incredibly simple.</p> Generate the parity or sign of a permutation (Python) 2012-07-28T07:21:49-07:00Paddy McCarthyhttp://code.activestate.com/recipes/users/398009/http://code.activestate.com/recipes/578227-generate-the-parity-or-sign-of-a-permutation/ <p style="color: grey"> Python recipe 578227 by <a href="/recipes/users/398009/">Paddy McCarthy</a> (<a href="/recipes/tags/determinants/">determinants</a>, <a href="/recipes/tags/mathematics/">mathematics</a>, <a href="/recipes/tags/matrix/">matrix</a>, <a href="/recipes/tags/permutations/">permutations</a>). </p> <p>The <a href="http://en.wikipedia.org/wiki/Parity_of_a_permutation">parity</a> of a given permutation is whether an odd or even number of swaps between any two elements are needed to transform the given permutation to the first permutation.</p> <p>The sign of the permutation is +1 for an even parity and -1 for an odd parity.</p> <p>This python function returns the sign of a permutation of all the integers 0..N. When the program is run it shows the sign of permutations as generated by the standard function itertools.permutations.</p> <p>The function uses a modified <a href="http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort#Python">selection sort</a> to compute the parity.</p> Counting freespace of all drives with ready status (Batch) 2012-11-14T19:06:44-08:00greg zakharovhttp://code.activestate.com/recipes/users/4184115/http://code.activestate.com/recipes/578328-counting-freespace-of-all-drives-with-ready-status/ <p style="color: grey"> Batch recipe 578328 by <a href="/recipes/users/4184115/">greg zakharov</a> (<a href="/recipes/tags/disk/">disk</a>). </p> <p>Checking freespace of drives which active at execution batch moment.</p> Area of Polygon using Shoelace formula (Python) 2012-02-18T16:34:33-08:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/578047-area-of-polygon-using-shoelace-formula/ <p style="color: grey"> Python recipe 578047 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>). </p> <p>Area of Polygon using Shoelace formula.</p> A Simpler Namespace Class (Python) 2013-02-14T17:42:24-08:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/578141-a-simpler-namespace-class/ <p style="color: grey"> Python recipe 578141 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/namespaces/">namespaces</a>, <a href="/recipes/tags/object/">object</a>). Revision 3. </p> <p>A very simple, attribute-based namespace type (and one offspring). Everyone's written one of these...</p> Flatten Array/Tuple (Python) 2011-10-31T10:53:39-07:00Luca Zarottihttp://code.activestate.com/recipes/users/4179728/http://code.activestate.com/recipes/577932-flatten-arraytuple/ <p style="color: grey"> Python recipe 577932 by <a href="/recipes/users/4179728/">Luca Zarotti</a> (<a href="/recipes/tags/array/">array</a>, <a href="/recipes/tags/flatten/">flatten</a>, <a href="/recipes/tags/tuple/">tuple</a>). </p> <p>Flatten a nested array/tuple</p> Turn a Function Into a Class (Python) 2011-10-05T18:38:43-07:00Eric Snowhttp://code.activestate.com/recipes/users/4177816/http://code.activestate.com/recipes/577822-turn-a-function-into-a-class/ <p style="color: grey"> Python recipe 577822 by <a href="/recipes/users/4177816/">Eric Snow</a> (<a href="/recipes/tags/classes/">classes</a>, <a href="/recipes/tags/functions/">functions</a>). </p> <p>The only catch is that the function has to return locals() at the end. And it doesn't do the __prepare__ part of 3.x metaclasses.</p> Lambert W Function (Python) 2011-05-29T23:09:31-07:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/577729-lambert-w-function/ <p style="color: grey"> Python recipe 577729 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/math/">math</a>, <a href="/recipes/tags/mathematics/">mathematics</a>). </p> <p>Lambert W function.</p> Partition a sequence (Python) 2011-05-03T17:52:47-07:00Anoop.Khttp://code.activestate.com/recipes/users/4177869/http://code.activestate.com/recipes/577682-partition-a-sequence/ <p style="color: grey"> Python recipe 577682 by <a href="/recipes/users/4177869/">Anoop.K</a> (<a href="/recipes/tags/sequence/">sequence</a>). </p> <p>Using simple recursive logic.</p> Random Passwords (Python) 2010-07-27T20:28:17-07:00Danillo Souzahttp://code.activestate.com/recipes/users/4174445/http://code.activestate.com/recipes/577339-random-passwords/ <p style="color: grey"> Python recipe 577339 by <a href="/recipes/users/4174445/">Danillo Souza</a> (<a href="/recipes/tags/generator/">generator</a>, <a href="/recipes/tags/password/">password</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/random/">random</a>). </p> <p>Generate strong random passwords of specified length.</p> Convert PDF to plain text (Python) 2010-11-25T15:30:52-08:00ccpizzahttp://code.activestate.com/recipes/users/4170754/http://code.activestate.com/recipes/577095-convert-pdf-to-plain-text/ <p style="color: grey"> Python recipe 577095 by <a href="/recipes/users/4170754/">ccpizza</a> (<a href="/recipes/tags/converter/">converter</a>, <a href="/recipes/tags/pdf/">pdf</a>). </p> <p>This is a very raw PDF converter which has absolutely no idea of the page layout or text positioning.</p> <p>To install the required module try <code>easy_install pypdf</code> in a console.</p> Komodo JS Macro - force the focus back onto the editor after an alt-tab (JavaScript) 2010-03-29T18:59:03-07:00Todd Whitemanhttp://code.activestate.com/recipes/users/2666241/http://code.activestate.com/recipes/577164-komodo-js-macro-force-the-focus-back-onto-the-edit/ <p style="color: grey"> JavaScript recipe 577164 by <a href="/recipes/users/2666241/">Todd Whiteman</a> (<a href="/recipes/tags/focus/">focus</a>, <a href="/recipes/tags/javascript/">javascript</a>, <a href="/recipes/tags/komodo/">komodo</a>, <a href="/recipes/tags/macro/">macro</a>, <a href="/recipes/tags/setfocus/">setfocus</a>, <a href="/recipes/tags/tab/">tab</a>, <a href="/recipes/tags/window/">window</a>). </p> <p>A <a href="http://www.activestate.com/komodo">Komodo</a> JavaScript macro that can be used to force the focus back to the Komodo editor after switching between windows (i.e. after using Alt-Tab).</p> <p>This macro only applies to Windows and Mac OS - where there is an application activated notification event available.</p> <p>To use this macro - set the macro to trigger on the "On startup" event.</p> Polar-to-rectangular conversions using CORDIC (Python) 2011-04-23T23:46:18-07:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/576792-polar-to-rectangular-conversions-using-cordic/ <p style="color: grey"> Python recipe 576792 by <a href="/recipes/users/178123/">Raymond Hettinger</a> . </p> <p>Demonstrate CORDIC algorithm for computing coordinate conversions using only adds and shifts (plus one multiply in the outer loop).</p>