package
stringlengths 1
122
| pacakge-description
stringlengths 0
1.3M
|
---|---|
ahbicht | A python package that parses condition expressions from EDI@Energy
Anwendungshandbücher (AHB). Since it’s based on lark, we named the
module AHBicht.What is this all about?The German energy market usesEDIFACTas an intercompany
data exchange format. The rules on how to structure and validate the
EDIFACT messages are written inoneMessageImplementationGuide (MIG) per EDIFACT
format (for example UTILMD or MSCONS)oneAnwendungshandbuch (AHB,
en. manual) per use case group (for exampleGPKEorWechselprozesse im Messwesen(WiM))According to the legislation for the German energy market, the
organisations in charge of maintaining the documents described above
(AHB and MIGs) are theBundesverbandderEnergie-
undWasserwirtschaft (BDEW) and theBundesnetzagentur (BNetzA). They form a working
group named “Arbeitsgruppe EDI@Energy”. This work group publishes the
MIGs and AHBs onedi-energy.de. The
documents are published as PDFs which is better than faxing them but far
from ideal.The AHBs contain information on how to structure single EDIFACT
messages. To create messages that are valid according to the respective
AHB, you have to process information of the kind:In this example:This library parses the string
``Muss [210] U ([182] X ([90] U [183]))`` and allows determining whether
“Details der Prognosegrundlage” is an obligatory field according to the
AHB, iff the individual status of the conditions is given.We call
this “expression evaluation”.Note that determining the individual status of[210],[182],[90]and[183]itself (the so called “content evaluation”, see
below) isnotwithin the scope of this parsing library.Note also, that this library also parses the new convention using logical operators that becomes effective 2022-04-01 (“MaKo2022”).Muss [210] ∧ ([182] ⊻ ([90] ∧[183])).Usage and ExamplesJupyter NotebookFor a minimal working example on how what the library is used, check outthis Jupyter notebook.Free to Use REST APIYou can also use our public REST API to parse condition expressions (other features will follow). Simply send a GET request with the condition expression as query parameter to:ahbicht.azurewebsites.net/api/ParseExpression?expression=[2] U ([3] O [4])[901] U [555]Easily Integrate AHBicht with Your SolutionIf you want to use AHBicht together with your own software, you can use theJSON Schema filesprovided to kick start the integration.Code Quality / Production ReadinessThe code has at least a 95% unit test coverage. ✔️The code is rated 10/10 in pylint and type checked with mypy. ✔️The code isMIT licensed. ✔️There are onlyfew dependencies. ✔️Expression Evaluation / Parsing the Condition StringEvaluating expressions likeMuss [59] U ([123] O [456])from the
AHBs by parsing it with theparsing library
larkand
combining the parsing result with information about the state of[59],[123],[456]is calledexpression evaluation.
Determining the state of each single condition (f.e.[59]is
fulfilled,[123]is not fulfilled,[456]is unknown) for a given
message is part of thecontent evaluation(see next chapter).If you’re new to this topic, please readedi-energy.de → Dokumente →
Allgemeine
Festlegungenfirst. This document contains German explanations, how the Bedingungen
are supposed to be read.FunctionalityExpressions can contain single numbers e.g.[47]or numbers
combined withU/O/Xor∧/∨/⊻respectively which are translated to boolean
operatorsand/or/exclusive or, e.g.[45]U[2]or they
can be combinedwithoutan operator, e.g.[930][5]in the
case of FormatConstraints.Expressions can contain random whitespaces.Input conditions are passed in form of aConditionNode, see
below.Bedingungen/RequirementConstraintswith a boolean value,
Hinweise/Hintsand Formatdefinitionen/FormatConstraintsare
so far functionally implemented as the result returns if the
condition expression is fulfilled and which Hints and
FormatConstraints are relevant.The boolean logic follows ‘brackets( )beforethen_alsobeforeandbeforeor’.Hints and UnevaluatedFormatConstraints are implemented asneutralelement, so not changing the boolean outcome of an expression for the
evaluation regarding the requirement constraints and raising errors
when there is no sensible logical outcome of the expression.Acondition_fulfilledattribute can also take the valueunknown.Brackets e.g.([43]O[4])U[5]Requirement indicators (i.eMuss,Soll,Kann,X,O,U) are seperated from the condition expressions and also
seperated into single requirement indicator expressions if there are
more than one (for modal marks).Format Constraint Expressionsthat are returned after the
requirement condition evaluation can now be parsed and evaluated.Evaluate several modal marks in one ahb_expression: the first one
that evaluates to fulfilled is the valid one.In planningEvaluate requirement indicators:Soll, Kann, Muss, X, O, U -> is_required, is_forbidden, etc…Definition of termsTermDescriptionExampleconditionsingle operand[53]condition_keyint or str, the number of the condition53operatorcombines two conditionsU, Ocompositiontwo parts of an expression combined by an operator([4]U[76])O[5] consists of an and_composition of [4] and [76] and an or_composition of [4]U[76] and [5]used in the context of the parsing and evaluation of the expressionahb expressionan expression as given from the ahbX[59]U[53]Consists of at least one single requirement indicator expression.Muss[59]U([123]O[456])Soll[53]In case of several model mark expressions the first one will be evaluated and if not fulfilled, it will be continued with the next one.single requirement indicator expressionAn expression consisting of exactly one requirement indicator and their respective condition expression.Soll[53]If there is only one requirement indicator in the ahb expression, then both expressions are identical.condition expressionone or multiple conditions combined with or (in case of FormatConstraints) also without operators[1]used as input for the condition parser[4]O[5]U[45]format constraint expressionIs returned after the evaluation of the RequirementConstraints[901]X[954]consist only of FormatConstraintsrequirement indicatorThe Merkmal/modal_mark or Operator/prefix_operator of the data element/data element group/segment/segment group.Muss, Soll, Kann, X, O, UMerkmal / modal_markas defined by the EDI Energy group (see edi-energy.de → Dokumente → Allgemeine Festlegungen)Muss, Soll, KannStands alone or before a condition expression, can be the start of several requirement indicator expressions in one ahb expressionprefix operatorOperator which does not function to combine conditions, but as requirement indicator.X, O, UStands alone or in front of a condition expression.tree, branches, tokenas used by larkConditionNodeDefines the nodes of the tree as they are passed, evaluated und returned.RequirementConstraint, FormatConstraint, Hint, EvaluatedComposition, RepeatabilityConstraintThere are different kinds of conditions (Bedingung, Hinweis, Format) as defined by the EDI Energy group (see edi-energy.de → Dokumente → Allgemeine Festlegungen) and also a EvaluatedComposition after a composition of two nodes is evaluated.Bedingung / RequirementConstraint (rc)are true or false, has to be determined“falls SG2+IDE+CCI == EHZ”keys between [1] and [499]Wiederholbarkeit / RepeatabilityConstraintgives minimum and maximum occurrence“Segmentgruppe ist mindestens einmal je SG4 IDE+24 (Vorgang) anzugeben”keys between [2000] and [2499]Hinweis / Hintjust a hint, even if it is worded like a condition“Hinweis: ‘ID der Messlokation’”keys from [500] onwards, starts with ‘Hinweis:’“Hinweis: ‘Es ist der alte MSB zu verwenden’”Formatdefinition / FormatConstraint (fc)a constraint for how the data should be given“Format: Muss größer 0 sein”keys between [901] and [999], starts with ‘Format:’“Format: max 5 Nachkommastellen”Format Constraints are “collected” while evaluating the rest of the tree, meaning the evaluated composition of the Mussfeldprüfung contains an expression that consists only of format constraints.UnevaluatedFormatConstraintA format constraint that is just “collected” during the requirement constraint evaluation. To have a clear separation of conditions that affect whether a field is mandatory or not and those that check the format of fields without changing their state it will become a part of the format_constraint_expression which is part of the EvaluatedComposition.EvaluatableFormatConstraintAn evaluatable FormatConstraint will (other than the UnevaluatedFormatConstraint) be evaluated by e.g. matching a regex, calculating a checksum etc. This happens after the Mussfeldprüfung. (details to be added upon implementing)EvaluatedCompositionis returned after a composition of two nodes is evaluatedPackage Resolvera package resolver is a class that replaces package nodes in a tree with a sub tree that is derived from a package definition. Replacing package nodes with sub trees is referred to as “package expansion”Example: “[123P]” is replaced with a tree for “[5]U[6]O[7]”neutralHints and UnevaluatedFormat Constraints are seen as neutral as they don’t have a condition to be fulfilled or unfulfilled and should not change the requirement outcome. See truth table below.unknownIf the condition can be fulfilled but we don’t know (yet) if it is or not. See truth table below.“Wenn vorhanden”The decision if a requirement constraint is met / fulfilled / true is
made in the content evaluation module.Program structureThe following diagram shows the structure of the condition check for
more than one condition. If it is only a single condition or just a
requirement indicator, the respective tree consists of just this token
and the result equals the input.The raw and updated data for this diagram can be found in thedraw_io_charts
repositoryand edited underapp.diagrams.netwith your GitHub Account.There is also anUML Diagramavailable (last updated 2022-01-29).Truth tablesAdditionally to the usual boolean logic we also haveneutralelements (e.g.Hints,UnevaluatedFormatConstraintsand in some
casesEvaluatedCompositions) orunknownrequirement constraints.
They are handled as follows:and_compositionABA U BNeutralTrueTrueNeutralFalseFalseNeutralNeutralNeutralUnknownTrueUnknownUnknownFalseFalseUnknownUnknownUnknownUnknownNeutralUnknownor_compositionABA O BnoteNeutralTruedoes not make senseNeutralFalsedoes not make senseNeutralNeutralNeutralno or_compositions of
hint and format
constraintUnknownTrueTrueUnknownFalseUnknownUnknownUnknownUnknownUnknownNeutraldoes not make sensexor_compositionABA X BnoteNeutralTruedoes not make senseNeutralFalsedoes not make senseNeutralNeutralNeutralno xor_compositions
of hint and format
constraintUnkownTrueUnknownUnkownFalseUnknownUnkownUnknownUnknownUnkownNeutraldoes not make senseLink to automatically generate HintsProvider Json content:https://regex101.com/r/za8pr3/5Content EvaluationEvaluation is the term used for the processing ofsingleunevaluated
conditions. The results of the evaluation of all relevant conditions
inside a message can then be used to validate a message. The latter isnotpart of the evaluation.This library doesnotprovide content evaluation code for all the
conditions used in the available AHBs. You can use the Content
Evaluation class stubs though. Please contact@JoschaMetzeif you’re interested in a
ready-to-use solution to validate your EDIFACT messages according to the
latest AHBs. We probably have you covered.EvaluatableData (Edifact Seed and others)For the evaluation of a condition (that is referenced by its key,
e.g. “17”) it is necessary to have a data basis that allows to decide
whether the respective condition is met or not met. This data basis that
is stable for all conditions that are evaluated in on evaluation run is
calledEvaluatableData. These data usually contain theedifact
seed(a JSON representation of the EDIFACT message) but may also hold
other information. TheEvaluatableDataclass acts a container for
these data.EvaluationContext (Scope and others)While the data basis is stable, the context in which a condition is
evaluated might change during on evaluation run. The same condition can
have different evaluation results depending on e.g. in which scope it is
evaluated. Ascopeis a (json) path that references a specific
subtree of the edifact seed. For example one “Vorgang” (SG4 IDE) in
UTILMD could be a scope. If a condition is described asThere has to be exactly one xyz per Vorgang (SG4+IDE) Then fornVorgänge there arenscopes:one scope for each Vorgang (pathes refer to an edifact seed):$["Dokument"][0]["Nachricht"][0]["Vorgang"][0]$["Dokument"][0]["Nachricht"][0]["Vorgang"][1]…$["Dokument"][0]["Nachricht"][0]["Vorgang"][<n-1>]Each of the single vorgang scopes can have a different evaluation
result. Those results are relevant for the user when entering data,
probably based in a somehow Vorgang-centric manner.TheEvaluationContextclass is a container for the scope and
other information that are relevant for a single condition and a single
evaluation only but (other thanEvaluatableData) might change within
an otherwise stable message.ReleasingThe version number has to be changed insetup.cfgfile.ContributingYou are very welcome to contribute to this repository by opening a pull
request against the main branch.How to use this Repository on Your Machine / Local SetupPlease follow the instructions in ourPython Template Repository. |
ahbichtfunctionsclient | AHBicht Functions Python ClientThis repository contains a lightweight client for anAHBichtpowered backend by Hochfrequenz.
It does not duplicate the core AHBicht logic but provides aPackageResolverthat accesses a database (via a REST API) that storesPackageKeyConditionExpressionMappings.
The database is maintained by Hochfrequenz.Internally this client uses and requiresaiohttp.How to use the ClientInstall using pip:pipinstallahbichtfunctionsclientThen call itimportasynciofromahbicht.mapping_resultsimportPackageKeyConditionExpressionMapping,ConditionKeyConditionTextMappingfromahbichtfunctionsclientimportHochfrequenzPackageResolverfrommaus.edifactimportEdifactFormat,EdifactFormatVersionasyncdefretrieve_package_key_condition_expression_mapping():# for a documentation about the purpose of a package resolver, you should read the ahbicht docspackage_resolver=HochfrequenzPackageResolver(EdifactFormatVersion.FV2204,EdifactFormat.UTILMD)# the following data are just hardcoded to provide you a minimal working examplepackage_mapping=awaitpackage_resolver.get_condition_expression("10P")# this does an HTTP GET requestassertisinstance(package_mapping,PackageKeyConditionExpressionMapping)# the result is ahbicht compatibleasyncdefretrieve_condition_key_condition_text_mapping():condition_resolver=HochfrequenzPackageResolver(EdifactFormatVersion.FV2204,EdifactFormat.UTILMD)# the following data are just hardcoded to provide you a minimal working examplecondition_mapping=awaitcondition_resolver.get_condition_expression("56")# this does an HTTP GET requestassertisinstance(condition_mapping,ConditionKeyConditionTextMapping)# the result is ahbicht compatibleasyncdefminimal_working_example():awaitretrieve_condition_key_condition_text_mapping()awaitretrieve_package_key_condition_expression_mapping()loop=asyncio.get_event_loop()loop.run_until_complete(minimal_working_example())Production ReadinessThis AHBicht client has a 100% code coverage, is linted, statically type checked and PEP561 compatible.
It relies on a Hochfrequenz API which is, as of today (2022-03-17), free to use.
Hochfrequenz does not give any guarantees regarding the stability or uptime of the API.
Also at one point it might require authorization.How to use this Repository on Your Machine (for development)Please follow the instructions in ourPython Template Repository.
And for futher information, see theTox Repository.You can also check out ourMIG AHB Utility Stack (MAUS)andAHBichtrepositories.ContributeYou are very welcome to contribute to this template repository by opening a pull request against the main branch. |
ah-blackjack | Belhard ProjectsBlackJackSimpleblack jackgame in terminal.Install:pip3installah-blackjackExecute:bjothers- WallPapper Calculator
- Backet Of Water |
ahc | --------------------------------------------------------------ABOUT--------------------------------------------------------------Package for control apache/nginx virtual hosts, mysql/ftpusers, bind zones, apache clients certificates ondeveloper/production web-hosts. Tested onUbuntu/Debian Linux.Published under GNU GPL v.2.--------------------------------------------------------------##############################################################--------------------------------------------------------------INSTALLATION--------------------------------------------------------------Apache Host Control:--------------------------------------------------------------$ sudo -i# apt-get update && apt-get upgrade -y# apt-get install -y python-pip python-mysqldb python-flup git-core make python-pycurl# cd /usr/src/ && git clone https://github.com/gotlium/ahc.git# cd ahc/ && pip install -r requirements.txt && make installOR using pip:# sudo pip install ahcAfter installation, you can install system packages and firewall:# ahc -m install -s lamp# ahc -m install -s firewall--------------------------------------------------------------##############################################################--------------------------------------------------------------USAGE--------------------------------------------------------------Apache hosts:--------------------------------------------------------------# ahc -m install -s apache2_ssl# ahc -m test -s apache# ahc -m apache -t php -a example.com----------------------------------------------------------------------------------------------------------------------------Nginx hosts:--------------------------------------------------------------# ahc -m install -s nginx_ssl# ahc -m test -s nginx# ahc -m nginx -t php -a example.com----------------------------------------------------------------------------------------------------------------------------FTP accounts:--------------------------------------------------------------# ahc -m install -s ftp# ahc -m test -s ftp# ahc -m ftp -a example.com -u User -p Password----------------------------------------------------------------------------------------------------------------------------MySQL accounts:--------------------------------------------------------------# ahc -m install -s mysql# ahc -m test -s mysql# ahc -m mysql -a example.com -u User -p Password----------------------------------------------------------------------------------------------------------------------------Bind zone:--------------------------------------------------------------# ahc -m install -s bind# ahc -m test -s bind# ahc -m bind -a example.com -i 127.0.0.1----------------------------------------------------------------------------------------------------------------------------Git deployment:--------------------------------------------------------------# ahc -m test -s git# ahc -m git -a example.com# ahc -m git -d example.com----------------------------------------------------------------------------------------------------------------------------Git jail:--------------------------------------------------------------ahc -m test -s git_jailahc -m git_jail -a [email protected] -p 'TYPE KEY-STRING COMMENT'ahc -m git_jail -d [email protected] -m git_jail -lahc -m git_jail -i example.com -e templates -u [email protected] -m git_jail -i example.com -f templates -u mail@example.com----------------------------------------------------------------------------------------------------------------------------Project Protection--------------------------------------------------------------# ahc -m test -s crypt# ahc -m crypt -a mount# ahc -m crypt -a umount----------------------------------------------------------------------------------------------------------------------------iRedMail--------------------------------------------------------------# ahc -m install -s mail----------------------------------------------------------------------------------------------------------------------------Firewall:--------------------------------------------------------------# ahc -m install -s firewall# iptables -L -nor# cat /etc/init.d/rc.fw--------------------------------------------------------------##############################################################--------------------------------------------------------------EXAMPLES----------------------------------------------------------------------------------------------------------------------------Apache2--------------------------------------------------------------# ahc -m apache -t php -a hostname -o -x# ahc -m apache -t php -d hostname# ahc -m apache -t php -e hostname# ahc -m apache -t php -f hostname# ahc -m apache -t php -l----------------------------------------------------------------------------------------------------------------------------Nginx--------------------------------------------------------------# ahc -m nginx -t php -a hostname# ahc -m nginx -t php -d hostname# ahc -m nginx -t php -e hostname# ahc -m nginx -t php -f hostname----------------------------------------------------------------------------------------------------------------------------FTP--------------------------------------------------------------# ahc -m ftp -a hostname -u user -p password# ahc -m ftp -a hostname -u user -p random# ahc -m ftp -a hostname -u user -p password -f folder# ahc -m ftp -a hostname# ahc -m ftp -d hostname----------------------------------------------------------------------------------------------------------------------------MySQL--------------------------------------------------------------# ahc -m mysql -a hostname -u user -p password# ahc -m mysql -a hostname -u user -p random# ahc -m mysql -a hostname# ahc -m mysql -d hostname -u user----------------------------------------------------------------------------------------------------------------------------Bind9--------------------------------------------------------------# ahc -m bind -a hostname -i ip-address# ahc -m bind -d hostname----------------------------------------------------------------------------------------------------------------------------Backups--------------------------------------------------------------# ahc -m backup -b mysql# ahc -m backup -b site----------------------------------------------------------------------------------------------------------------------------Tests--------------------------------------------------------------# ahc -m test -s apache# ahc -m test -s nginx# ahc -m test -s ftp# ahc -m test -s mysql# ahc -m test -s bind# ahc -m test -s crypt# ahc -m test -s git# ahc -m test -s git_jail# ahc -m test -s sendmail# ahc -m test -s all----------------------------------------------------------------------------------------------------------------------------Certificates--------------------------------------------------------------# ahc -m certs -i example.com -a email-address# ahc -m certs -i example.com -d email-address# ahc -m certs -i example.com -l----------------------------------------------------------------------------------------------------------------------------OpenVPN--------------------------------------------------------------# ahc -m vpn -a client1# ahc -m vpn -d client1----------------------------------------------------------------------------------------------------------------------------Projects protection--------------------------------------------------------------# ahc -m crypt -a encrypt# ahc -m crypt -a mount# ahc -m crypt -a umount# ahc -m crypt -a decryptOR# ahc -m crypt -a e# ahc -m crypt -a m# ahc -m crypt -a u# ahc -m crypt -a d----------------------------------------------------------------------------------------------------------------------------Service Installing--------------------------------------------------------------# ahc -m install -s apache2_ssl# ahc -m install -s nginx_ssl# ahc -m install -s ftp# ahc -m install -s bind# ahc -m install -s mysql# ahc -m install -s firewall# ahc -m install -s nginx_proxy# ahc -m install -s certs -i example.com# ahc -m install -s lighttpd# ahc -m install -s sendmail# ahc -m install -s mail# ahc -m install -s shell# ahc -m install -s jira# ahc -m install -s confluence# ahc -m install -s web# ahc -m install -s vpn# ahc -m install -s dropbox# ahc -m install -s all--------------------------------------------------------------Ahc flags:--version - current version-h or --help - help sectionBind flags:-a = add zone-d = remove zone-i = ip-address for a specified zoneCerts flags:-a = add user-d = remove user-l = List of usersMySQL flags:-a = add [database] or [hostname]-d = remove database-u = username(optional)-p = password(optional)FTP flags:-a = add ftp account for hostname-d = remove ftp account(still working, when hostname is removed)-u = username (optional)-p = password (optional)-f = manual specified folder (optional)Note:Default "username" & "password" is equal to hostnameGit jail flags:-a - add user-p - ssh public key-d - delete user-l - user list-i - project name (domain name)-e - add access for directory in project-u - email address-f - remove access for directoryApache/Nginx flags:-t = type [php,python,django,ruby,ror]-a = add host-d = remove host-e = enable host-f = disable host-o = static optimization(optional)-x = enable host protection(optional)-l = list available websites-w = wsgi config for python OR django (nginx/uwsgi)-b = basic auth. params=user:password-v = VirtualEnv (available for python & django) |
ahccchatbot | This is modified chatterbot library. |
ahcm | ahcm apply mypatch /prj/fooahcm apply blah.txt foo.txt /prj/foo- Copy all files under directory mypatch over corresponding files in/prj/foo. Do the same for blah.txt and foo.txtIf file doesn't exist under target dir, it's NOT created.Also other simple but handy "dirty" CM operations are supported for those unmanaged situations. ;-) |
ahc-tools | These are tools to perform advanced reporting and role matching based on the
introspection results fromOpenStack Ironicprior to doing anRDO-Managerdeployment. This is based on theAHCconcept from theenovance edeployinstall method.UsageUsage documentation is currently provided as part of theRDO-Manager documentation |
ahd | Ad-Hoc DispatcherCreate ad-hoc macros to be dispatched within their own namespace.Table of contentsWhat does ahd do?Features & RoadmapPath ExpansionCross PlatformDynamic Execution & OrganizationRoadmapExample use casesWhy should I use ahd?Who is ahd for?Quick StartDependenciesInstallationFrom PyPiFrom SourceUsageRegisterUsing a Registered CommandListDocsConfigContact/ContributeGlossaryAdditional DocumentationThis readme will give you enough information to get up and running with ahd. If you are confused about terminology used then take a look at theglossary sectionof the docs. If you are looking for more in-depth documentation:Additional user and development/contribution documentation will be available athttps://ahd.readthedocs.io/en/latest/API documentation is available athttps://kieranwood.ca/ahdWhat does ahd do?ahd allows you to take annoying to remember commands and organize them into easy to re-use macros.Features & RoadmapPath ExpansionMacros can take full advantage of wildcards + regex to match directories.
For example if you wanted to delete all PDFs in all folders on the desktop you can usesudo ahd register no-pdfs "rm *.pdf" "~/Desktop/*".*nix and windows path adages are cross-platform. For example~is converted to%USERPROFILE%on windows,\paths are converted to/on *nix systems and vice-versa.Cross platformahd natively supports windows and any *nix systems (including Mac OS).Supports copy-paste cross platform configurations (assuming the same commands and file structure are on both)
For example if you want to write a command that git pulls in a folder called/developmenton your desktop using the *nix standard~/Desktop/development/*works on both *nix and windows.Dynamic Execution & OrganizationOne YAML file contains the configuration for all your macros instead of being all over the place.Macros can be updated manually (editing the YAML file), or simply re-registered.The defined Paths and commands can be overwritten on each use (seeoverridingfor details).RoadmapA full roadmap for each project version can be found here:https://github.com/Descent098/ahd/projectsExample use casesReally the possibilities are only limited to what you can type in your regular terminal, but here are some good examples:Update every git repo in a directoryOrganize your downloads folder by various filetypesMulti-stage project compilation/build in various directoriesWhy should I use ahd?The easiest way to understand why this project is useful is with an example. Let's say you want to write a simple script to take all the PDF's in a directory and put them in a.7zarchive and then remove them. Well all you need is this simple command7za a -t7z PDFs.7z *.pdf && rm *.pdf...Yeah, pretty awful to remember. Assuming we want to do this every so often let's make a script we can call. Currently with bash you need to drop the script inusr/bin(and try to remember what you called it), or add it to your bash/fish/zsh aliases (assuming you use the alias file, or.bashrcetc. if you don't), and on windows it's just not even worth it.Enter ahd, you can register a macro (lets call it zip-pdfs) using the same annoying command, in this casesudo ahd register zip-pdfs "7za a -t7z PDFs.7z *.pdf && rm *.pdf" ".". Now when we want to re-use this macro in the directory we're in you just typeahd zip-pdfs.If you forget the name there's a list command, and if you use a longer name there's bash autocomplete (fish and zsh support coming later).Who is ahd for?The primary audience is developers looking to speed up annoying workflows. However there are a number of other people it could benefit, such as:devops specialists; can use ahd to create a common set of macros across servers .dual booters; people who want one common config for multiple OS's.testers; if you need to execute multiple tests on various systems you can write one macro to run them all.etc; people who are sick of having a bunch of random scripts everywhere and want one config file for complex commands.Quick-startDependenciesPython 3.6+ (or is at least only tested and officially supported for 3.6+)pip for pythonInstallationOnce you have python3 and pip you have a few installation options.From PypiRunpip install ahdorsudo pip3 install ahd(need a network connection)From sourceClone this repo: (https://github.com/Descent098/ahd)Runpip install .orsudo pip3 install .in the root directory (one with setup.py)UsageUsage:ahd[-h][-v]ahdlist[-l]ahddocs[-a][-o]ahdconfig[-e][-iCONFIG_FILE_PATH]ahdregister<name>[<command>][<paths>]ahd<name>[<command>][<paths>][-d]Options:-h,--helpshowthishelpmessageandexit-v,--versionshowprogram'sversionnumberandexit-l,--longShowsallcommandsinconfigurationwithpathsandcommands-a,--apishowsthelocalAPIdocs-o,--offlineshowsthelocalUserdocsinsteadofliveones-e,--exportexportstheconfigurationfile-iCONFIG_FILE_PATH,--importCONFIG_FILE_PATHimportstheconfigurationfile-d,--detailsprintsthedetailsofacommandRegisterThe register command allows you to register a command to be used later on.Required Arguments:<name>; This is apositionalplaceholder value for the name of a command you are registering. Once the command is registered you can run it by usingahd <name>.<command>; This is apositionalplaceholder value for the macro you want to run when the command is used after being registered. For example if you wanted to delete all the PDF's in a directory the macro you would normally run isrm *.pdfand so you would doahd register <name> "rm *.pdf" <paths>.It is generally advised to use encapsulating quotes since this avoids argument parsing artifacts.<paths>; This is apositionalplaceholder value for the path(s) that you want the command to run the macro in by default. For example if you wanted to a command to execute a macro on the desktop when it's run you can doahd register <name> <command> "~/Desktop".It is generally advised to use encapsulating quotes since this avoids argument parsing artifacts. Additionally you can specify multiple directories through comma delimiting, for example:ahd register <name> <command> "~/Desktop, ~/Documents, ~/Pictures", or you can usepath expansionwhich will match directories through regex or wildcards. For example to run a command in all directorieswithinthe desktop you could doahd register <name> <command> "~/Desktop/*"or just use regex to match paths more explicitly for example to only include folders on the desktop that are numbers between 0-9 you could do:ahd register <name> <command> "~/Desktop/[0-9]".Using a Registered CommandYou can use a registered command by simply typingahd <name>, where<name>is whatever name you gave to the command.Optional Arguments:<command>; This is an optional positional argument that lets you overwrite the command, while retaining the registered paths. For example lets say you have a set of paths registered with a command that typically runsgit pullover the specified paths. You want to run a different command on the paths (lets say remove all the pdfs in the folder) You can do:ahd <name> "rm *.pdf"which will executerm *.pdfinstead ofgit pullon the defined paths.It is generally advised to use encapsulating quotes since this avoids argument parsing artifacts.<paths>; This is an optional positional argument that lets you overwrite the paths the command will run against. To retain the original command you must use a ".". So for example lets say you have a command registered that runsgit pullagainst~/Desktop/*, but now you want to rungit pullagainst~/Documents/*you can useahd <name> "." "~/Documents/*"and it will run the macro against~/Documents/*instead of~/Desktop/*It is generally advised to use encapsulating quotes since this avoids argument parsing artifacts. Additionally you can specify multiple directories through comma delimiting, for example:ahd register <name> <command> "~/Desktop, ~/Documents, ~/Pictures", or you can usepath expansionwhich will match directories through regex or wildcards. For example to run a command in all directorieswithinthe desktop you could doahd register <name> <command> "~/Desktop/*"or just use regex to match paths more explicitly for example to only include folders on the desktop that are numbers between 0-9 you could do:ahd register <name> <command> "~/Desktop/[0-9]".listThe list command shows a list of your current registered commands.Optional Arguments:-l or --long: Shows all commands in configuration with the registered paths and macros.docsThe docs command is designed to bring up documentation as needed, you can runahd docsto open the documentation site in the default browser.Optional Arguments:-a or --api: Used to serve local API documentation (Not yet implemented)-o or --offline: Used to serve local user documentation (Not yet implemented)configThis command is used for configuration management. It is recomended to useregisterto register/update commands. The config command is for managing configurations manually take a look at the documentation for details aboutmanual configuration.Optional Arguments:-e --export: Export the current configuration file (calledahdconfig.yml)-i --import: Import a configuration file; takes the path to the config file as an argumentContact/ContributeFor a full contribution guide, check thecontribution section of the documentation. Also be sure to check thefaqbefore submitting issues.For any additional questions please submit then through githubhere(much faster response), or my [email protected] 1.0.0; June 6th 2022The version was bumped to a major release because pre V0.5.0 configs have been fully deprecated, if you are using an old config see migration steps belowThere are 3 primary focuses for this release:Improve developer/contributor documentation and infrastructureAdd metadata to configs so you can review how you use ahdFinalize some features that make ahd more intuitive and simple to useFeatures:Added spell-check for suggestions when input is close to a valid commandAdded additional metadata to config file for each entry:updated: The datestamp when the command was updated (will update on re-registering)created: The datestamp when the command was created (will not update on re-registering)runs: The number of times a command has been runlast_run: The datestamp when the command was last run (initially "never")Added-dflag to display command detailsAdded command metadata for usage details like how many times it's been run and when it was added (access usingahd <command> -d)Also will provide details like the current config for a given command, similar toahd listbut for a single commandUpdated testing to run on a schedule for quicker bug awarenessUpdated testing for coverage of all modulesAllowed for globbing paths with filesfor example you can run a command over all files by extension in a path usingahd register <command name> "<command>" "/path/*.<extension>"Documentation:Added documentation about removing migration for preV0.5.0configurationsBug Fixes:Fixed errors in testing pipelineFixed bugs with initializing a config fileAdded missing reserved commands to autocompleteFixed bugs on *nix installs without bashFixed several bugs with escaping on *nix systemsMigrating old configs:in order to migrate old configs install ahd v0.5.0pip install --upgrade ahd==0.5.0then follow guide here (ignore step 1):Migrating from Pre v0.5.0 configs - Ad-Hoc Dispatcher (ahd.readthedocs.io)Once updated to new config reinstall latest version usingpip install --upgrade ahdV 0.5.0; August 22nd 2020Focus for this release was to make it easier to understand how to use and contribute to ahd, to convert from configparser to PyYaml and cleanup some left over errors in deepsource.Features:Replaced configparser withPyYaml; see migration notice in the docs for detailsDocumentation:Overhauled user documentation site for clarityRevamped READMEAdded GlossaryRevamped contribution guideAdded Code Style guideCleaned up wording surrounding what the project actually doesTransitioned from full roadmap project boards to per-release project boardsBug Fixes:Inability to build from sdist due to missing files; Thanks tothatchfor the fixFixed testing pipeline in github actionsV 0.4.0; February 10th 2020Focus for this release was breaking up command line parsing into more testable chunks.Features:All argument parsing is now based on discrete functionsAdded a list command to show your current available commandsDocumentation:Created API documentation site:https://kieranwood.ca/ahdV 0.3.0; February 6th 2020Focus for this release was on building sustainable development pipelines (logging, testing etc.), and making the project more reliable in edge cases and error handling.Features:Built out the testing suite to be run before releaseBuilt out the logging mechanism for debuggingIntroduced many error catches for various issues.Bug Fixes:Added config command to bash autocompleteV 0.2.1; February 2nd 2020Added support for . as current directory pathFixed issue with being unable to import configuration filesFixed issue with docs command when running --apiV 0.2.0; February 2nd 20202Focus was on improving the overall useability of ahd. Note this version breaks backwards compatibility, but includes a migration guide in the docs (to be removed in V0.3.0).Features:Bash Autocomplete implemented (ZSH and fish to come)Ability to export configurationAbility to import configurationAdded a top level "docs" command to easy access documentationAdded cross-platform wildcard support (see docs for usage)Added cross-platform home directory (see docs for details)Bug fixes:Fixed issue where running "register" command without any flags would error out instead of printing help infoFixed issue with relative path trackingDocumentation improvements:Added issue templates for bug reports and feature requestsAdded pull request templatesAdded contribution guideAdded migration informationAdded relevant documentation for all features released in V0.2.0V 0.1.0; January 28th 2020Initial release focused on creating the basic functionality for the ahd command.Features:Ability to register a commandAbility to specify command to runAbility to specify the location(s) to run the command in.Have commands store to a configuration file using configparser |
ahdcmotor | No description available on PyPI. |
ahdcreative-sphinx-theme | Sphinx AHD themeSphinx AHD theme contains all files required to build a Sphinx extension that provides the theme.MIT licenseRepositorySecurityChangelogSupports Python > 3.7Installationpipinstallsphinx-ahd-themeUsageSelect the "Sphinx AHD theme" in theconf.pyfile of a Sphinx# include the theme in the list of extensions to be loadedextensions=['sphinx_ahd_theme',…]# select the themehtml_theme='sphinx_ahd_theme'See the documentation for more usage instructionsDevelopmentGetting startedInstructions for Mac, Linux, and WindowsRelease processChecklist:CHANGELOG.mdis updatedsetup.cfgis updated (seeversion)Everything is committed, clean checkout~/.pypirchas a username and password (token)Add a git tag and a Github release once completedWith an active virtual environment:python-mpipinstall--upgrade-rrequirements.txt
makeclean
makeclean-frontend
npmci
npmrunbuild
prerelease
gittag-aN.N.N-m"N.N.N"gitpushoriginN.N.N
python-mbuild
python-mtwineupload--repositorypypidist/*
postreleaseCreditsSphinx AHD themeis based onSphinx Typo3 themewhich is based ont3SphinxThemeRtdwhich is based on theRead the Docs Sphinx theme. |
ah-distributions-gauss-binom | No description available on PyPI. |
ahdp | ahdp==================================ahdp is an ansible library of modules for integration with hadoop framework, it provides a way to interact with different hadoop services in a very simple and flexible way using ansible's easy syntax. The popse of this project is to provide DevOps and platform administrators a simple way to automate their operations on large scale hadoop clusters using ansible.Features---------------Currently ahdp provides modules to interact with HDFS through WEBHDFS or HTTPFS and with hive server 2 or impala using thrift.* Ansible libraries and utilities functions for HDFS operations :* create directories and files* change directories and files attributes and ownership* manage acls* manage extra attributes* fetch and copy files to HDFS* advanced search functionalities.* manage hdfs snapshots* The HDFS modules are based on [ pywhdfs ](https://github.com/yassineazzouz/pywhdfs) project to establish WebHDFS and HTTPFS connections with hdfs service.- Support both secure (Kerberos,Token) and insecure clusters- Supports HA clusters and handle namenode failover- Supports HDFS federation with multiple nameservices and mount points.* Please refer to the [ hdfs modules documentation ](webdocs/web/hdfs-modules-docs.md) for more details about all the supported modules* Ansible libraries and utilities functions for HIVE operations :* create and delete databases* Manage privileges on hive database objects.* The hive modules are based on [ impyla client ](https://github.com/cloudera/impyla) project to interact with HIVE Mmetastore:- Support for multiple types of authentication (Kerberos, LDAP, PLAIN, NOSASL)- Support for SSL- Works with both hive server 2 and impala daemons connections.* Please refer to the [ hive modules documentation ](webdocs/web/hive-modules-docs.md) for more details about all the supported modulesInstallation & Configuration---------------The ahdp module need to be installed on both the ansible server and on client machines (for instance the gateways that you will use as targets on the playbook). Normally simple ansible modules does not need to exist on target machines, however since the hdfs and hive modules uses a custom module_utils they need to be installed also on the target machine.To install ahdp on the ansible host :```pip install ahdp```or```pip install ahdp[ansible]```To install ahdp on the target hosts :```pip install ahdp[client]```The client extension will also install all dependencies that need to exist on target machines:* [ pywhdfs ](https://github.com/yassineazzouz/pywhdfs)* [ impyla client ](https://github.com/cloudera/impyla)* thrift_sasl* saslMake sure the following packages are also installed on the target machines :libffi-develgcc-c++python-develkrb5-develNote:To use ahdp modules you need to configure ansible to know where the modules are located, you need simply add the library configuration to your ~/.ansible.cfg or to /etc/ansible.cfg, for instance if you have python 2.7, the modules path will be :```library = /usr/lib/python2.7/site-packages/ahdp/modules/```You can also place manually the modules in a path of your choise then set the library option to that path.DependenciesUSAGE-------The best way to use ahdp is to run ansible playbooks and see it as work, there are some testcases under "test" directory, which can give a high level idea of how an ansible project should be structured around hadoop.Below a simple playbook that creates a User home directory in hdfs and a database in hive:```yml- hosts: localhostvars:nameservices:- urls: "http://localhost:50070"mounts: "/"hs2_host: "localhost"tasks:- name: Create HDFS user home directoryhdfsfile:authentication: "none"state: "directory"path: "/user/ansible"owner: "ansible"group: "supergroup"mode: "0700"nameservices: "{{nameservices | to_json}}"- name: Create User hive databasehive_db:authentication: "NOSASL"user: "hive"host: "{{hs2_host}}"port: 10000db: "ansible"owner: "ansible"state: "present"```To run the playbook, simply run:```ansible-playbook simple_test.yml```SOME GOOD PRACTICES--------The folowing project aim to make hadoop administration and operation easier using ansible, below some useful tips and gidelines on how to structure a hadoop project in ansible:* Create a separate inventory group for each hadoop cluster and create separate groups for different services and roles, If you are using a cloudera distribution you can also use dynamic inventory based the [ cloudera api ] ( tools/cloudera.py ).* Define a gateway or edge node for each cluster to use it as target in your ansible playbooks. Make sure the ahdp project and its dependencies are installed on all edge nodes, you can also configure [ pywhdfs ](https://github.com/yassineazzouz/pywhdfs) and use its cli to interact programatically with the HDFS service.* Create separate group variables for every cluster where you can define the connection parameters, for instance below a configuration example for a standalone hadoop installation :```cat group_vars/local/local.yml---nameservices:- urls: "http://localhost:50070"mounts: "/"hs2_host: "localhost"impala_daemon_host: "localhost"cloudera_manager_host: "localhost"```* Use ansible vault for passwords, create a separate vault file for every cluster.```ansible-vault view group_vars/local/local_encrypted.yml---hdfs_kerberos_password: "password"hdfs_principal: "hdfs@LOCALDOMAIN"hive_ldap_password: "password"```* Create ansible roles for different kind of operational tasks you perform on your platforms and use "--limit=NAME_OF_CLUSTER" to control the target cluster.Question or Ideas ?------------I'd love to hear what you think about ahdp and appreciate any idea or suggestion, Pull requests are also very welcome! |
ahds | ContentsOverviewLicenseUse CasesInstallationGetting StartedFuture PlansOverviewahdsis a Python package to parse and handle Amira (R) files.
It was developed to facilitate reading of Amira (R) files as part of theEMDB-SFF toolkit.NoteAmira (R) is a trademark of Thermo Fisher Scientific. This package is in no way affiliated with with Thermo Fisher Scientific.Licenseahdsis free software and is provided under the terms of the Apache License, Version 2.0.Copyright 2017 EMBL - European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific
language governing permissions and limitations under the License.Use CasesDetect and parse Amira (R) headers and return structured dataDecode data (HxRLEByte,HxZip)Easy extensibility to handle previously unencountered data streamsahdswas written and is maintained by Paul K. Korir but there isa list of contributors.
Feel free to join this initiative.Installationahdsworks with Python 2.7, 3.5, 3.6 and 3.7. It requiresnumpyto build.pip install numpyAfterwards you may runpip install ahdsNoteFigure out a way to avoid the need fornumpyas part of the build.Getting StartedYou can begin playing withahdsout of the box using the provided console commandahds.me@home~$ahdsahds/data/FieldOnTetraMesh.am********************************************************************************************************************************************AMIRA(R)HEADERANDDATASTREAMS--------------------------------------------------------------------------------------------------------------------------------------------+-ahds/data/FieldOnTetraMesh.amAmiraFile[is_parent?True]|+-metaBlock[is_parent?False]||+-file:ahds/data/FieldOnTetraMesh.am||+-header_length:182||+-data_streams:1||+-streams_loaded:False|+-headerAmiraHeader[is_parent?True]||+-filetype:AmiraMesh||+-dimension:3D||+-format:BINARY||+-endian:BIG||+-version:2.0||+-extra_format:None||+-ParametersBlock[is_parent?False]||+-TetrahedraBlock[is_parent?False]|||+-length:23685|+-data_streamsBlock[is_parent?False]********************************************************************************************************************************************Theahdscommand takes the following argumentsme@home~$ahds-husage:ahds[-h][-s][-d][-l]file[file...]PythontooltoreadanddisplayAmirafilespositionalarguments:fileavalidAmirafilewithanoptionalblockpathoptionalarguments:-h,--helpshowthishelpmessageandexit-s,--load-streamswhethertoloaddatastreamsornot[default:False]-d,--debugdisplaydebugginginformation[default:False]-l,--literaldisplaytheliteralheader[default:False]You can specify adotted pathafter the filename to only render that the content of that field in the header:me@home~$ahdsahds/data/FieldOnTetraMesh.amheader***********************************************************************************************************************************ahds:Displayingpath'header'-----------------------------------------------------------------------------------------------------------------------------------+-headerAmiraHeader[is_parent?True]|+-filetype:AmiraMesh|+-dimension:3D|+-format:BINARY|+-endian:BIG|+-version:2.0|+-extra_format:None|+-ParametersBlock[is_parent?False]|+-TetrahedraBlock[is_parent?False]||+-length:23685For debugging you can display the literal header (the exact header present in the file) using the-l/--literalflag.
Also, you can display the parsed data structure using the-d/--debugflag.me@home~$ahds--literal--debugahds/data/FieldOnTetraMesh.am***********************************************************************************************************************************ahds:Displayingliteralheader-----------------------------------------------------------------------------------------------------------------------------------# AmiraMesh 3D BINARY 2.0
# CreationDate: Tue Nov 2 11:46:31 2004nTetrahedra23685TetrahedronData{float[3]Data}@1Field{float[3]f}Constant(@1)# Data section follows***********************************************************************************************************************************ahds:Displayingparsedheaderdata-----------------------------------------------------------------------------------------------------------------------------------[{'designation':{'dimension':'3D','filetype':'AmiraMesh','format':'BINARY','version':'2.0'}},{'comment':{'date':'Tue Nov 2 11:46:31 2004'}},{'array_declarations':[{'array_dimension':23685,'array_name':'Tetrahedra'}]},{'data_definitions':[{'array_reference':'Tetrahedra','data_dimension':3,'data_index':1,'data_name':'Data','data_type':'float'},{'array_reference':'Field','data_dimension':3,'data_index':1,'data_name':'f','data_type':'float','interpolation_method':'Constant'}]}]********************************************************************************************************************************************AMIRA(R)HEADERANDDATASTREAMS--------------------------------------------------------------------------------------------------------------------------------------------+-ahds/data/FieldOnTetraMesh.amAmiraFile[is_parent?True]|+-metaBlock[is_parent?False]||+-file:ahds/data/FieldOnTetraMesh.am||+-header_length:182||+-data_streams:1||+-streams_loaded:False|+-headerAmiraHeader[is_parent?True]||+-filetype:AmiraMesh||+-dimension:3D||+-format:BINARY||+-endian:BIG||+-version:2.0||+-extra_format:None||+-ParametersBlock[is_parent?False]||+-TetrahedraBlock[is_parent?False]|||+-length:23685|+-data_streamsBlock[is_parent?False]********************************************************************************************************************************************By default, data streams are not read — only the header is parsed. You may obtain the data streams using the-s/--load-streamsflag.me@home~$ahds--load-streamsahds/data/FieldOnTetraMesh.am********************************************************************************************************************************************AMIRA(R)HEADERANDDATASTREAMS--------------------------------------------------------------------------------------------------------------------------------------------+-ahds/data/FieldOnTetraMesh.amAmiraFile[is_parent?True]|+-metaBlock[is_parent?False]||+-file:ahds/data/FieldOnTetraMesh.am||+-header_length:182||+-data_streams:1||+-streams_loaded:True|+-headerAmiraHeader[is_parent?True]||+-filetype:AmiraMesh||+-dimension:3D||+-format:BINARY||+-endian:BIG||+-version:2.0||+-extra_format:None||+-ParametersBlock[is_parent?False]||+-TetrahedraBlock[is_parent?False]|||+-length:23685|+-data_streamsBlock[is_parent?True]||+-DataAmiraMeshDataStream[is_parent?False]|||+-data_index:1|||+-dimension:3|||+-type:float|||+-interpolation_method:None|||+-shape:23685|||+-format:None|||+-data:[0.89173080.9711809300.],...,[1.43905041.1243758300.]********************************************************************************************************************************************Future PlansWrite out valid Amira (R) files |
ahead | A package for time series forecasting with Machine Learning and uncertainty quantification |
aheadworks-deploy-manager | deploy manager from aheadworks |
ahegao | AhegaoAPIWrapperEndpoints:ТУТЬ(Пока пусто)Установка:Используя pip:$ pip install ahegaoКак использовать:fromahegaoimportAhegaoAPI,APISessionses=APISession()api=AhegaoAPI(ses,v="api-version",p="part-of-api",token="your-token")user=api.users.get(user_id=1)# returns jsonprint(user) |
ahelper | No description available on PyPI. |
aheui | 알파희 - 알파희썬(rpython)으로 만든 엔터프라이즈급 고성능 아희====[](https://travis-ci.org/aheui/rpaheui)* English: [README.en.md](https://github.com/aheui/rpaheui/blob/master/README.en.md)* Working log (English): [LOG.md](https://github.com/aheui/rpaheui/blob/master/LOG.md)* 빌드 및 실행 영상: [Youtube](https://www.youtube.com/watch?v=mjoj69i_f8s)* 2015 한국 파이콘: [PyPy/RPython으로 20배 빨라지는 JIT 아희 인터프리터](http://www.slideshare.net/YunWonJeong/pypyrpython-20-jit)알파희썬(RPython)은 PyPy를 개발하기 위해 개발/사용된 python의 방언으로서 정적 언어로 컴파일되고 tracing-JIT를 지원하기 위한 라이브러리를 내장하고 있습니다.알파희썬으로 개발한 언어는 손쉽게 파이썬으로 실행하거나 바이너리로 빌드할 수 있고, JIT를 적용하기도 쉽습니다.이 프로젝트는 RPython으로 JIT 인터프리터를 개발하는 예제로 활용할 수 있습니다. 위의 링크에서 LOG.md를 확인해 더 알아보세요.* 파이썬이란?아직 파이썬을 모르세요? [알파희 개발자가 번역한 책](http://www.yes24.com/24/Goods/15240210?Acode=101)으로 파이썬을 공부해 봅시다.* 알파희썬이란?: [http://rpython.readthedocs.org][rpython]```git clone https://github.com/aheui/rpaheuimake # set RPYTHON in Makefile. You can get pypy by: hg clone http://bitbucket.org/pypy/pypy./aheui-c <your-aheui-code>```JIT로 속도 올리기----PyPy 기술은 PyPy를 CPython보다 빠르게 동작하게 만듭니다. ([http://speed.pypy.org/](http://speed.pypy.org/) 참고)알파희도 이 기술을 이용해 JIT로 빨라지고 있습니다. 벤치마크에 널리 쓰이는 로고 실행이 caheui보다 30배 이상 더 빠릅니다!```$ time ./rpaheui-c snippets/logo/logo.aheui > /dev/nullreal 0m0.915suser 0m0.640ssys 0m0.269s``````$ time ../caheui/aheui snippets/logo/logo.aheui > /dev/nullreal 0m26.026suser 0m25.970ssys 0m0.035s```실행 옵션----- 옵션을 제외한 첫 인자는 파일 이름입니다. 파일이름이 `-`면 표준 입력입니다.- --help,-h: 도움말- --version,-v: 버전- --opt,-O: 최적화 수준. 기본값은 `1`입니다. `0`과 `2` 사이의 정수를 쓸 수 있습니다.- 0: 최적화 없음.- 1: 간단한 스택크기 추정으로 빠르게 쓰이지 않는 코드를 제거하고 상수 연산을 병합합니다.- 2: 스택크기 추정으로 완벽하게 쓰이지 않는 코드를 제거하고, 코드 조각을 직렬화해 재배치하고, 상수 연산을 병합합니다.- usage: `--opt=0`, `-O1` or `-O 2`- --source,-S: 소스 유형. 기본 값은 `auto`입니다. `auto`, `bytecode`, `asm`, `text` 가운데 하나를 쓸 수 있습니다.- `auto`: 소스 유형을 추측합니다. 파일이름이 `.aheuic`이거나 바이트코드 종료 패턴이 담겨 있으면 `bytecode`로 추측합니다. 파일이름이 `.aheuis`이면 `asm`으로 추측합니다. 파일이름이 `.aheui`이면 `text`로 추정합니다. 추정할 수 없으면 `text`로 추정합니다.- `bytecode`: 아희 바이트코드. (`앟셈블리`의 바이트코드 표현형)- `asm`: `앟셈블리` 참고- usage: `--source=asm`, `-Sbytecode` or `-S text`- --target,-T: 결과물 유형. 기본값은 `run`입니다. `run`, `bytecode`, `asm` 가운데 하나를 쓸 수 있습니다.- `run`: 주어진 코드를 실행합니다.- `bytecode`: 아희 바이트코드. (`앟셈블리`의 바이트코드 표현형)- `asm`: `앟셈블리` 참고- usage: `--target=asm`, `-Tbytecode` or `-T run`- --output,-o: 결과물 파일. 기본값은 아래와 같습니다. 각 결과물 유형에 따라 자세한 내용을 확인하세요. `-`이면 표준 출력입니다.- --target=run: 이 옵션은 무시됩니다.- --target=bytecode: 기본 값은 `.aheuic` 파일입니다.- --target=asm: 기본 값은 `.aheuis` 파일입니다.- --cmd,-c: 코드를 파일 대신 문자열로 받아 넘겨줍니다.- --no-c: `.aheuic` 파일을 자동으로 생성하지않습니다.- `.aheuic` 파일은 왜 생성되나요?: [https://github.com/aheui/snippets/commit/cbb5a12e7cd2db771538ab28dfbc9ad1ada86f35](https://github.com/aheui/snippets/commit/cbb5a12e7cd2db771538ab28dfbc9ad1ada86f35)앟셈블리와 ahsembler----* 알림: `ahsembler`는 `./aheui-c --source=asm --output=-`와 같은 명령입니다.앟셈블러로 아희 코드를 컴파일해 직렬화 된 앟셈블리로 만드세요!아희 코드를 선형으로 디버그할 수 있습니다!원시 명령- halt: ㅎ- add: ㄷ- mul: ㄸ- sub: ㅌ- div: ㄴ- mod: ㄹ- pop: ㅁ without ㅇ/ㅎ- popnum: ㅁ with ㅇ- popchar: ㅁ with ㅎ- push $v: ㅂ without ㅇ/ㅎ. Push THE VALUE $v. $v is not an index of consonants.- pushnum: ㅂ with ㅇ- pushchar: ㅂ with ㅎ- dup: ㅃ- swap: ㅍ- sel $v: ㅅ. $v is always an integer order of final consonants.- mov $v: ㅆ. $v is always an integer order of final consonants.- cmp: ㅈ- brz $v: ㅊ. If a popped value is zero, program counter is set to $v; otherwise +1.확장 명령 (선형 코드는 위치 정보를 잃고 일부 명령이 스택 크기 점검을 하지 않으므로 추가 명령이 필요합니다)- brpop2 $v: If current stack doesn't have 2 values to pop, program counter is set to $v; otherwise +1.- brpop1 $v: If current stack doesn't have 1 values to pop, program counter is set to $v; otherwise +1.- jmp $v: Program counter is set to $v.사용법```git clone https://github.com/aheui/rpaheuipython ahsembler.py <your-aheui-code>```[rpython]: http://rpython.readthedocs.org |
ahfhalotools | AHFHaloToolsAHFHaloTools is a Python 3 library for the analysis of data produced by AMIGA's Halo Finder (AHF).FeaturesFile parsing for.AHF_halos,.AHF_profiles,.AHF_mtree(_idx)File truncationAnalysis of radial profile dataAnalysis of integral properties (halo data)Proper tracking of halos through timeMerger detectionAnalysis of enclosed halos as indicator of host halo kinematicsDependenciesNumPymatplotlibAstroPyInstallationpip install ahfhalotoolsDocumentationView HTML documentationhereDocumentation is also available in docstrings within the
code, which can be viewed using the built-inhelpfunction:>>>fromahfhalotools.objectsimportCluster>>>help(Cluster)HelponclassClusterinmoduleahfhalotools.objects:...The majority of analysis is enabled by theahfhalotools.objects.Clusterobject.ExamplesExample scripts are available in/examples. These scripts are provided without data, as the data files are large and can't go on GitHub. To run them on a local machine, data must be downloaded and truncated, and the paths to the data in the scripts should be updated to reflect the location of the files.
Alternatively the scripts could be deployed to popia/castor and run there, after updating the directory paths in the code. Data should still be truncated before running, otherwise the scripts will execute very slowly.AHF documentationFor information on AMIGA's Halo Finder, including documentation and output file formats, you can visit their websitehere.Gallery |
ah-fibonacci | ah_fibonaccitesting uploading a python package |
ahg48 | AHG 48 from Eiheiji. |
ahg-nester | No description available on PyPI. |
ahgregate | This package provides tools for aggregate pricing and risk analysis.Version Log0.1.0: Initial releasestrip code from rst doc filesDocumentationInstallationClone repo. Then, from the root directory, runpip install .LicenseMIT |
ahh | No description available on PyPI. |
ahhhhhhhh-cobalt | testtest |
ahi | Application Hacking InterfaceUsing the simple HTTPClientfromloggingimport*c=ahi.HTTPClient(cache_ttl=60,force_wait_interval=1,auto_adjust_for_rate_limiting=True,logging_level=DEBUG,proxy='http://127.0.0.1:8080',verify=True,allow_redirects=False,timeout=None)resp=c.get('http://example.com/')print(resp)Using the Selenium driver for Firefoxfromloggingimport*fromselenium.webdriver.common.keysimportKeysff=ahi.SeleniumFirefox(headless=True,force_wait_interval=timedelta(seconds=0),logging_level=DEBUG)ff.get('https://example.com/')ff.html.css('#LoginForm_Password').send_keys('P4$$w0rd')ff.html.css('#LoginForm_Password').send_keys(Keys.RETURN)ff.execute_script('''SetLocation('\x2Fdocs\x2FProMyPlanning.aspx?_Division_=549942',event, 0)''')ff.html.css('#Reports_Reports_Reports_MyPlanning').click()print(ff.html)Converting from a curl command linegirl--curlhttps://example.com/ |
ahio | ahioahio is a communication library whose goal
is to abstract the interfacing with various I/O hardwares, so that changing
hardware becomes possible with minimum code modification. It's desired that
an application that already works with an I/O hardware will only need pin
remapping and possibly initial setup change to work with another hardware, not
entire code rewrite.It works with drivers, which are installed in theahio.driverspackage. Every
driver must implement the API described in theahio.abstract_driverpackage.
If you plan to use this library or develop a driver, read the documentation
there.InstallationSimplest way is to use pip:pip3 install ahioAlternatively you can checkout this repository and runpython3 setup.py installBasic usage# Import the package:importahio# You can see what drivers are available in this platform by callingprint(ahio.list_available_drivers())# Instantiate the desired driverwithahio.new_driver('Arduino')asarduino:# The driver can have a driver-specific setup function. Call it as/if needed.arduino.setup('/dev/tty.usbmodem1421')# Map the pins. From now on, when you use 1 in the API, it will have effects# on pin D3 in the Arduino. If you change hardware in the future, just change# the mapping.arduino.map_pin(1,arduino.Pins.D3)arduino.map_pin(2,arduino.Pins.D13)arduino.map_pin(3,arduino.Pins.A1)# Change a pin direction (Input or Output)arduino.set_pin_direction([1,2],ahio.Direction.Output)arduino.set_pin_direction(3,ahio.Direction.Input)# Set the output of a pinarduino.write([1,2],ahio.LogicValue.High)arduino.write(1,0.4,pwm=True)# Read the input of a pinprint(arduino.read(3))DocumentationDocumentation is hosted atGitHub |
ahIOT | Package info in python/ |
ahip | This is a placeholder package to reserve the name for the hip project:https://github.com/python-trio/hipFor more details see:https://github.com/python-trio/hip/issues/168If you have any questions, please get in touch with us! |
ahjo | Ahjo FrameworkDescriptionAhjo is a database project framework and a deployment script. It is made to unify database project deployment and development practices and to give basic tooling for such projects.Ahjo provides a base scripts for database deployment with simple commands ("actions"), and the possibility to define custom actions for project's special needs. The scripts are designed to reduce accidental operations to production environments. The actions and their parts are logged by Ahjo.Database tooling is currently based on sqlalchemy/alembic and SQL scripts. Support for other backends than Microsoft SQL Server is currently limited.DependenciesCommonalembicpyparsingSQL AlchemyPyYAMLlarkPlatform-specificmssqlpyodbcazureazure-identityInstall GuideInstall Guide 1 - PyPIInstall Ahjo (without platform-specific dependencies) fromPython Package Indexwith the following command:pip install ahjoIn order to use Ahjo with the database engine of your choice, install platform-specific dependencies using available tags. For example, if you use Ahjo with Microsoft SQL Server, use tagmssqlto install required dependencies. See full list of available tags below.pip install ahjo[mssql]Install Guide 2 - Clone and installClone AhjoGet your clone command from the repository.Install with pipUse-eflag to install package in develop mode.cd .\ahjo
pip install [-e] .[mssql,azure]Available platform tagsmssql- Microsoft SQL Serverazure- Microsoft Azure SQL DatabaseInstall Guide 3 - MSI installation packageBuilding an MSI installation packageThis assumes you have cloned the source code repository and have it open in a shell.Create a new, empty build venv and install build requirements into it.Notice:at the time of writing this (10/2023),the latest stable cx_freeze version(6.15.10)does not support Python 3.12yet. As soon as new cx_freeze version with Python 3.12 support is released, it should be taken in to use.py -3.11 -m venv venv_msi_build
.\venv_msi_build\Scripts\Activate.ps1
pip install -r .\msi_build_requirements.txtNotice:the last command installs ahjo with the most common options. You may need to update msi_build_requirements.txt to suit your needs.Notice:if you make changes to the source code, you must install ahjo into build venv again to have those changes included in the next build. Editable pip install doesn't work here, so don't use it.With the build venv active, build the MSI package with the following command.python .\msi_build.py bdist_msiFind the built MSI installation package under (automatically created)distdirectory.Installing the MSI packageMSI installation package installs everything that is needed to execute ahjo shell commands including the required parts of the Python runtime setup. In other words, the target environment doesn't need to have Python installed and there is no need to create separate venvs for ahjo.Run the msi installer with the default settings it offersMake sure to start a new shell instance (e.g. Windows PowerShell) after the installationAfter a successful installation the following CLI commands are available in the shell:ahjoahjo-init-projectahjo-multi-project-buildahjo-upgradeahjo-scanahjo-install-git-hookahjo-configIf a new shell instance can't find the executables, ensure that installation path is included in the PATH enviroment variableProject InitializationCreate a new project by running the following command:ahjo-init-projectThis will start the project initialization command and you'll be asked to enter a name for your new project:This is Ahjo project initialization command.
Enter project name:Enter a name for your project and hit enter. Confirm, if project name and locations are correct.Enter project name: project_1
You are about to initialize a new project project_1 to location C:\projects
Are you sure you want to proceed?
[Y/N] (N): Y
confirmed
[2019-06-04 08:46:23] Ahjo - Creating new project project_1
Project C:\projects\project_1 created.Usage ExampleBefore running actions:Install Ahjo (see "Install Guide")Initialize project using ahjo-init-project (see "Project Initialization")Have your development database server running (SQL Server for the example)Fill database connection information to the config-fileTo create a database without objects, run the following command in the project root:ahjo init config_development.jsoncAfter the command, there should be a empty database at the server, as configured in config_development.jsonc. This step is usually run only once, and is not required if the database already exists in the server.After tables are defined using alembic (see alembic's documentation for creating new version scripts), the tables can be deployed using:ahjo deploy config_development.jsoncThis command also runs all the SQL scripts that are defined in directories database/functions, database/procedures and database/views.Conventionally scripts under database/data include row inserts for dimension tables, and database/testdata for mock data insertion scripts. To populate the dimension tables run:ahjo data config_development.jsoncTo run test SQL on top of mock data:ahjo testdata config_development.jsonc
ahjo test config_development.jsoncTo run all the previous commands at once, a single (multi-)action "complete-build" can be used:ahjo complete-build config_development.jsoncTo deploy your project to production you need a new config-file. In production environment actions like "downgrade" can be quite hazard. To exclude such actions set "allowed_actions" to a list:"allowed_actions": ["deploy", "data"]Now running "downgrade" is not possible using production configuration.ahjo downgrade config_production.jsonc
[2019-10-01 12:58:12] Starting to execute "downgrade"
Action downgrade is not permitted, allowed actions: deploy, data
------To add your own actions (f.e. for more complex testing), modify ahjo_actions.py.Script and argumentsahjo <action> <config_filename><config_filename>is not mandatory if the config path is defined in environment variableAHJO_CONFIG_PATH.
By default, confirmation is asked for actions that affect the database. Confirmation can be skipped with-nior--non-interactiveargument.
Depending on the configuration, the database credentials can be stored into files or be asked when needed, once per application run. The later option is recommended for production environments. The credential handling is shared with alembic with customenv.pyfile.Pre-defined actions include:init-configInitializes local configuration file. This file is intended to hold configurations that should not be versioned.initCreates the database. Database is created with modulecreate_db.py. Required configurations aretarget_database_name,target_server_hostnameandsql_port. For optional configurations, see config file cheat sheet below.structureCreates database structure, that is schemas, tables and constraints. Primary method runs all SQL files under directories./database/schemas,./database/tablesand./database/constraints. Alternate method runs SQL script./database/create_db_structure.sql. If structure can't be created with primary method (one of the listed directories does not exists etc.), alternate method is attempted.deployRuns alembic migrations, creates views, procedures and functions. First, runsalembic upgrade head. Second, creates functions, views and procedures by executing all SQL files under directories./database/functions,./database/viewsand./database/procedures. Third, attempts to update documented extended properties to database. Finally, updates current GIT version (git describe) to GIT version table.deploy-filesRunsalembic upgrade head, creates database objects by executing all SQL files listed in --files argument and updates current GIT version (git describe) to GIT version table.
Example usage:ahjo deploy-files .\config_development.jsonc --files ./database/procedures/dbo.procedure.sql ./database/functions/dbo.function.sql.dataRuns data insertion scripts. Runs all SQL files under./database/data.testdataInserts data for testing into database. Runs all SQL files under./database/data/testdata.complete-buildRuns actions init, deploy, data, testdata and test in order.dropDrops all views, procedures, functions, clr-procedures and assemblies that are listed in directory./database. Drops are executed with TRY-CATCH.drop-filesDrops database objects from locations that are listed in --files argument. Database objects can be views, procedures, functions or assemblies. Object type is read from --object_type argument. Acceptable --object_type parameters: view, procedure, function, assembly.
Example usage:ahjo drop-files .\config_development.jsonc --files ./database/procedures/dbo.procedure_1.sql ./database/procedures/dbo.procedure_2.sql --object_type procedure.downgradeReverts the database back to basic structure.
First, drops all views, procedures, functions, clr-procedures and assemblies that are listed in directory./database. Drops are executed with TRY-CATCH. Second, runsalembic downgrade base.versionPrints the alembic- and git-version currently in the database.
Alembic version is read fromalembic_version_table. GIT version is read fromgit_table.update-file-obj-propWrite objects and their extended properties (only SQL Server) to JSON files under./docsdirectory.
Documented schemas are listed inmetadata_allowed_schemas.update-db-obj-propUpdate documented extended properties (only SQL Server) from JSON files under./docsdirectory to database.
Updated schemas are listed inmetadata_allowed_schemas.testRuns tests and returns the results.
Runs all SQL scripts under./database/tests.scanScans files in the working directory or git staging area and searches for matches with search rules. Search results are printed to the console and logged to a file.ArgumentShorthandDescriptionRequiredDefault Value--search-rules-srList of rules used to search for matches. Currently it is only possible to search for Finnish Personal Identity Numbers (hetu) from files.Nohetu--filesList of file paths to scan. File paths are regular expressions.No^database/--stage-stScan files in git staging area instead of working directory.NoExamplesScan all files under database directory and git staging area:ahjo scan --files "^database/" --stageScan all files under project root:ahjo scan --files "^.*"Scan only employee.sql file under database/data directory:ahjo scan --files "^database/data/employee.sql$"Scan all .sql files under database/data and database/procedures directories:ahjo scan --files "^database/(data|procedures)/.*\.sql"Scan all files starting with dm. in database/data directory:ahjo scan --files "^database/data/dm\..*"Ignoring scan resultsTo filter out false positives, scan results can be ignored by adding them to theahjo_scan_ignore.yamlfile (in the project root directory).
The file is created automatically when the scan command is run for the first time.
The file should be in the following format:files:-file_path:database/data/example_1.sqlmatches:-match_pattern_1-match_pattern_2-file_path:database/data/example_2.sqlmatches:-match_pattern_3ListYou can view all available actions and their descriptions with commandahjo list.ahjo list
-------------------------------
List of available actions
-------------------------------
'assembly': (MSSQL) Drop and deploy CLR-procedures and assemblies.
'complete-build': (MSSQL) Run 'init', 'deploy', 'data', 'testdata' and 'test' actions.
.
.
.Config FileAhjo requires config file to be JSON, JSONC (JSON with comments) or YAML format. Ahjo configs are located inBACKENDsection of file.
Below is an example of config file (in both JSONC and YAML format) and a cheat sheet for config file parameters.JSONC config file{
"BACKEND": {
"allowed_actions": "ALL",
//Git repository and git version table information
"url_of_remote_git_repository": "https:\\\\github.com\\user\\projectx\\",
"git_table": "git_version",
"git_table_schema": "dbo",
//Database connection information
"sql_port": 1433,
"sql_driver": "ODBC Driver 17 for SQL Server",
"target_database_name": "PROJECTX",
"target_server_hostname": "localhost",
// Database file location
"database_data_path": "/var/opt/mssql/data/PROJECTX.mdf",
"database_log_path": "/var/opt/mssql/data/PROJECTX.ldf",
//Alembic
//the table that alembic creates automatically for migration version handling
"alembic_version_table": "alembic_version",
"alembic_version_table_schema": "dbo",
}
}YAML config fileBACKEND:## List of allowed Ahjo actions. If all actions are allowed use "ALL" option.allowed_actions:ALL## Git repository url and git version table information.url_of_remote_git_repository:''git_table:git_versiongit_table_schema:dbo## Database connection information.sql_port:14330sql_driver:ODBC Driver 17 for SQL Serversql_dialect:mssql+pyodbctarget_server_hostname:localhosttarget_database_name:DB_NAMEConfig file cheat sheetParameterRequiredDescriptionTypeDefault Valuealembic_version_tableNoName of Alembic version table. Table holds the current revision number.str"alembic_version"alembic_version_table_schemaNoSchema of Alembic version table.str"dbo"allowed_actionsYesList of actions Ahjo is allowed to execute. If all actions are allowed, use"ALL".str or list of strskipped_actionsNoList of actions that are skipped.list of str[]azure_authenticationNoAuthentication type to Azure AD. Possible values are"ActiveDirectoryPassword","ActiveDirectoryInteractive","ActiveDirectoryIntegrated"and"AzureIdentity".strazure_identity_settingsNoA dictionary containing parameters for azure-identity library (used only if azure_authentication is"AzureIdentity"). Dictionary holds a key:"token_url"(str). Note: currently ahjo supports only AzureCliCredential authentication method.dictdatabase_collationNoCollation of database. If the defined collation is different from the database collation, a warning is logged.str"Latin1_General_CS_AS"database_compatibility_levelNoCompatibility level of database.intDepends on server. SQL Server 2017 default is140.database_data_pathNoPath of database data file.strdatabase_file_growthNoThe size (MB) of how much database data file will grow when it runs out of space.int500database_init_sizeNoInitial size (MB) of database data file.int100database_log_pathNoPath of database log file.strdatabase_max_sizeNoMaximum size (MB) of database data file.int10000git_tableNoName of git hash table. Table holds current branch, commit hash and URL of remote repository.str"git_version"git_table_schemaNoSchema of git hash table.str"dbo"metadata_allowed_schemasNoList of schemas that extended properties will be written to JSON files and updated to database. If list left empty, nothing is documented or updated.list of strpassword_fileNoPath of file where password will be stored. If no path given, credentials are asked everytime any database altering action is run.strsql_dialectNoDialect used by SQL Alchemy.str"mssql+pyodbc"sql_driverNoName of ODBC driver.strsql_portYesPort number of target database server.inttarget_database_nameYesName of target database.strtarget_server_hostnameYesHost name of target database server.strurl_of_remote_git_repositoryNoURL of project's remote repository.strusername_fileNoPath of file where username will be stored. If no path given, credentials are asked everytime any database altering action is run.strdb_permissionsNoList of dictionaries containing file locations & scripting variables for setting up database permissions from sql file(s). Dictionary holds keys: "source" (str) and "variables" (dict).listofdictdb_permission_invoke_methodNoInvoke method for setting up database permissions. Available options:"sqlcmd"or"sqlalchemy"(default).str"sqlalchemy"upgrade_actions_fileNoConfiguration file for upgrade actions.str"./upgrade_actions.jsonc"catalog_collation_type_descNoCatalog collation setting of database. If the defined setting is different from the database setting, a warning is logged. Applies only to Azure SQL Databasestr"DATABASE_DEFAULT"display_db_infoNoPrint database collation information to console before running actions.booleantruecontext_connectable_typeNoType of SQLAlchmey object returned by Context.get_connectable(). Possible values are"engine"and"connection".str"engine"transaction_modeNoTransaction management style for ahjo actions. Applied only if context_connectable_type is"connection". Possible values are"begin_once"and"commit_as_you_go". If"begin_once", a transaction is started before running actions and committed after all actions are run. If"commit_as_you_go", a transaction is started before running actions but not committed automatically.str"begin_once"git_version_info_pathNoPath to git version info file. Retrieve git commit information from this file if git repository is not available. JSON file format:{"repository": "<url>", "commit": "<commit hash>", "branch": "<branch name>"}strwindows_event_logNoLog Ahjo events to Windows Event Log.booleanfalseahjo_action_filesNoDefines the location and name of project-specific Ahjo actions files.list of dictsqlalchemy.urlNoSQLAlchemy database URL. If defined, overrides the values ofdialect,sql_port,sql_driver,target_server_hostnameandtarget_database_name.strsqlalchemy.*NoItems under sqlalchemy.* are passed as parameters to SQLAlchemy'screate_enginefunction. For examplesqlalchemy.pool_size: 10is passed as pool_size=10 tocreate_enginefunction.dictIfdialectismssql+pyodbc:"sqlalchemy.use_insertmanyvalues": false,"sqlalchemy.use_setinputsizes": falsesqla_url_query_mapNoA dictionary containingSQLAlchemy URL query connection parameters.dictIf ODBC Driver 18:{"Encrypt" : "yes", "LongAsMax": "Yes"}. If ODBC Driver 17 or older:{"Encrypt" : "no"}. Else:{}Config conversionConfig file can be converted from JSON/JSONC to YAML or vice versa withahjo-configcommand:ahjo-config --convert-to <target_format> --config <config_file_path> --output <output_file_path>Using Alembic with AhjoAlembic upgrade HEAD is used in deploy action, but for many use cases other alembic commands are needed. For these needs Ahjo comes with aenv.pyfile that enables running Alembic commands without running Ahjo.The env.py modifications provide logging integration to Ahjo, default naming schema and possibility to run alembic according to project configuration. The engines are created according to configuration, and there is no need for storing plain-text connection strings in the project.Usage example:alembic -x main_config=config_development.jsonc downgrade -1Theenv.pyis created in initialize-project command.Authentication with azure-identityInstructions for enabling azure identity authentication in ahjo:InstallAzure CLI&azure-identitySet the config variableazure_authenticationtoAzureIdentitySign in interactively through your browser with theaz logincommand.
If the login is successful, ahjo will use Azure credentials for creating an engine that connects to an Azure SQL database.Running actions from multiple projectsTo run all selected actions from different projects at once, a single command "ahjo-multi-project-build" can be used:ahjo-multi-project-build path/to/config_file.jsoncUse-cor--confirmflag to enable confirmation messages for ahjo actions.Below is an example of JSONC config file. With the following definition, multi-project-build command executes complete-build actions of three ahjo projects:{"projects_path":"path/to/projects_folder","connection_info":{"sql_port":14330,"sql_driver":"ODBC Driver 17 for SQL Server","target_server_hostname":"localhost"},"projects":{"ahjo_project_1_name":{"config":"path/to/projects_folder/ahjo_project_1_name/config_development.jsonc","actions":["complete-build"]},"ahjo_project_2_name":{"config":"path/to/projects_folder/ahjo_project_2_name/config_development.jsonc","actions":["complete-build"]},"ahjo_project_3_name":{"config":"path/to/projects_folder/ahjo_project_3_name/config_development.jsonc","actions":["complete-build"]}}}Settings underconnection_infocontains database server definitions in the same format as in ahjo project config file (excludingtarget_database_nameparameter, which is not used here).Currently in this version ahjo projects should be located under the folder specified inprojects_pathsetting.Ahjo project names are listed underprojectssection in run order. In this example, the actions of projectahjo_project_1_nameare executed first and the actions of projectahjo_project_3_nameare executed last.The following settings are defined under the name of the ahjo project(s):config- File path to the project-specific config fileactions- List of project actions to be executedAhjo project upgradeDatabase updates can be run withahjo-upgradecommand. The command detects automatically the latest installed git version and runs the required database version updates (in order).
The upgrade actions are defined in a JSONC file and its location is defined inupgrade_actions_filesetting in project config file.
The ahjo actions required for version upgrades are defined with key-value pairs, where key is the git version tag and value is a list of actions.
The list of actions can contain strings of action names or lists of action names and action parameters.
If the action is defined with parameters, the action name is the first item in the list and the parameters are defined as a dictionary in the second item in the list.
The dictionary contains the parameters of the action as key-value pairs, where key is the parameter name and value is the parameter value.Below is an example of upgrade actions file:{"v3.0.0":["deploy","data"],"v3.1.0":["deploy",["deploy-files",{"files":["./database/procedures/dbo.procedure_1.sql","./database/procedures/dbo.procedure_2.sql"]}]],"v3.1.1":["deploy"]}To upgrade specific version, use-vor--versionflag:ahjo-upgrade -v v3.1.0Scan pre-commit hookAhjo scan command can be used as a pre-commit hook to prevent committing files that contain sensitive information (e.g. personal identity numbers) to the repository.
This can be accomplished by utilizing a Git pre-commit hook script that automatically executes ahjo-scan command on each commit and prevents the commit if the scan finds matches with the defined search rules.
Currently the scan pre-commit hook searches for Finnish Personal Identity Numbers (hetu) from staged files under the project root directory. Later on, the search rules can be extended to cover other use cases as well.
To use the hook, you need to have theahjo-scan.exeaccessible as a shell command. (e.g. the tool is installed from an MSI package, see Installation Guide 3).Setting up the hookTo install the hook, run the following command in the project root directory:ahjo-install-git-hookThe script creates a file namedpre-committo Git hooks directory. By default, Git hooks are located in the.git/hooksdirectory of the repository. This can be changed by setting thecore.hooksPathconfiguration variable to the desired path. SeeGit documentationfor more information.LoggingAhjo's logging is very inclusive. Everything Ahjo prints to console, is also written into log file ahjo.log. Logging can be done to Windows Event Log by settingwindows_event_logtotruein config file. This feature can be utilized for Azure Monitor activities, for example.CustomizationSetting up custom action filesEvery default Ahjo action and multiaction can be overwritten in project's Ahjo actions file. By default, the file is located inahjo_actions.py, but the location can be changed in config file with keyahjo_action_files. It is possible to define multiple Ahjo actions files. This can be useful for example when you want to use different actions for different environments or separate actions that are compatible with MSI-installed ahjo from actions that are compatible with pip-installed ahjo. The action files are loaded in order, so if you define multiple actions for the same action name, the last loaded action file will be used. If a multi-action uses actions from different files, remember to load all the subactions before the multi-action. Here is an example ofahjo_action_filesconfiguration:"ahjo_action_files": [
{
"source_file": "ahjo_prod_actions.py", // The location is relative to project root directory.
"name": "Example project Ahjo actions (prod)" // Name is used in logging.
},
{
"source_file": "ahjo_dev_actions.py",
"name": "Example project Ahjo actions (dev)"
}
]Overwriting default Ahjo actionsIn example below,'init'and'complete-build'actions are overwritten.importahjo.operationsasopfromahjo.actionimportaction,create_multiaction@action(affects_database=True)defstructure(context):"""New structure action."""frommodelsimportBaseBase.metadata.create_all(context.get_engine())# overwrite Ahjo complete-buildcreate_multiaction("complete-build",["init","structure","deploy","data","test"])LicenseCopyright 2019 - 2023 ALM Partners OyLicensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. |
ahk | ahkA fully typed Python wrapper around AutoHotkey.Installationpip install ahkRequires Python 3.8+Supports AutoHotkey v1 and v2. See also:Non-Python dependenciesUsagefromahkimportAHKahk=AHK()ahk.mouse_move(x=100,y=100,blocking=True)# Blocks until mouse finishes moving (the default)ahk.mouse_move(x=150,y=150,speed=10,blocking=True)# Moves the mouse to x, y taking 'speed' seconds to moveprint(ahk.mouse_position)# (150, 150)ExamplesNon-exhaustive examples of some functions available with this package. See thefull documentationfor complete API references and additional features.HotkeysHotkeys can be configured to run python functions as callbacks.For example:fromahkimportAHKdefmy_callback():print('Hello callback!')ahk=AHK()# when WIN + n is pressed, fire `my_callback`ahk.add_hotkey('#n',callback=my_callback)ahk.start_hotkeys()# start the hotkey process threadahk.block_forever()# not strictly needed in all scripts -- stops the script from exiting; sleep foreverNow whenever you press+n, themy_callbackcallback function will be called in a background thread.You can also add an exception handler for your callback:fromahkimportAHKahk=AHK()defgo_boom():raiseException('boom!')defmy_ex_handler(hotkey:str,exception:Exception):print('exception with callback for hotkey',hotkey,'Here was the error:',exception)ahk.add_hotkey('#n',callback=go_boom,ex_handler=my_ex_handler)There are also methods for removing hotkeys:# ...ahk.remove_hotkey('#n')# remove a hotkey by its keynameahk.clear_hotkeys()# remove all hotkeysNote that:Hotkeys run in a separate process that must be started manually (withahk.start_hotkeys())Hotkeys can be stopped withahk.stop_hotkeys()(will not stop actively running callbacks)Hotstrings (discussed below) share the same process with hotkeys and are started/stopped in the same mannerIf hotkeys or hotstrings are added or removed while the process is running, the underlying AHK process is restarted automaticallySee also therelevant AHK documentationHotstringsHotstringscan also be added to the hotkey process thread.In addition to Hotstrings supporting normal AHK string replacements, you can also provide Python callbacks (with optional exception handlers) in response to hotstrings triggering.fromahkimportAHKahk=AHK()defmy_callback():print('hello callback!')ahk.add_hotstring('btw','by the way')# string replacementsahk.add_hotstring('btw',my_callback)# call python function in response to the hotstringYou can also remove hotstrings:ahk.remove_hotstring('btw')# remove a hotstring by its trigger sequenceahk.clear_hotstrings()# remove all registered hotstringsMousefromahkimportAHKahk=AHK()ahk.mouse_position# Returns a tuple of mouse coordinates (x, y) (relative to active window)ahk.get_mouse_position(coord_mode='Screen')# get coordinates relative to the screenahk.mouse_move(100,100,speed=10,relative=True)# Moves the mouse reletave to the current positionahk.mouse_position=(100,100)# Moves the mouse instantly to absolute screen positionahk.click()# Click the primary mouse buttonahk.click(200,200)# Moves the mouse to a particular position and clicks (relative to active window)ahk.click(100,200,coord_mode='Screen')# click relative to the screen instead of active windowahk.click(button='R',click_count=2)# Clicks the right mouse button twiceahk.right_click()# Clicks the secondary mouse buttonahk.mouse_drag(100,100,relative=True)# Holds down primary button and moves the mouseKeyboardfromahkimportAHKahk=AHK()ahk.type('hello, world!')# Send keys, as if typed (performs string escapes for you)ahk.send_input('Hello, {U+1F30E}{!}')# Like AHK SendInput# Unlike `type`, control sequences must be escaped manually.# For example the characters `!^+#=` and braces (`{` `}`) must be escaped manually.ahk.key_state('Control')# Return True or False based on whether Control key is pressed downahk.key_state('CapsLock',mode='T')# Check toggle state of a key (like for NumLock, CapsLock, etc)ahk.key_press('a')# Press and release a keyahk.key_down('Control')# Press down (but do not release) Control keyahk.key_up('Control')# Release the keyahk.set_capslock_state("On")# Turn CapsLock onahk.key_wait('a',timeout=3)# Wait up to 3 seconds for the "a" key to be pressed. NOTE: This throws# a TimeoutError if the key isn't pressed within the timeout windowWindowsYou can do stuff with windows, too.Getting windowsfromahkimportAHKahk=AHK()win=ahk.active_window# Get the active windowwin=ahk.win_get(title='Untitled - Notepad')# by titleall_windows=ahk.list_windows()# list of all windowswin=ahk.win_get_from_mouse_position()# the window under the mouse cursorwin=ahk.win_get(title='ahk_pid 20366')# get window from pid# Wait for a windowtry:# wait up to 5 seconds for notepadwin=ahk.win_wait(title='Untitled - Notepad',timeout=5)# see also: win_wait_active, win_wait_not_activeexceptTimeoutError:print('Notepad was not found!')Working with windowsfromahkimportAHKahk=AHK()ahk.run_script('Run Notepad')# Open notepadwin=ahk.find_window(title='Untitled - Notepad')# Find the opened windowwin.send('hello')# Send keys directly to the window (does not need focus!)win.move(x=200,y=300,width=500,height=800)win.activate()# Give the window focuswin.close()# Close the windowwin.hide()# Hide the windwowwin.kill()# Kill the windowwin.maximize()# Maximize the windowwin.minimize()# Minimize the windowwin.restore()# Restore the windowwin.show()# Show the windowwin.disable()# Make the window non-interactablewin.enable()# Enable it againwin.to_top()# Move the window on top of other windowswin.to_bottom()# Move the window to the bottom of the other windowswin.always_on_top='On'# Make the window always on top# orwin.set_always_on_top('On')forwindowinahk.list_windows():print(window.title)# Some more attributesprint(window.text)# window text -- or .get_text()print(window.get_position())# (x, y, width, height)print(window.id)# the ahk_id of the windowprint(window.pid)# process ID -- or .get_pid()print(window.process_path)# or .get_process_path()ifwin.active:# or win.is_active()...ifwin.exist:# or win.exists()...ScreenfromahkimportAHKahk=AHK()ahk.image_search('C:\\path\\to\\image.jpg')# Find an image on screen# Find an image within a boundary on screenahk.image_search('C:\\path\\to\\image.jpg',upper_bound=(100,100),# upper-left corner of search arealower_bound=(400,400))# lower-right corner of search areaahk.pixel_get_color(100,100)# Get color of pixel located at coords (100, 100)ahk.pixel_search(color='0x9d6346',search_region_start=(0,0),search_region_end=(500,500))# Get coords of the first pixel with specified colorClipboardGet/setClipboarddatafromahkimportAHKahk=AHK()ahk.set_clipboard('hello\N{EARTH GLOBE AMERICAS}')# set clipboard text contentsahk.get_clipboard()# get clipboard text contents# 'hello 🌎'You may also get/setClipboardAll-- however, you should never try to callset_clipboard_allwith any other
data than asexactlyas returned byget_clipboard_allor unexpected problems may occur.fromahkimportAHKahk=AHK()# save all clipboard contents in all formatssaved_clipboard=ahk.get_clipboard_all()ahk.set_clipboard('something else')...ahk.set_clipboard_all(saved_clipboard)# restore saved content from earlierSoundfromahkimportAHKahk=AHK()ahk.sound_play('C:\\path\\to\\sound.wav')# Play an audio fileahk.sound_beep(frequency=440,duration=1000)# Play a beep for 1 second (duration in microseconds)ahk.get_volume(device_number=1)# Get volume of a deviceahk.set_volume(50,device_number=1)# Set volume of a deviceahk.sound_get(device_number=1,component_type='MASTER',control_type='VOLUME')# Get sound device propertyahk.sound_set(50,device_number=1,component_type='MASTER',control_type='VOLUME')# Set sound device propertyGUITooltips/traytipsimporttimefromahkimportAHKahk=AHK()ahk.show_tooltip("hello4",x=10,y=10)time.sleep(2)ahk.hide_tooltip()# hide the tooltipahk.show_info_traytip("Info","It's also info",silent=False,blocking=True)# Default info traytipahk.show_warning_traytip("Warning","It's a warning")# Warning traytipahk.show_error_traytip("Error","It's an error")# Error trytipDialog boxesfromahkimportAHK,MsgBoxButtonsahk=AHK()ahk.msg_box(text='Do you like message boxes?',title='My Title',buttons=MsgBoxButtons.YES_NO)ahk.input_box(prompt='Password',title='Enter your password',hide=True)ahk.file_select_box(title='Select one or more mp3 files',multi=True,filter='*.mp3',file_must_exist=True)ahk.folder_select_box(prompt='Select a folder')Global state changesYou can change various global states such asCoordMode,DetectHiddenWindows, etc. so you don't have to pass
these parameters directly to function callsfromahkimportAHKahk=AHK()ahk.set_coord_mode('Mouse','Screen')# set default Mouse CoordMode to be relative to Screenahk.set_detect_hidden_windows(True)# Turn on detect hidden windows by defaultahk.set_send_level(5)# Change send https://www.autohotkey.com/docs/v1/lib/SendLevel.htmahk.set_title_match_mode('Slow')# change title match speed and/or modeahk.set_title_match_mode('RegEx')ahk.set_title_match_mode(('RegEx','Slow'))# or both at the same timeAdd directivesYou can add directives that will be added to all generated scripts.
For example, to prevent the AHK trayicon from appearing, you can add the NoTrayIcon directive.fromahkimportAHKfromahk.directivesimportNoTrayIconahk=AHK(directives=[NoTrayIcon])By default, some directives are automatically added to ensure functionality and are merged with any user-provided directives.Directives are not applied for the AHK process used for handling hotkeys and hotstrings (discussed below) by default. To apply a directive
to the hotkeys process using the keyword argumentapply_to_hotkeys_process=True:fromahkimportAHKfromahk.directivesimportNoTrayIcondirectives=[NoTrayIcon(apply_to_hotkeys_process=True)]ahk=AHK(directives=directives)Menu tray iconAs discussed above, you can hide the tray icon if you wish. Additionally, there are some methods available for
customizing the tray icon.fromahkimportAHKahk=AHK()# change the tray icon (in this case, using a builtin system icon)ahk.menu_tray_icon('Shell32.dll',174)# revert it back to the original:ahk.menu_tray_icon()# change the tooltip that shows up when hovering the mouse over the tray iconahk.menu_tray_tooltip('My Program Name')# Show the tray icon that was previously hidden by ``NoTrayIcon``ahk.menu_tray_icon_show()Registry methodsYou can read/write/delete registry keys:fromahkimportAHKahk=AHK()ahk.reg_write('REG_SZ',r'HKEY_CURRENT_USER\SOFTWARE\my-software',value='test')ahk.reg_write('REG_SZ',r'HKEY_CURRENT_USER\SOFTWARE\my-software',value_name='foo',value='bar')ahk.reg_read(r'HKEY_CURRENT_USER\SOFTWARE\my-software')# 'test'ahk.reg_delete(r'HKEY_CURRENT_USER\SOFTWARE\my-software')If a key does not exist or some other problem occurs, an exception is raised.non-blocking modesMost methods in this library supply a non-blocking interface, so your Python scripts can continue executing while
your AHK scripts run.By default, all calls areblocking-- each function will execute completely before the next function is ran.However, sometimes you may want to run other code while AHK executes some code. When theblockingkeyword
argument is supplied withFalse, function calls will return immediately while the AHK function is carried out
in the background.As an example, you can move the mouse slowly and report its position as it moves:importtimefromahkimportAHKahk=AHK()ahk.mouse_position=(200,200)# Moves the mouse instantly to the start positionstart=time.time()# move the mouse very slowlyahk.mouse_move(x=100,y=100,speed=30,blocking=False)# This code begins executing right away, even though the mouse is still movingwhileTrue:t=round(time.time()-start,4)position=ahk.mouse_positionprint(t,position)# report mouse position while it movesifposition==(100,100):breakWhen you specifyblocking=Falseyou will always receive a specialFutureResultobject (orAsyncFutureResultobject in the async API, discussed below)
which allows you to wait on the function to complete and retrieve return value through aget_resultfunction. Even
when a function normally returnsNone, this can be useful to ensure AHK has finished executing the function.nonblocking calls:Are isolated in a new AHK process that will terminate after the call is completeAlways start immediatelyDo not inherit previous global state changes (e.g., fromset_coord_modecalls or similar) -- this may change in a future version.will not block other calls from startingwill always return a specialFutureResultobject (orAsyncFutureResultobject in the async API, discussed below)
which allows you to wait on the function to complete and retrieve return value through theresultfunction. Even
when a function normally returnsNone, this can be useful to ensure AHK has finished executing the function.fromahkimportAHKahk=AHK()future_result=ahk.mouse_move(100,100,speed=40,blocking=False)...# wait on the mouse_move to finishfuture_result.result(timeout=10)# timeout keyword is optionalAsync API (asyncio)An async API is provided so functions can be called usingasync/await.
All the same methods from the synchronous API are available in the async API.fromahkimportAsyncAHKimportasyncioahk=AsyncAHK()asyncdefmain():awaitahk.mouse_move(100,100)x,y=awaitahk.get_mouse_position()print(x,y)asyncio.run(main())The async API is identical to that of the normal API, with a few notable differences:While properties (like.mouse_positionor.titlefor windows) can beawaited,
additional methods (likeget_mouse_position()andget_title()) have been added for a more intuitive API and
are recommended over the use of properties.Propertysetters(e.g.,ahk.mouse_postion = (200, 200)) are not allowed in the async API (a RunTimeError is raised).
Property setters remain available in the sync API.AsyncFutureResultobjects (returned when specifyingblocking=False) work the same as theFutureResultobjects in the sync API, except thetimeoutkeyword is not supported for theresultmethod).Note also that:by default, awaited tasks on a singleAsyncAHKinstance will not run concurrently. You must either
useblocking=False, as in the sync API, or use multiple instances ofAsyncAHK.There is no difference in working with hotkeys (and their callbacks) in the async vs sync API.type-hints and mypyThis library is fully type-hinted, allowing you to leverage tools likemypyto help validate the type-correctness
of your code. IDEs that implement type-checking features are also able to leverage type hints to help ensure your
code is safe.Run arbitrary AutoHotkey scriptsYou can also run arbitrary AutoHotkey code either as a.ahkscript file or as a string containing AHK code.fromahkimportAHKahk=AHK()my_script='''\MouseMove, 100, 100; etc...'''ahk.run_script(my_script)fromahkimportAHKahk=AHK()script_path=r'C:\Path\To\myscript.ahk'ahk.run_script(script_path)Non-Python dependenciesTo use this package, you need theAutoHotkey executable(e.g.,AutoHotkey.exe).
It's expected to be on PATH by default OR in a default installation location (C:\Program Files\AutoHotkey\AutoHotkey.exefor v1 orC:\Program Files\AutoHotkey\v2\AutoHotkey64.exefor v2)AutoHotkey v1 is fully supported. AutoHotkey v2 support is available, but is considered to be in beta status.The recommended way to supply the AutoHotkey binary (for both v1 and v2) is to install thebinaryextra for this package. This will
provide the necessary executables and help ensure they are correctly placed on PATH.pip install "ahk[binary]"Alternatively, you may provide the path in code:fromahkimportAHKahk=AHK(executable_path='C:\\path\\to\\AutoHotkey.exe')You can also use theAHK_PATHenvironment variable to specify the executable location.set AHK_PATH=C:\Path\To\AutoHotkey.exepython myscript.pyUsing AHK v2By default, when noexecutable_pathparameter (orAHK_PATHenvironment variable) is set, only AutoHotkey v1 binary names
are searched for on PATH or default install locations. This behavior may change in future versions to allow v2 to be used by default.To use AutoHotkey version 2, you can do any of the following things:provide theexecutable_pathkeyword argument with the location of the AutoHotkey v2 binaryset theAHK_PATHenvironment variable with the location of an AutoHotkey v2 binaryProvide theversionkeyword argument with the valuev2which enables finding the executable using AutoHotkey v2 binary names and default install locations.For example:fromahkimportAHKahk=AHK(executable_path=r'C:\Program Files\AutoHotkey\v2\AutoHotkey64.exe')# ORahk=AHK(version='v2')When you provide theversionkeyword argument (with either"v1"or"v2") a check is performed to ensure the provided (or discovered) binary matches the requested version. When
theversionkeyword is omitted, the version is determined automatically from the provided (or discovered) executable binary.Differences when using AutoHotkey v1 vs AutoHotkey v2The API of this project is originally designed against AutoHotkey v1 and function signatures are the same, even when using AutoHotkey v2.
While most of the behavior remains the same, some behavior does change when using AutoHotkey v2 compared to v1. This is mostly due to
underlying differences between the two versions.Some of the differences that you will experience when using AutoHotkey v2 include:Functions that find and return windows will often raise an exception rather than returningNone(as in AutoHotkey v2, a TargetError is thrown in most cases where the window or control cannot be found)The behavior ofControlSend(ahk.control_sendorWindow.sendorControl.send) differs in AutoHotkey v2 when thecontrolparameter is not specified. In v1, keys are sent to the topmost controls, which is usually the correct behavior. In v2, keys are sent directly to the window. This means in many cases, you need to specify the control explicitly when using V2.Some functionality is not supported in v2 -- specifically: thesecondstowaitparamater forTrayTip(ahk.show_traytip) was removed in v2. Specifying this parameter in the Python wrapper will cause a warning to be emitted and the parameter is ignored.Some functionality that is present in v1 is not yet implemented in v2 -- this is expected to change in future versions. Specifically: somesound functionsare not implemented.ContributingAll contributions are welcomed and appreciated.Please feel free to open a GitHub issue or PR for feedback, ideas, feature requests or questions.Similar projectsThese are some similar projects that are commonly used for automation with Python.Pyautogui- Al Sweigart's creation for cross-platform automationPywinauto- Automation on Windows platforms with Python.keyboard- Pure Python cross-platform keyboard hooks/control and hotkeys!mouse- From the creators ofkeyboard, Pure Pythonmousecontrol!pynput- Keyboard and mouse control |
ahkab | a SPICE-like electronic circuit simulator written in PythonThe code should be easy to read and modify, the main language is Python
– 2 or 3 – and it is platform-independent.News!Ahkab v0.18 was released on July 18 2015, including new features,
bugfixes and improved documentation. It is recommended to upgrade.
Check outthe release
notesfor
more!The whole codebase has been going through a (yet incomplete)
refactoring and documenting effort. Thenew documentation is
available on RTD.My resources are limited these days, so the much-needed work is
proceeding slowly, albeit hopefully steadily. If you are interested and
you would like to contribute to refactoring or documenting a particular
feature, it would be very welcome.Supported simulations:Numeric:Operating point, with guess computation to speed up the
solution. See example:Downscaling current
mirrorDC sweepTransient analysis, available differentiation formulas:
implicit Euler, trapezoidal, gear orders from 2 to 5. See for
example thesimulation of a Colpitts
Oscillator.AC analysisPZanalysisPeriodic steady state analysisof non-autonomous circuits,timedomainshooting and brute-force algorithms.Symbolic:Small signal analysis, AC or DC, with extraction of transfer
functions, DC gain, poles and zeros. Varioussymbolic analysis
examples on this
page.The results are saved to disk, plotted or printed to stdout and can be
read/processed by the most common tools (eg.Octave,gnuplot,Matlab,gwaveand others)InstallThe program requires:the Python interpreter version 2 or 3 (at least v.2.6 for Python2,
v.3.3 for Python3),numpy>=1.7.0, scipy>=0.14.0, sympy>=0.7.6 and tabulate>=0.7.3.Matplotlib is strongly recommended and no plotting will work without.If you need more information about the dependencies, check theInstall
notes.Usage1.ahkabcan be run as a Python libraryfromahkabimportnew_ac,runfromahkab.circuitimportCircuitfromahkab.plottingimportplot_results# calls matplotlib for youimportnumpyasnp# Define the circuitcir=Circuit('Butterworth 1kHz band-pass filter')cir.add_vsource('V1','n1',cir.gnd,dc_value=0.,ac_value=1.)cir.add_resistor('R1','n1','n2',50.)cir.add_inductor('L1','n2','n3',0.245894)cir.add_capacitor('C1','n3','n4',1.03013e-07)cir.add_inductor('L2','n4',cir.gnd,9.83652e-05)cir.add_capacitor('C2','n4',cir.gnd,0.000257513)cir.add_inductor('L3','n4','n5',0.795775)cir.add_capacitor('C3','n5','n6',3.1831e-08)cir.add_inductor('L4','n6',cir.gnd,9.83652e-05)cir.add_capacitor('C4','n6',cir.gnd,0.000257513)cir.add_capacitor('C5','n7','n8',1.03013e-07)cir.add_inductor('L5','n6','n7',0.245894)cir.add_resistor('R2','n8',cir.gnd,50.)# Define the analysisac1=new_ac(2.*np.pi*.97e3,2.*np.pi*1.03e3,1e2,x0=None)# run itres=run(cir,ac1)# plot the resultsplot_results('5th order 1kHz Butterworth filter',[('|Vn8|',"")],res['ac'],outfilename='bpf_transfer_fn.png')2.ahkabcan be run from the command line with a netlist fileThe syntax is:`$ python ahkab -o graph.dat <netlist file>`Seeahkab--helpfor command line switches,also online on the
documentation
pages.DocumentationThedocumentation is available on
RTD.There, you can find adocumentationandexamplesregarding how to simulate from a Python script.Refer to thenetlist syntax
pageif you prefer to write netlist files that describe the circuit.Experience with running SPICE or related commercial simulators can be
very useful: this is not for the faint of heart.Development modelThe development happens on thegithub
repository,Mostly on the master branch, with feature branch being created only
for special purposes or non-trivial features.Snapshots are released on a (hopefully) regular basis and are
available on theReleases pages, complete with
changelogand onPYPIPatches and pull requests are welcome!How this project was bornThis project was born when I was an enthusistic undergrad, apparently
with plenty of free time, attending “Simulazione Circuitale” (Circuit
Simulation) taught byProf. A.
Brambillaback in Italy at the
Polytechnic University of Milan.I am grateful to prof. Brambilla for teaching one of the most
interesting courses of my university years. -GVBugs and patchesDoes it work? Bugs? Do you have patches? Did you run some noteworthy
simulation? Let me know! Feedback is very welcome, myemail
addressis available after a captcha.Support the development with a donationIf you wish to support the development ofahkab,*please donate to
cancer research:*Association for International Cancer Research
(eng),orFond. IRCCS Istituto Nazionale dei Tumori
(it).CreditsAuthors:Giuseppe Venturini,
with contributions fromIan DaniherandRob Crowther.Code:the modulepy3compat.pyis (c) 2013 - the Jinja team.Dependencies:many thanks to the authors ofnumpy,scipy,sympy,matplotlibandtabulate! |
ahk-bin | ahk-binA python package that bundled with workable AutoHotkey binary which could works for ‘ahk’ packageUsageimport ahkbin
from ahk import AHK
# If your Scripts directory of python be placed in PATH, it should works
# like a charm
ahk = AHK()
# Otherwise, you must specific the path which bundled in our package
ahk = AHK(executable_path=ahkbin.get_executable())LicenseThis package is licensed under GPLv2.The license of AutoHotkey binary are described in LICENSE_AHK.txtHistory0.0.5 (2021-02-08)Upgrade binary to AutoHotkeyU32 1.1.33.020.0.4 (2020-07-03)Upgrade binary to AutoHotkeyU32 1.1.330.0.3 (2020-05-30)Placed the AutoHotkey.exe into Scripts directory of python, so it’s easier to
create the AHK object when Scripts directory in PATH.Thanks @spyoungtechSpencer Phillip Young0.0.2 (2020-04-26)First release on PyPI. |
ahk-binary | Packages the AutoHotkey binary as an installable Python package. Intended for use with the [ahkpackage](https://pypi.org/project/ahk/).The license of AutoHotkey is included in theAutoHotkey_LICENSEfile.Installation:Since this is used as an accessory to theahkpackage, the recommended way to do this is to use the “extras” from ahk:$ pip install ahk[binary]Alternatively, it can be installed directly:$ pip install ahk-binary |
ahk-distributions | No description available on PyPI. |
ahk-json | ahk-jsonThis is an extension package intended to be used with the Pythonahkpackage.It provides interfaces fromcocobelgica/AutoHotkey-JSONfor
working with JSON in AutoHotkey. The extensions in this package do not provide any additional methods,
but simply provide a convenient way to includeJxon.ahkand/orJSON.ahkinto other extensions.This package provides two extensions:JXONandJSON. It also registers a JSON message type (ahk_json.message.JsonResponseMessage)InstallationInstall this extension usingpippipinstallahk-jsonUsageTypically, you use this as a dependency when building your own extensions.In the following example, a simple extension (my_extension) is created. It implements an AHK functionMyTestFunction-- the registered to the extension using the Python functionmy_test_function.fromahk.extensionsimportExtensionfromahkimportAHKfromahk_jsonimportJXON# importing is necessary for ``extensions='auto'`` to work, even if this is not usedext_script='''\MyTestFunction(ByRef command) {arg := command[2]obj := Object("test", arg)res := Jxon_Dump(obj) ; this is available thanks to the extensionreturn FormatResponse("ahk_json.message.JsonResponseMessage", res)}'''my_extension=Extension(script_text=ext_script)@my_extension.registerdefmy_test_function(ahk:AHK,arg:str):returnahk.function_call('MyTestFunction',[arg])defmain():ahk=AHK(extensions='auto')# automatically use all imported/created extensions# or use the extensions explicitly:# ahk = AHK(extensions=[JXON, my_extension])# now ``.my_test_function`` is a method on the `ahk` instance:assertahk.my_test_function('foo')=={'test':'foo'}LicenseThis work is licensed under the MIT license.This package includes substantial portions of theoriginal AutoHotkey-JSON.
The code included from AutoHotkey-JSON is owned and copyrighted by its original author(s) and is used/redistributed
under the terms of theWTFPL. |
ahkunwrapped | ahkUnwrappedI wanted to automate Windows with the coverage and simplicity of thecompleteAutoHotkey API, yet code in Python, so I createdahkUnwrapped.AutoHotkey already abstracts the Windows API, so another layer to introduce complexity and slowdowns is undesirable.Instead, we bundle and bridgeAutoHotkey.exe, sending your initial scriptvia stdinwith minimal boilerplate to listen forwindow messagesfrom Python and respondvia stdout.FeaturesAllof AutoHotkey!Execute arbitrary AHK code or load scripts.Hypothesispowered testing of convoluted unicode, et al.Warnings for loss of precision (maximum 6 decimal places).Errors for unsupported values (NaNInf\0).Unhandled AHK exceptions carry over to Python.Won't explode when used from multiple threads.Separate auto-execute sections to ease scripting.SupportsPyInstallerforonefile/onedirinstallations.Special care for:Descriptive errors with accurate line numbers.PersistentWindows notification areasettings.Unexpected exit handling.Minimal latency.Get started> pip install ahkunwrappedcall(proc, ...)f(func, ...)get(var)set(var, val)fromahkunwrappedimportScriptahk=Script()# built-in functions are directly callableisNotepadActive=ahk.f('WinActive','ahk_class Notepad')# built-in variables (and user globals) can be set directlyahk.set('Clipboard',"Copied text!")print(isNotepadActive)fromahkunwrappedimportScriptahk=Script('''LuckyMinimize(winTitle) {global myVarmyVar := 7WinMinimize, % winTitleClipboard := "You minimized: " winTitle}''')ahk.call('LuckyMinimize','ahk_class Notepad')print("Lucky number",ahk.get('myVar'))frompathlibimportPathfromahkunwrappedimportScriptahk=Script.from_file(Path('my_msg.ahk'))ahk.call('MyMsg',"Wooo!")my_msg.ahk:; auto-execute section when ran standalone#SingleInstanceforce#WarnAutoExec(); we can call this if we wantMyMsg("test our function")return; auto-execute section when ran from PythonAutoExec(){SetBatchLines,100ms; slow our code to reduce CPU}MyMsg(text){MsgBox,%text}Settings fromAutoExec()willstill applyeven though we execute directly from the message listening thread for speed.(AutoHotkey's#Warnis special and will apply to both standalone and from-Python execution, unless you add/remove it dynamically.)Usagecall(proc, ...)is for performance, to avoid receiving a large unneeded result.get(var)set(var, val)are shorthand for accessing global variables andbuilt-inslikeA_TimeIdle.f(func, ...)get(var)will inferfloatandint(base-16 beginning with0x) like AutoHotkey.f_raw(func, ...)get_raw(var)will return the raw string as-stored.call_main(proc, ...)f_main(func, ...)f_raw_main(func, ...)will execute on AutoHotkey's main thread instead of theOnMessage()listener.
This avoidsAhkCantCallOutInInputSyncCallError, e.g. from some uses ofComObjCreate().
This is slower (except with very large data), but still fast and unlikely to bottleneck.Event loop with hotkeysimportsysimporttimefromdatetimeimportdatetimefromenumimportEnumfrompathlibimportPathfromahkunwrappedimportScript,AhkExitExceptionchoice=NoneHOTKEY_SEND_CHOICE='F2'classEvent(Enum):QUIT,SEND_CHOICE,CLEAR_CHOICE,CHOOSE_MONTH,CHOOSE_DAY=range(5)# format_dict= so we can use {{VARIABLE}} within example.ahkahk=Script.from_file(Path('example.ahk'),format_dict=globals())defmain()->None:print("Scroll your mousewheel in Notepad.")ts=0whileTrue:try:# ahk.poll() # detect exit, but all ahk functions include thiss_elapsed=time.time()-tsifs_elapsed>=60:ts=time.time()print_minute()event=ahk.get('event')# contains ahk.poll()ifevent:ahk.set('event','')on_event(event)exceptAhkExitExceptionasex:sys.exit(ex.args[0])time.sleep(0.01)defprint_minute()->None:print(f"It is now{datetime.now().time()}")defon_event(event:str)->None:globalchoicedefget_choice()->str:returnchoiceordatetime.now().strftime('%#I:%M %p')ifevent==str(Event.QUIT):ahk.exit()ifevent==str(Event.CLEAR_CHOICE):choice=Noneifevent==str(Event.SEND_CHOICE):ahk.call('Send',f'{get_choice()}')ifevent==str(Event.CHOOSE_MONTH):choice=datetime.now().strftime('%b')ahk.call('ToolTip',f"Month is{get_choice()},{HOTKEY_SEND_CHOICE}to insert.")ifevent==str(Event.CHOOSE_DAY):choice=datetime.now().strftime('%#d')ahk.call('ToolTip',f"Day is{get_choice()},{HOTKEY_SEND_CHOICE}to insert.")if__name__=='__main__':main()example.ahk:#SingleInstance,force#WarnToolTip("Standalone script test!")returnAutoExec(){globaleventevent:=""SendMode,input}Send(text){Send,%text}ToolTip(text,s:=2){ToolTip,%text; negative for non-repeatingSetTimer,RemoveToolTip,%s*-1000}RemoveToolTip:ToolTip,event={{Event.CLEAR_CHOICE}}returnMouseIsOver(winTitle){MouseGetPos,,,winIdresult:=WinExist(winTitle" ahk_id "winId)returnresult}#IfWinActive("ahk_class Notepad"){{HOTKEY_SEND_CHOICE}}::event={{Event.SEND_CHOICE}}^Q::event={{Event.QUIT}}#IfMouseIsOver("ahk_class Notepad")WheelUp::event={{Event.CHOOSE_MONTH}}WheelDown::event={{Event.CHOOSE_DAY}}PyInstaller (single.exeor folder)example.spec:# -*- mode: python -*-frompathlibimportPathimportahkunwrappeda=Analysis(['example.py'],datas=[(Path(ahkunwrapped.__file__).parent/'lib','lib'),# required('example.ahk','.'),])pyz=PYZ(a.pure)# for onefileexe=EXE(pyz,a.scripts,a.binaries,a.datas,name='my-example',upx=True,console=False)# for onedir# exe = EXE(pyz, a.scripts, exclude_binaries=True, name='my-example', upx=True, console=False)# dir = COLLECT(exe, a.binaries, a.datas, name='my-example-folder')Folder considerationsexample.py:frompathlibimportPathfromahkunwrappedimportScript# tray icon visibility settings rely on consistent exe pathsLOCALAPP_DIR=Path(os.getenv('LOCALAPPDATA')/'pyinstaller-example')# working directory is different between onefile and onedir modes# https://pyinstaller.readthedocs.io/en/stable/runtime-information.htmlCUR_DIR=Path(getattr(sys,'_MEIPASS',Path(__file__).parent))ahk=Script.from_file(CUR_DIR/'example.ahk',format_dict=globals(),execute_from=LOCALAPP_DIR)# ...example.ahk:AutoExec(){Menu,Tray,Icon,{{CUR_DIR}}\black.icoMenu,Tray,Icon; unhide}; ... |
ahlev-django-about | long description |
ahlev-django-auth-rename | to rename authentication and authorization |
ahlev-django-brand | long description |
ahlev-django-layout | long description |
ahlev-django-uikit | long description |
ahlfors | A sample project that exists as an aid to thePython Packaging User Guide’sTutorial on Packaging and Distributing
Projects.This projects does not aim to cover best practices for Python project
development as a whole. For example, it does not provide guidance or tool
recommendations for version control, documentation, or testing.This is the README file for the project.The file should use UTF-8 encoding and be written using ReStructured Text. It
will be used to generate the project webpage on PyPI and will be displayed as
the project homepage on common code-hosting services, and should be written for
that purpose.Typical contents for this file would include an overview of the project, basic
usage examples, etc. Generally, including the project changelog in here is not
a good idea, although a simple “What’s New” section for the most recent version
may be appropriate. |
ahliang-distributions | No description available on PyPI. |
ahlive | ahlive - animate your data to life!Install the package:pip install ahliveFull Documentation:http://ahlive.readthedocs.io/ahlive is an open-source Python package that makes animating data simple, clean, and enjoyable.It can be as easy as:importahliveasahdf=ah.open_dataset("owid_co2_concentrations_over_the_long_term_scripps",names=["entity","year","co2"])ah.DataFrame(df,xs="year",ys="co2").render()Here are some features that make ahlive stand out!inline labels that follow the datadynamic axes limits that expand as necessaryremarks that pause the animation when a threshold is metmoving average reference linestraightforward usage; just set keywords!The code to generate this example can be foundhere.Need support? Join the community and ask a question at thediscussionspage. Don't be shy--it would make my day to see others use my package, seriously! (And I personally would love to )And if you like the project, don't forget to star the project! |
ahmadaktestpy | this is the home page of our project. |
ahmadHashMap | ahmadHashMapahmadHashMap is a cross-platform hashing/mapping Python module for human beings. Used to simulate a Python dictionary. |
ahmad-json-manger | A package that allows to build simple streams of video, audio and camera data. |
ahmadpdf | This is the homepage of our project |
ahmadsMathLibrary | No description available on PyPI. |
ahmad-taj-pkg-printer | small package |
ahmad-tik | ahmad-tik |
ahmadzahoor-distributions | No description available on PyPI. |
ahmedalsamet | This library print my name in new window using python TkinterChange Log0.0.1 (28/01/2024)First Release |
ahmedbenpdf | This is the homepage of our project. |
ahmed-laaziz | No description available on PyPI. |
ahmedlones1 | Failed to fetch description. HTTP Status Code: 404 |
ahmed-package | No description available on PyPI. |
ahmedpdf | This is the homepage of our project. |
ahmedrajapdf | This is the homepage of our project. A practice package! |
ahmetin-k-t-phanesi | This is a very simple calculator that takes two numbers and either add, subtract, multiply or divide them.Change Log0.0.1 (19/04/2020)First Release |
ahmetturk-probability | No description available on PyPI. |
ahnb | A callback library which submits model and training statistics to AHNB |
ahn-cli | AHN CLIDescriptionAHN CLI is a command-line interface tool designed for the effortless downloading of AHN (Actueel Hoogtebestand Nederland) point cloud data for specific cities and classification classes.InstallationNOTE:AHN CLI requires PDAL to be installed on your system. Follow the installation instructions in thePDAL documentationbefore proceeding.Install AHN CLI using pip:pip install ahn_cliUsageTo utilize the AHN CLI, execute the following command with the appropriate options:Options:-c,--city<city_name>Downloadpointclouddataforthespecifiedcity.-o,--output<file>Designatetheoutputfileforthedownloadeddata.-i,--include-class<class>Includespecificpointcloudclassesinthedownload,specifiedinacomma-separatedlist.Availableclasses:0:Created,neverclassified;1:Unclassified;2:Ground;6:Building;9:Water;14:Hightension;26:Civilstructure.-e,--exclude-class<class>Excludespecificpointcloudclassesfromthedownload,specifiedinacomma-separatedlist.Availableclassesasabove.-d,--decimate<step>Decimatethepointclouddatabythespecifiedstep.-ncc,--no-clip-cityAvoidclippingthepointclouddatatothecityboundary.-cf,--clip-file<file>Provideafilepathforaclippingboundaryfiletoclipthepointclouddatatoaspecifiedarea.-e,--epsg<epsg>SettheEPSGcodeforuser'sclipfile.-b,--bbox<bbox>Specifyaboundingboxtoclipthepointclouddata.Itshouldbecomma-separatedlistwithminx,miny,maxx,maxycenteredonthecitypolygon.-p,--previewPreviewthepointclouddataina3Dviewer.-h,--help[category]Showhelpinformation.Optionallyspecifyacategoryfordetailedhelponaspecificcommand.-v,--versionDisplaytheversionnumberoftheAHNCLIandexit.Usage ExamplesDownload Point Cloud Data for Delft with All Classification Classes:ahn_cli -c delft -o ./delft.lazTo Include or Exclude Specific Classes:ahn_cli -c delft -o ./delft.laz -i 1,2For Non-Clipped, Rectangular-Shaped Data:ahn_cli -c delft -o ./delft.laz -i 1,2 -nccTo Decimate City-Scale Point Cloud Data:ahn_cli -c delft -o ./delft.laz -i 1,2 -d 2Specify a Bounding box for clipping:If you specify ab, it will clip the point cloud data with specified bounding box.ahn_cli -c delft -o ./delft.laz -i 1,2 -d 2 -b 194198.302994,443461.343994,194594.109009,443694.838989Reporting IssuesEncountering issues or bugs? We greatly appreciate your feedback. Please report any problems by opening an issue on our GitHub repository. Be as detailed as possible in your report, including steps to reproduce the issue, the expected outcome, and the actual result. This information will help us address and resolve the issue more efficiently.ContributingYour contributions are welcome! If you're looking to contribute to the AHN CLI project, please first review our Contribution Guidelines. Whether it's fixing bugs, adding new features, or improving documentation, we value your help.To get started:Fork the repository on GitHub.Clone your forked repository to your local machine.Create a new branch for your contribution.Make your changes and commit them with clear, descriptive messages.
Push your changes to your fork.Submit a pull request to our repository, providing details about your changes and the value they add to the project.We look forward to reviewing your contributions and potentially merging them into the project! |
aho | ahoGeneral purpose Discord bot.InstallationRequirementspython3 (>=3.11.2) with pipvirtualenvClone and install in virtualenvgit clone [email protected]:nul.one/aho.gitcd ahosetup and enable virtualenv with correct version of pythonpip install ./ahoInstall from pypipip install ahoNote that running aho bot will create a socket file in current directory.Usageaho --help- show available commandsaho run --help- show options for runningYou can run the bot with these minimal options:aho run -t DISCORD_AUTHORIZATION_TOKEN --database SQLITE_DB_FILE_PATHAdditional run options and environment variblesEach of these variables can be set using corresponding env variable. If both command line option and env variable are present, the command line option will be used.-t, --tokenor exportTOKENDiscord bot authorization token.-o, --owneror exportOWNERBot owner (dev) Discord user ID.--databasePath to sqlite database file. If not provided, it will use ephemeral database in ram.--prefixor exportDEFAULT_PREFIXDefault prefix in guilds. Each guild prefix can be configured in the guild itself.--descriptionor exportBOT_DESCRIPTIONBot description that shows up in guild commands help printout.-n, --nameor exportBOT_NAMEBot name that shows up in guild commands help printout.--openaior exportOPENAI_API_KEYOpenAI API secret key.--openai-system-messageor exportOPENAI_SYSTEM_MESSAGEDefault ChatGPT system message if you want to customize it.-l, --log-fileLog file path.FeaturesThese are the features as used from Discord. All of these should start with a bot prefix (default isaho) specific for each guild.MetadataMetadata is a list of key/value pairs associated with either a guild, channel, user or member. You can create any key/value pair. Some specific keys are used by other extensions and features. Having an unrestricted key/value pair simplifies configuration of existing features or adding new features in the future.Here is a list of commands for manipulating metadata:meta (guild|CHANNEL_TAG|MEMBER_TAG) (get|set) KEY [VALUE]This will get the value of a key for selected entity or set the new value.The guild as an entity is just a literal word "guild" or "g" for short. There is no tag for a guild. E.g.meta g set prefix ~.If you want to delete a key/value entry, use set command without the value. E.g.meta g set openai_api_key.To list keys/vlues, omit key when getting. E.g.meta #general get.User metaThis is separate command to manipulate user specific metadata as opposed to a member. Member is user entity tied to a guild. User metadata is same across all guilds for a specific user. As such, this command is restricted to a bot owner (see--owneroption in instructions on how to run the bot).The command is similar to howmetaworks:umeta (MEMBER_TAG|DISCORD_USER_ID) (get|set) KEY [VALUE]Moderation commandsThese commands are used for user/channel/guild moderation and are available to users with those specific permissions.ban (MEMEBER_TAG|DISCORD_USER_ID) [REASON]ban a user.unban (MEMEBER_TAG|DISCORD_USER_ID)lift a user ban.kick (MEMEBER_TAG|DISCORD_USER_ID) [REASON]kick a user from guild.perms (MEMEBER_TAG|DISCORD_USER_ID)display member permissions in guild.clear [N]delete N lines (defaults to 1) right above in the current channel.OpenAI (ChatGPT) chatThere are 2 modes of chatting with ChatGPT bot: using chat command and using a chat specific channel. ChatGPT 3.5 is being used as of the time of writing this manual.Chat commandGuild level metadata values should be configured:openai_api_keyPut your OpenAI API key here. Alternatively, you can specify this value when running the bot with--openaioption or exportingOPENAI_API_KEYenvironment variable. Note that by doing so the api will be enabled by default on all guilds. I recommend having a specific setting in metadata for each guild if your discord bot is publically available.openai_system_messageThis is optional and is used if you want to customize your ChatGPT experience.Using achatcommand, e.g.chat Hello! Can you tell me the radius of Earth?will initiate a respons from the bot in all channels.Chat channelYou can configure one channel that will always initiate a response from a bot, no commands need to be used in it. To configure a channel for this, set these meta variables at the channel level:openai_chat_enabledSet it to1to start using this channel as dedicated for a chatbot interraction.openai_system_messageOptional, same as forchatcommand. Each dedicated channel can have specific ChatGPT customization.You still need anopenai_api_keyset at the guild level for this dedicated channel chat to work.PointsMembers who have permission to manage other members can use the point system. Point system is used to award other members for any deeds or to promote competitive environment. It's up to you on how you will use this feature.transaction (MEMBER_TAG|DISCORD_USER_ID) AMOUNT [DESCRIPTION]Add (or remove by adding negative AMOUNT) points to a member.Points can be visible in the member info (see info command).Member InfoUse this command to see following information about a member:number of pointsguild joining date and joining positionguild rolesdiscord account creation dateUse it as soinfoIf you don't provide a member tag or ID, it will show your own info.RollRoll dice in NdN format, first number being number of dice and second being number of sides on each die.roll [NdN]Default is 1d6 which you can use without arguments.Emojiaddemoji EMOJI NAMECopy an existing emoji (that you can access from another server with Discord premium) and add it to the current server under a new NAME.getemoji EMOJIGet a link to the emoji image or animation.General purpose commandshelp [command]Show usage of specific command. If you don't specify a command, it will list all commands with short description.avatar [MEMBER_TAG|DISCORD_USER_ID]It will reply with a member avatar image. If you don't provide a member tag or ID, it will show your own avatar.embed "Some Title" Some message.This will create an embeded message in a current channel and delete your command message. Used to create emphasized messages.info [MEMBER_TAG|DISCORD_USER_ID]Show member info, including number of points, guild joining date and position, guild roles and discord account creation date. If you don't specify a member, your own info will be shown.prefix NEW_PREFIXSet new Discord bot prefix at a guild level.versionDisplay the current bot version.Versioning and compatibilityStarting from version1.3.0the versions will followSemantic versioning v2.0.0.License3-Clause BSD Licensewhich you can see in the LICENSE file. |
ahocode-test | This repo is a pure python implementation forpyahocorasick, inspired byabusix/ahocorapy.InstallationRequirementsPython 3.8 or laterpipinstallahocode-testDocumentationahocode is a fallback library for pyahocorasick, so theAutomatonclass and its methods
have same names and parameters.Below listed are the implemented classes and methods.ClassesAutomatonMethods for Automaton classadd_wordgetclearexistsfind_allitemsmake_automatoniterkeysvalues__getstate____setstate____len____contains__For documentation please refer to:https://pyahocorasick.readthedocs.io/en/latest |
ahocorapy | ahocorapy - Fast Many-Keyword Search in Pure Pythonahocorapy is a pure python implementation of the Aho-Corasick Algorithm.
Given a list of keywords one can check if at least one of the keywords exist in a given text in linear time.Comparison:Why another Aho-Corasick implementation?We started working on this in the beginning of 2016. Our requirements included unicode support combined with python2.7. That
was impossible with C-extension based libraries (likepyahocorasick). Pure
python libraries were very slow or unusable due to memory explosion. Since then another pure python library was releasedpy-aho-corasick. The repository also contains some discussion about different
implementations.
There is alsoacora, but it includes the note ('current construction algorithm is not
suitable for really large sets of keywords') which really was the case the last time I tested, because RAM ran out quickly.DifferencesCompared topyahocorasickour library supports unicode in python 2.7 just likepy-aho-corasick.
We don't use any C-Extension so the library is not platform dependant.On top of the standard Aho-Corasick longest suffix search, we also perform a shortcutting routine in the end, so
that our lookup is fast while, the setup takes longer. During set up we go through the states and directly add transitions that are
"offered" by the longest suffix or their longest suffixes. This leads to faster lookup times, because in the end we only have to
follow simple transitions and don't have to perform any additional suffix lookup. It also leads to a bigger memory footprint,
because the number of transitions is higher, because they are all included explicitely and not implicitely hidden by suffix pointers.We added a small tool that helps you visualize the resulting graph. This may help understanding the algorithm, if you'd like. See below.Fully pickleable (pythons built-in de-/serialization). ahocorapy uses a non-recursive custom implementation for de-/serialization so that even huge keyword trees can be pickled.PerformanceI compared the two libraries mentioned above with ahocorapy. We used 50,000 keywords long list and an input text of 34,199 characters.
In the text only one keyword of the list is contained.
The setup process was run once per library and the search process was run 100 times. The following results are in seconds (not averaged for the lookup).You can perform this test yourself usingpython tests/ahocorapy_performance_test.py. (Except for the pyahocorasick_py results. These were taken by importing the
pure python version of the code ofpyahocorasick. It's not available through pypi
as stated in the code.)I also added measurements for the pure python libraries with run with pypy.These are the results:Library (Variant)Setup (1x)Search (100x)ahocorapy*0.30s0.29sahocorapy (run with pypy)*0.37s0.10spyahocorasick*0.04s0.04spyahocorasick (run with pypy)*0.10s0.05spyahocorasick (pure python variant in github repo)**0.50s1.68spy_aho_corasick*0.72s4,60spy_aho_corasick (run with pypy)*0.83s2.02sAs expected the C-Extension shatters the pure python implementations. Even though there is probably still room for optimization in
ahocorapy we are not going to get to the mark that pyahocorasick sets. ahocorapy's lookups are faster than py_aho_corasick.
When run with pypy ahocorapy is almost as fast as pyahocorasick, at least when it comes to
searching. The setup overhead is higher due to the suffix shortcutting mechanism used.* SpecsCPU: AMD Ryzen 2700X
Linux Kernel: 6.0.6
CPython: 3.11.0pypy: PyPy 7.3.9 (Python 3.9.12) with GCC 10.2.1 20210130
Date tested: 2022-11-22** Old measurement with different specsBasic Usage:Installationpip install ahocorapyCreation of the Search Treefromahocorapy.keywordtreeimportKeywordTreekwtree=KeywordTree(case_insensitive=True)kwtree.add('malaga')kwtree.add('lacrosse')kwtree.add('mallorca')kwtree.add('mallorca bella')kwtree.add('orca')kwtree.finalize()Searchingresult=kwtree.search('My favorite islands are malaga and sylt.')print(result)Prints :('malaga',24)The search_all method returns a generator for all keywords found, or None if there is none.results=kwtree.search_all('malheur on mallorca bellacrosse')forresultinresults:print(result)Prints :('mallorca',11)('orca',15)('mallorca bella',11)('lacrosse',23)Thread SafetyThe construction of the tree is currently NOT thread safe. That meansadding shouldn't be called multiple times concurrently. Behavior is undefined.Afterfinalizeis called you can use thesearchfunctionality on the same tree from multiple threads at the same time. So that part is thread safe.Drawing GraphYou can print the underlying graph with the Visualizer class.
This feature requires a working pygraphviz library installed.fromahocorapy_visualizer.visualizerimportVisualizervisualizer=Visualizer()visualizer.draw('readme_example.png',kwtree)The resulting .png of the graph looks like this: |
ahocorasick | The Aho-Corasick automaton is a data structure that can quickly do a multiple-keyword search across text. It’s described in the classic paper ‘Efficient string matching: an aid to bibliographic search’:http://portal.acm.org/citation.cfm?id=360855&dl=ACM&coll=GUIDE. The majority of the code here is adapted from source code from the Fairly Fast Packet Filter (FFPF) project:http://ffpf.sourceforge.net/general/overview.php. |
ahocorasick-python | ahocorasick-pythonac自动机python的实现,可用于python2 python3等主流python发行版,对标准的ac自动机算法进行了完善 优化(主要是改进了结果的准确性)。注意:为了保证结果的准确性,请安装使用最新版(0.0.9)。1.如何安装pip 安装(推荐)pip install ahocorasick-python源码安装git clone https://github.com/xizhicode/ahocorasick-python.git
cd ahocorasick-python && python setup.py install2.如何使用注: 此处python3为例,python2也是类似的结果简单检索importahocorasick# 导入包tree=ahocorasick.AhoCorasick("test","book","oo","ok","k")# 构建ac自动机print(tree.search("test book"))# 检索输出结果:{'test','k','oo','book','ok'}检索并返回结果字符所在的位置(可以用于字符替换等场景)importahocorasick# 导入包tree=ahocorasick.AhoCorasick("test","book","oo","ok","k")# 构建ac自动机print(tree.search("test book",True))# 检索输出结果:{('k',(8,9)),('book',(5,9)),('oo',(6,8)),('ok',(7,9)),('test',(0,4))}3.参考资料ac自动机算法详解ac自动机4.联系我QQ: 943489924邮箱:[email protected]. 注意如果在windows平台上遇到了编码问题,删除所有的中文即可。 |
ahocorasick-rs | ahocorasick_rs: Quickly search for multiple substrings at onceahocorasick_rsallows you to search for multiple substrings ("patterns") in a given string ("haystack") using variations of theAho-Corasick algorithm.In particular, it's implemented as a wrapper of the Rustaho-corasicklibrary, and provides a faster alternative to thepyahocorasicklibrary.Found any problems or have any questions?File an issue on the GitHub project.QuickstartChoosing the matching algorithmAdditional configuration: speed and memory usage tradeoffsImplementation detailsBenchmarksQuickstartTheahocorasick_rslibrary allows you to search for multiple strings ("patterns") within a haystack, or alternatively search multiple bytes.
For example, let's install the library:$pipinstallahocorasick-rsSearching stringsWe can construct aAhoCorasickobject:>>>importahocorasick_rs>>>patterns=["hello","world","fish"]>>>haystack="this is my first hello world. hello!">>>ac=ahocorasick_rs.AhoCorasick(patterns)You can construct aAhoCorasickobject from any iterable (including generators), not just lists:>>>ac=ahocorasick_rs.AhoCorasick((p.lower()forpinpatterns))AhoCorasick.find_matches_as_indexes()returns a list of tuples, each tuple being:The index of the found pattern inside the list of patterns.The start index of the pattern inside the haystack.The end index of the pattern inside the haystack.>>>ac.find_matches_as_indexes(haystack)[(0,17,22),(1,23,28),(0,30,35)]>>>patterns[0],patterns[1],patterns[0]('hello','world','hello')>>>haystack[17:22],haystack[23:28],haystack[30:35]('hello','world','hello')find_matches_as_strings()returns a list of found patterns:>>>ac.find_matches_as_strings(haystack)['hello','world','hello']Searchingbytesand other similar objectsYou can also searchbytes,bytearray,memoryview, and other objects supporting the Python buffer API.>>>patterns=[b"hello",b"world"]>>>ac=ahocorasick_rs.BytesAhoCorasick(patterns)>>>haystack=b"hello world">>>ac.find_matches_as_indexes(b"hello world")[(0,0,5),(1,6,11)]>>>patterns[0],patterns[1](b'hello',b'world')>>>haystack[0:5],haystack[6:11](b'hello',b'world')Thefind_matches_as_strings()API is not supported byBytesAhoCorasick.Choosing the matching algorithmMatch kindThere are three ways you can configure matching in cases where multiple patterns overlap, supported by bothAhoCorasickandBytesAhoCorasickobjects.
For a more in-depth explanation, see theunderlying Rust library's documentation of matching.Assume we have this starting point:>>>fromahocorasick_rsimportAhoCorasick,MatchKindStandard(the default)This returns the pattern that matches first, semantically-speaking.
This is the default matching pattern.>>>acAhoCorasick(["disco","disc","discontent"])>>>ac.find_matches_as_strings("discontent")['disc']>>>ac=AhoCorasick(["b","abcd"])>>>ac.find_matches_as_strings("abcdef")['b']In this casediscwill match beforediscoordiscontent.Similarly,bwill match beforeabcdbecause it ends earlier in the haystack thanabcddoes:>>>ac=AhoCorasick(["b","abcd"])>>>ac.find_matches_as_strings("abcdef")['b']LeftmostFirstThis returns the leftmost-in-the-haystack matching pattern that appears first inthe list of given patterns.
That means the order of patterns makes a difference:>>>ac=AhoCorasick(["disco","disc"],matchkind=MatchKind.LeftmostFirst)>>>ac.find_matches_as_strings("discontent")['disco']>>>ac=AhoCorasick(["disc","disco"],matchkind=MatchKind.LeftmostFirst)['disc']Here we seeabcdmatched first, because it starts beforeb:>>>ac=AhoCorasick(["b","abcd"],matchkind=MatchKind.LeftmostFirst)>>>ac.find_matches_as_strings("abcdef")['abcd']LeftmostLongestThis returns the leftmost-in-the-haystack matching pattern that is longest:>>>ac=AhoCorasick(["disco","disc","discontent"],matchkind=MatchKind.LeftmostLongest)>>>ac.find_matches_as_strings("discontent")['discontent']Overlapping matchesYou can get all overlapping matches, instead of just one of them, but only if you stick to the default matchkind,MatchKind.Standard.
Again, this is supported by bothAhoCorasickandBytesAhoCorasick.>>>fromahocorasick_rsimportAhoCorasick>>>patterns=["winter","onte","disco","discontent"]>>>ac=AhoCorasick(patterns)>>>ac.find_matches_as_strings("discontent",overlapping=True)['disco','onte','discontent']Additional configuration: speed and memory usage tradeoffsAlgorithm implementations: trading construction speed, memory, and performance (AhoCorasickandBytesAhoCorasick)You can choose the type of underlying automaton to use, with different performance tradeoffs.
The short version: if you want maximum matching speed, and you don't have too many patterns, try theImplementation.DFAimplementation and see if it helps.The underlying Rust library supportsfour choices, which are exposed as follows:Noneuses a heuristic to choose the "best" Aho-Corasick implementation for the given patterns, balancing construction time, memory usage, and matching speed.
This is the default.Implementation.NoncontiguousNFA: A noncontiguous NFA is the fastest to be built, has moderate memory usage and is typically the slowest to execute a search.Implementation.ContiguousNFA: A contiguous NFA is a little slower to build than a noncontiguous NFA, has excellent memory usage and is typically a little slower than a DFA for a search.Implementation.DFA: A DFA is very slow to build, uses exorbitant amounts of memory, but will typically execute searches the fastest.>>>fromahocorasick_rsimportAhoCorasick,Implementation>>>ac=AhoCorasick(["disco","disc"],implementation=Implementation.DFA)Trading memory for speed (AhoCorasickonly)If you usefind_matches_as_strings(), there are two ways strings can be constructed: from the haystack, or by caching the patterns on the object.
The former takes more work, the latter uses more memory if the patterns would otherwise have been garbage-collected.
You can control the behavior by using thestore_patternskeyword argument toAhoCorasick().AhoCorasick(..., store_patterns=None): The default.
Use a heuristic (currently, whether the total of pattern string lengths is less than 4096 characters) to decide whether to store patterns or not.AhoCorasick(..., store_patterns=True): Keep references to the patterns, potentially speeding upfind_matches_as_strings()at the cost of using more memory.
If this uses large amounts of memory this might actually slow things down due to pressure on the CPU memory cache, and/or the performance benefit might be overwhelmed by the algorithm's search time.AhoCorasick(..., store_patterns=False): Don't keep references to the patterns, saving some memory but potentially slowing downfind_matches_as_strings(), especially when there are only a small number of patterns and you are searching a small haystack.Implementation detailsMatching on strings releases the GIL, to enable concurrency.
Matching on bytes does not currently release the GIL for memory-safety reasons, unless the haystack type isbytes.Not all features from the underlying library are exposed; if you would like additional features, pleasefile an issueor submit a PR.BenchmarksAs with any benchmark, real-world results will differ based on your particular situation.
If performance is important to your application, measure the alternatives yourself!That being said, I've seenahocorasick_rsrun 1.5× to 7× as fast aspyahocorasick, depending on the options used.
You can run the included benchmarks, if you want, to see some comparative results locally.
Clone the repository, then:pip install pytest-benchmark ahocorasick_rs pyahocorasick
pytest benchmarks/ |
ahogeotagger | ahogeotaggerIf you have thousands of passages of text and you want to search them for hundreds or thousands of search strings, the process can become very cumbersome very soon. This is where ahocorasick search becomes very relevant and blazingly fast. You can read more about the algorithmhere.This code combines thevery efficient implementation of ahocorasickin python with a pre-bundled list of cities, states and countries to tag locations in text.RequirementsPython 3.6 or higherpyahocorasick 1.4.0 or higherInstallationUsing PIP via PyPipip install ahogeotaggerUsageRight now the usage is pretty simple. You import and init the tagger with the number of cities you want to search your text for. The cities are in order of population (Tokyo, New york, Mexico City etc.).The data for these cities has been prepopulated from the free version of simplemaps database which you can findhere.from ahogeotagger import tagger
tagger.init(num_cities = 10000)Optionally, if you dont want to use the built-in database of cities, you can provide your own list of cities. The list needs to be a list of tuples with each tuple's values in the following order:(id,city,state,country,iso2,iso3,population,lat,lng)The types foridandpopulationareint,latandlngare floats and all the rest are strings.tagger.init(num_cities = 500, cities = [a,b,c])where a,b,c are tuples described above.To search whether text contains locations, supply any plain text to the search function like this:results = tagger.search('New york and London are are competing for tech talent')
print(results)This produces the following list of tuples as a result[(0, 7, 'New York', 'New York', 'United States', 'US', 'USA', 19354922, 40.6943, -73.9249),
(13, 18, 'London', 'London, City of', 'United Kingdom', 'GB', 'GBR', 8567000, 51.5, -0.1167)]Each tuple always contains values in this orderstart_index(for the match in the source string),end_index,city,state,country,iso2,iso3,population,latitude,longitude |
ahoi | ahoi (A Horrible Optimisation Instrument)This module contains a few python functions to run Brute-force scans for rectangular cut optimization.InstallationTo install ahoi runpython3-mpipinstall[--user]ahoiUse--userif not in a virtual environment or conda environment.It's recommended to use python3, but currently python2 is also supported.ExampleThe basic functionality uses amasks_listwhich is a list of lists or a list
of 2D numpy arrays that represent pass flags for selection criteria.For example, the following represents pass flags for the criteria>0,>0.1,>0.2, ...,>0.9for 5 random uniform variables in 10000 events:importnumpyasnpnp.random.seed(42)x=np.random.rand(10000,5)masks_list=[[x[:,i]>vforvinnp.linspace(0,0.9,10)]foriinrange(x.shape[1])]To count all matching combinations for all criteria on each variable runimport ahoi
counts = ahoi.scan(masks_list)The entry[0, 1, 2, 3, 4]ofcountswill contain the number of matching
events where the first column ofxis>0, the second one>0.1, the third
one>0.2etc.>>>counts[0,1,2,3,4]3032>>>np.count_nonzero((x[:,0]>0)&(x[:,1]>0.1)&(x[:,2]>0.2)&(x[:,3]>0.3)&(x[:,4]>0.4))3032You can also pass weightsweights=np.random.normal(loc=1,size=len(x))counts,sumw,sumw2=ahoi.scan(masks_list,weights=weights)The arrayssumwandsumw2will contain the sum of weights and sum of squares
of weights for matching combinations. The sum of squares of weights can be used
to estimate the statistical uncertainty on the sum of weights ($\sigma = \sqrt{\sum w_i^2}$).>>>sumw[0,1,2,3,4]3094.2191136427627>>>np.dot(...(x[:,0]>0)&(x[:,1]>0.1)&(x[:,2]>0.2)&(x[:,3]>0.3)&(x[:,4]>0.4),...weights...)3094.219113642755>>>np.sqrt(sumw2[0,1,2,3,4])78.5528532026876>>>np.sqrt(...np.dot(...(x[:,0]>0)&(x[:,1]>0.1)&(x[:,2]>0.2)&(x[:,3]>0.3)&(x[:,4]>0.4),...weights**2...)...)78.55285320268761Tutorial/NotebookHave a look at theexamplesfor a tutorial that explains how to use
this for solving a classification problem.Tests/CoverageRun the tests and coverage report inside the project directory withpython3-mpytest--cov=ahoi--doctest-modules
coveragehtml |
ahook | No description available on PyPI. |
ahorn | UNKNOWN |
ahoy | Agent-based simulations of active particlesFree software: BSD licenseDocumentation:https://ahoy.readthedocs.org.FeaturesTODOHistory0.1.0 (2015-01-11)First release on PyPI. |
ahoy-dtu-webthing | ahoy_dtu_webthingA webthing adapter to provide theAhyoDTUinterface via thewebthing API.Example# webthing has been started on host 192.168.0.23
curl http://192.168.0.23:7122/0/properties
{
"name": "Terrasse",
"serial": "114180123418",
"p_dc": 23
....
}To install this software you can usePIPpackage manager as shown belowsudo pip install ahoy_dtu_webthingAfter this installation you can use the Webthing http endpoint in your Python code or from the command line withsudo dtu --command listen --port 7122 --base_uri http://10.1.11.35/Here the webthing API is bound to the local port 7122. Additionally, the base uri of the AhyoDTU REST api must be set.As an alternative to thelistcommand, you can also use theregistercommand to register and start the webthing service as a systemd entity.
This way, the webthing service is started automatically at boot time. Starting the server manually with thelistencommand is no longer necessary.sudo dtu --command register --port 7122 --base_uri http://10.1.11.35/ |
ahoyhoy | OverviewA friendly greeting for your services!ahoyhoyis intended as a universal service client for python/django applications.GoalsProvide a standard service discovery and resolution interface for python.Include all required information in each request before sending it to downstream servicesDocumentationFor full documentation, including installation, please seehttp://ahoyhoy.readthedocs.io/en/latest/About the nameFromWikipedia:Ahoyis a signal word used to call to a ship or boat, stemming from the Middle English cry, ‘Hoy!’.Alexander Graham Bell originally suggestedahoybe adopted as the standard greeting when answering a telephone, before ‘hello’ (suggested by Thomas Edison) became common.(Formerly a Ukrainian Unicorn.) |
ahp-calculator | Installationpip install ahp_calculatorUsagefrom ahp_calculator import ahp_calculator
AC=ahp_calculator()
AC.open_calculator()INTRODUCTIONThe Analytic Hierarchy Process (AHP) is a method for organizing and evaluating complicated decisions, using Maths and Psychology. In 1970s, Thomas L. Saaty developed AHP which is a theory of measurement. AHP has been widely used, particularly in large-scale situations with several criteria and when the evaluation of alternatives is mostly subjective. It has quantifying capability which distinguishes the AHP from other decision making techniques.AHP is one of the extensively used Multi Criteria Decision Making (MCDM) tool for processing multiple important objectives and weighting the criteria. The AHP allows to assign a priority among various alternatives and integrating multidimensional measures into a single scale of priorities.METHODThe pair-wise comparison is used to compare the importance of criteria. It can be carried out with nine-point scale value which includes values 9, 8, 7, 6...., 1/7, 1/8, 1/9, which indicates 9 as extreme preference, 7 as very strong preference, 5 as strong preference and so on down to 1 which represents no preference. Thus, the pair-wise comparison aids to simplify the criteria by evaluating the independent contribution of each criterion with each other. The square matrix is organized for pairwise comparisons of various criteria. The principal eigenvalue and their corresponding eigenvector was developed among the relative importance within the criteria from the comparison matrix. The weights for each element can be generated from the normalized eigenvector. The subjective judgment from AHP were checked via consistency index. The consistency index (CI) is calculated as:CI = ( λmax - n ) / ( n - 1 )Where CI = Consitency Indexλmax = maximum eigenvector of the matrixn = order of the matrixAfter comparing CI with random index, Consistency Ratio (CR) can be derived from their ratio. The consistency ratio should be ≤ 0.1 (Saaty, 1990). The pairwise comparison is assumed to be inconsistent if the CR exceeds the threshold, the process has to be reviewed in such case. |
ahp-graph | ahp_graph - Python Attributed Hierarchical Port GraphAHP Graphs -https://arxiv.org/pdf/1802.06492.pdfRequires Python3.9 at a minimum. There is a "noTyping" branch which works with older versions of Python (like 3.6)Ubuntu apt packages:aptinstallgraphvizlibgraphviz-devRHEL/CentOS yum packages:yuminstallgraphvizgraphviz-develPython3 packages:python3-mpipinstallpygraphvizorjsonUseful TipsAssembly names are automatically prefixed to the expanded devices names when the graph is flattenedBesides graph construction, the main features that ahp_graph provides are several outputsSSTGraph.build()will immediately turn your graph into SST components and begin a simulationSSTGraph.write_json()will output the graph along with parameters in JSON formatDeviceGraph.write_dot()will output the graph in DOT format and optionally draw SVGs with themAll output generated by ahp_graph goes into a folder called 'output'This is for theSSTGraph.write_json()andDeviceGraph.write_dot()functionsSST global parameters are set by adding things to the DeviceGraph attr fieldSST component parameters are set by adding things to the Device attr fieldYou can still do normal SST Python things (examples below):sst.setProgramOption()sst.setStatisticLoadLevel()sst.setStatisticOutput()SSTGraph.build()returns a dictionary of devices with their name as the keyYou can use this to enable statistics for devices after they are createdIf you plan to build the graph with ahp_graph partitioning and run with MPI, remember to include the--parallel-load=SINGLEflag to sst--parallel-loadby default will work with multiple unique filesahp_graph can generate the graph for each rank using a single file, so it needs the value 'SINGLE'By default sst grabs all command line parametersYou can pass parameters to the python script by putting--before your script parameters |
ah-probability | No description available on PyPI. |
ahps_alerts | ahps_alertsRetrieve NWS AHPS alertsFree software: MIT licenseDocumentation:https://ahps-alerts.readthedocs.io.FeaturesTODOCreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.History0.1.0 (2017-09-18)First release on PyPI. |
ahpy | AHPyAHPyis an implementation of the Analytic Hierarchy Process (AHP), a method used to structure, synthesize and evaluate the elements of a decision problem. Developed byThomas Saatyin the 1970s, AHP's broad use in fields well beyond that of operational research is a testament to its simple yet powerful combination of psychology and mathematics.AHPy attempts to provide a library that is not only simple to use, but also capable of intuitively working within the numerous conceptual frameworks to which the AHP can be applied. For this reason, general terms have been preferred to more specific ones within the programming interface.Installing AHPyAHPy is available on the Python Package Index (PyPI):python -m pip install ahpyAHPy requiresPython 3.7+, as well asnumpyandscipy.Table of ContentsExamplesRelative consumption of drinks in the United StatesChoosing a leaderPurchasing a vehiclePurchasing a vehicle reprised: normalized weights and the Compose classDetailsThe Compare ClassCompare.add_children()Compare.report()The Compose ClassCompose.add_comparisons()Compose.add_hierarchy()Compose.report()A Note on WeightsMissing Pairwise ComparisonsDevelopment and TestingExamplesThe easiest way to learn how to use AHPy is toseeit used, so this README begins with worked examples of gradually increasing complexity.Relative consumption of drinks in the United StatesThis example is often used in Saaty's expositions of the AHP as a brief but clear demonstration of the method; it's what first opened my eyes to the broad usefulness of the AHP (as well as the wisdom of crowds!). The version I'm using here is from his 2008 article 'Decision making with the analytic hierarchy process'. If you're unfamiliar with the example, 30 participants were asked to compare the relative consumption of drinks in the United States. For instance, they believed that coffee was consumedmuchmore than wine, but at the same rate as milk. The matrix derived from their answers was as follows:CoffeeWineTeaBeerSodaMilkWaterCoffee1952111/2Wine1/911/31/91/91/91/9Tea1/5311/31/41/31/9Beer1/29311/211/3Soda1942121/2Milk19311/211/3Water2993231The table below shows the relative consumption of drinks as computed using the AHP, given this matrix, together with theactualrelative consumption of drinks as obtained from U.S. Statistical Abstracts::exploding_head:CoffeeWineTeaBeerSodaMilkWaterAHP0.1770.0190.0420.1160.1900.1290.327Actual0.1800.0100.0400.1200.1800.1400.330We can recreate this analysis with AHPy using the following code:>>>drink_comparisons={('coffee','wine'):9,('coffee','tea'):5,('coffee','beer'):2,('coffee','soda'):1,('coffee','milk'):1,('coffee','water'):1/2,('wine','tea'):1/3,('wine','beer'):1/9,('wine','soda'):1/9,('wine','milk'):1/9,('wine','water'):1/9,('tea','beer'):1/3,('tea','soda'):1/4,('tea','milk'):1/3,('tea','water'):1/9,('beer','soda'):1/2,('beer','milk'):1,('beer','water'):1/3,('soda','milk'):2,('soda','water'):1/2,('milk','water'):1/3}>>>drinks=ahpy.Compare(name='Drinks',comparisons=drink_comparisons,precision=3,random_index='saaty')>>>print(drinks.target_weights){'water':0.327,'soda':0.19,'coffee':0.177,'milk':0.129,'beer':0.116,'tea':0.042,'wine':0.019}>>>print(drinks.consistency_ratio)0.022First, we create a dictionary of pairwise comparisons using the values from the matrix above.We then create aCompareobject, initializing it with a unique name and the dictionary we just made. We also change the precision and random index so that the results match those provided by Saaty.Finally, we print the Compare object's target weights and consistency ratio to see the results of our analysis.Brilliant!Choosing a leaderThis example can be foundin an appendix to the Wikipedia entry for AHP. The names have been changed in a nod tothe original saying, but the input comparison values remain the same.N.B.You may notice that in some cases AHPy's results will not match those on the Wikipedia page. This is not an error in AHPy's calculations, but rather a result ofthe method used to compute the values shown in the Wikipedia examples:You can duplicate this analysis at this online demonstration site...IMPORTANT: The demo site is designed for convenience, not accuracy. The priorities it returns may differ somewhat from those returned by rigorous AHP calculations.In this example, we'll be judging job candidates by their experience, education, charisma and age. Therefore, we need to compare each potential leader to the others, given each criterion...>>>experience_comparisons={('Moll','Nell'):1/4,('Moll','Sue'):4,('Nell','Sue'):9}>>>education_comparisons={('Moll','Nell'):3,('Moll','Sue'):1/5,('Nell','Sue'):1/7}>>>charisma_comparisons={('Moll','Nell'):5,('Moll','Sue'):9,('Nell','Sue'):4}>>>age_comparisons={('Moll','Nell'):1/3,('Moll','Sue'):5,('Nell','Sue'):9}...as well as compare the importance of each criterion to the others:>>>criteria_comparisons={('Experience','Education'):4,('Experience','Charisma'):3,('Experience','Age'):7,('Education','Charisma'):1/3,('Education','Age'):3,('Charisma','Age'):5}Before moving on, it's important to note that theorderof the elements that form the dictionaries' keys is meaningful. For example, using Saaty's scale, the comparison('Experience', 'Education'): 4means that "Experience ismoderately+ more important thanEducation."Now that we've created all of the necessary pairwise comparison dictionaries, we'll create their corresponding Compare objects and use the dictionaries as input:>>>experience=ahpy.Compare('Experience',experience_comparisons,precision=3,random_index='saaty')>>>education=ahpy.Compare('Education',education_comparisons,precision=3,random_index='saaty')>>>charisma=ahpy.Compare('Charisma',charisma_comparisons,precision=3,random_index='saaty')>>>age=ahpy.Compare('Age',age_comparisons,precision=3,random_index='saaty')>>>criteria=ahpy.Compare('Criteria',criteria_comparisons,precision=3,random_index='saaty')Notice that the names of the Experience, Education, Charisma and Age objects are repeated in thecriteria_comparisonsdictionary above. This is necessary in order to properly link the Compare objects together into a hierarchy, as shown next.In the final step, we need to link the Compare objects together into a hierarchy, such that Criteria is theparentobject and the other objects form itschildren:>>>criteria.add_children([experience,education,charisma,age])Now that the hierarchy represents the decision problem, we can print the target weights of the parent Criteria object to see the results of the analysis:>>>print(criteria.target_weights){'Nell':0.493,'Moll':0.358,'Sue':0.15}We can also print the local and global weights of the elements within any of the other Compare objects, as well as the consistency ratio of their comparisons:>>>print(experience.local_weights){'Nell':0.717,'Moll':0.217,'Sue':0.066}>>>print(experience.consistency_ratio)0.035>>>print(education.global_weights){'Sue':0.093,'Moll':0.024,'Nell':0.01}>>>print(education.consistency_ratio)0.062The global and local weights of the Compare objects themselves are likewise available:>>>print(experience.global_weight)0.548>>>print(education.local_weight)0.127Callingreport()on a Compare object provides a standard way to learn information about the object. In the code below, the variablereportcontains aPython dictionaryof important information, while theshow=Trueargument prints the same information to the console in JSON format:>>>report=criteria.report(show=True){"Criteria":{"global_weight":1.0,"local_weight":1.0,"target_weights":{"Nell":0.493,"Moll":0.358,"Sue":0.15},"elements":{"global_weights":{"Experience":0.548,"Charisma":0.27,"Education":0.127,"Age":0.056},"local_weights":{"Experience":0.548,"Charisma":0.27,"Education":0.127,"Age":0.056},"consistency_ratio":0.044}}}Purchasing a vehicleThis example can also be foundin an appendix to the Wikipedia entry for AHP. Like before, in some cases AHPy's results will not match those on the Wikipedia page, even though the input comparison values are identical. To reiterate, this is due to a difference in methods, not an error in AHPy.In this example, we'll be choosing a vehicle to purchase based on its cost, safety, style and capacity. Cost will further depend on a combination of the vehicle's purchase price, fuel costs, maintenance costs and resale value; capacity will depend on a combination of the vehicle's cargo and passenger capacity.First, we compare the high-level criteria to one another:>>>criteria_comparisons={('Cost','Safety'):3,('Cost','Style'):7,('Cost','Capacity'):3,('Safety','Style'):9,('Safety','Capacity'):1,('Style','Capacity'):1/7}If we create a Compare object for the criteria, we can view its report:>>>criteria=ahpy.Compare('Criteria',criteria_comparisons,precision=3)>>>report=criteria.report(show=True){"Criteria":{"global_weight":1.0,"local_weight":1.0,"target_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"elements":{"global_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"local_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"consistency_ratio":0.08}}}Next, we compare thesubcriteria of Cost to one another...>>>cost_comparisons={('Price','Fuel'):2,('Price','Maintenance'):5,('Price','Resale'):3,('Fuel','Maintenance'):2,('Fuel','Resale'):2,('Maintenance','Resale'):1/2}...as well as the subcriteria of Capacity:>>>capacity_comparisons={('Cargo','Passenger'):1/5}We also need to compare each of the potential vehicles to the others, given each criterion. We'll begin by building a list of all possible two-vehicle combinations:>>>importitertools>>>vehicles=('Accord Sedan','Accord Hybrid','Pilot','CR-V','Element','Odyssey')>>>vehicle_pairs=list(itertools.combinations(vehicles,2))>>>print(vehicle_pairs)[('Accord Sedan','Accord Hybrid'),('Accord Sedan','Pilot'),('Accord Sedan','CR-V'),('Accord Sedan','Element'),('Accord Sedan','Odyssey'),('Accord Hybrid','Pilot'),('Accord Hybrid','CR-V'),('Accord Hybrid','Element'),('Accord Hybrid','Odyssey'),('Pilot','CR-V'),('Pilot','Element'),('Pilot','Odyssey'),('CR-V','Element'),('CR-V','Odyssey'),('Element','Odyssey')]Then we can simply zip together the vehicle pairs and their pairwise comparison values for each criterion:>>>price_values=(9,9,1,1/2,5,1,1/9,1/9,1/7,1/9,1/9,1/7,1/2,5,6)>>>price_comparisons=dict(zip(vehicle_pairs,price_values))>>>print(price_comparisons){('Accord Sedan','Accord Hybrid'):9,('Accord Sedan','Pilot'):9,('Accord Sedan','CR-V'):1,('Accord Sedan','Element'):0.5,('Accord Sedan','Odyssey'):5,('Accord Hybrid','Pilot'):1,('Accord Hybrid','CR-V'):0.1111111111111111,('Accord Hybrid','Element'):0.1111111111111111,('Accord Hybrid','Odyssey'):0.14285714285714285,('Pilot','CR-V'):0.1111111111111111,('Pilot','Element'):0.1111111111111111,('Pilot','Odyssey'):0.14285714285714285,('CR-V','Element'):0.5,('CR-V','Odyssey'):5,('Element','Odyssey'):6}>>>safety_values=(1,5,7,9,1/3,5,7,9,1/3,2,9,1/8,2,1/8,1/9)>>>safety_comparisons=dict(zip(vehicle_pairs,safety_values))>>>passenger_values=(1,1/2,1,3,1/2,1/2,1,3,1/2,2,6,1,3,1/2,1/6)>>>passenger_comparisons=dict(zip(vehicle_pairs,passenger_values))>>>fuel_values=(1/1.13,1.41,1.15,1.24,1.19,1.59,1.3,1.4,1.35,1/1.23,1/1.14,1/1.18,1.08,1.04,1/1.04)>>>fuel_comparisons=dict(zip(vehicle_pairs,fuel_values))>>>resale_values=(3,4,1/2,2,2,2,1/5,1,1,1/6,1/2,1/2,4,4,1)>>>resale_comparisons=dict(zip(vehicle_pairs,resale_values))>>>maintenance_values=(1.5,4,4,4,5,4,4,4,5,1,1.2,1,1,3,2)>>>maintenance_comparisons=dict(zip(vehicle_pairs,maintenance_values))>>>style_values=(1,7,5,9,6,7,5,9,6,1/6,3,1/3,7,5,1/5)>>>style_comparisons=dict(zip(vehicle_pairs,style_values))>>>cargo_values=(1,1/2,1/2,1/2,1/3,1/2,1/2,1/2,1/3,1,1,1/2,1,1/2,1/2)>>>cargo_comparisons=dict(zip(vehicle_pairs,cargo_values))Now that we've created all of the necessary pairwise comparison dictionaries, we can create their corresponding Compare objects:>>>cost=ahpy.Compare('Cost',cost_comparisons,precision=3)>>>capacity=ahpy.Compare('Capacity',capacity_comparisons,precision=3)>>>price=ahpy.Compare('Price',price_comparisons,precision=3)>>>safety=ahpy.Compare('Safety',safety_comparisons,precision=3)>>>passenger=ahpy.Compare('Passenger',passenger_comparisons,precision=3)>>>fuel=ahpy.Compare('Fuel',fuel_comparisons,precision=3)>>>resale=ahpy.Compare('Resale',resale_comparisons,precision=3)>>>maintenance=ahpy.Compare('Maintenance',maintenance_comparisons,precision=3)>>>style=ahpy.Compare('Style',style_comparisons,precision=3)>>>cargo=ahpy.Compare('Cargo',cargo_comparisons,precision=3)The final step is to link all of the Compare objects into a hierarchy. First, we'll make the Price, Fuel, Maintenance and Resale objects the children of the Cost object...>>>cost.add_children([price,fuel,maintenance,resale])...and do the same to link the Cargo and Passenger objects to the Capacity object...>>>capacity.add_children([cargo,passenger])...then finally make the Cost, Safety, Style and Capacity objects the children of the Criteria object:>>>criteria.add_children([cost,safety,style,capacity])Now that the hierarchy represents the decision problem, we can print the target weights of thehighest levelCriteria object to see the results of the analysis:>>>print(criteria.target_weights){'Odyssey':0.219,'Accord Sedan':0.215,'CR-V':0.167,'Accord Hybrid':0.15,'Element':0.144,'Pilot':0.106}For detailed information about any of the Compare objects in the hierarchy, we can call that object'sreport()with theverbose=Trueargument:>>>report=criteria.report(show=True,verbose=True){"name":"Criteria","global_weight":1.0,"local_weight":1.0,"target_weights":{"Odyssey":0.219,"Accord Sedan":0.215,"CR-V":0.167,"Accord Hybrid":0.15,"Element":0.144,"Pilot":0.106},"elements":{"global_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"local_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"consistency_ratio":0.08,"random_index":"Donegan & Dodd","count":4,"names":["Cost","Safety","Style","Capacity"]},"children":{"count":4,"names":["Cost","Safety","Style","Capacity"]},"comparisons":{"count":6,"input":{"Cost, Safety":3,"Cost, Style":7,"Cost, Capacity":3,"Safety, Style":9,"Safety, Capacity":1,"Style, Capacity":0.14285714285714285},"computed":null}}Callingreport(show=True, verbose=True)on Compare objects at lower levels of the hierarchy will provide different information, depending on the level they're in:>>>report=cost.report(show=True,verbose=True){"name":"Cost","global_weight":0.51,"local_weight":0.51,"target_weights":null,"elements":{"global_weights":{"Price":0.249,"Fuel":0.129,"Resale":0.082,"Maintenance":0.051},"local_weights":{"Price":0.488,"Fuel":0.252,"Resale":0.161,"Maintenance":0.1},"consistency_ratio":0.016,"random_index":"Donegan & Dodd","count":4,"names":["Price","Fuel","Maintenance","Resale"]},"children":{"count":4,"names":["Price","Fuel","Resale","Maintenance"]},"comparisons":{"count":6,"input":{"Price, Fuel":2,"Price, Maintenance":5,"Price, Resale":3,"Fuel, Maintenance":2,"Fuel, Resale":2,"Maintenance, Resale":0.5},"computed":null}}>>>report=price.report(show=True,verbose=True){"name":"Price","global_weight":0.249,"local_weight":0.488,"target_weights":null,"elements":{"global_weights":{"Element":0.091,"Accord Sedan":0.061,"CR-V":0.061,"Odyssey":0.023,"Accord Hybrid":0.006,"Pilot":0.006},"local_weights":{"Element":0.366,"Accord Sedan":0.246,"CR-V":0.246,"Odyssey":0.093,"Accord Hybrid":0.025,"Pilot":0.025},"consistency_ratio":0.072,"random_index":"Donegan & Dodd","count":6,"names":["Accord Sedan","Accord Hybrid","Pilot","CR-V","Element","Odyssey"]},"children":null,"comparisons":{"count":15,"input":{"Accord Sedan, Accord Hybrid":9,"Accord Sedan, Pilot":9,"Accord Sedan, CR-V":1,"Accord Sedan, Element":0.5,"Accord Sedan, Odyssey":5,"Accord Hybrid, Pilot":1,"Accord Hybrid, CR-V":0.1111111111111111,"Accord Hybrid, Element":0.1111111111111111,"Accord Hybrid, Odyssey":0.14285714285714285,"Pilot, CR-V":0.1111111111111111,"Pilot, Element":0.1111111111111111,"Pilot, Odyssey":0.14285714285714285,"CR-V, Element":0.5,"CR-V, Odyssey":5,"Element, Odyssey":6},"computed":null}}Finally, callingreport(complete=True)on any Compare object in the hierarchy will return a dictionary containing a report foreveryCompare object in the hierarchy, with the keys of the dictionary being the names of the Compare objects:>>>complete_report=cargo.report(complete=True)>>>print([keyforkeyincomplete_report])['Criteria','Cost','Price','Fuel','Maintenance','Resale','Safety','Style','Capacity','Cargo','Passenger']>>>print(complete_report['Cargo']){'name':'Cargo','global_weight':0.0358,'local_weight':0.1667,'target_weights':None,'elements':{'global_weights':{'Odyssey':0.011,'Pilot':0.006,'CR-V':0.006,'Element':0.006,'Accord Sedan':0.003,'Accord Hybrid':0.003},'local_weights':{'Odyssey':0.311,'Pilot':0.17,'CR-V':0.17,'Element':0.17,'Accord Sedan':0.089,'Accord Hybrid':0.089},'consistency_ratio':0.002}}>>>print(complete_report['Criteria']['target_weights']){'Odyssey':0.219,'Accord Sedan':0.215,'CR-V':0.167,'Accord Hybrid':0.15,'Element':0.144,'Pilot':0.106}Callingreport(complete=True, verbose=True)will return a similar dictionary, but with the detailed version of the reports.>>>complete_report=style.report(complete=True,verbose=True)>>>print(complete_report['Price']['comparisons']['count'])15We could also print all of the reports to the console with theshow=Trueargument.Purchasing a vehicle reprised: normalized weights and the Compose classAfter reading through the explanation of thevehicle decision problem on Wikipedia, you may have wondered whether the data used to represent purely numeric criteria (such as passenger capacity) could be useddirectlywhen comparing the vehicles to one another, rather than requiring tranformation into judgments of "intensity." In this example, we'll solve the same decision problem as before, except now we'll normalize the measured values for passenger capacity, fuel costs, resale value and cargo capacity in order to arrive at a different set of weights for these criteria.We'll also use aComposeobject to structure the decision problem. The Compose object allows us to work with an abstract representation of the problem hierarchy, rather than build it dynamically with code, which is valuable when we're not using AHPy in an interactive setting. To use the Compose object, we'll need to first add the comparison information, then the hierarchy,in that order. But more on that later.Using the list of vehicles from the previous example, we'll first zip together the vehicles and their measured values, then create a Compare object for each of our normalized criteria:>>>passenger_measured_values=(5,5,8,5,4,8)>>>passenger_data=dict(zip(vehicles,passenger_measured_values))>>>print(passenger_data){'Accord Sedan':5,'Accord Hybrid':5,'Pilot':8,'CR-V':5,'Element':4,'Odyssey':8}>>>passenger_normalized=ahp.Compare('Passenger',passenger_data,precision=3)>>>fuel_measured_values=(31,35,22,27,25,26)>>>fuel_data=dict(zip(vehicles,fuel_measured_values))>>>fuel_normalized=ahp.Compare('Fuel',fuel_data,precision=3)>>>resale_measured_values=(0.52,0.46,0.44,0.55,0.48,0.48)>>>resale_data=dict(zip(vehicles,resale_measured_values))>>>resale_normalized=ahp.Compare('Resale',resale_data,precision=3)>>>cargo_measured_values=(14,14,87.6,72.9,74.6,147.4)>>>cargo_data=dict(zip(vehicles,cargo_measured_values))>>>cargo_normalized=ahp.Compare('Cargo',cargo_data,precision=3)Let's print the normalized local weights of the new Passenger object to compare them to the local weights in the previous example:>>>print(passenger_normalized.local_weights){'Pilot':0.229,'Odyssey':0.229,'Accord Sedan':0.143,'Accord Hybrid':0.143,'CR-V':0.143,'Element':0.114}>>>print(passenger.local_weights){'Accord Sedan':0.493,'Accord Hybrid':0.197,'Odyssey':0.113,'Element':0.091,'CR-V':0.057,'Pilot':0.049}When we use the measured values directly, we see that the rankings for the vehicles are different than they were before. Whether this will affect thesynthesizedrankings of the target variables remains to be seen, however.We next create a Compose object and begin to add the comparison information:>>>compose=ahpy.Compose()>>>compose.add_comparisons([passenger_normalized,fuel_normalized,resale_normalized,cargo_normalized])We can add comparison information to the Compose object in a few different ways. As shown above, we can provide a list of Compare objects; we can also provide them one at a time or stored in a tuple. Using Compare objects from our previous example:>>>compose.add_comparisons(cost)>>>compose.add_comparisons((safety,style,capacity))We can even treat the Compose object like a Compare object and add the data directly. Again using code from the previous example:>>>compose.add_comparisons('Price',price_comparisons,precision=3)Finally, we can provide an ordered list or tuple containing the data needed to construct a Compare object:>>>comparisons=[('Maintenance',maintenance_comparisons,3),('Criteria',criteria_comparisons)]>>>compose.add_comparisons(comparisons)Now that all of the comparison information has been added, we next need to create the hierarchy and add it to the Compose object. A hierarchy is simply a dictionary in which the keys are the names ofparentCompare objects and the values are lists of the names of theirchildren:>>>hierarchy={'Criteria':['Cost','Safety','Style','Capacity'],'Cost':['Price','Fuel','Resale','Maintenance'],'Capacity':['Passenger','Cargo']}>>>compose.add_hierarchy(hierarchy)With these two steps complete, we can now view the synthesized results of the analysis.We view a report for a Compose object in the same way we do for a Compare object. The only difference is that the Compose object displays a complete report by default; in order to view the report of a single Compare object in the hierarchy, we need to specify its name:>>>criteria_report=compose.report('Criteria',show=True){"name":"Criteria","global_weight":1.0,"local_weight":1.0,"target_weights":{"Odyssey":0.218,"Accord Sedan":0.21,"Element":0.161,"Accord Hybrid":0.154,"CR-V":0.149,"Pilot":0.108},"elements":{"global_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"local_weights":{"Cost":0.51,"Safety":0.234,"Capacity":0.215,"Style":0.041},"consistency_ratio":0.08}}We can access the public properties of the comparison information we've added to the Compose object using either dot or bracket notation:>>>print(compose.Criteria.target_weights){'Odyssey':0.218,'Accord Sedan':0.21,'Element':0.161,'Accord Hybrid':0.154,'CR-V':0.149,'Pilot':0.108}>>>print(compose['Resale']['local_weights']){'CR-V':0.188,'Accord Sedan':0.177,'Element':0.164,'Odyssey':0.164,'Accord Hybrid':0.157,'Pilot':0.15}We can see that normalizing the numeric criteria leads to a slightly different set of target weights, though the Odyssey and the Accord Sedan remain the top two vehicles to consider for purchase.DetailsKeep reading to learn the details of the AHPy library's API...The Compare ClassThe Compare class computes the weights and consistency ratio of a positive reciprocal matrix, created using an input dictionary of pairwise comparison values. Optimal values are computed for anymissing pairwise comparisons. Compare objects can also belinked together to form a hierarchyrepresenting the decision problem: the target weights of the problem elements are then derived by synthesizing all levels of the hierarchy.Compare(name, comparisons, precision=4, random_index='dd', iterations=100, tolerance=0.0001, cr=True)name:str (required), the name of the Compare objectThis property is used to link a child object to its parent and must be uniquecomparisons:dict (required), the elements and values to be compared, provided in one of two forms:A dictionary of pairwise comparisons, in which each key is a tuple of two elements and each value is their pairwise comparison value{('a', 'b'): 3, ('b', 'c'): 2, ('a', 'c'): 5}The order of the elements in the key matters: the comparison('a', 'b'): 3means "a is moderately more important than b"A dictionary of measured values, in which each key is a single element and each value is that element's measured value{'a': 1.2, 'b': 2.3, 'c': 3.4}Given this form, AHPy will automatically create consistent, normalized target weightsprecision:int, the number of decimal places to take into account when computing both the target weights and the consistency ratio of the Compare objectThe default precision value is 4random_index:'dd'or'saaty', the set of random index estimates used to compute the Compare object's consistency ratio'dd' supports the computation of consistency ratios for matrices less than or equal to 100 × 100 in size and uses estimates from:Donegan, H.A. and Dodd, F.J., 'A Note on Saaty's Random Indexes,'Mathematical and Computer Modelling, 15:10, 1991, pp. 135-137 (DOI:10.1016/0895-7177(91)90098-R)'saaty' supports the computation of consistency ratios for matrices less than or equal to 15 × 15 in size and uses estimates from:Saaty, T.,Theory And Applications Of The Analytic Network Process, Pittsburgh: RWS Publications, 2005, p. 31The default random index is 'dd'iterations:int, the stopping criterion for the algorithm used to compute the Compare object's target weightsIf target weights have not been determined after this number of iterations, the algorithm stops and the last principal eigenvector to be computed is used as the target weightsThe default number of iterations is 100tolerance:float, the stopping criterion for the cycling coordinates algorithm used to compute the optimal value of missing pairwise comparisonsThe algorithm stops when the difference between the norms of two cycles of coordinates is less than this valueThe default tolerance value is 0.0001cr:bool, whether to compute the target weights' consistency ratioSetcr=Falseto compute the target weights of a matrix when a consistency ratio cannot be determined due to the size of the matrixThe default value is TrueThe properties used to initialize the Compare class are intended to be accessed directly, along with a few others:Compare.global_weight:float, the global weight of the Compare object within the hierarchyCompare.local_weight:float, the local weight of the Compare object within the hierarchyCompare.global_weights:dict, the global weights of the Compare object's elements; each key is an element and each value is that element's computed global weight{'a': 0.25, 'b': 0.25}Compare.local_weights:dict, the local weights of the Compare object's elements; each key is an element and each value is that element's computed local weight{'a': 0.5, 'b': 0.5}Compare.target_weights:dict, the target weights of the elements in the lowest level of the hierarchy; each key is an element and each value is that element's computed target weight;if the global weight of the Compare object is less than 1.0, the value will beNone{'a': 0.5, 'b': 0.5}Compare.consistency_ratio:float, the consistency ratio of the Compare object's pairwise comparisonsCompare.add_children()Compare objects can be linked together to form a hierarchy representing the decision problem. To link Compare objects together into a hierarchy, calladd_children()on the Compare object intended to form theupperlevel (theparent) and include as an argument a list or tuple of one or more Compare objects intended to form itslowerlevel (thechildren).In order to properly synthesize the levels of the hierarchy, thenameof each child object MUST appear as an element in its parent object's inputcomparisonsdictionary.Compare.add_children(children)children:listortuple (required), the Compare objects that will form the lower level of the current Compare object>>>child1=ahpy.Compare(name='child1',...)>>>child2=ahpy.Compare(name='child2',...)>>>parent=ahpy.Compare(name='parent',comparisons={('child1','child2'):5})>>>parent.add_children([child1,child2])The precision of the target weights is updated as the hierarchy is constructed: each timeadd_children()is called, the precision of the target weights is set to equal that of the Compare object with the lowest precision in the hierarchy. Because lower precision propagates up through the hierarchy,the target weights will always have the same level of precision as the hierarchy's least precise Compare object. This also means that it is possible for the precision of a Compare object's target weights to be different from the precision of its local and global weights.Compare.report()A standard report on the details of a Compare object is available. To return the report as a dictionary, callreport()on the Compare object; to simultaneously print the information to the console in JSON format, setshow=True. The report is available in two levels of detail; to return the most detailed report, setverbose=True.Compare.report(complete=False, show=False, verbose=False)complete:bool, whether to return a report for every Compare object in the hierarchyThis returns a dictionary of reports, with the keys of the dictionary being the names of the Compare objects{'a': {'name': 'a', ...}, 'b': {'name': 'b', ...}}The default value is Falseshow:bool, whether to print the report to the console in JSON formatThe default value is Falseverbose:bool, whether to include full details of the Compare object in the reportThe default value is FalseThe keys of the report take the following form:name:str, the name of the Compare objectglobal_weight:float, the global weight of the Compare object within the hierarchylocal_weight:float, the local weight of the Compare object within the hierarchytarget_weights:dict, the target weights of the elements in the lowest level of the hierarchy; each key is an element and each value is that element's computed target weight{'a': 0.5, 'b': 0.5}If the global weight of the Compare object is less than 1.0, the value will beNoneelements:dict, information regarding the elements compared by the Compare objectglobal_weights:dict, the global weights of the Compare object's elements; each key is an element and each value is that element's computed global weight{'a': 0.25, 'b': 0.25}local_weights:dict, the local weights of the Compare object's elements; each key is an element and each value is that element's computed local weight{'a': 0.5, 'b': 0.5}consistency_ratio:float, the consistency ratio of the Compare object's pairwise comparisonsThe remaining dictionary keys are only displayed whenverbose=True:random_index:'Donegan & Dodd' or 'Saaty', the random index used to compute the consistency ratiocount:int, the number of elements compared by the Compare objectnames:list, the names of the elements compared by the Compare objectchildren:dict, the children of the Compare objectcount:int, the number of the Compare object's childrennames:list, the names of the Compare object's childrenIf the Compare object has no children, the value will beNonecomparisons:dict, the comparisons of the Compare objectcount:int, the number of comparisons made by the Compare object,not counting reciprocal comparisonsinput:dict, the comparisons input to the Compare object; this is identical to the inputcomparisonsdictionarycomputed:dict, the comparisons computed by the Compare object; each key is a tuple of two elements and each value is their computed pairwise comparison value{('c', 'd'): 0.730297106886979}, ...}If the Compare object has no computed comparisons, the value will beNoneThe Compose ClassThe Compose class can store and structure all of the information making up a decision problem. After firstadding comparison informationto the object, thenadding the problem hierarchy, the analysis results of the multiple different Compare objects can be accessed through the single Compose object.Compose()After adding all necessary information, the public properties of any stored Compare object can be accessed directly through the Compose object using either dot or bracket notation:>>>my_compose_object.a.global_weights>>>my_compose_object['a']['global_weights']Compose.add_comparisons()The comparison information of a decision problem can be added to a Compose object in any of the several ways listed below. Always add comparison informationbeforeadding the problem hierarchy.Compose.add_comparisons(item, comparisons=None, precision=4, random_index='dd', iterations=100, tolerance=0.0001, cr=True)item:Compare object, list or tuple, or string (required), this argument allows for multiple input types:A single Compare objectCompare('a', comparisons=a, ...)A list or tuple of Compare objects[Compare('a', ...), Compare('b', ...)]The data necessary to create a Compare object'a', comparisons=a, precision=3, ...The method signature mimics that of the Compare class for this reasonA nested list or tuple of the data necessary to create a Compare object(('a', a, 3, ...), ('b', b, 3, ...))All other arguments are identical to those of theCompare class.Compose.add_hierarchy()The Compose class uses an abstract representation of the problem hierarchy to automatically link its Compare objects together. When a hierarchy is added, the elements of the decision problem are synthesized and the analysis results are immediately available for use or viewing.Compose.add_hierarchy()should only be called AFTER all comparison information has been added to the Compose object.Compose.add_hierarchy(hierarchy)hierarchy:dict, a representation of the hierarchy as a dictionary, in which the keys are the names of parent Compare objects and the values are lists of the names of their children{'a': ['b', 'c'], 'b': ['d', 'e']}Compose.report()The standard report available for a Compare object can be accessed through the Compose object. Callingreport()on a Compose object is equivalent to callingreport(complete=True)on a Compare object and will return a dictionary of all the reports within the hierarchy; callingreport(name='a')on a Compose object is equivalent to callinga.report()on the named Compare object.Compose.report(name=None, show=False, verbose=False)name:str, the name of a Compare object report to return; if None, returns a dictionary of reports, with the keys of the dictionary being the names of the Compare objects in the hierarchy{'a': {'name': 'a', ...}, 'b': {'name': 'b', ...}}The default value is NoneAll other arguments are identical to theCompare class'sreport()method.A Note on WeightsCompare objects compute up to three kinds of weights for their elements: global weights, local weights and target weights.
Compare objects also compute their own global and local weight, given their parent.Globalweights display the computed weights of a Compare object's elementsdependent onthat object's global weight within the current hierarchyGlobal weights are derived by multiplying the local weights of the elements within a Compare object by that object'sownglobal weight in the current hierarchyLocalweights display the computed weights of a Compare object's elementsindependent ofthat object's global weight within the current hierarchyThe local weights of the elements within a Compare object will always (approximately) sum to 1.0Targetweights display the synthesized weights of the problem elements described in thelowest levelof the current hierarchyTarget weights are only available from the Compare object at the highest level of the hierarchy (i.e.the only Compare object without a parent)N.B.A Compare object that does not have a parent will have identical global and local weights; a Compare object that has neither a parent nor children will have identical global, local and target weights.In many instances, the sum of the local or target weights of a Compare object will not equal 1.0exactly. This is due to rounding. If it's critical that the sum of the weights equals 1.0, it's recommended to simply divide the weights by their cumulative sum:x = x / np.sum(x). Note, however, that the resulting values will contain a false level of precision, given their inputs.Missing Pairwise ComparisonsWhen a Compare object is initialized, the elements forming the keys of the inputcomparisonsdictionary are permuted. Permutations of elements that do not contain a value within the inputcomparisonsdictionary are then optimally solved for using the cyclic coordinates algorithm described in:Bozóki, S., Fülöp, J. and Rónyai, L., 'On optimal completion of incomplete pairwise comparison matrices,'Mathematical and Computer Modelling, 52:1–2, 2010, pp. 318-333 (DOI:10.1016/j.mcm.2010.02.047)As the paper notes, "The number ofnecessarypairwise comparisons ... depends on the characteristics of the real decision problem and provides an exciting topic of future research" (29). In other words, don't rely on the algorithm to fill in a comparison dictionary that has a large number of missing values: it certainly might, but it also very well might not.Caveat emptor!The example below demonstrates this functionality of AHPy using the following matrix:abcda1152b1134c1/51/313/4d1/21/44/31We'll first compute the target weights and consistency ratio for the complete matrix, then repeat the process after removing the(c, d)comparison marked in bold. We can view the computed value in the Compare object's detailed report:>>>comparisons={('a','b'):1,('a','c'):5,('a','d'):2,('b','c'):3,('b','d'):4,('c','d'):3/4}>>>complete=ahpy.Compare('Complete',comparisons)>>>print(complete.target_weights){'b':0.3917,'a':0.3742,'d':0.1349,'c':0.0991}>>>print(complete.consistency_ratio)0.0372>>>delcomparisons[('c','d')]>>>missing_cd=ahpy.Compare('Missing_CD',comparisons)>>>print(missing_cd.target_weights){'b':0.392,'a':0.3738,'d':0.1357,'c':0.0985}>>>print(missing_cd.consistency_ratio)0.0372>>>report=missing_cd.report(verbose=True)>>>print(report['comparisons']['computed']){('c','d'):0.7302971068355002}Development and TestingTo set up a development environment and run the included tests, you can use the following commands:virtualenv .venv
source .venv/bin/activate
python setup.py develop
pip install pytest
pytest |
ahqapiclient | # DEPRECATED! Please use the information at https://[yourname].abusehq.net/api/v1/docs/ and use an http client of your liking for accessing the API directly# AbuseHQ API Client## About**ahqapiclient** is a library which reflects the AbuseHQ API on client side.## Usageimport Client from ahqapiclient### Setupendpoint = {"auth_method": "JWT","auth_options": {"token": "<YOUR_API_KEY>"},"url": "https://<yourcompany>.abusehq.net/api/v1"}api_client = Client(endpoint)### Usage#### Get a casecase = api_client.case.get_case('case_id')#### Perform a transitionapi_client.case.trigger_transition('case_id', 'transition_id') |
ahr-distributions | No description available on PyPI. |
ahrefs-api-python | No description available on PyPI. |
ahrens-lab-to-nwb | ahrens-lab-to-nwbNWB conversion scripts for theAhrens labdata to theNeurodata Without Bordersdata format.Clone and installTo run the conversion some basic machinery is needed:python, git and pip. For most users, we recommend you to installconda(installation instructions) as it contains all the required machinery in a single and simple install. If your system is windows you might also need to installgit(installation instructions) to interact with this repository.From a terminal (note that conda should install one in your system) you can do the following:git clone https://github.com/catalystneuro/ahrens-lab-to-nwb
cd ahrens-lab-to-nwb
conda env create --file make_env.yml
conda activate ahrens-lab-to-nwb-envThis create aconda environmentwhich isolates the conversion from your system. We recommend that you run all your conversion related tasks and analysis from that environment to minimize the intereference of this code with your own system.Alternatively, if you want to avoid conda altogether (for example if you use another virtual environment tool) you can install the repository with the following commands using only pip:git clone https://github.com/catalystneuro/ahrens-lab-to-nwb
cd ahrens-lab-to-nwb
pip install -e .Note:
both of the methods above install the repository ineditable modeRepository structureEach conversion is organized in a directory of its own in thesrcdirectory:ahrens-lab-to-nwb/
├── LICENSE
├── make_env.yml
├── pyproject.toml
├── README.md
├── requirements.txt
├── setup.py
└── src
├── ahrens_lab_to_nwb
│ ├── conversion_directory_1
│ └── yu_mu_cell_2019`
│ ├── yu_mu_cell_2019behaviorinterface.py
│ ├── yu_mu_cell_2019_convert_script.py
│ ├── yu_mu_cell_2019_metadata.yml
│ ├── yu_mu_cell_2019nwbconverter.py
│ ├── yu_mu_cell_2019_requirements.txt
│ ├── yu_mu_cell_2019_notes.md
│ └── __init__.py
│ ├── conversion_directory_b
└── __init__.pyFor example, for the conversionyu_mu_cell_2019you can find a directory located insrc/ahrens-lab-to-nwb/yu_mu_cell_2019. Inside each conversion directory you can find the following files:yu_mu_cell_2019_convert_script.py: this is the cemtral script that you must run in order to perform the full conversion.yu_mu_cell_2019_requirements.txt: dependencies specific to this conversion specifically.yu_mu_cell_2019_metadata.yml: metadata in yaml format for this specific conversion.yu_mu_cell_2019behaviorinterface.py: the behavior interface. Usually ad-hoc for each conversion.yu_mu_cell_2019nwbconverter.py: the place where theNWBConverterclass is defined.yu_mu_cell_2019_notes.md: notes and comments concerning this specific conversion.The directory might contain other files that are necessary for the conversion but those are the central ones.Running a specific conversionTo run a specific conversion, you might need to install first some conversion specific dependencies that are located in each conversion directory:pip install -r src/ahrens_lab_to_nwb/yu_mu_cell_2019/yu_mu_cell_2019_requirements.txtYou can run a specific conversion with the following command:python src/ahrens_lab_to_nwb/yu_mu_cell_2019/yu_mu_cell_2019_conversion_script.py |
ahri | Failed to fetch description. HTTP Status Code: 404 |
ahri-mime | Ahri - ahri_mimeGithubContact [email protected] to useinstallpipinstallahri_mimeimportfromahri_mimeimportget_ext,get_exts,get_type,get_typesThe ahri_mime hasattr:attributetypeexplainMIMEfileincludeEXT_TO_TYPEandTYPE_TO_EXTEXT_TO_TYPEdictkey isExtension, value isTypeTYPE_TO_EXTdictkey isType, value isExtensionget_extfunctiongetExtensionby typeget_extsfunctionget allExtensions by typeget_typefunctiongetTypeby extget_typesfunctiongetTypes by extExamplefromahri_mimeimportget_ext,get_exts,get_type,get_typesdefhandle():print(get_ext('x-world/x-3dmf'))print(get_exts('x-world/x-3dmf',dot=False))print(get_type('docx',dot=False))print(get_types('.docx'))if__name__=="__main__":handle().3dm['3dm','3dmf','qd3','qd3d']application/vnd.openxmlformats-officedocument.wordprocessingml.document['application/vnd.openxmlformats-officedocument.wordprocessingml.document'] |
ahrli-huobi-client | No description available on PyPI. |
ahs8p | AHRS-8This repository contains the SRMASV AHRS8 library.To install just run the following:python setup.py installThe following module contains the following:IMU class for library to interface AHRS-8PSerial Auto Detection to detect IMU's serial port on OS |
ahsay | UNKNOWN |
ahs-csp-si-wwpd | No description available on PyPI. |
ahserver | ahserverahserver is a http(s) server base on aiohttp asynchronous framework.ahserver capabilities:user authorization and authentication supporthttps supportprocessor for registed file typepre-defined variables and function can be called by processorsmultiple database connection and connection poola easy way to wrap SQLconfigure data from json file stored at ./conf/config.jsonupload file auto save under config.filesroot folderi18n supportprocessors include:'dspy' file subffix by '.dspy', is process as a python script'tmpl' files subffix by '.tmpl', is process as a template'md' files subffix by '.md', is process as a markdown file'xlsxds' files subffix by '.xlsxds' is process as a data source from xlsx file'sqlds' files subffixed by '.sqlds' is process as a data source from database via a sql commandRequirementssee requirements.txtpyutilssqlorHow to usesee ah.pyfrom ahserver.configuredServer import ConfiguredServer
if __name__ == '__main__':
server = ConfiguredServer()
server.run()Folder structureapp|-ah.py|--ahserver|-conf|-config.json|-i18nConfiguration file contentahserver using json file format in its configuration, the following is a sample:{
"databases":{
"aiocfae":{
"driver":"aiomysql",
"async_mode":true,
"coding":"utf8",
"dbname":"cfae",
"kwargs":{
"user":"test",
"db":"cfae",
"password":"test123",
"host":"localhost"
}
},
"cfae":{
"driver":"mysql.connector",
"coding":"utf8",
"dbname":"cfae",
"kwargs":{
"user":"test",
"db":"cfae",
"password":"test123",
"host":"localhost"
}
}
},
"website":{
"paths":[
["$[workdir]$/../usedpkgs/antd","/antd"],
["$[workdir]$/../wolon",""]
],
"host":"0.0.0.0",
"port":8080,
"coding":"utf-8",
"ssl":{
"crtfile":"$[workdir]$/conf/www.xxx.com.pem",
"keyfile":"$[workdir]$/conf/www.xxx.com.key"
},
"indexes":[
"index.html",
"index.tmpl",
"index.dspy",
"index.md"
],
"visualcoding":{
"default_root":"/samples/vc/test",
"userroot":{
"ymq":"/samples/vc/ymq",
"root":"/samples/vc/root"
},
"jrjpath":"/samples/vc/default"
},
"processors":[
[".xlsxds","xlsxds"],
[".sqlds","sqlds"],
[".tmpl.js","tmpl"],
[".tmpl.css","tmpl"],
[".html.tmpl","tmpl"],
[".tmpl","tmpl"],
[".dspy","dspy"],
[".md","md"]
]
},
"langMapping":{
"zh-Hans-CN":"zh-cn",
"zh-CN":"zh-cn",
"en-us":"en",
"en-US":"en"
}
}database configurationthe ahserver using packages for database engines are:oracle:cx_Oraclemysql:mysql-connectorpostgresql:psycopg2sql server:pymssqlhowever, you can change it, but must change the "driver" value the the package name in the database connection definition.in the databases section in config.json, you can define one or more database connection, and also, it support many database engine, just as ORACLE,mysql,postgreSQL.
define a database connnect you need follow the following json format.mysql or mariadb"metadb":{
"driver":"mysql.connector",
"coding":"utf8",
"dbname":"sampledb",
"kwargs":{
"user":"user1",
"db":"sampledb",
"password":"user123",
"host":"localhost"
}
}the dbname and "db" should the same, which is the database name in mysql databaseOracle"db_ora":{
"driver":"cx_Oracle",
"coding":"utf8",
"dbname":sampledb",
"kwargs":{
"user":"user1",
"host":"localhost",
"dsn":"10.0.185.137:1521/SAMPLEDB"
}
}SQL Server"db_mssql":{
"driver":"pymssql",
"coding":"utf8",
"dbname":"sampledb",
"kwargs":{
"user":"user1",
"database":"sampledb",
"password":"user123",
"server":"localhost",
"port":1433,
"charset":"utf8"
}
}PostgreSQL"db_pg":{
"driver":"psycopg2",
"dbname":"testdb",
"coding":"utf8",
"kwargs":{
"database":"testdb",
"user":"postgres",
"password":"pass123",
"host":"127.0.0.1",
"port":"5432"
}
}https supportIn config.json file, config.website.ssl need to set(see above)website configurationpathsahserver can serve its contents (static file, dynamic contents render by its processors) resided on difference folders on the server file system.
ahserver finds a content identified by http url in order the of the paths specified by "paths" lists inside "website" definition of config.json fileprocessorsall the prcessors ahserver using, must be listed here.hostby defaualt, '0.0.0.0'portby default, 8080codingahserver recomments using 'utf-8'langMappingthe browsers will send 'Accept-Language' are difference even if the same language. so ahserver using a "langMapping" definition to mapping multiple browser lang to same i18n fileinternationalahserver using MiniI18N in appPublic modules in pyutils package to implements i18n supportit will search translate text in ms* txt file in folder named by language name inside i18n folder in workdir folder, workdir is the folder where the ahserver program resided or identified by command line paraments.performanceTo be list hereenvironment for processorsWhen coding in processors, ahserver provide some environment stuff for build apllication, there are modules, functions, classes and variablesmodules:timedatetimerandomjsonfunctions:configValueisNoneintstrfloattypestr2datestr2datetimecurDatetimeuuidrunSQLrunSQLPagingrunSQLIteratorrunSQLResultFieldsgetTablesgetTableFieldsgetTablePrimaryKeygetTableForignKeysfolderInfoabspathrequest2nsCRUDdata2xlsxxlsxdataopenfilei18ni18nDictabsurlabspathrequest2nsvariablesresourceterminalTypeclassesArgsConvert |
ahservo | No description available on PyPI. |
ahsoka | Failed to fetch description. HTTP Status Code: 404 |
ahs-orchestrator-client-python | No description provided (generated by Openapi Generatorhttps://github.com/openapitools/openapi-generator) # noqa: E501 |
ahstu-sign-up | 安科填报自动化脚本填报过程自动化,适用于安徽科技学院某填报系统,摆脱被班委催填报的尴尬,以造福劳苦大众允许自定义填报信息支持多人填报(需要相应配置文件)支持Windows, Linux与人工填写几经无差别使用方法Windows用户提供一键脚本, 具体使用方法参见help.txt文件Linux用户需自建python虚拟环境(提供requirements.txt)使用须知以下情况均不负责因使用本脚本而被查处并记过因使用本脚本而造成填写内容不为实际信息(有bug在issue提出)因使用本脚本而造成本人实质性的损失本脚本制作本意仅为方便日常生活,减少重复工作的目的。个人应在保证自身身体健康的情况下使用,积极配合学校防疫工作,时刻检查自身身体情况,若察觉到异常情况,请关停该脚本,认真填写填报信息并上报。请低调使用 |
ahsunpdf | No description available on PyPI. |
ahtest-distributions | No description available on PyPI. |
ahttp | The Instructions of ahttp athttps://github.com/web-trump/ahttp.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.