Saravanan666/pypi-org huggingface dataset:
Package: pythonreact
PythonReactDid you ever think: "We need a JS library turned into a python module used for console output in stead of rendering a webpage."? No? Well I did. So here it is.InstallationThis package is onpypi.Installing can be done viapipWindows:pip install pythonreactMac/ Linux:pip3installpythonreactUsageIf you are familliar with the JS library react this should be very easy.ComponentEverything is a component.To create a new component, make a class that inherits fromPythonReact.ComponentimportPythonReactclassMyComponent(PythonReact.Component):passHello python reactTo show something in the console we will add a render function. This render function should return a list of printable items or other Components.importPythonReactclassMyComponent(PythonReact.Component):defrender(self)->list:return["Hello","Python React"]Let's make an object of that type:# snipmy_comp=MyComponent()It will automatically start printing now.
And it will render your function.StateIf you have used React you know about state.To create a state add it to the__init__of your component.
And then simply call the variables in your render function.importPythonReactclassMyComponent(PythonReact.Component):def__init__(self):self.state={"name":"Donkere",}super().__init__()defrender(self)->list:return[f"Hello{self.state['name']}!",]my_comp=MyComponent()>>>HelloDonkere!Set stateJust as in React there is a set state function.importPythonReactclassMyComponent(PythonReact.Component):def__init__(self):self.state={"name":"Donkere",}super().__init__()defrender(self)->list:return[f"Hello{self.state['name']}!",]my_comp=MyComponent()my_comp.set_state({"name":"New Name"})>>>HelloDonkere!# Screen get's clearedHelloNewName!
Package: python-readenv
python-readenvreadenvmakes it easy to automatically load environment variables from.envfile(s) and put intoos.environ.Install$pipinstallpython-readenvGetting startedYou can automatically load at startup time with the helper importimport readenv.loads,
which try to locate and load the first env file found from your current working directory up to
root.
By default it will search for.envand.env.localfiles.Automatic loadYou can automatically load at startup time with the helper importimportreadenv.loads...which try to locate and load the first env file found from your current working directory up to
root.Manual loadAlternatively, you can customize which filesreadenvshould search and loadimportreadenvreadenv.load("myenv","myenv.local")mypy integrationIf you need to load the environment from mypy you could add[mypy]plugins=readenv.mypyin yourmypy.iniorsetup.cfgfile.pyproject.tomlconfiguration is also supported:[tool.mypy]plugins=["readenv.mypy"]Custom environmentYou can create your own environmentimportreadenvenv=readenv.Environ()or start with the current environ copyimportcopyimportosimportreadenvenv=Environ(copy.deepcopy(os.environ))ExamplesDjango integrationPut the helper import as first placemanage.py#!/usr/bin/env python3importreadenv.loads# noqa: F401 isort:skipimportsysif__name__=="__main__":readenv.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings")fromdjango.core.managementimportexecute_from_command_lineexecute_from_command_line(sys.argv)wsgi.pyimportreadenv.loads# noqa: F401 isort:skipfromdjango.core.wsgiimportget_wsgi_applicationreadenv.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings")application=get_wsgi_application()asgi.pyimportreadenv.loads# noqa: F401 isort:skipfromdjango.core.asgiimportget_asgi_applicationreadenv.setdefault("DJANGO_SETTINGS_MODULE","myproject.settings")application=get_asgi_application()
Package: python-realtimecongress
A python library for interacting with the Real Time Congress API.Usage:Fetching the first page of bills co-sponsored by John Lewis:>>>from realtimecongress import RTC
>>>RTC.apikey = ‘mykey’
>>>RTC.getBills(cosponsor_ids=’L000287’)
[RTCResponse(…),]Getting data about the last request:>>>RTC.meta
{‘count’: 838, ‘page’: {‘count’: 20, ‘per_page’: 20, ‘page’: 1}}
Package: python-reaperdaw
python-reaperdawPython wrapper for REAPER DAW REST interface.Please refer to ReaTeam'sweb interface moddingdocumentation for API insights.Setup in ReaperLaunch your Reaper DAWHitCtrl + Por go to Options > PreferencesNavigate to "Control/OSC/web" menu and click "Add"From the "Control surface mode" dropdown menu choose "Web browser interface"Set the web interface port or leave default8080Optionally set username:passwordOptionally set the default web interfaceCopy the Access URL and paste it in your browser - now your Reaper has a web interface.Hit OK in both preference windowsExample usageimportaiohttpimportasyncioimportjsonfromreaperdawimportReaperasyncdefmain(host="localhost",port="8080",username="",password=""):asyncwithaiohttp.ClientSession()assession:reaper=Reaper(session,host,port,username,password)# Sets Master Volume to 0db (maximum volume)awaitreaper.setMasterVolume(1)status=awaitreaper.getStatus()response=json.loads(status)print("Status:",status)print("Number of tracks:",response["number_of_tracks"])print("Number of armed tracks:",response["number_of_armed_tracks"])print("Armed tracks:",response["armed_tracks"])print("Time signature:",response["time_signature"])print("Play state:",response["play_state"])print("Repeat:",response["repeat"])print("Metronome:",response["metronome"])loop=asyncio.get_event_loop()loop.run_until_complete(main())getStatus response{"tracks":[{"index":0,"name":"MASTER","flags":[],"volume":"1.000000","pan":"0.000000","last_meter_peak":"-1500","last_meter_pos":"-1500","width_pan2":"1.000000","panmode":"0","sendcnt":"0","recvcnt":"0","hwoutcnt":"1","color":"#000000"},{"index":1,"name":"Track 1","flags":["record-armed"],"volume":"1.000000","pan":"0.000000","last_meter_peak":"-1500","last_meter_pos":"-1500","width_pan2":"1.000000","panmode":"3","sendcnt":"0","recvcnt":"0","hwoutcnt":"0","color":"#764e78"},{"index":2,"name":"Track 2","flags":["selected"],"volume":"1.000000","pan":"0.000000","last_meter_peak":"-1500","last_meter_pos":"-1500","width_pan2":"1.000000","panmode":"3","sendcnt":"0","recvcnt":"0","hwoutcnt":"0","color":"#d9c25b"}],"repeat":true,"metronome":false,"time_signature":"4/4","beatpos":{"position_seconds":"0.000000000000000","full_beat_position":"0.000000000000000","measure_cnt":"0","beats_in_measure":"0.000000000010000"},"play_state":"stopped","transport":{"playstate":"stopped","position_seconds":"0.000000","repeat":true,"position_string":"1.1.00","position_string_beats":"1.1.00"},"number_of_tracks":2,"number_of_armed_tracks":2,"armed-tracks":["Track 1"]}
Package: python-reapy
reapyreapyis a nice pythonic wrapper around the quite unpythonicReaScript Python APIforREAPER.ContentsInstallationUsageReaScript APIreapyAPIPerformanceDocumentationContributingAuthorLicenseInstallationIf you feel you need more explanation than the straightforward instructions below, head to the detailedinstallation guide.reapy is available viapip:$pipinstallpython-reapyOne additional step is required to let REAPER know reapy is available. First, open REAPER. Then in a terminal, run:$python-c"import reapy; reapy.configure_reaper()"Restart REAPER, and you're all set! You can now importreapyfrom inside or outside REAPER as any standard Python module.Instead of creating a new ReaScript containing:fromreaper_pythonimport*RPR_ShowConsoleMsg("Hello world!")you can open your usual Python shell and type:>>>importreapy>>>reapy.print("Hello world!")UsageReaScript APIAll ReaScript API functions are available inreapyin the sub-modulereapy.reascript_api. Note that in ReaScript Python API, all function names start with"RPR_". That unnecessary pseudo-namespace has been removed inreapy. Thus, you shall callreapy.reascript_api.GetCursorPositionin order to triggerreaper_python.RPR_GetCursorPosition. See example below.>>>fromreapyimportreascript_apiasRPR>>>RPR.GetCursorPosition()0.0>>>RPR.SetEditCurPos(1,True,True)>>>RPR.GetCursorPosition()1.0Note that if you have theSWS extensioninstalled, the additional ReaScript functions it provides will be available inreapy.reascript_apiand usable inside and outside REAPER as well.reapyAPIThe purpose ofreapyis to provide a more pythonic API as a substitute for ReaScript API. Below is thereapyway of executing the example above.>>>importreapy>>>project=reapy.Project()# Current project>>>project.cursor_position0.0>>>project.cursor_position=1>>>project.cursor_position1.0Thetranslation tablematches ReaScript functions with theirreapycounterparts.PerformanceWhen used from inside REAPER,reapyhas almost identical performance than native ReaScript API. Yet when it is used from the outside, the performance is quite worse. More precisely, since external API calls are processed in adeferloop inside REAPER, there can only be around 30 to 60 of them per second. In a time-critical context, you should make use of thereapy.inside_reapercontext manager.>>>importreapy>>>project=reapy.Project()# Current project>>># Unefficient (and useless) call>>>bpms=[project.bpmfor_inrange(1000)]# Takes at least 30 seconds...>>># Efficient call>>>withreapy.inside_reaper():...bpms=[project.bpmfor_inrange(1000)]...>>># Takes only 0.1 second!DocumentationCheck thedocumentationand especially theAPI guideandTranslation Tablefor more information.ContributingFor now, about a half of ReaScript API has areapycounterpart, the docs are far from great, and many bugs are waiting to be found. Feel free to improve the project by checking thecontribution guide!AuthorRomÃ©o DesprÃ©s-RomeoDespresLicenseThis project is licensed under the MIT License - see theLICENSE.txtfile for details.
Package: python-reCAPTCHA
reCAPTCHA is a free CAPTCHA service that protects your site against spam,
malicious registrations and other forms of attacks where computers try to
disguise themselves as a human.python-reCAPTCHAis a Python3.xmodule, that provides an easy
way to interact with thereCAPTCHA API.Installation$ pip install python-reCAPTCHAor$ git clone https://github.com/rbika/python-reCAPTCHA.git
$ cd python-reCAPTCHA
$ python setup.py install
$ cd .. && rm -rf python-reCAPTCHAUsageTo use reCAPTCHA, you need tosign up for API keysfor your site.Once you’ve signed up for API keys, adding reCAPTCHA to your site consists of
two steps.1. Displaying the reCAPTCHA WidgetGenerate the widget HTML by calling thegenerate_htmlfunction.>>> from recaptcha.captcha import generate_html
>>>
>>> public_key = "your_public_key"
>>> recaptcha_html = generate_html(public_key)
>>>
>>> print(recaptcha_html)
<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=your_public_key"></script><noscript><iframe src="http://www.google.com/recaptcha/api/api/noscript?k=your_public_key"height="300" width="500" frameborder="0"></iframe><br><textarea name="recaptcha_challenge_field"rows="3" cols="40"></textarea><input type="hidden" name="recaptcha_response_field"value="manual_challenge"></noscript>Place the generated HTML inside your form. If you are working with Django por
example, your form will looks like this:<form action="">
    {% autoscape on %}recaptcha_html{% endautoescape %}
    <input type="submit" value="Submit">
