Latest recipes http://code.activestate.com/recipes/new/2017-07-17T05:53:45-07:00ActiveState Code RecipesShoelace Formula for polygonal area (Python) 2017-07-17T05:53:45-07:00Paddy McCarthyhttp://code.activestate.com/recipes/users/398009/http://code.activestate.com/recipes/580812-shoelace-formula-for-polygonal-area/ <p style="color: grey"> Python recipe 580812 by <a href="/recipes/users/398009/">Paddy McCarthy</a> (<a href="/recipes/tags/2d/">2d</a>, <a href="/recipes/tags/area/">area</a>). </p> <p>Copied, by author from "Paddy3118 Go deh!: Python investigation of the Shoelace Formula for polygonal area <a href="http://paddy3118.blogspot.com/2017/07/python-investigation-of-shoelace.html#ixzz4n43Dqhaa" rel="nofollow">http://paddy3118.blogspot.com/2017/07/python-investigation-of-shoelace.html#ixzz4n43Dqhaa</a> " Where there is more meat on the bone (under a different license though).</p> Uno (Text-Based) (Python) 2017-07-15T00:46:59-07:00Brandon Martinhttp://code.activestate.com/recipes/users/4194238/http://code.activestate.com/recipes/580811-uno-text-based/ <p style="color: grey"> Python recipe 580811 by <a href="/recipes/users/4194238/">Brandon Martin</a> (<a href="/recipes/tags/artificial_intelligence/">artificial_intelligence</a>, <a href="/recipes/tags/cards/">cards</a>, <a href="/recipes/tags/game/">game</a>, <a href="/recipes/tags/text_game/">text_game</a>, <a href="/recipes/tags/uno/">uno</a>). </p> <p>A text based recreation of the classic card game featuring functional AIs to play with. Some rules have been modified. User interface is text based, non-curses, using only simple python commands to draw it. </p> How to create a simple PDF Pie Chart using fitz / PyMuPDF (Python) 2017-07-10T16:07:51-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580810-how-to-create-a-simple-pdf-pie-chart-using-fitz-py/ <p style="color: grey"> Python recipe 580810 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/pdf_generation/">pdf_generation</a>). </p> <p>PyMuPDF now supports drawing pie charts on a PDF page.</p> <p>Important parameters for the function are center of the circle, one of the two arc's end points and the angle of the circular sector. The function will draw the pie piece (in a variety of options) and return the arc's calculated other end point for any subsequent processing.</p> <p>This example creates a chart of the parliament seat distribution for political parties in the current German Bundestag.</p> Insert a Text Box in a PDF page (fitz / PyMuPDF) (Python) 2017-06-29T22:54:25-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580809-insert-a-text-box-in-a-pdf-page-fitz-pymupdf/ <p style="color: grey"> Python recipe 580809 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/textbox/">textbox</a>). </p> <p>This method inserts text into a predefined rectangular area of a (new or existing) PDF page. Words are distributed across the available space, put on new lines when required etc. Line breaks and tab characters are respected / resolved. Text can be aligned in the box (left, center, right) and fonts can be freely chosen. The method returns a float indicating how vertical space is left over after filling the area.</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> Variable 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> How to Create a PDF with a Caustic Drawing (Python) 2017-06-18T17:43:47-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580806-how-to-create-a-pdf-with-a-caustic-drawing/ <p style="color: grey"> Python recipe 580806 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>). </p> <p>Just a little demo on how to create simple drawings with PyMuPDF.</p> <p>This script simulates what you see looking into your coffee mug, early in the morning after a long night of programming ...</p> Create Calendars on PDF with a few lines (Python) 2017-06-13T10:57:34-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580805-create-calendars-on-pdf-with-a-few-lines/ <p style="color: grey"> Python recipe 580805 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/calendar/">calendar</a>, <a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>). Revision 2. </p> <p>PyMuPDF (fitz) provides easy to use ways to create PDF documents out of simple texts.</p> <p>An example is the text output of Python's calendar module. Here we take a starting year as script parameter and output a 3-page (A4 landscape) document with calendars for this and the following two years - in less than 20 lines of code.</p> Interactive Mandelbrot Fractal Using HTML5 Canvas (JavaScript) 2017-06-06T03:48:09-07:00FB36http://code.activestate.com/recipes/users/4172570/http://code.activestate.com/recipes/580804-interactive-mandelbrot-fractal-using-html5-canvas/ <p style="color: grey"> JavaScript recipe 580804 by <a href="/recipes/users/4172570/">FB36</a> (<a href="/recipes/tags/canvas/">canvas</a>, <a href="/recipes/tags/fractal/">fractal</a>, <a href="/recipes/tags/graphics/">graphics</a>, <a href="/recipes/tags/math/">math</a>). </p> <p>Interactive Mandelbrot Fractal Using HTML5 Canvas.</p> <p>(Download and save as html file and open it.)</p> <p>(Tested only using Firefox browser.)</p> Inserting Images on PDF Pages (Python) 2017-05-17T21:10:26-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580803-inserting-images-on-pdf-pages/ <p style="color: grey"> Python recipe 580803 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>). </p> <p>Version 1.11.0 of PyMuPDF allows putting an image on an existing PDF page. The following example puts the same image on every page of a given PDF - like a thumbnail.</p> Inserting pages into a PDF with PyMuPDF (Python) 2017-05-17T21:15:26-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580802-inserting-pages-into-a-pdf-with-pymupdf/ <p style="color: grey"> Python recipe 580802 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/text_conversion/">text_conversion</a>). Revision 2. </p> <p>Version 1.11.0 of PyMuPDF allows creating new PDF pages, as well as inserting images into existing pages.</p> <p>Here is a script that converts any textfile into a PDF.</p> A white noise generator to sooth baby to sleep. (Bash) 2017-05-13T12:12:30-07:00Barry Walkerhttp://code.activestate.com/recipes/users/4177147/http://code.activestate.com/recipes/580801-a-white-noise-generator-to-sooth-baby-to-sleep/ <p style="color: grey"> Bash recipe 580801 by <a href="/recipes/users/4177147/">Barry Walker</a> (<a href="/recipes/tags/alarm/">alarm</a>, <a href="/recipes/tags/apple/">apple</a>, <a href="/recipes/tags/audio/">audio</a>, <a href="/recipes/tags/baby_alarm/">baby_alarm</a>, <a href="/recipes/tags/cygwin/">cygwin</a>, <a href="/recipes/tags/linux/">linux</a>, <a href="/recipes/tags/noise/">noise</a>, <a href="/recipes/tags/sleep/">sleep</a>, <a href="/recipes/tags/sound/">sound</a>, <a href="/recipes/tags/whitenoise/">whitenoise</a>). </p> <p>This is a simple BASH, DASH and SH script to sooth a newborn baby to sleep for a laptop with a builtin mic. Develeoped around an Apple MacBook Pro.</p> <p>Usage:- [./]shush.sh &lt;time in seconds from 18 to 2700&gt; [sensitivity [Hh|Mm|Ll]]&lt;CR&gt;</p> <p>If time is omitted it defaults to 2 bursts of 9 seconds each and if sensitivity is omitted defaults to [M]edium.</p> <p>It uses Quicktime Player for Apple OSX 10.12.4 minimum /dev/dsp for CygWin and some Linux flavours and arecored for Linux ALSA machines for baby awake detector.</p> <p>Upon the two arguments the white noise generator runs for approximately the time given in $1 in bursts of 9 seconds until the time limit is reached. $2 is used to detect of baby is awake and reruns the noise generator again with a new noise waveform.</p> <p>Enjoy...</p> groupby() For Unsorted Input (Python) 2017-05-12T10:40:58-07:00Alfehttp://code.activestate.com/recipes/users/4182236/http://code.activestate.com/recipes/580800-groupby-for-unsorted-input/ <p style="color: grey"> Python recipe 580800 by <a href="/recipes/users/4182236/">Alfe</a> (<a href="/recipes/tags/algorithm/">algorithm</a>, <a href="/recipes/tags/datastructures/">datastructures</a>, <a href="/recipes/tags/generators/">generators</a>, <a href="/recipes/tags/grouping/">grouping</a>, <a href="/recipes/tags/lazy/">lazy</a>). </p> <p>We all know the <code>groupby()</code> which is available in the <code>itertools</code> standard module. This one yields groups of consecutive elements in the input which are meant to be together in one group. For non-consecutive elements this will yield more than one group for the same key.</p> <p>So effectively, <code>groupby()</code> only reformats a flat list into bunches of elements from that list without reordering anything. In practice this means that for input sorted by key this works perfect, but for unsorted input it might yield several groups for the same key (with groups for other keys in between). Typically needed, though, is a grouping with reordering if necessary.</p> <p>I implemented a likewise lazy function (yielding generators) which also accepts ungrouped input.</p> Python-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> Tkinter frame with different border sizes (Python) 2017-05-06T18:45:00-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580798-tkinter-frame-with-different-border-sizes/ <p style="color: grey"> Python recipe 580798 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/border/">border</a>, <a href="/recipes/tags/size/">size</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). </p> <p>This trick shows how to create a bordered frame with different border size in each side.</p> Scrolled Frame V2 (Python) 2017-05-06T18:54:47-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580797-scrolled-frame-v2/ <p style="color: grey"> Python recipe 580797 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/frame/">frame</a>, <a href="/recipes/tags/scrolling/">scrolling</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). Revision 4. </p> <p>This is another version of scrolled frame. It doesn't use Canvas. Instead it does the trick using place geometry manager.</p> <p>Based on these codes:</p> <ul> <li><p>https://github.com/alejandroautalan/pygubu/blob/master/pygubu/widgets/tkscrolledframe.py</p></li> <li><p>http://wiki.tcl.tk/9223 </p></li> </ul> <p>This is my other version of scrolled frame:</p> <p><a href="https://code.activestate.com/recipes/580640-scrolling-frame-with-mouse-wheel-support/" rel="nofollow">https://code.activestate.com/recipes/580640-scrolling-frame-with-mouse-wheel-support/</a></p> How to handle PDF embedded files with PyMuPDF (Python) 2017-07-11T18:57:54-07:00Jorj X. McKiehttp://code.activestate.com/recipes/users/4193772/http://code.activestate.com/recipes/580796-how-to-handle-pdf-embedded-files-with-pymupdf/ <p style="color: grey"> Python recipe 580796 by <a href="/recipes/users/4193772/">Jorj X. McKie</a> (<a href="/recipes/tags/embedded_files/">embedded_files</a>, <a href="/recipes/tags/fitz/">fitz</a>, <a href="/recipes/tags/mupdf/">mupdf</a>, <a href="/recipes/tags/pdf/">pdf</a>, <a href="/recipes/tags/pymupdf/">pymupdf</a>). Revision 3. </p> <p>Version 1.11.0 (based on MuPDF v1.11) allows exporting, importing and interrogating files embedded in a PDF.</p> <p>PDF "/EmbeddedFiles" are similar to ZIP archives (or the Microsoft OLE technique), allowing arbitrary data to be incorporated in a PDF and benefit from its unique features.</p> bind all tkinter "bug" (Python) 2017-05-05T20:33:31-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580795-bind-all-tkinter-bug/ <p style="color: grey"> Python recipe 580795 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/all/">all</a>, <a href="/recipes/tags/bind/">bind</a>, <a href="/recipes/tags/binding/">binding</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). Revision 3. </p> <p>This recipes tries to solve the problem of bind_all and unbind_all for tkinter.</p> <p>When a callback is registered using bind_all method and later it's unregistered using unbind_all, all the callbacks are deleted for the "all" tag event. This makes difficult to register and unregister only one callback at a time. This recipes tries to solve this problem.</p> <p>Observe the difference between the code below and the recipe. With the code below, when the user clicks nothing happens. But with my recipe it's possible to bind and unbind specific callbacks.</p> <pre class="prettyprint"><code>try: from Tkinter import Tk, Frame except ImportError: from tkinter import Tk, Frame root = Tk() f = Frame(root, width= 300, height=300) f.pack() def callback1(event): print("callback1") def callback2(event): print("callback2") def callback3(event): print("callback3") root.bind_all("&lt;1&gt;", callback1, add="+") f.bind_all("&lt;1&gt;", callback2, add="+") f.bind_all("&lt;1&gt;", callback3, add="+") f.unbind_all("&lt;1&gt;") root.mainloop() </code></pre> Simple multicolumn listbox for tkinter (Python) 2017-05-02T22:27:15-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580794-simple-multicolumn-listbox-for-tkinter/ <p style="color: grey"> Python recipe 580794 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/listbox/">listbox</a>, <a href="/recipes/tags/multicolumn/">multicolumn</a>, <a href="/recipes/tags/table/">table</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). </p> <p>This recipe makes easy to work a treeview widget like a table.</p> <p>It has several options for styling:</p> <ul> <li>heading_anchor</li> <li>heading_font</li> <li>heading_background</li> <li>heading_foreground</li> <li>cell_anchor</li> <li>cell_background</li> <li>cell_foreground</li> <li>cell_font</li> <li>cell_pady</li> <li>height</li> <li>padding</li> <li>adjust_heading_to_content</li> <li>stripped_rows</li> <li>headers</li> <li>selection_background</li> <li>selection_foreground</li> <li>field_background</li> </ul> <p>The "command" parameter is a callback and its called each time a row is selected.</p> Tkinter table with scrollbars (Python) 2017-05-06T19:06:05-07:00Miguel Martínez Lópezhttp://code.activestate.com/recipes/users/4189907/http://code.activestate.com/recipes/580793-tkinter-table-with-scrollbars/ <p style="color: grey"> Python recipe 580793 by <a href="/recipes/users/4189907/">Miguel Martínez López</a> (<a href="/recipes/tags/scrollbars/">scrollbars</a>, <a href="/recipes/tags/table/">table</a>, <a href="/recipes/tags/tkinter/">tkinter</a>). Revision 13. </p> <p>I created here a tkinter table with scrollbar support. I use one of my other recipes for the mousewheel support and scrolling:</p> <p><a href="https://code.activestate.com/recipes/580640-scrolling-frame-with-mouse-wheel-support" rel="nofollow">https://code.activestate.com/recipes/580640-scrolling-frame-with-mouse-wheel-support</a></p>