Saravanan666/pypi-org huggingface dataset:
Package: quart-rate-limiter
Quart-Rate-Limiter is an extension forQuartto allow for rate limits to be
defined and enforced on a per route basis. The 429 error response
includes aRFC7231compliantRetry-Afterheader and the successful responses contain headers
compliant with theRateLimit Header Fields for HTTPRFC
draft.UsageTo add a rate limit first initialise the RateLimiting extension with
the application,app=Quart(__name__)rate_limiter=RateLimiter(app)or via the factory pattern,rate_limiter=RateLimiter()defcreate_app():app=Quart(__name__)rate_limiter.init_app(app)returnappNow this is done you can apply rate limits to any route by using therate_limitdecorator,@app.route('/')@rate_limit(1,timedelta(seconds=10))asyncdefhandler():...Or to apply rate limits to all routes within a blueprint by using thelimit_blueprintfunction,blueprint=Blueprint("name",__name__)limit_blueprint(blueprint,1,timedelta(seconds=10))Or to apply rate limits to all routes in an app, define the default
limits when initialising the RateLimiter,rate_limiter=RateLimiter(default_limits=[RateLimit(1,timedelta(seconds=10))])and then to exempt a route,@app.route("/exempt")@rate_exemptasyncdefhandler():...To alter the identification of remote users you can either supply a
global key function when initialising the extension, or on a per route
basis.By default rate limiting information (TATs) will be stored in memory,
which will result in unexpected behaviour if multiple workers are
used. To solve this a redis store can be used by installing theredisextra (pip installquart-rate-limiter[redis]) and then
using as so,fromquart_rate_limiter.redis_storeimportRedisStoreredis_store=RedisStore(address)RateLimiter(app,store=redis_store)This store usesredis,
and any extra keyword arguments passed to theRedisStoreconstructor will be passed to the rediscreate_redisfunction.A custom store is possible, see theRateLimiterStoreABCfor the
required interface.Simple examplesTo limit a route to 1 request per second and a maximum of 20 per minute,@app.route('/')@rate_limit(1,timedelta(seconds=1))@rate_limit(20,timedelta(minutes=1))asyncdefhandler():...Alternatively thelimitsargument can be used for multiple limits,@app.route('/')@rate_limit(limits=[RateLimit(1,timedelta(seconds=1)),RateLimit(20,timedelta(minutes=1)),],)asyncdefhandler():...To identify remote users based on their authentication ID, rather than
their IP,asyncdefkey_function():returncurrent_user.idRateLimiter(app,key_function=key_function)Thekey_functionis a coroutine function to allow session lookups
if appropriate.ContributingQuart-Rate-Limiter is developed onGitHub. You are very welcome to
openissuesor
proposemerge requests.TestingThe best way to test Quart-Rate-Limiter is with Tox,$pipinstalltox$toxthis will check the code style and run the tests.HelpThis README is the best place to start, after that try opening anissue.
Package: quart-redis
Quart-RedisAn easy way of setting up a redis connection in quart.Requirementsquart >= 0.18redis >= 4.2Example of Usepip install quart-redisfromquartimportQuartfromquart_redisimportRedisHandler,get_redisapp=Quart(__name__)app.config["REDIS_URI"]="redis://localhost"# override default connection attempts, set < 0 to disable# app.config["REDIS_CONN_ATTEMPTS"] = 3redis_handler=RedisHandler(app)@app.route("/")asyncdefindex():redis=get_redis()val=awaitredis.get("my-key")ifvalisNone:awaitredis.set("my-key","it works!")val=awaitredis.get("my-key")returnval
Package: quart-schema
Quart-Schema is a Quart extension that provides schema validation and
auto-generated API documentation. This is particularly useful when
writing RESTful APIs.Quart-Schema can use eithermsgspecorpydanticto validate.QuickstartQuart-Schema can validate an existing Quart route by decorating it
withvalidate_querystring,validate_request, orvalidate_response. It can also validate the JSON data sent and
received over websockets using thesend_asandreceive_asmethods.fromdataclassesimportdataclassfromdatetimeimportdatetimefromquartimportQuart,websocketfromquart_schemaimportQuartSchema,validate_request,validate_responseapp=Quart(__name__)QuartSchema(app)@dataclassclassTodo:task:strdue:datetime|None@app.post("/")@validate_request(Todo)@validate_response(Todo,201)asyncdefcreate_todo(data:Todo)->tuple[Todo,int]:...# Do something with data, e.g. save to the DBreturndata,201@app.websocket("/ws")asyncdefws()->None:whileTrue:data=awaitwebsocket.receive_as(Todo)...# Do something with data, e.g. save to the DBawaitwebsocket.send_as(data,Todo)The documentation is served by default at/openapi.jsonaccording
to the OpenAPI standard, or at/docsfor aSwaggerUIinterface, or/redocsfor
aredocinterface, or/scalarfor aScalarinterface. Note that there is currently no documentation standard for
WebSockets.ContributingQuart-Schema is developed onGitHub. If you come across an
issue, or have a feature request please open anissue. If you want to
contribute a fix or the feature-implementation please do (typo fixes
welcome), by proposing amerge request.TestingThe best way to test Quart-Schema is withTox,$pipinstalltox$toxthis will check the code style and run the tests.HelpThe Quart-Schemadocumentationis the best places to
start, after that try searchingstack overflowor ask for helpon gitter. If you still
can’t find an answer pleaseopen an issue.
Package: quart-sqlalchemy
Quart-SQLAlchemy provides a simple wrapper for SQLAlchemy made for humans.  I’ve kept things as
simple as possible, abstracted much complexity, and implemented everything using the current
best practices recommended by the SQLAlchemy developers and targets version 2.0.x+.  As a
convenience, a framework adapter is provided for Quart, but the rest of this library is framework
agnostic.The bundled SQLAlchemy object intentionally discards the use of scoped_session and it’s async
counterpart.  With version 2.x+, it’s expected that sessions are short lived and vanilla and
context managers are used for managing sesssion lifecycle.  Any operations that intend to change
state should open an explicit transaction using the context manager returned by session.begin().
This pattern of usage prevents problems like sessions being shared between processes, threads, or
tasks entirely, as opposed to the past conventions of mitigating this type of sharing.  Another
best practice is expecting any transaction to intermittently fail, and structuring your logic to
automatically perform retries.  You can find the retrying session context managers in the retry
module.InstallingInstall and update usingpip:$ pip install quart-sqlalchemyInstall the latest release with unreleased pytest-asyncio fixes:$ pip install git+ssh://git@github.com/joeblackwaslike/quart-sqlalchemy.git#egg=quart_sqlalchemyInstall a wheel from our releases:$ pip install https://github.com/joeblackwaslike/quart-sqlalchemy/releases/download/v3.0.1/quart_sqlalchemy-3.0.1-py3-none-any.whlAdd to requirements.txt:quart-sqlalchemy @ https://github.com/joeblackwaslike/quart-sqlalchemy/releases/download/v3.0.1/quart_sqlalchemy-3.0.1-py3-none-any.whlA Simple Exampleimportsqlalchemyassaimportsqlalchemy.ormfromsqlalchemy.ormimportMapped,mapped_columnfromquartimportQuartfromquart_sqlalchemyimportSQLAlchemyConfigfromquart_sqlalchemy.frameworkimportQuartSQLAlchemyapp=Quart(__name__)db=QuartSQLAlchemy(config=SQLAlchemyConfigbinds=dict(default=dict(engine=dict(url="sqlite:///",echo=True,connect_args=dict(check_same_thread=False),),session=dict(expire_on_commit=False,),))),app,)classUser(db.Model)__tablename__="user"id:Mapped[int]=mapped_column(sa.Identity(),primary_key=True,autoincrement=True)name:Mapped[str]=mapped_column(default="default")db.create_all()withdb.bind.Session()ass:withs.begin():user=User(username="example")s.add(user)s.flush()s.refresh(user)users=s.scalars(sa.select(User)).all()print(user,users)assertuserinusersContributingFor guidance on setting up a development environment and how to make a
contribution to Quart-SQLAlchemy, see thecontributing guidelines.
Package: quart-tasks
Quart-Tasks is a Quart extension that provides scheduled background
tasks.QuickstartQuart-Tasks is used by associating it with an app and then registering
scheduled tasks,fromquartimportQuartfromquart_tasksimportQuartTasksapp=Quart(__name__)tasks=QuartTasks(app)@tasks.cron("*/5 * * * *")# every 5 minutesasyncdefinfrequent_task():...# Do something@tasks.cron(seconds="*1/0",# every 10 secondsminutes="*",hours="*",day_of_month="*",month="*",day_of_week="*",)asyncdeffrequent_task():...# Do something@tasks.periodic(timedelta(seconds=10))asyncdefregular_task():...# Do SomethingNote: the non-standard cron format (for seconds) is as defined bycroniter.The tasks will then run in the background as the app itself runs or
they can be run manually via the CLIquartrun-tasks.ContributingQuart-Tasks is developed onGitHub. If you come across an issue,
or have a feature request please open anissue. If you want to
contribute a fix or the feature-implementation please do (typo fixes
welcome), by proposing amerge request.TestingThe best way to test Quart-Tasks is withTox,$pipinstalltox$toxthis will check the code style and run the tests.HelpThe Quart-Tasksdocumentationis the best places to
start, after that try searchingstack overflowor ask for helpon gitter. If you still
can’t find an answer pleaseopen an issue.
Package: quart-trio
Quart-Trio is an extension forQuartto support theTrioevent loop. This is an
alternative to using the asyncio event loop present in the Python
standard library and supported by default in Quart.QuickstartQuartTrio can be installed viapip,$pipinstallquart-trioand requires Python 3.8 or higher (seepython version supportfor reasoning).A minimal Quart example is,fromquartimportwebsocketfromquart_trioimportQuartTrioapp=QuartTrio(__name__)@app.route('/')asyncdefhello():return'hello'@app.websocket('/ws')asyncdefws():whileTrue:awaitwebsocket.send('hello')app.run()if the above is in a file calledapp.pyit can be run as,$pythonapp.pyTo deploy in a production setting see thedeploymentdocumentation.ContributingQuart-Trio is developed onGitHub. You are very welcome to
openissuesor
proposemerge requests.TestingThe best way to test Quart-Trio is with Tox,$pipinstalltox$toxthis will check the code style and run the tests.HelpTheQuart-TrioandQuartdocumentation are the best
places to start, after that try searchingstack overflow, if you still
can’t find an answer pleaseopen an issue.
Package: quart-uploads
Quart UploadsQuart-Uploads allows your application to flexibly and efficiently handle file
uploading and serving the uploaded files.You can create different sets of uploads - one for document attachments, one
for photos, etc. - and the application can be configured to save them all in
different places and to generate different URLs for them.For more information on Quart,visit hereQuart-Uploads is based onFlask-Uploadsby maxcountryman.
Package: quartustcl
quartustclquartustclis a Python module to interact with Intel Quartus Tcl
shells. It opens a single shell in a subprocess, then helps you with
reading and writing data to it, and parsing Tcl lists.InstallationInstall viapip:pipinstallquartustclDemoYou can start a demo Python REPL by running the package as a script:python3-mquartustclThequartustclsubshell is exposed in a variable namedquartus.Basic UseInstantiate aQuartusTclobject to start a shell. Then, call methods
on it.quartus=quartustcl.QuartusTcl()three=quartus.expr('1 + 2')assertthree=='3'If you are expecting a list as a result, useparseto turn Tcl lists
into Python lists.devnames=quartus.parse(quartus.get_device_names(hardware_name="Foo Bar"))In the Tcl subshell, this runsget_device_names-hardware_name{FooBar}and parses the result into a Python list.For more detailed information, pleaseread the documentation.
Package: quasar-client
Quasar Python ClientInstallationpipinstallquasar-clientUsagefromquasar_clientimportQuasarquasar_base="URL for Quasar-compatible server"quasar=Quasar(quasar_base=quasar_base)# Use OpenAI-compatible interfaces...chat_completion=quasar.chat.completions.create(messages=[{"role":"user","content":"Hello quasar",}],model="gpt-3.5-turbo",)# Use Quasar-specific interfaces like NER...entities=quasar.tagger.tag(task="ner",text="Yurts Technologies is based in SF.")Quasar provides a convenient interface for common RAG APIs. In addition to the OpenAI APIs, the client supports:EntitiesEmbeddingRankingAsynchronous SupportFor developers looking to leverage asynchronous programming for improved performance and non-blocking IO operations, Quasar introduces async support for its APIs. This allows you to efficiently handle large volumes of requests and data processing in a non-blocking manner.Async Usage ExampleBelow is an example of how to use the asynchronous interface for embedding texts:fromquasar_clientimportAsyncQuasarquasar_base="URL for Quasar-compatible server"quasar=AsyncQuasar(quasar_base=quasar_base)# Asynchronously embed textsasyncdefembed_texts(texts):embeddings=awaitquasar.embedding.embed(texts=texts)returnembeddings# Example textstexts=["Hello, world!","How are you?"]# Remember to run this in an async contextThis async support ensures that your application can scale more efficiently, handling concurrent operations without the need for complex threading or multiprocessing setups.Sync and Async Resource ModulesQuasar provides both synchronous and asynchronous resource classes to cater to different use cases and preferences. Whether you prefer the simplicity of synchronous code or the efficiency of asynchronous operations, Quasar has you covered.# Synchronous Embedding Resource ClassclassSyncEmbeddingResource(SyncResource):...# Asynchronous Embedding Resource ClassclassAsyncEmbeddingResource(AsyncResource):...
Package: quasar-unred
quasar_unredQuasar Unred is a Python library for determining the E(B-V) value of observed quasar spectra. It can also be used to appropriately deredden these spectra.Installationpip install quasar_unredqso_template.txt must be downloaded and in working directory for load_template() to work with no argument.UsageA simple demonstration is shown in quasar_unred_demo.ipynbIt is assumed that qso_template.txt and ukfs1037.p0236.final.dat are both downloaded and in your working directory.DependenciesDependencies for use are numpy, scipy, astropy, and dust_extinctionContributingPull requests are welcome. For major changes, please open an issue first
to discuss what you would like to change.LicenseThis project is Copyright (c) John Klawitter and Eilat Glikman and licensed under the terms of the BSD 3-Clause license.
Package: quasigraph
Quasigraphis an open-source toolkit designed for generating chemical and geometric descriptors to be used in machine learning models.InstallationThe easiest method to install quasigraph is by utilizing pip:$pipinstallquasigraphGetting startedfromase.buildimportmoleculefromquasigraphimportQuasiGraph# Initialize an Atoms object for methanol (CH3OH) using ASE's molecule functionatoms=molecule('CH3OH')# Instantiate a QuasiGraph object containing chemical and coordination numbersqgr=QuasiGraph(atoms)# Convert the QuasiGraph object into a pandas DataFramedf=qgr.get_dataframe()# Convert the QuasiGraph object into a vectorvector=qgr.get_vector()DescriptorThe descriptor can be separated into two parts, a chemical part and a geometric part.Chemical partThe chemical part of the descriptor employs theMendeleev library, incorporating atomic details like the valence electron concentration, covalent radius, atomic radius, Pauling electronegativity and electron affinitity for every element within the object.For example, for methanol (CH3OH) we have the table:VECcovalent_radiusen_pauling040.752.55160.633.44210.322.2310.322.2410.322.2510.322.2Geometric partThe geometric part involves identifying all bonds and computing the coordination numbers for each atom, indicated as CN. Additionally, the generalized coordination number (GCN)[^1] is determined by summing the coordination numbers of the neighboring ligands for each atom and normalizing this sum by the highest coordination number found in the molecule.Figure 1- Schematic representation of the methanol molecule, indicating the chemical symbol and coordination number (CN) for every atom.For example, for methanol (CH3OH) we have the geometric data, as shown inFig. 1.CNGCN41.2521.2511.0010.5011.0011.00LicenseThis is an open source code underMIT License.AcknowledgementsWe thank financial support from FAPESP (Grant No. 2022/14549-3), INCT Materials Informatics (Grant No. 406447/2022-5), and CNPq (Grant No. 311324/2020-7).[^1]: Calle-Vallejo, F., Martínez, J. I., García-Lastra, J. M., Sautet, P. & Loffreda, D.Fast Prediction of Adsorption Properties for Platinum Nanocatalysts with Generalized Coordination Numbers,Angew. Chem. Int. Ed.53, 8316-8319 (2014).
Package: quasinet
QuasinetDescriptionInfer non-local structural dependencies in genomic sequences. Genomic sequences are esentially compressed encodings of phenotypic information. This package provides a novel set of tools to extract long-range structural dependencies in genotypic data that define the phenotypic outcomes. The key capabilities implemented here are as follows:Compute the Quasinet (Q-net) given a database of nucleic acid sequences. The Q-net is a family of conditional inference trees that capture the predictability of each nucleotide position given the rest of the genome. The constructed Q-net for COVID-19 and Influenza A H1N1 HA 2008-9 is shown below.COVID-19INFLUENZACompute a structure-aware evolution-adaptive notion of distance between genomes, which is demonstrably more biologically relevant compared to the standard edit distance.Draw samples in-silico that have a high probability of being biologically correct. For example, given a database of Influenza sequences, we can generate a new genomic sequence that has a high probability of being a valid influenza sequence.InstallationTo install with pip:pip install quasinetTo fix error with Mac or Windows:from quasinet.osfix import osfix
# for windows
osfix('win')
# for max x86_64 (macbook pro)
osfix('macx86')
# mac arm (macbook air)
osfix('macarm')NOTE: If trying to reproduce the paper below, please usepip install quasinet==0.0.58Dependenciesscikit-learnscipynumpynumbapandasjoblibbiopythonUsagefrom quasinet import qnet

