From f864f96718796d096f433c03438903128f0c0ecc Mon Sep 17 00:00:00 2001 From: Angel Segura Date: Mon, 31 Jul 2017 21:01:52 -0400 Subject: [PATCH 01/35] Adding header with Browser info. Before: some sites returned HTTP Error 403: Forbidden due to lack of browser information on the request header After: Unlimited image downloads ! --- recipes/Python/577385_Image_Downloader/recipe-577385.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/recipes/Python/577385_Image_Downloader/recipe-577385.py b/recipes/Python/577385_Image_Downloader/recipe-577385.py index 86344a700..557fcfcc5 100644 --- a/recipes/Python/577385_Image_Downloader/recipe-577385.py +++ b/recipes/Python/577385_Image_Downloader/recipe-577385.py @@ -23,7 +23,9 @@ def downloadImages(url, level): # the root URL is level 0 return try: - urlContent = urllib2.urlopen(url).read() + hdr = {'User-Agent': 'Mozilla/5.0'} + req = urllib2.Request(url,headers=hdr) + urlContent = urllib2.urlopen(req).read() urlList.append(url) print url except: @@ -42,7 +44,9 @@ def downloadImages(url, level): # the root URL is level 0 imgUrl.lower().endswith('.png') or \ imgUrl.lower().endswith('.bmp'): try: - imgData = urllib2.urlopen(imgUrl).read() + hdr = {'User-Agent': 'Mozilla/5.0'} + req = urllib2.Request(imgUrl,headers=hdr) + imgData = urllib2.urlopen(req).read() global minImageFileSize if len(imgData) >= minImageFileSize: print " " + imgUrl From 546a9404c31ac66fea778b938cb54835a60e16b3 Mon Sep 17 00:00:00 2001 From: kgashok Date: Thu, 10 Aug 2017 02:08:01 +0530 Subject: [PATCH 02/35] Update recipe-115421.py simplifying leapyear checking --- .../Python/115421_Date_difference/recipe-115421.py | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/recipes/Python/115421_Date_difference/recipe-115421.py b/recipes/Python/115421_Date_difference/recipe-115421.py index fd9493036..d4bdd23af 100644 --- a/recipes/Python/115421_Date_difference/recipe-115421.py +++ b/recipes/Python/115421_Date_difference/recipe-115421.py @@ -14,16 +14,7 @@ JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC = range(len(months)) def leapyear(year): - if year % 4 == 0: - if year % 100 == 0: - if year % 400 == 0: - return TRUE - else: - return FALSE - else: - return TRUE - else: - return FALSE + return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 def main(): days=sum=0 From 702450dbdfd193d825ae1acca5c7320c92d32543 Mon Sep 17 00:00:00 2001 From: kgashok Date: Tue, 15 Aug 2017 15:52:49 +0530 Subject: [PATCH 03/35] Update recipe-576917.py Added the recursive version from the comments at https://code.activestate.com/recipes/576917-functional-selection-sort/#c1 --- .../576917_Functional_selection_sort/recipe-576917.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/recipes/Python/576917_Functional_selection_sort/recipe-576917.py b/recipes/Python/576917_Functional_selection_sort/recipe-576917.py index bf4ccaf61..ebeb7283c 100644 --- a/recipes/Python/576917_Functional_selection_sort/recipe-576917.py +++ b/recipes/Python/576917_Functional_selection_sort/recipe-576917.py @@ -15,3 +15,9 @@ test_list = [ 5, 1, 7, 0, -3, -10, 10, -6, 1, 0, 2, 4, -2, 6, 5, 8, 2] print test_list print selection_sort(test_list) + +# Recursive version +def select_sort_r(L): + if not L: return [] # terminal case + idx, v = min(enumerate(L), key=lambda e: e[1]) # select the minimum + return [v] + select_sort_r(L[:idx] + L[idx+1:]) # recursively call on the remainder From c3f4ec4717619e51ae90e4c75be9720bf9f3f495 Mon Sep 17 00:00:00 2001 From: kgashok Date: Tue, 15 Aug 2017 23:18:05 +0530 Subject: [PATCH 04/35] Update recipe-576917.py --- .../Python/576917_Functional_selection_sort/recipe-576917.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/recipes/Python/576917_Functional_selection_sort/recipe-576917.py b/recipes/Python/576917_Functional_selection_sort/recipe-576917.py index ebeb7283c..f1630f62e 100644 --- a/recipes/Python/576917_Functional_selection_sort/recipe-576917.py +++ b/recipes/Python/576917_Functional_selection_sort/recipe-576917.py @@ -19,5 +19,5 @@ # Recursive version def select_sort_r(L): if not L: return [] # terminal case - idx, v = min(enumerate(L), key=lambda e: e[1]) # select the minimum + v, idx = min((v, i) for i, v in enumerate(L)) # select the smallest return [v] + select_sort_r(L[:idx] + L[idx+1:]) # recursively call on the remainder From a733521c7d10ac6b52c7bf493805f68b38d45f7e Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Thu, 17 Aug 2017 07:33:04 -0400 Subject: [PATCH 05/35] Create drawSines.py --- .../Draw Sine Function in PDF/drawSines.py | 148 ++++++++++++++++++ 1 file changed, 148 insertions(+) create mode 100644 recipes/Python/Draw Sine Function in PDF/drawSines.py diff --git a/recipes/Python/Draw Sine Function in PDF/drawSines.py b/recipes/Python/Draw Sine Function in PDF/drawSines.py new file mode 100644 index 000000000..a558563fa --- /dev/null +++ b/recipes/Python/Draw Sine Function in PDF/drawSines.py @@ -0,0 +1,148 @@ +import fitz, math +""" +Created on 2017-08-17 + +@author: (c) 2017, Jorj X. McKie + +License: GNU GPL V3 + +PyMuPDF Demo Program +--------------------- +Create a PDF with drawings of the sine and cosine functions using PyMuPDF. +Depending on how start and end points are located with respect to each +other, horizontal or vertical drawings result. +The vertical case can obviously be used for creating inverse function +(arcus sine / cosine) graphs. + +The function graphs are pieced together in 90 degree parts, for which Bezier +curves are used. + +Note that the 'alfa' and 'beta' constants represent values for use as +Bezier control points like so: +x-values (written in degrees): [0, 30, 60, 90] +corresponding y-values: [0, alfa, beta, 1] + +These values have been calculated by the scipy.interpolate.splrep() method. +They provide an excellent spline approximation of the sine / cosine +functions - please look at SciPy documentation for background. + +""" +def bsinPoints(pb, pe): + """Return Bezier control points, when pb and pe stand for a full period + from (0,0) to (2*pi, 0), respectively, in the user's coordinate system. + The returned points can be used to draw up to four Bezier curves for + the complete sine function graph from 0 to 2*pi. + """ + f = abs(pe - pb) * 0.5 / math.pi # represents the unit + alfa = 5.34295228e-01 + beta = 1.01474288e+00 + # adjust for either horizontal or vertical + if pb.y == pe.y: + y_ampl = (0, f) + y_alfa = (0, f * alfa) + y_beta = (0, f * beta) + elif pb.x == pe.x: + y_ampl = (-f, 0) + y_alfa = (-f * alfa, 0) + y_beta = (-f * beta, 0) + else: + raise ValueError("can only draw horizontal or vertical") + + p0 = pb + p4 = pe + p1 = pb + (pe - pb)*0.25 - y_ampl + p2 = pb + (pe - pb)*0.5 + p3 = pb + (pe - pb)*0.75 + y_ampl + k1 = pb + (pe - pb)*(1./12.) - y_alfa + k2 = pb + (pe - pb)*(2./12.) - y_beta + k3 = pb + (pe - pb)*(4./12.) - y_beta + k4 = pb + (pe - pb)*(5./12.) - y_alfa + k5 = pb + (pe - pb)*(7./12.) + y_alfa + k6 = pb + (pe - pb)*(8./12.) + y_beta + k7 = pb + (pe - pb)*(10./12.) + y_beta + k8 = pb + (pe - pb)*(11./12.) + y_alfa + return p0, k1, k2, p1, k3, k4, p2, k5, k6, p3, k7, k8, p4 + +def bcosPoints(pb, pe): + """Return Bezier control points, when pb and pe stand for a full period + from (0,0) to (2*pi, 0), respectively, in the user's coordinate system. + The returned points can be used to draw up to four Bezier curves for + the complete cosine function graph from 0 to 2*pi. + """ + f = abs(pe - pb) * 0.5 / math.pi # represents the unit + alfa = 5.34295228e-01 + beta = 1.01474288e+00 + # adjust for either horizontal or vertical + if pb.y == pe.y: + y_ampl = (0, f) + y_alfa = (0, f * alfa) + y_beta = (0, f * beta) + elif pb.x == pe.x: + y_ampl = (-f, 0) + y_alfa = (-f * alfa, 0) + y_beta = (-f * beta, 0) + else: + raise ValueError("can only draw horizontal or vertical") + + p0 = pb - y_ampl + p4 = pe - y_ampl + p1 = pb + (pe - pb)*0.25 + p2 = pb + (pe - pb)*0.5 + y_ampl + p3 = pb + (pe - pb)*0.75 + k1 = pb + (pe - pb)*(1./12.) - y_beta + k2 = pb + (pe - pb)*(2./12.) - y_alfa + k3 = pb + (pe - pb)*(4./12.) + y_alfa + k4 = pb + (pe - pb)*(5./12.) + y_beta + k5 = pb + (pe - pb)*(7./12.) + y_beta + k6 = pb + (pe - pb)*(8./12.) + y_alfa + k7 = pb + (pe - pb)*(10./12.) - y_alfa + k8 = pb + (pe - pb)*(11./12.) - y_beta + return p0, k1, k2, p1, k3, k4, p2, k5, k6, p3, k7, k8, p4 + +if __name__ == "__main__": + from fitz.utils import getColor + doc = fitz.open() + page = doc.newPage() + red = getColor("red") # line color for sine + blue = getColor("blue") # line color for cosine + yellow = getColor("py_color") # background color + w = 0.3 # line width + #-------------------------------------------------------------------------- + # define end points of x axis we want to use as 0 and 2*pi + # these may be oriented horizontally or vertically + #-------------------------------------------------------------------------- + pb = fitz.Point(50, 200) # example values for + pe = fitz.Point(550, 200) # horizontal drawing + #pb = fitz.Point(300, 100) # example values for + #pe = fitz.Point(300, 600) # vertical drawing + page.drawLine(pb, pe, width = w) # draw x-axis (default color) + + # get all points for the sine function + pnt = bsinPoints(pb, pe) + # draw some points for better orientation + for i in (0, 3, 6, 9, 12): + page.drawCircle(pnt[i], 1, color = red) + # now draw a complete sine graph period in "red" + for i in (0, 3, 6, 9): # draw all 4 function segments + page.drawBezier(pnt[i], pnt[i+1], pnt[i+2], pnt[i+3], + color = red, width = w) + + # same thing for cosine with "blue" + pnt = bcosPoints(pb, pe) + for i in (0, 3, 6, 9, 12): + page.drawCircle(pnt[i], 1, color = blue) + for i in (0, 3, 6, 9): # draw all 4 function segments + page.drawBezier(pnt[i], pnt[i+1], pnt[i+2], pnt[i+3], + color = blue, width = w) + + # finally draw a rectangle around everything (in background): + rect = fitz.Rect(pb, pb) # create smallest rectangle + for p in pnt: # containing all the points + rect = rect | p + # leave 5 px space around the picture + rect.x0 -= 5 + rect.y0 -= 5 + rect.x1 += 5 + rect.y1 += 5 + page.drawRect(rect, width = w, fill = yellow, overlay = False) + doc.save("drawSines.pdf") From 37bbfedc58cdcef66d8d8939cfa14b2b93111c0c Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Thu, 17 Aug 2017 07:34:52 -0400 Subject: [PATCH 06/35] Create License.md --- .../Draw Sine Function in PDF/License.md | 674 ++++++++++++++++++ 1 file changed, 674 insertions(+) create mode 100644 recipes/Python/Draw Sine Function in PDF/License.md diff --git a/recipes/Python/Draw Sine Function in PDF/License.md b/recipes/Python/Draw Sine Function in PDF/License.md new file mode 100644 index 000000000..94a9ed024 --- /dev/null +++ b/recipes/Python/Draw Sine Function in PDF/License.md @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. From bc7c69f5218c6e6f829891194910bafe288ca4c0 Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Thu, 17 Aug 2017 07:36:41 -0400 Subject: [PATCH 07/35] Create README.md --- .../Draw Sine Function in PDF/README.md | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 recipes/Python/Draw Sine Function in PDF/README.md diff --git a/recipes/Python/Draw Sine Function in PDF/README.md b/recipes/Python/Draw Sine Function in PDF/README.md new file mode 100644 index 000000000..53265954c --- /dev/null +++ b/recipes/Python/Draw Sine Function in PDF/README.md @@ -0,0 +1,26 @@ +Created on 2017-08-17 + +@author: (c) 2017, Jorj X. McKie + +License: GNU GPL V3 + +PyMuPDF Demo Program +--------------------- +Create a PDF with drawings of the sine and cosine functions using PyMuPDF. +Depending on how start and end points are located with respect to each +other, horizontal or vertical drawings result. +The vertical case can obviously be used for creating inverse function +(arcus sine / cosine) graphs. + +The function graphs are pieced together in 90 degree parts, for which Bezier +curves are used. + +Note that the 'alfa' and 'beta' constants represent values for use as +Bezier control points like so: +x-values (written in degrees): [0, 30, 60, 90] +corresponding y-values: [0, alfa, beta, 1] + +These values have been calculated by the `scipy.interpolate.splrep()` method. +They provide an excellent spline approximation of the sine / cosine +functions - please look at SciPy documentation for background. + From 243e45614fb2ca3da450dffd87edf3a3e627eb57 Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Thu, 17 Aug 2017 07:40:51 -0400 Subject: [PATCH 08/35] Update README.md --- recipes/Python/Draw Sine Function in PDF/README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/recipes/Python/Draw Sine Function in PDF/README.md b/recipes/Python/Draw Sine Function in PDF/README.md index 53265954c..d1fc5b939 100644 --- a/recipes/Python/Draw Sine Function in PDF/README.md +++ b/recipes/Python/Draw Sine Function in PDF/README.md @@ -17,10 +17,11 @@ curves are used. Note that the 'alfa' and 'beta' constants represent values for use as Bezier control points like so: -x-values (written in degrees): [0, 30, 60, 90] -corresponding y-values: [0, alfa, beta, 1] -These values have been calculated by the `scipy.interpolate.splrep()` method. +* x-values (written in degrees): `[0, 30, 60, 90]` +* corresponding y-values: `[0, alfa, beta, 1]` + +These values have been calculated using the `scipy.interpolate.splrep()` method. They provide an excellent spline approximation of the sine / cosine functions - please look at SciPy documentation for background. From 4eadf1e468e3204fb100d0daf801aff92ae3fc38 Mon Sep 17 00:00:00 2001 From: Jim Scarborough Date: Wed, 23 Aug 2017 21:18:12 -0400 Subject: [PATCH 09/35] 2.7 compatibility for OrderedDictionary dict doesn't have keys() in older versions --- recipes/Python/107747_Ordered_Dictionary/recipe-107747.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py b/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py index 650377521..01d2a3dca 100644 --- a/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py +++ b/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py @@ -45,8 +45,9 @@ def setdefault(self, key, failobj = None): def update(self, dict): UserDict.update(self, dict) - for key in dict.keys(): - if key not in self._keys: self._keys.append(key) + for key in dict.__iter__(): + if key not in self._keys: + self._keys.append(key) def values(self): return map(self.get, self._keys) From 759becf449172016c270fcf0d70986fb72cbce11 Mon Sep 17 00:00:00 2001 From: Jim Scarborough Date: Wed, 23 Aug 2017 22:00:15 -0400 Subject: [PATCH 10/35] implement move_to_end(self, key) introduced in 3.2 --- recipes/Python/107747_Ordered_Dictionary/recipe-107747.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py b/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py index 01d2a3dca..35c9aa134 100644 --- a/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py +++ b/recipes/Python/107747_Ordered_Dictionary/recipe-107747.py @@ -51,3 +51,7 @@ def update(self, dict): def values(self): return map(self.get, self._keys) + + def move_to_end(self, key): + self._keys.remove(key) + self._keys.append(key) From 5665dcbe1aa2a358a30178e89f261ba5381b08a1 Mon Sep 17 00:00:00 2001 From: mrJean1 Date: Thu, 24 Aug 2017 20:20:35 -0400 Subject: [PATCH 11/35] Update recipe-546530.py Updated for one particular use case asizeof(all=True) to prevent crash with Python 3 in Pythonista on iOS. --- .../recipe-546530.py | 219 +++++++++++------- 1 file changed, 132 insertions(+), 87 deletions(-) diff --git a/recipes/Python/546530_Size_of_Python_objects_revised/recipe-546530.py b/recipes/Python/546530_Size_of_Python_objects_revised/recipe-546530.py index 451b28d07..30f0bfff2 100644 --- a/recipes/Python/546530_Size_of_Python_objects_revised/recipe-546530.py +++ b/recipes/Python/546530_Size_of_Python_objects_revised/recipe-546530.py @@ -3,6 +3,8 @@ # Copyright, license and disclaimer are at the very end of this file. # This is the latest, enhanced version of the asizeof.py recipes at +# , # # and . @@ -13,9 +15,10 @@ # memory footprint recipe . # Tested with 64-bit Python 2.6.9 (and numpy 1.6.2), 2.7.13 (and numpy -# 1.13.1), 3.5.3 and 3.6.2 on macOS 10.12.5 Sierra and with Pythonista -# 3.1 using 64-bit Python 2.7.12 and 3.5.1 (both with numpy 1.8.0) on -# iOS 10.3.2. +# 1.13.1), 3.5.3 and 3.6.2 on macOS 10.12.6 Sierra, with 64-bit Intel- +# Python 3.5.3 (and numpy 1.11.3) on macOS 10.12.6 Sierra and with +# Pythonista 3.1 using 64-bit Python 2.7.12 and 3.5.1 (both with numpy +# 1.8.0) on iOS 10.3.3. # Earlier versions of this module were tested with 32-bit Python 2.2.3, # 2.3.7, 2.4.5, 2.5.1, 2.5.2, 2.6.2, 3.0.1 or 3.1a2 on CentOS 4.6, SuSE @@ -222,7 +225,7 @@ class and the ``... def`` suffix marks the *definition object*. __all__ = ['adict', 'asized', 'asizeof', 'asizesof', 'Asized', 'Asizer', # classes 'basicsize', 'flatsize', 'itemsize', 'alen', 'refs'] -__version__ = '17.07.22' +__version__ = '17.08.24' # any classes or types in modules listed in _builtin_modules are # considered built-in and ignored by default, as built-in functions @@ -308,19 +311,19 @@ class ABCMeta(type): # behavior across Python version 2.2 thu 3.0 def _items(obj): # dict only - '''Returns iter-/generator, preferably. + '''Return iter-/generator, preferably. ''' return getattr(obj, 'iteritems', obj.items)() def _keys(obj): # dict only - '''Returns iter-/generator, preferably. + '''Return iter-/generator, preferably. ''' return getattr(obj, 'iterkeys', obj.keys)() def _values(obj): # dict only - '''Returns iter-/generator, preferably. + '''Return iter-/generator, preferably. ''' return getattr(obj, 'itervalues', obj.values)() @@ -340,6 +343,15 @@ def _iscallable(obj): _cell_type = type(c.func_closure[0]) del c +try: + from gc import get_objects as _getobjects # containers only? +except ImportError: + def _getobjects(): + # modules first, globals and stack + # objects (may contain duplicates) + return tuple(_values(sys.modules)) + ( + globals(), stack(sys.getrecursionlimit())[2:]) + try: # only used to get referents of # iterators, but gc.get_referents() # returns () for dict...-iterators @@ -361,7 +373,7 @@ def _intern(val): # private functions def _basicsize(t, base=0, heap=False, obj=None): - '''Gets non-zero basicsize of type, + '''Get non-zero basicsize of type, including the header sizes. ''' s = max(getattr(t, '__basicsize__', 0), base) @@ -385,13 +397,13 @@ def _c100(stats): def _classof(obj, dflt=None): - '''Returns the object's class object. + '''Return the object's class object. ''' return getattr(obj, '__class__', dflt) def _derive_typedef(typ): - '''Returns single, existing super type typedef or None. + '''Return single, existing super type typedef or None. ''' v = [v for v in _values(_typedefs) if _issubclass(typ, v.type)] if len(v) == 1: @@ -400,7 +412,7 @@ def _derive_typedef(typ): def _dir2(obj, pref='', excl=(), slots=None, itor=''): - '''Returns an attribute name, object 2-tuple for certain + '''Return an attribute name, object 2-tuple for certain attributes or for the ``__slots__`` attributes of the given object, but not both. Any iterator referent objects are returned with the given name if the @@ -433,7 +445,7 @@ def _dir2(obj, pref='', excl=(), slots=None, itor=''): def _infer_dict(obj): - '''Returns True for likely dict object via duck typing. + '''Return True for likely dict object via duck typing. ''' for ats in (('__len__', 'get', 'has_key', 'items', 'keys', 'update', 'values'), ('__len__', 'get', 'has_key', 'iteritems', 'iterkeys', 'itervalues')): @@ -443,18 +455,27 @@ def _infer_dict(obj): def _iscell(obj): - '''Returns True if obj is a cell as used in a closure. + '''Return True if obj is a cell as used in a closure. ''' return isinstance(obj, _cell_type) def _isdictclass(obj): - '''Returns True for known dict objects. + '''Return True for known dict objects. ''' c = _classof(obj) return c and c.__name__ in _dict_classes.get(c.__module__, ()) +def _isframe(obj): + '''Return True for a stack frame object. + ''' + try: # safe isframe(), see pympler.muppy + return isframe(obj) + except ReferenceError: + return False + + def _isnamedtuple(obj): '''Named tuples are identified via duck typing: @@ -462,8 +483,18 @@ def _isnamedtuple(obj): return isinstance(obj, tuple) and hasattr(obj, '_fields') +def _isNULL(obj): + '''Prevent asizeof(all=True, ...) crash. + + Sizing gc.get_objects() crashes in Pythonista3 with + Python 3.5.1 on iOS due to 1-tuple (,) object. + ''' + return isinstance(obj, tuple) and len(obj) == 1 \ + and repr(obj) == '(,)' + + def _isnumpy(obj): - '''Returns True for a NumPy arange, array, matrix, etc. instance. + '''Return True for a NumPy arange, array, matrix, etc. instance. ''' if _numpy_types: # see also _len_numpy return isinstance(obj, _numpy_types) or \ @@ -484,7 +515,7 @@ def _issubclass(sub, sup): def _itemsize(t, item=0): - '''Gets non-zero itemsize of type. + '''Get non-zero itemsize of type. ''' # replace zero value with default return getattr(t, '__itemsize__', 0) or item @@ -510,37 +541,37 @@ def _lengstr(obj): def _moduleof(obj, dflt=''): - '''Returns the object's module name. + '''Return the object's module name. ''' return getattr(obj, '__module__', dflt) def _nameof(obj, dflt=''): - '''Returns the name of an object. + '''Return the name of an object. ''' return getattr(obj, '__name__', dflt) def _objs_opts(objs, all=None, **opts): - '''Returns given or 'all' objects + '''Return given or 'all' objects and the remaining options. ''' if objs: # given objects t = objs elif all in (False, None): t = () - elif all is True: # 'all' objects ... - # ... modules first, globals and stack - # (may contain duplicate objects) - t = tuple(_values(sys.modules)) + ( - globals(), stack(sys.getrecursionlimit())[2:]) + elif all is True: # 'all' objects + t = tuple(_getobjects()) + if sys.platform == 'ios': + # remove any tuples containing NULLs + t = tuple(o for o in t if not _isNULL(o)) else: raise ValueError('invalid option: %s=%r' % ('all', all)) return t, opts def _p100(part, total, prec=1): - '''Returns percentage as string. + '''Return percentage as string. ''' r = float(total) if r: @@ -550,7 +581,7 @@ def _p100(part, total, prec=1): def _plural(num): - '''Returns 's' if plural. + '''Return 's' if plural. ''' if num == 1: s = '' @@ -595,7 +626,7 @@ def _printf(fmt, *args, **print3opts): def _refs(obj, named, *attrs, **kwds): - '''Returns specific attribute objects of an object. + '''Return specific attribute objects of an object. ''' if named: _N = _NamedRef @@ -626,7 +657,7 @@ def _repr(obj, clip=80): def _SI(size, K=1024, i='i'): - '''Returns size as SI string. + '''Return size as SI string. ''' if 1 < K < size: f = float(size) @@ -638,7 +669,7 @@ def _SI(size, K=1024, i='i'): def _SI2(size, **kwds): - '''Returns size as regular plus SI string. + '''Return size as regular plus SI string. ''' return str(size) + _SI(size, **kwds) @@ -650,20 +681,20 @@ def _cell_refs(obj, named): def _class_refs(obj, named): - '''Returns specific referents of a class object. + '''Return specific referents of a class object. ''' return _refs(obj, named, '__class__', '__dict__', '__doc__', '__mro__', '__name__', '__slots__', '__weakref__') def _co_refs(obj, named): - '''Returns specific referents of a code object. + '''Return specific referents of a code object. ''' return _refs(obj, named, pref='co_') def _dict_refs(obj, named): - '''Returns key and value objects of a dict/proxy. + '''Return key and value objects of a dict/proxy. ''' try: if named: @@ -680,39 +711,39 @@ def _dict_refs(obj, named): def _enum_refs(obj, named): - '''Returns specific referents of an enumerate object. + '''Return specific referents of an enumerate object. ''' return _refs(obj, named, '__doc__') def _exc_refs(obj, named): - '''Returns specific referents of an Exception object. + '''Return specific referents of an Exception object. ''' # .message raises DeprecationWarning in Python 2.6 return _refs(obj, named, 'args', 'filename', 'lineno', 'msg', 'text') # , 'message', 'mixed' def _file_refs(obj, named): - '''Returns specific referents of a file object. + '''Return specific referents of a file object. ''' return _refs(obj, named, 'mode', 'name') def _frame_refs(obj, named): - '''Returns specific referents of a frame object. + '''Return specific referents of a frame object. ''' return _refs(obj, named, pref='f_') def _func_refs(obj, named): - '''Returns specific referents of a function or lambda object. + '''Return specific referents of a function or lambda object. ''' return _refs(obj, named, '__doc__', '__name__', '__code__', '__closure__', pref='func_', excl=('func_globals',)) def _gen_refs(obj, named): - '''Returns the referent(s) of a generator object. + '''Return the referent(s) of a generator object. ''' # only some gi_frame attrs f = getattr(obj, 'gi_frame', None) @@ -720,26 +751,26 @@ def _gen_refs(obj, named): def _im_refs(obj, named): - '''Returns specific referents of a method object. + '''Return specific referents of a method object. ''' return _refs(obj, named, '__doc__', '__name__', '__code__', pref='im_') def _inst_refs(obj, named): - '''Returns specific referents of a class instance. + '''Return specific referents of a class instance. ''' return _refs(obj, named, '__dict__', '__class__', slots='__slots__') def _iter_refs(obj, named): - '''Returns the referent(s) of an iterator object. + '''Return the referent(s) of an iterator object. ''' r = _getreferents(obj) # special case return _refs(r, named, itor=_nameof(obj) or 'iteref') def _module_refs(obj, named): - '''Returns specific referents of a module object. + '''Return specific referents of a module object. ''' # ignore this very module if obj.__name__ == __name__: @@ -749,7 +780,7 @@ def _module_refs(obj, named): def _namedtuple_refs(obj, named): - '''Returns specific referents of obj-as-sequence and slots but exclude dict. + '''Return specific referents of obj-as-sequence and slots but exclude dict. ''' for r in _refs(obj, named, '__class__', slots='__slots__'): yield r @@ -758,44 +789,44 @@ def _namedtuple_refs(obj, named): def _prop_refs(obj, named): - '''Returns specific referents of a property object. + '''Return specific referents of a property object. ''' return _refs(obj, named, '__doc__', pref='f') def _seq_refs(obj, unused): # named unused for PyChecker - '''Returns specific referents of a frozen/set, list, tuple and xrange object. + '''Return specific referents of a frozen/set, list, tuple and xrange object. ''' return obj # XXX for r in obj: yield r def _stat_refs(obj, named): - '''Returns referents of a os.stat object. + '''Return referents of a os.stat object. ''' return _refs(obj, named, pref='st_') def _statvfs_refs(obj, named): - '''Returns referents of a os.statvfs object. + '''Return referents of a os.statvfs object. ''' return _refs(obj, named, pref='f_') def _tb_refs(obj, named): - '''Returns specific referents of a traceback object. + '''Return specific referents of a traceback object. ''' return _refs(obj, named, pref='tb_') def _type_refs(obj, named): - '''Returns specific referents of a type object. + '''Return specific referents of a type object. ''' return _refs(obj, named, '__dict__', '__doc__', '__mro__', '__name__', '__slots__', '__weakref__') def _weak_refs(obj, unused): # named unused for PyChecker - '''Returns weakly referent object. + '''Return weakly referent object. ''' try: # ignore 'key' of KeyedRef return (obj(),) @@ -1041,7 +1072,7 @@ def _instkey(obj): return k def _keytuple(obj): - '''Returns class and instance keys for a class. + '''Return class and instance keys for a class. ''' t = type(obj) if t is _Types_InstanceType: @@ -1054,7 +1085,7 @@ def _keytuple(obj): return None, None # not a class def _objkey(obj): - '''Returns the key for any object. + '''Return the key for any object. ''' k = type(obj) if k is _Types_InstanceType: @@ -1068,14 +1099,14 @@ def _objkey(obj): except AttributeError: # Python 3.0 def _keytuple(obj): # PYCHOK expected - '''Returns class and instance keys for a class. + '''Return class and instance keys for a class. ''' if type(obj) is _Type_type: # isclass(obj): return _claskey(obj, _new_style), obj return None, None # not a class def _objkey(obj): # PYCHOK expected - '''Returns the key for any object. + '''Return the key for any object. ''' k = type(obj) if k is _Type_type: # isclass(obj): @@ -1146,7 +1177,7 @@ def __str__(self): return ', '.join(t) def args(self): # as args tuple - '''Returns all attributes as arguments tuple. + '''Return all attributes as arguments tuple. ''' return (self.base, self.item, self.alen, self.refs, self.both, self.kind, self.type) @@ -1162,7 +1193,7 @@ def dup(self, other=None, **kwds): self.reset(**d) def flat(self, obj, mask=0): - '''Returns the aligned flat size. + '''Return the aligned flat size. ''' s = self.base if self.alen and self.item > 0: # include items @@ -1174,7 +1205,7 @@ def flat(self, obj, mask=0): return s def format(self): - '''Returns format dict. + '''Return format dict. ''' i = self.item if self.vari: @@ -1188,7 +1219,7 @@ def format(self): kind=self.kind) def kwds(self): - '''Returns all attributes as keywords dict. + '''Return all attributes as keywords dict. ''' return dict(base=self.base, item=self.item, alen=self.alen, refs=self.refs, @@ -1457,7 +1488,7 @@ def _numpy_kwds(obj): raise AssertionError('not %s: %r' % ('numpy', d)) # sizing numpy 1.13 arrays works fine, but 1.8 and older - # appears to suffer from sys.getsizeof() bug as array + # appears to suffer from sys.getsizeof() bug like array v = tuple(map(int, numpy.__version__.split('.'))) _numpy_excl = v < (1, 9, 0) if _numpy_excl: # see function _typedef below @@ -1621,7 +1652,7 @@ def _typedef(obj, derive=False, infer=False): # MCCABE 24 v.dup(item=_dict_typedef.item + _sizeof_CPyModuleObject, alen=_len_module, refs=_module_refs) - elif isframe(obj): + elif _isframe(obj): v.set(base=_basicsize(t, base=_sizeof_CPyFrameObject, obj=obj), item=_itemsize(t), alen=_len_frame, @@ -1714,7 +1745,7 @@ def __lt__(self, other): # for Python 3.0 return self.__cmp__(other) < 0 def format(self, clip=0, grand=None): - '''Returns format dict. + '''Return format dict. ''' if self.number > 1: # avg., plural a, p = int(self.total / self.number), 's' @@ -1796,7 +1827,7 @@ def format(self, format='%(name)s size=%(size)d flat=%(flat)d', return '\n'.join(lines) def get(self, name, dflt=None): - '''Returns the named referent (or *dflt* if not found). + '''Return the named referent (or *dflt* if not found). ''' for ref in self.refs: if name == ref.name: @@ -1805,7 +1836,7 @@ def get(self, name, dflt=None): class Asizer(object): - '''Sizer state and options. + '''State and options to accumulate sizes. ''' _align_ = 8 _clip_ = 80 @@ -1867,7 +1898,7 @@ def _clear(self): self._excl_d[k] = 0 def _nameof(self, obj): - '''Returns the object's name. + '''Return the object's name. ''' return _nameof(obj, '') or self._repr(obj) @@ -1877,7 +1908,7 @@ def _prepr(self, obj): return _prepr(obj, clip=self._clip_) def _prof(self, key): - '''Gets _Prof object. + '''Get _Prof object. ''' p = self._profs.get(key, None) if not p: @@ -1945,7 +1976,7 @@ def _sizer(self, obj, deep, sized): # MCCABE 16 return s def _sizes(self, objs, sized=None): - '''Returns the size or an **Asized** instance for each given + '''Return the size or an **Asized** instance for each given object and the total size. The total includes the size of any duplicates only once. ''' @@ -1982,7 +2013,7 @@ def asized(self, *objs, **opts): return t def asizeof(self, *objs, **opts): - '''Returns the combined size of the given objects (with modified + '''Return the combined size of the given objects (with modified options, see method **set**). ''' if opts: @@ -1991,7 +2022,7 @@ def asizeof(self, *objs, **opts): return s def asizesof(self, *objs, **opts): - '''Returns the individual sizes of the given objects (with + '''Return the individual sizes of the given objects (with modified options, see method **set**). ''' if opts: @@ -2298,7 +2329,7 @@ def adict(*classes): def asized(*objs, **opts): - '''Returns a tuple containing an **Asized** instance for each + '''Return a tuple containing an **Asized** instance for each object passed as positional argument. The available options and defaults are: @@ -2343,7 +2374,7 @@ def asized(*objs, **opts): def asizeof(*objs, **opts): - '''Returns the combined size (in bytes) of all objects passed + '''Return the combined size (in bytes) of all objects passed as positional arguments. The available options and defaults are: @@ -2369,8 +2400,9 @@ def asizeof(*objs, **opts): Set *align* to a power of 2 to align sizes. Any value less than 2 avoids size alignment. - All current module, global and stack objects are sized if - *all* is True and if no positional arguments are supplied. + If *all* is True and if no positional arguments are supplied. + size all current gc objects, including module, global and stack + frame objects. A positive *clip* value truncates all repr() strings to at most *clip* characters. @@ -2416,7 +2448,7 @@ def asizeof(*objs, **opts): def asizesof(*objs, **opts): - '''Returns a tuple containing the size (in bytes) of all objects + '''Return a tuple containing the size (in bytes) of all objects passed as positional argments. The available options and defaults are: @@ -2454,7 +2486,7 @@ def asizesof(*objs, **opts): def _typedefof(obj, save=False, **opts): - '''Gets the typedef for an object. + '''Get the typedef for an object. ''' k = _objkey(obj) v = _typedefs.get(k, None) @@ -2466,7 +2498,7 @@ def _typedefof(obj, save=False, **opts): def alen(obj, **opts): - '''Returns the length of an object (in *items*). + '''Return the length of an object (in *items*). See function **basicsize** for a description of the options. ''' @@ -2486,7 +2518,7 @@ def alen(obj, **opts): def basicsize(obj, **opts): - '''Returns the basic size of an object (in bytes). + '''Return the basic size of an object (in bytes). The available options and defaults are: @@ -2503,7 +2535,7 @@ def basicsize(obj, **opts): def flatsize(obj, align=0, **opts): - '''Returns the flat size of an object (in bytes), optionally aligned + '''Return the flat size of an object (in bytes), optionally aligned to a given power of 2. See function **basicsize** for a description of all other options. @@ -2523,7 +2555,7 @@ def flatsize(obj, align=0, **opts): def itemsize(obj, **opts): - '''Returns the item size of an object (in bytes). + '''Return the item size of an object (in bytes). See function **basicsize** for a description of the options. ''' @@ -2555,7 +2587,7 @@ def named_refs(obj, **opts): def refs(obj, **opts): - '''Returns (a generator for) specific *referents* of an object. + '''Return (a generator for) specific *referents* of an object. See function **basicsize** for a description of the options. ''' @@ -2569,15 +2601,28 @@ def refs(obj, **opts): if __name__ == '__main__': - # Show all static _typedefs - - n = len(_typedefs) - w = len(str(n)) * ' ' - _printf('%s%d type definitions: basic- and itemsize (alen), kind ... %s', linesep, n, '-type[def]s') - for k, v in sorted((_prepr(k), v) for k, v in _items(_typedefs)): - s = '%(base)s and %(item)s%(alen)s, %(kind)s%(code)s' % v.format() - _printf('%s %s: %s', w, k, s) + if '-types' in sys.argv: # print static _typedefs + n = len(_typedefs) + w = len(str(n)) * ' ' + _printf('%s%d type definitions: %s and %s, kind ... %s', linesep, + n, 'basic-', 'itemsize (alen)', '-type[def]s') + for k, v in sorted((_prepr(k), v) for k, v in _items(_typedefs)): + s = '%(base)s and %(item)s%(alen)s, %(kind)s%(code)s' % v.format() + _printf('%s %s: %s', w, k, s) + else: + if '-gc' in sys.argv: + try: + import gc # PYCHOK expected + gc.collect() + except ImportError: + pass + + # just an example + asizeof(all=True, stats=2) # print summary + + if '-v' in sys.argv: + print('\n%s %s (Python %s)' % (__file__, __version__, sys.version.split()[0])) # License from the initial version of this source file follows: From c7874c0f563289c061de540269782f946769d22f Mon Sep 17 00:00:00 2001 From: kekePower Date: Sat, 2 Sep 2017 17:47:16 +0200 Subject: [PATCH 12/35] Update recipe-578578.sh The old way didn't work for me and I've updated it to use http://icanhazip.com. It displays only the IP-address as the only output and we only grep for anything. Also added a curl option. --- recipes/Bash/578578_Get_external_IP/recipe-578578.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/recipes/Bash/578578_Get_external_IP/recipe-578578.sh b/recipes/Bash/578578_Get_external_IP/recipe-578578.sh index ab1c8a46d..a6d86af61 100644 --- a/recipes/Bash/578578_Get_external_IP/recipe-578578.sh +++ b/recipes/Bash/578578_Get_external_IP/recipe-578578.sh @@ -1,5 +1,5 @@ -wget -qO - http://internet.yandex.ru | grep IPv4 | awk '{print($2,$3)}' +wget -qO - http://icanhazip.com | grep ^ # or -wget -qO - http://internet.yandex.ru | grep -oP 'IPv4:\s(\d+\.){3}\d+' +lynx --dump http://icanhazip.com | grep ^ # or -lynx --dump http://internet.yandex.ru | grep IPv4 | awk '{print($2,$3)}' +curl -s http://icanhazip.com | grep ^ From e463b980a31c094a702496d1057ad593b6ccad91 Mon Sep 17 00:00:00 2001 From: kekePower Date: Sat, 2 Sep 2017 17:51:18 +0200 Subject: [PATCH 13/35] Fixed a new-line issue with lynx Lynx displayed a new-line after the expected output. This addition fixes this issue. --- recipes/Bash/578578_Get_external_IP/recipe-578578.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/recipes/Bash/578578_Get_external_IP/recipe-578578.sh b/recipes/Bash/578578_Get_external_IP/recipe-578578.sh index a6d86af61..12f8cf886 100644 --- a/recipes/Bash/578578_Get_external_IP/recipe-578578.sh +++ b/recipes/Bash/578578_Get_external_IP/recipe-578578.sh @@ -1,5 +1,5 @@ wget -qO - http://icanhazip.com | grep ^ # or -lynx --dump http://icanhazip.com | grep ^ +lynx --dump http://icanhazip.com | grep ^ | head -1 # or curl -s http://icanhazip.com | grep ^ From 90f423da775cddcf1fdcb3627cd3882fe4f9f7fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stig-=C3=98rjan=20Smelror?= Date: Sat, 2 Sep 2017 18:22:45 +0200 Subject: [PATCH 14/35] Using lsb_release to determine the distribution. It usually comes with every new Linux distribution, but it has to be installed. First check is if it is present and if not, aborts with a message. If present, presents the user with a list of strings that can later be manipulated. --- .../recipe-576676.sh | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100755 recipes/Bash/576676_How_detect_Linux_distributiinitd/recipe-576676.sh diff --git a/recipes/Bash/576676_How_detect_Linux_distributiinitd/recipe-576676.sh b/recipes/Bash/576676_How_detect_Linux_distributiinitd/recipe-576676.sh new file mode 100755 index 000000000..187165842 --- /dev/null +++ b/recipes/Bash/576676_How_detect_Linux_distributiinitd/recipe-576676.sh @@ -0,0 +1,14 @@ +#!/bin/bash + +LSB=$( which lsb_release ) + +if [[ ! ${LSB} ]]; then + + echo "LSB is not installed. Unable to determine your distribution." + exit + +else + + ${LSB} -a | grep -v LSB + +fi \ No newline at end of file From 4affc91538ce737f055a3b49c1cf539610a68e5b Mon Sep 17 00:00:00 2001 From: Muhammad Arslan Date: Sat, 2 Sep 2017 22:17:05 +0500 Subject: [PATCH 15/35] Combinations without using factorials-Python Signed-off-by: Muhammad Arslan --- .../LICENSE | 21 +++++++++++++++++++ .../README.md | 11 ++++++++++ .../combo.py | 11 ++++++++++ 3 files changed, 43 insertions(+) create mode 100644 recipes/Python/Combination without using factorials/LICENSE create mode 100644 recipes/Python/Combination without using factorials/README.md create mode 100644 recipes/Python/Combination without using factorials/combo.py diff --git a/recipes/Python/Combination without using factorials/LICENSE b/recipes/Python/Combination without using factorials/LICENSE new file mode 100644 index 000000000..a4d32d2ed --- /dev/null +++ b/recipes/Python/Combination without using factorials/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Muhammad Arslan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/recipes/Python/Combination without using factorials/README.md b/recipes/Python/Combination without using factorials/README.md new file mode 100644 index 000000000..a28b1deaf --- /dev/null +++ b/recipes/Python/Combination without using factorials/README.md @@ -0,0 +1,11 @@ +Created on 2017-09-02 + +Author : Muhammad Arslan + +Licence : MIT + +Finding the number of combinations (nCr) without use of factorials +------------------------------------------------------------------ + +Using factorials recursively can greatly reduce performance and use a lot of memory especially when finding nCr of large sets. This aims to correct that to some extent. +Enjoy and provide me with suggestions if any. diff --git a/recipes/Python/Combination without using factorials/combo.py b/recipes/Python/Combination without using factorials/combo.py new file mode 100644 index 000000000..504cfc6b7 --- /dev/null +++ b/recipes/Python/Combination without using factorials/combo.py @@ -0,0 +1,11 @@ +#!/usr/bin/env python + +import operator as op + + +def ncr(n, r): + r = min(r, n-r) + if x == 0: return 1 + num = reduce(op.mul, xrange(n, n-1, -1)) + denom = reduce(op.mul, xrange(1, r+1)) + return num // denom From 0bbecb2bed4e5183b15b1af7c2ce024cb387b8b5 Mon Sep 17 00:00:00 2001 From: Muhammad Arslan Date: Sat, 2 Sep 2017 22:28:36 +0500 Subject: [PATCH 16/35] Removed 1st line. Signed-off-by: Muhammad Arslan --- recipes/Python/Combination without using factorials/combo.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/recipes/Python/Combination without using factorials/combo.py b/recipes/Python/Combination without using factorials/combo.py index 504cfc6b7..b256bff0c 100644 --- a/recipes/Python/Combination without using factorials/combo.py +++ b/recipes/Python/Combination without using factorials/combo.py @@ -1,5 +1,3 @@ -#!/usr/bin/env python - import operator as op From 7fb6c00ddf7d1f58d82fb849ab72f60f7d080477 Mon Sep 17 00:00:00 2001 From: Muhammad Arslan Date: Sat, 9 Sep 2017 15:27:55 +0500 Subject: [PATCH 17/35] 2D Matrix Operations without using Numpy Signed-off-by: Muhammad Arslan --- .../Matrix Operations without numpy/LICENSE | 21 +++++++++ .../Matrix Operations without numpy/README.md | 11 +++++ .../matrix_ops.py | 43 +++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 recipes/Python/Matrix Operations without numpy/LICENSE create mode 100644 recipes/Python/Matrix Operations without numpy/README.md create mode 100644 recipes/Python/Matrix Operations without numpy/matrix_ops.py diff --git a/recipes/Python/Matrix Operations without numpy/LICENSE b/recipes/Python/Matrix Operations without numpy/LICENSE new file mode 100644 index 000000000..a4d32d2ed --- /dev/null +++ b/recipes/Python/Matrix Operations without numpy/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Muhammad Arslan + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/recipes/Python/Matrix Operations without numpy/README.md b/recipes/Python/Matrix Operations without numpy/README.md new file mode 100644 index 000000000..bdcf95b2a --- /dev/null +++ b/recipes/Python/Matrix Operations without numpy/README.md @@ -0,0 +1,11 @@ +Created on 2017-09-09 + +Author : Muhammad Arslan + +Licence : MIT + +2-D Matrix operations without the use of numpy module +------------------------------------------------------------------ + +In situations where numpy module isn't available, you can use these functions to calculate the inverse, determinant, transpose of matrix, calculate the minors of it's elements, and multiply two matrices together. +Any advice to make these functions better will be appreciated. diff --git a/recipes/Python/Matrix Operations without numpy/matrix_ops.py b/recipes/Python/Matrix Operations without numpy/matrix_ops.py new file mode 100644 index 000000000..a7baa2356 --- /dev/null +++ b/recipes/Python/Matrix Operations without numpy/matrix_ops.py @@ -0,0 +1,43 @@ +def transpose(matrix): + return [[row[i] for row in matrix] for i in range(len(matrix[0]))] + + +def multip(X, Y): + return [[sum(a*b for a, b in zip(X_row, Y_col)) for Y_col in zip(*Y)] for X_row in X] + + +def getMatrixMinor(m, i, j): + return [row[:j] + row[j+1:] for row in (m[:i]+m[i+1:])] + + +def getMatrixDeternminant(m): + # base case for 2x2 matrix + if len(m) == 2: + return (m[0][0]*m[1][1]-m[0][1]*m[1][0])*1.0 + + determinant = 0 + for c in range(len(m)): + determinant += ((-1.0)**c)*m[0][c]*getMatrixDeternminant(getMatrixMinor(m, 0, c)) + return determinant + + +def getMatrixInverse(m): + determinant = getMatrixDeternminant(m) + # special case for 2x2 matrix: + if len(m) == 2: + return [[m[1][1]/determinant, -1*m[0][1]/determinant], + [-1*m[1][0]/determinant, m[0][0]/determinant]] + + # find matrix of cofactors + cofactors = [] + for r in range(len(m)): + cofactorRow = [] + for c in range(len(m)): + minor = getMatrixMinor(m,r,c) + cofactorRow.append(((-1)**(r+c)) * getMatrixDeternminant(minor)) + cofactors.append(cofactorRow) + cofactors = transpose(cofactors) + for r in range(len(cofactors)): + for c in range(len(cofactors)): + cofactors[r][c] = cofactors[r][c]/determinant + return cofactors \ No newline at end of file From e3c7942931642da1c52cf6a489675b1e1f4b5962 Mon Sep 17 00:00:00 2001 From: kgashok Date: Sat, 16 Sep 2017 04:05:36 -0700 Subject: [PATCH 18/35] added function for Python3 (#1) --- .../Python/Combination without using factorials/combo.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/recipes/Python/Combination without using factorials/combo.py b/recipes/Python/Combination without using factorials/combo.py index b256bff0c..ec61d9d02 100644 --- a/recipes/Python/Combination without using factorials/combo.py +++ b/recipes/Python/Combination without using factorials/combo.py @@ -7,3 +7,10 @@ def ncr(n, r): num = reduce(op.mul, xrange(n, n-1, -1)) denom = reduce(op.mul, xrange(1, r+1)) return num // denom + +def ncr3(n, r): + r = min(r, n-r) + if x == 0: return 1 + num = reduce(op.mul, range(n, n-1, -1)) + denom = reduce(op.mul, range(1, r+1)) + return num // denom From 913a1316eca127d6d28ea2684b8f7fde8ea67433 Mon Sep 17 00:00:00 2001 From: Thomas Lehmann Date: Fri, 29 Sep 2017 05:48:09 +0200 Subject: [PATCH 19/35] recipe calculator --- .../Python/93379_Recipe_Calculator/LICENSE.md | 7 ++ .../Python/93379_Recipe_Calculator/README.md | 98 +++++++++++++++++++ .../Python/93379_Recipe_Calculator/food.yml | 35 +++++++ .../fruit_cocktail.yml | 10 ++ .../Python/93379_Recipe_Calculator/pyfood.py | 78 +++++++++++++++ 5 files changed, 228 insertions(+) create mode 100644 recipes/Python/93379_Recipe_Calculator/LICENSE.md create mode 100644 recipes/Python/93379_Recipe_Calculator/README.md create mode 100644 recipes/Python/93379_Recipe_Calculator/food.yml create mode 100644 recipes/Python/93379_Recipe_Calculator/fruit_cocktail.yml create mode 100755 recipes/Python/93379_Recipe_Calculator/pyfood.py diff --git a/recipes/Python/93379_Recipe_Calculator/LICENSE.md b/recipes/Python/93379_Recipe_Calculator/LICENSE.md new file mode 100644 index 000000000..508c75022 --- /dev/null +++ b/recipes/Python/93379_Recipe_Calculator/LICENSE.md @@ -0,0 +1,7 @@ +Copyright 2017 Thomas Lehmann + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/recipes/Python/93379_Recipe_Calculator/README.md b/recipes/Python/93379_Recipe_Calculator/README.md new file mode 100644 index 000000000..9790ff61a --- /dev/null +++ b/recipes/Python/93379_Recipe_Calculator/README.md @@ -0,0 +1,98 @@ +# Welcome to the simple recipe calculator + +## Quickstart + +The example yml files you will find in the repository (no guarantee for food values; fetch your own): + - [food.yml](food.yml) + - [fruit_cocktail.yml](fruit_cocktail.yml) + +``` +python pyfood.py --yml-food=food.yml --yml-recipe=fruit_cocktail.yml + +Rezept: Frucht Cocktail für 3 Person(en) +____________________ ____ _____ _____ _____ _____ + Name # kcal KH E F +____________________ ____ _____ _____ _____ _____ + Kiwi 200 124.0 18.2 2.0 1.2 + Orange 300 141.0 24.9 3.0 0.6 + Apfel 400 260.0 57.6 1.2 0.4 + Himbeeren 350 150.5 16.8 4.5 1.1 + Heidelbeeren 250 97.5 15.0 2.5 0.0 + Zitrone 200 66.0 6.0 2.8 1.2 +____________________ ____ _____ _____ _____ _____ + Summe 839.0 138.5 16.0 4.5 + Pro Person 279.7 46.2 5.3 1.5 + Anteil % 87.1 10.1 2.8 + +``` + +You can see the name and the quantity of each food and +the calculated ingredients. As an example for the Kiwi +the double of the ingredient values is shown as specified +in the food yml file. + +At the end you can see the sum per ingredient and the +sum per ingredient value calculated for one person. + +Finally you see the percentages. Obviously the example is +not really low carb :) + +Hint: there are a lot of online locations to find those +food ingredients but usually buying food you often have +such information available on the article somewhere with +some exceptions of course. + +My personal rules I try to follow: + - at least 50% protein for a recipe (in most cases) + - avoid to eat more large calories as you should (can be roughly calculated -> internet) + - avoid fast food; buying fresh things + - do some sport (no athletic; just a litte bit does help; you can do it at home) + - we (my wife and me) are making our own low carb bread (as an example) + +## The structure of the food file + +Quite simple it's a list of entries like following: + +``` +- name: Some Food + large_calories: 1.1 + fat: 2.2 + carb:3.3 + protein: 3.3 +``` + +It's always the ingredients related to 100 gram or +100 millilitre of a concrete food. The tool does +not check that the sum of fat, carb and protein +is less or equal that limit. + +You can find an example file in the repository. +Please note: no guarantee on the value there; +I fetched them from somewhere for testing purpose only. + +## The structure of one recipe file + +You would have to organise one recipe per file and +one file looks like following: + +``` +--- +name: Frucht Cocktail +persons: 3 +food: + - { name: Kiwi, quantity: 200 } + - { name: .*nge, quantity: 300 } + - { name: Ap.*, quantity: 400 } + - { name: Him.*, quantity: 350 } + - { name: Heid.*, quantity: 250 } + - { name: Zi.*, quantity: 200 } +``` + +Of course you have name (title) and you specify +for how many person the recipe is. Finally +you have a food list where you specify the food +and how many gram/millilitre you take. + +The name is a Python compatible regular expression +so that you do not have to specify the full name. + diff --git a/recipes/Python/93379_Recipe_Calculator/food.yml b/recipes/Python/93379_Recipe_Calculator/food.yml new file mode 100644 index 000000000..0b406d3a6 --- /dev/null +++ b/recipes/Python/93379_Recipe_Calculator/food.yml @@ -0,0 +1,35 @@ +- name: Kiwi + large_calories: 62 + fat: 0.6 + carb: 9.1 + protein: 1.0 + +- name: Apfel + large_calories: 65 + fat: 0.1 + carb: 14.4 + protein: 0.3 + +- name: Orange + large_calories: 47 + fat: 0.2 + carb: 8.3 + protein: 1.0 + +- name: Heidelbeeren + large_calories: 39.0 + fat: 0.0 + carb: 6.0 + protein: 1.0 + +- name: Himbeeren + large_calories: 43.0 + fat: 0.3 + carb: 4.8 + protein: 1.3 + +- name: Zitrone + large_calories: 33.0 + fat: 0.6 + carb: 3.0 + protein: 1.4 diff --git a/recipes/Python/93379_Recipe_Calculator/fruit_cocktail.yml b/recipes/Python/93379_Recipe_Calculator/fruit_cocktail.yml new file mode 100644 index 000000000..552592b17 --- /dev/null +++ b/recipes/Python/93379_Recipe_Calculator/fruit_cocktail.yml @@ -0,0 +1,10 @@ +--- +name: Frucht Cocktail +persons: 3 +food: + - { name: Kiwi, quantity: 200 } + - { name: .*nge, quantity: 300 } + - { name: Ap.*, quantity: 400 } + - { name: Him.*, quantity: 350 } + - { name: Heid.*, quantity: 250 } + - { name: Zi.*, quantity: 200 } diff --git a/recipes/Python/93379_Recipe_Calculator/pyfood.py b/recipes/Python/93379_Recipe_Calculator/pyfood.py new file mode 100755 index 000000000..4cd777dd2 --- /dev/null +++ b/recipes/Python/93379_Recipe_Calculator/pyfood.py @@ -0,0 +1,78 @@ +#!/usr/bin/python +# -*- coding: iso-8859-15 -*- +""" +Recipe calculator. +""" +import re +import click +import yaml + +FORMAT = "%20s %4s %5s %5s %5s %5s" + + +@click.command() +@click.option('--yml-food', default="", help="Yaml file with food details") +@click.option('--yml-recipe', default="", help="Yaml file with recipe details") +def main(yml_food, yml_recipe): + food = yaml.load(open(yml_food).read()) + recipe = yaml.load(open(yml_recipe).read()) + + persons = int(recipe['persons']) + print("\nRezept: %s für %d Person(en)" % (recipe['name'], persons)) + + separator = FORMAT % ("_"*20, "_"*4, "_"*5, "_"*5, "_"*5, "_"*5) + + print(separator) + print(FORMAT % ("Name", "#", "kcal", "KH", "E", "F")) + print(separator) + + sum_large_calories = 0.0 + sum_carb = 0.0 + sum_protein = 0.0 + sum_fat = 0.0 + + for rentry in recipe['food']: + for fentry in food: + if re.match(rentry['name'], fentry['name']): + name = fentry['name'] + quantity = int(rentry['quantity']) + large_calories = round(quantity * fentry['large_calories'] / 100.0, 1) + carb = round(quantity * fentry['carb'] / 100.0, 1) + protein = round(quantity * fentry['protein'] / 100.0, 1) + fat = round(quantity * fentry['fat'] / 100.0, 1) + + print(FORMAT % (name, quantity, large_calories, carb, protein, fat)) + + sum_large_calories += large_calories + sum_carb += carb + sum_protein += protein + sum_fat += fat + break + + sum_ingredients = sum_carb + sum_protein + sum_fat + percentage_carb = round(sum_carb * 100.0 / sum_ingredients, 1) + percentage_protein = round(sum_protein * 100.0 / sum_ingredients, 1) + percentage_fat = round(sum_fat * 100.0 / sum_ingredients, 1) + + print(separator) + print(FORMAT % ("Summe", "", + sum_large_calories, + sum_carb, + sum_protein, + sum_fat)) + + print(FORMAT % ("Pro Person", "", + round(sum_large_calories / persons, 1), + round(sum_carb / persons, 1), + round(sum_protein / persons, 1), + round(sum_fat / persons, 1))) + + print(FORMAT % ("Anteil %", "", "", + percentage_carb, + percentage_protein, + percentage_fat)) + print("") + + +if __name__ == "__main__": + main() From 2ed807a4cfd94236d894576c252e9828b3b5024b Mon Sep 17 00:00:00 2001 From: UlrichBlumensaat Date: Tue, 3 Oct 2017 14:28:56 -0700 Subject: [PATCH 20/35] Update README.md --- recipes/Python/578996_Snake_the_game/README.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/recipes/Python/578996_Snake_the_game/README.md b/recipes/Python/578996_Snake_the_game/README.md index 45cefb38c..0282fb272 100644 --- a/recipes/Python/578996_Snake_the_game/README.md +++ b/recipes/Python/578996_Snake_the_game/README.md @@ -1,7 +1,7 @@ -## Snake the game -Originally published: 2015-01-03 01:54:04 -Last updated: 2015-01-03 02:04:02 -Author: Veysel Nantu - -Popular Snake game with Python-Pygame module. **Important:** If you try to run this script without special **png-wav** files it will fail, you have to put following files to a directory with this script. "apple.png","snakehead.png","intro.wav","dead.wav". They are basically apple picture, head of snake, intro sound and dead sound.Without them script will not run. Just make inactive the statements intro.wav and dead.wav, and find a little apple picture and snake head :).Or you can play the game just install it. **Here is the installer:** http://dosya.co/7c6f15c0f4d04514/Flafel-1.26-win32.rar -It will install the game in program files, you can find it in search "Flafel" and click to Flafel.exe. \ No newline at end of file +## Snake the game +Originally published: 2015-01-03 01:54:04 +Last updated: 2015-01-03 02:04:02 +Author: Veysel Nantu + +Popular Snake game with Python-Pygame module. **Important:** If you try to run this script without special **png-wav** files it will fail, you have to put following files to a directory with this script. "apple.png","snakehead.png","intro.wav","dead.wav". They are basically apple picture, head of snake, intro sound and dead sound.Without them script will not run. Just make inactive the statements intro.wav and dead.wav, and find a little apple picture and snake head :).Or you can play the game just install it. **Here is the installer:** LINK-REMOVED-BECAUSE-IT-WAS-INVALID +It will install the game in program files, you can find it in search "Flafel" and click to Flafel.exe. From 53238d7841a08c1d291178289b4d55353090f357 Mon Sep 17 00:00:00 2001 From: Gabriel Freitas Date: Sat, 7 Oct 2017 20:37:18 +0200 Subject: [PATCH 21/35] Performance improvements * used itertools.count to improve readability * used arithmetic properties on odd and even numbers to only work with odd numbers, effectively improving function's speed * removed the __future__ import, which has become obsolete on the actual major versions of python2 and python3 --- .../recipe-117119.py | 29 ++++++++++--------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/recipes/Python/117119_Sieve_of_Eratosthenes/recipe-117119.py b/recipes/Python/117119_Sieve_of_Eratosthenes/recipe-117119.py index 300699840..d3f5997d4 100644 --- a/recipes/Python/117119_Sieve_of_Eratosthenes/recipe-117119.py +++ b/recipes/Python/117119_Sieve_of_Eratosthenes/recipe-117119.py @@ -1,18 +1,19 @@ # Sieve of Eratosthenes -# David Eppstein, UC Irvine, 28 Feb 2002 +# Originaly made by : David Eppstein, UC Irvine, 28 Feb 2002 +# Performance improvements : Gabriel Freitas, 7 Oct 2017 -from __future__ import generators +from itertools import count def eratosthenes(): - '''Yields the sequence of prime numbers via the Sieve of Eratosthenes.''' - D = {} # map composite integers to primes witnessing their compositeness - q = 2 # first integer to test for primality - while 1: - if q not in D: - yield q # not marked composite, must be prime - D[q*q] = [q] # first multiple of q not already marked - else: - for p in D[q]: # move each witness to its next multiple - D.setdefault(p+q,[]).append(p) - del D[q] # no longer need D[q], free memory - q += 1 + """Yields the sequence of prime numbers via the Sieve of Eratosthenes""" + yield 2 # force yield the first prime number + + D = {} # map composite integers to primes witnessing their compositeness + for q in count(start=3, step=2): + if q not in D: + yield q # not marked composite, must be prime + D[q*q] = [q] # first multiple of q not already marked + else: + for p in D[q]: # move each witness to its next odd multiple + D.setdefault(2*p+q,[]).append(p) + del D[q] # no longer need D[q], free memory From 541ca8142056242f63cae3976be34bfda555b76f Mon Sep 17 00:00:00 2001 From: anishk23733 Date: Sun, 8 Oct 2017 08:33:59 -0700 Subject: [PATCH 22/35] Web Interaction with Selenium Automate your web processes with the infamous Selenium python module. Added code to run the Chromedriver and perform some basic functions. --- .../Selenium_For_Web_Scraping/README.md | 17 +++++++++++++++++ .../selenium_main.py | 19 +++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 recipes/Python/Selenium_For_Web_Scraping/README.md create mode 100644 recipes/Python/Selenium_For_Web_Scraping/selenium_main.py diff --git a/recipes/Python/Selenium_For_Web_Scraping/README.md b/recipes/Python/Selenium_For_Web_Scraping/README.md new file mode 100644 index 000000000..c2eb66552 --- /dev/null +++ b/recipes/Python/Selenium_For_Web_Scraping/README.md @@ -0,0 +1,17 @@ +Created on 2017-10-08 + +Author : Anish Kachinthaya + +Web scraping made simple with Seleniun +------------------------------------------------------------------ + +Selenium is a module for browser testing and web scraping. +In this code example, the Chromedriver opens google and enters "do a barrel roll" in the search box. + +Modules required: +Selenium +* pip install selenium +Chromedriver (macOS): +* brew install chromedriver +Chromedriver (other): +* download driver from https://sites.google.com/a/chromium.org/chromedriver/downloads and place in PATH diff --git a/recipes/Python/Selenium_For_Web_Scraping/selenium_main.py b/recipes/Python/Selenium_For_Web_Scraping/selenium_main.py new file mode 100644 index 000000000..9b96e7a37 --- /dev/null +++ b/recipes/Python/Selenium_For_Web_Scraping/selenium_main.py @@ -0,0 +1,19 @@ +from selenium import webdriver +from selenium.webdriver.common.by import By +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +from selenium.common.exceptions import TimeoutException +from selenium.webdriver.common.keys import Keys +import time + +driver = webdriver.Chrome() +driver.wait = WebDriverWait(driver, 5) +driver.get("https://www.google.com/") + + +search_box = driver.find_element_by_xpath('//*[@id="lst-ib"]') +search_box.send_keys("do a barrel roll", Keys.ENTER) # Or whatever you want to fill the text box with + +time.sleep(5) + +driver.quit() From 938f80d37b41597902acfe34a8372e11be2af032 Mon Sep 17 00:00:00 2001 From: Devasia Thomas Date: Wed, 11 Oct 2017 14:57:44 -0700 Subject: [PATCH 23/35] Update recipe-408859.py Detection for closed/broken sockets in recv_timeout. --- .../408859_socketrecv__three_ways_turn_it/recipe-408859.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/recipes/Python/408859_socketrecv__three_ways_turn_it/recipe-408859.py b/recipes/Python/408859_socketrecv__three_ways_turn_it/recipe-408859.py index c2258eedb..4555f502f 100644 --- a/recipes/Python/408859_socketrecv__three_ways_turn_it/recipe-408859.py +++ b/recipes/Python/408859_socketrecv__three_ways_turn_it/recipe-408859.py @@ -27,7 +27,11 @@ def recv_timeout(the_socket,timeout=2): total_data.append(data) begin=time.time() else: - time.sleep(0.1) + # Incase there is actually no data to be read from a non blocking socket, + # a socket.error exception is raised with EWOULDBLOCK OR EAGAIN + # If there is data of zero length read, it implies the socket was closed on the other end. + the_socket.close() + break except: pass return ''.join(total_data) From 1123dd27c0c55201ae8c368556c469d68fcb8cac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sefa=20Y=C4=B1ld=C4=B1z?= Date: Sun, 15 Oct 2017 13:41:10 +0300 Subject: [PATCH 24/35] do more human readable --- recipes/Bash/576876_awk_sample/recipe-576876.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/recipes/Bash/576876_awk_sample/recipe-576876.sh b/recipes/Bash/576876_awk_sample/recipe-576876.sh index 209fd2abd..9a44943b3 100644 --- a/recipes/Bash/576876_awk_sample/recipe-576876.sh +++ b/recipes/Bash/576876_awk_sample/recipe-576876.sh @@ -1,6 +1,6 @@ -#!/bin/bash +#!/usr/bin/env bash -file=${1:?"file?"} +FILE=${1:?"FILE?"} echo $* #get the fields @@ -9,10 +9,10 @@ echo $* #print the fields #awk 'BEGIN { FS = "\n"; RS = "" }\ -#{print $2}' $file \ -sed -n '/.*user.*system.*/p' $file \ -|sed -e 's/user//' -e 's/system//' -e 's/elapsed//' |\ -awk 'BEGIN { FS = " "; RS = "\n" }\ +#{print $2}' $FILE \ +$(which sed) -n '/.*user.*system.*/p' ${FILE} \ +|$(which sed) -e 's/user//' -e 's/system//' -e 's/elapsed//' |\ +$(which awk) 'BEGIN { FS = " "; RS = "\n" }\ {split($3, real, ":"); $3=real[1]*60 + real[2]} \ #{printf $1 "\t"$2 "\t" $3"\n"} \ { user_sum += $1; sys_sum += $2; real_sum += $3; count++} \ From 1c8ea280ac1badd78a263a719bf073e2f806bcfd Mon Sep 17 00:00:00 2001 From: kgashok Date: Wed, 15 Nov 2017 07:10:44 +0530 Subject: [PATCH 25/35] Update recipe-576917.py included a lambda version (<2.7?) and added a >3.5x version as well. --- .../recipe-576917.py | 25 +++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/recipes/Python/576917_Functional_selection_sort/recipe-576917.py b/recipes/Python/576917_Functional_selection_sort/recipe-576917.py index f1630f62e..aec808a23 100644 --- a/recipes/Python/576917_Functional_selection_sort/recipe-576917.py +++ b/recipes/Python/576917_Functional_selection_sort/recipe-576917.py @@ -16,8 +16,33 @@ print test_list print selection_sort(test_list) + # Recursive version def select_sort_r(L): if not L: return [] # terminal case v, idx = min((v, i) for i, v in enumerate(L)) # select the smallest return [v] + select_sort_r(L[:idx] + L[idx+1:]) # recursively call on the remainder + + +# Lambda version +# Python > 2.7.10 and above +select_sort_l = ( + lambda L: [] if not L else ( + lambda idx, v: [v] + select_sort_l(L[:idx] + L[idx + 1:]))( + *min(enumerate(L), key=lambda t: t[1]) + ) +) + +# OP's version from the comments, works probably for Python < 2.7.10 +selsort2 = (lambda l: [] if not l else + (lambda (idx, v): [v] + selsort2(l[:idx] + l[idx + 1:])) + (min(enumerate(l), key=lambda(i, x): x))) + + +# OP's original test_list gets mutated by the functional version +test_list = [5, 1, 7, 0, -3, -10, 10, -6, 1, 0, 2, 4, -2, 6, 5, 8, 2] +expected = [-10, -6, -3, -2, 0, 0, 1, 1, 2, 2, 4, 5, 5, 6, 7, 8, 10] + +assert select_sort_r(test_list) == expected +assert select_sort_l(test_list) == expected +# assert selsort2(test_list) == expected From eb3910c872b400a25d803a709457011a3558f1ed Mon Sep 17 00:00:00 2001 From: elFua Date: Sun, 19 Nov 2017 17:09:09 +0100 Subject: [PATCH 26/35] find_replace_regex_colorized.py usage: find-replace-in-files-regex.py [-h] [--dir DIR] --search-regex SEARCH_REGEX --replace-regex REPLACE_REGEX [--glob GLOB] [--dry-run] [--create-backup] [--verbose] [--print-parent-folder] [--list-non-matching] DESCRIPTION: Find and replace recursively from the given folder using regular expressions optional arguments: -h, --help show this help message and exit --dir DIR, -d DIR folder to search in; by default current folder --search-regex SEARCH_REGEX, -s SEARCH_REGEX search regex --replace-regex REPLACE_REGEX, -r REPLACE_REGEX replacement regex --glob GLOB, -g GLOB glob pattern, i.e. *.html --dry-run, -dr don't replace anything just show what is going to be done --create-backup, -b Create backup files --verbose, -v Show files which don't match the search regex --print-parent-folder, -p Show the parent info for debug --list-non-matching, -n Supress colors USAGE: find-replace-in-files-regex.py -d [my_folder] -s -r -g [glob_pattern] --- ...recursive_file_regex_replacer_colorized.py | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 recipes/Python/recursive_file_regex_replacer_colorized.py diff --git a/recipes/Python/recursive_file_regex_replacer_colorized.py b/recipes/Python/recursive_file_regex_replacer_colorized.py new file mode 100644 index 000000000..4f6949311 --- /dev/null +++ b/recipes/Python/recursive_file_regex_replacer_colorized.py @@ -0,0 +1,189 @@ +#!/usr/bin/env python + +""" + + + +Recursively find and replace text in files under a specific folder with preview of changed data in dry-run mode +============ + +Example Usage +--------------- + +**See what is going to change (dry run):** + +> flip all dates from 2017-12-31 to 31-12-2017 + + find_replace.py --dir project/myfolder --search-regex "\d{4}-\d{2}-\d{2}" --replace-regex "\3-\2-\1" --dry-run + +**Do actual replacement:** + + find_replace.py --dir project/myfolder --search-regex "\d{4}-\d{2}-\d{2}" --replace-regex "\3-\2-\1" + +**Do actual replacement and create backup files:** + + find_replace.py --dir project/myfolder --search-regex "\d{4}-\d{2}-\d{2}" --replace-regex "\3-\2-\1" --create-backup + +**Same action as previous command with short-hand syntax:** + + find_replace.py -d project/myfolder -s "\d{4}-\d{2}-\d{2}" -r "\3-\2-\1" -b + +Output of `find_replace.py -h`: + +usage: find-replace-in-files-regex.py [-h] [--dir DIR] --search-regex + SEARCH_REGEX --replace-regex + REPLACE_REGEX [--glob GLOB] [--dry-run] + [--create-backup] [--verbose] + [--print-parent-folder] + +USAGE: + find-replace-in-files-regex.py -d [my_folder] -s -r -g [glob_pattern] +""" + +from __future__ import print_function +import os +import fnmatch +import sys +import shutil +import re + +import argparse + + +class Colors: + Default = "\033[39m" + Black = "\033[30m" + Red = "\033[31m" + Green = "\033[32m" + Yellow = "\033[33m" + Blue = "\033[34m" + Magenta = "\033[35m" + Cyan = "\033[36m" + LightGray = "\033[37m" + DarkGray = "\033[90m" + LightRed = "\033[91m" + LightGreen = "\033[92m" + LightYellow = "\033[93m" + LightBlue = "\033[94m" + LightMagenta = "\033[95m" + LightCyan = "\033[96m" + White = "\033[97m" + NoColor = "\033[0m" + + +def find_replace(cfg): + + search_pattern = re.compile(cfg.search_regex) + + if cfg.dry_run: + print('THIS IS A DRY RUN -- NO FILES WILL BE CHANGED!') + + for path, dirs, files in os.walk(os.path.abspath(cfg.dir)): + for filename in fnmatch.filter(files, cfg.glob): + + if cfg.print_parent_folder: + pardir = os.path.normpath(os.path.join(path, '..')) + pardir = os.path.split(pardir)[-1] + print('[%s]' % pardir) + full_path = os.path.join(path, filename) + + # backup original file + if cfg.create_backup: + backup_path = full_path + '.bak' + + while os.path.exists(backup_path): + backup_path += '.bak' + print('DBG: creating backup', backup_path) + shutil.copyfile(full_path, backup_path) + + if os.path.islink(full_path): + print("{}File {} is a symlink. Skipping{}".format(Colors.Red, full_path, Colors.NoColor)) + continue + + with open(full_path) as f: + old_text = f.read() + + all_matches = search_pattern.findall(old_text) + + if all_matches: + + print('{}Found {} match(es) in file {}{}'.format(Colors.LightMagenta, len(all_matches), filename, Colors.NoColor)) + + new_text = search_pattern.sub(cfg.replace_regex, old_text) + + if not cfg.dry_run: + with open(full_path, "w") as f: + print('DBG: replacing in file', full_path) + f.write(new_text) + # else: + # for idx, matches in enumerate(all_matches): + # print("Match #{}: {}".format(idx, matches)) + + if cfg.verbose or cfg.dry_run: + colorized_old = search_pattern.sub(Colors.LightBlue + r"\g<0>" + Colors.NoColor, old_text) + colorized_old = '\n'.join(['\t' + line.strip() for line in colorized_old.split('\n') if Colors.LightBlue in line]) + + colorized = search_pattern.sub(Colors.Green + cfg.replace_regex + Colors.NoColor, old_text) + colorized = '\n'.join(['\t' + line.strip() for line in colorized.split('\n') if Colors.Green in line]) + print("{}BEFORE:{}\n{}".format(Colors.White, Colors.NoColor, colorized_old)) + print("{}AFTER :{}\n{}".format(Colors.Yellow, Colors.NoColor, colorized)) + + elif cfg.list_non_matching: + print('File {} does not contain search regex "{}"'.format(filename, cfg.search_regex)) + + +if __name__ == '__main__': + + parser = argparse.ArgumentParser(description='''DESCRIPTION: + Find and replace recursively from the given folder using regular expressions''', + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog='''USAGE: + {0} -d [my_folder] -s -r -g [glob_pattern] + + '''.format(os.path.basename(sys.argv[0]))) + + parser.add_argument('--dir', '-d', + help='folder to search in; by default current folder', + default='.') + + parser.add_argument('--search-regex', '-s', + help='search regex', + required=True) + + parser.add_argument('--replace-regex', '-r', + help='replacement regex', + required=True) + + parser.add_argument('--glob', '-g', + help='glob pattern, i.e. *.html', + default="*.*") + + parser.add_argument('--dry-run', '-dr', + action='store_true', + help="don't replace anything just show what is going to be done", + default=False) + + parser.add_argument('--create-backup', '-b', + action='store_true', + help='Create backup files', + default=False) + + parser.add_argument('--verbose', '-v', + action='store_true', + help="Show files which don't match the search regex", + default=False) + + parser.add_argument('--print-parent-folder', '-p', + action='store_true', + help="Show the parent info for debug", + default=False) + + parser.add_argument('--list-non-matching', '-n', + action='store_true', + help="Supress colors", + default=False) + + config = parser.parse_args(sys.argv[1:]) + + find_replace(config) + From d82d03e737eb8e2a978eac4ff6c9c9e19c2efc71 Mon Sep 17 00:00:00 2001 From: Pavel Shishpor Date: Fri, 24 Nov 2017 15:01:17 +0100 Subject: [PATCH 27/35] Explicitly import rlcompleter as it may not be visible when imported in .pdbrc. The issue was observed on Python 2.7.13. --- .../Python/498182_sane_tab_completion_in_pdb/recipe-498182.py | 1 + 1 file changed, 1 insertion(+) diff --git a/recipes/Python/498182_sane_tab_completion_in_pdb/recipe-498182.py b/recipes/Python/498182_sane_tab_completion_in_pdb/recipe-498182.py index 3b42c9d14..a2427d233 100644 --- a/recipes/Python/498182_sane_tab_completion_in_pdb/recipe-498182.py +++ b/recipes/Python/498182_sane_tab_completion_in_pdb/recipe-498182.py @@ -22,6 +22,7 @@ def complete(self, text, state): """ # keep a completer class, and make sure that it uses the current local scope if not hasattr(self, 'completer'): + import rlcompleter self.completer = rlcompleter.Completer(self.curframe.f_locals) else: self.completer.namespace = self.curframe.f_locals From 8e2528c312791c2c56c8bca365669e06ab698a88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Niklas?= Date: Wed, 29 Nov 2017 08:00:27 +0100 Subject: [PATCH 28/35] omitting temporary tables and similar improvements --- .../recipe-576534.py | 365 ++++++++++----- .../recipe-576557.py | 432 ++++++++++++++---- .../recipe-576621.py | 397 +++++++++++----- 3 files changed, 894 insertions(+), 300 deletions(-) diff --git a/recipes/Python/576534_Dump_Oracle_db_schema_to_text/recipe-576534.py b/recipes/Python/576534_Dump_Oracle_db_schema_to_text/recipe-576534.py index e89501fb6..e6683673b 100644 --- a/recipes/Python/576534_Dump_Oracle_db_schema_to_text/recipe-576534.py +++ b/recipes/Python/576534_Dump_Oracle_db_schema_to_text/recipe-576534.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf8 -*- -__version__ = '$Id: schema_ora.py 1754 2014-02-14 08:57:52Z mn $' +__version__ = '$Id: schema_ora.py 3307 2017-11-29 06:18:57Z mn $' # export Oracle schema to text # usable to compare databases that should be the same @@ -8,29 +8,33 @@ # Oracle schema info: # http://www.eveandersson.com/writing/data-model-reverse-engineering # +# http://code.activestate.com/recipes/576534-dump-oracle-db-schema-to-text/ # # author: Michal Niklas, Adam Kopciński-Galik OPTIONS = """[OPTIONS] Options: ---tables_only raport only tables ---separate-files save tables, views etc in separate files - in db_schema directory, - tables are defined as CREATE TABLE statement ---sorted-info for CREATE TABLE add comment with columns - sorted by name ---zip with --separate-files enabled zip all created files +--add-ver-info add version information --date-dir with --separate-files add date and time to db_schema_[date]_[time] directory with -o[=file_name] save file_name in db_schema_[date]_[time] directory --force-dir with --separate-files do not check if db_schema directory exists +--lf-only use Unix style end of lines +--no-temp-tables do not show info about tables with 'tmp' or 'temp' in name -o[=file_name] send results to file instead of stdout +--separate-files save tables, views etc in separate files + in db_schema directory, + tables are defined as CREATE TABLE statement +--sorted-info for CREATE TABLE add comment with columns + sorted by name +--tables-only raport only tables --version show version ---add-ver-info add version information +--verbose show more info in output (SQL queries) --ver-info-sql[=SELECT ... FROM ... ORDER BY ...] extend version information by results of this query +--zip with --separate-files enabled zip all created files """ USAGE = 'usage:\n\tschema_ora.py tnsentry username passwd %s' % OPTIONS @@ -41,22 +45,25 @@ """ % OPTIONS import codecs -import sys import os -import zipfile import os.path -import time import re +import sys +import time +import traceback +import zipfile USE_JYTHON = 0 -TABLES_ONLY = 0 +TABLES_ONLY = '--tables_only' in sys.argv or '--tables-only' in sys.argv +LF_ONLY = '--lf_only' in sys.argv or '--lf-only' in sys.argv + SCHEMA_DIR = 'db_schema' if '--date-dir' in sys.argv: SCHEMA_DIR += time.strftime("_%y%m%d_%H%M%S", time.localtime()) -TABLES_INFO_DIR = SCHEMA_DIR + '/tables' -VIEWS_INFO_DIR = SCHEMA_DIR + '/views' +TABLES_INFO_DIR = SCHEMA_DIR + '/tables' +VIEWS_INFO_DIR = SCHEMA_DIR + '/views' SEQUENCES_INFO_DIR = SCHEMA_DIR + '/sequences' FUNCTIONS_INFO_DIR = SCHEMA_DIR + '/functions' PROCEDURES_INFO_DIR = SCHEMA_DIR + '/procedures' @@ -65,6 +72,7 @@ CREATED_FILES = [] +VERBOSE = '--verbose' in sys.argv try: from com.ziclix.python.sql import zxJDBC @@ -78,30 +86,40 @@ OUT_FILE_ENCODING = 'UTF8' - -TABLE_AND_VIEWS_NAMES_SQL = """SELECT DISTINCT table_name -FROM user_tab_columns -WHERE INSTR(table_name, 'X_') <> 1 +FILTER_TEMP = """ +INSTR(table_name, 'X_') <> 1 AND INSTR(table_name, '$') = 0 -ORDER BY table_name """ +FILTER_TEMP_SEQ = "" + +if '--no-temp-tables' in sys.argv: + # Oracle uses UPPER letters in table names + FILTER_TEMP += """AND INSTR(table_name, 'TMP') = 0 +AND INSTR(table_name, 'TEMP') = 0 +""" + FILTER_TEMP_SEQ = " WHERE INSTR(sequence_name, 'TMP') = 0 AND INSTR(sequence_name, 'TEMP') = 0" + +UC_FILTER_TEMP = FILTER_TEMP.replace('table_name', 'uc.table_name') + TABLE_NAMES_SQL = """SELECT DISTINCT table_name FROM user_tables -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s AND NOT table_name IN (SELECT view_name FROM user_views) AND NOT table_name IN (SELECT mview_name FROM user_mviews) ORDER BY table_name -""" +""" % (FILTER_TEMP) TABLE_COLUMNS_SQL = """SELECT table_name, column_name FROM user_tab_columns -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s +AND NOT table_name IN (SELECT view_name FROM user_views) +AND NOT table_name IN (SELECT mview_name FROM user_mviews) ORDER BY table_name, column_name -""" +""" % (FILTER_TEMP) TABLE_INFO_SQL = """SELECT table_name, column_name, data_type, nullable, @@ -109,53 +127,78 @@ decode(data_type, 'DATE', '11', 'NUMBER', data_precision || ',' || data_scale, + 'VARCHAR2', char_length || char_used, data_length) data_length FROM user_tab_columns -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s +AND NOT table_name IN (SELECT view_name FROM user_views) +AND NOT table_name IN (SELECT mview_name FROM user_mviews) ORDER BY table_name, column_name -""" +""" % (FILTER_TEMP) + + +SQL_TYPES = """SELECT COUNT(*), data_type, +decode(data_type, + 'NUMBER', data_precision || ',' || data_scale, + 'VARCHAR2', char_used, + 'CHAR', char_used, + data_length) +FROM user_tab_columns +WHERE +%s +AND NOT table_name IN (SELECT view_name FROM user_views) +AND NOT table_name IN (SELECT mview_name FROM user_mviews) +GROUP BY data_type, +decode(data_type, + 'NUMBER', data_precision || ',' || data_scale, + 'VARCHAR2', char_used, + 'CHAR', char_used, + data_length) +ORDER BY 1 DESC, 2, 3 +""" % (FILTER_TEMP) + PRIMARY_KEYS_INFO_SQL = """SELECT uc.table_name, ucc.column_name FROM user_constraints uc, user_cons_columns ucc -WHERE uc.constraint_name = ucc.constraint_name +WHERE +%s +AND uc.constraint_name = ucc.constraint_name AND uc.constraint_type = 'P' -AND INSTR(uc.table_name, 'X_') <> 1 -AND INSTR(uc.table_name, '$') = 0 ORDER BY uc.table_name, ucc.position -""" +""" % (UC_FILTER_TEMP) INDEXES_INFO_SQL = """SELECT ui.table_name, ui.index_name, ui.uniqueness FROM user_indexes ui -WHERE INSTR(ui.table_name, 'X_') <> 1 -AND INSTR(ui.table_name, '$') = 0 +WHERE +%s ORDER BY ui.table_name, ui.index_name -""" +""" % (FILTER_TEMP) INDEXES_COLUMNS_INFO_SQL = """SELECT table_name, column_name, index_name, column_position, descend FROM user_ind_columns -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s ORDER BY table_name, index_name, column_position -""" +""" % (FILTER_TEMP) COMPOSITE_INDEXES_COLUMNS_INFO_SQL = """SELECT table_name, column_name, index_name, column_position FROM user_ind_columns -WHERE index_name in (select distinct index_name from USER_IND_COLUMNS where column_position > 1) -AND INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s +AND index_name in (select distinct index_name from USER_IND_COLUMNS where column_position > 1) ORDER BY table_name, index_name, column_position -""" +""" % (FILTER_TEMP) FUNCTION_INDEXES_INFO_SQL = """SELECT table_name, column_expression, index_name, column_position FROM user_ind_expressions -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s ORDER BY table_name, index_name, column_position -""" +""" % (FILTER_TEMP) FOREIGN_KEYS_INFO_SQL = """SELECT uc.table_name, ucc.column_name, ucc.position @@ -166,29 +209,36 @@ ,user_constraints fc ,user_constraints uc ,user_ind_columns uic -WHERE uc.constraint_type = 'R' -AND uc.constraint_name = ucc.constraint_name -AND fc.constraint_name = uc.r_constraint_name +WHERE +%s +AND uc.constraint_type = 'R' +AND uc.constraint_name = ucc.constraint_name +AND fc.constraint_name = uc.r_constraint_name AND uic.index_name=fc.constraint_name ORDER BY uc.table_name, ucc.position, uic.column_position -""" +""" % (UC_FILTER_TEMP) DEFAULTS_INFO_SQL = """SELECT table_name, column_name, data_default -FROM user_tab_columns -WHERE default_length IS NOT NULL -AND INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +FROM user_tab_columns +WHERE +%s +AND default_length IS NOT NULL ORDER BY table_name, column_name -""" +""" % (FILTER_TEMP) -SEQUENCES_INFO_SQL = """SELECT sequence_name FROM user_sequences""" +SEQUENCES_INFO_SQL = """SELECT sequence_name +FROM user_sequences %s +ORDER BY sequence_name +""" % FILTER_TEMP_SEQ TSEQUENCES_INFO_SQL = """SELECT sequence_name, min_value, max_value, increment_by, last_number, cache_size, cycle_flag, order_flag FROM user_sequences -""" +%s +ORDER BY sequence_name +""" % FILTER_TEMP_SEQ VIEWS_INFO_SQL = """SELECT view_name, text @@ -204,20 +254,27 @@ TRIGGERS_INFO_SQL = """SELECT trigger_name, trigger_type, triggering_event, table_name, trim(chr(13) from trim(chr(10) from description)), trigger_body FROM user_triggers -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') = 0 +WHERE +%s ORDER BY table_name, trigger_name +""" % (FILTER_TEMP) + + +PROCEDURE_AND_FUNCTION_NAME_SQL = """SELECT object_name +FROM user_procedures +WHERE procedure_name IS NULL AND LOWER(object_type)=LOWER('%s') +ORDER BY object_name """ TTABLE_NAMES_SQL = """SELECT DISTINCT table_name FROM user_tab_columns -WHERE INSTR(table_name, 'X_') <> 1 -AND INSTR(table_name, '$') < 1 +WHERE +%s AND NOT table_name IN (SELECT view_name FROM user_views) AND NOT table_name IN (SELECT mview_name FROM user_mviews) ORDER BY table_name -""" +""" % (FILTER_TEMP) TTABLE_COLUMNS = """SELECT column_name, data_type, nullable, @@ -227,7 +284,8 @@ 'NUMBER', data_precision || ',' || data_scale, data_length) data_length, data_default, - char_length + char_length, + char_used FROM user_tab_columns WHERE table_name='%s' """ @@ -240,6 +298,7 @@ WHERE uc.constraint_name = ucc.constraint_name AND uc.constraint_type = 'P' AND uc.table_name='%s' +ORDER BY ucc.position """ @@ -277,8 +336,19 @@ """ +TTYPES_SQL = """SELECT type_name, line, text FROM user_types +LEFT JOIN user_source ON user_source.name=user_types.type_name WHERE user_source.type='TYPE' +ORDER BY type_name, line""" + + DB_VERSION_SQL = """SELECT * FROM v$version WHERE banner like 'Oracle%'""" +FEATURE_USAGE_SQL = """SELECT NAME, VERSION, detected_usages, +first_usage_date, last_usage_date +FROM dba_feature_usage_statistics +WHERE detected_usages > 0 +ORDER BY 1, 2""" + _CONN = None @@ -323,8 +393,8 @@ def init_db_conn(connect_string, username, passwd): print('--%s' % (dbinfo)) _CONN = cx_Oracle.connect(username, passwd, connect_string) except: - ex = sys.exc_info() - serr = 'Exception: %s: %s\n%s' % (ex[0], ex[1], dbinfo) + serr = traceback.format_exc() + serr = 'Exception while opening: %s\n%s' % (dbinfo, serr) print_err(serr) return None return _CONN @@ -339,6 +409,8 @@ def output_str(fout, line): """outputs line to fout trying various encodings in case of encoding errors""" if fout: try: + if LF_ONLY: + line = line.replace(chr(13), '') fout.write(line) except (UnicodeDecodeError, UnicodeEncodeError): try: @@ -357,13 +429,17 @@ def output_str(fout, line): if not ok: fout.write('!!! line cannot be encoded !!!\n') fout.write(repr(line)) - fout.write('\n') + if LF_ONLY: + # just LF, while we want to compare results on both Linux and Windows + # CRLF = 0d0a + fout.write(chr(10)) + else: + fout.write('\n') fout.flush() def output_line(line, fout=None): """outputs line""" - line = line.rstrip() output_str(fout, line) output_str(sys.stdout, line) @@ -371,15 +447,24 @@ def output_line(line, fout=None): def print_err(serr): """println on stderr""" sys.stderr.write('%s\n' % (serr)) + output_line('\nERROR! ERROR!\n%s\n' % (serr)) def select_qry(querystr): """executes SQL SELECT query""" - cur = db_conn().cursor() - cur.execute(querystr) - results = cur.fetchall() - cur.close() - return results + try: + qstr = querystr.encode('UTF8') + cur = db_conn().cursor() + if VERBOSE: + output_line('\n--\n%s\n--' % (qstr)) + cur.execute(qstr) + results = cur.fetchall() + cur.close() + return results + except: + serr = traceback.format_exc() + print_err('cos nie tak z zapytaniem:\n%s\n%s' % (qstr, serr)) + raise def run_qry(querystr): @@ -403,16 +488,29 @@ def fld2str(fld_v): return fld_v +def print_start_info(title, fout=None): + output_line('\n\n', fout) + output_line('--- %s (START) ---' % title, fout) + + +def print_stop_info(title, fout=None): + output_line('--- %s (END) ---' % title, fout) + output_line('\n\n', fout) + + def show_qry(title, querystr, fld_join='\t', row_separator=None, fout=None): """shows SQL query results""" + print_start_info(title, fout) rs = select_qry(querystr) if rs: - output_line('\n\n--- %s ---' % (title), fout) for row in rs: line = fld_join.join([fld2str(s) for s in row]) output_line(line, fout) if row_separator: output_line(row_separator, fout) + else: + output_line(' -- NO DATA --', fout) + print_stop_info(title, fout) def init_session(): @@ -420,7 +518,7 @@ def init_session(): run_qry("ALTER SESSION SET nls_numeric_characters = '.,'") -def get_type_length(data_type, data_length, char_length): +def get_type_length(data_type, data_length, char_length, char_used): """get string with length of field""" if data_type == 'NUMBER': if data_length == ',': @@ -431,7 +529,10 @@ def get_type_length(data_type, data_length, char_length): if data_type == 'RAW': return ' (%s)' % (data_length) if data_type in ('CHAR', 'VARCHAR2', 'NCHAR', 'NVARCHAR2'): - return ' (%.0f)' % (char_length) + char_used_str = 'BYTE' + if char_used.lower().startswith('c'): + char_used_str = 'CHAR' + return ' (%.0f %s)' % (char_length, char_used_str) return '' @@ -444,8 +545,9 @@ def table_info_row(row): data_length = row[4] data_default = row[5] char_length = row[6] + char_used = row[7] default_str = nullable_str = '' - data_length_str = get_type_length(data_type, data_length, char_length) + data_length_str = get_type_length(data_type, data_length, char_length, char_used) if int(hasdef) == 1: default_str = ' DEFAULT %s' % (data_default) if nullable == 'N': @@ -595,8 +697,12 @@ def create_create_table_ddl(table, sorted_in_comment): sc = '\n---------- order by column name ----------\n-- ' + sc + '\n---------- order by column name ----------' ct = ct + sc indices_str = get_table_indices(table, pk_columns) + if indices_str: + ct += '\n\n' + indices_str triggers_str = get_table_triggers(table) - return '%s\n\n%s\n\n%s' % (ct, indices_str, triggers_str) + if triggers_str: + ct += '\n\n' + triggers_str + return ct def save_table_definition(table, sorted_in_comment): @@ -611,7 +717,7 @@ def save_table_definition(table, sorted_in_comment): def show_tables(): """shows info tables""" - show_qry('tables', TABLE_AND_VIEWS_NAMES_SQL) + show_qry('tables', TABLE_NAMES_SQL) show_qry('table columns', TABLE_COLUMNS_SQL) show_qry('columns', TABLE_INFO_SQL) @@ -709,6 +815,16 @@ def show_views(separate_files): cur.close() +def show_types_stat(): + show_qry('column type count', SQL_TYPES) + + +def show_procedures_and_functions(): + """shows SQL triggers""" + show_qry('function names', PROCEDURE_AND_FUNCTION_NAME_SQL % ('function')) + show_qry('procedure names', PROCEDURE_AND_FUNCTION_NAME_SQL % ('procedure')) + + def show_normal_procedures(separate_files, title, out_dir=None): """shows valid SQL procedures and functions""" return show_procedures("SELECT object_name FROM user_procedures WHERE procedure_name IS NULL AND lower(object_type) = lower('%s') ORDER BY 1", separate_files, title, out_dir) @@ -721,7 +837,7 @@ def show_invalid_procedures(separate_files, title, out_dir=None): def show_procedures(sql, separate_files, title, out_dir=None): """shows SQL procedures and functions""" - output_line('\n\n --- %ss ---' % (title)) + print_start_info(title + 's') fout = None cur = db_conn().cursor() cur.execute(sql % (title)) @@ -738,19 +854,21 @@ def show_procedures(sql, separate_files, title, out_dir=None): cur2.execute("SELECT text FROM user_source where name = '%s' ORDER BY line" % funname) lines = cur2.fetchall() for line in lines: - output_line(line[0], fout) + output_line(line[0].rstrip(), fout) if lines: - output_line('\n/\n', fout) + output_line('\n/', fout) cur2.close() output_line('\n\n -- <<< %s %s <<< --' % (title, funname)) if fout: fout.close() cur.close() + print_stop_info(title + 's') def show_packages(separate_files): """shows SQL packages""" - output_line('\n\n --- packages ---') + title = 'packages' + print_start_info(title) fout = None cur1 = db_conn().cursor() cur1.execute("SELECT object_name FROM user_objects WHERE object_type='PACKAGE' ORDER BY 1") @@ -766,9 +884,9 @@ def show_packages(separate_files): cur2.execute("SELECT text FROM sys.user_source where name = '%s' AND type='PACKAGE' ORDER BY line" % funname) lines = cur2.fetchall() for line in lines: - output_line(line[0], fout) + output_line(line[0].rstrip(), fout) if(lines): - output_line('\n/\n', fout) + output_line('\n/', fout) output_line('\n') cur2.close() cur3 = db_conn().cursor() @@ -777,14 +895,15 @@ def show_packages(separate_files): if(lines): output_line('\nCREATE OR REPLACE ', fout) for line in lines: - output_line(line[0], fout) + output_line(line[0].rstrip(), fout) if(lines): - output_line('\n/\n', fout) + output_line('\n/', fout) cur3.close() if fout: fout.close() output_line('\n\n -- <<< package %s <<< --' % (funname)) cur1.close() + print_stop_info(title) def show_triggers(): @@ -792,6 +911,11 @@ def show_triggers(): show_qry('triggers', TRIGGERS_INFO_SQL, '\n', '\n-- end trigger --\n') +def show_types(): + """shows SQL types""" + show_qry('types', TTYPES_SQL) + + def save_files_in_zip(): """saves created files in zip file""" if not CREATED_FILES: @@ -815,12 +939,14 @@ def add_ver_info(separate_files, connect_string, username): if separate_files: ver_file = os.path.join(SCHEMA_DIR, 'version.txt') f = open_file_write(ver_file) - output_line('>>> ver info') + title = 'info' + print_start_info(title) output_line('date: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())), f) output_line('connect string: %s' % (connect_string), f) output_line('user: %s' % (username), f) script_ver = __version__[5:-2] output_line('created by: %s' % (script_ver), f) + print_stop_info(title) show_qry('DB version', DB_VERSION_SQL, fout=f) show_qry('DB name', 'SELECT ora_database_name FROM dual', fout=f) sel_info_option = '--ver-info-sql' @@ -830,11 +956,11 @@ def add_ver_info(separate_files, connect_string, username): try: show_qry(sel, sel, fout=f) except: - ex = sys.exc_info() - serr = '\nSQL: %s\nException: %s: %s\n' % (sel, ex[0], ex[1]) + ex_info = traceback.format_exc() + serr = '\nSQL: %s\nException: %s\n' % (sel, ex_info) print_err(serr) break - output_line('<<< ver info') + show_qry('DB features used', FEATURE_USAGE_SQL, fout=f) if f: f.close() @@ -848,22 +974,33 @@ def show_additional_info(separate_files): show_sequences(separate_files) show_views(separate_files) show_triggers() + show_procedures_and_functions() show_normal_procedures(separate_files, 'function', FUNCTIONS_INFO_DIR) - show_invalid_procedures(separate_files, 'function', FUNCTIONS_INFO_DIR + INVALID) + show_invalid_procedures(separate_files, 'invalid function', FUNCTIONS_INFO_DIR + INVALID) show_normal_procedures(separate_files, 'procedure', PROCEDURES_INFO_DIR) - show_invalid_procedures(separate_files, 'procedure', PROCEDURES_INFO_DIR + INVALID) + show_invalid_procedures(separate_files, 'invalid procedure', PROCEDURES_INFO_DIR + INVALID) show_packages(separate_files) + show_types() + show_types_stat() + + +def rmdir_ex(dirname): + try: + os.rmdir(dirname) + except: + pass def clean_up(): """removes created directories after zipping files""" for dn in CREATED_DIRS: - os.rmdir(dn) - os.rmdir(SCHEMA_DIR) + rmdir_ex(dn) + rmdir_ex(SCHEMA_DIR) def dump_db_info(separate_files, out_f, stdout): """saves information about database schema in file/files""" + t0 = time.time() test = '--test' in sys.argv if test or separate_files: for dn in (TABLES_INFO_DIR, VIEWS_INFO_DIR, SEQUENCES_INFO_DIR, FUNCTIONS_INFO_DIR, PROCEDURES_INFO_DIR, PACKAGES_INFO_DIR): @@ -880,7 +1017,10 @@ def dump_db_info(separate_files, out_f, stdout): show_tables() if not TABLES_ONLY and not test: show_additional_info(separate_files) - output_line('\n\n--- the end ---') + t2 = time.time() + td = t2 - t0 + output_line('\n\nexecution time: %d min %d sec' % (divmod(td, 60))) + output_line('\n\n-- the end --') if out_f: out_f.close() sys.stdout = stdout @@ -899,25 +1039,37 @@ def get_option_value(prefix): return result +def mk_schema_dir(): + try: + if not os.path.exists(SCHEMA_DIR): + os.mkdir(SCHEMA_DIR) + except: + pass + + def main(): """main function""" - conn_args = [s for s in sys.argv[1:] if not s.startswith('-')] - if len(conn_args) != 3: + if '--version' in sys.argv: + print(__version__) + return + db_conn_args = [s for s in sys.argv[1:] if not s.startswith('-')] + if len(db_conn_args) != 3 or '--help' in sys.argv: print(USAGE) - return 0 - connect_string, username, passwd = conn_args + return + connect_string, username, passwd = db_conn_args separate_files = '--separate-files' in sys.argv if separate_files: if os.path.exists(SCHEMA_DIR): - if not '--force-dir' in sys.argv: + if '--force-dir' not in sys.argv: print_err('Output directory "%s" already exists,\nuse --force-dir or --date-dir option!' % (SCHEMA_DIR)) return 0 + mk_schema_dir() stdout = sys.stdout out_f = None out_fn = get_option_value('-o') if out_fn: if '--date-dir' in sys.argv: - os.mkdir(SCHEMA_DIR) + mk_schema_dir() out_fn = os.path.join(SCHEMA_DIR, out_fn) out_f = open(out_fn, 'w') sys.stdout = out_f @@ -932,12 +1084,5 @@ def main(): dump_db_info(separate_files, out_f, stdout) -if '--version' in sys.argv: - print(__version__) -elif __name__ == '__main__': - if '--tables_only' in sys.argv: - TABLES_ONLY = 1 - if len(sys.argv) < 4: - print(USAGE) - else: - main() +if __name__ == '__main__': + main() diff --git a/recipes/Python/576557_Dump_PostgreSQL_db/recipe-576557.py b/recipes/Python/576557_Dump_PostgreSQL_db/recipe-576557.py index 2b7644a76..9c0c0e041 100644 --- a/recipes/Python/576557_Dump_PostgreSQL_db/recipe-576557.py +++ b/recipes/Python/576557_Dump_PostgreSQL_db/recipe-576557.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf8 -*- -__version__ = '$Id: schema_pg.py 1754 2014-02-14 08:57:52Z mn $' +__version__ = '$Id: schema_pg.py 3307 2017-11-29 06:18:57Z mn $' # export PostgreSQL schema to text # usable to compare databases that should be the same @@ -8,24 +8,37 @@ # PostgreSQL schema info: # http://www.alberton.info/postgresql_meta_info.html # +# https://code.activestate.com/recipes/576557-dump-postgresql-db-schema-to-text/ # # author: Michal Niklas -USAGE = 'usage:\n\tschema_pg.py connect_string\n\t\tconnect string:\n\t\t\thost:[port:]database:user:password\n\t\tor for ODBC:\n\t\t\tdatabase/user/passwd\n\t\tor (pyodbc)\n\t\t\tDriver={PostgreSQL};Server=IP address;Port=5432;Database=myDataBase;Uid=myUsername;Pwd=myPassword;' +USAGE = """usage: + schema_pg.py connect_string + connect string: + host:[port:]database:user:password + or for ODBC: + database/user/passwd + or (pyodbc) + Driver={PostgreSQL};Server=IP address;Port=5432;Database=myDataBase;Uid=myUsername;Pwd=myPassword; +""" -import sys import array import exceptions +import sys +import time +import traceback USE_JYTHON = 0 -TABLES_ONLY = 0 +TABLES_ONLY = '--tables_only' in sys.argv + +OUTPUT_FILE = sys.stdout try: from com.ziclix.python.sql import zxJDBC USE_JYTHON = 1 USAGE = """usage: -\tschema_inf.py jdbcurl user passwd +\tschema_py.py jdbcurl user passwd example: \tjython schema_py.py jdbc:postgresql://isof-test64:5434/gryfcard_mrb?stringtype=unspecified user passwd > db.schema 2> db.err """ @@ -38,10 +51,14 @@ OUT_FILE_ENCODING = 'UTF8' +DB_VERSION_SQL = """SELECT version()""" + TABLE_NAMES_SQL = """SELECT DISTINCT table_name FROM information_schema.columns WHERE table_schema='public' AND position('_' in table_name) <> 1 +AND position('pg_' in table_name) <> 1 +AND NOT table_name IN (SELECT viewname FROM pg_views) ORDER BY 1""" @@ -49,25 +66,69 @@ FROM information_schema.columns WHERE table_schema='public' AND position('_' in table_name) <> 1 +AND position('pg_' in table_name) <> 1 +AND position('_' in column_name) <> 1 +AND NOT table_name IN (SELECT viewname FROM pg_views) ORDER BY 1, 2""" +TABLE_COLUMN_NAME_BY_IDX = """SELECT column_name +FROM information_schema.columns +WHERE table_name = '%s' +AND ordinal_position = %s""" + -TABLE_INFO_SQL = """SELECT table_name, column_name, ordinal_position, data_type, is_nullable, character_maximum_length, numeric_precision +TABLE_INFO_SQL = """SELECT table_name, column_name, +case + when data_type='numeric' and numeric_precision is not null then data_type || '(' || numeric_precision || ',' || numeric_scale || ')' + when character_maximum_length is not null then data_type || '(' || character_maximum_length || ')' + else data_type end as data_type, +is_nullable FROM information_schema.columns WHERE table_schema='public' AND position('_' in table_name) <> 1 +AND position('pg_' in table_name) <> 1 +AND NOT table_name IN (SELECT viewname FROM pg_views) +AND position('_' in column_name) <> 1 ORDER BY 1, 2 """ -PRIMARY_KEYS_INFO_SQL = """SELECT t.relname AS table_name, array_to_string(c.conkey, ' ') AS constraint_key +SQL_TYPES = """SELECT COUNT(*), case when data_type='numeric' and numeric_precision is not null then data_type || '(' || numeric_precision || ',' || numeric_scale || ')' else data_type end +FROM information_schema.columns +WHERE table_schema='public' +AND position('_' in table_name) <> 1 +AND position('pg_' in table_name) <> 1 +AND NOT table_name IN (SELECT viewname FROM pg_views) +AND position('_' in column_name) <> 1 +GROUP BY 2 +ORDER BY 1 DESC, 2 +""" + + +xxPRIMARY_KEYS_INFO_SQL = """SELECT t.relname AS table_name, array_to_string(c.conkey, ' ') AS constraint_key FROM pg_constraint c LEFT JOIN pg_class t ON c.conrelid = t.oid WHERE c.contype = 'p' -AND position('_' in t.relname ) <> 1 +AND position('_' in t.relname) <> 1 +AND position('pg_' in t.relname) <> 1 ORDER BY table_name; """ +PRIMARY_KEYS_INFO_SQL = """select tc.table_name, kc.column_name +from + information_schema.table_constraints tc, + information_schema.key_column_usage kc +where + tc.constraint_type = 'PRIMARY KEY' + and tc.table_schema = 'public' + and position('_' in tc.table_name) <> 1 + and position('pg_' in tc.table_name) <> 1 + and kc.table_name = tc.table_name and kc.table_schema = tc.table_schema + and kc.constraint_name = tc.constraint_name +order by 1, 2; +""" + + INDEXES_INFO_SQL = """SELECT relname, indisunique FROM pg_class, pg_index WHERE pg_class.oid = pg_index.indexrelid @@ -107,14 +168,41 @@ AND a.attnum = %s """ - -FOREIGN_KEYS_INFO_SQL = """SELECT t.relname AS table_name, t2.relname AS references_table -FROM pg_constraint c -LEFT JOIN pg_class t ON c.conrelid = t.oid -LEFT JOIN pg_class t2 ON c.confrelid = t2.oid -WHERE c.contype = 'f' -AND position('_' in t.relname ) <> 1 -ORDER BY table_name, references_table +# http://stackoverflow.com/questions/1567051/introspect-postgresql-8-3-to-find-foreign-keys +FOREIGN_KEYS_INFO_SQL = """SELECT "table", array_agg(columns)::varchar, "foreign table", array_agg("foreign columns")::varchar, conname, 'ALTER TABLE ONLY ' || "table" || ' ADD CONSTRAINT ' || conname || ' FOREIGN KEY (' || trim(both '{}' from array_agg(columns)::varchar) || ') REFERENCES ' || "foreign table" || '(' || trim(both '{}' from array_agg("foreign columns")::varchar) || ');' +FROM (SELECT conrelid::regclass AS "table", + a.attname as columns, + confrelid::regclass as "foreign table", + af.attname as "foreign columns", + conname + FROM pg_attribute AS af, + pg_attribute AS a, + (SELECT conrelid, + confrelid, + conkey[i] AS conkey, + confkey[i] as confkey, + conname + FROM (SELECT conrelid, + confrelid, + conkey, + confkey, + generate_series(1, array_upper(conkey, 1)) AS i, + conname + FROM pg_constraint + WHERE contype = 'f' + ) AS ss + ) AS ss2 + WHERE af.attnum = confkey + AND af.attrelid = confrelid + AND a.attnum = conkey + AND a.attrelid = conrelid + AND position('_' in conrelid::regclass::varchar) <> 1 + AND position('pg_' in conrelid::regclass::varchar) <> 1 +) AS ss3 +GROUP BY "table", + "foreign table", + conname +ORDER BY 1, 2, 3, 4; """ @@ -122,12 +210,26 @@ FROM information_schema.columns WHERE column_default IS NOT NULL AND position('_' in table_name) <> 1 +AND position('pg_' in table_name) <> 1 +AND position('_' in column_name) <> 1 ORDER BY table_name, column_name""" -VIEWS_INFO_SQL = """SELECT viewname, definition +VIEW_NAMES_SQL = """SELECT DISTINCT table_name +FROM information_schema.columns +WHERE table_schema='public' +AND position('_' in table_name) <> 1 +AND position('pg_' in table_name) <> 1 +AND table_name IN (SELECT viewname FROM pg_views) +ORDER BY 1 +""" + + +VIEWS_INFO_SQL = """SELECT 'CREATE OR REPLACE VIEW ', viewname, ' AS ', definition FROM pg_views WHERE schemaname NOT IN ('pg_catalog', 'information_schema') +AND position('_' in viewname) <> 1 +AND position('pg_' in viewname) <> 1 ORDER BY viewname """ @@ -135,32 +237,76 @@ TRIGGERS_INFO_SQL = """SELECT event_object_table, trigger_name, action_orientation, action_timing, event_manipulation, action_statement FROM information_schema.triggers WHERE trigger_schema NOT IN ('pg_catalog', 'information_schema') +AND position('_' in event_object_table) <> 1 +AND position('pg_' in event_object_table) <> 1 ORDER BY 1, 2, 3, 4, 5""" +xxPROCEDURE_NAMES = """SELECT DISTINCT routine_name +FROM information_schema.routines +WHERE specific_schema NOT IN ('pg_catalog', 'information_schema') +AND position('_' in routine_name) <> 1 +AND position('pg_' in routine_name) <> 1 +AND position('dblink_' in routine_name) <> 1 +AND position('dex_' in routine_name) <> 1 +AND position('prsd_' in routine_name) <> 1 +AND position('rewrite' in routine_name) <> 1 +AND position('_tsquery' in routine_name) < 1 +AND routine_name NOT IN ('array_search', 'bytea_export', 'bytea_to_largeobject', +'headline', 'lexize', 'parse', 'rank', 'rank_cd', +'rewrite', 'rewrite_accum', 'rewrite_finish', +'set_curcfg', 'set_curdict', 'set_curprs', ) +ORDER BY 1""" + + +xxPROCEDURE_NAMES = """SELECT DISTINCT routine_name, external_language +FROM information_schema.routines +WHERE specific_schema NOT IN ('pg_catalog', 'information_schema') +AND position('_' in routine_name) <> 1 +AND position('pg_' in routine_name) <> 1 +AND position('ts_debug' in routine_name) <> 1 +AND external_language IN ('SQL', 'PLPGSQL', 'PLPYTHONU') +ORDER BY routine_name, external_language""" + + +PROCEDURE_NAMES = """SELECT proname, proname || '(' || pg_get_function_arguments(p.oid) || ')', lanname +FROM pg_catalog.pg_proc p +LEFT JOIN pg_catalog.pg_language l ON l.oid = prolang +JOIN pg_catalog.pg_namespace n + ON n.oid = p.pronamespace + WHERE n.nspname = 'public' +AND position('_' in p.proname) <> 1 +AND position('pg_' in p.proname) <> 1 +AND position('ts_debug' in p.proname) <> 1 +ORDER BY 1, 2, 3 +""" + _CONN = None TABLES = [] -def init_db_conn(connect_string, username, passwd): +def init_db_conn(connect_string, username, passwd, show_connection_info, show_version_info=True): """initializes db connections, can work with PyGres or psycopg2""" global _CONN try: dbinfo = connect_string - print(dbinfo) + if show_connection_info: + print(dbinfo) if USE_JYTHON: _CONN = zxJDBC.connect(connect_string, username, passwd, 'org.postgresql.Driver') elif '/' in connect_string: import odbc _CONN = odbc.odbc(connect_string) - print(_CONN) + if show_connection_info: + print(_CONN) elif connect_string.startswith('Driver='): import pyodbc # Driver={PostgreSQL};Server=IP address;Port=5432;Database=myDataBase;Uid=myUsername;Pwd=myPassword; # Driver={PostgreSQL};Server=isof-test64;Port=5435;Database=isof_stable;Uid=postgres;Pwd=postgres; _CONN = pyodbc.connect(connect_string) - print(_CONN) + if show_connection_info: + print(_CONN) else: # 'host:[port]:database:user:password' arr = connect_string.split(':') @@ -184,7 +330,8 @@ def init_db_conn(connect_string, username, passwd): else: sport = '' dsn = "host=%s %s dbname=%s user=%s password=%s" % (host, sport, dbname, user, passwd) - print(dsn) + if show_connection_info: + print(dsn) dbinfo = 'db: %s:%s' % (host, dbname) use_pgdb = 0 try: @@ -196,13 +343,18 @@ def init_db_conn(connect_string, username, passwd): except: raise exceptions.ImportError('No PostgreSQL library, install psycopg2 or PyGres!') if not _CONN: - print(dbinfo) + if show_connection_info: + print(dbinfo) if use_pgdb: _CONN = pgdb.connect(database=dbname, host=host, user=user, password=passwd) - print(_CONN) + if show_connection_info: + print(_CONN) else: _CONN = psycopg2.connect(dsn) - print(_CONN) + if show_connection_info: + print(_CONN) + if show_version_info: + add_ver_info(connect_string, username) except: ex = sys.exc_info() s = 'Exception: %s: %s\n%s' % (ex[0], ex[1], dbinfo) @@ -213,9 +365,18 @@ def init_db_conn(connect_string, username, passwd): def db_conn(): """access to global db connection""" + global _CONN return _CONN +def db_close(): + """closes global db connection""" + global _CONN + if _CONN: + _CONN.close() + _CONN = None + + def output_str(fout, line): """outputs line to fout trying various encodings in case of encoding errors""" if fout: @@ -228,11 +389,12 @@ def output_str(fout, line): ok = 0 for enc in DB_ENCODINGS: try: - line2 = line.decode(enc) - #fout.write(line2.encode(OUT_FILE_ENCODING)) - fout.write(line2) - ok = 1 - break + if not ok: + line2 = line.decode(enc) + #fout.write(line2.encode(OUT_FILE_ENCODING)) + fout.write(line2) + ok = 1 + break except (UnicodeDecodeError, UnicodeEncodeError): pass if not ok: @@ -246,7 +408,13 @@ def output_line(line, fout=None): """outputs line""" line = line.rstrip() output_str(fout, line) - output_str(sys.stdout, line) + output_str(OUTPUT_FILE, line) + + +def print_err(serr): + """println on stderr""" + sys.stderr.write('%s\n' % (serr)) + output_line('\nERROR! ERROR!\n%s\n' % (serr)) def select_qry(querystr): @@ -271,10 +439,19 @@ def fld2str(fld_v): return fld_v +def print_start_info(title): + output_line('\n\n') + output_line('--- %s (START) ---' % title) + + +def print_stop_info(title): + output_line('--- %s (END) ---' % title) + output_line('\n\n') + + def show_qry(title, querystr, fld_join='\t', row_separator=None): """prints rows from SELECT""" - output_line('\n\n') - output_line('--- %s ---' % title) + print_start_info(title) rs = select_qry(querystr) if rs: for row in rs: @@ -283,6 +460,7 @@ def show_qry(title, querystr, fld_join='\t', row_separator=None): output_line(row_separator) else: output_line(' -- NO DATA --') + print_stop_info(title) def show_qry_tables(title, querystr, fld_join='\t', row_separator=None): @@ -313,7 +491,33 @@ def show_qry_ex(querystr, table, fld_join='\t', row_separator=None): def init_session(): """place to change db session settings like locale""" - pass + global TABLES + TABLES = [] + + +def add_ver_info(connect_string, username): + """add version information""" + title = 'info' + print_start_info(title) + output_line('date: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) + output_line('connect string: %s' % (connect_string)) + output_line('user: %s' % (username)) + script_ver = __version__[5:-2] + output_line('created by: %s' % (script_ver)) + print_stop_info(title) + show_qry('DB version', DB_VERSION_SQL) + show_qry('DB name', 'SELECT current_catalog') + sel_info_option = '--ver-info-sql' + for s in sys.argv[1:]: + if s.startswith(sel_info_option): + sel = s[len(sel_info_option):].strip('=') + try: + show_qry(sel, sel) + except: + ex_info = traceback.format_exc() + serr = '\nSQL: %s\nException: %s\n' % (sel, ex_info) + print_err(serr) + break def show_tables(): @@ -328,17 +532,36 @@ def show_tables(): def show_primary_keys(): - show_qry('primary keys', PRIMARY_KEYS_INFO_SQL) + show_qry('primary keys idxs', PRIMARY_KEYS_INFO_SQL) + """ + title = 'primary keys' + print_start_info(title) + cur = db_conn().cursor() + cur.execute(PRIMARY_KEYS_INFO_SQL) + for row in cur.fetchall(): + pk_flds = [] + tblname = row[0] + if tblname in TABLES: + pk_idxs = '%s' % row[1] + for fld_idx in pk_idxs.split(): + sql = TABLE_COLUMN_NAME_BY_IDX % (tblname, fld_idx) + cur.execute(sql) + for row in cur.fetchall(): + pk_flds.append(row[0]) + output_line("%s\t(%s)" % (tblname, '-'.join(pk_flds))) + print_stop_info(title)""" def show_indexes(): - output_line('\n\n') - output_line('--- %s ---' % 'indexes') + title = 'indexes' + print_start_info(title) for tbl in TABLES: show_qry_ex(INDEXES_INFO_SQL, tbl) #show_qry('indexes columns', INDEXES_COLUMNS_INFO_SQL) - output_line('\n\n') - output_line('--- %s ---' % 'indexes columns') + print_stop_info(title) + + title = 'indexes columns' + print_start_info(title) cur = db_conn().cursor() for tbl in TABLES: #print @@ -353,6 +576,7 @@ def show_indexes(): cur.execute(sql) for row in cur.fetchall(): output_line("%s\t%s\t%s" % (tbl, idxname, row[0])) + print_stop_info(title) def show_foreign_keys(): @@ -364,9 +588,14 @@ def show_defaults(): def show_views(): + show_qry('view names', VIEW_NAMES_SQL) show_qry('views', VIEWS_INFO_SQL, '\n', '\n\n') +def show_types_stat(): + show_qry('column type count', SQL_TYPES) + + def get_arg_type(at): """returns type name from type id""" cur = db_conn().cursor() @@ -409,13 +638,12 @@ def get_subfields(subfield_fld): def show_procedures(): + show_qry('procedure names', PROCEDURE_NAMES) argtypes_dict = {} - output_line('\n\n --- procedures ---') + title = 'procedures' + print_start_info(title) cur = db_conn().cursor() - cur.execute("""SELECT DISTINCT routine_name - FROM information_schema.routines - WHERE specific_schema NOT IN ('pg_catalog', 'information_schema') - ORDER BY 1""") + cur.execute(PROCEDURE_NAMES) rows = cur.fetchall() for rt_row in rows: funname = rt_row[0] @@ -447,6 +675,7 @@ def show_procedures(): argtypes = [] argmodes = get_subfields(row[5]) argtypes_str = '%s' % row[1] + args = argtypes_str proc_body = '%s' % row[3] lang = row[6] argtypes_nrs = get_subfields(row[4]) @@ -456,17 +685,19 @@ def show_procedures(): argmodes = 'i' * len(argtypes_nrs) for at in argtypes_nrs: if at: - if not at in argtypes_dict.keys(): + if at not in argtypes_dict.keys(): argtypes_dict[at] = get_arg_type(at) ats = argtypes_dict[at] argtypes.append(ats) + if argtypes: + args = ', '.join(argtypes) argnames = get_subfields(row[2]) if argnames: args = ', '.join([join_arg(a, t, m) for (a, t, m) in zip(argnames, argtypes, argmodes)]) - output_line('\n\n -- >>> %s >>> --' % funname) - lines = proc_body.split('\n') - output_line('CREATE FUNCTION %s(%s) RETURNS %s\nAS $$' % (funname, args, ret_type)) + output_line('\n\n -- >>> %s(%s) [%s] >>> --' % (funname, args, lang)) + lines = proc_body.rstrip().split('\n') + output_line('CREATE OR REPLACE FUNCTION %s(%s) RETURNS %s\nAS $$' % (funname, args, ret_type)) was_line = 0 for line in lines: line = line.rstrip() @@ -475,8 +706,11 @@ def show_procedures(): output_line(line) output_line('$$') output_line(' LANGUAGE %s;' % (lang)) - output_line('\n\n -- <<< %s <<< --' % funname) + output_line(' -- <<< %s(%s) [%s] <<< --' % (funname, args, lang)) + output_line('') + output_line('') cur.close() + print_stop_info(title) def show_triggers(): @@ -484,43 +718,77 @@ def show_triggers(): def test(): - main('127.0.0.1:music:postgres:postgres') + info_filer = 'kifdvtp' + #main('127.0.0.1:music:postgres:postgres', None) + get_schema('test-baza.heuthesd:5494:pg_flugo:postgres:postgres', 'postgres', 'postgres', info_filer, True) -def main(connect_string): - username = None - passwd = None - if (len(sys.argv) > 2): - username = sys.argv[2] - if (len(sys.argv) > 3): - passwd = sys.argv[3] - if not init_db_conn(connect_string, username, passwd): +def get_schema(connect_string, username, passwd, info_filter, show_connection_info): + db_close() + t0 = time.time() + if not init_db_conn(connect_string, username, passwd, show_connection_info): print('Something is terribly wrong with db connection') else: init_session() show_tables() - if not TABLES_ONLY: - show_primary_keys() - show_indexes() - show_foreign_keys() - show_defaults() - show_views() - show_triggers() - show_procedures() - print('\n\n--- the end ---') - - -if '--version' in sys.argv: - print(__version__) -elif '--test' in sys.argv: - test() -elif '--help' in sys.argv: - print(USAGE) -elif __name__ == '__main__': - if '--tables_only' in sys.argv: - TABLES_ONLY = 1 - if len(sys.argv) < 2: - #print('arg len: %d' % (len(sys.argv))) + if not TABLES_ONLY and info_filter: + if 'k' in info_filter: + show_primary_keys() + if 'i' in info_filter: + show_indexes() + if 'f' in info_filter: + show_foreign_keys() + if 'd' in info_filter: + show_defaults() + if 'v' in info_filter: + show_views() + if 't' in info_filter: + show_triggers() + if 'p' in info_filter: + show_procedures() + if 'T' in info_filter: + show_types_stat() + t2 = time.time() + td = t2 - t0 + output_line('\n\nexecution time: %d min %d sec' % (divmod(td, 60))) + output_line('\n\n-- the end, filter [%s] --' % (info_filter)) + db_close() + + +def get_info_filter(): + result = '' + for s in sys.argv[1:]: + if s.startswith('--info-filter='): + _, result = s.split('=', 1) + if not result: + result = 'kifdvtpT' + return result + + +def main(): + if '--version' in sys.argv: + print(__version__) + return + if '--test' in sys.argv: + test() + return + if '--help' in sys.argv: print(USAGE) - else: - main(sys.argv[1]) + return + args = [x for x in sys.argv[1:] if not x.startswith('-')] + if not args: + print(USAGE) + return + connect_string = args[0] + username = None + passwd = None + if (len(args) > 1): + username = args[1] + if (len(args) > 2): + passwd = args[2] + info_filter = get_info_filter() + get_schema(connect_string, username, passwd, info_filter, False) + + +if __name__ == '__main__': + main() diff --git a/recipes/Python/576621_Dump_Informix_schema_to_text/recipe-576621.py b/recipes/Python/576621_Dump_Informix_schema_to_text/recipe-576621.py index 786574f7e..4226dde17 100644 --- a/recipes/Python/576621_Dump_Informix_schema_to_text/recipe-576621.py +++ b/recipes/Python/576621_Dump_Informix_schema_to_text/recipe-576621.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -*- coding: utf8 -*- -__version__ = '$Id: schema_inf.py 1754 2014-02-14 08:57:52Z mn $' +__version__ = '$Id: schema_inf.py 3307 2017-11-29 06:18:57Z mn $' # export Informix schema to text using ODBC # usable to compare databases that should be the same @@ -22,11 +22,15 @@ # # Table names that start with '_' are ignored as they are temp tables # +# https://code.activestate.com/recipes/576621-dump-informix-schema-to-text/ +# # author: Michal Niklas USAGE = 'usage:\n\tschema_inf.py connect_string\n\t\tconnect string: odbc_database/user/password' +import re import sys +import time import traceback USE_JYTHON = 0 @@ -49,50 +53,76 @@ OUT_FILE_ENCODING = 'UTF8' +FILTER_TEMP = """tabtype='T' +AND systables.tabid >= 100 +AND tabname[1] <> '_' +""" + +if '--no-temp-tables' in sys.argv: + FILTER_TEMP += """AND tabname NOT LIKE '%tmp%' +AND tabname NOT LIKE '%temp%' +""" + +DB_VERSION_SQL = """SELECT FIRST 1 DBINFO('version','full') FROM systables""" TABLE_NAMES_SQL = """SELECT tabname FROM systables -WHERE tabtype='T' -AND tabid >= 100 -AND tabname[1] <> '_' -ORDER BY tabname""" +WHERE +%s +ORDER BY tabname""" % (FILTER_TEMP) + + +TABLE_COLUMNS_SQL = """SELECT tabname, colname +FROM syscolumns, systables +WHERE +%s +AND syscolumns.tabid = systables.tabid +ORDER BY tabname, colname +""" % (FILTER_TEMP) TABLE_INFO_SQL = """SELECT tabname, colname, colno, HEX(coltype), CASE MOD(coltype, 256) - WHEN 0 THEN 'char' - WHEN 1 THEN 'smallint' - WHEN 2 THEN 'integer' - WHEN 3 THEN 'float' - WHEN 4 THEN 'smallfloat' - WHEN 5 THEN 'decimal' - WHEN 6 THEN 'serial' - WHEN 7 THEN 'date' - WHEN 8 THEN 'money' - WHEN 9 THEN 'null' - WHEN 10 THEN 'datetime' - WHEN 11 THEN 'byte' - WHEN 12 THEN 'text' - WHEN 13 THEN 'varchar' - WHEN 14 THEN 'interval' - WHEN 15 THEN 'nchar' - WHEN 16 THEN 'nvarchar' - WHEN 17 THEN 'int8' - WHEN 18 THEN 'serial8' - WHEN 19 THEN 'set' - WHEN 20 THEN 'multiset' - WHEN 21 THEN 'list' - WHEN 22 THEN 'Unnamed ROW' - WHEN 40 THEN 'Variable-length' - WHEN 4118 THEN 'Named ROW' - ELSE '???' + WHEN 0 THEN 'char' + WHEN 1 THEN 'smallint' + WHEN 2 THEN 'integer' + WHEN 3 THEN 'float' + WHEN 4 THEN 'smallfloat' + WHEN 5 THEN 'decimal(' || (collength / 256)::int || ', ' || mod(collength, 256) || ')' + WHEN 6 THEN 'serial' + WHEN 7 THEN 'date' + WHEN 8 THEN 'money(' || (collength / 256)::int || ', ' || mod(collength, 256) || ')' + WHEN 9 THEN 'null' + WHEN 10 THEN 'datetime ' || substr(hex(collength), -2, 1) || ' to ' || substr(hex(collength), -1, 1) + WHEN 11 THEN 'byte' + WHEN 12 THEN 'text' + WHEN 13 THEN 'varchar' + WHEN 14 THEN 'interval' + WHEN 15 THEN 'nchar' + WHEN 16 THEN 'nvarchar' + WHEN 17 THEN 'int8' + WHEN 18 THEN 'serial8' + WHEN 19 THEN 'set' + WHEN 20 THEN 'multiset' + WHEN 21 THEN 'list' + WHEN 22 THEN 'row (unnamed)' + WHEN 23 THEN 'collection' + WHEN 40 THEN 'lvarchar fixed-length opaque types' + WHEN 41 THEN 'blob, boolean, clob variable-length opaque types' + WHEN 43 THEN 'lvarchar (client-side only)' + WHEN 45 THEN 'boolean' + WHEN 52 THEN 'bigint' + WHEN 53 THEN 'bigserial' + WHEN 2061 THEN 'idssecuritylabel' + WHEN 4118 THEN 'row (named)' + ELSE '???' END CASE, collength FROM syscolumns, systables -WHERE tabtype='T' -AND systables.tabid >= 100 -AND tabname[1] <> '_' +WHERE +%s AND syscolumns.tabid = systables.tabid ORDER BY tabname, colname -""" +""" % (FILTER_TEMP) + KEYS_INFO_SQL = """select tabname, a.colname column1, b.colname column2, c.colname column3, d.colname column4, e.colname column5, @@ -107,12 +137,11 @@ outer syscolumns i, outer syscolumns j, outer syscolumns k, outer syscolumns l, outer syscolumns m, outer syscolumns n, outer syscolumns o, outer syscolumns p -WHERE st.tabid >= 100 -AND tabtype='T' -AND tabname[1] <> '_' +WHERE +%s AND sc.tabid = st.tabid AND si.idxname = sc.idxname -AND sc.constrtype='%s' +AND sc.constrtype='%%s' and st.tabid = si.tabid and st.tabid = a.tabid and st.tabid = b.tabid @@ -147,7 +176,7 @@ and o.colno = part15 and p.colno = part16 ORDER BY tabname, column1, column2, column3, column4, column5 -""" +""" % (FILTER_TEMP.replace('systables.', 'st.')) INDEXES_INFO_SQL = """SELECT idxname, idxtype @@ -216,21 +245,18 @@ DEFAULTS_INFO_SQL = """SELECT tabname, colname, type, default FROM syscolumns, systables, sysdefaults -WHERE tabtype='T' -AND systables.tabid >= 100 -AND tabname[1] <> '_' +WHERE +%s AND syscolumns.tabid = systables.tabid AND sysdefaults.tabid = systables.tabid AND syscolumns.colno = sysdefaults.colno -ORDER BY tabname, colname""" +ORDER BY tabname, colname""" % (FILTER_TEMP) VIEWS_INFO_SQL = """SELECT tabname, tabid FROM systables -WHERE tabtype='V' -AND tabid >= 100 -AND tabname[1] <> '_' -""" +WHERE +%s""" % (FILTER_TEMP.replace("'T'", "'V'")) VIEWS_TEXT_SQL = """SELECT viewtext FROM sysviews @@ -241,11 +267,10 @@ TRIGGERS_INFO_SQL = """SELECT tabname, trigname, event FROM systables, systriggers -WHERE tabtype='T' -AND systables.tabid >= 100 -AND tabname[1] <> '_' +WHERE +%s AND systables.tabid = systriggers.tabid -ORDER BY tabname, trigname""" +ORDER BY tabname, trigname""" % (FILTER_TEMP) PROCEDURES_INFO_SQL = """SELECT procname, numargs, isproc, paramtypes::LVARCHAR, variant, handlesnulls, parallelizable @@ -254,6 +279,50 @@ ORDER BY procname, numargs, procid""" +SQL_TYPES = """SELECT COUNT(*)::int, +CASE MOD(coltype, 256) + WHEN 0 THEN 'char' + WHEN 1 THEN 'smallint' + WHEN 2 THEN 'integer' + WHEN 3 THEN 'float' + WHEN 4 THEN 'smallfloat' + WHEN 5 THEN 'decimal(' || (collength / 256)::int || ', ' || mod(collength, 256) || ')' + WHEN 6 THEN 'serial' + WHEN 7 THEN 'date' + WHEN 8 THEN 'money(' || (collength / 256)::int || ', ' || mod(collength, 256) || ')' + WHEN 9 THEN 'null' + WHEN 10 THEN 'datetime ' || substr(hex(collength), -2, 1) || ' to ' || substr(hex(collength), -1, 1) + WHEN 11 THEN 'byte' + WHEN 12 THEN 'text' + WHEN 13 THEN 'varchar' + WHEN 14 THEN 'interval' + WHEN 15 THEN 'nchar' + WHEN 16 THEN 'nvarchar' + WHEN 17 THEN 'int8' + WHEN 18 THEN 'serial8' + WHEN 19 THEN 'set' + WHEN 20 THEN 'multiset' + WHEN 21 THEN 'list' + WHEN 22 THEN 'row (unnamed)' + WHEN 23 THEN 'collection' + WHEN 40 THEN 'lvarchar fixed-length opaque types' + WHEN 41 THEN 'blob, boolean, clob variable-length opaque types' + WHEN 43 THEN 'lvarchar (client-side only)' + WHEN 45 THEN 'boolean' + WHEN 52 THEN 'bigint' + WHEN 53 THEN 'bigserial' + WHEN 2061 THEN 'idssecuritylabel' + WHEN 4118 THEN 'row (named)' + ELSE '???' +END CASE +FROM syscolumns, systables +WHERE +%s +AND syscolumns.tabid = systables.tabid +GROUP BY 2 +ORDER BY 1 desc, 2 +""" % (FILTER_TEMP) + _CONN = None _CONNECT_STRING = None @@ -276,20 +345,21 @@ def init_db_conn(connect_string, username, passwd): dbinfo = connect_string try: if USE_JYTHON: - print(dbinfo) + output_line(dbinfo) _CONN = zxJDBC.connect(connect_string, username, passwd, 'com.informix.jdbc.IfxDriver') else: (dbname, dbuser, _) = connect_string.split('/', 3) dbinfo = 'db: %s:%s' % (dbname, dbuser) try: _CONN = odbc.odbc(connect_string) - print(dbinfo) + output_line(dbinfo) except KeyboardInterrupt: raise + add_ver_info(connect_string, username) except: ex = sys.exc_info() s = 'Exception: %s: %s\n%s' % (ex[0], ex[1], dbinfo) - print(s) + output_line(s) return None return _CONN @@ -310,12 +380,42 @@ def show_db_error(querystr): """shows exception info""" ex = sys.exc_info() s = 'Exception: %s: %s\n\nSomething is terribly wrong with query:\n%s\n\n' % (ex[0], ex[1], querystr) - print('\n\n!!!\n\n%s\n\n!!!\n\n' % (s)) + output_line('\n\n!!!\n\n%s\n\n!!!\n\n' % (s)) sys.stderr.write(s) traceback.print_exc() reload_conn() +RE_DATETIME = re.compile(r'datetime (.) to (.)', re.IGNORECASE) + +IFX_DATETYPE = { + '0': "YEAR", + '2': "MONTH", + '4': "DAY", + '6': "HOUR", + '8': "MINUTE", + 'A': "SECOND", + 'B': "FRACTION(1)", + 'C': "FRACTION(2)", + 'D': "FRACTION(3)", + 'E': "FRACTION(4)", + 'F': "FRACTION(5)", + } + + +def linefilter_datetime(s): + """converts 'datetime 0 to 4' + to 'datetime YEAR to DAY' + """ + line = s + rx = RE_DATETIME.search(line) + if rx: + txt = line[rx.start(1):rx.end(2)] + txt2 = '%s to %s' % (IFX_DATETYPE[rx.group(1)], IFX_DATETYPE[rx.group(2)]) + line = line.replace(txt, txt2) + return line + + def output_str(fout, line): """outputs line to fout trying various encodings in case of encoding errors""" if fout: @@ -342,12 +442,20 @@ def output_str(fout, line): fout.flush() -def output_line(line): +def output_line(line, linefilter=None): """outputs line""" + if linefilter: + line = linefilter(line) line = line.rstrip() output_str(sys.stdout, line) +def print_err(serr): + """println on stderr""" + sys.stderr.write('%s\n' % (serr)) + output_line('\nERROR! ERROR!\n%s\n' % (serr)) + + def select_qry(querystr): """return rows from SELECT""" if querystr: @@ -375,28 +483,38 @@ def field_str(fld_value): return "???????" -def show_qry(title, querystr, fld_join='\t', row_separator=None): +def print_start_info(title): + output_line('\n\n') + output_line('--- %s (START) ---' % title) + + +def print_stop_info(title): + output_line('--- %s (END) ---' % title) + output_line('\n\n') + + +def show_qry(title, querystr, fld_join='\t', row_separator=None, linefilter=None): """prints rows from SELECT""" - print('\n\n') - print('--- %s ---' % title) + print_start_info(title) rs = select_qry(querystr) if rs: for row in rs: - output_line(fld_join.join([field_str(s) for s in row])) + output_line(fld_join.join([field_str(s) for s in row]), linefilter=linefilter) if row_separator: - print(row_separator) + output_line(row_separator) else: - print(' -- NO DATA --') + output_line(' -- NO DATA --') + print_stop_info(title) -def show_qry_ex(querystr, table, fld_join='\t', row_separator=None): +def show_qry_ex(querystr, table, fld_join='\t', row_separator=None, linefilter=None): """like show_qry() but with table name as first column""" rs = select_qry(querystr % table) if rs: for row in rs: - output_line("%s%s%s" % (table, fld_join, fld_join.join([field_str(s) for s in row]))) + output_line("%s%s%s" % (table, fld_join, fld_join.join([field_str(s) for s in row])), linefilter=linefilter) if row_separator: - print(row_separator) + output_line(row_separator) def init_session(): @@ -404,6 +522,31 @@ def init_session(): pass +def add_ver_info(connect_string, username): + """add version information""" + title = 'info' + print_start_info(title) + output_line('date: %s' % (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))) + output_line('connect string: %s' % (connect_string)) + output_line('user: %s' % (username)) + script_ver = __version__[5:-2] + output_line('created by: %s' % (script_ver)) + print_stop_info(title) + show_qry('DB version', DB_VERSION_SQL) + show_qry('DB name', "SELECT DBINFO('dbname') FROM systables WHERE tabid = 1") + sel_info_option = '--ver-info-sql' + for s in sys.argv[1:]: + if s.startswith(sel_info_option): + sel = s[len(sel_info_option):].strip('=') + try: + show_qry(sel, sel) + except: + ex_info = traceback.format_exc() + serr = '\nSQL: %s\nException: %s\n' % (sel, ex_info) + print_err(serr) + break + + def show_tables(): """prints table names""" cur = db_conn().cursor() @@ -413,7 +556,8 @@ def show_tables(): TABLES.append(row[0]) cur.close() show_qry('tables', TABLE_NAMES_SQL) - show_qry('columns', TABLE_INFO_SQL) + show_qry('table columns', TABLE_COLUMNS_SQL) + show_qry('columns', TABLE_INFO_SQL, linefilter=linefilter_datetime) def show_primary_keys(): @@ -423,15 +567,18 @@ def show_primary_keys(): def show_indexes(): """print indexes""" - print('\n\n') - print('--- %s ---' % 'indexes') + title = 'indexes' + print_start_info(title) for tbl in TABLES: show_qry_ex(INDEXES_INFO_SQL, tbl) #show_qry('indexes columns', INDEXES_COLUMNS_INFO_SQL) - print('\n\n') - print('--- %s ---' % 'indexes columns') + print_stop_info(title) + + title = 'indexes columns' + print_start_info(title) for tbl in TABLES: show_qry_ex(INDEXES_COLUMNS_INFO_SQL, tbl) + print_stop_info(title) def show_foreign_keys(): @@ -446,8 +593,8 @@ def show_defaults(): def show_views(): """print views""" - print('\n\n') - print('--- %s ---' % 'views') + title = 'views' + print_start_info(title) cur = db_conn().cursor() try: cur.execute(VIEWS_INFO_SQL) @@ -458,17 +605,22 @@ def show_views(): try: cur2 = db_conn().cursor() cur2.execute(querystr) - print(tabname) + output_line(tabname) vt = [] for row2 in cur2.fetchall(): vt.append(row2[0]) vtt = ''.join(vt) output_line(vtt.rstrip()) - print('') + output_line('') except: show_db_error(querystr) except: show_db_error(VIEWS_INFO_SQL) + print_stop_info(title) + + +def show_types_stat(): + show_qry('column type count', SQL_TYPES, linefilter=linefilter_datetime) def get_body(qry): @@ -485,8 +637,8 @@ def get_body(qry): def show_procedures(): """show procedures and functions""" show_qry('procedures/functions', PROCEDURES_INFO_SQL) - print('\n\n') - print('--- %s ---' % 'procedures/functions bodies') + title = 'procedures/functions bodies' + print_start_info(title) querystr1 = """SELECT procid, procname FROM sysprocedures WHERE internal='f' AND mode IN ('D', 'd', 'O', 'o') @@ -502,17 +654,17 @@ def show_procedures(): for row in rs: funname = row[1] body = get_body(querystr2 % row[0]) - print('\n\n -- >>> %s >>> --' % funname) + output_line('\n\n -- >>> %s >>> --' % funname) output_line(body) - print('\n\n -- <<< %s <<< --' % funname) - print('--- ---') + output_line('\n\n -- <<< %s <<< --' % funname) + print_stop_info(title) def show_triggers(): """show triggers""" show_qry('triggers', TRIGGERS_INFO_SQL) - print('\n\n') - print('--- %s ---' % 'triggers bodies') + title = 'triggers bodies' + print_start_info(title) querystr1 = """SELECT trigid, tabname, trigname FROM systables, systriggers WHERE tabtype='T' @@ -537,41 +689,70 @@ def show_triggers(): for row in rs: body_def = get_body(querystr2 % trigid) body_txt = get_body(querystr3 % trigid) - print('\n\n -- >>> %s >>> --' % trigname) + output_line('\n\n -- >>> %s >>> --' % trigname) output_line(body_def) output_line(body_txt) - print('\n\n -- <<< %s <<< --' % trigname) - print('--- ---') + output_line('\n\n -- <<< %s <<< --' % trigname) + print_stop_info(title) + + +def get_info_filter(): + result = '' + for s in sys.argv[1:]: + if s.startswith('--info-filter='): + _, result = s.split('=', 1) + if not result: + result = 'kifdvtpT' + return result def main(): """main""" - connect_string = sys.argv[1] + if '--version' in sys.argv: + print(__version__) + return + args = [x for x in sys.argv[1:] if not x.startswith('-')] + if not args: + print(USAGE) + return + connect_string = args[0] username = None passwd = None - if (len(sys.argv) > 2): - username = sys.argv[2] - if (len(sys.argv) > 3): - passwd = sys.argv[3] + if (len(args) > 1): + username = args[1] + if (len(args) > 2): + passwd = args[2] if not init_db_conn(connect_string, username, passwd): - print('Something is terribly wrong with db connection') + output_line('Something is terribly wrong with db connection') else: + tables_only = '--tables-only' in sys.argv + info_filter = get_info_filter() + t0 = time.time() init_session() show_tables() - show_primary_keys() - show_indexes() - show_foreign_keys() - show_defaults() - show_views() - show_triggers() - show_procedures() - print('--- the end ---') - - -if '--version' in sys.argv: - print(__version__) -elif __name__ == '__main__': - if len(sys.argv) < 2: - print(USAGE) - else: - main() + if not tables_only and info_filter: + if 'k' in info_filter: + show_primary_keys() + if 'i' in info_filter: + show_indexes() + if 'f' in info_filter: + show_foreign_keys() + if 'd' in info_filter: + show_defaults() + if 'v' in info_filter: + show_views() + if 't' in info_filter: + show_triggers() + if 'p' in info_filter: + show_procedures() + if 'T' in info_filter: + show_types_stat() + + t2 = time.time() + td = t2 - t0 + output_line('\n\nexecution time: %d min %d sec' % (divmod(td, 60))) + output_line('\n\n-- the end, filter [%s] --' % (info_filter)) + + +if __name__ == '__main__': + main() From 744c1a3f65c2043b7d5302de677cc5b87933777b Mon Sep 17 00:00:00 2001 From: Alan Young Date: Sat, 23 Dec 2017 11:48:06 -0700 Subject: [PATCH 29/35] mktemp is a better way to manage tmp files --- recipes/Bash/578661_find__grep/recipe-578661.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/recipes/Bash/578661_find__grep/recipe-578661.sh b/recipes/Bash/578661_find__grep/recipe-578661.sh index 3846e2bee..62773a86f 100644 --- a/recipes/Bash/578661_find__grep/recipe-578661.sh +++ b/recipes/Bash/578661_find__grep/recipe-578661.sh @@ -1,6 +1,6 @@ #!/usr/bin/env zsh -tmp_file="/tmp/_unsorted_find_n_grep" +tmp_file="$(mktemp)" echo "--- find <$2> in <$1>" > $tmp_file find . -follow -iname "$1" | while read file From 610d487c85cbfc3d68c1027df8c1ca04d8a6f541 Mon Sep 17 00:00:00 2001 From: Alan Young Date: Sat, 23 Dec 2017 11:50:41 -0700 Subject: [PATCH 30/35] added an alias for tree command if it doesnt exist on the system --- recipes/Bash/tree_alias/LICENSE.md | 1 + recipes/Bash/tree_alias/README.md | 8 ++++++++ recipes/Bash/tree_alias/tree | 10 ++++++++++ 3 files changed, 19 insertions(+) create mode 100644 recipes/Bash/tree_alias/LICENSE.md create mode 100644 recipes/Bash/tree_alias/README.md create mode 100644 recipes/Bash/tree_alias/tree diff --git a/recipes/Bash/tree_alias/LICENSE.md b/recipes/Bash/tree_alias/LICENSE.md new file mode 100644 index 000000000..09dcacce0 --- /dev/null +++ b/recipes/Bash/tree_alias/LICENSE.md @@ -0,0 +1 @@ +This work is released to the public domain under the CC0 (Creative Commons) license terms: https://creativecommons.org/publicdomain/zero/1.0/legalcode \ No newline at end of file diff --git a/recipes/Bash/tree_alias/README.md b/recipes/Bash/tree_alias/README.md new file mode 100644 index 000000000..5d594ab7e --- /dev/null +++ b/recipes/Bash/tree_alias/README.md @@ -0,0 +1,8 @@ +### An alias for the tree command + +Author: Unknown +Submitter: Alan Young (harleypig) + +If the tree command does not exist on your system, this alias will fake it. + +I got this from a co-worker a long time ago. I don't remember when, or who it was. If it was you, let me know and I'll update this. diff --git a/recipes/Bash/tree_alias/tree b/recipes/Bash/tree_alias/tree new file mode 100644 index 000000000..d9282f262 --- /dev/null +++ b/recipes/Bash/tree_alias/tree @@ -0,0 +1,10 @@ +#!/bin/bash + +# I got this from a co-worker many moons ago. Unfortunately, I don't remember +# who. Basically, if a tree program is not installed, fake it with this. + +if ! command -v tree > /dev/null 2>&1; then + + alias tree="find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'" + +fi From acde9bbeb7337c821934d8649ca203c9e3192303 Mon Sep 17 00:00:00 2001 From: Geoff Crompton Date: Thu, 15 Mar 2018 11:42:03 +1100 Subject: [PATCH 31/35] Removing 278260, it's a duplicate of 278259 --- .../Python/278260_Dictionary_Tools/LICENSE.md | 3 - .../Python/278260_Dictionary_Tools/README.md | 6 - .../278260_Dictionary_Tools/recipe-278260.py | 291 ------------------ 3 files changed, 300 deletions(-) delete mode 100644 recipes/Python/278260_Dictionary_Tools/LICENSE.md delete mode 100644 recipes/Python/278260_Dictionary_Tools/README.md delete mode 100644 recipes/Python/278260_Dictionary_Tools/recipe-278260.py diff --git a/recipes/Python/278260_Dictionary_Tools/LICENSE.md b/recipes/Python/278260_Dictionary_Tools/LICENSE.md deleted file mode 100644 index 86fe1ce11..000000000 --- a/recipes/Python/278260_Dictionary_Tools/LICENSE.md +++ /dev/null @@ -1,3 +0,0 @@ -Copyright 2004 Runsun Pan - -The software is licensed according to the terms of the PSF (Python Software Foundation) license found here: http://www.python.org/psf/license/ \ No newline at end of file diff --git a/recipes/Python/278260_Dictionary_Tools/README.md b/recipes/Python/278260_Dictionary_Tools/README.md deleted file mode 100644 index 61a762b68..000000000 --- a/recipes/Python/278260_Dictionary_Tools/README.md +++ /dev/null @@ -1,6 +0,0 @@ -## Dictionary Tools -Originally published: 2004-04-14 14:06:08 -Last updated: 2004-04-14 14:06:08 -Author: Runsun Pan - -A collection of some dictionary tools \ No newline at end of file diff --git a/recipes/Python/278260_Dictionary_Tools/recipe-278260.py b/recipes/Python/278260_Dictionary_Tools/recipe-278260.py deleted file mode 100644 index 5a48beb42..000000000 --- a/recipes/Python/278260_Dictionary_Tools/recipe-278260.py +++ /dev/null @@ -1,291 +0,0 @@ -#======================================================================== - -def sumDict(d): - return reduce(lambda x,y:x+y, d.values()) - -#======================================================================== - -def avgDict(d): - return reduce(lambda x,y:x+y, d.values()) / (len(d)*1.0) - -#======================================================================== - -def mkDict(keyList, valueList, cond=None): - ''' - Make a new dict out of two lists. The first list provides keys, - the 2nd provides values. The cond is a function taking 2 arguments: - key and value. Example: lambda k,v:v%2==0 - A valid item means its cond(key, value) is true. Only valid items - are included in the returned dict. - - >>> a - [0, 1, 2, 3, 4] - - >>> b= [chr(x) for x in range(65,70)] - >>> b - ['A', 'B', 'C', 'D', 'E'] - - >>> mkDict(b,a) - {'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3} - - >>> mkDict(b,a,lambda x,y:y%2==0) - {'A': 0, 'C': 2, 'E': 4} - - Note: - mkDict(a,b) (without the conditional check) is equavilant to - dict(zip(a,b)), which is much faster. If you know there's no - conditional check, better use dict(zip(a,b)) instead. - ''' - - if cond==None: - return dict(zip(keyList, valueList)) - else: - return dict( [(k,v) for k,v in zip(keyList, valueList) if cond(k,v)] ) - -#======================================================================== - -def trimDict(aDict, cond=(lambda k,v:1)): - ''' Return a new dict in which its items whose cond(k,v) == true - are removed (discarded) from aDict. - The cond is a function taking 2 arguments: key and value - - >>> g - {'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3} - >>> trimDict(g, lambda x,y:y%2!=0) - {'A': 0, 'C': 2, 'E': 4} - - ''' - tmp={} - [tmp.setdefault(k,v) for k,v in aDict.items() if not cond(k,v)] - return tmp.copy() - -#======================================================================== - -def reDict(aDict, func, cond=(lambda k,v:1), delUnchanged=0): - ''' - Given aDict, return a new dict with valid items (= items whose - cond(key, value) is true) been modified by the function func. - if delUnchanged, then those invalid items are excluded from - the returned dict. - - >>> d - {'B': 1, 'D': 3} - >>> reDict(d, lambda x:x**2) - {'B': 1, 'D': 9} - >>> g - {'A': 0, 'C': 2, 'B': 1, 'E': 4, 'D': 3} - >>> reDict(g, lambda x:-x, lambda k,v: v%2==0) - {'A': 0, 'C': -2, 'B': 1, 'E': -4, 'D': 3} - >>> reDict(g, lambda x:-x, lambda k,v: v%2==0, delUnchanged=1) - {'A': 0, 'C': -2, 'E': -4} - - ''' - tmp={} - if delUnchanged: - [tmp.setdefault(k,func(v)) for k,v in aDict.items() if cond(k,v)] - else: - [tmp.setdefault(k,(cond(k,v) and func(v) or v)) for k,v in aDict.items()] - return tmp.copy() - -#======================================================================== - -def normDict(d, normalizeTo=1): - ''' Normalize the values of d by setting the largest value in d.values - to normalizeTo. The return dict will have it's values spreading - between 0~normalizeTo''' - ks = d.keys() - vs = d.values() - vMax = max(vs) - vs= [ x/(vMax*1.0)*normalizeTo for x in vs] - return dict(zip(ks, vs)) - -#======================================================================== - -def normDictSumTo(d, sumTo=1): - ''' Normalize the values of d to sumTo. The returned dict will - have value sum = sumTo - ''' - ks = d.keys() - vs = d.values() - sum = reduce(lambda x,y:x+y, vs) - vs= [ x/(sum*1.0)*sumTo for x in vs] - return dict(zip(ks, vs)) - -#======================================================================== - -def accumDict(d, normalizeTo=None): - ''' if d.values=[1,2,3,4,5]: - accumDict(d).values ==> [1, 3, 6, 10, 15] - if d.values=[0.25, 0.25, 0.25, 0.25] - accumDict(d).values ==> [0.25, 0.50, 0.75, 1.00] - - Required: odict() - Ordered Dictionary Class - Dave Benjamin - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/161403 - ''' - ks = d.keys() - vs = d.values() - if normalizeTo: vs = normListSumTo(vs, sumTo=normalizeTo) - - r = range(1, len(vs)) - newList=[vs[0]] - for i in r: - newList.append( newList[-1]+ vs[i] ) - - odic = odict() - for i in range(len(newList)): - odic[ks[i]] =newList[i] - return odic - -#======================================================================== - -def fallInDict(val, aDict, baseValue=0): - ''' - oo: - { - 'a':3, - 'b':5, - 'c':2 - } - accumDict(oo): - { - 'a':3, - 'b':8, - 'c':10 - } - fallInDict(0, oo)=0 - fallInDict(1, oo)=0 - fallInDict(2, oo)=0 - fallInDict(3, oo)=0 - fallInDict(4, oo)=1 - fallInDict(5, oo)=1 - fallInDict(6, oo)=1 - fallInDict(7, oo)=1 - fallInDict(8, oo)=1 - fallInDict(9, oo)=2 - fallInDict(10, oo)=2 - - When val out of range: - - fallInDict(-1, oo)= -1 - fallInDict(11, oo)= -2 - fallInDict(12, oo)= -2 - ''' - - if valacd.values()[-1]: return -2 - - ra = range(len(acd)) - - for i in ra: - vInDict = acd.values()[i] - if val <= vInDict: break - - return aDict.keys()[i] - -#======================================================================== - -def randomPickDict(d): - ''' given a diictionary d, with all values are numbers, - randomly pick an item and return it's key according - to the percentage of its values''' - ks = d.keys() - vs = accumList(d.values(),1) - return ks[ findIndex( vs, random.random()) ] - -#======================================================================== - -def sumInDict(L): - ''' Given a list L: - [ {'S': [s11,s12,s13], 'V':[v11,v12,v13], ...}, - {'S': [s21,s22,s23], 'V':[v21,v22,v23], ...}, - {'S': [s31,s32,s33], 'V':[v31,v32,v33], ...}, - ... ] - - Return a dict: - {'S': [s1,s2,s3], 'V':[v1,v2,v3], ...} - - where s1 = s11 + s21 + s31 + ... - s2 = s12 + s22 + s32 + ... - ''' - keys = L[0].keys() - new={} - for k in keys: - new[k] = [] # Init 'S':[] - for x in L: # x = {'S': [s11,s12,s13], 'V':[v11,v12,v13], ...} - y = x[k] # y = [s11,s12,s13] - new[k].append(y) - - ''' new[k] = [ [s11,s12,s13],[s21,s22,s23],[s31,s32,s33], ...] - Then use sumInList=> {'S': [s1,s2,s3],'V': [v1,v2,v3],... }''' - new[k] = sumInList(new[k]) - return new - -#======================================================================== - -def avgInDict(L): - ''' Given a list L: - [ {'S': [s11,s12,s13], 'V':[v11,v12,v13], ...}, - {'S': [s21,s22,s23], 'V':[v21,v22,v23], ...}, - {'S': [s31,s32,s33], 'V':[v31,v32,v33], ...}, - ... ] - - Return a dict: - {'S': [s1,s2,s3], 'V':[v1,v2,v3], ...} - - where s1 = avg of (s11 + s21 + s31 + ...) - s2 = avg of (s12 + s22 + s32 + ...) - ''' - ''' First turn L into: - {'S': [ [s11,s12,s13],[s21,s22,s23],[s31,s32,s33], ...], - 'V': [ [v11,v12,v13],[v21,v22,v23],[v31,v32,v33], ...], - ... } ''' - - keys = L[0].keys() - new={} - for k in keys: - new[k] = [] # Init 'S':[] - for x in L: # x = {'S': [s11,s12,s13], 'V':[v11,v12,v13], ...} - y = x[k] # y = [s11,s12,s13] - new[k].append(y) - - ''' new[k] = [ [s11,s12,s13],[s21,s22,s23],[s31,s32,s33], ...] - Then use avgInList=> {'S': [s1,s2,s3],'V': [v1,v2,v3],... }''' - new[k] = avgInList(new[k]) - return new - -#======================================================================== - -def sumInDict2(D): - ''' Given a dict: - {'A':{'S': [s11,s12,s13], 'V':[v11,v12,v13], ...}, - 'B':{'S': [s21,s22,s23], 'V':[v21,v22,v23], ...}, - 'C':{'S': [s31,s32,s33], 'V':[v31,v32,v33], ...}, ... - } - Return a dict: - {'S': [s1,s2,s3], 'V':[v1,v2,v3], ...} - - where s1 = s11 + s21 + s31 + ... - s2 = s12 + s22 + s32 + ... - ''' - return sumInDict(D.values()) - -#======================================================================== - -def avgInDict2(D): - ''' Given a dict: - {'A':{'S': [s11,s12,s13], 'V':[v11,v12,v13], ...}, - 'B':{'S': [s21,s22,s23], 'V':[v21,v22,v23], ...}, - 'C':{'S': [s31,s32,s33], 'V':[v31,v32,v33], ...}, ... - } - Return a dict: - {'S': [s1,s2,s3], 'V':[v1,v2,v3], ...} - - where s1 = avg of (s11 + s21 + s31 + ...) - s2 = avg of (s12 + s22 + s32 + ...) - ''' - return avgInDict(D.values()) - -#======================================================================== From 61a74f5f93da087d27c70b2efe779ac6bd2a3b4f Mon Sep 17 00:00:00 2001 From: Jeff Rouse Date: Tue, 2 Jul 2019 23:44:37 -0700 Subject: [PATCH 32/35] Changed extension to denote a java file. --- .../{recipe-576955.js => recipe-576955.java} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename recipes/JavaScript/576955_Incrementing_counter/{recipe-576955.js => recipe-576955.java} (100%) diff --git a/recipes/JavaScript/576955_Incrementing_counter/recipe-576955.js b/recipes/JavaScript/576955_Incrementing_counter/recipe-576955.java similarity index 100% rename from recipes/JavaScript/576955_Incrementing_counter/recipe-576955.js rename to recipes/JavaScript/576955_Incrementing_counter/recipe-576955.java From 5b83ef48a845deffe0f8596724678e73390a3885 Mon Sep 17 00:00:00 2001 From: Tammy DiPrima Date: Mon, 11 May 2020 12:08:15 -0400 Subject: [PATCH 33/35] fixed missing import statement 'import re' --- .../577468_Minimalistic_PostgreSQL_console/recipe-577468.py | 1 + 1 file changed, 1 insertion(+) diff --git a/recipes/Python/577468_Minimalistic_PostgreSQL_console/recipe-577468.py b/recipes/Python/577468_Minimalistic_PostgreSQL_console/recipe-577468.py index 53eb233f4..18c4e9769 100644 --- a/recipes/Python/577468_Minimalistic_PostgreSQL_console/recipe-577468.py +++ b/recipes/Python/577468_Minimalistic_PostgreSQL_console/recipe-577468.py @@ -1,6 +1,7 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- +import re import sys import psycopg2 import psycopg2.extras From db8c96c09c06d52b1ad4b0a6ff7f001f3d2241d6 Mon Sep 17 00:00:00 2001 From: swaroop998 <72223625+swaroop998@users.noreply.github.com> Date: Fri, 2 Oct 2020 00:08:28 +0530 Subject: [PATCH 34/35] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c7f9c4eb7..28c4eaf7a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ActiveState Code Recipes -Welcome to the ActiveState code recipes repo! We have migrated all of the great content from code.activestate.com to its new +Welcome to the ActiveState Code recipes repo! We have migrated all of the great content from code.activestate.com to its new forever-home here at GitHub. This makes it easier for everyone to submit new recipes, contribute code and integrate all the great information into their own projects. @@ -18,7 +18,7 @@ You can find the master index of all recipes over at the [wiki](https://github.c *Coming Soon: Search Functionality!* -## How do I submit a new recipe? +## How could I submit a new recipe? 1. Fork this repo. 2. Create your new recipe in the correct language subfolder (create a new folder if it doesn't already exist). From e6378c55515c45eb8eab07ca64c59ddefba9bf94 Mon Sep 17 00:00:00 2001 From: Jeff Rouse Date: Mon, 12 Oct 2020 16:31:24 -0700 Subject: [PATCH 35/35] Removed short form for between for inline docs. --- .../Python/578112_Bresenhams_line_algorithm/recipe-578112.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/recipes/Python/578112_Bresenhams_line_algorithm/recipe-578112.py b/recipes/Python/578112_Bresenhams_line_algorithm/recipe-578112.py index 8838ad588..dffe22406 100644 --- a/recipes/Python/578112_Bresenhams_line_algorithm/recipe-578112.py +++ b/recipes/Python/578112_Bresenhams_line_algorithm/recipe-578112.py @@ -68,8 +68,8 @@ def _bresenhamlines(start, end, max_iter): def bresenhamline(start, end, max_iter=5): """ - Returns a list of points from (start, end] by ray tracing a line b/w the - points. + Returns a list of points from (start, end] by ray tracing a line between + the points. Parameters: start: An array of start points (number of points x dimension) end: An end points (1 x dimension)