Popular recipes tagged "meta:min_python_2=6"http://code.activestate.com/recipes/tags/meta:min_python_2=6/2017-06-25T17:17:43-07:00ActiveState Code RecipesEqually-spaced numbers (linspace) (Python) 2015-01-12T22:16:37-08:00Andrew Barnerthttp://code.activestate.com/recipes/users/4184316/http://code.activestate.com/recipes/579000-equally-spaced-numbers-linspace/ <p style="color: grey"> Python recipe 579000 by <a href="/recipes/users/4184316/">Andrew Barnert</a> (<a href="/recipes/tags/float/">float</a>, <a href="/recipes/tags/linspace/">linspace</a>, <a href="/recipes/tags/range/">range</a>, <a href="/recipes/tags/spread/">spread</a>). </p> <p>An equivalent of <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html"><code>numpy.linspace</code></a>, but as a pure-Python lazy sequence.</p> <p>Like NumPy's <code>linspace</code>, but unlike the <a href="http://code.activestate.com/recipes/577068/"><code>spread</code></a> and <a href="http://code.activestate.com/recipes/577068/"><code>frange</code></a> recipes listed here, the <code>num</code> argument specifies the number of values, not the number of intervals, and the range is closed, not half-open.</p> <p>Although this is primarily designed for floats, it will work for <code>Fraction</code>, <code>Decimal</code>, NumPy arrays (although this would be silly) and even <code>datetime</code> values.</p> <p>This recipe can also serve as an example for creating lazy sequences.</p> <p>See the discussion below for caveats.</p> Guard against an exception in the wrong place (Python) 2017-06-25T17:17:43-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/580808-guard-against-an-exception-in-the-wrong-place/ <p style="color: grey"> Python recipe 580808 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/context/">context</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/guard/">guard</a>, <a href="/recipes/tags/manager/">manager</a>). Revision 2. </p> <p>Sometimes exception handling can obscure bugs unless you guard against a particular exception occurring in a certain place. One example is that <a href="https://www.python.org/dev/peps/pep-0479/">accidentally raising <code>StopIteration</code> inside a generator</a> will halt the generator instead of displaying a traceback. That was solved by PEP 479, which automatically has such <code>StopIteration</code> exceptions change to <code>RuntimeError</code>. See the discussion below for further examples.</p> <p>Here is a class which can be used as either a decorator or context manager for guarding against the given exceptions. It takes an exception (or a tuple of exceptions) as argument, and if the wrapped code raises that exception, it is re-raised as another exception type (by default <code>RuntimeError</code>).</p> <p>For example:</p> <pre class="prettyprint"><code>try: with exception_guard(ZeroDivisionError): 1/0 # raises ZeroDivisionError except RuntimeError: print ('ZeroDivisionError replaced by RuntimeError') @exception_guard(KeyError) def demo(): return {}['key'] # raises KeyError try: demo() except RuntimeError: print ('KeyError replaced by RuntimeError') </code></pre> Lines Of Code (LOC) (Python) 2016-10-25T17:53:01-07:00Jean Brouwershttp://code.activestate.com/recipes/users/2984142/http://code.activestate.com/recipes/580709-lines-of-code-loc/ <p style="color: grey"> Python recipe 580709 by <a href="/recipes/users/2984142/">Jean Brouwers</a> (<a href="/recipes/tags/count/">count</a>, <a href="/recipes/tags/lines/">lines</a>, <a href="/recipes/tags/python2/">python2</a>, <a href="/recipes/tags/python3/">python3</a>, <a href="/recipes/tags/source/">source</a>). Revision 3. </p> <p>Count the number of lines (code, comment, blank) in one or several Python source files.</p> Retry Decorator in Python (Python) 2017-01-11T10:10:30-08:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580745-retry-decorator-in-python/ <p style="color: grey"> Python recipe 580745 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/aspect/">aspect</a>, <a href="/recipes/tags/except/">except</a>, <a href="/recipes/tags/exception/">exception</a>, <a href="/recipes/tags/retry/">retry</a>, <a href="/recipes/tags/try/">try</a>). </p> <p>This is a Python decorator which helps implementing an aspect oriented implementation of a <em>retrying</em> of certain steps which might fail sometimes. A typical example for this would be communication processes with the outside world, e. g. HTTP requests, allocation of some resource, etc. To use it, refactor the step in question into a (local) function and decorate this with the <code>retry</code> decorator. See examples in the discussion sector below.</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> Fast min/max function (Python) 2011-10-22T18:40:32-07:00Raymond Hettingerhttp://code.activestate.com/recipes/users/178123/http://code.activestate.com/recipes/577916-fast-minmax-function/ <p style="color: grey"> Python recipe 577916 by <a href="/recipes/users/178123/">Raymond Hettinger</a> (<a href="/recipes/tags/minmax/">minmax</a>, <a href="/recipes/tags/sorting/">sorting</a>). </p> <p>Minimizes the number of comparisons to compute the minimum and maximum of a dataset. Uses 1.5 compares for every element, improving on the more obvious solution that does 2 comparisons per element.</p> ctypes CDLL with automatic errno checking (Python) 2017-01-03T10:31:26-08:00Oren Tiroshhttp://code.activestate.com/recipes/users/2033964/http://code.activestate.com/recipes/580741-ctypes-cdll-with-automatic-errno-checking/ <p style="color: grey"> Python recipe 580741 by <a href="/recipes/users/2033964/">Oren Tirosh</a> . </p> <p>This class extends ctypes.CDLL with automatic checking of errno and automatically raises an exception when set by the function.</p> How to build dobble as a Mixed Integer program. (Python) 2016-04-13T11:53:21-07:00alexander bakerhttp://code.activestate.com/recipes/users/4166679/http://code.activestate.com/recipes/580641-how-to-build-dobble-as-a-mixed-integer-program/ <p style="color: grey"> Python recipe 580641 by <a href="/recipes/users/4166679/">alexander baker</a> (<a href="/recipes/tags/integer/">integer</a>, <a href="/recipes/tags/interface/">interface</a>, <a href="/recipes/tags/mixed/">mixed</a>, <a href="/recipes/tags/program/">program</a>). </p> <p>A simple script to replicate the cards and symbols for the dobble game.</p> Safely and atomically write to a file (Python) 2016-03-23T14:14:26-07:00Steven D'Apranohttp://code.activestate.com/recipes/users/4172944/http://code.activestate.com/recipes/579097-safely-and-atomically-write-to-a-file/ <p style="color: grey"> Python recipe 579097 by <a href="/recipes/users/4172944/">Steven D'Aprano</a> (<a href="/recipes/tags/atomic/">atomic</a>, <a href="/recipes/tags/file/">file</a>, <a href="/recipes/tags/save/">save</a>). Revision 3. </p> <p>Saving the user's data is risky. If you write to a file directly, and an error occurs during the write, you may corrupt the file and lose the user's data. One approach to prevent this is to write to a temporary file, then only when you know the file has been written successfully, over-write the original. This function returns a context manager which can make this more convenient.</p> <p>Update: this now uses <code>os.replace</code> when available, and hopefully will work better on Windows.</p> vlc.py stream capture scheduler script (Python) 2015-08-19T05:00:25-07:00jwhite88http://code.activestate.com/recipes/users/4192711/http://code.activestate.com/recipes/579096-vlcpy-stream-capture-scheduler-script/ <p style="color: grey"> Python recipe 579096 by <a href="/recipes/users/4192711/">jwhite88</a> (<a href="/recipes/tags/recording/">recording</a>, <a href="/recipes/tags/stream/">stream</a>, <a href="/recipes/tags/vlc/">vlc</a>). </p> <p>Capture network streams using vlc.py on a schedule.</p> Python Gpa and Cgpa Calculator for Anna university : A forked python recepie (Python) 2015-07-31T02:37:19-07:00Emil george jameshttp://code.activestate.com/recipes/users/4191910/http://code.activestate.com/recipes/579089-python-gpa-and-cgpa-calculator-for-anna-university/ <p style="color: grey"> Python recipe 579089 by <a href="/recipes/users/4191910/">Emil george james</a> (<a href="/recipes/tags/calculator/">calculator</a>, <a href="/recipes/tags/cgpa/">cgpa</a>, <a href="/recipes/tags/gpa/">gpa</a>, <a href="/recipes/tags/python/">python</a>). Revision 2. </p> <p>Actually this python script is a forked one from activestate code by abhijeeth vaidya.A slightly edited version of the script to calculate Gpa and Cgpa for Anna university Students.</p> <p>Gpa and Cgpa Calculator</p> <p>Gpa is Grade point average, which is use to determine the student academic pointer based on the value of the grade he/she acquired in single semester, where as cgpa is cumlative grade point average is to calculate the total credits and total grade acquired in his/her entire academics. Here i have determined to use grade scale of two values 5.0 and 10.0, many other academics may have different grading system.For a different grades and their grade values, You can change the value in method called getGradeData.For any bug report </p> python EMI calculator (Python) 2015-07-29T18:20:36-07:00Emil george jameshttp://code.activestate.com/recipes/users/4191910/http://code.activestate.com/recipes/579086-python-emi-calculator/ <p style="color: grey"> Python recipe 579086 by <a href="/recipes/users/4191910/">Emil george james</a> (<a href="/recipes/tags/calculator/">calculator</a>, <a href="/recipes/tags/emi/">emi</a>, <a href="/recipes/tags/python/">python</a>). </p> <p>EMI Calculator is used to calculate Equated Monthly Installment(EMI) for Home Loans/Housing Loans,Car Loans &amp; Personal Advantages: What all this EMI Calculator does?</p> <p>. The Instant calculation of Loan EMI , Total Interest Payable and Total Payments to be done. . This can be used as EMI Calculator for Banks like HDFC, ICICI, SBI, AXIS etc. . This can be also used for calculating Home loans, Personal Loan, car loans , credit card, LIC loan</p> <p>How to calculate the EMI?</p> <p>The well known formula for calculating EMI is:</p> <p>Formula for EMI calculation</p> <p>[Formula] EMI = [(p*r/12) (1+r/12)^n]/[(1+r/12)^n – 1 ] where p = principal amount(primary loan amount) r = rate of interest per year n = Total number of Years</p> <p>output:</p> <p><a href="https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/" rel="nofollow">https://emilgeorgejames.wordpress.com/2015/07/29/python-emi-equated-monthly-installment-calculator/</a></p> <p>for more python recepies visit :https://emilgeorgejames.wordpress.com/</p> Yet another singleton pattern in Python using class decorators (Python) 2015-08-11T19:14:45-07:00David Hollmanhttp://code.activestate.com/recipes/users/4182331/http://code.activestate.com/recipes/579090-yet-another-singleton-pattern-in-python-using-clas/ <p style="color: grey"> Python recipe 579090 by <a href="/recipes/users/4182331/">David Hollman</a> (<a href="/recipes/tags/patterns/">patterns</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/singleton/">singleton</a>). Revision 8. </p> <p>Another pattern for creating singleton instances of classes in Python.</p> OrderedSet (Python) 2015-06-25T17:33:13-07:00Sanderhttp://code.activestate.com/recipes/users/4192426/http://code.activestate.com/recipes/579071-orderedset/ <p style="color: grey"> Python recipe 579071 by <a href="/recipes/users/4192426/">Sander</a> (<a href="/recipes/tags/ordered/">ordered</a>, <a href="/recipes/tags/set/">set</a>). </p> <p>Set that remembers original insertion order.</p> Python AST to XML (Python) 2015-02-05T20:18:08-08:00Robert Stewarthttp://code.activestate.com/recipes/users/4191612/http://code.activestate.com/recipes/579019-python-ast-to-xml/ <p style="color: grey"> Python recipe 579019 by <a href="/recipes/users/4191612/">Robert Stewart</a> (<a href="/recipes/tags/ast/">ast</a>, <a href="/recipes/tags/xml/">xml</a>). </p> <p>Convert Python ASTs to XML files for reading in other languages.</p> Keyword-only arguments in Python 2.x (Python) 2015-09-22T18:16:40-07:00Carahttp://code.activestate.com/recipes/users/4191397/http://code.activestate.com/recipes/578993-keyword-only-arguments-in-python-2x/ <p style="color: grey"> Python recipe 578993 by <a href="/recipes/users/4191397/">Cara</a> (<a href="/recipes/tags/arguments/">arguments</a>, <a href="/recipes/tags/decorator/">decorator</a>, <a href="/recipes/tags/keyword/">keyword</a>, <a href="/recipes/tags/keyword_only/">keyword_only</a>). Revision 10. </p> <p>This is a decorator that makes some of a function's or method's arguments into keyword-only arguments. As much as it possible, it emulates the Python 3 handling of keyword-only arguments, including messages for TypeErrors. It's compatible with Python 3 so it can be used in code bases that support both versions.</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> socket.sendfile() (Python) 2014-06-13T13:41:25-07:00Giampaolo Rodolàhttp://code.activestate.com/recipes/users/4178764/http://code.activestate.com/recipes/578889-socketsendfile/ <p style="color: grey"> Python recipe 578889 by <a href="/recipes/users/4178764/">Giampaolo Rodolà</a> (<a href="/recipes/tags/backport/">backport</a>, <a href="/recipes/tags/performance/">performance</a>, <a href="/recipes/tags/python/">python</a>, <a href="/recipes/tags/sendfile/">sendfile</a>). Revision 2. </p> <p>This is a backport of socket.sendfile() for Python 2.6 and 2.7. socket.sendfile() will be included in Python 3.5: <a href="http://bugs.python.org/issue17552" rel="nofollow">http://bugs.python.org/issue17552</a></p> Random Password Generation (Python) 2014-08-10T15:50:40-07:00Paul Wolfhttp://code.activestate.com/recipes/users/4190553/http://code.activestate.com/recipes/578920-random-password-generation/ <p style="color: grey"> Python recipe 578920 by <a href="/recipes/users/4190553/">Paul Wolf</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>, <a href="/recipes/tags/string/">string</a>, <a href="/recipes/tags/strong/">strong</a>). </p> <p>Generate a password (or other secure token) using a pattern language similar to regular expressions. We'll use the <code>strgen</code> module that enables a user to generate test data, unique ids, passwords, vouchers or other randomized data very quickly using a template language. The template language is superficially similar to regular expressions but instead of defining how to match or capture strings, it defines how to generate randomized strings.</p> First n primes numbers (Python) 2014-09-20T19:33:41-07:00juanhttp://code.activestate.com/recipes/users/4190606/http://code.activestate.com/recipes/578923-first-n-primes-numbers/ <p style="color: grey"> Python recipe 578923 by <a href="/recipes/users/4190606/">juan</a> . Revision 6. </p> <p>Using the Sieve of Eratosthenes find the first n primes numbers.</p>