</form>2. Verifying user’s anwserAfter the user submit the anwser, you should get the required paramenters and
call theverifyfunction. Again, a Django’s example.>>> from recaptcha.captcha import verify
>>>
>>> private_key = "your_private_key"
>>> remote_ip = request.META['REMOTE_ADDR']
>>> challenge = request.POST.get('recaptcha_challenge_field', '')
>>> response = request.POST.get('recaptcha_response_field', '')
>>>
>>> result = verify(private_key, remote_ip, challenge, response)
>>>
>>> print(result)
{'success': False, 'error': 'incorrect-captcha-sol'}DocumentationDocumentation will be available soon.
Package: python-reddcoinrpc
AuthServiceProxy is an improved version of python-jsonrpc.It includes the following generic improvements:HTTP connections persist for the life of the AuthServiceProxy objectsends protocol ‘version’, per JSON-RPC 1.1sends proper, incrementing ‘id’uses standard Python json libcan optionally log all RPC calls and resultsJSON-2.0 batch supportIt also includes the following reddcoin-specific details:sends Basic HTTP authentication headersparses all JSON numbers that look like floats as Decimal,
and serializes Decimal values to JSON-RPC connections.read config from ~/.reddcoin/reddcoin.conf as default or specify a different pathInstallationchange the first line of setup.py to point to the directory of your installation of python 2.*run setup.pyNote: This will only install reddcoinrpc. If you also want to install jsonrpc to preserve
backwards compatibility, you have to replace ‘reddcoinrpc’ with ‘jsonrpc’ in setup.py and run it again.Or simply install the library using pip:pip install python-reddcoinrpcExamplefromreddcoinrpc.authproxyimportAuthServiceProxy,JSONRPCException# rpc_user and rpc_password are set in the bitcoin.conf filerpc_connection=AuthServiceProxy()best_block_hash=rpc_connection.getbestblockhash()print(rpc_connection.getblock(best_block_hash))# batch support : print timestamps of blocks 0 to 99 in 2 RPC round-trips:commands=[["getblockhash",height]forheightinrange(100)]block_hashes=rpc_connection.batch_(commands)blocks=rpc_connection.batch_([["getblock",h]forhinblock_hashes])block_times=[block["time"]forblockinblocks]print(block_times)Logging all RPC calls to stderrfromreddcoinrpc.authproxyimportAuthServiceProxy,JSONRPCExceptionimportlogginglogging.basicConfig()logging.getLogger("ReddcoinRPC").setLevel(logging.DEBUG)rpc_connection=AuthServiceProxy()print(rpc_connection.getinfo())Produces output on stderr likeDEBUG:ReddcoinRPC:-1-> getinfo []
DEBUG:ReddcoinRPC:<-1- {“connections”: 8, …etc }Socket timeouts under heavy loadPass the timeout argument to prevent “socket timed out” exceptions:rpc_connection=AuthServiceProxy(rpctimeout=120)
Package: python-redfish
This repository will be used to house the python-redfish library, a reference
implementation to enable Python developers to communicate with the Redfish API
(http://www.dmtf.org/standards/redfish).NOTE:STATUS: Work in progress, ready for proof of concept.

The current Redfish specification revision is 1.0.0 - Note that the mockup
is still at version 0.99.0a and may not reflect what the standard provides
fullyDocumentationThe full documentation is available athttp://pythonhosted.org/python-redfish/installation.htmlProject StructureThis project follows the same convention as OpenStack projects, eg. using pbr
for build and test automation:doc/            # Documentation
doc/source      # The doc source files live here
doc/build/html  # Output of building any docs will go here
dmtf            # Reference documents and mockup provided by the DMTF
examples/       # Any sample code using this library, eg. for education
                # should be put here
pbconf          # Project builder file to build rpm/deb packages for
                # distributions
redfish/        # The redfish library itself
redfish/tests/  # python-redfish unit test suite
redfish-client  # Client tool to manage redfish devicesRequirementsTo use the enclosed examples, you will need Python 2.7 or Python 3.4
(https://www.python.org/downloads/).  Note that Python 2.7.9 enforces greater
SSL verification requiring server certificates be installed. Parameters to
relax the requirements are available in the library, but these configurations
are discouraged due to security.Python requirements are listed in requirements.txt; additional requirements for
running the unit test suite are listed in test-requirements.txt.Note: Running tests requires Docker engine.Note: The program was tested with Python 2.7.10 and 3.4.2 however it might work
as well with all Python 3 releases.Get the source codeThe source code is available on github and can be retrieved using:git clone https://github.com/openstack/python-redfish.gitInstallationPlease refer to the following link.http://pythonhosted.org/python-redfish/installation.htmlContactsDistribution list:python-redfish@mondorescue.orgFurther ReferencesPlease look atdmtf/README.rstfile.
Package: python-redis-cache
python-redis-cacheSimple redis cache for Python functionsRequirementsRedis 5+Python 3.8+ (should work in Python 3.6+, but not tested)How to installpip install python-redis-cacheHow to usefromredisimportStrictRedisfromredis_cacheimportRedisCacheclient=StrictRedis(host="redis",decode_responses=True)cache=RedisCache(redis_client=client)@cache.cache()defmy_func(arg1,arg2):result=some_expensive_operation()returnresult# Use the functionmy_func(1,2)# Call it again with the same arguments and it will use cachemy_func(1,2)# Invalidate a single valuemy_func.invalidate(1,2)# Invalidate all values for functionmy_func.invalidate_all()Limitations and things to knowArguments and return types must be JSON serializable by default. You can override the serializer, but be careful with using Pickle. Make sure you understand the security risks. Pickle should not be used with untrusted values.https://security.stackexchange.com/questions/183966/safely-load-a-pickle-filedecode_responsesparameter must beFalsein redis client if you use pickle.ttl- is based on the time from when it's first inserted in the cache, not based on the last accesslimit- The limit will revoke keys (once it hits the limit) based on FIFO, not based on LRUAPI# Create the redis cachecache=RedisCache(redis_client,prefix="rc",serializer=dumps,deserializer=loads,key_serializer=None,exception_handler=None)# Cache decorator to go on functions, see abovecache.cache(ttl=...,limit=...,namespace=...)->Callable[[Callable],Callable]# Get multiple values from the cachecache.mget([{"fn":my_func,"args":[1,2],"kwargs":{}},...])->List[Any]Redis# Cached function API# Returns a cached value, if it exists in cache. Saves value in cache if it doesn't existcached_func(*args,*kwargs)# Invalidates a single valuecached_func.invalidate(*args,**kwargs)# Invalidates all values for cached functioncached_func.invalidate_all()prefix - The string to prefix the redis keys withserializer/deserializer - functions to convert arguments and return value to a string (user JSON by default)ttl - The time in seconds to cache the return valuenamespace - The string namespace of the cache. This is useful for allowing multiple functions to use the same cache. By default itsf'{function.__module__}.{function.__file__}'exception_handler - Function to handle Redis cache exceptions. This allows you to fall back to calling the original function or logging exceptions. Function has the following signatureexception_handler(exception: Exception, function: Callable, args: List, kwargs: Dict) -> Any. If using this handler, reraise the exception in the handler to stop execution of the function. All return results will be used even ifNone. If handler not defined, it will raise the exception and not call the original function.
Package: python-redis-log
A logging handler for Python that publishes log messages using redis’s
pub/sub system.  You can use this to read or respond to streaming log
data in real time.InstallationThe current stable releaseeasy_install python-redis-logThe latest fromgithubgit clone git://github.com/jedp/python-redis-log.git
cd python-redis-log
python setup.py build
python setup.py install --prefix=$HOME  # for exampleRequirementsredisThePython redis clientby Andy McCurdysimplejsonUsage>>> from redislog import handlers, logger
>>> l = logger.RedisLogger('my.logger')
>>> l.addHandler(handlers.RedisHandler.to("my:channel"))
>>> l.info("I like pie")
>>> l.error("Trousers!", exc_info=True)Redis clients subscribed tomy:channelwill get a json log record like the
following (sent from functionfoo()in filetest.py:{ username: 'jed',
  args: [],
  name: 'my.logger',
  level: 'info',
  line_no: 6,
  traceback: null,
  filename: 'test.py',
  time: '2011-06-02T14:50:08.237052',
  msg: 'winning',
  funcname: 'foo',
  hostname: 'smoothie.local' }If an exception is raised, andexc_infoisTrue, the log will include
a formatted traceback intraceback.The date is stored as an ISO 8601 string in GMT.You can use theredis-clishell that comes withredisto test this.  At
the shell prompt, typesubscribe my:channel(replacing with the channel
name you choose, of course).  You will see subsequent log data printed in the
shell.Serving SuggestionRedis pub/sub messages are not persistent; they are just messages.  So you will
probably wish to use this handler in conjunction with other handlers that
actually save your data, like the standard python FileHandlers, or
Andrei Savu’sMongoDB logging handler.ContributorsYannis Leidel
Package: python-redis-rate-limit
This lib offers an abstraction of a Rate Limit algorithm implemented on top of
Redis >= 2.6.0.Supported Python Versions: 2.7, 3.5+Example: 10 requests per secondfromredis_rate_limitimportRateLimit,TooManyRequeststry:withRateLimit(resource='users_list',client='192.168.0.10',max_requests=10):return'200 OK'exceptTooManyRequests:return'429 Too Many Requests'Example: using as a decoratorfromredis_rate_limitimportRateLimit,TooManyRequests@RateLimit(resource='users_list',client='192.168.0.10',max_requests=10)deflist_users():return'200 OK'try:returnlist_users()exceptTooManyRequests:return'429 Too Many Requests'Example: 600 requests per minutefromredis_rate_limitimportRateLimit,TooManyRequeststry:withRateLimit(resource='users_list',client='192.168.0.10',max_requests=600,expire=60):return'200 OK'exceptTooManyRequests:return'429 Too Many Requests'Example: 100 requests per hourfromredis_rate_limitimportRateLimit,TooManyRequeststry:withRateLimit(resource='users_list',client='192.168.0.10',max_requests=100,expire=3600):return'200 OK'exceptTooManyRequests:return'429 Too Many Requests'Example: you can also setup a factory to use it laterfromredis_rate_limitimportRateLimiter,TooManyRequestslimiter=RateLimiter(resource='users_list',max_requests=100,expire=3600)try:withlimiter.limit(client='192.168.0.10'):return'200 OK'exceptTooManyRequests:return'429 Too Many Requests'Example: you can also pass an optional Redis Poolimportredisfromredis_rate_limitimportRateLimit,TooManyRequestsredis_pool=redis.ConnectionPool(host='127.0.0.1',port=6379,db=0)try:withRateLimit(resource='users_list',client='192.168.0.10',max_requests=10,redis_pool=redis_pool):return'200 OK'exceptTooManyRequests:return'429 Too Many Requests'