# initialize qnet
myqnet = qnet.Qnet()

# train the qnet
myqnet.fit(X)

# compute qdistance
qdist = qnet.qdistance(seq1, seq2, myqnet, myqnet)ExamplesExamples are locatedhere.DocumentationFor more documentation, seehere.PapersFor reference, please check out our paper:Preparing For the Next Pandemic: Learning Wild Mutational Patterns At Scale For Analyzing Sequence Divergence In Novel PathogensAuthorsYou can reach the ZED lab at: zed.uchicago.edu
Package: quasiquotes
Blocks of non-python code sprinkled in for extra seasoning.What is aquasiquoteAnquasiquoteis a new syntactical element that allows us to embed non
python code into our existing python code. The basic structure is as follows:# coding: quasiquotes[$name|somecodegoeshere|]This desuagars to:name.quote_expr("some code goes here",frame,col_offset)whereframeis the executing stack frame andcol_offsetis the column
offset of the quasiquoter.This allows us to use slightly nicer syntax for our code.
The# coding: quasiquotesis needed to enable this extension.
The syntax is chosen to match haskell’s quasiquote syntax from GHC 6.12. We need
to use the older syntax (with the$) because python’s grammar would be
ambiguous without it at the quote open step. To simplify the tokenizer, we chose
to use slighly more verbose syntax.We may also use statement syntax for quasiquotes in a modified with block:# coding: quasiquoteswith$name:somecodegoeshereThis desuagars to:name.quote_stmt("    some code goes here",frame,col_offset)ThecquasiquoterThe builtincquasiquoter allows us to inline C code into our python.
For example:>>>fromquasiquotes.cimportc>>>deff(a):...with$c:...printf("%ld\n",PyLong_AsLong(a));...a=Py_None;...Py_INCREF(a);...print(a)...>>>f(0)0None>>>f(1)1NoneHere we can see that the quasiquoter can read from and write to the local
scope.We can also quote C expressions with the quote expression syntax.>>>defcell_new(n):...return[$c|PyCell_New(n);]...>>>cell_new(1)<cellat0x7f8dde6cd5e8:intobjectat0x7f8ddf956780>Here we can see that thecquasiquoter is really convenient as a python
interface into the C API.WarningCPython uses a reference counting system to manage the lifetimes of objects.
Code like:return[$|Py_None|]can cause a potential segfault whenNonebecause it will have 1 less
reference than expected. Instead, be sure to remember to incref your
expressions with:return[$|Py_INCREF(Py_None);Py_None|]You must also incref when reassigning names from the enclosing python scope.
For more information, see theCPython docs.IPython IntegrationWe can use thecquasiquoter in the IPython repl or notebook as a cell or
line magic. When used as a line magic, it is quoted as an expression. When used
as a cell magic, it is quoted as a statement.In[1]:importquasiquotes.cIn[2]:a=5In[3]:%cPyObject*b=PyLong_FromLong(3);PyObject*ret=PyNumber_Add(a,b);Py_DECREF(b);ret;Out[3]:8In[4]:%%c...:printf("%ld+%ld=%ld\n",3,PyLong_AsLong(a),PyLong_AsLong(_3));...:puts("reassigning 'a'");...:a=Py_None;...:Py_INCREF(a);...:3+5=8reassigning'a'In[5]:aisNoneOut[5]:True
Package: quaspy
QuaspyTheQuaspy(Quantum algorithm simulations in Python) library forPython3contains modules that implement:Simulators for the quantum part of Shor's order-finding algorithm[Shor94], modified as in[E22p], and the classical post-processing in[E22p]that recovers the order in a single run with very high success probability.Simulators for factoring general integers via order-finding, and the post-processing in[E21b]and[E22p]that factors any integer completely in a single order-finding run with very high success probability.Simulators for the quantum part of Shor's algorithm for computing general discrete logarithms[Shor94], modified as in[E19p], and the post-processing in[E19p]that recovers the logarithm given the order in a single run with very high probability of success.Simulators for the quantum part of Ekerå–Håstad's algorithm for computing short discrete logarithms[EH17], modified as in[E20]and[E23p], and the post-processing in[E23p]that recovers the logarithm in a single run with very high probability of success. This algorithm does not require the order to be known.Simulators for factoring RSA integers via short discrete logarithms, by using the reduction in[EH17], modified as in[E20]and[E23p], and the post-processing in[E23p]that factors random RSA integers in a single run with very high probability of success.All modules, classes, methods and functions inQuaspyaredocumentedusingPython3docstrings.Note thatQuaspydoes not implement support for tradeoffs in the aforementioned algorithms. Support for tradeoffs may potentially be added in the future. For the time being, see instead theQunundrumrepository with its suite of MPI programs. Note furthermore that portions ofQuaspyare inherited from theFactoritallrepository.Quaspyis a work in progress, and may be subject to major changes without prior notice.Quaspywas developed for academic research purposes. It grew out of our research project in an organic manner as research questions were posed and answered. It is distributed "as is" without warranty of any kind, either expressed or implied. For further details, see thelicense.ExamplesFor examples that illustrate how to useQuaspy, please see theexamplesdirectory in theQuaspyrepository.See also thedocumentationforQuaspyfor help on how to use the library.About and acknowledgmentsTheQuaspylibrary was developed byMartin Ekerå, in part atKTH, the Royal Institute of Technology, in Stockholm,Sweden. Valuable comments and advice were provided by Johan Håstad throughout the development process.Funding and support was provided by the Swedish NCSA that is a part of theSwedish Armed Forces.