package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
alfred-workflow-tddschn
Note: this is a fork of the amazinghttps://github.com/deanishe/alfred-workflowand has some differences.alfred-workflow-tddschnA helper library in Python for authors of workflows forAlfred 3 and 4.Supports Alfred 3 and Alfred 4 on macOS 10.7+ (Python 3.7+).alfred-workflow-tddschn takes the grunt work out of writing a workflow by giving you the tools to create a fast and featureful Alfred workflow from an API, application or library in minutes.Always supports all current Alfred features.FeaturesAuto-saved settings API for your workflowSuper-simple data caching with expiryFuzzy filtering (with smart diacritic folding)Keychain support for secure storage of passwords, API keys etc.Background tasks to keep your workflow responsiveSimple generation of Alfred JSON feedbackFull support of Alfred's AppleScript/JXA APICatches and logs workflow errors for easier development and support"Magic" arguments to help development/debuggingUnicode supportPre-configured loggingAutomatically check for workflow updates via GitHub releasesPost notifications via Notification CenterAlfred 4+ featuresAdvanced modifiersAlfred 4-only updates (won't break older Alfred installs)Contentsalfred-workflow-tddschnFeaturesAlfred 4+ featuresContentsInstallationWith pipFrom sourceUsageWorkflow script skeletonExamplesKeychain accessDocumentationDash docsetLicensing, thanksContributingAdding a workflow to the listBug reports, pull requestsContributorsWorkflows using alfred-workflow-tddschnInstallationNote: If you're new to Alfred workflows, check outthe tutorialin the docs.With pipYou can install alfred-workflow-tddschn directly into your workflow with:# from your workflow directorypipinstall--target=.alfred-workflow-tddschnYou can install any other library available on theCheese Shopthe same way. See thepip documentationfor more information.It is highly advisable to bundle all your workflow's dependencies with your workflow in this way. That way, it will "just work".From sourceDownload thealfred-workflow-X.X.X.zipfrom theGitHub releases page.Extract the ZIP archive and place theworkflowdirectory in the root folder of your workflow (whereinfo.plistis).Your workflow should look something like this:Your Workflow/ info.plist icon.png workflow/ __init__.py background.py notify.py Notify.tgz update.py version workflow.py yourscript.py etc.Alternatively, you can clone/download the alfred-workflow-tddschnrepositoryand copy theworkflowsubdirectory to your workflow's root directory.UsageA few examples of how to use alfred-workflow-tddschn.Workflow script skeletonSet up your workflow scripts as follows (if you wish to use the built-in error handling orsys.pathmodification):#!/usr/bin/python# encoding: utf-8importsys# Workflow3 supports Alfred 3's new features. The `Workflow` class# is also compatible with Alfred 2.fromworkflowimportWorkflow3defmain(wf):# The Workflow3 instance will be passed to the function# you call from `Workflow3.run`.# Not super useful, as the `wf` object created in# the `if __name__ ...` clause below is global...## Your imports go here if you want to catch import errors, which# is not a bad idea, or if the modules/packages are in a directory# added via `Workflow3(libraries=...)`importsomemoduleimportanothermodule# Get args from Workflow3, already in normalized Unicode.# This is also necessary for "magic" arguments to work.args=wf.args# Do stuff here ...# Add an item to Alfred feedbackwf.add_item(u'Item title',u'Item subtitle')# Send output to Alfred. You can only call this once.# Well, you *can* call it multiple times, but subsequent calls# are ignored (otherwise the JSON sent to Alfred would be invalid).wf.send_feedback()if__name__=='__main__':# Create a global `Workflow3` objectwf=Workflow3()# Call your entry function via `Workflow3.run()` to enable its# helper functions, like exception catching, ARGV normalization,# magic arguments etc.sys.exit(wf.run(main))ExamplesCache data for 30 seconds:defget_web_data():importjsonfromurllibimportrequestwithrequest.urlopen('http://www.example.com')asf:data=f.read().decode('utf-8')returnjson.loads(data)defmain(wf):# Save data from `get_web_data` for 30 seconds under# the key ``example``data=wf.cached_data('example',get_web_data,max_age=30)fordatumindata:wf.add_item(datum['title'],datum['author'])wf.send_feedback()Keychain accessSave password:wf=Workflow()wf.save_password('name of account','password1lolz')Retrieve password:wf=Workflow()wf.get_password('name of account')DocumentationThe full documentation, including API docs and a tutorial, can be found atdeanishe.net.Dash docsetThe documentation is also available as aDash docset.Licensing, thanksThe code and the documentation are released under the MIT andCreative Commons Attribution-NonCommercialLicenses respectively. SeeLicense.txtfor details.The documentation was generated usingSphinxand a modified version of theAlabastertheme bybitprophet.Many of the cooler ideas in alfred-workflow-tddschn were inspired byAlfred2-Ruby-Templateby Zhaocai.The Keychain parser was based onPython-Keyringby Jason R. Coombs.ContributingAdding a workflow to the listIf you want to add a workflow to thelist of workflows using alfred-workflow-tddschn,don't add it to the docs!The list is machine-generated fromPackal.organd thelibrary_workflows.tsvfile. If your workflow is available onPackal, it will be added on the next update. If not, please add it tolibrary_workflows.tsv, and submit a corresponding pull request.The list is not auto-updated, so if you've released a workflow and are keen to see it in this list, pleaseopen an issueasking me to update the list.Bug reports, pull requestsPlease seethe documentation.ContributorsDean JacksonStephen MargheimFabio NiephausOwen MinWorkflows using alfred-workflow-tddschnHere is a listof some of the many workflows based on alfred-workflow-tddschn.
alfREST
A ligthweight python library based on the Alfresco RESTful web services.Sample usage:from alfREST import RESTHelper path = "/Sites/mysite/documentLibrary/test" # login rh = RESTHelper() rh.login(login, password, host, port) # createDocument (sio could be a file object...) from StringIO import StringIO sio = StringIO() sio.write("Well, that's all folks.") sio.seek(0) sio.name = "test.txt" tkns = path.split("/") siteId = tkns[2] containerId = tkns[3] uploadDirectory = "/".join(tkns[4:]) idObject = rh.fileUpload(sio, siteId, containerId, "/%s" % uploadDirectory) sio.close() # get properties props = rh.getProperties("%s/test.txt" % path) assert props["cmis:createdBy"] == login # get content content = rh.getContent("%s/test.txt" % path) assert content == "Well, that's all folks." # add a tag to the document rh.addTag("workspace", "SpacesStore", idObject, "tag_test") assert "tag_test" in rh.getNodeTags("workspace", "SpacesStore", idObject) # list document in folder children = rh.getChildren(path) assert children[0]["cmis:name"] == "test.txt" # create a group and apply a policy to the test folder rh.addRootGroup(u"GROUP_TEST") acl = {} acl[u'GROUP_TEST'] = [([u"{http://www.alfresco.org/model/content/1.0}cmobject.Consumer",], True),] rh.applyACL(path, acl) # create a new user, insert the user in the group rh.addPerson("supermario", "mario", "super", "[email protected]", "imsuper") rh.addGroupOrUserToGroup(u"supermario", u"GROUP_TEST") # some check users = rh.listChildAuthorities(u"GROUP_TEST") assert len(users) == 1 assert users[0]['fullName'] == "supermario" # restore initial status rh.removeAuthorityFromGroup(u"supermario", u"GROUP_TEST") rh.deletePerson("supermario") acl = {} rh.applyACL(path, acl) rh.deleteRootGroup(u"GROUP_TEST") # remove tag from the file object rh.deleteTag("workspace", "SpacesStore", idObject, "tag_test") assert "tag_test" not in rh.getNodeTags("workspace", "SpacesStore", idObject) # delete the file object rh.deleteObject(idObject) # logout rh.logout()Changelogs 0.9.3addTagdeleteTagChangelogs 0.9.2c (bugfix: upload binary files works)createFoldergetNodeTags (get all the tags for a node)Changelogs 0.9.1upload (upload file content and meta-data into repository)delete file (delete the specified object)getChildren (gets the list of child objects contained in the specified folder)getContent (gets the content stream for the specified document)getProperties (gets the properties for the object)Road to 1.0Create / Move a Folder or Document (createDocument, createFolder, createPolicy, moveObject)Write Content (setContent)Delete Content (deleteContent)Get Content (getContent)Get Folder Children (getChildren)Road to 1.1Get Checked Out Documents (getCheckedOutDocs)Checkout Document (checkOut)Cancel Checkout (cancelCheckout)Checkin Private Working Copy (checkin)ContactsFor more info and requests: tiziano [at] axiastudio.it
alfrodull
AlfrodullAlfrodull is a utility that controls lights based on the a computers events.The lights can be turned off when the computer sleepd, and turn on when the computer wakes up. The original use case was to attach an led strip behind the monitor that turn on and off as the display does. But much more can be doen as additional events can easily be added. For example blinking the lights when notifications are received or tracking CPU usage and warning when it passes a threshold.Right now the only supported devices are those fromblinksticks. More can be added if requested and I can get ahold of them.Alfrodull only works on Linux right now as all of the events uses DBUS notifications to react to events. Support for Windows could be added in the future but would require some other notification service.InstallpipinstallalfrodullUsageSimply start alfrodull and pass a configuration file path as input.alfrodullconfig.ymlAlfrodull could for example be started in xinit or i3wm config.ConfigurationAlfrodull is configured with a file, this is where the event, animation and, color are specified. Colors are defined as hex values ex.#ff00ff, the values will be checked when the program is started and throw an exception if they can't be parsed. Passing a null value to the color is parsed as turning off the lights. Below are the currently supported events and animations that can be used.EventDescriptionInitAfter the applicationn is first runShutdownBefore the computer turns offSleepBefore the computer goes to sleepWakeupAfter the computer wakes upEffectDescriptionFadeFades from the current color or if the color is null turn off.Outside InStarts from the outside and changes light one by one to the inside.Inside OutOpposite of Outside In.device: blinkstick events: - type: "Init" animation: type: "Fade" color: "#ffffff" - type: "Sleep" animation: type: "Inside Out" color: "#000000" - type: "Wakeup" animation: type: "Outside In" color: "#ffffff"LicenseThis project is licensed under the MIT License - see theLICENSEfile for details.
alfworld
No description available on PyPI.
alg
ALGDOCUMENTATIONAlgorithm Learning Group
alg3dpy
Travis-CI status:Coverage status:3D Algebra in Python (alg3dpy)Very useful basic algebra operations with points, vectors, planes:Calculate distancesCalculate anglesIntersectionsProjectionsLicensingDistrubuted under the 3-Clause BSD license (see the LICENSE file for details).Contact:[email protected].
alga
AlgaA command line utility for controlling a LG webOS TV over the network.It is still in it's early stages of development but the implemented functionality should work.Work yet to do:Add testsAdd way of adding TV without having to set environment variablesAdd CI for running Ruff and MypyAdd CI for releasing versions to PyPI when tags are addedAdd support for Python versions besides 3.12
algae
algaeAlgebraic Data Types for PythonThis repository contains an implementation from scratch of simple algebraic data types in Python.The following types are implemented and tested:EitherOptionTryThis library is inspired by Scala's implementation of these structures.Feel free to open an issue orsend me an emailin case you'd like to contribute or if you see something that can be improved.InstallationThis project is published onPyPiasalgaeso you can easily install it withpipas:pipinstallalgaeor withpoetryas:poetryaddalgaeSetupPoetryThis project usespoetryto manage its dependencies. Please refer topoetry's official docfor more info.Usage ExamplesEitherEitherrepresents a value that can assume one of two types.Concrete instances are of typeLeftorRight.As an example, let's consider the case of making HTTP calls which might return a status code representing an error as the url is user-defined. If a call is successful, we want to return the JSON from the response, but if it's not we'll map it to an internal error message.The examples use thisexample server.importrequestsfromalgae.eitherimportLeft,Right,EitherfromtypingimportDict,Anydefmap_response_to_msg(response:requests.models.Response):returnf"The{response.request.method}request to{response.url}couldn't be completed "\f"and returned a{response.status_code}status_code"defcall_and_check(url:str)->Either[str,Dict[Any,Any]]:response=requests.get(url)returnRight(response.json())ifresponse.okelseLeft(map_response_to_msg(response))Users of this method will then be able to further chain operations which can result in 2 different results easily, keeping track of the error message identifying the step that returned something unexpected in the chain.base_url="https://jsonplaceholder.typicode.com"users_json=call_and_check(f"{base_url}/users")posts=users_json.flat_map(lambdajson:call_and_check(f"{base_url}/posts?userId={json[0]['id']}"))Lastly, we'll log the content of theEitherat the appropriate level in each case; the contained string in theLeftcase atwarn, or themsgfield of the JSON dictionary in theRightcase atinfo.fromloggingimportgetLoggerlogger=getLogger()posts.fold(logger.warning,lambdax:logger.info(x[0]["title"]))The above example enters theRightbranch of theEither, change thebase_urlto$base_url/pizzato get aLeftat the first stage.Please note that this is different from the case where anExceptionis raised, which better fits theTrystructure described below.OptionOptionrepresents an optional value, its concrete instances are of typeNothingorSome.As an example, let's consider the case of checking for a variable in a dictionary. Normally, a default value ofNoneis returned if the request key is not present in the dictionary, however this requires the user of method returning such a value to check explicitly the content of the return variable.Further, multiple calls of this type cannot be chained together, and the value needs to be checked every time. UsingOptionwe can instead reason using the type directly, and demanding to it the checking steps.fromalgae.optionimportOptiond={"food":"Pizza"}result=Option.apply(d.get("another_key"))awesomize=lambdax:x+"is awesome"msg=result.map(awesomize)This way we didn't need to check whether the key was present in the dictionary or not. Finally, we can get a default value to go from anOptionto astr.msg.fold("Pizza is incredible anyways!",lamdbax:x+", but fries are good too!")The finalmsgwill bePizza is incredible anyways!.If instead we had looked for thefoodkey,msgwould have beenPizza is awesome, but fries are good too!TryTryrepresents a computation that can either fail (raising an Exception) or return the resulting value.Concrete instances are of typeFailureorSuccess.As an example, let's see the case of a function that can raise an Exception:importmathdefunsafe_computation(value:int):returnmath.log(value)# this throws an Exception if value is <= 0Upon calling this function withvalue<= 0 we'll see:unsafe_computation(0)Traceback(mostrecentcalllast):File"<stdin>",line1,in<module> ValueError:mathdomainerrorTo make this computation safe, even forvalue<= 0, we'll wrap its execution with Try:fromalgae.try_importTrysafe_result=Try.apply(unsafe_computation,0)safe_resultwill be of typeFailure, containing the Exception. In case it was called on proper input:safe_result=Try.apply(unsafe_computation,1)safe_resultwill be of type Success and it will contain the proper result.Please notice that you need to pass the function and any function arguments, named and not, as arguments toTry.apply()rather than passingf(args).Alternatively, you can use this syntax:safe_result=Try.apply(lambda:unsafe_computation(0))UsingTry, an appropriate return type can be used for methods that might fail and raise anExeception, leaving the user in charge of easily dealing with the subsequent behavior, for example:Try.apply(unsafe_computation,1).map(lambdax:x+1)Special thanks toDavid Cuthbertfor letting me have the "algae" name on PyPI.
algaestat
algaestat is a package to extract, transform and aggregate Algae cultivation data. A series of proprietary and open-source instruments collected this data: Burge Environmental MiProbe (Algae Probe), YSI (Algae Probe), HoboLink (Weather Data) pH Meters. Free from notebook entries are also accessible. Cultivation data. - Algae Pool Status including, levels, temperature. - This package contains classes to: - Query the WS Dynomodb (where the data is stored). - Extract data from AWS Dynomodb, - Transform and aggregate the data to relational tables or JSON formats. - Export results as files (i.e. csv)
algcore
algorithm tool and sdk
algcxdb
奥利给硬件科技工作室程序打包库!!!使用函数cxdb()即可!!!
algdq
奥利给硬件科技工作室读取库
alge
No description available on PyPI.
algebra
AlgebraAlgebraic structuresNote:Algebra requires Python 3.6 or higher.Requirements and InstallationpipinstallalgebraSee alsothe instructions here.AlgebraThis package provides an algebra where the elements can be manipulated in a natural way, with basic algebraic simplifications happening automatically. It also support equality checking, which is conservative: ifx == y, thenxis equal toy; but ifx != y, then eitherxis different fromy, or it could not be proven thatxis equal toy.As an example, let's create numbered elements.fromalgebraimportElementclassNumbered(Element):total=0def__init__(self):self.num=Numbered.totalNumbered.total+=1defrender(self,formatter):returnf'x{self.num}'Then instances ofNumberedcan be manipulated as follows.>>>x0=Numbered()>>>x1=Numbered()>>>x0==x0True>>>x0==x1False>>>x0+x1x0+x1>>>x0+x02*x0>>>x0+x1==x1+x0True>>>x0-x00>>>2+x02*1+x0>>>(2+x0)*x1(2*1+x0)*x1>>>(2+x0)*x1*00Create Your Own AlgebraComing soon.Function AlgebraComing soon.Create Your Own Function AlgebraComing soon.
algebra-collections
Django Algebraic CalculatorAplikasi web penghitungan aljabar untuk kelompok 7 Pemrograman Berbasis Penggunaan Ulang, Universitas Brawijaya.Anggota205150400111052 - AURELIUS ALEXANDER VIRIYA205150407111019 - BAGAS RADITYA NUR LISTYAWAN205150407111025 - KHALIFFMAN RAHMAT HILAL205150407111016 - RIZAL AKBAR SYAH FAUZAN PUTRAInstallation & UsageWithout UIInstall on your project’s virtual environmentUse this following syntax to install the package:'pip install algebra-collections'Add ‘algebra_calculator’ to your Django project’s “setting.py” INSTALLED_APPS:INSTALLED_APPS = [ ... 'algebra_calculator', ]Import ‘algebra_calculator’ to your app’s ‘views.py’ in order to use the pre-made Linear Equations or develop other type of Algebraic EquationsExample using pre-made LinearEquations(linear.views file):from algebra_calculator import *def showXandYvalue():listOfChars = [‘X’, ‘Y’] listOfExpressions = [“2X + 5Y = 10”, “3X + 2Y = 30”]result = LinearEquations.solve(2, listOfChars, listOfExpressions)for i in range(len(result)):printable(f”{listOfChars[i]}’s value is = {result}”)return HttpResponse(printable)Example developing other type of Algebraic Equations (commutative.views file):class CommutativeAlgebra(AlgebraFactory):def solve(…): … …def finishCommutativeAlgebra():result = CommutativeAlgebra.solve(…)return HttpResponse(result)With UIInstall on your project’s virtual environmentUse this following syntax to install the package:'pip install algebra-collections'Add ‘algebra_calculator’ and ‘ui’ to your Django project’s “setting.py” INSTALLED_APPS:INSTALLED_APPS = [ ... 'algebra_calculator', 'ui', ]Include the poll URLconf in your project’s urls.py:urlpattern = [ ... path('[your_pathing_here/]', include('ui.urls')), ]Access the Linear Equation’s UI by running server and using the following url:127.0.0.1:8000/[your_pathing_here]/TwoExpression_LinearEquations
algebra-easy
No description available on PyPI.
algebraIA
LibreriaAlgebra
algebraIA-Fernando-Leon-Franco
LibreriaAlgebra
algebraIberoIA
algebraLinealLibrería que te permite utilizar funciones básicas de álgebra linealfunciones y cómo utilizarlaspedir_matriz(filas, columnas) la función pedir_matriz te pedirá un valor por cada fila y columna, y agregará el valor a una matrizdeterminante(matriz, filas, columnas) la función determinante retornará el valor del determinante de la matriz si ésta es cuadrada; si no, retornará la cadena de texto: "Solo se pueden obtener determinantes de matrices cuadradas"producto_escalar(escalar, matriz) la función producto_escalar multiplicará cada valor en la matriz por un escalar, retornando como resultado la matriz resultantesuma_matrices(matriz1, matriz2) la función suma_matrices retornará una sola matriz en la que los valores de las dos matrices en los parámetros se sumaronresta_matrices(matriz1, matriz2) la función resta_matrices retornará una sola matriz en la que los valores de las dos matrices en los parámetros se restaron
algebraical
Subclass of thebuilt-in function typefor representing algebraic operators (that are typically associated with algebraic structures and algebraic circuits) as immutable, hashable, sortable, and callable objects.This library is compatible with thecircuitlibrary and is intended to complement thelogicallibrary for logical operations.Installation and UsageThis library is available as apackage on PyPI:python -m pip install algebraicalThe library can be imported in the usual ways:import algebraical from algebraical import *ExamplesEach instance of thealgebraicalclass (derived from the type of the built-in functions found in the built-inoperatorlibrary) represents a function that operates on values of typical algebraic structures (such asnumerictypes and any classes that define thespecial methodsassociated with these built-in operators):>>> from algebraical import algebraical >>> algebraical.add_(1, 2) 3Methods for retrieving the name and arity of analgebraicalinstance are provided:>>> algebraical.add_.name() 'add' >>> algebraical.add_.arity() 2Instances ofalgebraicalcan be compared according to their precedence:>>> algebraical.pow_ > algebraical.mul_ True >>> algebraical.pow_ <= algebraical.add_ False >>> sorted([pow_, mul_, add_] # From lowest to highest precedence. [add_, mul_, pow_]Instances are also hashable and can be used as members ofsetsand as keys withindictionaries:>>> from algebraical import * >>> {add_, mul_} {mul_, add_} >>> {add_: 0, mul_: 1} {add_: 0, mul_: 1}DevelopmentAll installation and development dependencies are fully specified inpyproject.toml. Theproject.optional-dependenciesobject is used tospecify optional requirementsfor various development tasks. This makes it possible to specify additional options (such asdocs,lint, and so on) when performing installation usingpip:python -m pip install .[docs,lint]DocumentationThe documentation can be generated automatically from the source files usingSphinx:python -m pip install .[docs] cd docs sphinx-apidoc -f -E --templatedir=_templates -o _source .. && make htmlTesting and ConventionsAll unit tests are executed and their coverage is measured when usingpytest(see thepyproject.tomlfile for configuration details):python -m pip install .[test] python -m pytestAlternatively, all unit tests are included in the module itself and can be executed usingdoctest:python src/algebraical/algebraical.py -vStyle conventions are enforced usingPylint:python -m pip install .[lint] python -m pylint src/algebraicalContributionsIn order to contribute to the source code, open an issue or submit a pull request on theGitHub pagefor this library.VersioningThe version number format for this library and the changes to the library associated with version number increments conform withSemantic Versioning 2.0.0.PublishingThis library can be published as apackage on PyPIby a package maintainer. First, install the dependencies required for packaging and publishing:python -m pip install .[publish]Ensure that the correct version number appears inpyproject.toml, and that any links in this README document to the Read the Docs documentation of this package (or its dependencies) have appropriate version numbers. Also ensure that the Read the Docs project for this library has anautomation rulethat activates and sets as the default all tagged versions. Create and push a tag for this version (replacing?.?.?with the version number):git tag ?.?.? git push origin ?.?.?Remove any old build/distribution files. Then, package the source into a distribution archive:rm -rf build dist src/*.egg-info python -m build --sdist --wheel .Finally, upload the package distribution archive toPyPI:python -m twine upload dist/*
algebraic-connectivity-directed
algebraic-connectivity-directedPython functions to compute various notions of algebraic connectivity of directed graphsRequirementsRequirespython>= 3.5 and packagesnumpy,scipy,networkxandcvxpy.Installationpip install algebraic-connectivity-directedUsageAfter installation, runfrom algebraic_connectivity_directed import *There are 4 main functions:Functionalgebraic_connectivity_directed: algebraic_connectivity_directed(G) returnsa, b, Mwhereais the algebraic connectivity of the digraph G. The graph G is anetworkxDiGraph object. The definitions ofa, b, M = Q'*(L+L')*Q/2can be found in Ref. [2].Functionalgebraic_connectivity_directed_variants: algebraic_connectivity_directed_variants(G,k) returns variations of algebraic connectivity of the digraph G. The graphGis anetworkxDiGraph object. Settingk = 1, 2, 3, 4returns a1, a2, a3, a4as defined in Ref. [6].Functioncompute_mu_directed: compute_mu_directed(G) returnsmu(G)defined as the supremum of numbers μ such that U(L-μ*I)+(L'-μ*I)U is positive semidefinite for some symmetric zero row sums real matrixUwith nonpositive off-diagonal elements whereLis the Laplacian matrix of graphG(see Ref. [1]). Computed number may be smaller than the defined value due to the difficulty of the SDP problem.Functioncompute_mu2_directed: compute_mu2_directed(G) returnsmu2(G)defined as the eigenvalue with the smallest real part among eigenvalues of the Laplacian matrixLthat do not belong to the all 1's vectore(see Ref. [5]).compute_mu_directedaccepts multiple arguments. If the input are multiple graphs G1, G2, G3, ... with Lithe Laplacian matrix of Gi, and all Gihave the same number of nodes, then compute_mu_directed(G1, G2, G3, ...) returns the supremum of μ such that there exist some symmetric zero row sums real matrix U with nonpositive off-diagonal elements where for all i, U(Li-μ*I)+(Li'-μ*I)U is positive semidefinite. This is useful in analyzing synchronization of networked systems where systems are coupled via multiple networks. See Ref. [7]. The graph G is anetworkxDiGraph object.a1is the same as the value returned by algebraic_connectivity_directed(G)[0] (see Ref. [2]).a2is the same as ã as described in Ref. [3].a3is described in the proof of Theorem 21 in Ref. [3].a4is equal to η as described in Ref. [4].PropertiesIf the reversal of the graph does not contain a spanning directed tree, then a2≤ 0.If G is strongly connected then a3≥ a2> 0.a4> 0 if and only if the reversal of the graph contains a spanning directed tree.a1≤ μ ≤ μ2.μ = μ2= 1 if the reversal of the graph is a directed tree (arborescence).If the Laplacian matrix L is a normal matrix, then a1= μ = μ2.ExamplesCycle graphfrom algebraic_connectivity_directed import * import networkx as nx import numpy as np G = nx.cycle_graph(10,create_using=nx.DiGraph) print(algebraic_connectivity_directed(G)[0:2]) >> (0.19098300562505233, 2.0) print(algebraic_connectivity_directed_variants(G,2)) >> 0.1909830056250514Directed graphs of 5 nodesA1 = np.array([[0,0,1,0,0],[0,0,0,1,1],[1,0,0,1,1],[1,1,0,0,1],[0,0,0,1,0]]) G1 = nx.from_numpy_matrix(A1,create_using=nx.DiGraph) print(compute_mu_directed(G1)) >>> 0.8521009635833089 print(algebraic_connectivity_directed_variants(G1, 4)) >>> 0.6606088707716056 A2 = np.array([[0,1,0,0,1],[0,0,0,1,0],[0,0,0,1,1],[1,0,0,0,0],[1,0,1,1,0]]) G2 = nx.from_numpy_matrix(A2,create_using=nx.DiGraph) A3 = np.array([[0,1,0,0,0],[1,0,1,0,0],[0,1,0,0,0],[0,0,1,0,0],[1,1,1,0,0]]) G3 = nx.from_numpy_matrix(A3,create_using=nx.DiGraph) print(compute_mu_directed(G1,G2,G3)) >>> 0.8381214637786955ReferencesC. W. Wu, "Synchronization in coupled arrays of chaotic oscillators with nonreciprocal coupling", IEEE Transactions on Circuits and Systems-I, vol. 50, no. 2, pp. 294-297, 2003.C. W. Wu, "Algebraic connecivity of directed graphs", Linear and Multilinear Algebra, vol. 53, no. 3, pp. 203-223, 2005.C. W. Wu, "On Rayleigh-Ritz ratios of a generalized Laplacian matrix of directed graphs", Linear Algebra and its applications, vol. 402, pp. 207-227, 2005.C. W. Wu, "Synchronization in networks of nonlinear dynamical systems coupled via a directed graph", Nonlinearity, vol. 18, pp. 1057-1064, 2005.C. W. Wu, "On a matrix inequality and its application to the synchronization in coupled chaotic systems," Complex Computing-Networks: Brain-like and Wave-oriented Electrodynamic Algorithms, Springer Proceedings in Physics, vol. 104, pp. 279-288, 2006.C. W. Wu, "Synchronization in Complex Networks of Nonlinear Dynamical Systems", World Scientific, 2007.C. W. Wu, "Synchronization in dynamical systems coupled via multiple directed networks," IEEE Transactions on Circuits and Systems-II: Express Briefs, vol. 68, no. 5, pp. 1660-1664, 2021.
algebraic-data-type
Algebraic Data TypeTo install the packagepip install algebraic-data-typeADT[To be written]Pattern Matchingfrom adt import Multimethod with Multimethod() as fib: fib[1] = 1 fib[2] = 1 fib[int] = lambda x: fib(x-1) + fib(x-2)TestTo run the tests, clone the repo and use pytest>>> git clone https://github.com/catethos/adt.git >>> cd adt/ >>> pytest
algebraic-data-types
adtadtis a library providingalgebraic data typesin Python, with a clean, intuitive syntax, and support fortypingthrough amypy plugin.NOTE:This project is experimental, and not actively maintained by the author. Contributions and forking are more than welcome.Table of contents:What are algebraic data types?Pattern matchingCompared to EnumsCompared to inheritanceExamples in other programming languagesInstallationmypy pluginDefining an ADTGenerated functionalityCustom methodsWhat are algebraic data types?Analgebraic data type(also known as an ADT) is a way to represent multiple variants of a single type, each of which can have some data associated with it. The idea is very similar totagged unions and sum types, which in Python are represented asEnums.ADTs are useful for a variety of data structures, including binary trees:@adtclassTree:EMPTY:CaseLEAF:Case[int]NODE:Case["Tree","Tree"]Abstract syntax trees (like you might implement as part of a parser, compiler, or interpreter):@adtclassExpression:LITERAL:Case[float]UNARY_MINUS:Case["Expression"]ADD:Case["Expression","Expression"]MINUS:Case["Expression","Expression"]MULTIPLY:Case["Expression","Expression"]DIVIDE:Case["Expression","Expression"]Or more generic versions of a variant type, like anEithertype that represents a type A or a type B, but not both:L=TypeVar('L')R=TypeVar('R')@adtclassEither(Generic[L,R]):LEFT:Case[L]RIGHT:Case[R]Pattern matchingNow, defining a type isn't that interesting by itself. A lot of the expressivity of ADTs arises when youpattern matchover them (sometimes known as "destructuring").For example, we could use theEitherADT from above to implement a sort of error handling:# Defined in some other module, perhapsdefsome_operation()->Either[Exception,int]:returnEither.RIGHT(22)# Example of building a constructor# Run some_operation, and handle the success or failuredefault_value=5unpacked_result=some_operation().match(# In this case, we're going to ignore any exception we receiveleft=lambdaex:default_value,right=lambdaresult:result)Aside: this is very similar to how error handling is implemented in languages likeHaskell, because it avoids the unpredictable control flow of raising and catching exceptions, and ensures that callers need to make an explicit decision about what to do in an error case.One can do the same thing with theExpressiontype above (just more cases to match):defhandle_expression(e:Expression):returne.match(literal=lambdan:...,unary_minus=lambdaexpr:...,add=lambdalhs,rhs:...,minus=lambdalhs,rhs:...,multiply=lambdalhs,rhs:...,divide=lambdalhs,rhs:...)Compared to EnumsADTs are somewhat similar toEnumsfrom the Python standard library (in fact, the uppercase naming convention is purposely similar).For example, anEnumversion ofExpressionmight look like:fromenumimportEnum,autoclassEnumExpression(Enum):LITERAL=auto()UNARY_MINUS=auto()ADD=auto()MINUS=auto()MULTIPLY=auto()DIVIDE=auto()However, this doesn't allow data to be associated with each of these enum values. A particular value ofExpressionwill tell you about akindof expression that exists, but the operands to the expressions still have to be stored elsewhere.From this perspective, ADTs are likeEnums that can optionally have data associated with each case.Compared to inheritanceAlgebraic data types are a relatively recent introduction to object-oriented programming languages, for the simple reason that inheritance can replicate the same behavior.Continuing our examples with theExpressionADT, here's how one might represent it with inheritance in Python:fromabcimportABCclassABCExpression(ABC):passclassLiteralExpression(ABCExpression):def__init__(self,value:float):passclassUnaryMinusExpression(ABCExpression):def__init__(self,inner:ABCExpression):passclassAddExpression(ABCExpression):def__init__(self,lhs:ABCExpression,rhs:ABCExpression):passclassMinusExpression(ABCExpression):def__init__(self,lhs:ABCExpression,rhs:ABCExpression):passclassMultiplyExpression(ABCExpression):def__init__(self,lhs:ABCExpression,rhs:ABCExpression):passclassDivideExpression(ABCExpression):def__init__(self,lhs:ABCExpression,rhs:ABCExpression):passThis is noticeably more verbose, and the code to consume these types gets much more complex as well:e:ABCExpression=UnaryMinusExpression(LiteralExpression(3))# Example of creating an expressionifisinstance(e,LiteralExpression):result=...# do something with e.valueelifisinstance(e,UnaryMinusExpression):result=...# do something with e.innerelifisinstance(e,AddExpression):result=...# do something with e.lhs and e.rhselifisinstance(e,MinusExpression):result=...# do something with e.lhs and e.rhselifisinstance(e,MultiplyExpression):result=...# do something with e.lhs and e.rhselifisinstance(e,DivideExpression):result=...# do something with e.lhs and e.rhselse:raiseValueError(f'Unexpected type of expression:{e}')ADTs offer a simple way to define a type which isone of a set of possible cases, and allowing data to be associated with each case and packed/unpacked along with it.Examples in other programming languagesAlgebraic data types are very common in functional programming languages, likeHaskellorScala, but they're gaining increasing acceptance in "mainstream" programming languages as well.Here are a few examples.RustRustenums are actually full-fledged ADTs. Here's how anEitherADT could be defined:enumEither<L,R>{Left(L),Right(R),}SwiftSwift enumerationsare very similar to Rust's, and behave like algebraic data types through their support of "associated values."enumEither<L,R>{caseLeft(L)caseRight(R)}TypeScriptTypeScriptoffers ADTs through a language feature known as"discriminated unions".See this example from their documentation:interfaceSquare{kind:"square";size:number;}interfaceRectangle{kind:"rectangle";width:number;height:number;}interfaceCircle{kind:"circle";radius:number;}typeShape=Square|Rectangle|Circle;InstallationTo addadtas a library in your Python project, simply runpip(orpip3, as it may be named on your system):pip install algebraic-data-typesThis will installthe latest version from PyPI.mypy pluginThe library also comes with a plugin formypythat enables typechecking [email protected] you are already using mypy, the plugin is required to avoid nonsensical type errors.To enable theadttypechecking plugin, add the following to amypy.inifile in your project's working directory:[mypy] plugins = adt.mypy_pluginDefining an ADTTo begin defining your own data type, import the@adtdecorator andCase[…]annotation:fromadtimportadt,CaseThen, define a new Python class, upon which you apply the@adtdecorator:@adtclassMyADT1:passFor each case (variant) that your ADT will have, declare a field with theCaseannotation. It's conventional to declare your fields with ALL_UPPERCASE names, but the only true restriction is that theycannotbe lowercase.@adtclassMyADT2:FIRST_CASE:CaseSECOND_CASE:CaseIf you want to associate some data with a particular case, list the type of that data in brackets afterCase(similar to theGeneric[…]andTuple[…]annotations fromtyping). For example, to add a case with an associated string:@adtclassMyADT3:FIRST_CASE:CaseSECOND_CASE:CaseSTRING_CASE:Case[str]You can build cases with arbitrarily many associated pieces of data, as long as all the types are listed:@adtclassMyADT4:FIRST_CASE:CaseSECOND_CASE:CaseSTRING_CASE:Case[str]LOTS_OF_DATA_CASE:Case[int,str,str,Dict[int,int]]ADTs can also be recursive—i.e., an ADT can itself be stored alongside a specific case—though the class name has to be provided in double quotes (a restriction which also applies totyping).A typical example of a recursive ADT is a linked list. Here, the list is also made generic over a typeT:T=TypeVar('T')@adtclassLinkedList(Generic[T]):NIL:CaseCONS:Case[T,"LinkedList[T]"]See the library'stestsfor more examples of complete ADT definitions.Generated functionalityGiven an ADT defined as follows:@adtclassMyADT5:EMPTY:CaseINTEGER:Case[int]STRING_PAIR:Case[str,str]The@adtdecorator will automatically generate accessor methods of the following form:defempty(self)->None:returnNonedefinteger(self)->int:...# unpacks int value and returns itdefstring_pair(self)->Tuple[str,str]:...# unpacks strings and returns them in a tupleThese accessors can be used to obtain the data associated with the ADT case, butaccessors will throw an exception if the ADT was not constructed with the matching case. This is a shorthand when you already know the case of an ADT object.@adtwill also automatically generate a pattern-matching method, which can be used when youdon'tknow which case you have ahead of time:Result=TypeVar('Result')defmatch(self,empty:Callable[[],Result],integer:Callable[[int],Result],string_pair:Callable[[str,str],Result])->Result:if...selfwasconstructedasEMPTY...:returnempty()elif...selfwasconstructedasINTEGER...:returninteger(self.integer())elif...selfwasconstructedasSTRING_PAIR...:returnstring_pair(*self.string_pair())# if pattern match is incomplete, an exception is raisedSee the library'stestsfor examples of using these generated methods.@adtwill also generate__repr__,__str__, and__eq__methods (only if they are notdefined already), to make ADTs convenient to use by default.Custom methodsArbitrary methods can be defined on ADTs by simply including them in the class definition as normal.For example, to build "safe" versions of the default accessors onExampleADT, which returnNoneinstead of throwing an exception when the case is incorrect:@adtclassExampleADT:EMPTY:CaseINTEGER:Case[int]STRING_PAIR:Case[str,str]@propertydefsafe_integer(self)->Optional[int]:returnself.match(empty=lambda:None,integer=lambdan:n,string_pair=lambda_a,_b:None)@propertydefsafe_string_pair(self)->Optional[Tuple[str,str]]:returnself.match(empty=lambda:None,integer=lambdan:None,string_pair=lambdaa,b:(a,b))However, additional fieldsmust notbe added to the class, as the decorator will attempt to interpret them as ADTCases (which will fail).
algebraics
Algebraic NumbersLibraryUse when you need exact arithmetic, speed is not critical, and rational numbers aren't good enough.Example:usealgebraics::prelude::*;usealgebraics::RealAlgebraicNumberasNumber;lettwo=Number::from(2);// 2 is a rational numberassert!(two.is_rational());// 1/2 is the reciprocal of 2letone_half=two.recip();// 1/2 is also a rational numberassert!(one_half.is_rational());// 2^(1/4)letroot=(&two).pow((1,4));// we can use all the standard comparison operatorsassert!(root!=Number::from(3));assert!(root<Number::from(2));assert!(root>Number::from(1));// we can use all of add, subtract, multiply, divide, and remainderletsum=&root+&root;letdifference=&root-Number::from(47);letproduct=&root*&one_half;letquotient=&one_half/&root;letremainder=&root%&one_half;// root is not a rational numberassert!(!root.is_rational());// the calculations are always exactassert_eq!((&root).pow(4),two);// lets compute 30 decimal places of rootletscale=Number::from(10).pow(30);letscaled=&root*scale;letdigits=scaled.into_integer_trunc();assert_eq!(digits.to_string(),1_18920_71150_02721_06671_74999_70560u128.to_string());// get the minimal polynomialletother_number=root+two.pow((1,2));assert_eq!(&other_number.minimal_polynomial().to_string(),"2 + -8*X + -4*X^2 + 0*X^3 + 1*X^4");// works with really big numbersletreally_big=Number::from(1_00000_00000i64).pow(20)+Number::from(23);assert_eq!(&really_big.to_integer_floor().to_string(),"100000000000000000000000000000000000000000000\000000000000000000000000000000000000000000000\000000000000000000000000000000000000000000000\000000000000000000000000000000000000000000000\000000000000000000023")Python supportUsing algebraics from Python:python3-mpipinstallalgebraicsfromalgebraicsimportRealAlgebraicNumbersqrt_2=2**(RealAlgebraicNumber(1)/2)assertsqrt_2*sqrt_2==2Using algebraics in your own Rust project:[dependencies.algebraics]version="0.3"Developing algebraics:cargoinstallmaturin maturindevelop--cargo-extra-args="--features python-extension"
algebraixlib
orphan:algebraixlibWhat Is It?algebraixlibis a library that provides constructs and facilities to harness the fundamentals of data algebra. Data algebra consists of mathematical constructs that can represent all data, no matter how it is structured, and the operations on that data. With this, all the advantages of a mathematically rigorous modeling can be unleashed. See alsoA Beginner’s Introduction to Data Algebra.Getting StartedMake sure you have the required versions of Python and Jupyter Notebook installed (seeRequirementsbelow).Install thealgebraixliblibrary (seeHow to Installbelow).Download theexamplesfrom ourGitHubrepository.Try the Hello_World.ipynb example first.(Alternatively, you can also look at a static version of the notebooks innbviewer; see the README file in ourexamplesdirectory for direct links. For this you don’t need to install or download anything. You can also start with the simpler hello_world.py. However, you’ll lose out on some math and need to read up on it in our documentation atRead the Docs. )Documentation and SupportFind documentation atRead the Docs.Find thepipinstaller onPyPI.Find the source code, the bugtracker and contribute onGitHub.Find tutorials and example code in theexamplesdirectory on GitHub.Post questions about algebraixlib onStack Overflowusing the tag[algebraixlib].Post questions about the mathematics of data algebra onmath.stackexchangeusing the tag[data-algebra].Contact us byemail.See also ourGitHub project page. In addition, there is abookabout data algebra.Detailed InstructionsRequirementsPython: Tested with 3.6.1. Likely to run with Python 3.6.x and later. It may run with earlier Python 3 versions, but you may run into issues. Does not run with any version of Python before Python 3.For installing and using multiple versions of Python on the same machine, seeOfficial multiple python versions on the same machine? (Stack Overflow),How to install both Python 2.x and Python 3.x in Windows 7 (Stack Overflow)andA Python Launcher For Windows (Python Insider).Jupyter Notebook: Tested with Jupyter 5.2 (used in the Jupyter notebook tutorials and examples).SeeJupyter Installationfor instructions how to install the Jupyter notebook (pip install jupyter).If you don’t want Jupyter in your system environment, you can install it into a virtual environment (seeCreation of virtual environments).How to InstallIf you already have Python installed and are familiar with installing packages, you can installalgebraixlibwithpip:> pip install algebraixlibAdditional user permissions may be necessary to complete the installation. In such a situation, other options include installing the package for a single user (in the user’s home directory):> pip install algebraixlib --user <username>or in a virtual environment (seeCreation of virtual environments).You can also manually downloadalgebraixlibfromGitHuborPyPI. To install from a download, unpack it and run the following command from the top-level source directory (the directory that contains the file setup.py):> python setup.py install(The same considerations about permissions apply.)Unit TestsThe unit tests require the following libraries to be installed:nosecoverageTo execute the unit tests, download the fileruntests.pyand the directorytestinto any location on your system, then runruntests.py:> mkdir algebraixlib-test > cd algebraixlib-test > svn export https://github.com/AlgebraixData/algebraixlib/trunk/runtests.py > svn export https://github.com/AlgebraixData/algebraixlib/trunk/test > python runtests.pyDocumentation BuildThe documentation build requires the following libraries be installed:Sphinx(1.3.2 or later)To run a documentation build, you need a local working copy of our completeGitHubrepository. Then runbuild.pyin the directorydocs:> mkdir algebraixlib > cd algebraixlib > svn export https://github.com/AlgebraixData/algebraixlib/trunk > cd trunk/docs > python build.pyLegaleseCopyrightCopyright(c) 2017 Algebraix Data Corporation.Licensealgebraixlibis free software: you can redistribute it and/or modify it under the terms ofversion 3 of the GNU Lesser General Public Licenseas published by theFree Software Foundation. A copy of the GNU Lesser General Public License is published along withalgebraixlibonGitHub. Otherwise, seeGNU licenses.Warrantyalgebraixlibis distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
algebraMathGenerator
Algebra generator that can easily create algebra equations in the Ax + b = C format. It can also solve equations in Ax + b = C. Right now, only the operations, '-' and '+' are supportedGetting StartedThe following is an example of how to create a algebra math equation. ThealgebraMathGenerator.generateAlgebraEquation()will return a class, so you can get the equation by adding a.equationafter it.importalgebraMathGeneratorequationClass=algebraMathGenerator.generateAlgebraEquation(operation="+")print(equationClass.equation)# returns equationYou can solve equations withalgebraMathGenerator.solveAlgebraEquation(equation : class). The equation variable should be a class returned fromalgebraMathGenerator.generateAlgebraEquation()importalgebraMathGeneratorequationClass=algebraMathGenerator.generateAlgebraEquation(operation="+")answer=algebraMathGenerator.solveAlgebraEquation(equationClass)print(equationClass.equation)# returns an equationprint(answer)# returns the answer to the equation aboveYou can even loop through the generate method to produce a bunch of equations and their answers!DocumentationClassalgebraMathGenerator2 functionsFunction:.generateAlgebraEquation(operation : str).equation- returns the equation Example:2x + 4 = 6.variable- returns the variable Example:x.operation- returns the operation done Example:+.equalsTo- returns the number the equation is equal to. Example:6.coeffecient- returns the number mutiplied by the variable Example:2.constant- returns the constant term in the equation. Example:4ReturnsclassobjectFunction:solveAlgebraEquation(equation : class)Input should be of type.generateAlgebraEquation()ReturnsfloatvalueChange Log0.0.3 (04/23/2020)Updating documentation
algebraML
Basic algebra for Machine LearningThis package performs basic operations between two matrices that are used in the field of machine learning such as:addition, subtraction, multiplication and division. It can also perform single matrix operations such as:dot product, inverse matrix finding and determinant.InstallationRun the following command in your terminal:$ pip install -i https://test.pypi.org/simple/ basic-algebra-ml==0.0.1UsageThe package is composed of two classes:1) Basic_OperationsParent class that has the following methods:check_type_matrix:checks if the parameters are a matrix of type<<numpy.ndarray>>.addition:adds two matrices together. For example:# Declare the matrix [In]: from basic_operations import Basic_Operations # Declare the matrix matrix1 = ([1, 6, 5], [6, 14, 34], [21, 12, 4]) matrix2 = ([3, 2, 54], [21, 12, 9], [1, 6, 5]) # Instantiate the class test = Basic_Operations(matrix1, matrix2) print(test.addition()) [Out]: [[ 4. 8. 59.] [27. 26. 43.] [22. 18. 9.]]subtraction:subtraction of two matrices. With the matrices of the previous example, then we have the following result:[In]: print(test.subtraction()) [Out]: [[ -2. 4. -49.] [-15. 2. 25.] [ 20. 6. -1.]]multiplication:multiply two matrices.Note: Remember that to perform multiplication between matrices the number of rows must match the number of columns.[In]: matrix3 = ([8, 56, 7], [6, 14, 34], [9, 63, 5]) matrix4 = ([36, 1, 2], [94, 9, 12], [3, 66, 1]) test2 = Basic_Operations(matrix3, matrix4) print(test2.multiplication()) [Out]: [[ 288. 56. 14.] [ 564. 126. 408.] [ 27. 4158. 5.]]Note the following example where the dimensions do not match between more matrices. The program will give a message indicating the error.[In]: matrix3 = ([8, 56, 7], [6, 14, 34], [9, 63, 5]) matrix4 = ([36, 1, 2], [94, 9, 12]) print(test2.multiplication()) [Out]: Error: operands could not be broadcast together with shapes (3,3) (2,3)division:divide two matrices. See the following example:Below are several examples of how you can use this package:[In]: print(test2.division()) [Out]: [[ 0.22222222 56. 3.5 ] [ 0.06382979 1.55555556 2.83333333] [ 3. 0.95454545 5. ]]dot:Dot product of two arrays. See the following example:[In]: matrix5 = ([8, 56, 7], [6, 14, 34], [9, 63, 5]) matrix6 = ([3, 2, 54], [21, 12, 9], [1, 6, 5]) test3 = Basic_Operations(matrix5, matrix6) print(test3.dot()) [Out]: [[1207. 730. 971.] [ 346. 384. 620.] [1355. 804. 1078.]]2) Operations_One_Matrix:Child class that inherits fromBasic_Operations. With this class you can perform the following operations with a matrix:scalar:multiply a matrix by a scalar[In]: from matrix_manipulations import Operations_One_Matrix matrix = ([36, 1, 2], [94, 9, 12], [3, 66, 1]) test = Operations_One_Matrix(matrix) print(test.scalar(2)) [Out]: [[ 72. 2. 4.] [188. 18. 24.] [ 6. 132. 2.]]shape:checks the dimensions of a matrix.[In]: print(test.scalar(2)) [Out]: (3, 3)inverse:calculate the inverse of a matrixtranspose:Invert or permute the axes of a matrix
algebrapackrpe
My first Python package with a slightly longer description
algebra.py
algebraInstall withPyPipip install algebra.pyHow to useImportingfromalgebra.componentsimporttermInitializingNote: to see the output shown in the comments you will need to runprint()orstr()at the answerNote:Do not use j as a variable.it is being used for complex number handlingterm1=term('2x')# 2x#exponent in termsterm2=term('2x²')# 2x²term3=term('2x2')# also works#supports multiple variablesterm4=term('2x2y3')# 2x²y³# suports negative coefficientsterm5=term('-2x3')# -2x³#supports complex exponents and coefficientsterm6=term('2x2+2j')# 2x²⁺²ⁱterm7=term('3+1jx3')# (3+1j)x³Accesssing propertiest1=term('2x3+2jy4+3j')# 2x³⁺²ⁱy⁴⁺³ⁱ# coefficientt1.coefficiente# 2# variablest1.variables# list of the variables,in alphabetic ordert1.variables[0].letra# xt1.variables[0].exponente# (3+2j)Supported Operationssumsubstraction is supported the same waysum1=term('2x')+term('3x')# 5xsum2=term('2x')+term('2y')# 2x + 2y# supports integer,float or decimal sumssum3=term('3x')+4# 3x + 4# supports complex sumssum4=term('3x2+1j')+term('3x3+2j')# 3x²⁺¹ⁱ + 3x³⁺²ⁱ#supports sums with complex numberssum5=term('3x2+1j')+5-2j# 3x²⁺¹ⁱ + (5-2j)multiplicationmul1=term('2x')*4# 8xmul2=term('2x')*term('3x')# 6x²mul3=term('2x')*term('3y')# 6xymul4=term('2xy')*term('3yz')# 6xy²zmul5=term('3x1+3j')*term('3x')# 9x²⁺³ⁱmul6=term('3x1+3j')*(2+1j)# (6+3j)x¹⁺³ⁱmul7=term('3x1+3j')*term('3x2+4j')#9x³⁺⁷ⁱdivisiondiv1=term('4x')/2# 2xdiv2=term('4x')/term('2x')# 2div3=term('4x2')/term('4x')# xdiv4=term('4x')/term('4x2')# xᐨ¹div5=term('4x2')/term('4x2')# 1Exponentiationexp1=term('2x')**2#4x²exp2=term('2x')**-1# 0.5xᐨ¹exp2=term('2x')**term('2x')# not supportedexp3=term('2x')**2.5# 5.656854249492381x⁵ᐟ²polynomsexamplepol1=term('2x')+term('3y')# 2x + 3ypol2=term('2x')-2# 2x - 2# polynom propertiespol2.variables# list of termspol2.variables[0]# 2xpol2.variables[1]# -2# sumpol4=pol1+pol2# 4x + 3y - 2# multiplicationpol5=pol1*pol2# 4x² + 6xy + -4x + -6y'# exponentiationpol6=pol1**2# 4x² + 12xy + 9y²pol7=pol1**2.5# non-integer powers are not yet supportedpol8=pol1**pol2# not supporteddiv1=pol1/2# x + 1.5ydiv2=pol1/term('2x')# 1 + 1.5xᐨ¹ydiv3=pol1/pol2# not supportedsubstituting numbers to the variablesterm1=term('2y')pol1=term('2x')+term('3y')term1.plot(y=2)# 4pol1.plot(x=2,y=3)# 13# univ sets every variable which does not has a value to its valuepol1.plot(univ=5)# 25 (x=5,y=5)pol1.plot(x=2,univ=4)# 16 (only replaces y,x is set to 2)accessing properties on termst1=term('2x²y')t1.coefficiente# acceses the coefficient (2)t1.variables# accesses the list of variables (returns [x²,y])t1.variables[0].letra# xt1.variables[0].exponente# 2accessing properties on polynomst1=term('2x²y')t2=2p1=t1+t2# 2x²y + 2p1.variables# [term(2x²y),2]foriinp1:print(i)# iterating a polynom iterates over the list of terms# it contains# term() objects cannot be iterated overpolynoms support sum, substraction, multiplication and exponents as terms do.have fun!
algebratrio
algebratrio
algebreb
algebreb
algefunc
AlgefuncA small demo library for studying libraries in pythonInstallationpip install algefuncGet startedHow to work with a function of first degree with this lib:fromalgefuncimportfunc# Instantiate a variablefunctiontest=func('4x-8')# Print the variableprint(functiontest)# Output: 2.0
algen
# AlgenAlgen generates opionated ORM classes for sqlalchemy given a simple schemaeither as a commandline string or as a yaml file. It is designed to haveminimal dependencies and is trivially extensible. A command line toolis bundled along to help generate the models. For DB specific types,only postgres is currently supported. The tool currently assumes thatsqlalchemy's declarative base object is to be imported like```from .alchemy_base import Base```The library prefers making the code verbose rather than concise for thesake of having better auto-completion and help from your editor/IDEe.g. first style is preferred to the second one:```pythondef update(self, a=None, b=None):if a is not None:self.a = aif b is not None:self.b = b``````pythondef update(self, **kwargs):for k,v in kwargs.items():if hasattr(self, k) and v is not None:setattr(self, k, v)```### CLI```bash$ algen --helpUsage: algen [OPTIONS]Options:-n, --name TEXT Name of model-c, --columns TEXT Column definition. e.g. col_name:col_type Can beused multiple times hence named columns. e.g. -cfoo:Int -c bar:Unicode(20)-d, --destination PATH Destination directory. Default will assume 'models'directory inside the current working directory-y, --yaml PATH Yaml file describing the Model. This supersedes thecolumn definition provided through --columns option.--help Show this message and exit.```Given a file as follows:```yamlPerson:columns:- name: idtype: BigIntegerprimary_key: Trueauto_increment: True- name: nametype: Unicode(255)- name: is_viptype: Boolean- name: created_attype: DateTime(timezone=True)server_default: now() at time zone 'utc'- name: updated_attype: DateTime(timezone=True)server_default: now() at time zone 'utc'relationships:- name: addressesclass: Addressback_populates: 'person'Address:columns:- name: idtype: BigIntegerprimary_key: Trueauto_increment: True- name: line1type: Unicode()- name: line2type: Unicode()- name: line3type: Unicode()- name: postcodetype: Unicode(10)index: True- name: created_attype: DateTime(timezone=True)server_default: now() at time zone 'utc'- name: updated_attype: DateTime(timezone=True)server_default: now() at time zone 'utc'foreign_keys:- name: person_idtype: BigIntegerreference:table: personscolumn: idnullable: Falserelationships:- name: personclass: Personback_populates: 'addresses'```The cli tool will create two the following two files ```person.py``` and ```address.py```.```pythonfrom __future__ import unicode_literals, absolute_import, print_functionfrom collections import namedtuplefrom sqlalchemy import Column, Unicode, BigInteger, DateTime, ForeignKeyfrom sqlalchemy.orm import relationshipfrom .alchemy_base import Base__author__ = 'danishabdullah'class Address(Base):__tablename__ = 'addresses'id = Column(BigInteger, auto_increment=True, primary_key=True)line1 = Column(Unicode(), )line2 = Column(Unicode(), )line3 = Column(Unicode(), )postcode = Column(Unicode(10), index=True)created_at = Column(DateTime(timezone=True), server_default="now() at time zone 'utc'")updated_at = Column(DateTime(timezone=True), server_default="now() at time zone 'utc'")# --- Foreign Keys ---person_id = Column(BigInteger, ForeignKey('persons.id'), nullable=False)# --- Relationships ---person = relationship('Person', back_populates='addresses')def __init__(self, id=None, line1=None, line2=None, line3=None, postcode=None, created_at=None, updated_at=None, person_id=None):self.id = idself.line1 = line1self.line2 = line2self.line3 = line3self.postcode = postcodeself.created_at = created_atself.updated_at = updated_atself.person_id = person_iddef add(self, session):session.add(self)def update(self, line1=None, line2=None, line3=None, postcode=None, created_at=None, updated_at=None, person_id=None):# This function only updates a value if it is not None.# Falsy values go through in the normal way.# To set things to None use the usual syntax:# Address.column_name = Noneif line1 is not None:self.line1 = line1if line2 is not None:self.line2 = line2if line3 is not None:self.line3 = line3if postcode is not None:self.postcode = postcodeif created_at is not None:self.created_at = created_atif updated_at is not None:self.updated_at = updated_atif person_id is not None:self.person_id = person_iddef delete(self, session):session.delete(self)def to_dict(self):return {x: y for x, y in self.__dict__.items() if not x.startswith("_sa")}def get_proxy_cls(self):# AddressProxy is useful when you want to persist data# independent of the sqlalchemy session. It's just a namedtuple# that has very low memory/cpu footprint compared the regular# orm class instances.keys = self.to_dict().keys()name = "AddressProxy"return namedtuple(name, keys)def to_proxy(self):# Proxy-ing is useful when you want to persist data# independent of the sqlalchemy session. It's just a namedtuple# that has very low memory/cpu footprint compared the regular# orm class instances.cls = self._get_proxy_cls()return cls(**self.to_dict())@classmethoddef from_proxy(cls, proxy):return cls(**proxy._asdict())def __hash__(self):return hash(str(self.id))def __eq__(self, other):return (self.id == other.id)def __neq__(self, other):return not (self.id == other.id)def __str__(self):return "<Address: {id}>".format(id=self.id)def __unicode__(self):return "<Address: {id}>".format(id=self.id)def __repr__(self):return "<Address: {id}>".format(id=self.id)``````pythonfrom __future__ import unicode_literals, absolute_import, print_functionfrom collections import namedtuplefrom sqlalchemy import Column, Unicode, BigInteger, Boolean, DateTimefrom sqlalchemy.orm import relationshipfrom .alchemy_base import Base__author__ = 'danishabdullah'class Person(Base):__tablename__ = 'persons'id = Column(BigInteger, auto_increment=True, primary_key=True)name = Column(Unicode(255), )is_vip = Column(Boolean, )created_at = Column(DateTime(timezone=True), server_default="now() at time zone 'utc'")updated_at = Column(DateTime(timezone=True), server_default="now() at time zone 'utc'")# --- Foreign Keys ---# --- Relationships ---addresses = relationship('Address', back_populates='person')def __init__(self, id=None, name=None, is_vip=None, created_at=None, updated_at=None):self.id = idself.name = nameself.is_vip = is_vipself.created_at = created_atself.updated_at = updated_atdef add(self, session):session.add(self)def update(self, name=None, is_vip=None, created_at=None, updated_at=None):# This function only updates a value if it is not None.# Falsy values go through in the normal way.# To set things to None use the usual syntax:# Person.column_name = Noneif name is not None:self.name = nameif is_vip is not None:self.is_vip = is_vipif created_at is not None:self.created_at = created_atif updated_at is not None:self.updated_at = updated_atdef delete(self, session):session.delete(self)def to_dict(self):return {x: y for x, y in self.__dict__.items() if not x.startswith("_sa")}def get_proxy_cls(self):# PersonProxy is useful when you want to persist data# independent of the sqlalchemy session. It's just a namedtuple# that has very low memory/cpu footprint compared the regular# orm class instances.keys = self.to_dict().keys()name = "PersonProxy"return namedtuple(name, keys)def to_proxy(self):# Proxy-ing is useful when you want to persist data# independent of the sqlalchemy session. It's just a namedtuple# that has very low memory/cpu footprint compared the regular# orm class instances.cls = self._get_proxy_cls()return cls(**self.to_dict())@classmethoddef from_proxy(cls, proxy):return cls(**proxy._asdict())def __hash__(self):return hash(str(self.id))def __eq__(self, other):return (self.id == other.id)def __neq__(self, other):return not (self.id == other.id)def __str__(self):return "<Person: {id}>".format(id=self.id)def __unicode__(self):return "<Person: {id}>".format(id=self.id)def __repr__(self):return "<Person: {id}>".format(id=self.id)```
algepy
algepyEnglish readme version, click to spand.What is Algepy?Algepy is a Python Package that allows you to manipulate vectors, points and planes. It can be useful to calculate or verify the results of your operations.This project is still under development and is not fully developed, it may have some bugs or failures.InstallationVectorBasic operationsOppositeMagnitudeDirection CosineAngle between two vectorsDot productPerpendicularProyectionCross productTriple productPointBasic operationsMidpointFind the vector between two pointsPlaneGeneral equationSymmetric equationPlotVectorPointPlaneContributionsInstallationUsingPython Package Index (PyPI)pipinstallalgepyManuallygitclonehttps://github.com/manucabral/algepy.gitcdalgepyVectorTo create a vector you simply need to instantiate the Vector class with its components (x, y, z)By default it will have 3 dimensions but you can specify the dimension as in the following example.fromalgepyimportVectorv=Vector(x=1,y=1,z=1)u=Vector(x=1,y=1,z=1,dimension=2)Basic operationsTo add and subtract you just have to use the + and - operator, both operations returns a vector.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>v=Vector(x=0,y=2,z=5)>>>u+v(1,4,8)>>>u-v(1,0,-2)OppositeTo get the opposite of a vector you have to use itsoppositemethod, this method returns a new vector.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>u.opposite()(-1,-2,-3)MagnitudeTo get magnitude of the vector, you have to usemagnitudemethod, this method returns a decimal number.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>u.magnitude()3.7416573867739413Direction CosineTo get the direction angles of a vector you have to use thedirection_cosinemethod, this method requires that you specify the axis (x, z, y).The method returns radians by default but you can change it to degrees using thedegreesparameter, the same applies with thedecimalsparameter.>>>fromalgepyimportVector>>>a=Vector(x=2,y=0,z=-2)>>>a.direction_cosine(axis='x',degrees=True)45.0>>>a.direction_cosine(axis='y',degrees=True)90.0>>>a.direction_cosine(axis='z',degrees=True)135.0Angle between two vectorsTo get the angle between two vectors, use the commutative methodangle.The method returns radians by default but you can change it to degrees using thedegreesparameter, the same applies with thedecimalsparameter.>>>fromalgepyimportVector>>>u=Vector(x=1,y=1,z=3)>>>v=Vector(x=-1,y=0,z=4)>>>u.angle(v,degrees=True,decimals=3)36.448>>>u.angle(v)# resultado en radianes0.6361Dot productTo get the dot product between two vectors, use the * operator (do not confuse this operator with the cross product), this operation returns a scalar number.>>>fromalgepyimportVector>>>u=Vector(x=-3,y=5,z=8)>>>v=Vector(x=1,y=1,z=1)>>>u*v10PerpendicularTo know if a vector is perpendicular to another you have to use theperpendicularmethod, this method returns a boolean value (True or False)>>>fromalgepyimportVector>>>u=Vector(x=1,y=1,z=3)>>>v=Vector(x=-1,y=0,z=4)>>>u.perpendicular(v)FalseProyectionTo get the projection of one vector in the direction of another you have to use theprojectionmethod, this method returns a list with two vectors.w:main vector (u) projected on another vector (v)n:other vector (v) projected on main vector (u)The main vector is the vector to which we apply theprojectionmethod.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=1)>>>v=Vector(x=0,y=1,z=-1)>>>w,n=u.proyection(v)>>>w(0.0,0.4999999999999999,-0.4999999999999999)# u on v>>>n(1.0,1.5,1.5)# v on uCross productTo get the cross product between two vectors, you must use thecrossmethod, this returns the vector resulting from the cross product.Bear in mind that the vector product is not commutative, since if we change the order of the vectors, the direction and the magnitude of the vector product are preserved, but the sense is reversed.>>>fromalgepyimportVector>>>a=Vector(x=1,y=2,z=3)>>>b=Vector(x=0,y=2,z=5)>>>v=a.cross(b)>>>v(4,-5,2)# cross product>>>v.perpendicular(a),v.perpendicular(b)True,TrueTriple productTo get the triple product you have to use thetriplemethod, this returns a number and isn't commutative.Definedu,vandwWhen using the method onu.triple(v,w) the cross product betweenvandwwill be applied and then the dot product betweenu(vxw)>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>v=Vector(x=0,y=2,z=5)>>>w=Vector(x=0,y=0,z=2)>>>u.triple(v,w)4>>>u*v.cross(w)# equivalentPointTo create a point you simply need to instantiate the Point class with its (x,y,z) components.You can only use 3-dimensional points.fromalgepyimportPoint>>>R=Point(x=1,y=1,z=4)>>>S=Point(x=3,y=0,z=2)Basic operationsTo add and subtract you just have to use the + and - operator, both operations return a point.MidpointTo get the midpoint between two points, use themidpointmethod, it returns a vector with the components of the midpoint.fromalgepyimportPoint>>>r=Point(x=1,y=2,z=3)>>>s=Point(x=3,y=-1,z=2)>>>r.midpoint(s)(2.0,0.5,2.5)Find the vector between two pointsTo get a vector from two points you have to use thefind_vectormethod, this returns a vector formed from the two points.fromalgepyimportPoint>>>r=Point(x=1,y=1,z=4)>>>s=Point(x=3,y=0,z=2)>>>r.find_vector(s)(2,-1,-2)PlaneTo create a plane we need the normal vector (vector perpendicular to the plane) and some point that belongs to the plane.>>>fromalgepyimportVector,Point,Plane>>>n=Vector(x=2,y=-3,z=1)>>>p=Point(x=1,y=3,z=1)>>>plane=Plane(normal=n,point=p)>>>planeπ:2x-3y1z6=0If we do not pass the normal vector and the default point so these will be null vectors, we can also manually assign the components of the plane by accessing the properties a, b, c and d.>>>fromalgepyimportVector,Point,Plane>>>plane=Plane()>>>planeπ:0x0y0z0=0>>>plane.a=5π:5x0y0z0=0General equationTo get the implicit or general equation of the plane, we simply access the plane object created previously.>>>planeπ:2x-3y1z6=0Symmetric equationTo get the segmental equation of the plane we must use thesymmetric_equationmethod, for this we need at least to have defined the components of the plane (a, b, c and d).We can indicate to the method if we want the result as a fraction or by decimals through thefractionparameter>>>fromalgepyimportVector,Point,Plane>>>n=Vector(x=2,y=-3,z=1)>>>plane=Plane(normal=n)>>>plane.d=6>>>plane.symmetric_equation(fraction=True)2x/-6-3y/-61z/-6=1>>>plane.symmetric_equation(decimals=3)x/0.333y/-0.5z/0.167=1PlotAlgepy uses pyplot from matplotlib so for this module to work, you need to have this package installed.For now the plot only supports 3 dimensions, you can try others dimensions but you will have errors.plot=Plot(name='Example',projection='3d')plot.show()Plot a vectorTo add a vector to our plot we need to use theadd_vectormethod and also have an origin point for the vector.Once this is done we can show the graph with theshowmethod.fromalgepyimportVector,Point,Plotorigin=Point(x=0,y=0,z=0)a=Vector(x=1,y=2,z=3)plot=Plot(name='Vector',projection='3d')plot.add_vector(origin=origin,vector=a)plot.show()Plot a pointTo add a point to our plot we need to use theadd_pointmethod.Once this is done we can show the graph with theshowmethod.fromalgepyimportPoint,Plotp=Point(x=1,y=2,z=3)plot=Plot(name='Point',projection='3d')plot.add_point(point=p,color='red')plot.show()Plot a planeTo add a plane to our plot we need to use theadd_planemethod.Once this is done we can show the graph with theshowmethod.fromalgepyimportVector,Point,Planen=Vector(x=2,y=-3,z=1)p=Point(x=1,y=3,z=1)plane=Plane(normal=n,point=p)plot=Plot(projection='3d',range=[-5,5])plot.add_plane(plane=plane,color='red')plot.show()ContributionsAll contributions, reports or bug fixes and ideas are welcome. You can go to the issues section and provide your help.Versión español, click para expander.¿Qué es algepy?Algepy es una libreria de python que te permite manipular vectores de hasta 3 dimensiones, te puede ser útil para calcular o verificar los resultados de tus operaciones.Este proyecto todavía se encuentra en desarrollo y no está completamente desarrollado, puede tener algunos bugs o fallos.InstalaciónVectorOperaciones básicasOpuestoMódulo o normaÁngulos directoresÁngulo entre dos vectoresProducto escalarPerpendicularidadProyección de vectoresProducto vectorialProducto mixtoPuntoOperaciones básicasPunto medioVector a partir de dos puntosPlanoEcuación generalEcuación segmentariaGráficoVectorPuntoPlanoContribucionesInstalaciónUtilizandoPython Package Index (PyPI)pipinstallalgepyManualmentegitclonehttps://github.com/manucabral/algepy.gitcdalgepyVectorPara definir un vector simplemente necesitas instanciar la clase Vector con sus componentes (x, y, z)Por defecto tendrá 3 dimensiones pero puedes especificarle la dimensión como en el siguiente ejemplo.fromalgepyimportVectorv=Vector(x=1,y=1,z=1)u=Vector(x=1,y=1,z=1,dimension=2)# ignorará el eje zOperaciones básicaPara sumar y restar solamente tienes que utilizar el operador + y -, las dos operaciones devuelve un vector.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>v=Vector(x=0,y=2,z=5)>>>u+v(1,4,8)>>>u-v(1,0,-2)OpuestoPara obtener el opuesto de un vector hay que utilizar su métodoopposite, este método devuelve un nuevo vector.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>u.opposite()(-1,-2,-3)Módulo o normaPara obtener el módulo o la norma del vector hay que utilizar su métodomagnitude, este método devuelve un número decimal.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>u.magnitude()3.7416573867739413Ángulos directoresPara obtener los ángulos directores de un vector hay que utilizar el métododirection_cosine, este método requiere que le especifiques el eje obligatoriamente (x, z, y).El método devuelve por defecto en radianes pero lo puedes cambiar a grados mediante el parámetrodegrees, aplica lo mismo con el parámetrodecimals.>>>fromalgepyimportVector>>>a=Vector(x=2,y=0,z=-2)>>>a.direction_cosine(axis='x',degrees=True)# ángulo director respecto al eje x45.0>>>a.direction_cosine(axis='y',degrees=True)# ángulo director respecto al eje y90.0>>>a.direction_cosine(axis='z',degrees=True)# ángulo director respecto al eje z135.0Ángulo entre dos vectoresPara obtener el ángulo que se forma entre dos vectores hay que utilizar el método conmutativoangle.El método devuelve por defecto en radianes pero lo puedes cambiar a grados mediante el parámetrodegrees, aplica lo mismo con el parámetrodecimals.>>>fromalgepyimportVector>>>u=Vector(x=1,y=1,z=3)>>>v=Vector(x=-1,y=0,z=4)>>>u.angle(v,degrees=True,decimals=3)# resultado en grados con 3 decimales36.448>>>u.angle(v)# resultado en radianes0.6361Producto escalarPara obtener el producto escalar entre dos vectores hay que utilizar el operador * (no confundir este operador con el producto vectorial) esta operación devuelve un número escalar.>>>fromalgepyimportVector>>>u=Vector(x=-3,y=5,z=8)>>>v=Vector(x=1,y=1,z=1)>>>u*v10PerpendicularidadPara saber si un vector es perpendicular a otro hay que utilizar el métodoperpendicular, este método devuelve un valor booleano (True o False)>>>fromalgepyimportVector>>>u=Vector(x=1,y=1,z=3)>>>v=Vector(x=-1,y=0,z=4)>>>u.perpendicular(v)FalseProyección de vectoresPara obtener la proyección de un vector en la dirección de otro hay que utilizar el métodoprojection, este método devuelve una lista con dos vectores.w:vector principal (u) proyectado en otro vector (v)n:otro vector (v) proyectado en el vector principal (u)El vector principal es el vector al que le aplicamos el métodoprojection.>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=1)>>>v=Vector(x=0,y=1,z=-1)>>>w,n=u.proyection(v)>>>w(0.0,0.4999999999999999,-0.4999999999999999)# vector u proyectado en v>>>n(1.0,1.5,1.5)# vector v proyectado en uProducto vectorialPara obtener el producto vectorial entre dos vectores hay que utilizar el métodocross, este método devuelve el vector resultado del producto vectorial.Tener en cuenta que el producto vectorial no es conmutativo, ya que si cambiamos el orden de los vectores se conservan la dirección y el módulo del producto vectorial pero se invierte el sentido.>>>fromalgepyimportVector>>>a=Vector(x=1,y=2,z=3)>>>b=Vector(x=0,y=2,z=5)>>>v=a.cross(b)>>>v(4,-5,2)# producto vectorial>>>v.perpendicular(a),v.perpendicular(b)True,TrueProducto mixtoPara obtener el producto mixto hay que utilizar el métodotriple, este método devuelve un escalar y no es conmutativo así que hay que tener en cuenta lo siguiente.Definidosu,vywCuando se utiliza el método enu.triple(v,w) se aplicará primero el producto vectorial entrevywpara después calcular el producto escalaru(vxw)>>>fromalgepyimportVector>>>u=Vector(x=1,y=2,z=3)>>>v=Vector(x=0,y=2,z=5)>>>w=Vector(x=0,y=0,z=2)>>>u.triple(v,w)4>>>u*v.cross(w)# equivalentePuntoPara definir un punto simplemente necesitas instanciar la clase Point con sus componentes (x, y, z).Por ahora solamente puedes utilizar puntos de 3 dimensiones.fromalgepyimportPoint>>>R=Point(x=1,y=1,z=4)>>>S=Point(x=3,y=0,z=2)Operaciones básicasPara sumar y restar solamente tienes que utilizar el operador + y -, las dos operaciones devuelve un punto.Punto medioPara obtener el punto medio entre dos puntos hay que utilizar el métodomidpoint, este devuelve un vector con los componentes del punto medio.fromalgepyimportPoint>>>r=Point(x=1,y=2,z=3)>>>s=Point(x=3,y=-1,z=2)>>>r.midpoint(s)(2.0,0.5,2.5)Vector a partir de dos puntosPara obtener un vector a partir de dos puntos hay que utilizar el métodofind_vector, este devuelve un vector formado a partir de los dos puntos.>>>fromalgepyimportPoint>>>r=Point(x=1,y=1,z=4)>>>s=Point(x=3,y=0,z=2)>>>r.find_vector(s)(2,-1,-2)PlanoPara crear un plano necesitamos el vector normal (vector perpendicular al plano) y algún punto que pertenezca al plano.>>>fromalgepyimportVector,Point,Plane>>>n=Vector(x=2,y=-3,z=1)>>>p=Point(x=1,y=3,z=1)>>>plano=Plane(normal=n,point=p)>>>planoπ:2x-3y1z6=0Si no le pasamos el vector normal y el punto por defecto estos serán vectores nulos, también podemos asignarle manualmente los componentes del plano accediendo a las propiedades a, b, c y d.>>>fromalgepyimportVector,Point,Plane>>>plano=Plane()>>>planoπ:0x0y0z0=0>>>plano.a=5π:5x0y0z0=0Ecuación generalPara obtener la ecucación implícita o general del plano simplemente accedemos al objeto plano creado anteriormente.>>>planoπ:2x-3y1z6=0Ecuación segmentariaPara obtener la ecucación segmentaria del plano hay que utilizar el métodosymmetric_equation, para esto necesitamos al menos tener definido los componentes del plano (a, b, c y d).Al método le podemos indicar si el resultado lo queremos como fracción o por decimales mediante el parámetrofraction>>>fromalgepyimportVector,Point,Plane>>>n=Vector(x=2,y=-3,z=1)>>>plano=Plane(normal=n)>>>plano.d=6>>>plano.symmetric_equation(fraction=True)2x/-6-3y/-61z/-6=1>>>plano.symmetric_equation(decimals=3)x/0.333y/-0.5z/0.167=1GráficoAlgepy utiliza pyplot de matplotlib así que para que este módulo te funcione necesitas tener instalado este paquete.Por ahora el gráfico solamente soporta 3 dimensiones, puedes intentar con otras pero corres el riesgo de obtener varios errores.grafico=Plot(name='Ejemplo',projection='3d')grafico.show()Gráfico de un vectorPara agregar un vector a nuestro gráfico necesitamos utilizar el métodoadd_vectory además tener un punto de origen para el vector.Una vez realizado esto podemos mostrar el gráfico con el métodoshowfromalgepyimportVector,Point,Plotorigen=Point(x=0,y=0,z=0)a=Vector(x=1,y=2,z=3)grafico=Plot(name='Vector',projection='3d')grafico.add_vector(origin=origen,vector=a)grafico.show()Gráfico de un puntoPara agregar un punto a nuestro gráfico necesitamos utilizar el métodoadd_pointUna vez realizado esto podemos mostrar el gráfico con el métodoshowfromalgepyimportPoint,Plotp=Point(x=1,y=2,z=3)grafico=Plot(name='Punto',projection='3d')grafico.add_point(point=p,color='red')grafico.show()Gráfico de un planoPara agregar un plano a nuestro gráfico necesitamos utilizar el métodoadd_planeUna vez realizado esto podemos mostrar el gráfico con el métodoshowfromalgepyimportVector,Point,Planen=Vector(x=2,y=-3,z=1)p=Point(x=1,y=3,z=1)plano=Plane(normal=n,point=p)grafico=Plot(projection='3d',range=[-5,5])grafico.add_plane(plane=plano,color='red')grafico.show()ContribuciónTodas las contribuciones, reportes o arreglos de bugs e ideas es bienvenido. Para esto puedes dirigirte al apartado de issues y aportar tu ayuda.
algeria
🇩🇿 Algeria 🇩🇿Algeria is a Python library that allows you to calculate the (clé) and RIP (Relevé d'Identité Postal) of a given CCP (Compte de Chèque Postal) number account. It provides a simple and convenient way to obtain the clé and rip values for CCP accounts. Please note that additional features may be added to the library in the future. You can check features section for any updates.Contributions are welcome! If you would like to contribute to the development of the Algeria library, feel free to submit pull requests or open issues on the GitHub repository.💡 FeaturesClé (Compte de Chèque Postal) calculation.RIP (Relevé d'Identité Postal) calculation.RIP's Clé calculation.Deposit fees calculationCheckout fees calculation📌 InstalationYou can install the "algeria" library using pip:pipinstallalgeriaIf you want to use the development version:pipinstallgit+https://github.com/mouh2020/algeria.git📚 UsageCCP class :The CCP class provides methods to calculate the (clé) and (RIP) for a given CCP account number.InitializationTo create an instance of the CCP class, pass the CCP account number as a string to the constructor:fromalgeria.ccpimportCCPccp_account=CCP("1234567890")Calculating the cléTo calculate the clé of the CCP account, use the get_cle method:cle=ccp_account.get_cle()print("Clé CCP:",cle)Calculating the ripTo calculate the rip of the CCP account, including the first 8 digits "00799999", use the get_rip method:rip=ccp_account.get_rip()print("RIP:",rip)Calculating the cle of the ripTo calculate only the clé of the rip, use the get_rip_cle method:rip_cle=ccp_account.get_rip_cle()print("RIP Clé:",rip_cle)Transaction class :The Transaction class provides methods to calculate the fees of a deposit or checkout amount.InitializationTo create an instance of the Transaction class, pass the amount as a float to the constructor:fromalgeria.ccpimportTransactiontransaction=Transaction(2000000)Calculating the fees of a deposit transactionTo calculate the fees of a deposit transaction, use the get_deposit_fees method:transaction_fees=transaction.get_deposit_fees()print("Deposit fees:",transaction_fees)Calculating the fees of a checkout transactionTo calculate the fees of a checkout transaction, use the get_checkout_fees method:checkout_fees=transaction.get_checkout_fees()print("Checkout fees:",checkout_fees)ExampleHere's an example demonstrating the usage of the "algeria" library :fromalgeria.ccpimportCCP,Transactionccp_account=CCP("1234567890")cle=ccp_account.get_cle()print("Clé CCP:",cle)// 45rip=ccp_account.get_rip()print("RIP:",rip)// 0079999912345678906rip_cle=ccp_account.get_rip_cle()print("RIP Clé:",rip_cle)// 06transaction=Transaction(2000000)deposit_fees=transaction.get_deposit_fees()print("Deposit fees:",deposit_fees)// 4818checkout_fees=transaction.get_checkout_fees()print("Checkout fees:",checkout_fees)// 9018💡 NoteThe algorithms extracted from the web app providedhereafter testing them.🚀 About MeA self-taught Python programmer who enjoys developing simple scripts, bots, and automation tools.
algernon
algernonReinforcement learning framework which supports scikit like interface.How to install$ pip install algernon
algerography
No description available on PyPI.
algfastcoding
这个库,什么功能都有!!/This library has all functions!!
algmarket
Algmarket Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algmarket.
alg-mat
No description available on PyPI.
algmonbody
the Algmon Body libcompany introhttps://algmon.com/lib introhttps://algmon.com/docs/infra/introlib source codegithubgiteehttps://gitee.com/algmon/public/tree/master/src/algmon-brainlib features(for human and env)3D & 4D & 5D time & space modelingsequence & position motion computation & simulationstatic & dynamic interaction among objectsdependenciesthe licenseThis package is released under the Apache License v2
algmonbrain
the Algmon Brain libcompany introhttps://algmon.com/lib introhttps://algmon.com/docs/infra/introlib source codegithubgiteehttps://gitee.com/algmon/public/tree/master/src/algmon-brainlib featuresintents simulation in deepsingle neural re-modelingneural network design & training & prediction at scaledependenciesthe licenseThis package is released under the Apache License v2
algmoninfra
the Algmon Infra libcompany introhttps://algmon.com/lib introhttps://algmon.com/docs/infra/introlib source codegithubgiteehttps://gitee.com/algmon/public/tree/master/src/algmon-brainlib featuresbe stableat scalein intelligentdependenciesthe licenseThis package is released under the Apache License v2
algmonpositiveflow
Algmon PositiveFlow toolkitcompany introhttps://algmon.com/toolkit introhttps://algmon.com/docs/infra/introfeaturesfocus ONLY on upper level applications & apisFAST prototyping for pocs and engineering projectseasy BABY Code for everyone to read, understand and writedependend python packagesalgmonbrain for brain support(algmon) ➜ pip install algmonbrainalgmonbody for body support(algmon) ➜ pip install algmonbodyalgmoninfra for computation infra support(algmon) ➜ pip install algmoninfrahow to publishpython -m build(optional) twine upload -r testpypi dist/*twine upload --skip-existing dist/*how to installpip install -r requirements.txthow to testhow to runpython main.pythe licenseApache License v2
algn2pheno
algn2phenoA bioinformatics tool for rapid screening of genetic features (nt or aa changes) potentially linked to specific phenotypesINTRODUCTIONThealgn2phenomodule screens a amino acid/nucleotide alignment against a "genotype-phenotype" database and reports the repertoire of mutations of interest per sequences and their potential impact on phenotype.INPUT FILESTable database in .tsv or .xlsx formatANDAlignment (nucleotide or amino acid)(Mutation numbering will refer to the user-defined reference sequence included in the alignment).INSTALLATIONpipinstallalgn2phenoUSAGEusage:algn2pheno[-h][--dbDB][--sheetSHEET][--tableTABLE][--gencolGENCOL][--phencolPHENCOL]-gGENE--algnALGN-rREFERENCE[--nucl][--odirODIR][--outputOUTPUT][--logLOG][-f]parsearguments optionalarguments:-h,--helpshowthishelpmessageandexit--dbDBphenotypedb.ifexcel,providesheetnameandcolumnsnumbersforgenotypeandphenotypedata.ifnotexcel,providepathtodb,ensure3columns'Mutation','Phenotype category'&'Flag'--sheetSHEET,-sSHEETGivesheetname(genenameor'Lineages').excelinput.--tableTABLE,-tTABLEtablenameindb.default:pokay.sqliteinput.--gencolGENCOLnrofcolumnwithgenotypedata.excelinput.--phencolPHENCOLnrofcolumnwithphenotypedata.excelinput.-gGENE,--geneGENESetgeneorproteinprefix--algnALGNInputalignmentfile-rREFERENCE,--referenceREFERENCEGivefullreferencesequenceasinalignmentfile(usequotationmarksifthiscontainsaspace)--nuclprovideifnucleotidealignmentinsteadofaminoacid.--odirODIR,-oODIRoutputdirectory--outputOUTPUTSetoutputfileprefix--logLOGlogfile-f,--forceoverwriteexistingfilesHow to run (examples)database (.tsv) + amino acid alignment (SARS-CoV-2 Spike)algn2pheno--dbdatabase.tsv--algnalignment_aa_Spike.fasta-gS-rreference_header--odiroutput_folder--outputoutput_prefixdatabase (.xlsx) + amino acid alignment (SARS-CoV-2 Spike)algn2pheno--dbdatabase.xlsx--algnalignment_aa_Spike.fasta--sheetS--gencol["Mutation"columnnumber]--phencol["Phenotype category"columnnumber]-gS-rreference_header--odiroutput_folder--outputoutput_prefixREQUIREMENTSThe input database must contain mutations and associated phenotypes, listed in columns namedMutationandPhenotype categoryrespectively. An additional columnFlagmay be provided for the ".tsv" input format.In the case of using an excel file as input, an intermediary .tsv database will be created. A "Flag" column will be generated automatically with Flags "D" and "P" to differentiate mutation(s) Directly associated with the phenotype ("D") and mutation(s) Partially associated with the phenotype (i.e., the mutation is Part of a constellation associated with that phenotype) ("P"). Constellation of mutations should be included in the same row separated by commas (e.g., H69del,H70del,L452R,N501Y).Undefined amino acids should be included as "X" in the protein alignment. Undefined nucleotides should be included as "N" in the gene alignment.Modules:Main alignment to phenotype.python=3.7biopythonnumpypandasFurther modules required to scrape Pokay database.openpyxlrequestspygithubsqlalchemybeautifulsoup4lxmlINSTALLATIONgit clone this repository.install and activate environment with required modules (seepyenv.yml).CONFIGURATIONThis module does not require configuration.MAIN OUTPUTS_full_mutation_report.tsv: provides the repertoire of "Flagged mutations" (i.e., database mutations detected in the alignment), the list of "phenotypes" supported by those mutations of interest and the list of "All mutations" detected in alignment for each sequence._flagged_mutation_report.tsv: "Flagged mutation" binary matrix for all sequences and the "associated" phenotypes.Other intermediate outputs:_all_mutation_matrix: matrix of all mutations found in the alignment [mutations coded as 1 (presence), 0 (absence)]. At this stage, undefined amino acids ("X") or undefined nucleotides ("n") are not yet handled as no coverage positions._all_mutation_report: matrix of all mutations found in the alignment [mutations coded as 1 (presence), 0 (absence) or nc (no coverage) positions] and associated phenotypes for the mutations in the database._all_db_mutations_report: matrix of mutations in the database [mutations coded as 1 (presence), 0 (absence) or nc (no coverage) positions] and associated phenotypes, regardless if they were found or not in the alignmentdatabase.CLEAN.tsv: conversion of the ".xlsx" database into a clean ".tsv" format adding the gene "prefix" (-g argument) to each mutation (similar to when providing a .tsv database with the three headers 'Mutation', 'Phenotype category' and 'Flag')MAINTAINERSCurrent maintainers:Joao Santos (santosjgnd)Bioinformatics Unit of the Portuguese National Institute of Health Dr. Ricardo Jorge (INSA) (insapathogenomics)CITATIONIf you run algn2pheno, please cite:João D. Santos, Carlijn Bogaardt, Joana Isidro, João P. Gomes, Daniel Horton, Vítor Borges (2022). Algn2pheno: A bioinformatics tool for rapid screening of genetic features (nt or aa changes) potentially linked to specific phenotypes.FUNDINGThis work was supported by funding from the European Union’s Horizon 2020 Research and Innovation programme under grant agreement No 773830: One Health European Joint Programme.
algnuth
![travis](https://travis-ci.org/louisabraham/algnuth.svg?branch=master)Algebraic Number Theory packageLouis AbrahamandYassir AkramInstallationpip install –upgrade algnuthor get the development version with:pip install –upgrade git+https://github.com/louisabraham/algnuthFeatures### Jacobi symbol` pycon >>> from algnuth.jacobi import jacobi >>> jacobi(3763, 20353)-1`### Solovay-Strassen primality test` pycon >>> from algnuth.jacobi import solovay_strassen >>> p = 12779877140635552275193974526927174906313992988726945426212616053383820179306398832891367199026816638983953765799977121840616466620283861630627224899026453 >>> q = 12779877140635552275193974526927174906313992988726945426212616053383820179306398832891367199026816638983953765799977121840616466620283861630627224899027521 >>> n = p * q >>> solovay_strassen(p) True >>> solovay_strassen(q) True >>> solovay_strassen(n) False `### Quadratic forms` pycon >>> from algnuth.quadratic import * >>>display_classes(-44)x^2 + 11⋅y^2 2⋅x^2 + 2⋅xy + 6⋅y^2 3⋅x^2 - 2⋅xy + 4⋅y^2 3⋅x^2 + 2⋅xy + 4⋅y^2 >>>display_primitive_forms(-44)x^2 + 11⋅y^2 3⋅x^2 - 2⋅xy + 4⋅y^2 3⋅x^2 + 2⋅xy + 4⋅y^2 >>>display_ambiguous_classes(-44)x^2 + 11⋅y^2 2⋅x^2 + 2⋅xy + 6⋅y^2 >>>display(*reduced(18,-10,2)) 2⋅x^2 + 2⋅xy + 6⋅y^2 `### Real polynomials` pycon >>> from algnuth.polynom import Polynomial >>> P =Polynomial([0]* 10 +[-1,0, 1]) >>> print(P)X^12-X^10>>> P(2) 3072 >>> P.disc 0 >>> P.sturm() # Number of distinct real roots 3 >>> P.r1 # Number of real roots with multiplicity 12 `### Modular arithmetic` pycon >>> P =Polynomial([1,2, 3]) >>> Pmodp = P % 41 >>> print(Pmodp ** 3) 27⋅X^6+13⋅X^5+22⋅X^4+3⋅X^3+21⋅X^2+6⋅X+1 >>>print((P** 3) % 41) 27⋅X^6+13⋅X^5+22⋅X^4+3⋅X^3+21⋅X^2+6⋅X+1 `### Polynomial division` pycon >>> A =Polynomial([1,2, 3, 4]) % 7 >>> B =Polynomial([0,1, 2]) % 7 >>> print(A) 4⋅X^3+3⋅X^2+2⋅X+1 >>> print(B) 2⋅X^2+X >>> print(A % B) 5⋅X+1 >>> print(A // B) 2⋅X+4 >>>print((A// B) * B + A % B) 4⋅X^3+3⋅X^2+2⋅X+1 `### Berlekamp’s factorization algorithm` pycon >>> P =Polynomial([0,1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) >>> Pmodp = P % 41 >>>print(Polynomial.ppfactors(Pmodp.factor()))12⋅(X+31)⋅X⋅(X^2+40⋅X+24)⋅(X^2+36⋅X+13)⋅(X^6+34⋅X^5+26⋅X^4+13⋅X^3+25⋅X^2+26⋅X+35)`### Unique Factorization of Ideals` pycon >>> from algnuth.ideals import factorIdeals >>>factorIdeals(Polynomial([4,0, 0,1]))X^3+4 mod 2 = X^3 (2) = (2,α)^3X^3+4 mod 3 =(X+1)^3(3) = (3,α+1)^3X^3+4 mod 5 =(X+4)⋅(X^2+X+1)(5) = (5,α+4)⋅(5,α^2+α+1) `
algo
No description available on PyPI.
algo2
No description available on PyPI.
algoa-blockchain
Failed to fetch description. HTTP Status Code: 404
algoaccess
AlgoAccessThis is to provide a simple client to interact with the AlgoAccess Third-Party API
algoaid
algoaidA collection of useful tools for students taking an introductory course in algorithms and data structures.InstallationpipinstallalgoaidFeaturesTime complexity analysis of functionsGraphsRepresent: [weighted] [un]directed, disjoint-set/union findEasy to input a graphRun basic graph algorithms (DFS, BFS, MST, Dijkstra's and more)Visualise resultsVersatile Min/Max-heap withdecrease/increasekey functionalityModulesTime complexity:analyseGraph class:GraphPriority queues:MinHeap,MaxHeapUsage: Time Complexity AnalysisAnalyse time complexity of a function with a single parameter:1. Importfromalgoaidimportanalyse2. Define a Functiondeff(n):j=1whilej*j<n:j+=13. Analyseanalyse(f)Example ResultUsage: GraphsConstruct various types of graphs and run a selection of popular graph algorithms:1. ImportfromalgoaidimportGraph2. Declare the Graph (each line represents an edge)edges="""0..2 60..1 10..5 2...2..5 4"""Syntax:Undirected:[node1]..[node2] [weight (optional)]Directed:[from]..[to] [weight (optional)]Disjoint-set:[parent]..[child]3. Construct the Graph# construct undirected graphg=Graph(edges,type=Graph.GraphType.GRAPH)# construct directed graphg=Graph(edges,type=Graph.GraphType.DI_GRAPH)# construct disjoint setg=Graph(edges,type=Graph.GraphType.DISJOINT_SET)4. Display the Graphg.display("My Graph")5. Run Algorithms# Run DFS from node 0g.dfs_tree("0")# Run BFS from node 0g.bfs_tree("0")# Compute MST (requires a weighted undirected graph)g.mst_tree()# Run Dijkstra's algorithm from node 0 (requires a weighted graph)g.dijkstra_tree("0")# Topological sorting (requires a directed graph)g.topological_sort()# Find with path compression (requires disjoint-set)g.show_find("6")# Union (requires disjoint-set)g.show_union("9","11")Example Results
algo-amm
Automated Prediction Market Maker on AlgorandNOTE: This code is not audited and should not be used in production environment.SummaryAlgo AMM is an automated prediction market maker on Algorand that allows users to trade on the outcomes of events, and follow the odds to garner accurate insights about the future.Our target market is traders, speculators and investors who are interested in taking advantage of the predictive power of markets. The user problem we are addressing is the difficulty in predicting outcomes of events accurately and reliably. Our solution is an automated prediction market maker that allows users to trade on the outcomes of events, and follow the odds to garner accurate insights about the future. We provide liquidity for users to buy or sell Voting Shares, which can be redeemed for 1 unit of the stable asset if the outcome is resolved as correct, and become worthless if it’s incorrect.The goal is, by harnessing the power of free markets to aggregate collective knowledge and provide the general public with an unbiased source of truth in regards to the likelihood of certain significant events happening in the future.Project Slides DeckWe wrote contract for Prediction Market Constant Function Automated Market Maker with the help ofPyTealandPy-algorand-sdk.The front end application is written with react and vite.The repository for the front-endAlgoAMM LiveFoundersPavel Fedotov:LinkedInTwitterGitHubGrigore Gabriel Trifan:LinkedInTwitterGitHubOverviewConstant Function Automated Market Maker (AMM) contract provides configuration options and creates a market for an event that has a binary outcome.Liquidity Pool provides a foundation for users to purchase and redeem spawned tokens once the event has been resolved. The Liquidity Pool supports a constant reserve ratio for stable price discovery and protection from liquidity drain. The liquidity provided allows to spawn two tokens in equal amount in 25%/25% proportion of the liquidity supplied.The purchase price for each token is determined by equation: x + y = k. Where x is the amount of A tokens in the AMM, y is the amount of B tokens in the AMM.Once the event has occurred the price for one token should resolve to 1, while 0 for another.Liquidity Shares and Voting Shares can only be released after the creator of the contract moderated the outcome.As a prediction market maker on Algorand, our primary role would be to provide liquidity to users who are looking to buy and sell prediction market tokens on the platform. This involves creating markets for events or outcomes, such as the winner of a political election or the outcome of a sports game, and setting prices for these tokens based on supply and demand.RequirementsVscodeor another IDEPython 3PIP Package ManagerPy-algorand-sdkPyTEALAlgorandPurestake node api keyPyTeal AMM Smart ContractPyTeal contracts are written in Python using any editor of your choice.compileProgrammethod produces the TEAL code which is then compiled into bytecode and deployed to the blockchain.The PyTeal smart contract consists of two programs. These are called the approval program and the clear programs. In PyTeal both of these programs are generally created in the same Python file.Theapproval_programis responsible for processing all application calls to the contract, with the exception of the clear call. The program is responsible for implementing most of the logic of an application.Theclear_programis used to handle accounts using the clear call to remove the smart contract from their balance record.Inamm.pywe keep the high-level logic of the contract,helpers.pycontains lower level methods andconfig.pykeeps track of global variable and key configuration variables.Useful ResourcesPyTEALTestnet DispensaryAlgorand DispenserPy-algorand-sdkAlgoExplorerAlgorand: Build with PythonAlgorand: Smart contract detailsAmm Demo contractCreating Stateful Algorand Smart Contracts in Python with PyTealHow to publish PIP packageAlgorand Ecosystem Algo AMM pageHow To Use unittest to Write a Test Case for a Function in PythonMore Information about DspytDspyt HomepageDspyt GitHub DAO Page
algoands
My first Python package with a slightly longer description
algoapi
AlgoAPiALgoAPI is a Python library for dealing with executing trading using FXCM ForexConnect API.Installationgit clone https://github.com/KrishnaInvestment/algoapi.git cd algoapi pip3 install .Alternatively you can install the package using PIPpip install algoapiUsageLoginfromalgoapi.fxconnectimportFXCMClient# Login to the APIfx=FXCMClient(USER_ID="YOUR_ID",USER_PASSWORD="YOUR_PASSWORD",URL="http://www.fxcorporate.com/Hosts.jsp",CONNECTION="Demo",).login()#You can add all the parameters of login in the link below as per the requirements#to avoid entering the information each time maintain .env with variablesUSER_ID='YOUR_ID'USER_PASSWORD='YOUR_PASSWORD'URL='http://www.fxcorporate.com/Hosts.jsp'CONNECTION='Real'You can check other inputs for loginExecuting a tradefromalgoapi.fxconnect.tradeimportOpenPosition#You can place two types of order here at market price and at entry price#Trading at entry priceop=OpenPosition(fx)order_id=op.at_entry_price(INSTRUMENT="EUR/USD",TRANSACTION_TYPE="B",LOTS=1,RATE=rate,RATE_STOP=40,TRAIL_STEP_STOP=30,RATE_LIMIT=30,)#At entry price the rate must be added and stop/target are based on the pip value#Instrument, TRANSACTION_TYPE, LOTS, RATE are required variable for executing entry trade#However other variable are optional# The entry price returns the order_id#Trading at market pricetrade_id,order_id=op.at_market_price(INSTRUMENT="EUR/USD",TRANSACTION_TYPE="B",LOTS=1)# You can add stop loss , limit , trail_step_stop as per the requirementClosing a Tradefromalgoapi.fxconnect.tradeimportClosePositioncp=ClosePosition(fx)#Closing a position with the trade idcp.close_position(trade_id)#Close all Open positioncp.close_all_open_position()Updating a Tradefromalgoapi.fxconnect.tradeimportUpdatePositionup=ClosePosition(fx)#Update Limit priceup.update_limit_price(limit_price,trade_id)#Limit price should be the actual priceup.update_limit_price(1.11875,'75134317')#Note all the ID's (trade_id, order_id are in string format)#Update Stop priceup.update_stop_price(stop_price,trade_id,trail_step)#Stop price should be the actual priceup.update_stop_price(1.11575,'75134317',trail_step)#Trail step moves the stop limit as the price fluctuates in our desire directionDeleting an Orderfromalgoapi.fxconnect.tradeimportDeleteOrderdo=DeleteOrder(fx)#Closing a position with the trade iddo.delete_order(order_id)Fetching Trade and Order Informationfromalgoapi.fxconnect.utilsimportget_pandas_tabledf=get_pandas_table(fx,table_type)#Table types like TRADES, OFFERS, ORDERS, CLOSED_POSITION, ACCOUNTS etc#It will list all the information of that particular tabledf_orders=get_pandas_table(fx,'TRADES')#You can filter the tables based on the column valuedf_filter_column=get_pandas_table(fx,table_type,key='Columns_name',value='column_value')df_order_id_filter=get_pandas_table(fx,'ORDERS',key='order_id',value='75134317')#To get the latest price of the instrumentfromforexconnectimportCommonoffer=Common.get_offer(fx,"EUR/USD")# depending on the long and short position you can get theask=offer.askbid=offer.bidContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.LicenseMIT
algo-app-dev
Algo App DevUtilities to help in the development of PyTeal contracts for Algorand. Documentation:https://gmcgoldr.github.io/algo-app-dev/.Installationpipinstall-Ualgo-app-devPre-requisitsIn this documentation, it is assumed that you are running an Algorand node in an Ubuntu environment.You can install Algorand with following these commands:sudoapt-getupdate sudoapt-getinstall-ygnupg2curlsoftware-properties-common curl-Ohttps://releases.algorand.com/key.pub sudoapt-keyaddkey.pub rm-fkey.pub sudoadd-apt-repository"deb [arch=amd64] https://releases.algorand.com/deb/ stable main"sudoapt-getupdate sudoapt-getinstallalgorandCommand line utilitiesThe following command line utilities are installed with the package. They are used to work with a local private network and node daemons for development:aad-make-node: this command can be used to setup a private networkaad-run-node: this command can be used to start or stop node daemonsModulesThe following is a brief overview of the package's functionality and organization:clientsTheclientsmodule contains a few utilities to help manage thealgodandkmddaemons clients.There are also utilities to help extract key-value information from global and local state queries.transactionsThetransactionsmodule contains utilities to help create and manage transactions.appsTheappsmodule contains utilities and classes to help construct and manage stateful applications (stateful smart contracts). This is the core of the package.Most the app development work utilizes two classes: theStateandAppBuilderclasses. These help reduce the amount of boiler-plate needed to create functionalpytealexpressions.Manually managing the app's state is very error prone. The interface provided byStateand its derivedStateGlobal,StateGlobalExternal,StateLocalandStateLocalExternalcan reduce these errors.Here is an example of a very simple app with a global counter. Every time a (no-op) call is made with the argument "count", it increments the counter.importpytealastlfromalgosdk.utilimportalgos_to_microalgosfromalgoappdevimportapps,clients,dryruns,transactions,utils# build the clientsalgod_client=clients.build_algod_local_client(NODE_PATH)kmd_client=clients.build_kmd_local_client(NODE_PATH)# fund an account on the private net which can be used to transactfunded_account,txid=transactions.fund_from_genesis(algod_client,kmd_client,algos_to_microalgos(1))# wait for the funding to go throughtransactions.get_confirmed_transaction(algod_client,txid,WAIT_ROUNDS)# define the state: a single global counter which defaults to 0state=apps.StateGlobal([apps.State.KeyInfo("counter",tl.Int,tl.Int(0))])# define the logic: invoking with the argument "count" increments the counterapp_builder=apps.AppBuilder(invocations={"count":tl.Seq(state.set("counter",state.get("counter")+tl.Int(1)),tl.Return(tl.Int(1)),),},global_state=state,)# deploy the applicationtxn=app_builder.create_txn(algod_client,funded_account.address,algod_client.suggested_params())txid=algod_client.send_transaction(txn.sign(funded_account.key))# the app id and address can be derived from the transaction outputtxn_info=transactions.get_confirmed_transaction(algod_client,txid,WAIT_ROUNDS)app_meta=utils.AppMeta.from_result(txn_info)print(app_meta)The resultingapp_metaobject:AppMeta(app_id=1,address='...')dryrunsThedryrunsmodule contains utilities to help send dry runs to a node, and parse the results.Here is how thedryrunsutilities could be used to test the contract:# build a dryrun request containing the entire state needed to call the appresult=algod_client.dryrun(dryruns.AppCallCtx()# use the app's programs and schema.with_app(app_builder.build_application(algod_client,1))# add a transaction calling the app with the given arg.with_txn_call(args=[b"count"]).build_request())foritemindryruns.get_trace(result):print(item)fordeltaindryruns.get_global_deltas(result):print(delta)The last few lines of the stack trace should resemble:55 :: app_global_get :: [b'counter' , 0 ] 56 :: intc_0 // 1 :: [b'counter' , 0 , 1 ] 57 :: + :: [b'counter' , 1 ] 58 :: app_global_put :: [] 59 :: intc_0 // 1 :: [1 ] 81 :: return :: [1 ]The resulting state delta:KeyDelta(key=b'counter',value=1)TestingNOTE: in order to use the testing functionality, you must install thedevdependencies. This is done with the command:pipinstall-Ualgo-app-dev[dev]Start the daemons before testing, and optionally stop them after the tests run.The tests make calls to the node, which is slow. There are two mitigations for this: using the dev node, and using thepytest-xdistplugin for pytest to parallelize the test.The dev node creates a new block for every transaction, meaning that there is no need to wait for consensus. Whereas testing withprivate_devcan take a 10s of seconds, testing withpivatetakes 10s of minutes.The flag-n Xcan be used to split the tests into that many parallel processes.# create a new network (overwrites an existing private dev node)aad-make-nodenets/private_dev-f# start the node daemonsaad-run-nodenets/private_devstart# run the tests in 4 processes with the given node dirAAD_NODE_DIR=nets/private_dev/Primarypytest-n4tests/# stop the node daemonsaad-run-nodenets/private_devstopPyTest environmentThe modulealgoappdev.testingcontains somepytestfixtures that are widely applicable. If you want to make those fixtures available to all your tests, you can create a fileconftest.pyin your test root directory and write to it:# conftest.pyfromalgoappdev.testingimport*It also exposes two variables which can be configured through environment variables:NODE_DIR: this should be the path to the node data directoryWAIT_ROUNDS: this should be set to the maximum number of rounds to await transaction confirmations.Both are read from the environment variable with corresponding name prefixed withAAD_.NODE_DIRdefaults to the private dev node data path. If your system is configured differently, you will need to set this accordingly.WAIT_ROUNDSdefaults to 1, because when interacting with a dev node transactions are immediately committed. If doing integration tests with a non-dev node, this should be increased to give time for transactions to complete before moving onto another test.
algoauditor
Lethai LibraryThe library, named "lethai", provides a standard library to interact with the services provided by Lethical.ai.Getting StartedGenerate API KeySteps to followCreate an account on Lethical.aiClick on API Keys on the side panelClick "add key" buttonProvide tags to the key if needed (They will help you identify and filter the keys for your reference)Choose the access level for the keyClick on generateA key will be displayed on the screen please copy it and store it safely for future usage.NOTE: The key will only be shown once. This is for security purposesInstallationpip3 install lethaiUsageThe various features provided by our library include the following:Discrimination detection -NLG models
algo-auto-ml
No description available on PyPI.
algobacktest
Algo Backtest PackageApplying significance test to backtestingGet historical data from Yahoo FinanceUse default technical analysis strategies for practiceApply significance test to backtest results with Monte Carlo simulationsQuick usageimport algobacktest.Backtest as algobt bt = algobt.Test() bt.prices = algobt.getprice('AAPL') bt.positions = algobt.getsma(bt.prices) bt.run() bt.plot_significance() print(f'Backtested strategy return: {round(bt.strategy_return,2)}')
algobase
algobaseA type-safe Python library for interacting with assets on Algorand.💡 Motivationalgobaseaims to provide a first-class developer experience for creating, managing, and querying Algorand ASAs.It's designed to be easy to use, extensible, and compliant withAlgorand ARCstandards.algobase usesPydanticto validate and serialise data, making it easier to integrate with other tools in the ecosystem likeFastAPIandSQLModel.⚠️ WarningThis library is in the early stages of development.The API is not stable and the code has not been audited.📖 Documentationalgobase docs🚀 FeaturesDevelopment featuresSupportsPython 3.11and higher.Poetryas the dependencies manager. See configuration inpyproject.toml.Automatic codestyle withruff,pydocstyleandpyupgrade.Ready-to-usepre-commithooks with code-formatting.Type checks withmypy; security checks withsafetyandbanditTesting withpytest.Ready-to-use.editorconfig,.dockerignore, and.gitignore. You don't have to worry about those things.Deployment featuresGitHubintegration: issue and PR templates.Github Actionswith predefinedbuild workflowas the default CI/CD.Everything is already set up for security checks, codestyle checks, code formatting, testing, linting, docker builds, etc withMakefile. More details inmakefile-usage.Dockerfilefor your package.Always up-to-date dependencies with@dependabot. You will onlyenable it.Automatic drafts of new releases withRelease Drafter. You may see the list of labels inrelease-drafter.yml. Works perfectly withSemantic Versionsspecification.Open source community featuresReady-to-usePull Requests templatesand severalIssue templates.Files such as:LICENSE,CONTRIBUTING.md,CODE_OF_CONDUCT.md, andSECURITY.mdare generated automatically.Stale botthat closes abandoned issues after a period of inactivity. (You will onlyneed to setup free plan). Configuration ishere.Semantic Versionsspecification withRelease Drafter.Installationpipinstall-Ualgobaseor install withPoetrypoetryaddalgobaseMakefile usageMakefilecontains a lot of functions for faster development.1. Download and remove PoetryTo download and install Poetry run:makepoetry-downloadTo uninstallmakepoetry-remove2. Install all dependencies and pre-commit hooksInstall requirements:makeinstallPre-commit hooks coulb be installed aftergit initviamakepre-commit-install3. CodestyleAutomatic formatting usesruff.makecodestyle# or use synonymmakeformattingCodestyle checks only, without rewriting files:makecheck-codestyleNote:check-codestyleusesrufflibraries.Update all dev libraries to the latest version using one comandmakeupdate-dev-deps4. Code securitymakecheck-safetyThis command launchesPoetryintegrity checks as well as identifies security issues withSafetyandBandit.makecheck-safety5. Type checksRunmypystatic type checkermakemypy6. Tests with coverage badgesRunpytestmaketest7. All lintersOf course there is a command torulerun all linters in one:makelintthe same as:maketest&&makecheck-codestyle&&makemypy&&makecheck-safety8. Dockermakedocker-buildwhich is equivalent to:makedocker-buildVERSION=latestRemove docker image withmakedocker-removeMore informationabout docker.9. CleanupDelete pycache filesmakepycache-removeRemove package buildmakebuild-removeDelete .DS_STORE filesmakedsstore-removeRemove .mypycachemakemypycache-removeOr to remove all above run:makecleanup📈 ReleasesYou can see the list of available releases on theGitHub Releasespage.We followSemantic Versionsspecification.We useRelease Drafter. As pull requests are merged, a draft release is kept up-to-date listing the changes, ready to publish when you’re ready. With the categories option, you can categorize pull requests in release notes using labels.List of labels and corresponding titlesLabelTitle in Releasesenhancement,feature🚀 Featuresbug,refactoring,bugfix,fix🔧 Fixes & Refactoringbuild,ci,testing📦 Build System & CI/CDbreaking💥 Breaking Changesdocumentation📝 Documentationdependencies⬆️ Dependencies updatesYou can update it inrelease-drafter.yml.GitHub creates thebug,enhancement, anddocumentationlabels for you. Dependabot creates thedependencieslabel. Create the remaining labels on the Issues tab of your GitHub repository, when you need them.📖 Additional ResourcesARC Token Standards Explained for NFT CreatorsAlgorand Requests for Comments (ARCs)🛡 LicenseThis project is licensed under the terms of theApache Software License 2.0license. SeeLICENSEfor more details.📃 Citation@misc{algobase,author={code-alexander},title={A type-safe Python library for interacting with assets on Algorand.},year={2023},publisher={GitHub},journal={GitHub repository},howpublished={\url{https://github.com/code-alexander/algobase}}}CreditsThis project was generated withpython-package-template
algo-base
组件开发基础工具
algo-battle
Algo BattleInstallationBasiert auf Python3, idealerweise in einer virtuellen Umgebung installieren:python3-mvenvvenv .venv/bin/activate pip3installalgo-battleStartenpython3-malgo_battleGUIAnleitungEine ausführliche Anleitung zur Verwendung ist unterAnleitungzu finden.
algobattle-base
Algorithmic BattleThe lab course "Algorithmic Battle" is offered by theComputer Science Theory group of RWTH Aachen Universitysince 2019. This repository contains the necessary code and documentation to set up the lab course yourself.In an Algorithmic Battle, pairs of teams compete against one another in order to solve a problem of your choice, e.g. a problem from the class NP. The teams each design agenerator, that outputs hard-to-solve instances for a given instance size, as well as asolverthat accepts an instance and outputs a solution to it as quickly as possible.The framework is written to be completely language-agnostic regarding the code of thegeneratorand thesolver, as each is wrapped in a docker container that only needs to adhere to an I/O structure of your choice (by default, in the form ofjson-files.)If you are interested in how to use the framework for a lab course of your own, please consult the teaching concept in thedocumentation.Installation and UsageThis project is developed and tested on all major operating systems.Please consult the officialdocumentationfor detailed instructions on installation and usage.Related projectsThis repository only includes the core framework for executing anAlgorithmic Battle. For a selection of concrete problems that you can use to play around with the framework, have a look at thealgobattle-problemsrepository. These are problems that have been posed to students in some form over the past years.While the framework provides all essential tools to host a tournament yourself, e.g. in the form of a lab course, you may be interested in thealgobattle-webproject. Thealgobattle-webproject implements a webframework with which you are able to comfortably manage your students teams and their code, your problem files and their documentation as well as schedule matches to be fought between registered student teams, using thealgobattleAPI.ContributingWe welcome any input on how to make this project accessible to as many people as possible. If you have feedback regarding the usage of the framework, the documentation or would even like to help us out with corrections, new features, or translations, feel free to open an issue or pull request. We have developed this project on the basis of practical experience inside our lab courses, thus some design elements may be unintuitive to you. Feel free to point out anything that appears odd to you.FundingThe development of version4.0.0was funded byStiftung Innovation in der Hochschullehre(ProjectFRFMM-106/2022 Algobattle) and by theDepartment of Computer Science of RWTH Aachen University.
algobattle-problems
No description available on PyPI.
algobin
algobin
algobowl
AlgoBOWLAlgoBOWL is a group project for algorithms courses. Students compete to create heuristics to an NP-hard problem. For more information, see the paper inITiCSE 2019.This is the AlgoBOWL web application, as well as associated tools (e.g., command line interface).Getting StartedThe rest of thisREADMEassumes you're interested in hacking on the AlgoBOWL code, and want to install the web app locally. For other topics of interest, check out thedocs/directory.You'll need a system running Linux and Python 3.8+.Create and activate a virtual environment to install in:$ python3 -m venv venv $ . venv/bin/activateNext, install the app in editable mode::$ pip install -e ".[dev]"Next, copy the sample development config and setup the application::$ cp development.ini.sample development.ini $ gearbox setup-appFinally, you can serve the app::$ gearbox serve --reload --debugHave fun!
algobox
algoboxAlgorithms package for python
algobra
ALGOBRAThis is an algorithmic trading engine used to backtest, model, and develop trading strategies on real time/historic stock data.InstallationRun the following to install:pipinstallalgobraUsagefromalgobraimportengine# Systems check to see if your machine can utilitize native performance improvements.engine.optimize()# See engine informationprint(engine.info())Developing AlgobraTo install algobra, along with the tools you need to develop and run tests, run the following in your virtualenv.pipinstall-e.[dev]ConceptsTrading System DevelopmentTrading System DesignTrading System EnvironmentTime Series AnalysisOptimizationPerformance MeasurementsRisk ManagementTrading Strategy ImplementationExecutionConfiguring DBmysql -u root -pmysql> CREATE DATABASE securities_master; mysql> USE securities_master; mysql> CREATE USER ’sec_user’@’localhost’ IDENTIFIED BY ’password’; mysql> GRANT ALL PRIVILEGES ON securities_master.* TO ’sec_user’@’localhost’; mysql> FLUSH PRIVILEGES;Referenceschemas.sqlfor the commands to create needed tables
algobrew
No description available on PyPI.
algobroker
Algobroker is an interface to trading and events
algo-bus-sdk
No description available on PyPI.
algocash-sdk
This is a Algocash API # noqa: E501
algocli
algo-CLIPrint common algorithms to the command lineIndexInstallationDescriptionHow to useOptionsSupported LanguagesSupported AlgorithmsExamplesAvailable ThemesContributionsCreditsInstallationUse pip:$ pip install algocliManual installation:$ git clone https://github.com/emanuel2718/algocli.git $ cd algocli $ python setup.py installDescriptionalgocliis a command-line tool that lets users print common algorithms directly into the terminal. Why open a browser search through countless articles about how to doinsertionsort in pythonwhen you can just typealgocli python insertionsortin the terminal.$ algocli [INPUT ...] [OPTIONS]How to useOptions:-h, --help show this help message and exit -v, --version displays the current version of algcli --list-colors print list of available colorschemes --list-lang print list of supported languages --list-algo print list of supported algorithms -c [COLORSCHEME], --color [COLORSCHEME] colorized outputSupported Language:Correct language query (shown on the left) must be given foralgoclito understandactionscript Actionscript ada Ada algol68 ALGOL68 applescript Applescript autohotkey Autohotkey awk AWK c C cpp C++ csharp C# d D delphi Delphi fsharp F# eiffel Eiffel fortran Fortran go Go haskell Haskell objc Objective-C java Java javascript Javascript lua Lua matlab Matlab ocaml Ocaml pascal Pascal perl Perl php PHP powershell PowerShell python Python ruby Ruby rust Rust scala Scala swift SwiftSupported Algorithms:Correct language query (shown on the left) must be given foralgoclito understandavltrees AVL Trees b64 Decode Base64 data beadsort Bead Sort algorithm binarysearch Binary Search algorithm bogosort Bogo Sort algorithm bubblesort Bubble Sort algorithm caesarcipher Caesar Cipher cocktailsort Cocktail Sort algorithm combsort Comb Sort algorithm countingsort Counting Sort algorithm cyclesort Cycle Sort algorithm damm Damm algorithm dijkstra Dijkstra algorithm e Calculate the value of e eulermethod Euler method evolutionary Evolutionary algorithm factorial Calculate factorials factorions Calculate factorions fft Fast Fourier Transforms fib Fibonacci Sequence fibnstep Fibonacci N-step Number Sequence fileexists Check if a given file exists or not fizzbuzz FizzBuzz floydwarshall Floy Warshall algorithm gnomesort Gnome Sort algorithm hammingnumbers Hamming numbers heapsort Heap Sort algorithm huffman Huffman coding insertionsort Insertion Sort algorithm isaac ISAAC Cipher knapsack Knapsack Problem 0-1 knapsackbound Knapsack Problem Bounded knapsackcont Knapsack Problem Continous knapsackunbound Knapsack Problem Unbounded kolakoski Kolakoski Sequence mandelbrot Mandelbrot Set mazegen Maze Generation mazesolve Maze Solving md4 How to use MD4 md5 How to use MD5 md5imp MD5 Algorithm implementation mergesort Merge Sort algorithm nqueen N-Queens Problem pancakesort Pancake Sort algorithm patiencesort Patience Sort algorithm permutationsort Permutation Sort algorithm quickselect Quickselect Algorithm quicksort Quick Sort algorithm radixsort Radix Sort algorithm recaman Recaman Sequence regex Simple Regular Expressions rot13 Rot-13 Algorithm rsa RSA code selectionsort Selection Sort algorithm sexyprime Sexy primes sha1 SHA-1 Algorithm sha256 SHA-256 Algorithm shellsort Shell Sort algorithm sieve Sieve of Eratosthenes Algorithm sleepsort Sleep Sort algorithm stoogesort Stooge Sort algorithm strandsort Strand Sort algorithm subcipher Substitution Cipher toposort Topological Sort AlgorithmExamplesNOTE: The order of the options do not matter, but for the sake of simplicity all the examples will be shown with the algorithm first followed by the language. The following are equivalent:$ algocli radixsort cpp $ algocli cpp radixsortList of supported languages$ algocli --list-langList of supported algorithms$ algocli --list-algoInsertion Sort with Pythonwithoutcolor$ algocli insertionsort pythonInsertion Sort with Pythonwithcolor$ algocli insertionsort python -cInsertion Sort with Pythonwithmaterial colorscheme$ algocli insertionsort python -c materialRadix Sort with C++$ algocli radixsort cppFibonacci Sequence calculation with Java$ algocli fib javaAvailable ThemesList of available ThemesContributionsinsert contributions message hereCreditsThis project couldn't have been possible withoutRosetta Code, which is a wonderful resource for any programmer looking to learn about how to do different things in almost any programming language in existence.All credits go to Rosetta Code and all the contributors of the site.
algo-cmd
No description available on PyPI.
algocoin
# AlgoCoin Algorithmic Trading Bitcoin.# UPDATE: MASTER is working for market orders ONLY on gemini. Everything else is still in beta until limit order support is done[![Version](https://img.shields.io/badge/version-0.0.2-lightgrey.svg)](https://img.shields.io/badge/version-0.0.2-lightgrey.svg) [![Build Status](https://travis-ci.org/timkpaine/algo-coin.svg?branch=master)](https://travis-ci.org/timkpaine/algo-coin) [![Coverage](https://codecov.io/gh/timkpaine/algo-coin/coverage.svg?branch=master&token=JGqz8ChQxd)](https://codecov.io/gh/timkpaine/algo-coin) [![Gitter](https://img.shields.io/gitter/room/nwjs/nw.js.svg)](https://gitter.im/algo-coin/Lobby) [![Waffle.io](https://badge.waffle.io/timkpaine/algo-coin.png?label=ready&title=Ready)](https://waffle.io/timkpaine/algo-coin?utm_source=badge) [![BCH compliance](https://bettercodehub.com/edge/badge/timkpaine/algo-coin?branch=master)](https://bettercodehub.com/) [![Beerpay](https://beerpay.io/timkpaine/algo-coin/badge.svg?style=flat)](https://beerpay.io/timkpaine/algo-coin) [![License](https://img.shields.io/github/license/timkpaine/algo-coin.svg)]() [![PyPI](https://img.shields.io/pypi/v/algocoin.svg)]() [![Site](https://img.shields.io/badge/Site–grey.svg?colorB=FFFFFF)](http://paine.nyc/algo-coin)## Overview Lightweight, extensible program for algorithmically trading cryptocurrencies across multiple exchanges.### System Architecture AlgoCoin is an event based trading system written in python. It comes with support for live trading across (and between) multiple exchanges, fully integrated backtesting support, slippage and transaction cost modeling, and robust reporting and risk mitigation through manual and programatic algorithm controls.### Algorithm Like Zipline, the inspriation for this system, AlgoCoin exposes a single algorithm class which is utilized for both live trading and backtesting. The algorithm class is simple enough to write and test algorithms quickly, but extensible enough to allow for complex slippage and transaction cost modeling, as well as mid- and post- trade analysis.### Markets Eventual coverage:BitstampBitfinexCEXGDAXGeminiHitBTCItBitKrakenLakeBTCPoloniex#### Market Data (Websocket) [![GDAX](https://img.shields.io/badge/GDAX-OK-brightgreen.svg)](https://img.shields.io/badge/GDAX-OK-brightgreen.svg) [![GEMINI](https://img.shields.io/badge/Gemini-OK-brightgreen.svg)](https://img.shields.io/badge/Gemini-OK-brightgreen.svg) [![ITBIT](https://img.shields.io/badge/ItBit-ERR-brightred.svg)](https://img.shields.io/badge/ItBit-ERR-brightred.svg) [![KRAKEN](https://img.shields.io/badge/Kraken-ERR-brightred.svg)](https://img.shields.io/badge/Kraken-ERR-brightred.svg) [![POLONIEX](https://img.shields.io/badge/Poloniex-ERR-brightred.svg)](https://img.shields.io/badge/Poloniex-ERR-brightred.svg)#### Order Entry (REST) [![GDAX](https://img.shields.io/badge/GDAX-OK-brightgreen.svg)](https://img.shields.io/badge/GDAX-OK-brightgreen.svg) [![GEMINI](https://img.shields.io/badge/Gemini-OK-brightgreen.svg)](https://img.shields.io/badge/Gemini-OK-brightgreen.svg) [![ITBIT](https://img.shields.io/badge/ItBit-ERR-brightred.svg)](https://img.shields.io/badge/ItBit-ERR-brightred.svg) [![KRAKEN](https://img.shields.io/badge/Kraken-ERR-brightred.svg)](https://img.shields.io/badge/Kraken-ERR-brightred.svg) [![POLONIEX](https://img.shields.io/badge/Poloniex-ERR-brightred.svg)](https://img.shields.io/badge/Poloniex-ERR-brightred.svg)—## Getting Started### Installation Install the library from source:`python python setup.py install `### API Keys You should creat API keys for exchanges you wish to trade on. For this example, we will assume a GDAX sandbox account with trading enabled. I usually put my keys in a set of shell scripts that are gitignored, so I don’t post anything by accident. My scripts look something like:`bash exportGDAX_API_KEY=...exportGDAX_API_SECRET=...exportGDAX_API_PASS=...`Prior to running, I then source the keys I need.Let’s make sure everything worked out by running a sample strategy on the GDAX sandbox exchange:`bash python3-malgocoin--sandbox`### Writing an algorithm### Backtesting#### Getting Data### Sandboxes### Live Trading—## Contributing—
algo-crawler
Algo CrawlerUsageInstall Packagepipinstallalgo_crawlerCrawl Solutionpython3-malgo_crawler-sBJ-ukoosaga# {'user_id': 'koosaga', 'problem_codes': ['1000', '1001' ...]Crawl Problempython3-malgo_crawler-sBJ-p1000# {'code': 'LC_1', 'level': '1', 'link': 'https://leetcode.com/problems/two-sum', 'title': 'Two Sum'}Developer SettingDeveloper settingpipinstall-rrequirements.txt pre-commitinstallTestpython3-malgo_crawler.test
algodata
algodataA python library for interacting with financial timeseries for algorithmic trading.
algo-db-controller
No description available on PyPI.
algodocs
AlgoDocs API Python ClientThis client API provides all required Python bindings for communicating withAlgoDocs REST API.DocumentationPlease visitAlgoDocs API Documentationfor a detailed documentation of all API methods with their parameters and expected responses.InstallationUsing pip:Note:algodocs python client was only tested with Python 3.pip install algodocsORClone current repository or download as zip file and unzip its contents, then change directory to the root folder and then install.git clone https://github.com/algodocs/algodocs-pythoncd algodocs-pythonpython setup.py installFor development:pip install -r requirements.txtUsageTo use AlgoDocs Python Client, you need to register atAlgoDocsand get your API Key fromhereimportalgodocsemail_address="your_email_addres_you_registered_with_at_AlgoDocs"key="your_secret_api_key"client=algodocs.AlgoDocsClient(email_address,key)Test connection and authenticate as follows:result=client.me()print(result)#this will print your name, surname and email addressGet all extractors in your AlgoDocs account:result=client.getExtractors()print(result)Get all folders in your AlgoDocs account:result=client.getFolders()print(result)Upload local file using its full path:file_path="full_path_to_your_file.pdf"#accepted file types: PDF, PNG, JPG/JPEG, WORD (.doc, .docx), EXCEL (.xls, .xlsx)extractor_id="your_extractor_id"#use extractor id that you got from client.getExtractors()folder_id="your_folder_id"#use folder id that you got from client.getFolders()result=client.uploadDocumentLocal(extractor_id,folder_id,file_path)print(result)Upload file in base64 format:withopen(file_path,"rb")asfile_contents:file_base64=base64.b64encode(file_contents.read())result=client.uploadDocumentBase64(extractor_id,folder_id,file_base64,os.path.basename(file_path))print(result)Upload file using its publicly accessible url:url="https://api.algodocs.com/content/SampleInvoice.pdf"result=client.uploadDocumentUrl(extractor_id,folder_id,url)print(result)Get extracted data of a single document using its id:document_id="your_document_id"#this document_id comes from result['id'] above, so use your actual document_id that you received in response dictionary object after importing the document to AlgoDocs...result=client.getExtractedDataByDocumentID(document_id)print(result)Get extracted data of multiple documents using extractor id:#`folder_id`, `limit` and `date` parameters are optionallimit=10date=(datetime.now()+timedelta(days=-10)).isoformat()# i.e. get extracted data from documents that were uploaded during last 10 daysresult=client.getExtractedDataByExtractorID(extractor_id,folder_id,limit,date)print(result)ContributingBug reports and pull requests are welcome onGitHub.LicenseThe library is available as open source under the terms of theMIT License.MIT LicenseCopyright (c) 2022 Algosoft Ltd.Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
algodojo
dojoAlgo Dojo is a Python library for program traders are convenient to use our lib for program tradingInstallationUse the package managerpipto install algodojo.pipinstallalgodojoUsageimportalgodojoContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.License
algoesup
AlgoesupThis small library was written to support the writing ofalgorithmic essays, but can be used independently of that purpose. The library provides auxiliary functions that make it easier to:write unit tests for functionsmeasure and plot run-times for best, average and worst case inputsuse linters within Jupyter Notebook environments.Guidance on how to use the library ishere.To install in the global Python environment, open a terminal or PowerShell, and enterpipinstallalgoesupTo install in a virtual environment, activate it before entering the command above.The library supports theruffandallowedlinters, and thepytypetype checker. You have to install them explicitly if you want to use them from within a notebook:pipinstallruffallowedpytypeNote thatpytypeis not available for Windows.Licencealgoesupis Copyright © 2023–2024 by The Open University, UK. The code is licensed under aBSD 3-clause licence. The documentation is licensed under aCreative Commons Attribution 4.0 International Licence
algofunc
This library consists of different sorting and searching algorithms to make it easier to use these algorithms in your code without having to type them out yourself.Library includes the following functions:binary_search( array, target )linear_search( array, target )fibonacci_search( array, target )jump_search( array, target )linear_search( array, target )ternary_search( array, target )bitonic_sort( array )bucket_sort( array )bubble_sort( array )cocktail_sort( array )comb_sort( array )counting_sort( array )cycle_sort( array )gnome_sort( array )heap_sort( array )merge_sort( array )odd_even_sort( array )pancake_sort( array )quick_sort( array )radix_sort( array )selection_sort( array )shell_sort( array )timsort( array )
algogd
UNKNOWN
algo-gen
AlgoGenRequirements
algogene
Failed to fetch description. HTTP Status Code: 404
algograd
No description available on PyPI.
algoGUI
No description available on PyPI.
algogym
simfin
algoholic
UNKNOWN
algoind
ALGOIND: A Technical Indicators collection in Python.🔎 What is italgoindis python3 package that contains technical indicators for backtesting and for implementing trading strategies in Python3.😃 Who I amMy name is Matteo, a 21 years old FinTech student.I created this library for my personal usage and I decided publish it because it think can be useful for someone.👋 You can find mycontacts here.The source code is currently hosted on GitHub at:https://github.com/matteoincremona/algoind/Thanks toInvestopedia.comthat provided me a vast amount of knowledge to be able to create this library.💻 How to Install it# condacondainstall-cconda-forgealgoind# PyPIpipinstallalgoind📈 FeaturesThis is the list of all the indicatorsalgoindcontains:Single Moving Average (SMA)Esponential Moving Average (EMA)Average True Range (ATR)Relative Strenght Index (RSI)Upper Bollinger Bands (BBU)Lower Bollinger Bands (BBL)Mid Bollinger Bands (BBM)Moving Average Convergence Divergence (MACD)Moving Average Convergence Divergence Signal (MACDsignal)✅ Example: How to use it# After the installation of the package:importalgoind fromalgoindimportindicatorsasind# Let's try SMA: what should we know about it?help(ind.SMA)# Let's try SMA that takes, for example:# - The close prices of a df: "df.Close"# - The period for the calculation of the SMA: "20"SMA20=ind.SMA(df.Close,20)# To see the values of the indicator:SMA20⚙️ Discussion and DevelopmentI will be very enthusiastic if somebody would like to help me with this project.Contact meif you have anyproblemor if you want me to addnew indicators.Thank you.
algoisto
usecomming soon
algojig
No description available on PyPI.
algokit
The Algorand AlgoKit CLI is the one-stop shop tool for developers building on theAlgorand network.AlgoKit gets developers of all levels up and running with a familiar, fun and productive development environment in minutes. The goal of AlgoKit is to help developers build and launch secure, automated production-ready applications rapidly.Install AlgoKit|Quick Start Tutorial|DocumentationWhat is AlgoKit?AlgoKit compromises of a number of components that make it the one-stop shop tool for developers building on theAlgorand network.AlgoKit can help youlearn,developandoperateAlgorand solutions. It consists ofa number of repositories, including this one.LearnThere are many learning resources on theAlgorand Developer Portaland theAlgoKit landing pagehas a range of links to more learning materials. In particular, check out thequick start tutorialand theAlgoKit detailed docs page.If you need help you can access both theAlgorand Discord(pro-tip: check out the algokit channel!) and theAlgorand Forum.We have also developed anAlgoKit video series.DevelopAlgoKit helps you develop Algorand solutions:Interaction: AlgoKit exposes a number of interaction methods, namely:AlgoKit CLI: A Command Line Interface (CLI) so you can quickly access AlgoKit capabilitiesVS Code: All AlgoKit project templates include VS Code configurations so you have a smooth out-of-the-box development experience using VS CodeDappflow: AlgoKit has integrations with Dappflow; a web-based user interface that let's you visualise an Algorand network and deploy and call smart contracts via a graphical user interfaceGetting Started: AlgoKit helps you get started quickly when building new solutions:AlgoKit Templates: Template libraries to get you started faster and quickly set up a productive dev experienceDevelopment: AlgoKit provides SDKs, tools and libraries that help you quickly and effectively build high quality Algorand solutions:AlgoKit Utils(Python|TypeScript): A set of utility libraries so you can develop, test, build and deploy Algorand solutions quickly and easilyalgosdk(Python|TypeScript) - The core Algorand SDK providing Algorand protocol API calls, which AlgoKit Utils wraps, but still exposes for advanced scenariosBeaker: A productive Python framework for building Smart Contracts on Algorand.PyTEAL: The Python language bindings for Algorand Smart Contracts, which Beaker wrapsTEAL: Transaction Execution Approval Language (TEAL) is the assembly-like language interpreted by the Algorand Virtual Machine (AVM) running within an Algorand node, which Beaker exportsAlgoKit LocalNet: A local isolated Algorand network so you can simulate real transactions and workloads on your computerOperateAlgoKit can help you deploy and operate Algorand solutions.AlgoKit comes with out-of-the-boxContinuous Integration / Continuous Deployment (CI/CD) templatesthat help you rapidly set up best-practice software delivery processes that ensure you build quality in and have a solution that can evolveWhat can AlgoKit help me do?The set of capabilities supported by AlgoKit will evolve over time, but currently includes:Quickly run, explore and interact with an isolated local Algorand network (LocalNet)Building, testing, deploying and callingAlgorand PyTEAL/Beakersmart contractsFor a user guide and guidance on how to use AlgoKit, please refer to thedocs.Future capabilities are likely to include:Quickly deploystandardised, audited smart contractsBuilding and deploying Algorand dAppsIs this for me?The target audience for this tool is software developers building applications on the Algorand network. A working knowledge of using a command line interfaces and experience using the supported programming languages is assumed.How can I contribute?This is an open source project managed by the Algorand Foundation. See thecontributing pageto learn about making improvements to the CLI tool itself, including developer setup instructions.InstallPrerequisitesThe key required dependency is Python 3.10+, but some of the installation options below will install that for you.AlgoKit also has some runtime dependencies that also need to be available for particular commands.NoteYou can still install and use AlgoKit without these dependencies and AlgoKit will tell you if you are missing one for a given command.Git - Git is used when creating and updating projects from templatesDocker - Docker Compose (and by association, Docker) is used to run the AlgoKit LocalNet environment, we require Docker Compose 2.5.0+Cross-platform installationAlgoKit can be installed using OS specific package managers, or using the python toolpipxsee below for specific installation instructions.WindowsMacLinuxpipxInstall AlgoKit on WindowsNoteThis method will install the most recent python3 versionvia winget. If you already have python 3.10+ installed, you mayprefer to use pipx directly insteadso you can control the python version used.Ensure prerequisites are installedGit(orwinget install git.git)Docker(orwinget install docker.dockerdesktop)NoteSeeour LocalNet documentationfor more tips on installing Docker on WindowsInstall using WinGetInstall python:winget install python.python.3.11Restart the terminal to ensure Python and pip are available on the pathNoteWindows has a feature calledApp Execution Aliasesthat provides redirects for the Python command that guide users to the Windows Store. Unfortunately these aliases can prevent normal execution of Python if Python is installed via other means, to disable them search forManage app execution aliasesfrom the start menu, and then turn off entries listed asApp Installer python.exeorApp Installer python3.exe.Install pipx:pip install --user pipx python -m pipx ensurepathRestart the terminal to ensure pipx is available on the pathInstall AlgoKit via pipx:pipx install algokitRestart the terminal to ensure AlgoKit is available on the pathVerify installationMaintenanceSome useful commands for updating or removing AlgoKit in the future.To update AlgoKit:pipx upgrade algokitTo remove AlgoKit:pipx uninstall algokitInstall AlgoKit on MacNoteThis method will install Python 3.10 as a dependency via Homebrew. If you already have python installed, you may prefer to usepipx install algokitas explainedhere.Ensure prerequisites are installedHomebrewGit(should already be available ifbrewis installed)Docker, (orbrew install --cask docker)NoteDocker requires MacOS 11+Install using Homebrewbrew install algorandfoundation/tap/algokitRestart the terminal to ensure AlgoKit is available on the pathVerify installationMaintenanceSome useful commands for updating or removing AlgoKit in the future.To update AlgoKit:brew upgrade algokitTo remove AlgoKit:brew uninstall algokitInstall AlgoKit on LinuxEnsure prerequisites are installedPython 3.10+NoteThere is probably a better way to install Python than to download it directly, e.g. your local Linux package managerpipxGitDockerContinue with step 2 in the following section to install viapipxInstall AlgoKit with pipx on any OSEnsure desired prerequisites are installedPython 3.10+pipxGitDockerInstall using pipxpipx install algokitRestart the terminal to ensure AlgoKit is available on the pathVerify installationMaintenanceSome useful commands for updating or removing AlgoKit in the future.To update AlgoKit:pipx upgrade algokitTo remove AlgoKit:pipx uninstall algokitVerify installationVerify AlgoKit is installed correctly by runningalgokit --versionand you should see output similar to:algokit, version 1.0.1NoteIf you get receive one of the following errors:command not found: algokit(bash/zsh)The term 'algokit' is not recognized as the name of a cmdlet, function, script file, or operable program.(PowerShell)Then ensure thatalgokitis available on the PATH by runningpipx ensurepathand restarting the terminal.It is also recommended that you runalgokit doctorto verify there are no issues in your local environment and to diagnose any problems if you do have difficulties running AlgoKit. The output of this command will look similar to:timestamp: 2023-03-27T01:23:45+00:00 AlgoKit: 1.0.1 AlgoKit Python: 3.11.1 (main, Dec 23 2022, 09:28:24) [Clang 14.0.0 (clang-1400.0.29.202)] (location: /Users/algokit/.local/pipx/venvs/algokit) OS: macOS-13.1-arm64-arm-64bit docker: 20.10.21 docker compose: 2.13.0 git: 2.37.1 python: 3.10.9 (location: /opt/homebrew/bin/python) python3: 3.10.9 (location: /opt/homebrew/bin/python3) pipx: 1.1.0 poetry: 1.3.2 node: 18.12.1 npm: 8.19.2 brew: 3.6.18 If you are experiencing a problem with AlgoKit, feel free to submit an issue via: https://github.com/algorandfoundation/algokit-cli/issues/new Please include this output, if you want to populate this message in your clipboard, run `algokit doctor -c`Per the above output, the doctor command output is a helpful tool if you need to ask for support orraise an issue.
algokit-cli
Failed to fetch description. HTTP Status Code: 404
algokit-client-generator
AlgoKit Python client generatorThis project generates a type-safe smart contract client in Python for the Algorand Blockchain that wraps theapplication clientinAlgoKit Utils. It does this by reading anARC-0032application spec file.NoteThere is also an equivalentTypeScript client generator.UsagePrerequisitesTo be able to consume the generated file you need to include it in a Python project that has (at least) the following package installed:poetry add algokit-utils@^1.2UseTo install the generator as a CLI tool:pipx install algokit-client-generatorThen to use italgokitgen-py path/to/application.json path/to/output/client_generated.pyOr if you haveAlgoKit1.1+ installedalgokit generate client path/to/application.json --output path/to/output/client_generated.pyExamplesThere are a range ofexamplesthat you can look at to see a source smart contract ({contract.py}), the generated client (client_generated.py) and some tests that demonstrate how you can use the client (test_client.py).ContributingIf you want to contribute to this project the following information will be helpful.Initial setupClone this repository locallyInstall pre-requisites:InstallAlgoKit-Link: Ensure you can executealgokit --version.Bootstrap your local environment; runalgokit bootstrap allwithin this folder, which will:InstallPoetry-Link: The minimum required version is1.2. Ensure you can executepoetry -Vand get1.2+Runpoetry installin the root directory, which will set up a.venvfolder with a Python virtual environment and also install all Python dependenciesOpen the project and start debugging / developing via:VS CodeOpen the repository root in VS CodeInstall recommended extensionsRun tests via test explorerIDEA (e.g. PyCharm)Open the repository root in the IDEIt should automatically detect it's a Poetry project and set up a Python interpreter and virtual environment.Run testsOtherOpen the repository root in your text editor of choiceRunpoetry run pytestSubsequentlyIf you update to the latest source code and there are new dependencies you will need to runalgokit bootstrap allagainFollow step 3 aboveBuilding examplesIn theexamplesfolder there is a series of example contracts along with their generated client. These contracts are built usingBeaker.If you want to make changes to any of the smart contract examples and re-generate the ARC-0032 application.json files then change the correspondingexamples/{contract}/{contract}.pyfile and then run:poetry run python -m examplesOr in Visual Studio Code you can use the default build task (Ctrl+Shift+B).Continuous Integration / Continuous Deployment (CI/CD)This project usesGitHub Actionsto define CI/CD workflows, which are located in the.github/workflowsfolder.Approval testsMaking any changes to the generated code will result in the approval tests failing. The approval tests work by generating a version of client and outputting it to./examples/APP_NAME/client_generated.pythen comparing to the approved version./examples/APP_NAME/client.ts. If you make a change and break the approval tests, you will need to update the approved version by overwriting it with the generated version. You can runpoe update-approvalsto update all approved clients in one go.
algokit-learn
No description available on PyPI.
algokit-utils
AlgoKit Python UtilitiesA set of core Algorand utilities written in Python and released via PyPi that make it easier to build solutions on Algorand. This project is part ofAlgoKit.The goal of this library is to provide intuitive, productive utility functions that make it easier, quicker and safer to build applications on Algorand. Largely these functions wrap the underlying Algorand SDK, but provide a higher level interface with sensible defaults and capabilities for common tasks.NoteIf you prefer TypeScript there's an equivalentTypeScript utility library.Install|DocumentationInstallThis library can be installed using pip, e.g.:pip install algokit-utilsGuiding principlesThis library follows theGuiding Principles of AlgoKit.ContributingThis is an open source project managed by the Algorand Foundation. See theAlgoKit contributing pageto learn about making improvements.To successfully run the tests in this repository you need to be running LocalNet viaAlgoKit:algokit localnet start
algolab
AlgoLab APISitehttps://algolab.cloudPyPIhttps://pypi.org/project/algolab/
algol-bayer
Capture, display and convert RAW DSLR astronomical imagesThis package was developed for astro-spectroscopic student projects at the Dresden Gönnsdorf observatory.Installationapt-get install gphoto2 pip install algol-bayerCapture and display$ bayer_capture_sequence.sh usage: bayer_capture_histograms.sh min-exp-time-s max-exp-time-s Create and display histograms by doubling the exposure times between min and max exposure time. Example: bayer_capture_histograms.sh 30 240 will create histograms for exposures of 30, 60, 120 and 240 seconds. $ bayer_capture_sequence.sh usage: bayer_capture_sequence.sh object image-count exp-time-s Capture and image sequence and store them as raw images. Example: bayer_capture_sequence.sh zetori 20 1800 will capture 20 halve hour exposures zetori_1800_00.cr2, zetori_1800_01.cr2, ...ConvertTBDLinkshttp://gphoto.org/https://pypi.org/project/rawpy/https://pypi.org/project/algol-reduction/
algolia-places-python
No description available on PyPI.
algoliaqb
A library to help build queries for searching Algolia.This package is meant to be used with thealgoliasearchlibrary.Problem:An app I have been working on has a few points of code duplication and increased complexity. This package is a way for me to fix those issues and increase readability.Installationpip install algoliaqbFilter StringsBy defaultfilter_mapconsiders all input as strings. This is pretty straight forward. Lets say for example you have the following filter map:filter_map = { "group_id": "tenant_id", }with the followingflask.args:{ "group_id": 1 }AlgoliaQB will look forgroup_idwithinflask.args, grab the value, then remap the key and value for you.tenant_id:1Now lets try an example with a few more filters.filter_map = { "group_id": "tenant_id", "is_reported": "is_reported" }with the followingflask.args:{ "group_id": 1, "is_reported": "true }The returned filter_string is as follows.tenant_id:1 AND is_reported:trueLibrary Usage Example:fromalgoliasearch.search_clientimportSearchClientfromalgoliaqbimportAlgoliaQueryBuilderfromflaskimportrequestaqb=AlgoliaQueryBuilder(search_param="search",filter_map={"group_id":"tenant_id","is_reported":"is_reported"})# Extract the search query from our flask apps request.args var.search_query=aqb.get_search_query(request.args)# Get the filter query from our request args.filter_query=aqb.get_filter_query(request.args)# Now that we have the filter string, we just pass it into the search function.search_client=SearchClient()index=search_client.init_index("contacts")results=index.search(search_query,{"filters":filter_query})