package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
ampform
AmpFormAmpForm is a Python library of spin formalisms and dynamics with which you can automatically formulate symbolic amplitude models for Partial Wave Analysis. The resulting amplitude models are formulated withSymPy(a Computer Algebra System). This not only makes it easy to inspect and visualize the resulting amplitude models, but also means the amplitude models can be used as templates for faster computational back-ends (seeTensorWaves)!Visitampform.rtfd.iofor several usage examples. For an overview ofupcoming releases and planned functionality, seehere.Available featuresAutomatic amplitude model buildingConvert state transition graphs fromQRulesto an amplitude model that ismathematically expressedwithSymPyand can beconverted to any backend(seeTensorWaves).Spin formalismsHelicity formalismCanonical formalismSpin alignmentfor generic, multi-body decays that feature different decay topologiesDynamicsRelativistic Breit-Wigner, optionally with form factors and/orenergy-dependent widthSymbolicK-matrixfor an arbitrary number of poles and channelsSymbolicP-vectorfor an arbitrary number of poles and channelsContributeSeeCONTRIBUTING.md
ampform-dpd
Symbolic Dalitz-Plot DecompositionThis repository is a (temporary) extension ofAmpFormand provides a symbolic implementation of Dalitz-plot decomposition (10.1103/PhysRevD.101.034033) withSymPy. It has been extracted from theComPWA/polarimetryrepository, which is not yet public.Installation instructions can be foundhere.
ampgo
ampgoGlobal optimization via adaptive memory programming with a scipy.optimize like API.InstallationpipinstallampgoExample: Minimizing the six-hump camelback function in ampgoimportampgodefobj(x):"""Six-hump camelback function"""x1=x[0]x2=x[1]f=(4-2.1*(x1*x1)+(x1*x1*x1*x1)/3.0)*(x1*x1)+x1*x2+(-4+4*(x2*x2))*(x2*x2)returnfbounds=[(-5,5),(-5,5)]res=ampgo.ampgo(obj,bounds)print(res.x)print(res.fun)DocumentationFor the full API reference check out theonline documentation.HistoryCoded by Andrea Gavana,[email protected]. Original hosted athttps://code.google.com/p/ampgo/. Made available under the MIT licence. Usage and installation modified by Daniel Schmitz.Differences compared to original version:Support all of SciPy's local minimizersReturn a OptimizeResult class like SciPy's global optimizersRequire bounds instead of starting pointJacobian and Hessian supportSupport all of NLopt's local minimizers (requiressimplenlopt)Drop support for OpenOpt solvers as OpenOpt has been stale for several years
ampharos
Lightweight Pokemon Database for use withDonphanORM.
amphetype
AmphetypeAmphetype is an advanced typing practice program.Features include:Type your favorite novel!One of the core ideas behind Amphetype was to not just use boring "stock texts" for typing practice, but to allow me to practice on texts that I actually want to read. So one feature is the ability to import whole novels (for example fromProject Gutenberg) and have Amphetype automatically generate bite-sized lessons from the text. For example, when I was learning theColemakkeyboard layout, I typedThe Metamorphosisby Franz Kafka!Typing statistics.It provides the basic typing statistics (accuracy and WPM) across keys, trigrams, and words. It also tries to identify parts that break your flow and what impact these "viscous" combinations have on your typing speed overall. It also shows a graphs of progress over time.Generate lessons from past statistics.Amphetype features an advanced lesson generator where you can generate texts based on your past performance. Generate blocks of text to target practice your slowest words, trigrams, or keys!Layout-agnostic.Amphetype doesn't carewhatkeyboard or layout you use, it only looks athowyou use it.Highly customizable in functionality, looks, and feel.InstallingGNU/LinuxEasiest is to install viapip[^1] orpipx[^2]:$pipinstall--useramphetypeNote that Amphetype requires at least Python 3.6+.The most recent version (1.2.x) on PyPi could be considered BETA as it features a major update and overhaul and a new typing widget. You can specify the old version withamphetype==1.0.1.WindowsCheck out the releases for an installer.Making Windows installations is a bit painful for me since I don't have regular access to Windows for testing. As a last resort you could try usingLinux in Windows.MacOS... nor do I have access to a Mac, so here I will pretty much just copy instructions out of Google, because I have no experience.(If you're an experienced user, the Linux instructions above are probably enough for you.)First installHomebrewif you don't have it.Then (in the terminal app) install Python 3 if you don't have it:$brewinstallpythonI've encountered at least one user who had to manually installpyqt5:$brewinstallpyqt5Not sure if this is necessary, or indeed if it installs its own Python, thus making step #2 redundant.Either way, hopefully you will now either:Have a command calledpip(orpip3?), so use that like in the Linux instructions:$pipinstall--useramphetypeOR, if not, you should at least have Python so you could try:$python3-mpipinstallamphetype(The command might bepython3.9orpython3.10orpython.)Run the program:$amphetype(I'm not sure if it shows up in Finder?)If a OSX dev is willing to write better and less confusing instructions, let me know!Resurrected?Yes, I originally made this program 12 years agohere. I've updated it somewhat and implemented some features that were requested back then, and upgraded the code to use Python 3 and Qt5 (instead of Python 2 and Qt4).Google Code has gone read-only though, so I am unable to do anything about what's shown there.Other LinksReview of (old) Amphetype:https://forum.colemak.com/topic/2201-training-with-amphetype/My own inspiration for switching to a different keyboard layout and why I made Amphetype:http://steve-yegge.blogspot.com/2008/09/programmings-dirtiest-little-secret.htmlhttps://blog.codinghorror.com/we-are-typists-first-programmers-second/https://www.ryanheise.com/colemak/ScreenshotsTODO: make more attractive screenshots.Using various themes:[^1]: If you get something like "command not found," replace all instances ofpipwithpython -m pip. Ifthatgives an error like "module not found," trypython -m ensurepipfirst.[^2]: You could also try usingpipxwhich isolates installations in its own virtual environment, so dependencies do not interact with the rest of your system.
amphi
amphiMoviePy OOP wrapperAdditional RequirementsImageMagick binary fileMatplotlibOpenCVUsagefromamphiimportAmphimovie=Amphi()movie.new_audio("music","<path/to/audio/file>")movie.new_video("video1","<path/to/audio/file>")movie.new_video("video2","<path/to/audio/file>")movie.new_video("video3","<path/to/audio/file>",stabilize=True)movie.new_text("title","My Video",font="Arial",fontsize=100,duration=4)print("Processing media resources...")movie.video("video1").subclip(0,5).keep("video1a")movie.video("video2").subclip(0,2).keep("video2a")movie.video("video3").subclip(2).keep("video3a")movie.video("video1a").composite("title").keep("intro")movie.concatenate_by_video_id(["intro","video2a","video3a"])movie.set_audio("music")movie.render()ifmovie.save("my-movie.mp4",fps=30,bitrate="16000k"):print("The video has been successfully saved.")
amphipathic
amphipathicThis library can analyze an aminoacid sequence and gives a list of secondary structures with the respective hydrophobicity mean[1] and amphipathic index[1].When it is useful to calculate this measurements on a secondary structure?By looking into this measurements for an alpha helix, you can test some hiphotesis related with:the context of aglobular soluble protein:hydrofobic core, it will be no amphipathic and hydrophobicinterface between core and the superficial region, it will be amphiphaticsuperficial region, it will be no amphipathic and hydrophilicthe interactions of atrans-membrane protein:on lipids interaction, it will be not amphipathic and hidrophobicon multiple trans-membrane helix interacion(homomeric or heteromeric), it will be amphipathic building like anionic channel.RequirementsIf you want to use this library on any GNU/Linux or OSX system you just need to execute:$ pip install amphipathicIf you want to collaborate with this library, you should download thegithub repositoryand execute:$ make deployTestingTo test all the project you should use the command:$ pytest testsExampleThis library can analyze an aminoacid sequence and gives a list of secondary structures with the respective hydrophobicity mean and amphipathic index.importamphipathicresume=amphipathic.index('NLYIQWLKDGGPSSGRPPPS')printresumeor specifingscale="prift"from Cornette et al.[1]importamphipathicresume=amphipathic.index('NLYIQWLKDGGPSSGRPPPS',scale="prift")printresumeAnd the result should be:[[{'end':2,'begin':0,'type':u'c','seq':'nl','amphipathic':{'index':7.572935321054872e-05,'mean':2.6}},{'end':5,'begin':2,'type':u'e','seq':'yiq','amphipathic':{'index':1.4312912272216411,'mean':1.7299999999999998}},{'end':18,'begin':5,'type':u'c','seq':'wlkdggpssgrpp','amphipathic':{'index':0.002511560979331271,'mean':-0.43}},{'end':20,'begin':18,'type':u'e','seq':'ps','amphipathic':{'index':1.6242872515167746,'mean':-1.34}}]]Each secondary structure block has specific information like:typecould be "c" (from coil), "e" (extended/beta sheet) or "h" (alpha helix).meanprovides the hydrophobicity mean obtained using the aminoacids of the block through Hydrophobicity scales obtained from Table 4 (STA PRIFT **) Cornette et al.[1].indexprovides an amphipathic index adapted from Cornette et al.[1], first implemented into Pablo Daniel Ghiringhelli's PhD thesis[2]. Cornette et al.[1] suggests an scalar equal or greater than 2, means apmhipathicity. On alpha helix cases this is only valid for segments shorter than 20-25 residues. When an alpha helix go further in longitude, the index is not valid anymore.It also accept a nucleotide sequence to perform the same analysis:importamphipathicresume=amphipathic.index('cgcgtccttggagcaatgcagttcaagaccaagaatcgaattgaacctgt')printresumeAnd the output:[[{'end':12,'begin':0,'type':u'c','seq':'rvlgamqfktkn','amphipathic':{'index':0.007560225956225585,'mean':0.7825000000000001}},{'end':15,'begin':12,'type':u'e','seq':'rie','amphipathic':{'index':1.6297837670649824,'mean':1.4599999999999997}},{'end':16,'begin':15,'type':u'c','seq':'p','amphipathic':{'index':0.0,'mean':-2.23}}]]Last, it also accept a polyprotein sequence. When working with aminoacid it detect the '*' character as a stop signal:importamphipathicresume=amphipathic.index('NLYIQWLKDG*GPSSGRPPPS')printresumeUsagesThis library was used intomistic2.Bibliography[1] Cornette, J. L., Cease, K. B., Margalit, H., Spouge, J. L., Berzofsky, J. A., & DeLisi, C. (1987). Hydrophobicity scales and computational techniques for detecting amphipathic structures in proteins. Journal of Molecular Biology, 195(3), 659–685. doi:10.1016/0022-2836(87)90189-6.[2] Ghiringhelli D (2002). Virus Junín: Clonado molecular y análisis estructural y funcional del RNA S y sus productos génicos, Facultad de Ciencias Exactas, Universidad Nacional de La Plata.Questions?If you want to develope with us or have questions about this library, please file an issue in this repository so some of the project managers can get back to you. Please check the existing (and closed) issues to make sure your issue hasn't already been addressed.
amphivena
tbd
ampho
Amphois a Python library that provides simple and convenient way to develop applications by splitting them into small, easily maintainable parts.Build statusDocumentationSee thedocumentationfor details.ChangelogSee theCHANGELOG.rstfor details.SupportUse project’sissue tracker.ContributingSee theCONTRIBUTING.rstfor details.AuthorsAlexander Shepetko– initial work.LicenseThis project is licensed under the MIT License. See theLICENSE.rstfile for details.
ampho-model
Abstract base data model for using in Ampho applications.Build statusInstallationpipinstall-Uampho-modelUsageUseampho_model.Modelas a base class for your models.ChangelogSee theCHANGELOG.rstfor details.SupportUse project’sissue tracker.ContributingSee theCONTRIBUTING.rstfor details.AuthorsAlexander Shepetko– initial work.LicenseThis project is licensed under the MIT License. See theLICENSE.rstfile for details.
amphora
UNKNOWN
amphoradata
Connect information in real time with Amphora Data. Learn more athttps://docs.amphoradata.com# noqa: E501
ampit
No description available on PyPI.
ampl
An IPython extension for working with AMPL.SeeAMPL magic: using IPython as an interface to AMPLfor an introduction to IAMPL.IAMPL is licensed under the terms of theBSD license.InstallationUsingpipThe following command installs the ampl extension usingpip:$ pip install amplUsingeasy_installThe following command installs the ampl extension usingeasy_install:$ easy_install amplCreditsThanks Leonardo Taccari (sbebo) for implementing the realtime output.
amplabs
AmpLabsAmpLabs is a open source platform which provides easy way of data visualisation.DescriptionBuilt on top of Plotly.js, Dash, Pandas and Flask, AmpLabs ties modern UI elements like dropdowns and graphs directly to analytical Python code.Method provided -MethodDescriptionParameterReturn valuereadCSVmethod to read a csv filefile_path = path of the file to readdataframereadDATmethod to read a dat filefile_path = path of the file to readdataframereadTDMSmethod to read a tdms filefile_path = path of the file to readdataframeminutesToSecondsmethod to convert time column from minutes to secondscolumn = column list that has to be convertedconverted column listshowHeadersmethod to display list of headersdf = dataframelist of headersconvertToExcelmethod which convert a dataframe to excel filedf = dataframe, file_path = path of the file where it should be saved-addHeadersmethod to add headers to the dataframedf = dataframe, column_list = list of columns that should be addeddataframeplotmethod to generate graph from the data framedata_list = list of dataframes, data_names = list of names of dataframescolors(optional) = list of colorsOther Services by AmpLabsWebsite to upload and plot data on cloud [www.app.amplabs.ai]Desktop Application to visual data locally
ample
No description available on PyPI.
amplecode.recipe.template
amplecode.recipe.template is a Buildout recipe for generating files using Jinja2 templates. The recipe configures a Jinja2 environment, by default relative to the Buildout directory, allowing templates to extend and include other templates relative to the environment.Downloads are available from pypi:http://pypi.python.org/pypi/amplecode.recipe.template/Buildout Optionstemplate-file (required): One or more Jinja2 template file paths.target-file (required): One of more target file paths. The number of files must match the number of template files.base-dir: Base directory of the Jinja2 environment. Template file paths are relative to this directory. Default is the Buildout directory.target-executable: One or more boolean flags (yes|no|true|false|1|0) indicating the executability of the target files. If only one flag is given it is applied to all target files.eggs: Reserved for a list of eggs, conveniently converted into a pkg_resources.WorkingSet when specifiedAdditional options are simply forwarded to the templates, and options from all the other parts listed in buildout:parts are made available throughparts.<part-name>.<option-name>andparts[<part-name>][<option-name>].Lists of ValuesIt is possible for a recipe option to contain one or more values, separated by whitespace. A split filter is available for when you want to iterate over the whitespace separated values in your Jinja2 template:#!/bin/sh {% for cmd in cmds|split %} echo "{{ cmd }}" {% endfor %}Minimal Examplefoo.txt is created from foo.txt.jinja2 without any extra options:[buildout] parts = foo [foo] recipe = amplecode.recipe.template template-file = foo.txt.jinja2 target-file = foo.txtLarger Examplefoo.txt is created from myapp/foo.txt.jinja2, bar.sh is created from myapp/bar.sh.jinja2, the second will be executable, and both templates can utilize the additional options specified:[buildout] parts = foo [foo] recipe = amplecode.recipe.template base-dir = myapp template-file = foo.txt.jinja2 bar.sh.jinja2 target-file = foo.txt bar.sh target-executable = false true project_name = Another Example author = MeChangelogSee the CHANGELOG fileLicenseSee the LICENSE file
amplee
Atom Publishing Protocol implementation
amplia-client
This library contains classes that encapsulate the call to the Amplia service (X.509 certificate issuing solution) for Amplia applicationsThe recommend way to installRest PKI Client Libis through [PyPi](https://pypi.org/):$ pip install amplia-clientOr informing on your project’srequirements.txtfile:amplia-client==1.0.0For more information, see [Amplia](http://www.lacunasoftware.com/en/certificate/#/amplia) page.
amplicnv
ampliCNV is a Python 3.x package for copy number variation (CNV) detection on whole exome sequencing (WES) data from amplicon-based enrichment technologies.
amplicon-coverage-inspector
Amplicon Coverage Inspector (aci)Amplicon Coverage Inspector (aci) is a bioinformatics tool designed to analyze the depth of amplicons using samtools. It provides a convenient way to determine the coverage and depth of specified regions in a BAM file based on a BED file.Installationpip install amplicon_coverage_inspectorFrom githubgit clone https://github.com/erinyoung/ACI.git cd ACI pip install .Dependenciespython3.7+pandasmatplotlibpysamUsageaci --bam input.bam --bed amplicon.bed --out outFinal files areout/amplicon_depth.csv : csv file of the depth of each ampliconout/amplicon_depth.png : boxplot of information from csv fileout/overall_depth.csv : csv file of overall depth of bam fileout/overall_depth.png : boxplot of information from csv fileExpected run time: About 30 seconds per amplicon when using SRR13957125 (SARS-CoV-2 with ~30 KB genome size and 5,350.27 mean depth) and the artic V3 primers. Larger genomes, more coverage, and larger amplicons increase the computation time. Use -t or --threads to take advantage of determining the coverage of amplicons in parallel.There are not currently options to change the look of the final image file. Instead, the amplicon_depth.csv file contains all the values in a '.csv' format that can be read into R, python, excel, or another tool for visualization.Optionsusage: aci [-h] -b BAM [BAM ...] -d BED [-o OUT] [-log LOGLEVEL] [-t THREADS] [-v] options: -h, --help show this help message and exit -b BAM [BAM ...], --bam BAM [BAM ...] (required) input bam file(s) -d BED, --bed BED (required) amplicon bedfile -o OUT, --out OUT directory for results -log LOGLEVEL, --loglevel LOGLEVEL logging level -t THREADS, --threads THREADS specifies number of threads to use -v, --version print version and exitBed file formatACI is not very strict on thebed file formatas only the first four columns are used.The four columns (tab-delimited only) areReference (must the same as the reference of the bam file)Start positionStop positionName of the ampliconACI does not support bedfiles with headers.Example amplicon bedfile.MN908947.3 54 385 1 1 + MN908947.3 342 704 2 2 + MN908947.3 664 1004 3 1 + MN908947.3 965 1312 4 2 + MN908947.3 1264 1623 5 1 + MN908947.3 1595 1942 6 2 + MN908947.3 1897 2242 7 1 + MN908947.3 2205 2568 8 2 + MN908947.3 2529 2880 9 1 + MN908947.3 2850 3183 10 2 +Amplicon bedfilePrimers should be trimmed out of the bam file prior to ACI regardless of whether the sequencing was paired or single-end. Primer sequences force portions of DNA to match reference and mask SNPs and other variants, so it is a normal request to trim primers out first.Please be careful to not use a primer scheme bedfile because they are not the same. For an example, let's take a left and right primer based off of the reference MN908947.3. If left primer is expected to bind to 30-54 of MN908947.3, and the right primer is expected to bind to 385-410, the expected amplicon would be from 55-384.ACI uses the bedfile to identify regions of the genome where both read1 and read2 are bounded by the start and stop location of that bedfile. If using a bam file generated with mapping single-end reads, only that one read must be within bounds. Any reads that map out of that specific region will be excluded. Then coverage is determined for that region. Therefore, all intended sequences are included. Nearby overlapping amplicons can still mask problematic primers/primer pairs and this should be taken into account when evaluating the output of ACI.TestingThis repository contains a test bam and bed file in the/tests/datasubdirectory.aci -b tests/data/test.bam -d tests/data/test.bed -o testingThe resulting image should look something like the following.ContributingContributions are welcome! If you find any issues or have suggestions for improvements, please feel free toopen an issueor submit a pull request.Why this existsI just needed an individual tool that evaluates how effective a set of primers are for an amplicon or bait-based NGS library prep. Similar scripts are included in many workflows including that of (artic)[https://github.com/artic-network/artic-ncov2019], but I needed something that was standalone. Samtools has a function,ampliconstats, that predicts amplicons based on a primer schema bedfile, but has errors when there are large number of primer pairs and can incorrectly pair primers when determining amplicons. This means that I needed control as to what was in the amplicon file.LicenseThis project is licensed under the MIT License.ContactFor any questions or inquiries, pleasesubmit an issue.
amplicov
amplicon_coverage_plotThe script will generate aninteractive barplotgiven amplicon info inbed6/bedpeformat and coverage information in cov/bam file.DependenciesProgramming/Scripting languagesPython >=v3.7The pipeline has been tested in v3.7.6Python packagesnumpy >=1.15.1plotly >=4.7.1pysam >= 0.15.4Third party softwares/packagessamtools >=1.9- process bam fileInstallationInstall by pippip install amplicovInstall by condaconda install -c bioconda amplicon_coverage_plotInstall from sourceClone theamplicon_coverage_plotrepository.git clone https://github.com/chienchi/amplicon_coverage_plotThen change directory toamplicon_coverage_plotand install.cd amplicon_coverage_plot python setup.py installIf the installation was succesful, you should be able to typeamplicov -hand get a help message on how to use the tool.amplicov -hUsageusage: amplicov [-h] (--bed [FILE] | --bedpe [FILE]) (--bam [FILE] | --cov [FILE]) [-o [PATH]] [-p [STR]] [--pp] [--mincov [INT]] [--version] Script to parse amplicon region coverage and generate barplot in html optional arguments: -h, --help show this help message and exit --pp process proper paired only reads from bam file (illumina) --count_primer count overlapped primer region to unqiue coverage --mincov [INT] minimum coverage to count as ambiguous N site [default:10] -r [STR], --refID [STR] reference accession (bed file first field) --depth_lines DEPTH_LINES [DEPTH_LINES ...] Add option to display lines at these depths (provide depths as a list of integers) [default:5 10 20 50] --gff [FILE] gff file for data hover info annotation --version show program's version number and exit Amplicon Input (required, mutually exclusive): --bed [FILE] amplicon bed file (bed6 format) --bedpe [FILE] amplicon bedpe file Coverage Input (required, mutually exclusive): --bam [FILE] sorted bam file (ex: samtools sort input.bam -o sorted.bam) --cov [FILE] coverage file [position coverage] Output: -o [PATH], --outdir [PATH] output directory -p [STR], --prefix [STR] output prefixTestcd tests ./runTest.shOutputs-- prefix_amplicon_coverage.txtIDWhole_AmpliconUniqueWhole_Amplicon_Ns(cov<10)Unique_Amplicon_Ns(cov<10)nCoV-2019_1217.7453.000.000.00nCoV-2019_21552.831235.500.000.00nCoV-2019_33164.222831.730.000.00nCoV-2019_42005.161658.000.000.00etc...Table Header Definition in the amplicon_coverage.txtWhole_Amplicon_Ns(cov<10): The number of aligned position with coverage < 10 or (--mincov) in the Whole Amplicon regionUnique_Amplicon_Ns(cov<10): The number of aligned position with coverage < 10 or (--mincov) in the Unique region-- prefix_amplicon_coverage.htmlcolor black for < 5x and blue for <20x
amplified
No description available on PyPI.
amplify
About Fixstars AmplifyFixstars Amplify SDK is a middleware library for Ising machines developed by Fixstars Amplify Corporation. Ising machines specialize in solving optimization problems described by quadratic polynomials of binary variables. Various types of Ising machines implemented with digital circuits and GPUs have been released, starting with the quantum annealing machine by D-Wave Systems. This middleware is an intermediate layer between hardware and applications using Ising machines. We provide various functions that improve the convenience of the machines and enable highly efficient application software development.
amplify-aws-utils
amplify_aws_utilsUtility functions for working with AWS resources though Boto3 with less hiccups.About AmplifyAmplify builds innovative and compelling digital educational products that empower teachers and students across the country. We have a long history as the leading innovator in K-12 education - and have been described as the best tech company in education and the best education company in tech. While others try to shrink the learning experience into the technology, we use technology to expand what is possible in real classrooms with real students and teachers.Getting StartedPrerequisitesamplify_aws_utils requires the following to be installed:python >= 3.8InstallationThis package can be installed usingpippip install amplify_aws_utilsBuilding From SourceFor development,tox>=2.9.1is recommended.Python package can be built as follows:python setup.py sdistThis creates a package indistdirectory.Running Testsamplify_aws_utilsusestox. You will need to install tox withpip install tox. Runningtoxwill automatically execute linters as well as the unit tests. You can also run them individually with the -e argument.For example,tox -e lint,py38-unitwill run the linters, and then the unit tests in python 3.8To see all the available options, runtox -l.DeploymentDeployment is done with Travis.Package is built as described above, and is uploaded to PyPI repo usingdevpi-clientUsageFunctions provided by this package can be imported after package has been installed.Example:from amplify_aws_utils.resource_helper import throttled_call
amplify-bench
Fixstars Amplify BenchmarkWhat is Amplify Benchmark?Fixstars Amplify Benchmark is a framework for benchmarking the performances of solvers for quadratic unconstrained binary optimization problems (QUBO). It provides a command line interface to perform benchmarking and a definition of the benchmark problem.TheFixstars Amplify SDKis used as the backend, allowing benchmarks to be run with many solvers such as quantum annealing machines, Ising machines, and mathematical optimization solvers. Benchmarks are run based on a job set file that defines the target problems, the number of runs, and the solvers to be used, making it easy to automate the process from benchmark execution to analyzing results.The results of this library run can be loaded into theAmplify Benchmark Viewerto visualize the results in a web browser. A demo of the benchmark results for Amplify AE ishere.FeaturesEasy to runParallel executionAutomatic evaluation and analysisBenchmark result viewer is providedCustomizable solver and problem parametersFormulations for several benchmark sets are pre-definedUser-define problems can be addedPre-defined benchmark sets:Traveling Salesperson Problem:TSPLIBQuadratic Assignment Problem:QAPLIBMax-CUT Problem:GsetCapacitated Vehicle Routing Problem:CVRPLIBQuadratic Problem:QPLIBSudoku (logic-based combinatorial number-placement puzzle)Supported solvers powered by Amplify SDK:Fixstars Amplify AED-Wave AdvantageFujitsu Digital Annealer 3/4Toshiba SQBM+Gurobi Optimizer(Seesupported solvers of Amplify SDK)GalleryObjective value for execution timeTime To Solution (TTS)Probability of obtaining a feasible solutionProbability of obtaining the best solution RateTable DATAGetting startedInstallationAmplify benchmark is provided as a Python (>=3.8) library. It can be installed with pip as follows:$pipinstallamplify-benchRun example job setAfter installation, theamplify-benchcommand is enabled.$amplify-bench--help Usage:amplify-bench[OPTIONS]COMMAND[ARGS]... Options:--helpShowthismessageandexit. Commands:downloadDownloadallsupportedinstancefilesinthespecified...runQUBOBenchmarkstatsGenerateQUBObenchmarkstatsdata.To run a benchmark, you have to create a benchmark definition ("job set") file. Theexample/benchmark.ymlfile contains a sample job set file.example/benchmark.ymljobs:-problem:class:Tspinstance:eil51client:-FixstarsClient-token:INPUT_API_TOKENparameters:timeout:3000num_samples:2The benchmark job set file contains a list of benchmark jobs in YAML or JSON file format. The jobs consist of the number of runs, a list of problems to solve, and parameter values passed to theClient classto run. For this job set, it consists of the following benchmark jobs:target problem:TSPLIB:eil51instancenumber of runs: 2FixstarsClienttoken: INPUT_API_TOKENparameter.timeout: 3000Now to start the benchmark using this job set file, run theamplify-benchcommand with therunsubcommand with the path to the job set file.NoteReplaceINPUT_API_TOKENwith your API token. If you do not have an API token, go toAmplify WEB siteandcreate an account.$amplify-benchrunbenchmark.yml input_json:benchmark.yml label:20230803_223440 output:None parallel:1aws_profile:None dry_run:False cli_benchmark_impl()20230803_2234402023-08-0322:34:41,308[pid:94470][INFO]:542.49msinamplify_bench.cli.parser.parse_input_data2023-08-0322:34:41,309[pid:94470][INFO]:makemodelofeil512023-08-0322:34:41,519[pid:94470][INFO]:209.08msinamplify_bench.problem.tsp.make_tsp_model totaljobs:2successjobs:2errorjobs:0Jobsnotyetstarted:0When execution completes a JSON file is output as the result of the execution in the same directory. The file name is appended with the execution time by default. The output file path can be changed with the--output <path>option.Open the result with Amplify Benchmark ViewerThe results can be visualized using theAmplify Benchmark Viewer. To analyze for the viewer, give thestatssubcommand with the path to a directory or a result file to theamplify-benchcommand.$amplify-benchstatspreset_20230803_223440.jsonBy default, areport/data.jsonfile is created in the current directory. The path directory of the output file can be changed with the--outputoption.Then, drag and drop the createdreport/data.jsonfile into the Amplify Benchmark ViewerGitHub pagesto visualize the results.NoteThe data is analyzed only on the browser and is not stored on the external server.Drag and Dropdata.jsonfileShow the evaluated problem listThe detailed evaluation for each problemAdvanced usagejob set file in detailsPresetObjectA job set file consisted of JSON objects with the following keys. The schema of the job set file is described inamplify_bench/cli/schemas.keytypedescriptionjobsarray[JobObject]list of benchmark jobsvariablesobjectdefinitions of variables used injobs(Optional)importsarray[string]User-defined problem file path (Optional)Strings in the file that begin with$are treated as variable names. Variables are first expanded by the environment variables at runtime, then the variable definitions given in thevariableskey are referenced injobs. This is useful, for example, to specify a setting that is commonly used in multiple jobsvariables:CLIENT:-FixstarsClient-parameters:timeout:3000jobs:-problem:class:Tspinstance:eil51client:$CLIENTnum_samples:2-problem:class:Tspinstance:burma14client:$CLIENTnum_samples:1importsspecifies the list of paths to the user-defined problem file. Enter the path as a relative path from a job set file, a relative path from the current directory, or an absolute path. For details on user-defined question files, seeCreate your own benchmark problems.JobObjectkeytypedescriptionnum_samplesintthe number of runsclientarrayclient name and parametersproblemProblemObjectthe problem definitionmatrixobject[array]the definitions of variable patterns (Optional)Ifnum_samplesis an integer greater than 1, it will be run multiple times with the same settings. Thematrixkey is given with the patterns of variables explained later.Theclientkey is given an array of length 2. The first element of the array is the name of the client class, and the second element is an object with the property values of the client. For example, the following client configuration in the Amplify SDKfromamplify.clientimportFixstarsClientclient=FixstarsClient()client.token="INPUT_API_TOKEN"client.parameters.timeout=1000should be specified as follows in the job set file.jobs:-client:-FixstarsClient-token:INPUT_API_TOKENparameters:timeout:1000NoteSee thedocumentationfor the available properties for eachClientclass.ProblemObjectTheproblemkey has an object consisting of the following keys:keytypedescriptionclassstringThe name of the problem classinstancestringInstance nameparametersobjectConstructor parameters of the problem classTheclassis the name of the problem class contained inamplify_bench/problem. The predefined problem classes areTsp(TSPLIB),Qap(QAPLIB),Cvrp(CVRPLIB),MaxCut(GSET),SudokuandQplib(QPLIB). Theinstanceis the name of the instance in the problem set corresponding to each problem class. Seeamplify_bench/problem/datafor details. Problem classes may have formulation parameters that can be passed to the constructor, which can be specified byparameterkey.Using a matrix for your jobsMultiple jobs can be automatically generated for all combinations of multiple variable patterns given in a single job definition. For example, to run for all combinations of multiple instances and multiple runtimes, the following job set file can be used.variables:NUM_SAMPLES:100FIXSTARS:-FixstarsClient-token:INPUT_API_TOKENparameters:timeout:$TIMEOUTjobs:-problem:class:Qapinstance:$INSTANCEclient:$FIXSTARSnum_samples:$NUM_SAMPLESmatrix:INSTANCE:-esc32a-sko56TIMEOUT:-10000-30000Thematrixis an array of values with the variable names as keys. In this case, jobs withtimeoutof10000and30000will be created foresc32aandsko56respectively. Note that you can refer to the variables you pass tomatrixin the variables defined invariables.NoteVariables are referenced recursively, but an infinite loop will fail.Create your own benchmark problemsUser-defined formulations can be added as benchmark problems that are recognized in Amplify Benchmark.The following example runs a benchmark against theMyTspclass defined in themytsp.pyfile. Setting a list of Python file paths to theimportskey will load additional probem classes defined in the files. A file path must be specified as an absolute path or relative to the job set file or the current directory.imports:-mytsp.pyjobs:-problem:class:MyTspinstance:random8NoteUser-defined class names should not duplicate the built-in problem classes.The problem class must extend theProblemclass and implement the constructor (__init__) and the methodsmake_modelandevaluate. Themake_modelmethod formulates the problem in Amplify SDK and theevaluatemethod evaluates the formulated model with the solution as input.The following code snippet is an example of aMyTspproblem class.mytsp.pyclassMyTsp(Problem):def__init__(self,instance:str,constraint_weight:float=1.0,seed:int=0,path:Optional[str]=None,):super().__init__()self._instance:str=instanceself._problem_parameters["constraint_weight"]=constraint_weightifinstance.startswith("random"):self._problem_parameters["seed"]=seedself._symbols=Nonencity,distances,locations,best_known=self.__load(self._instance,seed,path)self._ncity=ncityself._distances=distancesself._locations=locations# not usedself._best_known=best_knowndefmake_model(self):symbols,model=make_tsp_model(self._ncity,self._distances,self._problem_parameters["constraint_weight"])self._symbols=symbolsself._model=modeldefevaluate(self,solution:SolverSolution)->Dict[str,Union[None,float,str]]:value:Optional[float]=Nonepath:str=""ifsolution.is_feasible:spins=solution.valuesvariables=np.array(self._symbols.decode(spins))# type: ignoreindex=np.where(variables==1)[1]index_str=[str(idx)foridxinindex]value=calc_tour_dist(list(index),self._distances)path=" ".join(index_str)else:passreturn{"label":"total distances","value":value,"path":path}...Constructordef__init__(self,instance:str,**kwargs)->NoneThe constructor must accept at least aninstance: strargument. Otherwise, if you addconstraint_weight: floatto the constructor arguments for example, theparameterskey inProblemObjectcan have aconstraint_weight.make_modelmethoddefmake_model(self)->NoneThemake_modelmethod is responsible for formulating and storing an instance of theamplify.BinaryQuadraticModelclass inself._model.evaluatemethoddefevaluate(self,solution:amplify.SolverSolution)->Dict[str,Union[None,float,str]]Theevaluatemethod takes and evaluates aamplify.SolverSolution. The return value can be any key and value asDict[str, Union[None, float, str]]. The return value is output to theobjective_valuekey in the JSON file of the benchmark result.ContributingAmplify Benchmark is an open source project. Contributions are welcome, including bug reports, feature additions, documentation improvements, etc.Developed byThe Amplify benchmark project ties together:Fixstars Amplify SDKFixstars Amplify Annealing EngineFixstars Amplify Benchmark Viewer
amplify-cf
No description available on PyPI.
amplifyit
No description available on PyPI.
amplifyme
No description available on PyPI.
amplify-model
AmplifyGetting startedAmplifycan be installed viapip install amplify-model. Then, the model can be used in an existing project by callingfrom amplify.src.flex_calculation import FlexCalculator.Alternatively, the repo can of course be cloned. The source code ofAmplifylies underamplify/src/flex_calculation.py. Its results require thedata_classes.pyfile. The calculation relies only on basic python modules.TestsThe basic tests lie underamplify/tests/unit_tests. They can be started by callingpytest.test_total_flex_calculation.py: Assert valid flexibility calculationtest_ppr_detection.py: Validate problem detectiontest_accept_short_trades_scenarios.py: Verify valid sizing of multi purpose obligations with MPOs lasting single time intervalstest_accept_long_trades_scenarios.py: Verify valid sizing of multi purpose obligations with MPOs lasting more than one time interval (contains multiple scenarios)full_result_test_accept_long_trades_scenarios.txt: Contains result of full accept long trades test. For all failed tests, some information is given as well as a short summary.RequirementsUntil now,Amplifyonly requires thepytestmodule, which can be installed viapip.LicenseAmplify is licensed under the Apache 2.0 license.Project statusAmplifyis still under development.Author of documentationPaul Hendrik Tiemann (2022)
amplify.qaoa
About Amplify QAOAAmplify QAOA is a submodule of Amplify, a middleware library for Ising machines developed by Fixstars. Quantum Approximate Optimization Algorithm (QAOA) is algorithm for solving optimization problems (e.g. Ising model). This module supports to solve optimization problems with QAOA for Ising model by the quantum computers or simulators of a quantum computer.
amplify-sched
Amplify Scheduling Engine SDK
ampligraph
No description available on PyPI.
amplikyzer
# amplikyzeramplikyzeris short for amplicon analyzer. It is a software to analyze sequenced amplicons with emphasis on flowgram analysis (resulting from 454 or IonTorrent sequencing) and methylation analysis after sodium bisulfite treatment.Please read the information in the [Wiki](https://bitbucket.org/svenrahmann/amplikyzer/wiki/Home).
amplikyzer2
amplikyzeris short for amplicon analyzer. It is a software to analyze sequenced amplicons with emphasis on flowgram analysis (resulting from 454 or IonTorrent sequencing) and methylation analysis after sodium bisulfite treatment.amplikyzer2is the successor toamplikyzerand adds support for the analysis of FASTQ reads from Illumina’s MiSeq sequencer.Please read the information in the [Wiki](https://bitbucket.org/svenrahmann/amplikyzer/wiki/Home).
amplimap
amplimap: amplicon mapping and analysis pipelineamplimap is a command-line tool to automate the processing and analysis of data from targeted next-generation sequencing (NGS) experiments with PCR-based amplicons or capture-based enrichment systems.From raw sequencing reads, amplimap generates a variety of output files including read alignments, per-basepair nucleotide counts, target coverage data and annotated variant calls.In addition to its focus on user-friendliness and reproducibility, amplimap supports advanced features such as the generation of consensus base calls for read families based on molecular identifiers/barcodes (UMIs) and the detection of chimeric reads caused by amplification of off-target loci.InstallationWe recommend that you install amplimap through Conda:wget https://raw.githubusercontent.com/koelling/amplimap/master/environment.yml conda env create --file environment.ymlWe also have aDocker imageavailable. Please see ourfull installation instructionsfor additional details.OverviewTo run amplimap you create a directory containing a small set of input files:A subdirectory with FASTQ.GZ or BAM files representing your different samples (tested with Illumina MiSeq, HiSeq and NextSeq)Optionally: Files describing the targeted genomic regions, the primers you used or other custom configuration parametersThen you can runamplimapto generate a variety of different output files, depending on your experiment. These include, for example:A target coverage table, showing you how well-covered each target region was in each sample.A table of germline variants in your samples, annotated with gene, impact, population frequencies, deleteriousness scores, etc.A per-basepair “pileup” table telling you how often each nucleotide was seen in each sample at each position.Built on top ofSnakemakeand Python 3, amplimap is entirely automated and can be run on a single machine as well as on an HPC cluster (e.g. LSF, SGE).Supported experimental protocolsamplimap is compatible with most targeted sequencing protocols that generate paired-end short read data.For protocols utilising PCR or smMIPs each read should start with a known primer (or targeting arm) sequence, followed by the amplified target DNA. Reads can optionally contain a unique molecular identifier (UMI) sequence in front of the primer, which can be used to group reads into families. Data should be available as demultiplexed FASTQ.GZ files, with each pair of files representing a different sample.For capture-based protocols data can be provided in FASTQ.GZ or unmapped/mapped BAM format, which may contain UMIs as BAM tags.Some of the protocols we have analyzed with amplimap include:PCR-based targeted resequencing (single/multiplex)smMIPs with and without UMIsProbe based target enrichment, for example:IDT xGen Lockdown probesTwist Bioscience Custom PanelsTutorialsCalling germline variants in amplicon-based resequencing dataIdentifying low-frequency somatic mutations in FGFR2 with UMI-tagged smMIPsQuantifying allele-specific expressionLinksPackage:https://pypi.org/project/amplimap/Code:https://github.com/koelling/amplimap/Documentation:https://amplimap.readthedocs.io/Citation and LicenseLicensed under the Apache License, version 2.0. Copyright 2020 Nils Koelling. When you use amplimap, please cite theamplimap paperin your work:Nils Koelling, Marie Bernkopf, Eduardo Calpena, Geoffrey J Maher, Kerry A Miller, Hannah K Ralph, Anne Goriely, Andrew O M Wilkie, amplimap: a versatile tool to process and analyze targeted NGS data, Bioinformatics, Volume 35, Issue 24, 15 December 2019, Pages 5349–5350,https://doi.org/10.1093/bioinformatics/btz582
ampliomws
See README.md
amplitf
AmpliTFLibrary of primitives for amplitude analyses in high-energy physics using TensorFlow v2IntroductionThe package includes the primitives to operate with relativistic kinematics (operations with Lorentz vectors, elements of helicity formalism), and descriptions of the dynamical functions (such as Breit-Wigner line shapes) using Google TensorFlow library.This package is a fork of TensorFlowAnalysishttps://gitlab.cern.ch/poluekt/TensorFlowAnalysisthat includes only the "stable" basic functionality.The package is compatible with TensorFlow v2.PrerequisitesTensorFlow v2.1NumPySymPyIMinuitROOT is not required anymore.LinksTensorFlowAnalysis:https://gitlab.cern.ch/poluekt/TensorFlowAnalysisZFit:https://github.com/zfit/zfitComPWA:https://github.com/ComPWA
amplitude-analytics
Amplitude Python SDKThe official Amplitude backend Python SDK for server-side instrumentation.DevelopmentRun Server LocallyRefer toexamples/README.md.Run Unit Tests LocallyRun Directlypython3 -m unittest discover -s ./src -p 'test_*.py'Run withtoxpip3 install --user tox python3 -m tox -e pyAmplitude and Ampli WrapperAmpli SDKis autogenerated library based on your pre-definedtracking plan. The Ampli Wrapper, is a lightweight wrapper over the Amplitude SDK that provides type-safety, supports linting, and enables features like input validation. The code replicates the spec in the Tracking Plan and enforces its rules and requirements. This repository is aboutAmplitude SDK. To learn more about Ampli Wrapper, please refer to theAmpli Pythonandexamples.Installation and Quick StartPlease visit theDeveloper Centerfor instructions on installing and using our the SDK.ChangelogView thereleases here.Need Help?If you have any issues using our SDK, feel free tocreate a GitHub issueor submit a request onAmplitude Help.
amplitude-client
No description available on PyPI.
amplitude-data-wrapper
Amplitude data wrapperThis is a wrapper forAmplitudeAPIs. You can use it to query and export data from your account and use the taxonomy API.Built withrequestsandtqdmWhy use this package instead of other wrappers?This package supports regions and so you can use it with Amplitude accounts in the EU and USA.This package also supports using a proxy so you can keep your project API keys and API secrets confidential.Supported Amplitude APIs and docsAmplitude data wrapperSupported Amplitude APIs and docsDashboard Rest APIPrivacy APICohort APIExport APITaxonomy APISee examples below and inexample.pyInstall withpip install amplitude-data-wrapperDashboard Rest APIResults from an existing chartGet data from EU account by settingregion=1.importamplitude_data_wrapper.analytics_apiasampr=amp.get_chart(chart_id,api_key,api_secret,region=1)r.status_code# 200r.text# print dataGet data from US account by settingregion=2.r=amp.get_chart(chart_id,api_key,api_secret,region=2)r.status_code# 200r.text# print dataGet data from EU account with a proxy by setting region and proxy using a dictionary.proxies={"http":"http://myproxy.domain.org/path"}r=amp.get_chart(chart_id,api_key,api_secret,region=1,proxy=proxies)r.status_code# 200r.text# print dataEvent segmentationlets you export events with segments and filters.our_event_dict={"event_type":"pageview","group_by":[{"type":"event","value":"app"},{"type":"event","value":"team"}],}data=amp.get_event_segmentation(api_key=api_key,secret=api_secret,start="20220601",end="20220602",event=our_event_dict,metrics="uniques",interval=1,limit=1000,)User searchlets you search for a user with a specific Amplitude ID, Device ID, User ID, or User ID prefix.user=amp.find_user(user=example_id_eu,api_key=api_key,secret=api_secret,region=1)Privacy APIDelete user data with adeletion jobdeleteme=amp.delete_user_data(user["matches"][0]["amplitude_id"],email=email,api_key=api_key,secret=api_secret,region=1,ignore_invalid_id=True,delete_from_org=False,)Get a list of deletion jobstobe_deleted=amp.get_deletion_jobs(start="2022-06-01",end="2022-07-01",api_key=api_key,secret=api_secret,region=1,)Cohort APIGetting one cohortproxies={"http":"http://myproxy.domain.org/path"}file_path="path-to/cohortdata.csv"kull=amp.get_cohort(api_key,api_secret,cohort_id,filename=file_path,props=1,region=1,proxy=proxies,)Export APIExport API - Export your project's event datastart="20220601T00"end="20220601T01"data=amp.export_project_data(start=start,end=end,api_key=api_key,secret=api_secret,filename="path-to/projectdata_eu.zip",region=1,)Taxonomy APIGet all event typestypes=amp.get_all_event_types(api_key=api_key,secret=api_secret,region=1)
amplitude-experiment
Experiment Python SDKAmplitude Python Server SDK for Experiment.Installationpipinstallamplitude-experimentRemote Evaluation Quick Startfromamplitude_experimentimportExperiment,RemoteEvaluationConfig,RemoteEvaluationClient,User# (1) Get your deployment's API keyapiKey='YOUR-API-KEY'# (2) Initialize the experiment remote evaluationexperiment=Experiment.initialize_remote(api_key)# (3) Fetch variants for a useruser=User(device_id="abcdefg",user_id="[email protected]",user_properties={'premium':True})# (4) Lookup a flag's variant## To fetch synchronousvariants=experiment.fetch(user)variant=variants['YOUR-FLAG-KEY']ifvariant:ifvariant.value=='on':# Flag is onelse:# Flag is off# To fetch asynchronousexperiment.fetch_async(user,fetch_callback)deffetch_callback(user,variants):variant=variants['YOUR-FLAG-KEY']ifvariant:ifvariant.value=='on':# Flag is onelse:# Flag is offLocal Evaluation Quick Start# (1) Initialize the local evaluation client with a server deployment key.experiment=Experiment.initialize_local(api_key)# (2) Start the local evaluation client.experiment.start()# (3) Evaluate a user.user=User(device_id="abcdefg",user_id="[email protected]",user_properties={'premium':True})variants=experiment.evaluate(user)More InformationPlease visit our :100:Developer Centerfor more instructions on using our the SDK.See ourExperiment Python SDK Docsfor a list and description of all available SDK methods.Need Help?If you have any problems or issues over our SDK, feel free tocreate a github issueor submit a request onAmplitude Help.
amplitude-logger
amplitude-loggerPython client for Amplitude API v2 (https://developers.amplitude.com/docs/http-api-v2)Installationpip install amplitude-loggerUsageAmplitude APIRequest your API key athttps://developers.amplitude.com/Use that token to initialize client:fromamplitudeimportAmplitudeLoggerapi_key='xxxxxxxxxxxxxxx'amplitude_logger=AmplitudeLogger(api_key=api_key)event_args={"user_id":"USER_ID","event_type":"Event Name","event_properties":{"param":"value","data":"value"},}event=amplitude_logger.create_event(**event_args)amplitude_logger.log_event(event)
amplitude-python
[CircleCI]AMPLITUDE-PYTHONPython API for Amplitude Analytics Logging - https://amplitude.comThis API is a simple (unofficial) wrapper for the Amplitude HTTP API1. Install amplitude-pythonPotential preparation before installing: create and activate virtualenv or conda environment1.1 Install from pypi with conda or pippip install amplitude-python1.2 Install from github$ git clone https://github.com/atveit/amplitude-python.git$ cd amplitude-python$ python setup.py instal2. Logging to Amplitude with amplitude-pythonRecommend having a look at Amplitude HTTP API Documentation before start logging.import amplitude# initialize amplitude loggeramplitude_logger = amplitude.AmplitudeLogger(api_key = "SOME_API_KEY_STRING")# example eventevent_args = {"device_id":"somedeviceid", "event_type":"justtesting","event_properties":{"property1":"somevalue", "propertyN":"anothervalue"}event = amplitude_logger.create_event(**event_args)# send event to amplitudeamplitude_logger.log_event(event)3. Test amplitude-python modulepython setup.py test
amplitude-python-sdk
amplitude-python-sdkUnofficialSDK for the Amplitude HTTP API, providing a user-friendly interface through Pydantic models.Seethe Amplitude docsfor more information on the various API methods and their parameters.WARNING: This library is in very early development, and APIs are not guaranteed to be stable. Please bear that in mind when using this library.Installationpip install amplitude-python-sdkDependenciespydanticis used to create cleaner and more readable data models within this library.requestsis used to handle all HTTP interactions with the Amplitude API.UsageMethods supportedCurrently, only theIdentify APIand theHTTP API V2are supported. Support for other API methods coming soon!Identify API Exampleimportloggingfromamplitude_python_sdk.common.exceptionsimportAmplitudeAPIExceptionfromamplitude_python_sdk.v1.clientimportAmplitudeV1APIClientfromamplitude_python_sdk.v1.models.identifyimportIdentification,UserPropertiesclient=AmplitudeV1APIClient(api_key='<YOUR API KEY HERE>')try:resp=client.identify([Identification(user_id='example',user_properties=UserProperties()])exceptAmplitudeAPIException:logging.exception('Failed to send identify request to Amplitude')Event API Client Exampleimportloggingfromamplitude_python_sdk.common.exceptionsimportAmplitudeAPIExceptionfromamplitude_python_sdk.v2.clients.event_clientimportEventAPIClientfromamplitude_python_sdk.v2.models.eventimportEventfromamplitude_python_sdk.v2.models.event.optionsimportEventAPIOptionsclient=EventAPIClient(api_key='<YOUR API KEY HERE>')try:events=[Event(user_id='example',event_type='Clicked on Foo',event_properties={'foo_id':'bar','click_position':5,})]client.upload(events=events,options=EventAPIOptions(min_id_length=1),)exceptAmplitudeAPIException:logging.exception('Failed to log event to Amplitude')Batch Event Upload API ExampleExactly the same as the Event V2 API example, just substituteclient.batch_uploadforclient.upload.
amplitude-sdk
Amplitude Python SDKSDK for Amplitude APISDK for Amplitude API.https://developers.amplitude.com/docshttps://github.com/paulokuong/amplitudeRequirementsPython 3.7.0GoalTo provide a python API client for Amplitude API.(More clients to be implemented)Code sampleRequesting Behavioral Cohorts APIfromamplitude_sdkimportBehavioralCohortsClientb=BehavioralCohortsClient(api_key='xxxxxxx',secret='yyyyyyyy')b.list_cohorts()ContributorsPaulo Kuong (@paulokuong)
amplitude-tracker
Amplitude Tracker library lets you record analytics data from your Python code toAmplitudeGetting StartedInstallamplitude-trackerusing pip:pip install amplitude-trackerInside your app, you’ll want toset yourwrite_keybefore making any analytics calls:importamplitude_trackerasamplitudeamplitude.write_key='xxxxxxxxxxxxxxx'Note:If you need to send data to multiple Segment sources, you can initialize a new Client for each write_key.Development SettingsThe default initialization settings are production-ready and queue messages to be processed by a background thread.In development you might want to enable some settings to make it easier to spot problems. Enabling amplitude.debug will log debugging info to the Python logger. You can also add an on_error handler to specifically print out the response you’re seeing from the Amplitude’s API.defon_error(error,items):print("An error occurred:",error)analytics.debug=Trueanalytics.on_error=on_errorTracktracklets you record the actions your users perform. Every action triggers what we call an “event”, which can also have associated properties.importamplitude_trackerasamplitudeamplitude.write_key='xxxxxxxxxxxxxxx'amplitude.track(user_id="xxx",event_type="xxx",user_properties={"trait":"xxx"},event_properties={"attribute":"xxx"})BatchingThis library is built to support high performance environments. That means it is safe to use amplitude-tracker on a web server that’s serving hundreds of requests per second.Every calltrackmethoddoes notresult in an HTTP request, but is queued in memory instead. Messages are flushed in batch in the background, which allows for much faster operation.By default, this library will flush:every100messages (control withupload_size)if0.5seconds has passed since the last flush (control withupload_interval)There is a maximum of500KBper batch request and32KBper call.
amplot
# AmPlot[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)受到 [gmplot](https://github.com/vgm64/gmplot) 启发, 基于高德地图做一个可以python 简单调用生成地图 html 页面. 用于展示数据用TODO~~画 Polyline~~~~画 Polygon~~~~重构做到可以增加多个 Polygon, 及 Polygon 与 Polyline 混合使用.~~~~画圆~~带洞多边形生成热力图~~重构, 使用 dict 替换 list, 避免重复~~~~海量点图~~ 样式可传递, 更灵活.重构, 规范命名方式. 更简单易懂.Example TODO * 海量点图
amplParser
No description available on PyPI.
amplpy
AMPLPY: Python API for AMPL# Install Python API for AMPL$python-mpipinstallamplpy--upgrade# Install solver modules (e.g., HiGHS, CBC, Gurobi)$python-mamplpy.modulesinstallhighscbcgurobi# Activate your license (e.g., free https://ampl.com/ce license)$python-mamplpy.modulesactivate<license-uuid># Import in Python$python>>>fromamplpyimportAMPL>>>ampl=AMPL()# instantiate AMPL object# Minimal example:fromamplpyimportAMPLimportpandasaspdampl=AMPL()ampl.eval(r"""set A ordered;param S{A, A};param lb default 0;param ub default 1;var w{A}>= lb <= ub;minimize portfolio_variance:sum {i in A, j in A} w[i] * S[i, j] * w[j];s.t. portfolio_weights:sum {i in A} w[i] = 1;""")tickers,cov_matrix=# ... pre-process data in Pythonampl.set["A"]=tickersampl.param["S"]=pd.DataFrame(cov_matrix,index=tickers,columns=tickers)ampl.solve(solver="gurobi",gurobi_options="outlev=1")assertampl.solve_result=="solved"sigma=ampl.get_value("sqrt(sum {i in A, j in A} w[i] * S[i, j] * w[j])")print(f"Volatility:{sigma*100:.1f}%")# ... post-process solution in Python[Documentation] [AMPL Modules for Python] [Available on Google Colab] [AMPL Community Edition]amplpyis an interface that allows developers to access the features ofAMPLfrom within Python. For a quick introduction to AMPL seeQuick Introduction to AMPL.In the same way that AMPL’s syntax matches naturally the mathematical description of the model, the input and output data matches naturally Python lists, sets, dictionaries,pandasandnumpyobjects.All model generation and solver interaction is handled directly by AMPL, which leads to great stability and speed; the library just acts as an intermediary, and the added overhead (in terms of memory and CPU usage) depends mostly on how much data is sent and read back from AMPL, the size of the expanded model as such is irrelevant.Withamplpyyou can model and solve large scale optimization problems in Python with the performance of heavily optimized C code without losing model readability. The same model can be deployed on applications built on different languages by just switching the API used.Documentationhttp://amplpy.ampl.comRepositories:GitHub Repository:https://github.com/ampl/amplpyPyPI Repository:https://pypi.python.org/pypi/amplpy
amplpy-ampls
Failed to fetch description. HTTP Status Code: 404
amplpy-copt
copt driver for AMPL. This package uses AMPLS-API, which is an open source set of lightweight interfaces between AMPL and solvers, which allow:Read in an AMPL model instance from anNLfileWrite out the solution as asolfile, ready to be imported by AMPLA choiche between:Use of all the solver’s capabilities, using its own C API functionalitiesUse of a (provided) generic interface, that encapsulates the most common functionalities of the solver interfaces, permitting hassle-free solver swapUsage of existing AMPL licenses, when used together with the AMPL driversThe interfaces are available for multiple languages; the core is written in C++ and it is wrapped using [swig](https://www.swig.org) to other target languages.
amplpy-cplex
CPLEX driver for AMPL. This package uses AMPLS-API, which is an open source set of lightweight interfaces between AMPL and solvers, which allow:Read in an AMPL model instance from anNLfileWrite out the solution as asolfile, ready to be imported by AMPLA choiche between:Use of all the solver’s capabilities, using its own C API functionalitiesUse of a (provided) generic interface, that encapsulates the most common functionalities of the solver interfaces, permitting hassle-free solver swapUsage of existing AMPL licenses, when used together with the AMPL driversThe interfaces are available for multiple languages; the core is written in C++ and it is wrapped using [swig](https://www.swig.org) to other target languages.
amplpyfinance
This package replicates some financial portfolio optimization models frompypfoptusingamplpy.LinksGitHub Repository:https://github.com/ampl/amplpyfinancePyPI Repository:https://pypi.python.org/pypi/amplpyfinance
amplpy-gurobi
GUROBI driver for AMPL. This package uses AMPLS-API, which is an open source set of lightweight interfaces between AMPL and solvers, which allow:Read in an AMPL model instance from anNLfileWrite out the solution as asolfile, ready to be imported by AMPLA choiche between:Use of all the solver’s capabilities, using its own C API functionalitiesUse of a (provided) generic interface, that encapsulates the most common functionalities of the solver interfaces, permitting hassle-free solver swapUsage of existing AMPL licenses, when used together with the AMPL driversThe interfaces are available for multiple languages; the core is written in C++ and it is wrapped using [swig](https://www.swig.org) to other target languages.
amplpy-knitro
Failed to fetch description. HTTP Status Code: 404
amplpy-xpress
XPRESS driver for AMPL. This package uses AMPLS-API, which is an open source set of lightweight interfaces between AMPL and solvers, which allow:Read in an AMPL model instance from anNLfileWrite out the solution as asolfile, ready to be imported by AMPLA choiche between:Use of all the solver’s capabilities, using its own C API functionalitiesUse of a (provided) generic interface, that encapsulates the most common functionalities of the solver interfaces, permitting hassle-free solver swapUsage of existing AMPL licenses, when used together with the AMPL driversThe interfaces are available for multiple languages; the core is written in C++ and it is wrapped using [swig](https://www.swig.org) to other target languages.
amplremote
AMPL Remote Driver is a solver driver for AMPL based on a REST API that allows solving models on a remote machine while using AMPL on a local machine.LinksGitHub Repository:https://github.com/ampl/ampl-remotePyPI Repository:https://pypi.python.org/pypi/amplremote
ampl-sphinx-theme
Sphinx Theme based onpydata-sphinx-theme.
ampltools
AMPL Python ToolsThis package includes tools to use withAMPLandamplpy.LinksGitHub Repository:https://github.com/ampl/amplpy/PyPI Repository:https://pypi.python.org/pypi/ampltools
amply
IntroductionAmply allows you to load and manipulate AMPL data as Python data structures.Amply only supports a specific subset of the AMPL syntax:set declarationsset data statementsparameter declarationsparameter data statementsDeclarations and data statementsTypically, problems expressed in AMPL consist of two parts, amodelsection and adatasection. Amply is only designed to parse the parameter and set statements contained within AMPL data sections. However, in order to parse these statements correctly, information that would usually be contained within the model section may be required. For instance, it may not be possible to infer the dimension of a set purely from its data statement. Therefore, Amply also supports set and parameter declarations. These do not have to be put in a separate section, they only need to occur before the corresponding data statement.The declaration syntax supported is extremely limited, and does not include most elements of the AMPL programming language. The intention is that this library is used as a way of loading data specified in an AMPL-like syntax.Furthermore, Amply does not perform any validation on data statements.About this documentThis document is intended as a guide to the syntax supported by Amply, and not as a general AMPL reference manual. For more in depth coverage see theGNU MathProg manual, Chapter 5: Model dataor the following links:Sets in AMPLParameters in AMPLQuickstart Guide>>> from amply import AmplyImport the class:>>> from amply import AmplyA simple set. Sets behave a lot like lists.>>> data = Amply("set CITIES := Auckland Wellington Christchurch;") >>> print data.CITIES <SetObject: ['Auckland', 'Wellington', 'Christchurch']> >>> print data['CITIES'] <SetObject: ['Auckland', 'Wellington', 'Christchurch']> >>> for c in data.CITIES: print c ... Auckland Wellington Christchurch >>> print data.CITIES[0] Auckland >>> print len(data.CITIES) 3Data can be integers, reals, symbolic, or quoted strings:>>> data = Amply(""" ... set BitsNPieces := 0 3.2 -6e4 Hello "Hello, World!"; ... """) >>> print data.BitsNPieces <SetObject: [0.0, 3.2000000000000002, -60000.0, 'Hello', 'Hello, World!']>Sets can contain multidimensional data, but we have to declare them to be so first.>>> data = Amply(""" ... set pairs dimen 2; ... set pairs := (1, 2) (2, 3) (3, 4); ... """) >>> print data.pairs <SetObject: [(1, 2), (2, 3), (3, 4)]>Sets themselves can be multidimensional (i.e. be subscriptable):>>> data = Amply(""" ... set CITIES{COUNTRIES}; ... set CITIES[Australia] := Adelaide Melbourne Sydney; ... set CITIES[Italy] := Florence Milan Rome; ... """) >>> print data.CITIES['Australia'] ['Adelaide', 'Melbourne', 'Sydney'] >>> print data.CITIES['Italy'] ['Florence', 'Milan', 'Rome']Note that in the above example, the set COUNTRIES didn’t actually have to exist itself. Amply does not perform any validation on subscripts, it only uses them to figure out how many subscripts a set has. To specify more than one, separate them by commas:>>> data = Amply(""" ... set SUBURBS{COUNTRIES, CITIES}; ... set SUBURBS[Australia, Melbourne] := Docklands 'South Wharf' Kensington; ... """) >>> print data.SUBURBS['Australia', 'Melbourne'] ['Docklands', 'South Wharf', 'Kensington']Slicescan be used to simplify the entry of multi-dimensional data.>>> data=Amply(""" ... set TRIPLES dimen 3; ... set TRIPLES := (1, 1, *) 2 3 4 (*, 2, *) 6 7 8 9 (*, *, *) (1, 1, 1); ... """) >>> print data.TRIPLES <SetObject: [(1, 1, 2), (1, 1, 3), (1, 1, 4), (6, 2, 7), (8, 2, 9), (1, 1, 1)]> >Set data can also be specified using a matrix notation. A ‘+’ indicates that the pair is included in the set whereas a ‘-’ indicates a pair not in the set.>>> data=Amply(""" ... set ROUTES dimen 2; ... set ROUTES : A B C D := ... E + - - + ... F + + - - ... ; ... """) >>> print data.ROUTES <SetObject: [('E', 'A'), ('E', 'D'), ('F', 'A'), ('F', 'B')]>Matrices can also be transposed:>>> data=Amply(""" ... set ROUTES dimen 2; ... set ROUTES (tr) : E F := ... A + + ... B - + ... C - - ... D + - ... ; ... """) >>> print data.ROUTES <SetObject: [('E', 'A'), ('F', 'A'), ('F', 'B'), ('E', 'D')]>Matrices only specify 2d data, however they can be combined with slices to define higher-dimensional data:>>> data = Amply(""" ... set QUADS dimen 2; ... set QUADS := ... (1, 1, *, *) : 2 3 4 := ... 2 + - + ... 3 - + + ... (1, 2, *, *) : 2 3 4 := ... 2 - + - ... 3 + - - ... ; ... """) >>> print data.QUADS <SetObject: [(1, 1, 2, 2), (1, 1, 2, 4), (1, 1, 3, 3), (1, 1, 3, 4), (1, 2, 2, 3), (1, 2, 3, 2)]>Parameters are also supported:>>> data = Amply(""" ... param T := 30; ... param n := 5; ... """) >>> print data.T 30 >>> print data.n 5Parameters are commonly indexed over sets. No validation is done by Amply, and the sets do not have to exist. Parameter objects are represented as a mapping.>>> data = Amply(""" ... param COSTS{PRODUCTS}; ... param COSTS := ... FISH 8.5 ... CARROTS 2.4 ... POTATOES 1.6 ... ; ... """) >>> print data.COSTS <ParamObject: {'POTATOES': 1.6000000000000001, 'FISH': 8.5, 'CARROTS': 2.3999999999999999}> >>> print data.COSTS['FISH'] 8.5Parameter data statements can include adefaultclause. If a ‘.’ is included in the data, it is replaced with the default value:>>> data = Amply(""" ... param COSTS{P}; ... param COSTS default 2 := ... F 2 ... E 1 ... D . ... ; ... """) >>> print data.COSTS['D'] 2.0Parameter declarations can also have a default clause. For these parameters, any attempt to access the parameter for a key that has not been defined will return the default value:>>> data = Amply(""" ... param COSTS{P} default 42; ... param COSTS := ... F 2 ... E 1 ... ; ... """) >>> print data.COSTS['DOES NOT EXIST'] 42.0Parameters can be indexed over multiple sets. The resulting values can be accessed by treating the parameter object as a nested dictionary, or by using a tuple as an index:>>> data = Amply(""" ... param COSTS{CITIES, PRODUCTS}; ... param COSTS := ... Auckland FISH 5 ... Auckland CHIPS 3 ... Wellington FISH 4 ... Wellington CHIPS 1 ... ; ... """) >>> print data.COSTS <ParamObject: {'Wellington': {'FISH': 4.0, 'CHIPS': 1.0}, 'Auckland': {'FISH': 5.0, 'CHIPS': 3.0}}> >>> print data.COSTS['Wellington']['CHIPS'] # nested dict 1.0 >>> print data.COSTS['Wellington', 'CHIPS'] # tuple as key 1.0Parameters support a slice syntax similar to that of sets:>>> data = Amply(""" ... param COSTS{CITIES, PRODUCTS}; ... param COSTS := ... [Auckland, * ] ... FISH 5 ... CHIPS 3 ... [Wellington, * ] ... FISH 4 ... CHIPS 1 ... ; ... """) >>> print data.COSTS <ParamObject: {'Wellington': {'FISH': 4.0, 'CHIPS': 1.0}, 'Auckland': {'FISH': 5.0, 'CHIPS': 3.0}}>Parameters indexed over two sets can also be specified in tabular format:>>> data = Amply(""" ... param COSTS{CITIES, PRODUCTS}; ... param COSTS: FISH CHIPS := ... Auckland 5 3 ... Wellington 4 1 ... ; ... """) >>> print data.COSTS <ParamObject: {'Wellington': {'FISH': 4.0, 'CHIPS': 1.0}, 'Auckland': {'FISH': 5.0, 'CHIPS': 3.0}}>Tabular data can also be transposed:>>> data = Amply(""" ... param COSTS{CITIES, PRODUCTS}; ... param COSTS (tr): Auckland Wellington := ... FISH 5 4 ... CHIPS 3 1 ... ; ... """) >>> print data.COSTS <ParamObject: {'Wellington': {'FISH': 4.0, 'CHIPS': 1.0}, 'Auckland': {'FISH': 5.0, 'CHIPS': 3.0}}>Slices can be combined with tabular data for parameters indexed over more than 2 sets:>>> data = Amply(""" ... param COSTS{CITIES, PRODUCTS, SIZE}; ... param COSTS := ... [Auckland, *, *] : SMALL LARGE := ... FISH 5 9 ... CHIPS 3 5 ... [Wellington, *, *] : SMALL LARGE := ... FISH 4 7 ... CHIPS 1 2 ... ; ... """) >>> print data.COSTS <ParamObject: {'Wellington': {'FISH': {'SMALL': 4.0, 'LARGE': 7.0}, 'CHIPS': {'SMALL': 1.0, 'LARGE': 2.0}}, 'Auckland': {'FISH': {'SMALL': 5.0, 'LARGE': 9.0}, 'APIAll functionality is contained within theAmplyclass.load_string(string)Parse string data.load_file(file)Parse contents of file or file-like object (has a read() method).from_file(file)Alternate constructor. Create Amply object from contents of file or file-like object.The parsed data structures can then be accessed from anAmplyobject via attribute lookup (if the name of the symbol is a valid Python name) or item lookup.from pulp import Amply data = Amply("set CITIES := Auckland Hamilton Wellington") # attribute lookup assert data.CITIES == ['Auckland', 'Hamilton', 'Wellington'] # item lookup assert data['CITIES'] == data.CITIESNote that additional data may be loaded into an Amply object simply by calling one of its methods. A common idiom might be to specify the set and parameter declarations within your Python script, then load the actual data from external files.from pulp import Amply data = Amply(""" set CITIES; set ROUTES dimen 2; param COSTS{ROUTES}; param DISTANCES{ROUTES}; """) for data_file in ('cities.dat', 'routes.dat', 'costs.dat', 'distances.dat'): data.load_file(open(data_file))Development NotesMany thanks to Johannes Ragam (@thet), former custodian of the “amply” project on PyPi. Johannes graciously transferred the project to this. Thanks!
amply-mail
AmplyThis is the Amply Python SDK that integrates with thev1 API.Table of ContentsInstallQuick StartMethodsemailInstallPrerequisitesPython 2.7, 3.5, 3.6, 3.7, or 3.8Amply account,sign up here.Access TokenObtain your access token from theAmply UI.Install Packagepip install amply-mailDomain VerificationAdd domains you want to sendfromvia theVerified Domainstab on your dashboard.Any emails you attempt to send from an unverified domain will be rejected. Once verified, Amply immediately starts warming up your domain and IP reputation. This warmup process will take approximately one week before maximal deliverability has been reached.Quick StartThe following is the minimum needed code to send a simple email. Use this example, and modify thetoandfromvariables:importamplyimportosamply.set_access_token(os.environ.get('AMPLY_ACCESS_TOKEN'))try:response=amply.email.create({'to':'[email protected]','from':'[email protected]','subject':'My first Amply email!','text':'This is easy','html':'<strong>and fun :)</strong>'})exceptExceptionase:ifhasattr(e,'errors'):print('Validation or resource not found error')print(e.errors)elifhasattr(e,'text'):print('Generic API error:%s'%(e.text))else:raiseeOnce you execute this code, you should have an email in the inbox of the recipient. You can check the status of your email in the UI from theSearch,SQL, orUserspage.MethodsemailParameter(s)Descriptionto, cc, bccEmail address of the recipient(s). This may be a stringTest <[email protected]>, an object{name: 'Test', email: '[email protected]'}, or an array of strings and objects.personalizationsFor fine tuned access, you may override the to, cc, and bcc keys and use advanced personalizations. See the API guidehere.fromEmail address of the sender. This may be formatted as a string or object. An array of senders is not allowed.subjectSubject of the message.htmlHTML portion of the message.textText portion of the message.contentAn array of objects containing the following keys:type(required),value(required).templateThe template to use. This may be a string (the UUID of the template), an array of UUID's (useful for A/B/... testing where one is randomly selected), or an object of the format{template1Uuid: 0.25, template2Uuid: 0.75}(useful for weighted A/B/... testing).dynamic_template_dataThe dynamic data to be replaced in your template. This is an object of the format{variable1: 'replacement1', ...}. Variables should be defined in your template body using handlebars syntax{{variable1}}.reply_toEmail address of who should receive replies. This may be a string or an object withnameandemailkeys.headersAn object where the header name is the key and header value is the value.ip_or_pool_uuidThe UUID of the IP address or IP pool you want to send from. Default is your Global pool.unsubscribe_group_uuidThe UUID of the unsubscribe group you want to associate with this email.attachments[][content]A base64 encoded string of your attachment's content.attachments[][type]The MIME type of your attachment.attachments[][filename]The filename of your attachment.attachments[][disposition]The disposition of your attachment (inlineorattachment).attachments[][content_id]The content ID of your attachment.clicktrackingEnable or disable clicktracking.categoriesAn array of email categories you can associate with your message.substitutionsAn object of the format{subFrom: 'subTo', ...}of substitutions.send_atDelay sending until a specified time. An ISO8601 formatted string with timezone information.Exampleamply.email.create({'to':'[email protected]','from':'From <[email protected]>','text':'Text part','html':'HTML part','personalizations':[{'to':[{'name':'Override To','email':'[email protected]'}]}],'content':[{'type':'text/testing','value':'some custom content type'}],'subject':'A new email!','reply_to':'Reply To <[email protected]>','template':'faecb75b-371e-4062-89d5-372b8ff0effd','dynamic_template_data':{'name':'Jimmy'},'unsubscribe_group_uuid':'5ac48b43-6e7e-4c51-817d-f81ea0a09816','ip_or_pool_uuid':'2e378fc9-3e23-4853-bccb-2990fda83ca9','attachments':[{'content':'dGVzdA==','filename':'test.txt','type':'text/plain','disposition':'inline'}],'headers':{'X-Testing':'Test'},'categories':['Test'],'clicktracking':True,'substitutions':{'sub1':'replacement1'},'send_at':datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).isoformat()})
ampo
Aio Mongo Pydantic ORM (ampo)Features:AsynchronousUsageAll example run into:python-masyncioCreate and get objectfromampoimportCollectionWorker,AMPODatabase,ORMConfig,init_collection# Initilize DB before calls db methodsAMPODatabase(url="mongodb://test")# Pydantic ModelclassModelA(CollectionWorker):field1:strfield2:intmodel_config=ORMConfig(orm_collection="test")awaitinit_collection()inst_a=ModelA("test",123)awaitinst_a.save()# Get objectinst_a=awaitModelA.get(field1="test")IdFor search by 'id' usages in filter '_id' or 'id' name.Indexes# import# Initilize DB before calls db methodsAMPODatabase(url="mongodb://test")# Pydantic ModelclassModelA(CollectionWorker):field1:strmodel_config=ORMConfig(orm_collection="test",orm_indexes=[{"keys":["field1"],"options":{"unique":True}}])# This method create indexes# Call only one timeawaitinit_collection()Suppport options:uniqueexpireAfterSecondsKeys is list of fields.TTL IndexIt works only with single field (TTL Indexes).You should set the option 'expireAfterSeconds', and field 'keys' should have only single field.Example:# import# Initilize DB before calls db methodsAMPODatabase(url="mongodb://test")# Pydantic ModelclassModelA(CollectionWorker):field1:datetimemodel_config=ORMConfig(orm_collection="test",orm_indexes=[{"keys":["field1"],"options":{"expireAfterSeconds":10}}])# optional, set new valueModelA.update_expiration_value("field1",20)awaitinit_collection()if you want to set the 'expireAfterSeconds' only from method 'update_expiration_value', set it to '-1'.Relationships between documentsEmbededIt is supported by default. Just, you need create the embedded document as class of pydantic - 'BaseModel'. It will be stored into db as object.Example:frompydanticimportBaseModelclassEmbeded(BaseModel):name:strclassModelA(CollectionWorker):field1:strfield2:Embededmodel_config=ORMConfig(orm_collection="test")DevelopmentStyle:NumPy/SciPy docstrings style guideRun tests:envTEST_MONGO_URL=mongodb://localhost/testpytest
ampoul3
Ampoule is a process pool implementation written on top of Twisted Matrix. Its name comes from the use of AMP as the default communication protocol between the pool and all its children.It’s different from other alternative solutions because it provides an API very close to that of the Twisted ThreadPool. As an helper function it also provides a deferToAMPProcess function that creates the ProcessPool and submits jobs to it.
ampoule
Ampoule - a process pool for Twisted, based on AMPAmpoule is a process pool written on top ofTwisted. Its name comes from the use ofAMPas the default communication protocol between the pool and all its children.It provides an API very close to that of the built-in TwistedThreadPool. As an helper function it also provides adeferToAMPProcessfunction that creates theProcessPooland submits jobs to it.
amp-player
No description available on PyPI.
amp-python-thin-scaledinference
amp-python-thinPython thin client for Amp.ai
ampq_cl
Python version must be greater than 3.7.1Based on the packagekombu==3.0.35pika==0.13.1The sample code::def worker(data):… return SUCCESSconsumer = Consumer(“amqp://account:password@ip:port/vhost”, “queue”, worker) consumer.run()
amp-renderer
AMP RendererUnofficial Python port ofserver-side renderingfromAMP Optimizer. Supports Python 3.6 and above.AMP Renderer performs the following optimizations:Inject the specific layout markup into each AMP elementInsert the AMP runtime styles into the documentRemove the AMP boilerplate styles, if possibleMark the document as “transformed” with the appropriate tags on thehtmlelementInsertimgtags for images with the data-hero attributeIt also makes these formatting updates:Remove emptyclassandstyletags for AMP HTML elementsConvert tag names and attribute names to lowercaseConvert numerical attribute values to stringsUse double quotes ("") for attributes, and escape double quotes inside attribute valuesRemove whitespace between html attributesIf desired, removes comments (disabled by default)If desired, trims whitespace around HTML attribute values (disabled by default, and not always a good idea)AMPRenderer can be used on a block of arbitrary HTML, but when used on a full document, it will insert the AMP runtime styles and, if possible, remove the AMP boilerplate styles.Boilerplate styles can be removed except in these cases:An AMP element uses an unsupported value for thelayoutattributeamp-audiois usedThere is at least oneamp-experimentactiveTransformation fails for one or more elements due to an invalid attribute value formedia,sizes, orheightsAny render-delaying extension is used. Currently this means:amp-dynamic-css-classesamp-storyIf boilerplate styles can’t be removed, the attributeno_boilerplatewill be set toTrueafter callingrender; otherwise it will beFalse. Untilrenderruns, theno_boilerplateattribute isn’t set at all.UsageIf using Django, you can use theDjango AMP Renderer middleware.Otherwise, install via PyPI:pip install amp-rendererMinimal usage:from amp_renderer import AMPRenderer ... RUNTIME_VERSION = "012345678" /* Current AMP runtime version number */ RUNTIME_STYLES = "..." /* Current contents of https://cdn.ampproject.org/v0.css */ renderer = AMPRenderer( runtime_version=RUNTIME_VERSION, runtime_styles=RUNTIME_STYLES) original_html = """ <!doctype html> <html ⚡> ... </html> """ result = renderer.render(original_html) print(result)Remove comments and/or trim attributes:renderer.should_strip_comments = True renderer.should_trim_attributes = True result = renderer.render(original_html) print(result)The AMPRenderer class inherits fromHTMLParser, and can be similarly extended.Testing, etc.Install requrements:make installSort imports (Requires Python >= 3.8):make formatLint (Requires Python >= 3.8):make lintTest:make testDiscussionThere are still some aspects of the official AMP Optimizer implementation that haven’t been addressed yet. PRs welcome.GeneralTested against AMP Optimizer’s ServerSideRendering specAutomatic runtime version managementDynamic attributesSupportsizes,media, andheightsvia CSS injectionGroup CSS injections formediaattributes by shared media queries to reduce necessary bytesSupport percent values inheightsWarn or fail if CSS injection puts theamp-customelement over the byte limitHero ImagesInjectimgtag foramp-imgs with thedata-heroattributeEnforce 2-image limit ondata-heroAutodetect hero imagesSupport hero image functionality foramp-iframe,amp-video, andamp-video-iframePerformanceThe Python AMP Renderer does not insertpreloadlinks into theheadof the DOM object for hero images; This can be done by hand for more control over the critical path.
amps
Amps (Are My Packages Safe?) - A package scanner for Arch Linux based systemsampsscans all packages installed via pacman on your system and provides you a simple report of those with open CVE's reportedhere.Amps currently only supports Arch Linux based systems, butapt,dpkg, anddnfcapabilities are planned to work for more devices.InstallationVia PyPI:pipinstallampsAs a python script:curl-Ohttps://raw.githubusercontent.com/isaacmg00/amps/main/amps/amps.py pythonamps.py
ampscz-anonymize-dicom
AMP-SCZ Dicom AnonymizerContentsIntroduction Dependencies Installation How to run AMP-SCZ Dicom AnonymizerIntroductionDependenciesTested on osxxquartz (https://www.xquartz.org)python(3) withpipaccessible in the shellInstallationInstallation throughpypi$ pip install ampscz_anonymize_dicomHow to run AMP-SCZ Dicom Anonymizer$ ampscz_anonymize_dicomDrag the root of the dicom directoryDrag the output directoryEdit the AMP-SCZ IDEnter the session numberClick "Run deidentification"
ampscz-lochness
Lochness: Sync data from all over the cloud to a local directoryLochness is a data management tool designed to periodically poll and download data from various data archives into a local directory. This is often referred to as building a "data lake" (hence the name).Out of the box there is support for pulling data down from Beiwe, XNAT, REDCap, Dropbox, external hard drives, and more. Extending Lochness to support new services is also a fairly simple process.Table of contentsInstallationQuick setup from a templateDocumentationInstallationJust usepippip install lochnessFor most recent DPACC-lochnesspip install git+https://github.com/PREDICT-DPACC/lochnessFor debuggingcd ~ git clone https://github.com/PREDICT-DPACC/lochness pip install -r ~/lochness/requirements.txt export PATH=${PATH}:~/lochness/scripts # add to ~/.bashrc export PYTHONPATH=${PYTHONPATH}:~/lochness # add to ~/.bashrcRunning testCopy the token template, and add the information for each module.cd lochness/tests cp token_template_for_test_template.csv token_template_for_test.csvRun testbash run_test.shSetup from a templateCreating the templateSetting up lochness from scratch could be slightly confusing in the beginning. Try using thelochness_create_template.pyto create a starting point.Create an example template to easily structure the lochness system# ProNETlochness_create_template.py\--outdir/data/lochness_root\--studiesPronetLAPronetSLPronetWU\--sourcesredcapxnatboxmindlamp\[email protected]\--poll_interval43200\--ssh_hosterisone.partners.org\--ssh_userkc244\--lochness_sync_send\--s3# PRESCIENTlochness_create_template.py\--outdir/data/lochness_root\--studiesPrescientADPrescientMEPrescientPE\--sourcesRPMSmediafluxmindlamp\[email protected]\--poll_interval43200\--ssh_hosterisone.partners.org\--ssh_userkc244\--lochness_sync_send\--s3# For more options: lochness_create_template.py -hMaking edits to the templateRunning one of the commands above will create the structure below/data/lochness_root/ ├──1_encrypt_command.sh ├──2_sync_command.sh ├──PHOENIX │├──GENERAL ││├──PronetLA │││└──PronetLA_metadata.csv ││├──PronetSL │││└──PronetSL_metadata.csv ││└──PronetWU ││└──PronetWU_metadata.csv │└──PROTECTED │├──PronetLA │├──PronetSL │└──PronetWU ├──config.yml ├──lochness.json └──pii_convert.csvChange information inconfig.ymlandlochness.jsonas needed.Either manually update thePHOENIX/GENERAL/*/*_metadata.csvor amend the field names in REDCap / RPMS sources correctly for lochness to automatically update the metadata files.Currently, lochness initializes the metadata using the following field names in REDCap and RPMS.chric_subject_id: the record ID field namethis field name must be in the REDCap or RPMS repository for the metadata to be updated by lochness.chric_consent_date: the field name of the consent datethis field name must be in the REDCap or RPMS repository for the metadata to be updated by lochness.beiwe_id: the field name of the BEIWE ID.xnat_id: the field name of the XNAT ID.dropbox_id: the field name of the Dropbox ID.box_id: the field name of the Box ID.mediaflux_id: the field name of the Mediaflux ID.mindlamp_id: the field name of the Mindlamp ID.daris_id: the field name of the DaRIS ID.rpms_id: the field name of the RPMS ID.Encrypt thelochness.jsonby runningcd/data/lochness_root bash1_encrypt_command.shThis encryption step creates a copy of encrypted keyrings to/data/lochness_root/.lochness.enc. To protect the sensitive keyring information in json, remove thelochness.jsonafter running the encryption.You can still extract keyring structure without sensitive information by runninglochness_check_config.py -ke /data/lochness_root/.lochness.encSet up REDCap Data Entry Trigger if using REDCap. Please see below "REDCap Data Entry Trigger capture" section.Edit Personally identifiable information mapping table. Please seee below "Personally identifiable information removal from REDCap and RPMS data"/data/lochness_root/pii_convert.csvRun thesync.pyor use the example command in2_sync_command.shbash 2_sync_command.shTo uselochness_to_lochnesstransfer throughaws s3Set up s3 bucketInstall aws CLIConfigure CLI with your s3 bucket information$ aws configureAdd your AWS information toconfig.ymlAWS_BUCKET_NAME: ampscz-dev AWS_BUCKET_ROOT: TEST_PHOENIX_ROOTREDCap Data Entry Trigger captureIf your sources include REDCap and you would like to configure lochness to only pull new REDCap data, "Data Entry Trigger" needs to be set up in REDCap.In REDCap,"Project Setup""Enable optional modules and customizations""Additional customizations"Check "Data Entry Trigger" and give address of the server including the port number e.g.http://pnl-t55-7.partners.org:9999In order to use this functionality, the server where lochness is installed should be able to receieve HTTP POST signal from REDCap server. Which means it has to be eitherlochness server is inside the same firewall as REDCap server. Orlochness server has a open port that could listen to the REDCap POST signal.After setting the "Data Entry Trigger" on REDCap settings, run below to update the/data/data_entry_trigger_db.csvreal-time# please specify the same port defined in the REDCap settings listen_to_redcap.py --database_csv /data/data_entry_trigger_db.csv \ --port 9999It would be useful to runlisten_to_redcap.pyin background, maybe inside agnu screenso it runs continuously without interference.Personally identifiable information removal from REDCap and RPMS dataA path of csv file can be provided, which has information about how to process each PII fields.For example/data/personally_identifiable_process_mappings.csvpii_label_string | process -----------------|--------------- address | remove date | change_date phone_number | random_number patient_name | random_string subject_name | replace_with_subject_idAny value from the field, with names that match topii_label_stringrows, the labelledPII processing methodwill be used to process the raw values to remove or replace the PIIs.DocumentationYou can find all the documentation you will ever needhere
amps-py
AMPS PythonThis package serves as an interface to theAgile Message Processing System (AMPS)by providing Action, Endpoint, and Service classes that can be used in AMPS Actions, Gateways, and Custom Services, respectively.The package documentation is availablehere
amps-python-client
AMPS Python ClientIntroductionThe AMPS Python Client is a Python extension module that makes it easy to connect to AMPS. This client builds upon the AMPS C++ Client and Python/C api to bring high performance AMPS connectivity to Python code.PrerequisitesTo use the AMPS Python Client, you must have the following software installed and configured on your system:Python 2.7 or Python 3.5 and above.Python distutils. Most python installations build and include this package by default, but you may run into issues building this extension module if distutils is not functioning properly on your system. Python distutils may be packaged in a standalone package named 'python-distutils', or included in 'python-devel.x86_64'. You can also run the setup script availablehere.C++ compiler. gcc 4.4 or greater on Linux, or a verion of Visual Studio with Mainstream Support from Microsoft (please refer to Microsoft product lifecycle policies) on Windows. Note that this must be the same compiler used to build your python distribution, else python distutils may be unable to invoke your compiler.Fedora prerequisites:dnf install redhat-rpm-configdnf install python-devel # for use with Python2dnf install python3-devel # for use with Python3dnf install gcc-c++Building From a Git CloneIf you obtained this client by a git clone of the 60East amps-client-python repository, you also need to fetch the correct version of the AMPS C++ client submodule. To do this, issue a git submodule command to initialize and update the src/cpp submodule. One easy way to do this is by issuing the command:git submodule update --initwhich will initialize and update the submodule in one step. Note that working with submodules in git requires extra care. Visitthis chapterto learn more about git submodules.BuildThis client is distributed as source code and must be compiled before it is used. The build process emits a shared library (or DLL on Windows) that can be imported into your python application.To build on Linux:Runpython setup.py buildfrom the AMPS Python Client directory to build the client.This script uses Python distutils to build the client library. Python distutils provides many additional options for installing the built library into your Python distribution, or otherwise controlling the output of the build process. Runpython setup.py --helpto view command help.Check under thebuilddirectory forAMPS.so-- this is the Python extension module. Ensure this library's directory is in your PYTHONPATH.To test, runpython -c "import AMPS". If any errors occur importing the AMPS module, validate that the module built properly, and that the containing directory is in your PYTHONPATH.To build on Windows:Use a Visual Studio Command Prompt to create a command prompt where the necessary Visual Studio environment variables are set for command line builds.Add the Python directory (the location of the python.exe interpreter) to your path.Note:The platform of your python installation must match the target platform for this python module. If you want to build a 64-bit module, you must set your PATH to a 64-bit Python installation; for a 32-bit module, you must set it to a 32-bit installation. If you'd like to build both, you must do so separately, once with each Python installation.Runpython setup.py buildfom the AMPS Python Client directory to build the client module. Use the-p win32option to build a 32-bit client module.Check under thebuilddirectory forAMPS.pyd-- this is the Python extension module. Ensure this library's directory is in your PYTHONPATH.To test, runpython -c "import AMPS". If any errors occur importing the AMPS module, validate that the module built properly, and that the containing directory is in your PYTHONPATH.Installing the Python Binary Wheel60East also provides Linux-x86-64 and Windows 64-bit binary wheels built with Python 2.7 and for Python 3.x. These wheel files are provided on the 60East website.If your system is not Linux-x86-64, or you are not using Python 2.6, you can generate your own egg by running 'python setup.py bdist_wheel'.Installing:Download the wheel file from the 60East client release page.run 'python -m pip install *.whl'.Troubleshooting Build ProblemsSymptom: Python.h not foundResolution: Update or install python distutils. See the entry on python distutils in the prequisites section for information on installing this package.For More InformationThe developer's guide and generated reference documentation for this client are available under the doc/ directory.
ampt2
ampt2这是一个简单的介绍
amptk
AMPtkNGS AMPlicon Tool Kit:Documentation:http://amptk.readthedocs.io/CitationPalmer JM, Jusino MA, Banik MT, Lindner DL. 2018. Non-biological synthetic spike-in controls and the AMPtk software pipeline improve mycobiome data. PeerJ 6:e4925; DOI 10.7717/peerj.4925.https://peerj.com/articles/4925/
amp-tools
Python AMP LibraryThis library contains class what converts html to AMP.Work in progressInstallationpipinstallamp_toolsUsage examplefromamp_toolsimportTransformHtmlToAmphtml_elements='<span class="test-class">'\'<form class="form-test"></form>'\'<img src="media/test.png" width="300" height="220">'\'</span>'valid_amp=TransformHtmlToAmp(html_elements)()# Returnb'<div class="amp-text"><amp-img src="media/test.png" width="300" height="220" layout="responsive"></amp-img></div>'
amptrac
# -*- mode: org -*-* Amptrac, A Completely Ridiculous Issue TrackerI wrote this because twistedmatrix.com has a Trac instance full ofvaluable data, and Trac has become increasingly annoying over the past7 years. Amptrac is an attempt to provide a better face on that data.** How It WorksAmptrac provides an AMP listeners in a Twisted-based server,and a command-line client.*** ServerAMP commands in amptrac.responder define the interface for working withticket data.*** ClientXXX** How To Run ItIf you want to develop Frack, the tests can be run via 'trialamptrac.test'. For running a development server:# load some test data into an sqlite dbsqlite3 < frack/test/trac_test.sql trac.db# start the server (the URL here must be the url at which you will# access the site)twistd -n amptrac --sqlite_db=trac.db# After starting the server, you can thenbin/review-tickets# orbin/fetch-ticket <id>Ticket numbers in the test database are: 3312, 5622, 5517, 2723, 4712.
ampule
No description available on PyPI.
ampy
Website|Documentation|Paper|Video Tutorial(TBD) |Colab NotebookAMPyis abaselinelibrary built uponOpenCVandNumPyto easily process experimental video data for active matter and disordered systems. Our library turns the processing of experiment recordings into a cakewalk, considerably accelerating extraction of system dynamics.OverviewThe library is comprised of 4 components:processing.py,statistic2d.py,statistic3d.py,animation.py, andutils.py.processing.pyhandles the initial processing of experimental video recordings and tracks the ArUco markers placed on the robots' upper surfaces.statistics2d.pyextracts various two-dimensional statistical measures from obtained kinematics (such as Cartesian displacement or order parameters).statistics3d.pyevaluates position, orientation, and velocity correlation maps for the entire platform.animation.pygenerates .gif/.mp4 with different visual augmentations of an input video.utils.pyprovides methods for reading/saving video data.If you want a brief introduction into library capabilities, we prepareda Colab tutorialfor that occasion.InstallationAMPy is available atthe Python Package Index:$ pip install ampyPreparing markersFor users' convenience, we providethe .ipynb notebookallowing to generate ArUco- and AprilTag-based markers for tracking of their own robots.Contact usIf you have some questions about the code, you are welcome to open an issue, we will respond to that as soon as possible. Contributions towards extension of AMPy functionality are more than welcome!LicenseEstablished code released as open-source software under the GPLv3 license.Citation@misc{ dmitriev2023swarmobot, title={Swarmodroid 1.0: A Modular Bristle-Bot Platform for Robotic Active Matter}, author={Alexey A. Dmitriev and Alina D. Rozenblit and Vadim A. Porvatov and Mikhail K. Buzakov and Anastasia A. Molodtsova and Daria V. Sennikova and Vyacheslav A. Smirnov and Oleg I. Burmistrov and Ekaterina M. Puhtina and Nikita A. Olekhno}, year={2023}, eprint={2305.13510}, archivePrefix={arXiv}, primaryClass={cond-mat.soft} }
ampy-batch-tool
AMPY Batch Tool项目介绍AMPY Batch Tool简称ab,可以批量将项目中指定的文件夹或文件上传到MicroPython开发板痛点问题使用MicroPython写代码玩板子的时候我遇到过一些看似可以忍受但内心不停在咆哮的痛点问题比如最早使用PyCharm写代码,遇到的问题是上传文件太慢,这个是看似可以忍受的,但不能忍的是经常性的出现上传失败的问题,放弃后来使用过rshell-lite,纯命令行工具,不支持批量文件和文件夹上传,这对只写单文件项目的人来说问题不大,不过我喜欢把项目文件分类保存,放弃现在使用VS Code+RT-Thread插件,这个插件支持文件夹上传了,但速度依然很慢,而且不支持排除文件、文件夹功能,但最大的问题是它会在后台不停的运行一个串口检测程序,浪费内存可以忍,不能忍的是当打开第二个VS Code窗口的时候,前一个已经连接的串口会被强迫断开,而且作者已经停更了,这个不放弃,改改脚本还可以当做代码补全工具使用上面说到上传速度慢的问题,归根结底是因为它们上传文件的模式有问题,大概流程是这样的:打开串口创建文件夹、上传文件关闭串口重复第一步,直到最后一个文件上传完毕所以问题就出现在不停打开关闭串口上了,要解决问题也很简单,使用pyboard.py替代ampy工具,然后:打开串口创建所有文件夹、上传所有文件关闭串口简单粗暴,有效果!如何安装在线安装(推荐)# 安装$pipinstallampy-batch-tool# 更新$pipinstall--upgradeampy-batch-tool离线安装首先克隆或下载项目源文件压缩包并解压缩,然后进入项目文件夹运行命令$pythonsetup.pyinstall# for local develop$pipinstall-e.如何上传文件在你的项目文件夹下新建abconfig配置文件(ab工具默认查找该配置文件,也可以手动指定其它文件)配置文件中填写需要上传的文件夹或文件,每行一个,例如:drivers/ !test.py main.py !services/ not_exists/ #services/websocket.py # .git/以#号开头的行:上传时排除的文件夹或文件以!号开头的行:在repl模式下上传文件后立即运行该文件在需要上传项目文件的时候执行如下命令即可$ab# 或$ababconfig如果找不到或者未手动指定配置文件,则显示使用说明完整输出内容Port List: [1] COM8 - Silicon Labs CP210x USB to UART Bridge (COM8) [2] COM1 - 通信端口 (COM1) Choose a port: 1 File List (3): - drivers/button.py - services/mqtt.py - main.py Dir List (3) - drivers - drivers/others - services Not Found List (1) - not_exists Making dirs on board... - drivers exist - drivers/others exist - services exist Upload files to board... - uploading drivers/button.py (1/3) - uploading services/mqtt.py (2/3) - uploading main.py (3/3) Upload FinishedREPL 模式使用说明$ab--repl# --replcdc // for usb cdc visual serial portPortList:[1]COM3-SiliconLabsCP210xUSBtoUARTBridge(COM3)[2]COM1-通信端口(COM1)Chooseaport:1MinitermforMicroPythonREPLCtrl-Z-QuitCtrl-N-HelpCtrl-X-Killmain.pyCtrl-Y-SerialInfoCtrl-L-RunlastfileCtrl-R-RunlocalfileCtrl-T-RunboardfileCtrl-G-RunclipboardcodeCtrl-U-Uploadfilestoboard >>>help()WelcometoMicroPythonontheESP32! Forgenericonlinedocspleasevisithttp://docs.micropython.org/ >>>repl模式快捷键Ctrl+Z:退出replCtrl+X:一键删除main.py文件Ctrl+G:将剪贴板中的代码粘贴到repl中Ctrl+Y:显示串口相关设置Ctrl+O:显示快捷键说明Ctrl+R:运行本地文件Ctrl+T:运行远程文件Ctrl+L:再次运行上次的本地文件Ctrl+U:上传配置文件中的文件,并运行指定文件一键删除main.py文件有些时候由于在代码中写入死循环,导致无法删除或者重新上传文件的情况,可以尝试使用这个功能,快捷键为:Ctrl+X运行本地.py文件快捷键为:Ctrl+R>>> Run local file [1] upload_to_pypi.py [2] setup.py [3] local.py [4] ab\__main__.py [5] ab\__init__.py [6] ab\pyboard.py [7] ab\miniterm.py Choose a file: 3 boot.py - FILE client - PATH drivers - PATH onboard.py - FILE this is a local py file >>>运行远程.py文件也就是运行开发板上的文件,快捷键为:Ctrl+T>>> Run onboard file [1] /boot.py [2] /drivers/ssd1306.py [3] /onboard.py Choose a file: 3 this is a onboard py file >>>运行剪贴板中的代码段快捷键为:Ctrl+G需要注意复制的代码段的缩进>>> Run clipboard code HZK Info: //client/combined.bin file size : 303520 font height : 16 data size : 32 scan mode : Horizontal byte order : LSB characters : 8932 slave id: 60 >>>重新运行之前的文件快捷键为:Ctrl+L注意:只能重新运行上一次的本地文件和使用快捷键Ctrl+U上传并运行的远程文件因为开发板上文件的运行方式不同,所以暂不支持一键重新运行上传配置文件中指定的文件省去每次上传文件都要退出repl模式的麻烦,快捷键为:Ctrl+U上传时会查找根目录下以abc开头的文件作为配置文件烧录固件要烧录固件,可以使用如下命令并根据提示操作:每个选择列表中第一项为默认值,可使用回车直接选择$ab--flash Anesptoolshell PortList:[1]COM3-SiliconLabsCP210xUSBtoUARTBridge(COM3)Chooseanoption: ChipList:[1]auto[2]esp8266[3]esp32[4]esp32c3[5]esp32s2[6]esp32s3[7]esp32c2[8]esp32c6[9]esp32s3beta2[10]esp32c6beta[11]esp32h2beta1[12]esp32h2beta2 Chooseanoption: AddressList:[1]0x1000[2]0x0-foresp32c3,esp32s3 Chooseanoption: FirmwareList:[1]wh_esp32_espnow_v1.17_20210912.bin Chooseanoption:参数说明-h:显示使用说明-m:使用minify工具压缩代码(功能未实现)-q:屏蔽操作过程中的相关提示-s:模拟操作过程,不实际上传文件--repl:进入repl模式--replcdc:进入虚拟串口repl模式--flash:使用esptool烧录固件--readme:在网页中显示使用说明已知问题调用ampy工具新建文件夹的时候如果文件夹已存在,则会抛出异常且无法捕捉偶尔出现无法进入raw_repl模式的问题,重新运行一次即可解决偶尔出现repl模式下无法输入的问题,重启开发板即可解决repl模式下上传文件也许会出现文件不完整的问题,尝试重新上传可以解决使用烧录固件功能时如果提示类似找不到esptool的信息,卸载后重新安装一次即可更新记录v0.7.14:修复快捷键Ctrl+X可能导致串口卡死的问题v0.7.13:精简代码v0.7.12:修复USB CDC模式下快捷键Ctrl+X无法正常复位的问题修复USB CDC模式下运行本地文件串口卡死的问题v0.7.11:MicroPython最新固件不需要--replcdc参数也可以正常调试了修复了使用虚拟串口发送数据可能导致的卡死的问题v0.7.10:新增--replcdc参数,可用于虚拟串口调试v0.7.9:修复串口号过滤错误v0.7.8:修复串口号过滤错误,增加对esptool工具的版本要求v0.7.7:烧录固件工具串口列表过滤掉COM1v0.7.6:修复串口列表过滤逻辑错误v0.7.5:一键删除main.py文件后执行硬重启,串口列表过滤掉COM1v0.7.4:repl模式使用回车键选择第一个端口v0.7.3:修复v0.7.2的 bug,无语。。。。v0.7.2:修改运行esptool.py为esptool。。。。v0.7.1:修改运行esptool为esptool.pyv0.7:新增--flash参数,使用esptool烧录固件v0.6.2:再次尝试修复v0.6.1的问题,应该是串口写入等待时间不够,只能增加延时v0.6.1:修复repl模式下上传文件不完整和不能运行文件的问题v0.6:增加在repl模式下直接上传文件的功能v0.5:调整了repl模式下的快捷键repl模式增加运行本地文件功能repl模式增加运行远程文件功能美化repl模式提示内容v0.4.2:repl模式增加一键删除main.py文件功能v0.4.1:repl模式增加粘贴代码功能v0.4:增加进入repl模式菜单和相关功能v0.3.2:修复由于v0.3.1导致的分隔路径错误问题v0.3.1:修复上传文件时字符转义的问题v0.3:重构了获取所有文件和文件夹列表功能增加了显示网页版使用说明的参数enter_raw_repl()中增加延时,尝试解决已知问题2v0.2.2:修复某些开发板不能读取串口数据的问题(如安信可 ESP32C3 系列开发板)v0.2.1:修复导入模块路径问题v0.2:使用pyboard.py替代ampy以提升文件上传效率,并解决已知问题 1禁用了代码压缩功能,使用pyminifier压缩代码会出现问题删除指定临时目录参数v0.1.1:尝试上传到PyPIv0.1:完成基本功能附录:repl快捷键汇总排除掉MicroPython已经使用的,以及与各种编辑器和终端发生冲突的,而且只能使用字母键,所以实际可用的按键其实并不多,凑合选择了一组,就是现在使用的这些# 不可用的Ctrl+:A-rawreplmodeB-softreset/exitrawreplC-interruptrun/cancelpastemodeD-softreset/finishpastemodeE-pastemodeI-listimportedmodulesJ,M-enterkeyP-upkeyV-mostlypaste# 之前使用的Ctrl+:L-showserialportinfoO-showhelpR-runlocalpyfileT-runonboardpyfileU-runcodeinclipboard]-quit[-deleteonboardfilemain.py# 现在使用的Ctrl+:Z-quitX-deleteonboardfilemain.pyN-showhelpY-showserialportinfoL-runlastpyfile(local/onboard)R-runlocalpyfileT-runonboardpyfileG-runcodeinclipboardU-uploadfilestoboard# 可用的 (闲置的)Ctrl+:F-vsc冲突H-bs冲突K-vsc冲突Q-vsc冲突S-vsc冲突W-cmder冲突合作及交流联系邮箱:[email protected] 交流群:走线物联:163271910扇贝物联:31324057
ampycloud
ampycloudIntroductionampycloud refers to both this Python package and the algorithm at its core, designed to characterize cloud layers (i.e. height and sky coverage fraction) using ceilometer measurements (i.e. automatic cloud basehitsmeasurements), and derive the corresponding METAR-like message.For the full documentation, installation instructions, etc ..., go to:https://meteoswiss.github.io/ampycloudLicense & Copyrightampycloud is released under the terms ofthe 3-Clause BSD license. The copyright (2021-2023) belongs to MeteoSwiss.Contributing to ampycloudPlease see thecontributing guidelinesfor details.
amqcfg
Template based configuration files generator based on jinja2 and yaml mainly focused on Apache ActiveMQ Artemis and related projects
amqencode
ffmpeg scripts for handicapsThis Python 3 package simplifies 2-pass VP9/Opus encoding for AMQ usingffmpeg. It's basically a wrapper with presets forffmpeg-python, with some hacky stuff to get 2-pass encodes working.You can use it to encode every resolution of a video with a single command.You can override a lot of the presets. Passingnorm=Trueautomatically adjusts volume levels for you.I'll write up documentation later.Install it withpipFirst, install Python 3 if you haven't already. Then,pipinstallamqencodeor maybe this on Windowspy -3 -m pip install amqencodeAlso make sure thatffmpegis on your PATH.Usageimport amqencodein your python scripts.Seesample_encode.pyfor an example of a script that encodes a video into mp3 and webms, then muxes those outputs with clean audio.CLIIf you just want to encode a file without writing a standalone script, you can call the package directly from a terminal.*nixpython3-mamqencodeWindowspy -3 -m amqencodeHowever, this is incapable of muxing clean audio into an encode.
amqp
Version:5.2.0Web:https://amqp.readthedocs.io/Download:https://pypi.org/project/amqp/Source:http://github.com/celery/py-amqp/Keywords:amqp, rabbitmqAboutThis is a fork ofamqplibwhich was originally written by Barry Pederson. It is maintained by theCeleryproject, and used bykombuas a pure python alternative whenlibrabbitmqis not available.This library should be API compatible withlibrabbitmq.Differences fromamqplibSupports draining events from multiple channels (Connection.drain_events)Support for timeoutsChannels are restored after channel error, instead of having to close the connection.Support for heartbeatsConnection.heartbeat_tick(rate=2)must called at regular intervals (half of the heartbeat value if rate is 2).Or some other scheme by usingConnection.send_heartbeat.Supports RabbitMQ extensions:Consumer Cancel Notificationsby default a cancel results inChannelErrorbeing raisedbut not if aon_cancelcallback is passed tobasic_consume.Publisher confirmsChannel.confirm_select()enables publisher confirms.Channel.events['basic_ack'].append(my_callback)adds a callback to be called when a message is confirmed. This callback is then called with the signature(delivery_tag, multiple).Exchange-to-exchange bindings:exchange_bind/exchange_unbind.Channel.confirm_select()enables publisher confirms.Channel.events['basic_ack'].append(my_callback)adds a callback to be called when a message is confirmed. This callback is then called with the signature(delivery_tag, multiple).Authentication Failure NotificationsInstead of just closing the connection abruptly on invalid credentials, py-amqp will raise anAccessRefusederror when connected to rabbitmq-server 3.2.0 or greater.Support forbasic_returnUses AMQP 0-9-1 instead of 0-8.Channel.access_requestandticketarguments to methodsremoved.Supports theargumentsargument tobasic_consume.internalargument toexchange_declareremoved.auto_deleteargument toexchange_declaredeprecatedinsistargument toConnectionremoved.Channel.alertshas been removed.Support forChannel.basic_recover_async.Channel.basic_recoverdeprecated.Exceptions renamed to have idiomatic names:AMQPException->AMQPErrorAMQPConnectionException-> ConnectionError``AMQPChannelException-> ChannelError``Connection.known_hostsremoved.Connectionno longer supports redirects.exchangeargument toqueue_bindcan now be empty to use the “default exchange”.AddsConnection.is_alivethat tries to detect whether the connection can still be used.AddsConnection.connection_errorsand.channel_errors, a list of recoverable errors.Exposes the underlying socket asConnection.sock.AddsChannel.no_ack_consumersto keep track of consumer tags that set the no_ack flag.Slightly better at error recoveryQuick overviewSimple producer publishing messages totestqueue using default exchange:importamqpwithamqp.Connection('broker.example.com')asc:ch=c.channel()ch.basic_publish(amqp.Message('Hello World'),routing_key='test')Producer publishing totest_exchangeexchange with publisher confirms enabled and using virtual_hosttest_vhost:importamqpwithamqp.Connection('broker.example.com',exchange='test_exchange',confirm_publish=True,virtual_host='test_vhost')asc:ch=c.channel()ch.basic_publish(amqp.Message('Hello World'),routing_key='test')Consumer with acknowledgments enabled:importamqpwithamqp.Connection('broker.example.com')asc:ch=c.channel()defon_message(message):print('Received message (delivery tag:{}):{}'.format(message.delivery_tag,message.body))ch.basic_ack(message.delivery_tag)ch.basic_consume(queue='test',callback=on_message)whileTrue:c.drain_events()Consumer with acknowledgments disabled:importamqpwithamqp.Connection('broker.example.com')asc:ch=c.channel()defon_message(message):print('Received message (delivery tag:{}):{}'.format(message.delivery_tag,message.body))ch.basic_consume(queue='test',callback=on_message,no_ack=True)whileTrue:c.drain_events()SpeedupsThis library hasexperimentalsupport of speedups. Speedups are implemented using Cython. To enable speedups,CELERY_ENABLE_SPEEDUPSenvironment variable must be set during building/installation. Currently speedups can be installed:using source package (using--no-binaryswitch):CELERY_ENABLE_SPEEDUPS=truepipinstall--no-binary:all:amqpbuilding directly source code:CELERY_ENABLE_SPEEDUPS=truepythonsetup.pyinstallFurtherDifferences between AMQP 0.8 and 0.9.1http://www.rabbitmq.com/amqp-0-8-to-0-9-1.htmlAMQP 0.9.1 Quick Referencehttp://www.rabbitmq.com/amqp-0-9-1-quickref.htmlRabbitMQ Extensionshttp://www.rabbitmq.com/extensions.htmlFor more information about AMQP, visithttp://www.amqp.orgFor other Python client libraries see:http://www.rabbitmq.com/devtools.html#python-devpy-amqp as part of the Tidelift SubscriptionThe maintainers of py-amqp and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/pypi-amqp?utm_source=pypi-amqp&utm_medium=referral&utm_campaign=readme&utm_term=repo)
amqp1.0
Failed to fetch description. HTTP Status Code: 404
amqp-aio
file: README.md
amqp-api-client-py
No description available on PyPI.
amqp_broker
No description available on PyPI.
amqp-bundle
No description available on PyPI.
amqpcli
amqpcliAn interactive shell developed by Python to be used as a client to communicate with an AMQP broker(server).It is inspired byCelery's amqp command line, but amqpcli meant to provide a light-weight tool and others can use it without the necessity to install the whole Celery package.Getting StartedInstall it by pip:pipinstallamqpcliRun the command line:amqpcli-Hlocalhost:5672-uguest-pguest-V/That is it!Just try to enter ahelpcommand to check all available commands and their corresponding usages.Certainly you can also download the source code and run:PYTHONPATH=./bin/amqpcli-Hlocalhost:5672-uguest-pguest-V/
amqpclient
# amqpclient [![Build Status](https://travis-ci.org/okurz/amqpclient.svg?branch=master)](https://travis-ci.org/okurz/amqpclient) Simple AMQP python CLI applications for receiving/sending## CommunicationIf you have questions, contact me (okurz) irc.freenode.net, e.g. in [#opensuse-factory](irc://chat.freenode.net/opensuse-factory).## ContributeThis project lives inhttps://github.com/okurz/amqpclientFeel free to add issues in github or send pull requests.TODOs and ideas are tracked in the fileTODOas well as github issues.### Rules for commitsEvery commit is checked by [Travis CI](https://travis-ci.org/travis) as soon as you create a pull request but youshouldruntoxlocally,It would be nice to keep the test coverage or increase it, e.g. by adding test reference data for new scenarios. TDD is advised :-)For git commit messages use the rules stated on [How to Write a Git Commit Message](http://chris.beams.io/posts/git-commit/) as a referenceIf this is too much hassle for you feel free to provide incomplete pull requests for consideration or create an issue with a code change proposal.## LicenseThis project is licensed under the MIT license, see LICENSE file for details.
amqp-client-cli
amqp-client-cliA simple CLI tool for sending amqp messages to exchanges.What is the purpose ofamqp-client-cli?The purpose of this command line tool is to make sending messages to exchanges as simple as possible. Uses include:Incronscripts that periodically send simple messages to anampqserver for workers to pick up.Unit testing during implementation of anamqpsystem into a workflow.Simple one-off queue messages where anything more than a simple command line tool is a hassle to use.What doesamqp-client-clinotdo?This tool isnotintended for configuration. It assumes your entire infrastructure is already in place. It canonlysend to existing exchanges and vhosts and provide a routing key.It is up to you to configure your infrastructure elsewhere before using this tool (i.e. through your queue workers, through something likerabbitmqadmin, through a web management console. etc).How do I get it?Install via pip:pip install amqp_client_cliHow do I use it?amqp-client-cliis run via theamqpclicommand. Run thehelpsubcommand to see the list of options:$ amqpcli --help usage: amqpcli [-h] {send,config} ... A command line interface for interacting with amqp exchanges positional arguments: {send,config} send Send a message to an exchange. config Configure the amqpcli client. optional arguments: -h, --help show this help message and exitLet's send a message!Sending messages can be done using theamqpcli sendcommand.$amqpcli send --help usage: amqpcli send [-h] [-n] (-m MESSAGE | -f FILE_PATH) [-p] [-s] [-u USER] [-v VHOST] host port exchange routing_key positional arguments: host Address of the amqp server. port Port of the amqp server. exchange Name of the exchange being sent to. routing_key The routing key for the message. optional arguments: -h, --help show this help message and exit -n, --nocolor Do not colorize output. -m MESSAGE, --message MESSAGE String to use as the message body. -f FILE_PATH, --file-path FILE_PATH Path of a file to use as the message body. -p, --persistent Make the message persistent if routed to a durable queue. -s, --ssl Use ssl/tls as the connection protocol. -u USER, --user USER User to connect to the queue as. -v VHOST, --vhost VHOST The vhost to connect to.Let's assume we have aRabbitMQserver listening atlocalhost:5671with an exchange we would like to send a message to namedexchange_aon a vhostmy_vhostwith a routing key ofsimple_message. We are going to send via theguestuser.Let's define our message on the command line!$ amqpcli send localhost 5671 exchange_a simple_message -m "Hello there" -v my_vhost -s User: guest Password: Connecting to queue @ localhost:5671... SUCCESS! Message successfully published to exchange [exchange_a]!Let's define our message as a file!The message body can also be a file. It will be interpreted as binary.Warning:Althoughanybinary content can be sent, it isnotrecommended to insert large payloads into the queue for performance reasons.$echo"I'm a message in a file">my_message.txt$ amqpcli send localhost 5671 exchange_a simple_message -f my_message.txt -v my_vhost -s User: guest Password: Connecting to queue @ localhost:5671... SUCCESS! Message successfully published to exchange [exchange_a]!How can I specify credentials/configurations for a script?You can optionally add user credentials to a config file for use with the tool (~/.amqpclirc). There is no limit to the number of users that can be added.Configuration options can be seen from the command line.$ amqpcli config --help usage: amqpcli config [-h] {add_user,delete_user,list_users} ... positional arguments: {add_user,delete_user,list_users} add_user Add a new queue user to config or edit an existing one. delete_user Delete an existing user from the config. list_users List existing users in config. optional arguments: -h, --help show this help message and exitWithadd_user, you will be prompted for a username, password, and vhost (default is/).A user can also be specified in the environment variables by definingAMQP_USER,AMQP_PASSWORD, andAMQP_VHOST.$ amqpcli config add_user User: guest Password: vhost? [/]: my_vhost $ amqpcli send localhost 5671 exchange_a simple_message -m "Hello there" -u guest Connecting to queue @ localhost:5671... SUCCESS! Message successfully published to exchange [exchange_a]!
amqp-client-python
AMQP Client PythonClient with high level of abstraction for manipulation of messages in the event bus RabbitMQ.Features:Automatic creation and management of queues, exchanges and channels;Connection persistence and auto reconnect;Support fordirect,topicandfanoutexchanges;Publish;Subscribe;Support for a Remote procedure call(RPC).Examples:you can usesync,async eventbusandsync wrapperof async eventbusasync usage# basic configurationfromamqp_client_pythonimport(AsyncEventbusRabbitMQ,Config,Options)fromamqp_client_python.eventimportIntegrationEvent,IntegrationEventHandlerconfig=Config(Options("queue","rpc_queue","rpc_exchange"))eventbus=AsyncEventbusRabbitMQ(config)# publishclassExampleEvent(IntegrationEvent):EVENT_NAME:str="ExampleEvent"def__init__(self,event_type:str,message=[])->None:super().__init__(self.EVENT_NAME,event_type)self.message=messagepublish_event=ExampleEvent(rpc_exchange,["message"])eventbus.publish(publish_event,rpc_routing_key,"direct")# subscribeclassExampleEventHandler(IntegrationEventHandler):asyncdefhandle(self,body)->None:print(body)# handle messagesawaiteventbus.subscribe(subscribe_event,subscribe_event_handle,rpc_routing_key)# rpc_publishresponse=awaiteventbus.rpc_client(rpc_exchange,"user.find",["content_message"])# providerasyncdefhandle2(*body)->bytes:print(f"body:{body}")returnb"content"awaiteventbus.provide_resource("user.find",handle)sync usagefromamqp_client_pythonimport(EventbusRabbitMQ,Config,Options)fromamqp_client_python.eventimportIntegrationEvent,IntegrationEventHandlerfromexamples.defaultimportqueue,rpc_queue,rpc_exchange,rpc_routing_keyclassExampleEvent(IntegrationEvent):EVENT_NAME:str="ExampleEvent"ROUTING_KEY:str=rpc_routing_keydef__init__(self,event_type:str,message=[])->None:super().__init__(self.EVENT_NAME,event_type)self.message=messageself.routing_key=self.ROUTING_KEYclassExampleEventHandler(IntegrationEventHandler):defhandle(self,body)->None:print(body,"subscribe")config=Config(Options(queue,rpc_queue,rpc_exchange))eventbus=EventbusRabbitMQ(config=config)classExampleEvent(IntegrationEvent):EVENT_NAME:str="ExampleEvent"def__init__(self,event_type:str,message=[])->None:super().__init__(self.EVENT_NAME,event_type)self.message=messagefromtimeimportsleepfromrandomimportrandintdefhandle(*body):print(body[0],"rpc_provider")returnf"{body[0]}".encode("utf-8")subscribe_event=ExampleEvent(rpc_exchange)publish_event=ExampleEvent(rpc_exchange,["message"])subscribe_event_handle=ExampleEventHandler()eventbus.subscribe(subscribe_event,subscribe_event_handle,rpc_routing_key)eventbus.provide_resource(rpc_routing_key+"2",handle)count=0running=Truefromconcurrent.futuresimportTimeoutErrorwhilerunning:try:count+=1ifstr(count)!=eventbus.rpc_client(rpc_exchange,rpc_routing_key+"2",[f"{count}"]).decode("utf-8"):running=False#eventbus.publish(publish_event, rpc_routing_key, "direct")#running = FalseexceptTimeoutErroraserr:print("timeout!!!: ",str(err))exceptKeyboardInterrupt:running=FalseexceptBaseExceptionaserr:print("Err:",err)sync wrapper usagefromamqp_client_pythonimportEventbusWrapperRabbitMQ,Config,Optionsfromamqp_client_python.eventimportIntegrationEvent,IntegrationEventHandlerconfig=Config(Options(queue,rpc_queue,rpc_exchange))eventbus=EventbusWrapperRabbitMQ(config=config)classExampleEvent(IntegrationEvent):EVENT_NAME:str="ExampleEvent"def__init__(self,event_type:str,message=[])->None:super().__init__(self.EVENT_NAME,event_type)self.message=messageclassExampleEventHandler(IntegrationEventHandler):asyncdefhandle(self,body)->None:print(body,"subscribe")asyncdefhandle(*body):print(body[0],"rpc_provider")returnf"{body[0]}".encode("utf-8")subscribe_event=ExampleEvent(rpc_exchange)publish_event=ExampleEvent(rpc_exchange,["message"])subscribe_event_handle=ExampleEventHandler()# rpc_providereventbus.provide_resource(rpc_routing_key+"2",handle).result()# subscribeeventbus.subscribe(subscribe_event,subscribe_event_handle,rpc_routing_key).result()count=0running=Truewhilerunning:try:count+=1# rpc_client calleventbus.rpc_client(rpc_exchange,rpc_routing_key+"2",[f"{count}"]).result().decode("utf-8")# publisheventbus.publish(publish_event,rpc_routing_key,"direct").result()#running = FalseexceptKeyboardInterrupt:running=FalseexceptBaseExceptionaserr:print("Err:",err)Know Limitations:basic eventbusWhen usingEventbusRabbitMQShould not use rpc call inside of rpc provider and subscribe handlers, it may block the ioloop #/obs: fixed on other kinds of eventbus, will be removed on nexts releases
amqpclt
amqpclt is a versatile tool to interact with messaging brokers speaking AMQP and/or message queues (see messaging.queue) on disk.It receives messages (see messaging.message) from an incoming module, optionally massaging them (i.e. filtering and/or modifying), and sends them to an outgoing module. Depending on which modules are used, the tool can perform different operations.
amqp-connection
No description available on PyPI.
amqpconsumer
No description available on PyPI.
amqpctl
AMQP Control Command Line Utility
amqp-dispatcher
A daemon to run AMQP consumersRequirementsPython 2.6+InstallationUsing PIP:From Github:pip install git+git://github.com/opschops/[email protected]#egg=amqp-dispatcherFrom PyPI:pip install amqp-dispatcher==0.11.0Runningamqp-dispatcher--configamqp-dispatcher-config.ymlThe environment variableRABBITMQ_URLcan also be used which will cause attempt to connect to the defined data source name. Hosts are separated via commas, and they are connected to in random order.Note that you can specify a heartbeat via theheartbeatquerystring value on theRABBITMQ_URL. By default, it is set toNone, which ensures that the client respects the broker specified heartbeat settings. You may wish to override this for a particular environment.Additionally, you can specifically set a heartbeat override via theRABBITMQ_HEARTBEATenvironment variable. This will take precedence over the heartbeat set inRABBITMQ_URL.To see an example run:makeexampleConsumersConsumers are a class with 2 required methods:consumeandshutdown. amqp-dispatcher will not monkey patch the environment, you will have to do that yourself.consume:consumeis called once for each message being handled. It should take 2 parameters, a proxy for AMQP operations (amqp) and the message (msg).shutdown-shutdownis called before the instance of the consumer is removed. It takes a single argumentexceptionwhich may beNone. If your consumer raises an exception while consuming theshutdownmethod will be called. Onceshutdownis finished a new instance of your consumer will be created to replace the one that raised the exception. If you would like to rate limit instance replacement you can callgevent.sleep(X)to sleep forXseconds after a failure.Example consumer:classConsumer(object):def__init__(self):self.init_msg="I've been initiliazed"defconsume(self,amqp,msg):print'Consuming message',msg.bodygevent.sleep(1)val=random.random()ifval>.8:print'publishing'amqp.publish('test_exchange','test_routing_key',{},'New body!')ifval<.5:raiseValueError()print'Done sleeping'amqp.ack()defshutdown(self,exception=None):print'Shut down'Configurationamqp-dispatcher will read environment variable for connection information and a YAML file for worker configuration.You can validate the yaml file configuration with the following command:amqp-dispatcher--validate--configamqp-dispatcher-config.ymlThis will validate that thestartup_handlerandconsumersexist and can be imported. Note that if there is any logic contained outside of those functions, said logic will be executed.Environment VariablesRABBITMQ_URL: Connection string of the formamqp://USER:PASS@HOST:PORT/VHOSTStartup ConfigurationIf you need to perform custom actions (configure your logging, create initial objects) you can add a startup handler.This is configured in the config yml with thestartup_handleroption.startup_handler:amqpdispatcher.example_startup:startupQueue configurationQueues can be created on the fly by amqp dispatcher, and may bind existing exchanges on the fly as well.There are a few obvious constraints:To create a non-passive queue (typical behavior) the current user must haveconfigure=queuepermissionTo bind to an exchange, the current user must havereadpermission on the binding exchangeQueue configuration is as follows:queue: (required) name of the queuedurable: (optional) queue created in “durable” mode (default = True)auto_delete: (optional) queue created in “auto_delete” mode (default = False), meaning it will be deleted automatically once all consumers disconnect from it (e.g. on restart)exclusive: (optional) queue created in “exclusive” mode (default = False) meaning it will only be accessible by this processx_dead_letter_exchange: (optional) name of dead letter exchangex_dead_letter_routing_key: (optional) dead letter routing keyx_max_length: (optional) maximum length of ready messages. (default = INFINITE)x_expires: (optional) How long a queue can be unused for before it is automatically deleted (milliseconds) (default=INFINITE)x_message_ttl: (optional) How long a message published to a queue can live before it is discarded (milliseconds) (default=INFINITE)Bindingsbindingsshould contain a list ofexchange/routing_keypairs and defines the binding for the queue (there can be multiple)A complete configuration example would look like:queues:-queue:notify_mat_jobdurable:trueauto_delete:falsepassive:trueexclusive:falsex_dead_letter_exchange:nullx_dead_letter_routing_key:nullx_max_length:nullx_expires:nullx_message_ttl:nullbindings:-exchange:notifyrouting_key:transaction.*-exchange:notifyrouting_key:click.*-queue:notify_apsalar_jobbindings:-exchange:notifyrouting_key:transaction.*-exchange:notifyrouting_key:click.*Worker configurationWorkers are autoloaded when AMQP Dispatcher starts. This means your worker must be importable from the environment.A complete configuration example would look like:consumers:-consumer:workers.module:Consumerconsumer_count:1queue:test_queueprefetch_count:2-consumer:workers.module_2:Consumerconsumer_count:2queue:test_queue_2prefetch_count:10prefetch_countis the AMQPprefetch_countwhen consuming. Theconsumer_countis the number of instances of your consumer to handle messages from that queue. Connection pools are highly recommended. MySQL will require theMySQL Connectorinstead ofmysqldbin order for gevent to switch properly.Pools can be created and attached to the consumer class during the__init__. Example with SQLAlchemyclassConsumer(object):session_maker=Nonedef__init__(self):self.session=NoneifConsumer._engineisNone:print'Creating session maker'Consumer._engine=create_engine(...)Consumer.sessionmaker=sessionmaker(bind=Consumer._engine)And then a session created during the consume method.defconsume(self,proxy,msg):session=self.sessionmaker()# Do something with the sessionsession.close()LoggingLogging is performed on the loggeramqp-dispatcher. The RabbitMQ connection provided by Haigha will log onamqp-dispatcher.haigha.You can also configure the logger by using theLOGGING_FILE_CONFIGenvironment variable to specify a file config path. This will be used bylogging.config.fileConfigbefore creating the initial logger.
amqpeek
AMQPeekA flexible RMQ monitor that keeps track of RMQ, notifying you over multiple channels when connections cannot be made, queues have not been declared, and when queue lengths increase beyond specified limits.Support OSS, and me :)If you find this project useful, please feel free tobuy me a coffeeInstall$ pip install amqpeekOnce installed, you can then setup AMQPeek to suit your needs by editing the configuration fileCreate configuration fileTo create a base configuration file:$ amqpeek --gen_configThis will create a file calledamqpeek.yamlin your current directory. Here you can setup your connection details for RMQ, define queues you wish to monitor and define the notifier channels you wish to use. Edit this file to suit your needsRunninglisting all options:$ amqpeek --helpRun AMQPeek with no arguments: This runs the monitoring script once and then exits out (useful when running AMQPeek as a Cron job)$ amqpeekRun AMQPeek with an interval: This monitors RMQ, running the tests every 10 minutes in a continuous loop (useful when running AMQPeek under Supervisor or something similar)$ amqpeek --interval 10You can also specify the location of a configuration file to use instead of the default location of your current directory$ amqpeek --config config.yamlNotification channelsAMQPeek supports multiple notification channels.Currently supported channels:SlackEmail (SMTP)These are controlled via the configuration file, under notifiers. You can mix and match the notifiers you wish to use, and you can have multiples of the same notifier types.