package
stringlengths
1
122
pacakge-description
stringlengths
0
1.3M
ztz
Failed to fetch description. HTTP Status Code: 404
zu
zuUseful Layers for Data Access
zuanfeng
zuanfeng captain sdk for python
zubbi
The Zuul Building Blocks Index (aka Zubbi) makes it easy to search for available jobs and roles ("Building Blocks") within aZuulbased CI system - even if they are spread over multiple tenants or repositories.Contents:Architecture|Quickstart|Development|Scraper usage|Configuration Examples|Available Connections|ArchitectureZubbi consists of two parts,zubbi webandzubbi scraper. It usesElasticsearchas storage backend and needsGit repositoriesas source for job and role definitions.Zubbi webA web frontend based on Flask that reads the data from Elasticsearch. It allows searching for roles and jobs used within the CI system and shows the results including their documentation, last updates, changelog and some additional meta data.Zubbi scraperA Python application that scrapes Git repositories, searches for job and role definitions in specific files and stores them in Elasticsearch.QuickstartPrerequisites:Docker ComposeZubbi can simply be started by using the provideddocker-compose.yamlfile.NOTEThe providedDockerfileshould only be used for demonstration purposes and not in a production system. Flask is running in development mode and listens on all public IPs to make it reachable from outside the docker container.To get the whole stack up and running, do the following:$cddocker $docker-composebuild $docker-composeupThis will build the docker container with the newest Zubbi version, start all necessary services (Elasticsearch, zubbi-scraper, zubbi-web) and does a full scrape of theopenstack-infra/zuul-jobsrepository to get an initial set of data.When everything is up, you can visithttp://localhost:5000and explore the jobs and roles from theopenstack-infra/zuul-jobsrepo.DevelopmentPrerequisites: Python 3.6,ToxandPipenvinstalled.To install necessary dependencies for development, run:$pipenvshell $pipenvinstall--devWe are usingblackto ensure well-formatted Python code. To automatically ensure this on each commit, you can use the included pre-commit hook. To install the hook, simply run:$pre-commitinstallBefore submitting pull requests, run tests and static code checks using tox:$toxInstalling & updating dependenciesNew dependencies should be added to therequireslist in thesetup.pyfile:requires=["arrow","click",...,"<new dependency>",]Afterwards, run the following command to update thePipfile.lockand install the new dependencies in your local pipenv environment:$pipenvupdateTest dependencies should be installed as development dependencies:$pipenvinstall--devmy-test-dependencyTo update the dependencies to the latest version or after a new dependency was installed you have to runtox -e update-requirementsand commit the changed Pipenv and requirements files.Configuring and starting ZubbiIf you followed theDevelopmentguide so far, you should already have a virtual environment with all required packages to run Zubbi. What's left, are a few configuration files and a local Elasticsearch instance for testing.ElasticsearchZubbi is currently depending on Elasticsearch as data backend. If you haveDocker Composeinstalled, you can use the provideddocker-compose.yamlfile to start Elasticsearch locally.$cddocker $docker-composeupelasticsearchIf not, we recommend to use the latest available Elasticsearch Docker image, to get a local instance up and running for development.ConfigurationBoth - Zubbi scraper and Zubbi web - read their configuration from the file path given via theZUBBI_SETTINGSenvironment variable:$exportZUBBI_SETTINGS=$(pwd)/settings.cfgIn order to show jobs and roles in Zubbi, we need to provide a minimaltenant configurationcontaining at least a single repository (which is used as source). Therefore, put the following in atenant-config.yamlfile:-tenant:name:openstacksource:openstack-gerrit:untrusted-projects:-openstack-infra/zuul-jobsPut the following in yoursettings.cfgto allow scraping based on the tenant configuration above and store the results in the local Elasticsearch instance. Please note, that the key in theCONNECTIONSdictionary must go in hand with thesourcenames in the tenant configuration.ELASTICSEARCH={'host':'localhost','port':9200,}TENANT_SOURCES_FILE='tenant-config.yaml'CONNECTIONS={'openstack-gerrit':{'provider':'git','git_host_url':'https://git.openstack.org',},}Running ZubbiNow we can scrape theopenstack-infra/zuul-jobsrepository to get a first set of jobs and roles into Elasticsearch and show them in Zubbi:$zubbi-scraperscrape--fullWhen the scraper run was successful, we can start Zubbi web to take a look at our data:$exportFLASK_APP=zubbi $exportFLASK_DEBUG=true$flaskrunBuilding the syntax highlighting stylesheet with pygmentsWe are using a pre-build pygments stylesheet to highlight the code examples in job and roles documentations. In case you want to rebuild this syntax highlighting stylesheet (e.g. to try out another highlighting style) you can run the following command:$pygmentize-Sdefault-fhtml-a.highlight>zubbi/static/pygments.cssScraper usageThe Zubbi scraper supports two different modes:periodic(default) andimmediate. To start the scraper in periodic mode, simply run:$zubbi-scraperscrapeThis should also scrape all repositories specified in the tenant configuration for the first time.To immediately scrape one or more repositories, you can use the following command:# Scrape one or more repositories$zubbi-scraperscrape--repo'orga1/repo1'--repo'orga1/repo2'# Scrape all repositories$zubbi-scraperscrape--fullAdditionally, the scraper provides alist-reposcommand to list all available repositories together with some additional information like the last scraping timestamp and the git provider (connection type):$zubbi-scraperlist-reposConfiguration examplesExamples for all available settings can be found insettings.cfg.example.Tenant ConfigurationZubbi needs to know which projects contain the job and role definitions that are used inside the CI system. To achieve this, it uses Zuul'stenant configuration. Usually, this tenant configuration is stored in a file that must be specified in thesettings.cfg, but it could also come from a repository.# Use only one of the following, not bothTENANT_SOURCES_FILE='<path_to_the_yaml_file>'TENANT_SOURCES_REPO='<orga>/<repo>'Elasticsearch ConnectionThe Elasticsearch connection can be configured in thesettings.cfglike the following:ELASTICSEARCH={'host':'<elasticsearch_host>','port':9200,# default'user':'<user>','password':'<password>',# Optional, to avoid name clashes with existing ES indices from other applications# E.g. 'zubbi' will result in indices like 'zubbi-zuul-jobs', 'zubbi-ansible-roles', ...index_prefix:'<prefix>',# Optional, to enable SSL for the Elasticsearch connection.# You must at least set 'enabled' to True and provide other parameters if the default# values are not sufficient.'tls':{'enabled':False,# default'check_hostname':True,# default'verify_mode':'CERT_REQUIRED',# default},}Available ConnectionsCurrently, Zubbi supports the following connection types:GitHub,GerritandGit. The latter one can be used for repositories that are not hosted on either GitHub or Gerrit.GitHubThe GitHub connection uses GitHub's REST API to scrape the repositories. To be able to use this connection, you need to create a GitHub App with the following permissions:Repository contents:Read-onlyRepository metadata:Read-onlyIf you are unsure about how to set up a GitHub App, take a look at theofficial guide.Once you have successfully created your GitHub App, you can define the connection with the following parameters in yoursettings.cfgaccordingly:CONNECTIONS={'<name>':{'provider':'github','url':'<github_url>','app_id':<your_github_app_id>,'app_key':'<path_to_keyfile>',},...}Using GitHub WebhooksGitHub webhooks can be used to keep your Zubbi data up to date. To activate GitHub webhooks, you have to provide a weebhook URL pointing to the/api/webhookendpoint of your Zubbi web installation. The generated webhook secret must be specified in theGITHUB_WEBHOOK_SECRETsetting in yoursettings.cfg:NOTE:As of now, GitHub webhooks are not supported on a per-connection base. You can only have one webhook active in zubbi.GITHUB_WEBHOOK_SECRET='<secret>'Zubbi web receives webhook events from GitHub, validates the secret and publishes relevant events to the scraper viaZMQ. The Zubbi scraper on the other hand subscribes to the ZMQ socket and scrapes necessary repositories whenever a event is received. In order to make this communication work, you need to specify the following parameters in yoursettings.cfg:# Zubbi web (publish)ZMQ_PUB_SOCKET_ADDRESS='tcp://*:5556'# Zubbi scraper (subscribe)ZMQ_SUB_SOCKET_ADDRESS='tcp://localhost:5556'GerritIn contrary to GitHub, the Gerrit connection is based onGitPythonas the Gerrit REST API does not support all use cases. To use this connection, you have to provide the following parameters in yoursettings.cfg:CONNECTIONS={'<name>':{'provider':'gerrit','url':'<git_remote_url>',# Only necessary if different from the git_remote_url'web_url':'<gerrit_url>',# The web_type is necessary to build the correct URLs for Gerrit.# Currently supported types are 'cgit' (default) and 'gitweb'.'web_type':'cgit|gitweb',# Optional, if authentication is required'user':'<username>','password':'<password>',},...}GitThe Git connection is also based onGitPythonand can be used for Git repositories that are not hosted on either GitHub or Gerrit. To use this connection, put the following in yoursettings.cfg:CONNECTIONS={'<name>':{'provider':'git','url':'<git_host_url>',# Optional, if authentication is required'user':'<username>','password':'<password',},...}Happy coding!
zubie-api
zubie-python-apiZubie API for Python
zubr-temp
Zubr exchange SDKSimple exampleimportloggingfrompprintimportpprintfromzubrimportZubrSDK,OrderType,TimeInForcezubr_sdk=ZubrSDK(api_key='YOUR-API-KEY-HERE',api_secret='YOUR-API-SECRET-HERE',)logging.basicConfig(level=logging.INFO)context={'order_placed':False,'sell_price':'0',}defsell_and_cancel(message):print(f'order placed:{message}')order_id=message['result']['value']# Cancel orderzubr_sdk.cancel_order(order_id=order_id,callback=lambdax:(print(f'Order cancelled:{x}')),)defsell_and_replace(message):print(f'order placed:{message}')order_id=message['result']['value']# Replace orderzubr_sdk.replace_order(order_id=order_id,price=context['sell_price'],size=2,callback=lambdax:(print(f'Order replaced:{x}')),)# Fetch orderbook@zubr_sdk.subscribe_orderbookdefon_orderbook(message):print('orderbook:')pprint(message)ifcontext['order_placed']:returninstrument_id,orders=list(message['value'].items())[0]sell_price=max(x['price']forxinorders['asks'])context['sell_price']=sell_price# Place and replacezubr_sdk.sell(instrument_id=instrument_id,price=sell_price,size=1,order_type=OrderType.LIMIT,time_in_force=TimeInForce.GTC,callback=sell_and_replace,)# Place and cancelzubr_sdk.sell(instrument_id=instrument_id,price=sell_price,size=1,order_type=OrderType.LIMIT,time_in_force=TimeInForce.GTC,callback=sell_and_cancel,)context['order_placed']=True# Fetch last trades@zubr_sdk.subscribe_last_tradesdefon_last_trades(message):print('last trades:')pprint(message)zubr_sdk.run_forever()
zuby-test-dsnd-distributions
No description available on PyPI.
zucchini
ZucchiniZucchini is an automatic grader tool for use in grading programming assignments.Free software: Apache Software License 2.0Documentation:https://zucchini.readthedocs.io.Installation$ pip install --user zucchini $ zucc --helpGetting Started with DevelopmentAfter cloning this repo and installing virtualenv, run$ virtualenv -p python3 venv $ . venv/bin/activate $ pip install -r requirements.txt $ pip install -r requirements_dev.txt $ zucc --helpFeaturesUnified grading infrastructure: eliminates maintenance load of ad-hoc per-assignment gradersSeparates test results from computed grades: graders provide test results which are stored on disk, and then zucchini calculates grade based on the weight of each test. That is, graders do not perform grade calculation; they only gather information about students’ workSimple configuration: update one YAML file and store your graders in git repositories for all your TAsRelative weighting: no more twiddling with weights to get them to add up to 100Import submissions from Gradescope, Canvas Assignments, or Canvas QuizzesNo more copy-and-pasting grades and commments: automated upload of Canvas grades and gradelogsFlatten (extract) archived submissionsGradescope integration: generate a Gradescope autograder tarball for an assignment with one commandCreditsAustin Adams (@ausbin) for creating lc3grade, which eventually became zucchiniCem Gokmen (@skyman) for suggesting converting lc3grade into a generalized autograder for more than just C and LC-3 homeworks, and creating the initial structure of zucchiniPatrick Tam (@pjztam) for implementing a bunch of graders, gradelogs, and gradelog uploadKexin Zhang (@kexin-zhang) for exploring Canvas bulk submission downloads and for creating the demo downloader, which changed our livesTravis Adams (@travis-adams) for nothingHistory0.1.0 (2017-12-17)First release on PyPI.
zucked
zucked: analyze your Facebook Messenger dataWhat is it?zucked is a quick and easy way to veiw your facebook messenger data.Main FeaturesEasy viewing of your most used words on Facebook MessengerSee another facebook users most sent words to youCheck the amount of messages you have sent a person or groupSearch a word or phrase that you might have sent or recieved to see: The message the word or phrase was in, as well as who sent it and when the message was sentInstallThe source code is currently hosted on GitHub at:https://github.com/Jordan-Milne/zuckedThe latest released version is available at thePython package index (PyPI)pip install zuckedTutorialDownlaod your Facebook Messenger data (How to)When choosing file type make sure it is JSON and not HTMLCreate a python file in thesame directoryas the "inbox" folder from your download -not insidethe inbox folderImportTo import zucked, type:import zucked as zdread_messagessaveread_messagesas a variable, which we will be calling methods on later.Example:ms = zd.read_messagestop_words()calltop_words(facebook_name, stop_words=True, period='all time')onmsto return an ordered list of the most common words the user sent and how many times they sent it:This method works for top words you have sentandtop words you have recieved from a certain userExample:ms.top_words('Jordan Milne')Returns:[('I', 3), ('love', 2), ('data', 1)]If you want stop words filtered out, (what are stop words) and just the top words for a certain year then the method would simply be:ms.top_words('Jordan Milne', stop_words=False, period='2016')top_convoscalltop_convos(facebook_name)onmsto return an ordered list of the name(s) of the person or group and the amount of messages you sent to that person or group:Example:ms.top_convos('Jordan Milne')Returns:[('User 1', 33), ('User 2', 21)]If you want the top conversations for a certain year then the method would simply be:ms.top_words('Jordan Milne', period='2016')search_messages()callsearch_messages(facebook_name, value)onmsto return a list that has the full message containing the word or phrase input asvalue, who the message was sent to, and the date and time the message was sent.Example:ms.search_messages('Jordan Milne', 'hello')Returns:[{'Message': 'I'm sorry but, hello world', 'Sent to': 'Auston Matthews', 'Date': '2019-06-09 11:46:54'}]This method works for messages you have sentandmessages you have recieved from a certain userformat_top_words()callformat_top_words(facebook_name, input_list, year)onmsto return a nested dictionary with the year and counts of the list of words that the user inputs that is specifically formatted for plotting.Example:ms.format_top_words('Jordan Milne', ['Matthews','Tavares','Marner','Andersen'], '2019')Returns:{'2019': {'Matthews': 75, 'Andersen': 70, 'Marner': 17, 'Tavares': 10}}Now for the fun part. If you want to see how often you used your top 5 all time words each year it can be done in a few simple steps.Get all years into the same dictionary using this for loop:example={} for i in range(2010,2021): example.update(ms.format_top_words('Jordan Milne',['Matthews','Tavares','Marner','Andersen'], str(i)))Now that we have the data collected and organized we are ready to plot:import matplotlib.pyplot as plt # get inner keys inner_keys = list(example.values())[0].keys() # x-axis is the outer keys x_axis_values = list(example.keys()) # loop through inner_keys plt.title("Facebook Messenger Word Count") plt.xlabel("Year") plt.ylabel("Count"); for x in inner_keys: # create a list of values for inner key y_axis_values = [v[x] for v in example.values()] # plot each inner key plt.plot(x_axis_values, y_axis_values, label=x) plt.legend()The ouput should look like:
zucker
ZuckerZucker is a Python library forSugar CRMwith a simple, readable API. Features:No dependencies (except for an HTTP client of your choice)Native support for both synchronous andasyncioparadigmsSchema introspection that extracts supported fields from a Sugar server to speed up developmentORM-like feel that abstracts away details of the upstream APIFully type-checked (internal and external code)To get started, have a look at theDocumentation. If you find that something is missing, feel free to open an issue.What does it look like?First, connect to a Sugar server. Then you can define a model that matches what you have on the backend (use theintrospection featuresto speed up this process!):fromzuckerimportmodel,RequestsClientcrm=RequestsClient("https://crm.example.com","zucker","password")classContact(model.SyncModule,client=crm,api_name="Contacts"):lead_source=model.StringField()phone_work=model.StringField()contacts=Contact.find(Contact.lead_source=="Word of mouth")forcontactincontacts:print(contact.phone_work)print(",".join(contact.phone_workforcontactincontacts[:3]))Again, see theDocumentationfor more examples.IntrospectionZucker also supports introspecting a server, which will list the available modules and fields. Use it like this:$python-mzucker.codegen-b"https://crm.example.com"-u"username"-c"my_client"-PinspectSeepython -m zucker.codegen --helpfor detailed usage information.LicenseMIT
zuckup
zuckup ======simple facebook parsingInstallpip install zuckupTestRequiresnosenosetestsUsagezuckupcomes with three utilities:insights,page, andpage_statsInsightsNOTE: To get facebook insights data you must first have an access token that has necessary credentials to view this data.importzuckupforpost_statsinzuckup.insights(page_id='authenticated_page'):printpost_statsPage Postsimportzuckupforpostinzuckup.page(page_id='nytimes')printpostPage Statsimportzuckuppage_stats=zuckup.page_stats(page_id='nytimes')printpage_statsAuthenticationzuckupwill automatically connect to the facebook api viafacepyif you haveFB_APP_IDandFB_APP_SECRETset as environmental variables.Alternatively, you can connect beforehand and pass in this connection via the kwargconn:importzuckupconn=zuckup.connect(app_id='12345',app_secret='678910')page_stats=zuckup.page_stats(page_id='nytimes',conn=conn)printpage_statsFinally, if you want to connect with just an access token, say one acquired from a user authenticating to your app, pass inaccess_tokento any of the methods:importzuckuppage_stats=zuckup.page_stats(page_id='nytimes',access_token='a-users-access-token')printpage_statsPaginationpaginate through results usingpaginatewithinsightsandpage:for post in zuckup.page(page_id='nytimes', paginate=True) print postConcurrencyoptional concurrency forinsightsandpageviagevent:import zuckup for post in zuckup.page(page_id='nytimes', concurrent=True) print post
zuds
No description available on PyPI.
zuel-test
jieba“结巴”中文分词:做最好的 Python 中文分词组件“Jieba” (Chinese for “to stutter”) Chinese text segmentation: built to be the best Python Chinese word segmentation module.完整文档见README.mdGitHub:https://github.com/fxsjy/jieba特点支持三种分词模式:精确模式,试图将句子最精确地切开,适合文本分析;全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。支持繁体分词支持自定义词典MIT 授权协议在线演示:http://jiebademo.ap01.aws.af.cm/安装说明代码对 Python 2/3 均兼容全自动安装:easy_install jieba或者pip install jieba/pip3 install jieba半自动安装:先下载https://pypi.python.org/pypi/jieba/,解压后运行 python setup.py install手动安装:将 jieba 目录放置于当前目录或者 site-packages 目录通过import jieba来引用
zufaelliger
To use (with caution), simply do:>>> import zufaelliger >>> print zufaelliger.joke()
zufallsworte
No description available on PyPI.
zugbruecke
zugbrueckeCalling routines in Windows DLLs from Python scripts running under Linux, MacOS or BSD/ˈt͡suːkˌbʁʏkə/ (German, noun, feminine: drawbridge)Synopsiszugbrueckeis an EXPERIMENTALPython package(currently in developmentstatus 3/alpha). It allows tocall routines in Windows DLLs from Python code running on Unices / Unix-like systemssuch as Linux, MacOS or BSD.zugbrueckeis designed as adrop-in replacement for Python's standard library's ctypes module.zugbrueckeisbuilt on top of Wine. A stand-alone Windows Python interpreter launched in the background is used to execute the called DLL routines. Communication between the Unix-side and the Windows/Wine-side is based on Python's build-in multiprocessing connection capability.zugbrueckehas (limited) support for pointers, struct types and call-back functions.zugbrueckecomes with extensive logging features allowing to debug problems associated with both itself and with Wine.zugbrueckeis written usingPython 3 syntaxand primarily targets theCPythonimplementation of Python.About Wine (fromwinehq.org):Wine (originally an acronym for "Wine Is Not an Emulator") is a compatibility layer capable of running Windows applications on several POSIX-compliant operating systems, such as Linux, MacOS and BSD. Instead of simulating internal Windows logic like a virtual machine or emulator, Wine translates Windows API calls into POSIX calls on-the-fly, eliminating the performance and memory penalties of other methods and allowing you to cleanly integrate Windows applications into your desktop.This project is NEITHER associated NOR affiliated in any way or form with the Wine project.PrerequisitestypeprerequisiteversionuserCPython3.x (tested with 3.{7,8,9,10,11})userWine>= 6.x (tested with regular &staging) - expected to be in the user'sPATHdevelopermingw cross-compilerFor building DLLs against which examples and tests can be run. Latest stable release.Installationbranchstatusinstallationdocumentationmaster (release)pip install zugbrueckedeveloppip install git+https://github.com/pleiszenburg/zugbruecke.git@developAfter installing the package withpip, you may choose to manually initialize theWine Python environmentby runningwenv init. If you choose not to do this,zugbrueckewill take care of it during its first use.ExampleStart an interactive Python session on your favorite Unix(-like) operating system and try the following:importzugbruecke.ctypesasctypesdll_pow=ctypes.cdll.msvcrt.powdll_pow.argtypes=(ctypes.c_double,ctypes.c_double)dll_pow.restype=ctypes.c_doubleprint(f'You should expect "1024.0" to show up here: "{dll_pow(2.0,10.0):.1f}".')You have just witnessedmsvcrt.dll, Microsoft's C standard library (or Wine's implementation of it), in action on Unix.Interested in more?Check theGetting Startedsection inzugbruecke's documentation,Readctypes' documentation,Beyondctypessyntax, learn aboutmemory synchronizationwith thememsyncroutine attribute (or)Have a look atzugbruecke'stest suiteshowcasing its entire range of capabilities.A lot of code, which was written withctypes'cdll,windlloroledllin mind and which runs under Windows, should run just fine withzugbrueckeon Unix (assuming it does not use Windows features not supported by Wine). For more complex calls,memory synchronizationis potentially necessary.Speedzugbrueckeperforms reasonably well given its complexity witharound 0.15 ms overhead per simple callon average on modern hardware. For significantly more complex calls, the overhead can go into several milliseconds.zugbrueckeis not (yet) optimized for speed. Check the latestbenchmarksfor more details.Securityzugbrueckeisnotoriously insecure. Never, ever, run it with root / super users privileges! Do not use it where security matters! For details, check the section onsecurityin the documentation.Need help?See section onGetting Helponzugbruecke's documentation.Bugs & IssuesSee section onBugs and Issuesonzugbruecke's documentation.MiscellaneousFull project documentationatRead the DocsatzugbrueckerepositoryAuthorsChange log (current)(changes in development branch since last release)Change log (past)(release history)Contributing(Contributions are highly welcomed!)FAQLicense(LGPL v2.1)Long-term ideasMissing features(for full ctypes compatibility)Upstream issues(relevant bugs in dependencies)For production environmentsDO NOT run this code (as-is) in production environments unless you feel that you really know what you are doing (or unless you are absolutely desperate)! Being experimental in nature and of alpha quality, it is prone to fail in a number of unpredictable ways, some of which might not be obvious or might not even show any (intermediately) recognizable symptoms at all! You might end up with plain wrong, nonsensical results without noticing it! Verify and cross-check your results!zugbrueckeis usingsemantic versioning. Breaking changes are indicated by increasing the second version number, the minor version. Going for example from 0.0.x to 0.1.y or going from 0.1.x to 0.2.y therefore indicates a breaking change. For as long aszugbrueckehas development status "alpha", please expect more breaking changes to come.If you are relying onzugbrueckein one way or another, please consider monitoring the project:its repository on Github,its mailing listandits chatroom.
zugexianshi
UNKNOWN
zugh
Zugh[WIP] Access to database in pythonic wayZughStatusRequiredLicenceInstallUsageConnectionConfigPoolDatabaseTableQuery ObjectInsertInsert a RowInsert IgnoreInsert Or UpdateInsert Multi RowsSelectFilterLogic ExpressCompareAliasSortLimitAggregateDistinctSubqueryJoin InUnionUpdateF ObjectDeleteDecoratordb.query.querydb.query.transactionStringS ObjectMathZughis a tool for generating SQL and accessing databases flexibly in pythonic way. It empower you to use complex SQL, but didn't need to write them directly.StatusWork in progress.Now we support MySQL only.RequiredPython >= 3.6PyMySQL >= 0.9.3LicenceMIT.InstallUse pip:pipinstallzughUsageNote !The time of writing each part of this document is out of order. So the results before and after the execution of SQL may not match. Nevertheless, I recommend that you start reading from scratch and try the code.ConnectionConfig>>>fromzugh.db.connectionimportconnect_config>>>conn_config=connect_config('localhost','your_username','your_password')# You can use conn_config dict to configure connection for DdataBase object# or initial a connection poolPool>>>fromzugh.db.poolimportConnectionPool>>>pool=ConnectionPool(conn_config)DatabaseCreate a database:>>>fromzugh.schema.dbimportDataBase>>>db=DataBase('zugh',conn_config=conn_config)# or db = DataBase('zugh', pool=pool)>>>db.create()TableCreate a table.We haven't implemented those APIs to create a table yet, so just execute SQL with a connection:>>>fromzugh.dbimportconnect>>>sql="""CREATE TABLE zugh.users (`id` int(11) NOT NULL AUTO_INCREMENT,`age` int(11) NOT NULL,`score` int(11) NOT NULL DEFAULT '0',PRIMARY KEY (`id`)) Engine=InnoDB DEFAULT CHARSET=utf8mb4;""">>>conn=connect(conn_config)# return a connection context>>>withconnascn:withcn.cursor()ascursor:cursor.execute(sql)Initial aTableobject:>>>fromzugh.schema.tableimportTable>>>tb=Table('users',db)Query Objectzugh.query.core.QueryBaseprovide a base class for Query class below:zugh.query.core.SelectBasezugh.query.core.Updatezugh.query.core.Insertzugh.query.core.Deleteor subclass of above classQuery objectis a instance of above class. If they were printed, a string of SQL statement would output.If configure properly, they can call.exe()method to execute. Usually, you don't use them directly.Mostly, you would initial azugh.schema.table.Tableinstance and call relative method, then will return a newQuery object.Dangerous queries, such asupdate,deleteor similar mothed are expose afterTable.where()method.>>>q_1=tb.where().select()>>>type(q_1)<class'zugh.query.core.Select'>>>>q_2=tb.where().update(age=10)>>>type(q_2)<class'zugh.query.core.Update'>>>>q_3=tb.where().delete()>>>type(q_3)<class'zugh.query.core.Delete'>>>>q_4=tb.insert(dict(age=10,score=18))>>>type(q_4)<class'zugh.query.core.Insert'>>>>q_5=q_1.order_by()>>type(q_5)<class'zugh.query.core.OrderBy'>InsertInsert a Row>>>q1=tb.insert(age=16,score=7)>>>print(q1)INSERTINTOzugh.users(age,score)VALUES(16,7)>>>q2=tb.where().select()>>>print(q2)SELECT*FROMzugh.users>>>q2.exe()# execute q2((),0)>>>q1.exe()# execute q11>>>q2.exe()# execute q2 again(((1,16,7),),1)Insert Ignore>>>q3=tb.insert_ignore(id=1,age=16,score=7)>>>print(q3)INSERTIGNOREINTOzugh.users(id,age,score)VALUES(1,16,7)>>>q3.exe()# would show a duplicate key warningInsert Or UpdateYou can useFobject orvaluesobject to complete complex query.fromzugh.query.othersimportF,values>>>row=dict(id=1,age=16,score=7)>>>q4=tb.upsert(row,dict(age=9))>>>print(q4)INSERTINTOzugh.users(id,age,score)VALUES(1,16,7)ONDUPLICATEKEYUPDATEage=9>>>update_fv=dict(age=F('age')-1,score=values('age')+1)>>>q5=tb.upsert(row,update_fv=update_fv)>>>print(q5)INSERTINTOzugh.users(id,age,score)VALUES(1,16,7)ONDUPLICATEKEYUPDATEage=age-1,score=VALUES(age)+1Insert Multi Rows>>>rows=[dict(age=9,score=8),dict(age=7,score=9),dict(age=17,score=7),dict(age=23,score=7),]>>>q6=tb.insert_multi(rows)>>>print(q6)INSERTINTOzugh.users(age,score)VALUES(9,8),(7,9),(17,7),(23,7)>>>q6.exe()# execute q64>>>q2.exe()(((1,16,7),(2,9,8),(3,7,9),(4,17,7),(5,23,7)),5)Select>>>q7=tb.where(id=3).select()>>>print(q7)SELECT*FROMzugh.usersWHEREid=3>>>q7.exe()(((3,7,9),),1)>>>q8=tb.where().select('id','age')>>>print(q8)SELECTid,ageFROMzugh.users>>>q8.exe()(((1,16),(2,9),(3,7),(4,17),(5,23)),5)By default, when call.exe()of Select Query, it will return atuplewhich contain queryset and number of rows. The format of queryset format is stilltuple. If you prefer a dict-format queryset, you should pass a parametercursorclass=pymysql.cursors.DictCursorto configure connection. For more infomation, please refer docs ofPyMySQL.FiltertheTable.where()method of Table instance act as a filter.If don't need to filter table, You can callTable.select()directly. It is a shortup ofTable.where().select().Logic Express>>>fromzugh.query.logicimportAND,OR,L>>>q9=tb.where('id>3','id<7').select()>>>print(q9)SELECT*FROMzugh.usersWHEREid>3ANDid<7>>>q9.exe()(((4,17,7),(5,23,7)),2)>>>w1=L('id<3')|L('id>7')# equal to OR('id<3', 'id>7')>>>w2=OR('id<3','id>7')>>>w1OR(L(id<3),L(id>7))>>>w2OR(L(id<3),L(id>7))>>>print(w1)id<3ORid>7>>>print(w2)id<3ORid>7>>>q10=tb.where(w2).select()>>>print(q10)SELECT*FROMzugh.usersWHERE(id<3ORid>7)>>>q10.exe()(((1,16,7),(2,9,8)),2)# you can combine complex Logic object use L, OR and AND>>>w3=L('id>3')&L('id<7')# equal to AND('id>3', 'id<7')>>>print(w3)id>3ANDid<7>>>w4=L('age>3')&L('age<20')>>>print(w4)age>3ANDage<20>>>print(OR(w3,w4))(id>3ANDid<7)OR(age>3ANDage<20)>>>print(w3|w4)(id>3ANDid<7)OR(age>3ANDage<20)CompareWe use class or their instance to deal with compare express.You can find them inzugh.query.conditionmodule.SQL OperatorPython Class/Instance/Operatorexample=eq,=.where(name='lisa')!=ne.where(name=ne('lisa'))>gt.where(amount=gt(9))>=ge.where(amount=ge(9))<lt.where(amount=lt(6))<=le.where(amount=le(5))INIn.where(id=In(1,2,3,4))NOT INNIn.where(id=NIn(98,34,2))LIKElike.where(name=like('lisa%'))NOT LIKEunlike.where(name=unlike('john%'))IS NULLNULL.where(age=NULL)IS NOT NULLNOT_NULL.where(age=NOT_NULL)Though works,eqis meaningless. For convenience, you would always use=.>>>fromzugh.query.conditionimportNOT_NULL,NULL,In,NIn,ge,gt,le,like,lt,ne,unlike>>>q11=tb.where(id=gt(3)).select()>>>print(q11)SELECT*FROMzugh.usersWHEREid>3>>>q12=tb.where(id=gt(3),age=lt(18)).select()>>>print(q12)SELECT*FROMzugh.usersWHEREid>3ANDage<18>>>q12.exe()(((4,17,7),),1)>>>q13=tb.where(id=In(1,3,5,7,9)).select('id','score')>>>print(q13)SELECTid,scoreFROMzugh.usersWHEREidIN(1,3,5,7,9)>>>q13.exe()(((1,7),(3,9),(5,7)),3)>>>q14=tb.where(score=NULL).select()>>>print(q14)SELECT*FROMzugh.usersWHEREscoreISNULLAlias>>>fromzugh.query.othersimportAs>>>fromzugh.query.aggregateimportMax>>>qa=tb.where().select(max_age=Max('age'))>>>print(qa)SELECTmax(age)ASmax_ageFROMzugh.users>>>print(tb.where().select(As(Max('age'),'max_age')))SELECTmax(age)ASmax_ageFROMzugh.usersWe support alias, but the defaultcursorclassof PyMySQL will return query set in tuple. In this case, alias is useless. If you want to return dict, you need to configure connection parametercursorclass=pymysql.cursors.DictCursor. For more information, please refer PyMySQL's documents.Sort>>>q15=tb.where().select().order_by('age')>>>print(q15)SELECT*FROMzugh.usersORDERBYage>>>q15.exe()(((3,7,9),(2,9,8),(1,16,7),(4,17,7),(5,23,7)),5)# You can use prefix '-' to sort reverse.>>>q16=tb.where().select().order_by('-age','score')>>>print(q16)SELECT*FROMzugh.usersORDERBYageDESC,score>>>q16.exe()(((5,23,7),(4,17,7),(1,16,7),(2,9,8),(3,7,9)),5)LimitWe use a magicalsliceto act limit/offset,Select Query' slice will return a instance ofzugh.query.core.Limit, which is a subclass ofzugh.query.core.SelectBase.>>>qm=tb.where().select()>>>qm1=qm[:3]# fetch frist three>>>print(qm1)SELECT*FROMzugh.usersLIMIT3>>>qm2=qm[2:4]>>>print(qm2)SELECT*FROMzugh.usersLIMIT2,2>>>qm3=qm[2:]>>>print(qm3)SELECT*FROMzugh.usersLIMIT2,18446744073709551614Except for instances ofLimit, all the others instance ofSelectBasecould use slice to return a instance ofLimit.The slice here don't accept negative numbers.AggregateWe provide some aggregation functions inzugh.query.aggregatemoulde.>>>fromzugh.query.aggregateimportAvg,Count,Max,Min,Sum>>>q17=tb.where().select(Avg('age'))>>>print(q17)SELECTavg(age)FROMzugh.users>>>q17.exe()(((Decimal('14.4000'),),),1)>>>q18=tb.where().select('score',Count('id')).group_by('score')>>>print(q18)SELECTscore,count(id)FROMzugh.usersGROUPBYscore>>>q18.exe()(((7,3),(8,1),(9,1)),3)You can also use write 'raw' functions as long as you like it, such as:q17=tb.where().select('avg(age)')Distinctfromzugh.query.othersimportdistinct>>>q19=tb.where().select('distinct age','score')>>>print(q15)SELECTdistinctage,scoreFROMzugh.users>>>q19.exe()(((16,7),(9,8),(7,9),(17,7),(23,7)),5)>>>q20=tb.where().select(distinct('age'),'score')>>>print(q20)SELECTDISTINCTage,scoreFROMzugh.users>>>q21=tb.where().select(Count(distinct('age')))>>>print(q21)SELECTcount(DISTINCTage)FROMzugh.usersSubqueryAt present,InandNInexpress support subquery, it could accept a instance ofSelectBaseas a parameter.But they can not accept instance ofzugh.schema.table.TempTableas a parameter.TempTableaccept aSelect Queryas frist parameter and a alias string as second parameter. It would act like a normal read-only table, you could join it with others, or query data as a new instanceTempTable.>>>fromzugh.schema.tableimportTempTable>>>q22=tb.where().select(Max('age'))>>>print(q22)SELECTmax(age)FROMzugh.users>>>q23=tb.where(age=In(q22)).select()>>>print(q23)SELECT*FROMzugh.usersWHEREageIN(SELECTmax(age)FROMzugh.users)>>>q23.exe()(((5,23,7),),1)>>>q_t=tb.where(id=gt(2)).select()>>>tb_t1=q_t.as_table('ak')# equal to tb_t1 = TempTable(q_t, 'ak')>>>tb_t1TempTable(SELECT*FROMzugh.usersWHEREid>2)>>>>>>sql2="""CREATE TABLE zugh.account (`id` int(11) NOT NULL AUTO_INCREMENT,`user_id` int(11) NOT NULL,`amount` decimal(11,2) NOT NULL DEFAULT '0',PRIMARY KEY (`id`)) Engine=InnoDB DEFAULT CHARSET=utf8mb4;""">>>withconnascn:withcn.cursor()ascursor:cursor.execute(sql2)>>>tb2=Table('account',db,alias='a')# If tend to join table, alias is necessary>>>rows2=(dict(user_id=1,amount='99.89'),dict(user_id=2,amount='292.2'),dict(user_id=3,amount='299.89'),dict(user_id=4,amount='192.1'),dict(user_id=5,amount='183.7'),)>>>tb2.insert_multi(rows2).exe()>>>>>>tb_t2=tb_t1.inner_join(tb2,on='a.user_id = ak.id')>>>q_t2=tb_t2.select()>>>print(q_t2)SELECT*FROM(SELECT*FROMzugh.usersWHEREid>2)ASakINNERJOINzugh.accountASaONa.user_id=ak.id>>>q_t2.exe()(((3,7,8,3,3,Decimal('299.89')),(4,17,8,4,4,Decimal('192.10'))),2)Join InLet's add a new table and query from the join table:>>>tb3=Table('users',db,alias='b')# If tend to join table, alias is necessary>>>tb_i=tb2.inner_join(tb3,on='a.user_id=b.id')>>>q_i=tb_i.where(a__id=gt(2)).select('a.id','a.user_id','a.amount','b.score','b.age')>>>print(q_i)SELECTa.id,a.user_id,a.amount,b.score,b.ageFROMzugh.accountASaINNERJOINzugh.usersASbONa.user_id=b.idWHEREa.id>2>>>q_i.exe()(((3,3,Decimal('299.89'),8,7),(4,4,Decimal('192.10'),8,17)),2)If two underscores are used in the keyword ofwheremethod, the two underscores will be replaced by solid point. For example,a__idwill be replaced witha.id. This idea was copied from the Django project.We provideTable.inner_join(),Table.left_join()andTable.right_join()methods to support Table join.UnionYou can callunionorunion_allmethod fromSelect object. For example:>>>fromzugh.query.conditionimportgt,lt>>>q_u1=tb.where(id=lt(5)).select()>>>q_u2=tb.where(age=gt(20)).select()>>>q_u=q_u1.union_all(q_u2)>>>print(q_u)SELECT*FROMzugh.usersWHEREid<5UNIONALLSELECT*FROMzugh.usersWHEREage>20Update>>>tb.where(id=1).select().exe()(((1,16,7),),1)>>>q24=tb.where(id=1).update(age=28)>>>print(q24)UPDATEzugh.usersSETage=28WHEREid=1>>>q24.exe()1>>>tb.where(id=1).select().exe()(((1,28,7),),1)F ObjectF object means that it is a field, not a string. It could be used inTable.where()orWhere.update(). F class is a subclass ofArithmeticBase. So F objects can perform mathematical operations, and it will return a newArithmeticBaseinstance.See the following examples:>>>fromzugh.query.othersimportF>>>tb.where(id=1).select().exe()(((1,28,7),),1)>>>q25=tb.where(id=1).update(age=F('age')-2,score=F('score')+6)>>>print(q25)UPDATEzugh.usersSETage=age-2,score=score+6WHEREid=1>>>q25.exe()1>>>tb.where(id=1).select().exe()(((1,26,13),),1)# F object also use in filter>>>q26=tb.where(score=gt(F('age')*2)).select()>>>print(q26)SELECT*FROMzugh.usersWHEREscore>age*2>>>q26.exe()((),0)Delete>>>tb.where(id=5).select().exe()(((5,23,7),),1)>>>q23=tb.where(id=5).delete()>>>print(q23)DELETEFROMzugh.usersWHEREid=5>>>q23.exe()1>>>tb.where(id=5).select().exe()((),0)Decoratordb.query.queryquerydecorator wraps a function which return a Query object. When call the wrapped function, it would execute a Query object. For example:>>>fromzugh.query.aggregateimportMax>>>fromzugh.db.queryimportquery>>>@query()defquery_max_score():q1=tb.where().select(Max('score'))q2=tb.where(score=In(q1)).select()returnq2>>>query_max_score()(((1,26,13),),1)queryaccept 2 parameters:conn_configandconn_pool. If the Query object returned don't configure connection, you can pass aconn_configdict or a connection pool to it.db.query.transactiontransactiondecorator wrap a function which return a list ofQuery ojbect. When call the wrapped function, it would execute the list ofQuery objectas a transaction. If transaction succeed, return True, otherwise return False.For example:fromzugh.db.queryimporttransactionfromzugh.query.othersimportF@transaction(conn_pool=pool)defmv_score():q1=tb.where(id=3).update(score=F('score')-1)q2=tb.where(id=4).update(score=F('score')+1)return(q1,q2)>>>mv_score()TrueStringSome string function awailable inzugh.query.stringmodule.concat 2 field:fromzugh.query.stringimportConcat,S,Substring>>>q24=tb.where().select(Concat('age','score'))>>>print(q24)SELECTconcat(age,score)FROMzugh.usersS ObjectIn string functions, str meaning field name instead of string. You should useS objectto represent string.fromzugh.query.stringimportConcat,S,Substring>>>q25=tb.where().select(Concat(S('PRI-'),'age'))>>>print(q25)SELECTconcat('PRI-',age)FROMzugh.users>>>q25.exe()((('PRI-26',),('PRI-9',),('PRI-7',),('PRI-17',)),4)>>>print(tb.where().select(Substring('age',2)))SELECTsubstring(age,2)FROMzugh.usersMathSome math functions are awailable inzugh.query.mathmodule.
zuice
importzuiceclassBlogPostLister(zuice.Base):_fetcher=zuice.dependency(BlogPostFetcher)defall(self):return", ".join(post.nameforpostinself._fetcher.fetch_all())bindings=zuice.Bindings()bindings.bind(BlogPostFetcher).to_instance(blog_post_fetcher)injector=zuice.Injector(bindings)assertinjector.get(BlogPostFetcher)isblog_post_fetcherinjector.get(BlogPostLister)# constructs BlogPostLister using the bound instance of BlogPostFetcher
zuicorn
No description available on PyPI.
zuid
zuidGenerates URL-safe random ids with a prefix and optional timestamp.Installingpip install zuidUsageTheZUIDclass works as a callable id factory for a given prefix:>>> from zuid import ZUID >>> generator = ZUID(prefix='user_') >>> generator() 'user_03QewpfEIpPWUICXdgtvdR' >>> generator() 'user_1LJSXMoyH6p7VsiL8wwIm1'The factory generates ids that are 22 chars long by default, which in base 62 corresponds to 131 random bits. For comparison, a v4 UUID has 122 random bits. It can be changed with thelengthparameter:>>> generator = ZUID(prefix='user_', length=27) >>> generator() 'user_X5fSIStIKpYWcg07nqEfPbMvmME'With thetimestampedparameter, the factory uses the current nanoseconds since epoch as the first 8 bytes, preserving the order when sorting by id.>>> generator = ZUID(prefix='user_', timestamped=True) >>> generator() 'user_1qzuvBwgHdQVO2gA4GelYX' >>> generator() 'user_1qzuvCscVyClzGaqakgvsl' >>> generator() 'user_1qzuvDb0TuCuIJJON103Of' >>> generator() 'user_1qzuvES4mTQ7fWykywvjNb
zuken
ZukenSmall Python library for Zuken. Contains a variety of functions that I have found to be useful while creating scripts for Zuken at work.Will be updated as I find new things to include that I find useful.Tests aren't included yet, as it requires manual testing due to the integration with Zuken itself.
zuko
Zuko - Normalizing flows in PyTorchZuko is a Python package that implements normalizing flows inPyTorch. It relies as much as possible on distributions and transformations already provided by PyTorch. Unfortunately, theDistributionandTransformclasses oftorchare not sub-classes oftorch.nn.Module, which means you cannot send their internal tensors to GPU with.to('cuda')or retrieve their parameters with.parameters(). Worse, the concepts of conditional distribution and transformation, which are essential for probabilistic inference, are impossible to express.To solve these problems,zukodefines two concepts: theLazyDistributionandLazyTransform, which are any modules whose forward pass returns aDistributionorTransform, respectively. Because the creation of the actual distribution/transformation is delayed, an eventual condition can be easily taken into account. This design enables lazy distributions, including normalizing flows, to act like distributions while retaining features inherent to modules, such as trainable parameters. It also makes the implementations easy to understand and extend.In theAvatarcartoon,Zukois a powerful firebender 🔥AcknowledgementsZuko takes significant inspiration fromnflowsandStefan Webb's work inPyroandFlowTorch.InstallationThezukopackage is available onPyPI, which means it is installable viapip.pip install zukoAlternatively, if you need the latest features, you can install it from the repository.pip install git+https://github.com/probabilists/zukoGetting startedNormalizing flows are provided in thezuko.flowsmodule. To build one, supply the number of sample and context features as well as the transformations' hyperparameters. Then, feeding a context $c$ to the flow returns a conditional distribution $p(x | c)$ which can be evaluated and sampled from.importtorchimportzuko# Neural spline flow (NSF) with 3 sample features and 5 context featuresflow=zuko.flows.NSF(3,5,transforms=3,hidden_features=[128]*3)# Train to maximize the log-likelihoodoptimizer=torch.optim.Adam(flow.parameters(),lr=1e-3)forx,cintrainset:loss=-flow(c).log_prob(x)# -log p(x | c)loss=loss.mean()optimizer.zero_grad()loss.backward()optimizer.step()# Sample 64 points x ~ p(x | c*)x=flow(c_star).sample((64,))Alternatively, flows can be built as customFlowobjects.fromzuko.flowsimportFlow,MaskedAutoregressiveTransform,Unconditionalfromzuko.distributionsimportDiagNormalfromzuko.transformsimportRotationTransformflow=Flow(transform=[MaskedAutoregressiveTransform(3,5,hidden_features=(64,64)),Unconditional(RotationTransform,torch.randn(3,3)),MaskedAutoregressiveTransform(3,5,hidden_features=(64,64)),],base=Unconditional(DiagNormal,torch.zeros(3),torch.ones(3),buffer=True,),)For more information, check out the documentation and tutorials atzuko.readthedocs.io.Available flowsClassYearReferenceGMM-Gaussian Mixture ModelNICE2014Non-linear Independent Components EstimationMAF2017Masked Autoregressive Flow for Density EstimationNSF2019Neural Spline FlowsNCSF2020Normalizing Flows on Tori and SpheresSOSPF2019Sum-of-Squares Polynomial FlowNAF2018Neural Autoregressive FlowsUNAF2019Unconstrained Monotonic Neural NetworksCNF2018Neural Ordinary Differential EquationsGF2020Gaussianization FlowsBPF2020Bernstein-Polynomial Normalizing FlowsContributingIf you have a question, an issue or would like to contribute, please read ourcontributing guidelines.
zul
No description available on PyPI.
zula
zuladead simple key-value and in-memory database built uponjsonpackage.Install$ pip install zulaRequirementsPython 2.6, 2.7, 3.5, 3.6+DocumentationCommands>>>importzula>>>db=zula.load('samsun.db')>>>db.set('key','value')>>>db.get('key')'value'>>>db.drop('key')True>>>db.get_keys()set(['key1','key2'])>>>db.dump()True
zulip
DependenciesTheZulip APIPython bindings require the following dependencies:Python (version >= 3.8)requests (version >= 0.12.1)Note: If you'd like to use the Zulip bindings with Python 2, we recommend installing version 0.6.4.InstallingThis package uses setuptools, so you can just run:python setup.py installUsing the APIFor now, the only fully supported API operation is sending a message. The other API queries work, but are under active development, so please make sure we know you're using them so that we can notify you as we make any changes to them.The easiest way to use these API bindings is to base your tools off of the example tools under zulip/examples/ in this distribution.If you place your API key in the config file~/.zuliprcthe Python API bindings will automatically read it in. The format of the config file is as follows:[api] key=<api key from the web interface> email=<your email address> site=<your Zulip server's URI> insecure=<true or false, true means do not verify the server certificate> cert_bundle=<path to a file containing CA or server certificates to trust>If omitted, these settings have the following defaults:insecure=false cert_bundle=<the default CA bundle trusted by Python>Alternatively, you may explicitly use "--user", "--api-key", and--sitein our examples, which is especially useful when testing. If you are running several bots which share a home directory, we recommend using--configto specify the path to thezuliprcfile for a specific bot. Finally, you can control the defaults for all of these variables using the environment variablesZULIP_CONFIG,ZULIP_API_KEY,ZULIP_EMAIL,ZULIP_SITE,ZULIP_CERT,ZULIP_CERT_KEY, andZULIP_CERT_BUNDLE. Command-line options take precedence over environment variables take precedence over the config files.The command line equivalents for other configuration options are:--insecure --cert-bundle=<file>You can obtain your Zulip API key, create bots, and manage bots all from your Zulip settings page; with current Zulip there's also a button to download azuliprcfile for your account/server pair.A typical simple bot sending API messages will look as follows:At the top of the file:# Make sure the Zulip API distribution's root directory is in sys.path, then: import zulip zulip_client = zulip.Client(email="[email protected]", client="MyTestClient/0.1")When you want to send a message:message = { "type": "stream", "to": ["support"], "subject": "your subject", "content": "your content", } zulip_client.send_message(message)If you are parsing arguments, you may find it useful to use Zulip's option group; see any of our API examples for details on how to do this.Additional examples:client.send_message({'type': 'stream', 'content': 'Zulip rules!', 'subject': 'feedback', 'to': ['support']}) client.send_message({'type': 'private', 'content': 'Zulip rules!', 'to': ['[email protected]', '[email protected]']})send_message() returns a dict guaranteed to contain the following keys: msg, result. For successful calls, result will be "success" and msg will be the empty string. On error, result will be "error" and msg will describe what went wrong.ExamplesThe API bindings package comes with several nice example scripts that show how to use the APIs; they are installed as part of the API bindings bundle.LoggingThe Zulip API comes with a ZulipStream class which can be used with the logging module:import zulip import logging stream = zulip.ZulipStream(type="stream", to=["support"], subject="your subject") logger = logging.getLogger("your_logger") logger.addHandler(logging.StreamHandler(stream)) logger.setLevel(logging.DEBUG) logger.info("This is an INFO test.") logger.debug("This is a DEBUG test.") logger.warn("This is a WARN test.") logger.error("This is a ERROR test.")Sending messagesYou can use the includedzulip-sendscript to send messages via the API directly from existing scripts.zulip-send [email protected] [email protected] -m \ "Conscience doth make cowards of us all."Alternatively, if you don't want to use your ~/.zuliprc file:zulip-send --user [email protected] \ --api-key a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5 \ --site https://zulip.example.com \ [email protected] [email protected] -m \ "Conscience doth make cowards of us all."Working with an untrusted server certificateIf your server has either a self-signed certificate, or a certificate signed by a CA that you don't wish to globally trust then by default the API will fail with an SSL verification error.You can addinsecure=trueto your .zuliprc file.[api] site=https://zulip.example.com insecure=trueThis disables verification of the server certificate, so connections are encrypted but unauthenticated. This is not secure, but may be good enough for a development environment.You can explicitly trust the server certificate usingcert_bundle=<filename>in your .zuliprc file.[api] site=https://zulip.example.com cert_bundle=/home/bots/certs/zulip.example.com.crtYou can also explicitly trust a different set of Certificate Authorities from the default bundle that is trusted by Python. For example to trust a company internal CA.[api] site=https://zulip.example.com cert_bundle=/home/bots/certs/example.com.ca-bundleSave the server certificate (or the CA certificate) in its own file, converting to PEM format first if necessary. Verify that the certificate you have saved is the same as the one on the server.Thecert_bundleoption trusts the server / CA certificate only for interaction with the zulip site, and is relatively secure.Note that a certificate bundle is merely one or more certificates combined into a single file.
zulip-beta
UNKNOWN
zulipbot
The unofficial Python API for Zulip bots. A Zulip email and API key are needed to use this.To get your bot’s Zulip email and API key, go to your Settings page and scroll down to the Your Bots section.UsageTo install:pip install zulipbotInitializationIdentify your Zulip bot’s email and API key, and make a new Bot object.>>>importzulipbot>>>email='[email protected]'>>>key='spammyeggs'>>>my_bot=zulipbot.Bot(email,key)Bot MethodsFor an example on how the below methods work together in a program, check outexample.py.subscribe_to_all_streams- Subscribes to all Zulip streams.send_private_messageandsend_stream_messageboth have the same parameters:message_infoandcontent, i.e. the function signature for the two aforementioned methods issend_[[private||stream]]_message(message_info,content).message_infois the message meta-info dictionary that you acquire from the function callback that processes messages.contentis the response that you want your bot to make.
zulip-bots
Zulip botsThis directory contains the source code for thezulip_botsPyPI package.The Zulip documentation has guides onusing Zulip's bot systemandwriting your own bots.Directory structurezulip_bots# This directory├───zulip_bots# `zulip_bots` package.│├───bots/# Actively maintained and tested bots.│├───game_handler.py# Handles game-related bots.│├───lib.py# Backbone of run.py│├───provision.py# Creates a development environment.│├───run.py# Used to run bots.│├───simple_lib.py# Used for terminal testing.│├───test_lib.py# Backbone for bot unit tests.│├───test_run.py# Unit tests for run.py│└───bot_shell.py# Used to test bots in the command line.└───setup.py# Script for packaging.
zulip-botserver
zulip-botserver --config-file <path to botserverrc> --hostname <address> --port <port>Example:zulip-botserver --config-file ~/botserverrcThis program loads the bot configurations from the config file (botserverrc, here) and loads the bot modules. It then starts the server and fetches the requests to the above loaded modules and returns the success/failure result.The--hostnameand--portarguments are optional, and default to 127.0.0.1 and 5002 respectively.The format for a configuration file is:[helloworld] key=value [email protected] site=http://localhost token=abcd1234Is passed--use-env-varsinstead of--config-file, the configuration can instead be provided via theZULIP_BOTSERVER_CONFIGenvironment variable. This should be a JSON-formatted dictionary of bot names to dictionary of their configuration; for example:ZULIP_BOTSERVER_CONFIG='{"helloworld":{"email":"[email protected]","key":"value","site":"http://localhost","token":"abcd1234"}}' \ zulip-botserver --use-env-vars
zulip-doc
Zulip Duty of Care ServiceA small script to check user presence in Zulip. If a user hasn't been around for a while it will send you a message in Zulip so you can check up on them and see if they are ok.Installpipx install zulip-docUsageUsage: zdoc [OPTIONS] [SEND_TO]... Arguments: [SEND_TO]... Options: --max-idle INTEGER [env var: MAX_IDLE; default: 86400] --ignore-weekends / --no-ignore-weekends [env var: IGNORE_WEEKENDS; default: ignore- weekends] --config-file FILE [env var: CONFIG_FILE; default: /home/{username}/.zuliprc] --help Show this message and exit.Example:zdoc 12 22Cron Job Setupcrontab -eThen add something like:0 12 * * * /home/paul/.local/bin/zdoc --config-file /home/paul/.zuliprc 12 22runs everyday at noon
zulip-emoji-mapping
Zulip emoji mappingGet emojis by Zulip namesExample>>>fromzulip_emoji_mappingimportZulipEmojiMapping>>>print(ZulipEmojiMapping.get_emoji_name("🙂"))smile>>>print(ZulipEmojiMapping.get_emoji_by_name("smile"))🙂>>>print(ZulipEmojiMapping.get_emoji_by_name("cat"))🐈
zulip-term
Recent changes|Configuration|Hot Keys|FAQs|Development|TutorialAboutZulip Terminal is the official terminal client for Zulip, providing atext-based user interface (TUI).Specific aims include:Providing a broadly similar user experience to the Zulip web client, ultimately supporting all of its featuresEnabling all actions to be achieved through the keyboard (seeHot keys)Exploring alternative user interface designs suited to the display and input constraintsSupporting a wide range of platforms and terminal emulatorsMaking best use of available rows/columns to scale from 80x24 upwards (seeSmall terminal notes)Learn how to use Zulip Terminal with ourTutorial.Feature statusWe consider the client to already provide a fairly stable moderately-featureful everyday-user experience.The terminal client currently has a number of intentional differences to the Zulip web client:Additional and occasionallydifferentHot keysto better support keyboard-only navigation; other than directional movement these also include:z- zoom in/out, between streams & topics, or all private messages & specific conversationst- toggle view of topics for a stream in left panel (later adopted for recent topics in web client)#- narrow to messages in which you're mentioned (@is already used)f- narrow to messages you've starred (arefollowing)Not marking additional messages read when the end of a conversation is visible (FAQ entry)Emoji and reactions are rendered as text only, for maximum terminal/font compatibilityFootlinks - footnotes for links (URLs) - make messages readable, while retaining a list of links to cross-referenceContent previewable in the web client, such as images, are also stored as footlinksThe current development focus is on improving aspects of everyday usage which are more commonly used - to reduce the need for users to temporarily switch to another client for a particular feature.Current limitations which we expect to only resolve over the long term include support for:All operations performed by users with extra privileges (owners/admins)Accessing and updating all settingsUsing a mouse/pointer to achieve all actionsAn internationalized UIFor queries on missing feature support please take a look at theFrequently Asked Questions (FAQs), our openIssues, or sign up onhttps://chat.zulip.organd chat with users and developers in the#zulip-terminalstream!Supported platformsLinuxOSXWSL (On Windows)Supported Server VersionsThe minimum server version that Zulip Terminal supports is2.1.0. It may still work with earlier versions.Supported Python VersionsVersion 0.6.0 was the last release with support for Python 3.5.Later releases and the main development branch are currently tested (on Ubuntu) with:CPython 3.6-3.10PyPy 3.6-3.9Since our automated testing does not cover interactive testing of the UI, there may be issues with some Python versions, though generally we have not found this to be the case.Please note that generally we limit each release to between a lower and upper Python version, so it is possible that for example if you have a newer version of Python installed, then some releases (ormain) may not install correctly. In some cases this can give rise to the symptoms in issue #1145.InstallationWe recommend installing in a dedicated python virtual environment (see below) or using an automated option such aspipxStable- Numbered stable releases are available on PyPI as the packagezulip-termTo install, run a command like:pip3 install zulip-termLatest- The latest development version can be installed from the main git repositoryTo install, run a command like:pip3 install git+https://github.com/zulip/zulip-terminal.git@mainWe also provide some sample Dockerfiles to build docker images indocker/.Installing into an isolated Python virtual environmentWith the python 3.6+ required for running, the following should work on most systems:python3 -m venv zt_venv(creates a virtual environment namedzt_venvin the current directory)source zt_venv/bin/activate(activates the virtual environment; this assumes a bash-like shell)Run one of the install commands above,If you open a different terminal window (or log-off/restart your computer), you'll need to runstep 2of the above list again before runningzulip-term, since that activates that virtual environment. You can read more about virtual environments in thePython 3 library venv documentation.Keeping your install up to dateStable releases are made available on PyPI and GitHub; to ensure you keep up to date with them we suggest checking those sites for updates. Stable releases are also announced in the #announcestream on the Zulip Community server (https://chat.zulip.org), where you are welcome to make an account; future releases are expected to be announced in #announce>terminal releases.If running from themaingit branch, note that this does not automatically update, and you must do so manually. This also applies to other source or development installs, including eg.https://aur.archlinux.org/packages/python-zulip-term-git/Running for the first timeUpon first runningzulip-termit looks for azuliprcfile, by default in your home directory, which contains the details to log into a Zulip server.If it doesn't find this file, you have two options:zulip-termwill prompt you for your server, email and password, and create azuliprcfile for you in that locationNOTE:If you use Google, Github or another external authentication to access your Zulip organization then you likely won't have a password set and currently need to create one to use zulip-terminal. If your organization is on Zulip cloud, you can visithttps://zulip.com/accounts/go?next=/accounts/password/resetto create a new password for your account. For self-hosted servers please go to your<Organization URL>/accounts/password/reset/(eg:https://chat.zulip.org/accounts/password/reset/) to create a new password for your account.Each time you runzulip-term, you can specify the path to an alternativezuliprcfile using the-cor--config-fileoptions, eg.$ zulip-term -c /path/to/zuliprcYour personal zuliprc file can be obtained from Zulip servers in your account settings in the web application, which gives you all the permissions you have there. Bot zuliprc files can be downloaded from a similar area for each bot, and will have more limited permissions.NOTE:If your server uses self-signed certificates or an insecure connection, you will need to add extra options to thezuliprcfile manually - see the documentation for theZulip python module.We suggest runningzulip-termusing the-eor--exploreoption (in explore mode) when you are trying Zulip Terminal for the first time, where we intentionally do not mark messages as read. Try following along with ourTutorialto get the hang of things.ConfigurationThezuliprcfile contains information to connect to your chat server in the[api]section, but also optional configuration forzulip-termin the[zterm]section:[api] [email protected] key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx site=https://realm.zulipchat.com [zterm] # Alternative themes are listed in the FAQ theme=zt_dark # Autohide defaults to 'no_autohide', but can be set to 'autohide' to hide the left & right panels except when focused. autohide=autohide # Footlinks default to 'enabled', but can be set to 'disabled' to hide footlinks. # disabled won't show any footlinks. # enabled will show the first 3 per message. footlinks=disabled # If you need more flexibility, use maximum-footlinks. # Maximum footlinks to be shown, defaults to 3, but can be set to any value 0 or greater. # This option cannot be used with the footlinks option; use one or the other. maximum-footlinks=3 # Notify defaults to 'disabled', but can be set to 'enabled' to display notifications (see next section). notify=enabled # Color depth defaults to 256 colors, but can be set to 1 (for monochrome), 16, or 24bit. color-depth=256NOTE:Most of these configuration settings may be specified on the command line whenzulip-termis started;zulip-term -horzulip-term --helpwill give the full list of options.NotificationsNote that notifications are not currently supported on WSL; see#767.LinuxThe following command installsnotify-sendon Debian based systems, similar commands can be found for other linux systems as well.sudo apt-get install libnotify-binOSXNo additional package is required to enable notifications in OS X. However to have a notification sound, set the following variable (based on your type of shell). The sound value (here Ping) can be any one of the.aifffiles found at/System/Library/Soundsor~/Library/Sounds.Bashecho 'export ZT_NOTIFICATION_SOUND=Ping' >> ~/.bash_profile source ~/.bash_profileZSHecho 'export ZT_NOTIFICATION_SOUND=Ping' >> ~/.zshenv source ~/.zshenvCopy to clipboardZulip Terminal allows users to copy certain texts to the clipboard via a Python module,Pyperclip. This module makes use of various system packages which may or may not come with the OS. The "Copy to clipboard" feature is currently only available for copying Stream email, from theStream information popup.LinuxOn Linux, this module makes use ofxcliporxselcommands, which should already come with the OS. If none of these commands are installed on your system, then install any ONE using:sudo apt-get install xclip [Recommended]ORsudo apt-get install xselOSX and WSLNo additional package is required to enable copying to clipboard.Contributor GuidelinesZulip Terminal is being built by the awesomeZulipcommunity.To be a part of it and to contribute to the code, feel free to work on anyissueor propose your idea on#zulip-terminal.For commit structure and style, please review theCommit Stylesection below.If you are new togit(or not!), you may benefit from theZulip git guide. When contributing, it's important to note that we use arebase-oriented workflow.A simpletutorialis available for implementing thetypingindicator. Follow it to understand how to implement a new feature for zulip-terminal.You can of course browse the source on GitHub & in the source tree you download, and check thesource file overviewfor ideas of how files are currently arranged.UrwidZulip Terminal usesurwidto render the UI components in terminal. Urwid is an awesome library through which you can render a decent terminal UI just using python.Urwid's Tutorialis a great place to start for new contributors.Setting up a development environmentVarious options are available; we are exploring the benefits of each and would appreciate feedback on which you use or feel works best.Note that the tools used in each case are typically the same, but are called in different ways.With any option, you first need to clone the zulip/zulip-terminal repository locally (the following will place the repository in the current directory):$ git clone [email protected]:zulip/zulip-terminal.gitThe following commands should be run in the repository directory, which can be achieved withcd zulip-terminal.PipenvInstall pipenv (see therecommended installation notes; pipenv can be installed in a virtual environment, if you wish)$ pip3 install --user pipenvInitialize the pipenv virtual environment for zulip-term (using the default python 3; use eg.--python 3.6to be more specific)$ pipenv --threeInstall zulip-term, with the development requirements$ pipenv install --dev $ pipenv run pip3 install -e '.[dev]'PipManually create & activate a virtual environment; any method should work, such as that used in the above simple installationpython3 -m venv zt_venv(creates a venv namedzt_venvin the current directory)source zt_venv/bin/activate(activates the venv; this assumes a bash-like shell)Install zulip-term, with the development requirements$ pip3 install -e '.[dev]'make/pipThis is the newest and simplest approach, if you havemakeinstalled:make(sets up an installed virtual environment inzt_venvin the current directory)source zt_venv/bin/activate(activates the venv; this assumes a bash-like shell)Development tasksOnce you have a development environment set up, you might find the following useful, depending upon your type of environment:TaskMake & PipPipenvRun normallyzulip-termpipenv run zulip-termRun in debug modezulip-term -dpipenv run zulip-term -dRun with profilingzulip-term --profilepipenv run zulip-term --profileRun all linters./tools/lint-allpipenv run ./tools/lint-allRun all testspytestpipenv run pytestBuild test coverage reportpytest --cov-report html:cov_html --cov=./pipenv run pytest --cov-report html:cov_html --cov=./If using make with pip, runningmakewill ensure the development environment is up to date with the specified dependencies, useful after fetching from git and rebasing.Passing linters and automated testsThe linters and automated tests (pytest) are run in CI (GitHub Actions) when you submit a pull request (PR), and we expect them to pass before code is merged.NOTE:Mergeable PRs with multiple commits are expected to pass linting and tests ateach commit, not simply overallRunning these tools locally can speed your development and avoid the need to repeatedly push your code to GitHub simply to run these checks.If you have troubles understanding why the linters or pytest are failing, please do push your code to a branch/PR and we can discuss the problems in the PR or on chat.zulip.org.All linters and tests can be run using the commands in the table above. Individual linters may also be run via scripts intools/.In addition, if using amake-based system:make lintandmake testrun all of each group of tasksmake checkruns all checks, which is useful before pushing a PR (or an update)Correcting some linting errors requires manual intervention, such as frommypyfor type-checking. However, other linting errors may be fixed automatically, as detailed below -this can save a lot of time manually adjusting your code to pass the linters!Auto-formatting codeThe project usesblackandisortfor code-style and import sorting respectively.These tools can be run as linters locally , but can alsoautomaticallyformat your code for you.If you're using amake-based setup, runningmake fixwill run both (and a few other tools) and reformat the current state of your code - so you'll want to commit first just in case, then--amendthat commit if you're happy with the changes.You can also use the tools individually on a file or directory, eg.black zulipterminalorisort tests/model/test_model.pyCommit StyleWe aim to follow a standard commit style to keep thegit logconsistent and easy to read.Much like working with code, it's great to refer to the git log, for the style we're actively using.Our overall style for commit structure and messages broadly follows the generalZulip version control guidelines, so we recommend reading that first.Our commit titles have slight variations from the general Zulip style, with each:starting with one or more areas in lower case, followed by a colon and spacearea being slash-separated modified files without extensions, or the type of the changeending with a concise description starting with a capital and ending with a full-stop (period)having a maximum overall length of 72 (fitting github web interface without abbreviation)Some example commit titles:file3/file1/file2: Improve behavior of something.- a general commit updating filesfile1.txt,file2.pyandfile3.mdrefactor: file1/file2: Extract some common function.- a pure refactor which doesn't change the functional behaviorbugfix: file1: Avoid some noticeable bug.- an ideally small commit to fix a bugtests: file1: Improve test for something.- only improve tests forfile1, likely intest_file1.pyrequirements: Upgrade some-dependency from 9.2 to 9.3.- upgrade a dependency from version 9.2 to version 9.3Generally with changes to code we request you update linting and tests to pass on a per-commit basis (not just per pull request). If you update tests, you can add eg.Tests updated.in your commit text.Ideally we prefer that behavioral changes are accompanied by test improvements or additions, and an accompanyingTests added.or similar is then useful.To aid in satisfying some of these rules you can useGitLint, as described in the following section.However, please check your commits manually versus these style rules, since GitLint cannot check everything - including language or grammar!GitLintIf you plan to submit git commits in pull-requests (PRs), then we highly suggest installing thegitlintcommit-message hook by runninggitlint install-hook(orpipenv run gitlint install-hookwith pipenv setups). While the content still depends upon your writing skills, this ensures a more consistent formatting structure between commits, including by different authors.If the hook is installed as described above, then after completing the text for a commit, it will be checked by gitlint against the style we have set up, and will offer advice if there are any issues it notices. If gitlint finds any, it will ask if you wish to commit with the message as it is (yfor 'yes'), stop the commit process (nfor 'no'), or edit the commit message (efor 'edit').Other gitlint options are available; for example it is possible to apply it to a range of commits with the--commitsoption, eg.gitlint --commits HEAD~2..HEADwould apply it to the last few commits.Tips for working with tests (pytest)Tests for zulip-terminal are written usingpytest. You can read the tests in the/testsfolder to learn about writing tests for a new class/function. If you are new to pytest, reading its documentation is definitely recommended.We currently have thousands of tests which get checked upon runningpytest. While it is dependent on your system capability, this should typically take less than one minute to run. However, during debugging you may still wish to limit the scope of your tests, to improve the turnaround time:If lots of tests are failing in a very verbose way, you might try the-xoption (eg.pytest -x) to stop tests after the first failure; due to parametrization of tests and test fixtures, many apparent errors/failures can be resolved with just one fix! (try eg.pytest --maxfail 3for a less-strict version of this)To avoid running all the successful tests each time, along with the failures, you can run with--lf(eg.pytest --lf), short for--last-failed(similar useful options may be--failed-firstand--new-first, which may work well with-x)Since pytest 3.10 there is--sw(--stepwise), which works through known failures in the same way as--lfand-xcan be used, which can be combined with--stepwise-skipto control which test is the current focusIf you know the names of tests which are failing and/or in a specific location, you might limit tests to a particular location (eg.pytest tests/model) or use a selected keyword (eg.pytest -k __handle)When only a subset of tests are running it becomes more practical and useful to use the-voption (--verbose); instead of showing a.(orF,E,x, etc) for each test result, it gives the name (with parameters) of each test being run (eg.pytest -v -k __handle). This option also shows more detail in tests and can be given multiple times (eg.pytest -vv).For additional help with pytest options seepytest -h, or check out thefull pytest documentation.Debugging TipsOutput usingprintThe stdout (standard output) for zulip-terminal is redirected to./debug.logif debugging is enabled at run-time using-dor--debug.This means that if you want to check the value of a variable, or perhaps indicate reaching a certain point in the code, you can simply useprint(), eg.print(f"Just about to do something with{variable}")and when running with a debugging option, the string will be printed to./debug.log.With a bash-like terminal, you can run something liketail -f debug.login another terminal, to see the output fromprintas it happens.Interactive debugging using pudb & telnetIf you want to debug zulip-terminal while it is running, or in a specific state, you can insertfrompudb.remoteimportset_traceset_trace()in the part of the code you want to debug. This will start a telnet connection for you. You can find the IP address and port of the telnet connection in./debug.log. Then simply run$ telnet 127.0.0.1 6899in another terminal, where127.0.0.1is the IP address and6899is port you find in./debug.log.There's no effect in Zulip Terminal after making local changes!This likely means that you have installed both normal and development versions of zulip-terminal.To ensure you run the development version:If using pipenv, callpipenv run zulip-termfrom the cloned/downloadedzulip-terminaldirectory;If using pip (pip3), ensure you have activated the correct virtual environment (venv); depending on how your shell is configured, the name of the venv may appear in the command prompt. Note that not including the-ein the pip3 command will also cause this problem.
zulu
A drop-in replacement for native datetimes that embraces UTCLinksProject:https://github.com/dgilland/zuluDocumentation:https://zulu.readthedocs.ioPyPI:https://pypi.python.org/pypi/zulu/Github Actions:https://github.com/dgilland/zulu/actionsFeaturesAll datetime objects converted and stored as UTC.Parses ISO8601 formatted strings and POSIX timestamps by default.Timezone representation applied only during string output formatting or when casting to native datetime object.Drop-in replacement for native datetime objects.Python 3.6+QuickstartInstall using pip:pip3 install zuluimportzuluzulu.now()# <Zulu [2016-07-25T19:33:18.137493+00:00]>dt=zulu.parse('2016-07-25T19:33:18.137493+00:00')# <Zulu [2016-07-25T19:33:18.137493+00:00]>dt=zulu.create(2016,7,25,19,33,18,137493)# <Zulu [2016-07-25T19:33:18.137493+00:00]>dt.isoformat()# '2016-07-25T19:33:18.137493+00:00'dt.timestamp()# 1469475198.137493dt.naive# datetime.datetime(2016, 7, 25, 19, 33, 18, 137493)dt.datetime# datetime.datetime(2016, 7, 25, 19, 33, 18, 137493, tzinfo=<UTC>)dt.format('%Y-%m-%d')# 2016-07-25dt.format('YYYY-MM-dd')# 2016-07-25dt.format("E, MMM d, ''YY")# "Mon, Jul 25, '16"dt.format("E, MMM d, ''YY",locale='de')# "Mo., Juli 25, '16"dt.format("E, MMM d, ''YY",locale='fr')# "lun., juil. 25, '16"dt.shift(hours=-5,minutes=10)# <Zulu [2016-07-25T14:43:18.137493+00:00]>dt.replace(hour=14,minute=43)# <Zulu [2016-07-25T14:43:18.137493+00:00]>dt.start_of('day')# <Zulu [2016-07-25T00:00:00+00:00]>dt.end_of('day')# <Zulu [2016-07-25T23:59:59.999999+00:00]>dt.span('hour')# (<Zulu [2016-07-25T19:00:00+00:00]>, <Zulu [2016-07-25T19:59:59.999999+00:00]>)dt.time_from(dt.end_of('day'))# '4 hours ago'dt.time_to(dt.end_of('day'))# 'in 4 hours'list(zulu.range('hour',dt,dt.shift(hours=4)))# [Zulu [2016-07-25T19:33:18.137493+00:00]>,# Zulu [2016-07-25T20:33:18.137493+00:00]>,# Zulu [2016-07-25T21:33:18.137493+00:00]>,# Zulu [2016-07-25T22:33:18.137493+00:00]>]list(zulu.span_range('minute',dt,dt.shift(minutes=4)))# [(Zulu [2016-07-25T19:33:00+00:00]>, Zulu [2016-07-25T19:33:59.999999+00:00]>),# (Zulu [2016-07-25T19:34:00+00:00]>, Zulu [2016-07-25T19:34:59.999999+00:00]>),# (Zulu [2016-07-25T19:35:00+00:00]>, Zulu [2016-07-25T19:35:59.999999+00:00]>),# (Zulu [2016-07-25T19:36:00+00:00]>, Zulu [2016-07-25T19:36:59.999999+00:00]>)]zulu.parse_delta('1w 3d 2h 32m')# <Delta [10 days, 2:32:00]>zulu.parse_delta('2:04:13:02.266')# <Delta [2 days, 4:13:02.266000]>zulu.parse_delta('2 days, 5 hours, 34 minutes, 56 seconds')# <Delta [2 days, 5:34:56]>Why Zulu?Why zulu instead ofnative datetimes:Zulu has extended datetime features such asparse(),format(),shift(), andpython-dateutiltimezone support.Parses ISO8601 and timestamps by default without any extra arguments.Easier to reason aboutZuluobjects since they are only ever UTC datetimes.Clear delineation between UTC and other time zones where timezone representation is only applicable for display or conversion to native datetime.Supports more string parsing/formatting options usingUnicode date patternsas well asstrptime/strftimedirectives.Why zulu instead ofArrow:Zulu is a drop-in replacement for native datetimes (inherits fromdatetime.datetime). No need to convert usingarrow.datetimewhen you need a datetime (zulu is always a datetime).Stricter parsing to avoid silent errors. For example, one might expectarrow.get('02/08/1987','MM/DD/YY')to fail (input does not match format) but it gladly returns<Arrow[2019-02-08T00:00:00+00:00)whereaszulu.parse('02/08/1987','%m/%d/%y')throwszulu.parser.ParseError: Value "02/08/1987" does not match any format in['%m/%d/%y'].Avoids timezone/DST shifting bugs by only dealing with UTC datetimes when applying timedeltas or performing other calculations.Supportsstrptime/strftimeas well asUnicode date patternsfor string parsing/formatting.Special ThanksSpecial thanks goes out to the authors/contributors of the following libraries that have made it possible forzuluto exist:Babeliso8601python-dateutilpytimeparsepytzFor the full documentation, please visithttps://zulu.readthedocs.io.Changelogv2.0.1 (2023-11-20)Add support for Python 3.12Replace usage of deprecateddatetime.utcnowanddatetime.utcfromtimestamp.v2.0.0 (2021-06-26)Drop support for Python 3.4 and 3.5.v1.3.1 (2021-06-26)Fix compatibility issue with Python 3.4 and 3.5 by replacing f-string usage with string-format.v1.3.0 (2021-01-07)Add Python 3.9 support.Fix bug inZulu.time_from,Zulu.time_to,Zulu.time_from_now, andZulu.time_to_nowwhere keyword arguments weren’t passed to underlyingDelta.formatcall.Fix bug inZulu.formatwhere “YY” and “YYYY” format patterns would return the year in “Week of Year” based calendars instead of the regular calendar year.v1.2.0 (2020-01-14)Add Python 3.8 support.Add'week'option toZulu.start_of,Zulu.end_of,Zulu.span, andZulu.span_range. ThanksThomasChiroux!Fix bug inZulu.astimezonein Python 3.8 due to change in return type fromsuper().asdatetime. In Python<=3.7,super().asdatetimereturned as instance ofdatetime, but in Python 3.8 another instance ofZuluwas returned instead.Zulu.astimezonewill now return adatetimeinstance in Python 3.8.v1.1.1 (2019-08-14)Remove unused parameter inzulu.Timer.__init__().v1.1.0 (2018-11-01)Addfoldattribute support toZulu.Addzulu.to_secondsfor converting units of time to total number of seconds.Addzulu.Timerclass that can be used to track elapsed time (like a stopwatch) or as a countdown timer.v1.0.0 (2018-08-20)Drop support for Python 2.7.v0.12.1 (2018-07-16)Support Python 3.7.v0.12.0 (2017-07-11)AddZulu.datetimetuple().AddZulu.datetuple().RemoveZulu.__iter__method. (breaking change)RemoveDelta.__iter__method. (breaking change)v0.11.0 (2017-06-28)Add Python 3.6 support.AddDelta.__iter__method that yields 2-element tuples likeZulu.__iter__. Delta values are normalized into integer values distributed from the higher units to the lower units.AddDelta.__float__andDelta.__int__methods for converting to seconds.AddZulu.__float__andZulu.__int__methods for converting to epoch seconds.Fix issue in Python 3.6 wherezulu.now()returned a naive datetimeZuluinstance.MakeZulu.__iter__yield 2-element tuples containing(unit, value)like(('year',2000), ('month', 12),...)so it can be converted to adictwith proper keys easier. (breaking change)Remove previously deprecatedzulu.delta()function. Usezulu.parse_delta()instead. (breaking change)Rename modules: (breaking change)zulu.datetime->zulu.zuluzulu.timedelta->zulu.deltav0.10.1 (2017-02-15)Provide fallback for the default value oflocaleinDelta.format()when a locale is not known via environment variables.v0.10.0 (2017-02-13)Addzulu.parse_deltaas alias forDelta.parse.Deprecatezulu.deltain favor ofzulu.parse_delta.Allow first argument toZulu(),Zulu.parse(), andzulu.parse()to be adictcontaining keys corresponding to initialization parameters.Fix error message for invalid timezone strings so that the supplied string is shown correctly.v0.9.0 (2016-11-21)Requirepython-dateutil>=2.6.0. (breaking change)Replace usage ofpytztimezone handling for strings withdateutil.tz.gettz. Continue to supportpytztimezones duringZulu()object creation. (breaking change).Replace default UTC timezone withdateutil.tz.tzutc(). Was previouslypytz.UTC. (breaking change)Replace local timezone withdateutil.tz.tzlocal(). Was previously set by thetzlocallibrary. (breaking change)v0.8.0 (2016-10-31)Add comparison methods toZulu:is_beforeis_on_or_beforeis_afteris_on_or_afteris_betweenv0.7.3 (2016-10-24)OptimizeZulu()constructor by eliminating multiple unnecessary calls todatetimeconstructor.v0.7.2 (2016-09-06)FixZulunot being pickle-able.v0.7.1 (2016-08-22)Add missing magic method overrides forDeltafor+delta,-delta, andabs(delta)so thatDeltais returned instead ofdatetime.timedelta.__pos____neg____abs__v0.7.0 (2016-08-22)MakeZulu.__sub__andZulu.subtractreturn aDeltaobject instead ofdatetime.timedelta.Makezulu.deltaandZulu.Delta.parseaccept a number.Allow the first argument toZulu.shiftbe a timedelta or relative delta object.Ensure that mathematical magic methods forDeltareturnDeltaobjects and notdatetime.timedelta.__add____radd____sub____mul____rmul____floordiv____truediv__(Python 3 only)__div__(Python 2 only)__mod__(Python 3 only)__divmod__(Python 3 only)v0.6.0 (2016-08-14)Replace internal implementation of Unicode date pattern formatting with Babel’sformat_datetime.breaking changeRemove support for formatting to timestamp usingXandXX.breaking changeRename parse-from-timestamp token fromXtotimestamp.breaking changeAddzulu.createas factory function to create azulu.Zuluinstance.Add locale support toZulu.formatwhen using Unicode date pattern format tokens.Restore locale support toDelta.format.v0.5.0 (2016-08-13)Remove locale support fromDelta.format. Locale is currently not supported inZulu.formatso decided to disable it inDelta.formatuntil both can have it.breaking changev0.4.0 (2016-08-13)Renamezulu.DateTimetozulu.Zulu.breaking changeRenameZulu.isleaptoZulu.is_leap_year.breaking changeRemovezulu.formatalias (function can be accessed atzulu.parser.format_datetime).breaking changeRemoveZulu.leapdays.breaking changeAddZulu.days_in_month.Addzulu.Deltaclass that inherits fromdatetime.timedelta.Addzulu.deltaas alias tozulu.Delta.parse.AddZulu.time_from,Zulu.time_to,Zulu.time_from_now, andZulu.time_to_nowthat return “time ago” or “time to” humanized strings.Addzulu.rangeas alias toZulu.range.Addzulu.span_rangeas alias toZulu.span_range.Make time units (years, months, weeks, days, hours, minutes, seconds, microseconds) keyword arguments only forZulu.add/subtract, but allow positional argument to be an addable/subtractable object (datetime, timedelta, dateutil.relativedelta).breaking changev0.3.0 (2016-08-03)RenameDateTime.subtoDateTime.subtract.breaking changeAllow the first argument toDateTime.addto be adatetime.timedeltaordateutil.relativedeltaobject.Allow the first argument toDateTime.subtractto be aDateTime,datetime.datetime,datetime.timedelta, ordateutil.relativedeltaobject.Providezulu.ISO8601andzulu.TIMESTAMPas parse/format constants that can be used inzulu.parse(string, zulu.ISO8601)andDateTime.format(zulu.ISO8601).Remove special parse format string'timestamp'in favor of using just'X'as defined inzulu.TIMESTAMP.breaking changeImportzulu.parser.formattozulu.format.Fix bug inDateTimeaddition operation that resulted in a nativedatetimebeing returned instead ofDateTime.v0.2.0 (2016-08-02)AddDateTime.datetimeproperty that returns a native datetime.AddDateTime.fromgmtimethat creates aDateTimefrom a UTC basedtime.struct_time.AddDateTime.fromlocaltimethat creates aDateTimefrom a localtime.struct_time.AddDateTime.isleapmethod that returns whether its year is a leap year.AddDateTime.leapdaysthat calculates the number of leap days between its year and another year.AddDateTime.start_of/end_ofand other variants that return the start of end of a time frame:start/end_of_centurystart/end_of_decadestart/end_of_yearstart/end_of_monthstart/end_of_daystart/end_of_hourstart/end_of_minutestart/end_of_secondAddDateTime.spanthat returns the start and end of a time frame.AddDateTime.span_rangethat returns a range of spans.AddDateTime.rangethat returns a range of datetimes.AddDateTime.addandDateTime.submethods.Addyearsandmonthsarguments toDateTime.shift/add/sub.Drop support for milliseconds fromDateTime.shift/add/sub.breaking changeMakeDateTime.parse/formatunderstand a subset ofUnicode date patterns.Set defaults for year (1970), month (1), and day (1) arguments to newDateTimeobjects. Creating a newDateTimenow defaults to the start of the POSIX epoch.v0.1.2 (2016-07-26)Don’t pin install requirements to a specific version; use>=instead.v0.1.1 (2016-07-26)Fix bug inDateTime.naivethat resulted in aDateTimeobject being returned instead of a nativedatetime.v0.1.0 (2016-07-26)First release.MIT LicenseCopyright (c) 2020 Derrick GillandPermission 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.
zum
ZumStop writing scripts to interact with your APIs. Call them as CLIs instead.Zum(German word roughly meaning "to the" or "to" depending on the context, pronounced/tsʊm/) is a tool that lets you describe a web API using aTOMLfile and then interact with that API using your command line. This means thatthe days of writing custom scripts to help you interact and develop each of your APIs are over. Just create azum.toml, describe your API and forget about maintaining more code!Why Zum?While there are tools out there with goals similar tozum, the scopes are quite different. The common contenders areOpenAPI-based tools (likeSwaggerUI) andcURL. To me, using an OpenAPI-based documentation tool is essential on any large enough API, but the description method isveryverbose and quite complex, so often times it is added once the API has quite a few endpoints. On the other hand, cURL gets very verbose and tedious very fast when querying APIs, so I don't like to use it when developing my APIs. As a comparison, here's acurlcommand to query a local endpoint with a JSON body:curl--header"Content-Type: application/json"\--requestPOST\--data'{"name": "Dani", "city": "Santiago"}'\http://localhost:8000/living-beingsAnd here is thezumcommand to achieve the same result:zumcreateapplication/jsonDaniSantiagoNow, imagine having to run this command hundreads of times during API development changing only the values on the request body, for example. You can see how using cURL isnot ideal.Thecomplete documentationis available on theofficial website.InstallationInstall using pip!pipinstallzumUsageBasic UsageThe basic principle is simple:Describe your API using azum.tomlfile.Use thezumCLI to interact with your API.We get morein-depthwith how to structure thezum.tomlfile and how to use thezumCLI onthe complete documentation, but for now let's see a very basic example. Imagine that you are developing an API that gets the URL ofa song on YouTube. This API, for now, has only 1 endpoint:GET /song(clearly aWIP). To describe your API, you would have to write azum.tomlfile similar to this one:[metadata]server="http://localhost:8000"[endpoints.dada]route="/song"method="get"Now, to get your song's URL, all you need to do is to run:zumdadaNotice that, after thezumcommand, we passed an argument, that in this case wasdada. This argument tellszumthat it should interact with the endpoint described on thedadaendpoint section, denoted by the header[endpoints.dada]. As a rule, to access an endpoint described by the header[endpoints.{my-endpoint-name}], you will call thezumcommand with the{my-endpoint-name}argument:zum{my-endpoint-name}params,headersandbodyBeware!There are some nuances on these attribute definitions, so readingthe complete documentationishighly recommended.Theparamsof an endpointOn the previous example, theroutewas static, which means thatzumwillalwaysquery the same route. For some things, this might not be the best of ideas (for example, for querying entities on REST APIs), and you might want to interpolate a value on theroutestring. Let's say that there's a collection of songs, and you wanted to get the song withid57. Your endpoint definition should look like the following:[endpoints.get-song]route="/songs/{id}"method="get"params=["id"]As you can see, the element insideparamsmatches the element inside the brackets on theroute. This means that whatever parameter you pass to thezumCLI, it will be replaced on therouteon-demand:zumget-song57Now,zumwill send aGETHTTP request tohttp://localhost:8000/songs/57. Pretty cool!Theheadersof an endpointTheheadersare definedexactlythe same as theparams. Let's see a small example to illustrate how to use them. Imagine that you have an API that requiresJWTauthorization toGETthe songs of its catalog. Let's define that endpoint:[endpoints.get-authorized-catalog]route="/catalog"method="get"headers=["Authorization"]Now, to acquire the catalog, we would need to run:zumget-authorized-catalog"Bearer super-secret-token"⚠Warning: Notice that, for the first time, we surrounded something with quotes on the CLI. The reason we did this is that, without the quotes, the console has no way of knowing if you want to pass a parameter with a space in the middle or if you want to pass multiple parameters, so it defaults to receiving the words as multiple parameters. To stop this from happening, you can surround the string in quotes, and now the whole string will be interpreted as only one parameter with the space in the middle of the string. This will be handy on future examples, sokeep it in mind.This will send aGETrequest tohttp://localhost:8000/catalogwith the following headers:{"Authorization":"Bearer super-secret-token"}And now you have your authorization-protected music catalog!Thebodyof an endpointJust likeparamsandheaders, thebody(the body of the request) gets defined as an array:[endpoints.create-living-being]route="/living-beings"method="post"body=["name","city"]To run this endpoint, you just need to run:zumcreate-living-beingDaniSantiagoThis will send aPOSTrequest tohttp://localhost:8000/living-beingswith the following request body:{"name":"Dani","city":"Santiago"}Notice that you can also cast the parameters to different types. You can read more about this on the complete documentation's section aboutthe request body.Combiningparams,headersandbodyOf course, sometimes you need to use someparams, someheadersandabody. For example, if you wanted to create a song inside an authorization-protected album (anested entity), you would need to use the album's id as aparam, the "Authorization" key inside theheadersto get the authorization and the new song's data as thebody. For this example, the song has aname(which is a string) and adurationin seconds (which is an integer). Let's describe this situation![endpoints.create-song]route="/albums/{id}/songs"method="post"params=["id"]headers=["Authorization"]body=["name",{name="duration",type="integer"}]Now, you can call the endpoint using:zumcreate-song8"Bearer super-secret-token""Con Altura"161This will callPOST /albums/8/songswith the following headers:{"Authorization":"Bearer super-secret-token"}And the following request body:{"name":"Con Altura","duration":161}As you can probably tell,zumreceives theparamsfirst on the CLI, then theheadersand then thebody. Inpythonicterms, whatzumdoes is that it kind ofunpacksthe three arrays consecutively, something like the following:arguments=[*params,*headers,*body]zum(arguments)DevelopingClone the repository:gitclonehttps://github.com/daleal/zum.gitcdzumRecreate environment:makeget-poetry makebuild-envRun the linters:makeblackflake8isortmypypylintRun the tests:maketestsResourcesOfficial WebsiteIssue TrackerContributing Guidelines
zumanji
Copyright:(c) 2012 DISQUSlicense:Apache License 2.0, see LICENSE for more details.
zumbata-kamagra-bot-zumbata
Failed to fetch description. HTTP Status Code: 404
zumi
No description available on PyPI.
zumidashboard
No description available on PyPI.
zumpy
An array library inspired by numpy, written in C and ported to Python using ctypes.
zums
UNKNOWN
zumservices-api-py
ZUM Services Python API InterfaceThis wrapper allows you to easily interact with theZUM Services1.0.1 API to quickly develop applications that interact with theZumCoinNetwork.Table of ContentsInstallationIntializationDocumentationMethodsInstallationpipinstallzumservices-api-pyIntializationimportosfromZUMservicesimportZSos.environ["ZUM_SERVICES_TOKEN"]="eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoieW8iLCJhcHBJZCI6MjAsInVzZXJJZCI6MiwicGVybWlzc2lvbnMiOlsiYWRkcmVzczpuZXciLCJhZGRyZXNzOnZpZXciLCJhZGRyZXNzOmFsbCIsImFkZHJlc3M6c2NhbiIsImFkZHJlc3M6ZGVsZXRlIiwidHJhbnNmZXI6bmV3IiwidHJhbnNmZXI6dmlldyJdLCJpYXQiOjE1Mzk5OTQ4OTgsImV4cCI6MTU3MTU1MjQ5OCwiYXVkIjoiZ2FuZy5jb20iLCJpc3MiOiJUUlRMIFNlcnZpY2VzIiwianRpIjoiMjIifQ.KkKyg18aqZfLGMGTnUDhYQmVSUoocrr4CCdLBm2K7V87s2T-3hTtM2MChJB2UdbDLWnf58GiMa_t8xp9ZjZjIg"os.environ["ZUM_SERVICES_TIMEOUT"]=2000Generate a token with the ZUM ServicesDashboardand store it as the variableZUM_SERVICES_TOKENin your os environment along withZUM_SERVICES_TIMEOUTif you wish the change the default timeout of 2000.DocumentationAPI documentation is available athttps://zum.services/documentationMethodscreateAddress()Create a new ZUM addressesZS.createAddress()getAddress(address)Get address details by addressZS.getAddress("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC")deleteAddress(address)Delete a selected ZUM addressZS.deleteAdddress("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC")getAddresses()View all addresses.ZS.getAddresses()scanAddress(address, blockIndex)Scan an address for transactions between a 100 block range starting from the specified blockIndex.ZS.scanAddress("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC",899093)getAddressKeys(address)Get the public and secret spend key of an address.ZS.getAddressKeys("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC")integrateAddress(address, paymentId)Create an integrated address with an address and payment ID.ZS.integrateAddress("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC","7d89a2d16365a1198c46db5bbe1af03d2b503a06404f39496d1d94a0a46f8804")getIntegratedAddresses(address)Get all integrated addresses by address.ZS.getIntegratedAddresses("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC")getFee(amount)Calculate the ZUM Services fee for an amount specified in ZUM with two decimal points.ZS.getFee(1.23)createTransfer(sender, receiver, amount, fee, paymentId, extra)Send a ZUM transaction with an address with the amount specified two decimal points.ZS.createTransfer("Zum1yfSrdpfiSNG5CtYmckgpGe1FiAc9gLCEZxKq29puNCX92DUkFYFfEGKugPS6EhWaJXmhAzhePGs3jXvNgK4NbWXG4yaGBHC","Zum1yhbRwHsXj19c1hZgFzgxVcWDywsJcDKURDud83MqMNKoDTvKEDf6k7BoHnfCiPbj4kY2arEmQTwiVmhoELPv3UKhjYjCMcm",1234.56,1.23,"7d89a2d16365a1198c46db5bbe1af03d2b503a06404f39496d1d94a0a46f8804","3938f915a11582f62d93f82f710df9203a029f929fd2f915f2701d947f920f99")You can leave the last two fields (paymentId and extra) blank.getTransfer(address)Get a transaction details specified by transaction hash.ZS.getTransfer("EohMUzR1DELyeQM9RVVwpmn5Y1DP0lh1b1ZpLQrfXQsgtvGHnDdJSG31nX2yESYZ")getWallet()Get wallet container info and health check.ZS.getWallet()getStatus()Get the current status of the ZUM Services infrastructure.ZS.getStatus()LicenseCopyright (c) 2019 ZumCoin Development Team Please see the included LICENSE file for more information.
zun
Team and repository tagsZunOpenStack Containers serviceZun (ex. Higgins) is the OpenStack Containers service. It aims to provide an API service for running application containers without the need to manage servers or clusters.Free software: Apache licenseGet Started:https://docs.openstack.org/zun/latest/contributor/quickstart.htmlDocumentation:https://docs.openstack.org/zun/latest/Source:https://opendev.org/openstack/zunBugs:https://bugs.launchpad.net/zunBlueprints:https://blueprints.launchpad.net/zunREST Client:https://opendev.org/openstack/python-zunclientFeaturesTODO
zundamonai-streamer
No description available on PyPI.
zunda-python
Zunda PythonZunda: Japanese Enhanced Modality Analyzer client for Python.Zunda is an extended modality analyzer for Japanese. For details about Zunda, Seehttps://jmizuno.github.io/zunda/(Written in Japanese)this module requires installing Zunda, which is available at (https://github.com/jmizuno/zunda/releases), CaboCha (https://taku910.github.io/cabocha/), and MeCab (http://taku910.github.io/mecab/).Contributions are welcome!Installation# Install Zunda wget https://github.com/jmizuno/zunda/archive/2.0b4.tar.gz tar xzf zunda-2.0b4.tar.gz rm zunda-2.0b4.tar.gz cd zunda-2.0b4 ./configure make sudo make install cd ../ rm -rf zunda-2.0b4 # Install zunda-python pip install zunda-pythonExampleimportzundaparser=zunda.Parser()parser.parse('花子は太郎を食事に誘った裕子が嫌いだった')# => [{'assumptional': '0','authenticity':'成立','chunks':[{'func':'に','head':'食事','link_from':[],'link_to':3,'score':1.883877,'words':[{'feature':'名詞,サ変接続,*,*,*,*,食事,ショクジ,ショクジ','funcexp':'O','surface':'食事'},{'feature':'助詞,格助詞,一般,*,*,*,に,ニ,ニ','funcexp':'B:判断','surface':'に'}]}],'sentiment':'0','source':'筆者','tense':'非未来','type':'叙述','word':'食事','words':'食事に'},{'assumptional':'0','authenticity':'成立','chunks':[{'func':'を','head':'太郎','link_from':[],'link_to':3,'score':1.640671,'words':[{'feature':'名詞,固有名詞,地域,一般,*,*,太郎,タロウ,タロー','funcexp':'O','surface':'太郎'},{'feature':'助詞,格助詞,一般,*,*,*,を,ヲ,ヲ','funcexp':'O','surface':'を'}]},{'func':'に','head':'食事','link_from':[],'link_to':3,'score':1.883877,'words':[{'feature':'名詞,サ変接続,*,*,*,*,食事,ショクジ,ショクジ','funcexp':'O','surface':'食事'},{'feature':'助詞,格助詞,一般,*,*,*,に,ニ,ニ','funcexp':'B:判断','surface':'に'}]},{'func':'た','head':'誘っ','link_from':[1,2],'link_to':4,'score':1.565227,'words':[{'feature':'動詞,自立,*,*,五段・ワ行促音便,連用タ接続,誘う,サソッ,サソッ','funcexp':'O','surface':'誘っ'},{'feature':'助動詞,*,*,*,特殊・タ,基本形,た,タ,タ','funcexp':'B:完了','surface':'た'}]}],'sentiment':'0','source':'筆者','tense':'非未来','type':'叙述','word':'誘っ','words':'太郎を食事に誘った'},{'assumptional':'0','authenticity':'成立','chunks':[{'func':'は','head':'花子','link_from':[],'link_to':5,'score':-1.81792,'words':[{'feature':'名詞,固有名詞,人名,名,*,*,花子,ハナコ,ハナコ','funcexp':'O','surface':'花子'},{'feature':'助詞,係助詞,*,*,*,*,は,ハ,ワ','funcexp':'O','surface':'は'}]},{'func':'が','head':'裕子','link_from':[3],'link_to':5,'score':-1.81792,'words':[{'feature':'名詞,固有名詞,人名,名,*,*,裕子,ユウコ,ユーコ','funcexp':'O','surface':'裕子'},{'feature':'助詞,格助詞,一般,*,*,*,が,ガ,ガ','funcexp':'O','surface':'が'}]},{'func':'た','head':'嫌い','link_from':[0,4],'link_to':-1,'score':0.0,'words':[{'feature':'名詞,形容動詞語幹,*,*,*,*,嫌い,キライ,キライ','funcexp':'O','surface':'嫌い'},{'feature':'助動詞,*,*,*,特殊・ダ,連用タ接続,だ,ダッ,ダッ','funcexp':'B:判断','surface':'だっ'},{'feature':'助動詞,*,*,*,特殊・タ,基本形,た,タ,タ','funcexp':'B:完了','surface':'た'}]}],'sentiment':'0','source':'筆者','tense':'非未来','type':'叙述','word':'嫌い','words':'花子は裕子が嫌いだった'}]LICENSEMIT LicenseCopyrightZunda Python (c) 2019- Yukino Ikegami. All Rights Reserved.Zunda (Original version) (c) 2013- @jmizunoACKNOWLEDGEMENTThis module uses Zunda. I thank to @jmizuno and Tohoku University Inui-Okazaki Lab.CHANGES0.1.3 (2019-11-30)bugfix for installation on conda (thanks @Kensuke-Mitsuzawa)0.1.2 (2019-02-24)First release.
zungle
Zungle: Python Web Framework built for learning purposesZungle is a Python web framework built for learning purposes.It's a WSGI framework and can be used with any WSGI application server such as Gunicorn.InstallationpipinstallzungleBasic usage:fromzungle.apiimportAPIapp=API()@app.route("/home")defhome(request,response):response.text="Hello from the HOME page"@app.route("/hello/{name}")defgreeting(request,response,name):response.text=f"Hello,{name}"@app.route("/book")classBooksResource:defget(self,req,resp):resp.text="Books Page"defpost(self,req,resp):resp.text="Endpoint to create a book"@app.route("/template")deftemplate_handler(req,resp):resp.body=app.template("index.html",context={"name":"Zungle","title":"Best Framework"}).encode()Unit TestsThe recommended way of writing unit tests is withpytest. There are two built in fixtures that you may want to use when writing unit tests with Zungle. The first one isappwhich is an instance of the mainAPIclass:deftest_route_overlap_throws_exception(app):@app.route("/")defhome(req,resp):resp.text="Welcome Home."withpytest.raises(AssertionError):@app.route("/")defhome2(req,resp):resp.text="Welcome Home2."The other one isclientthat you can use to send HTTP requests to your handlers. It is based on the famousrequestsand it should feel very familiar:deftest_parameterized_route(app,client):@app.route("/{name}")defhello(req,resp,name):resp.text=f"hey{name}"assertclient.get("http://testserver/matthew").text=="hey matthew"TemplatesThe default folder for templates istemplates. You can change it when initializing the mainAPI()class:app=API(templates_dir="templates_dir_name")Then you can use HTML files in that folder like so in a handler:@app.route("/show/template")defhandler_with_template(req,resp):resp.html=app.template("example.html",context={"title":"Awesome Framework","body":"welcome to the future!"})Static FilesJust like templates, the default folder for static files isstaticand you can override it:app=API(static_dir="static_dir_name")Then you can use the files inside this folder in HTML files:<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><title>{{title}}</title><linkhref="/static/main.css"rel="stylesheet"type="text/css"></head><body><h1>{{body}}</h1><p>This is a paragraph</p></body></html>MiddlewareYou can create custom middleware classes by inheriting from thezungle.middleware.Middlewareclass and overriding its two methods that are called before and after each request:fromzungle.apiimportAPIfromzungle.middlewareimportMiddlewareapp=API()classSimpleCustomMiddleware(Middleware):defprocess_request(self,req):print("Before dispatch",req.url)defprocess_response(self,req,res):print("After dispatch",req.url)app.add_middleware(SimpleCustomMiddleware)
zuni
No description available on PyPI.
zunis
ZüNIS: Normalizing flows for neural importance samplingZüNIS (Zürich Neural Importance Sampling) a work-in-progress Pytorch-based library for Monte-Carlo integration based on Neural imporance sampling[1], developed at ETH Zürich. In simple terms, we use artificial intelligence to compute integrals faster.The goal is to provide a flexible library to integrate black-box functions with a level of automation comparable to the VEGAS Library[2], while using state-of-the-art methods that go around the limitations of existing tools.InstallationUsingpipThe library is available on PyPI:pipinstallzunisThe latest version can be installed directly from GitHub:pipinstall'git+https://github.com/ndeutschmann/zunis#egg=zunis&subdirectory=zunis_lib'Setting up a development environmentIf you would like to contribute to the library, run the benchmarks or try the examples, the easiest is to clone this repository directly and install the extended requirements:# Clone the repositorygitclonehttps://github.com/ndeutschmann/zunis.git./zunis# Create a virtual environment (recommended)python3.7-mvenvzunis_venvsource./zunis_venv/bin/activate pipinstall--upgradepip# Install the requirementscd./zunis pipinstall-rrequirements.txt# Run one benchmark (GPU recommended)cd./experiments/benchmarks pythonbenchmark_hypersphere.pyLibrary usageFor basic applications, the integrator is provided with default choices and can be created and used as follows:importtorchfromzunis.integrationimportIntegratordevice=torch.device("cuda")d=2deff(x):returnx[:,0]**2+x[:,1]**2integrator=Integrator(d=d,f=f,device=device)result,uncertainty,history=integrator.integrate()The functionfis integrated over thed-dimensional unit hypercube andtakestorch.Tensorbatched inputs with shape(N,d)for arbitrary batch sizeNondevicereturnstorch.Tensorbatched inputs with shape(N,)for arbitrary batch sizeNondeviceA more systematic documentation is under constructionhere.
z-units
z-unitsA simple unit-converter for chemical engineersFeatureGauge pressure units (MPag, kPag, psig, ...) are ready for useFriendly to HYSYS userInstallpipinstallz-unitsQuickstart>>>fromz_unitsimportquantityasq>>>f=q.MolarFlow(3)>>>f<MolarFlow(3,'kmol/s')>f.value,f.unit(3,<Unit('kmol/s')>)>>>f.to('kmol/h')<MolarFlow(10800.0,'kmol/h')>>>>q.Length(100,'cm')==q.Length(1000,'mm')True>>>q.Pressure(15,'psi').to('MPag')<Pressure(0.0020963594,'MPag')>Related to gauge pressure, local atmospheric pressure (default: 101325 Pa) can be altered:>>>fromz_unitsimportconfig# Before>>>q.Pressure(100,'kPa').to('kPag')<Pressure(-1.325,'kPag')># Set to 50e3 Pa (50 kPa)>>>config.set_local_atmospheric_pressure(50e3)# After>>>q.Pressure(100,'kPa').to('kPag')<Pressure(50.0,'kPag')>Standard temperature (default: 20 degC) can be redefined, affecting standard cubic meter "Sm**3":# Before>>>q.Substance(100,'Nm3').to('Sm3')<Substance(107.321984,'Sm3')># Set to 15 degC>>>config.set_standard_temperature(15)# After>>>q.Substance(100,'Nm3').to('Sm3')<Substance(105.491488,'Sm3')>Format quantity to string with styles:# Only value>>>format(q.MolarEntropy(100))'100'# With unit, quick style>>>format(q.MolarEntropy(100),'u')'100 kJ/kmol-C'# With unit, definition style>>>format(q.MolarEntropy(100),'up')'100 kJ/(kmol*C)'Predefined QuantitiesLengthAreaVolumeTimeMassForceSubstanceEnergyVelocityTemperatureDeltaTemperaturePressureVolumeFlowMassDensityHeatFlowMolarFlowMassFlowMolarDensityMolarHeatCapacityMolarEntropyMolarHeatThermalConductivityViscositySurfaceTensionMassHeatCapacityMassEntropyMassHeatStandardGasFlowKinematicViscosityMolarVolumeFractionDimensionlessAbout itAs a chemical engineer, the Gauge-Pressure units are very useful to me. Unfortunately those units are not supported in some popular modules, so I reinvent the wheel.
zun-tempest-plugin
Team and repository tagsTempest Integration of ZunThis directory contains Tempest tests to cover the Zun project, as well as a plugin to automatically load these tests into tempest.See the Tempest plugin docs for information on using it:https://docs.openstack.org/tempest/latest/#using-pluginsFree software: Apache licenseDocumentation:https://docs.openstack.org/zun-tempest-plugin/latestSource:https://opendev.org/openstack/zun-tempest-pluginBugs:https://bugs.launchpad.net/zunRunning the testsEdit/opt/stack/tempest/etc/tempest.conf:Add the[container_service]section, configuremin_microversionandmax_microversion:[container_service]min_microversion=1.32max_microversion=1.32NoteYou might need to modify the min/max microversion based on your test environment.To run all tests from this plugin, install Zun into your environment and navigate to tempest directory:$ cd /opt/stack/tempestRun this command:$ tempest run --regex zun_tempest_plugin.tests.tempest.apiTo run a single test case, run with the test case name, for example:$ tempest run --regex zun_tempest_plugin.tests.tempest.api.test_containers.TestContainer.test_list_containers
zun-ui
Zun UIFree software: Apache licenseSource:https://opendev.org/openstack/zun-uiBugs:https://bugs.launchpad.net/zun-uiManual InstallationInstall according toZun UI documentation.Enabling in DevStackAdd this repo as an external repository into yourlocal.conffile:[[local|localrc]] enable_plugin zun-ui https://github.com/openstack/zun-ui
zunzun
Zunzun FrameworkZunzun is a Python framework that uses other libraries to implement its features. Ones of them are:injectorIt's used to Dependency Injection.clickFor creating commands line interface.blinkerProvides a fast dispatching system.SQLAlchemyThe Python SQL Toolkit and Object Relational Mapper.Create an applicationClone the example application fromhttps://github.com/aprezcuba24/zunzun_appCreate .env file base on .env.exampleConfigure database configurationYou can use vscode to open the application in a container.Star the application using this command.python manage.py core runserverOpen the browser in this urlhttp://localhost:8001/ControllerWe can create two types of controller, a function controller, or a class controller.Function [email protected]("/")defregister():return"Register"Class controllerTo create a class controller we can use the following commandpython zunzun.py maker controller Role --route="/role"Where "Role" will be the name of the controller and "/role" the path to access the controller.The command will generate the fileapp/controllers/role.pyfromzunzunimportResponsefrommainimportrouterclassRoleController:@router.get('/role')defindex(self):return"RoleController Index"In the class controller or in the function controller we can inject dependencies. For example, if we have a service named "PaypalService" we can inject it, with the following code.frommainimportrouterfromapp.servicesimportPaypalService@router.post("/")defregister(paypal:PaypalService):paypal.call_a_method()return"Register"In a controller class, we can inject dependencies in the constructor or in any function.fromzunzunimportResponsefrommainimportrouterfromapp.servicesimportPaypalService,SomeServiceclassRoleController:def__init__(self,some_service:SomeService):[email protected]('/role')defindex(self,paypal:PaypalService):return"RoleController Index"CommandsCommands allow us to implement command line features. To do that we can use the following command.python manager.py maker command roleWhere "role" will be the name of the command. This command will create the following fileapp/commands/role.py.importclickfrominjectorimportsingleton,injectfromzunzunimportCommand@singletonclassroleCommand(Command):@injectdef__init__(self):super().__init__("role")self.add_option("--some-option")self.add_argument("some-argument")defhandle(self,some_option,some_argument):click.echo(f"roleCommand [some_argument:{some_argument}] [some_option:{some_option}]")To use the new command we can type the following in the console.python manager.py app role "An argument value" --some-option="An option value"ListenerThe listener allows us to implement the Event-Dispatcher pattern. To create a new listener with its signal we can use the following command.python manager.py maker listener Role RoleWhere the first word "Role" will be the listener name and the second will be the signal name. The command will generate the following files:Signal fileapp/signals/role.pyListener fileapp/listeners/role.pyThe signal file will have this code.fromzunzunimportSignalfrominjectorimportsingleton@singletonclassRoleSignal(Signal):passThe listener file will have this code.frominjectorimportsingleton@singletonclassRoleListener:def__call__(self,sender,**kwargs):passServicesWe can create classes to implement any logic that we need. For example to create a service to integrate Paypal we can use the following command.python manager.py maker service PaypalThe command will create the fileapp/services/paypal.pywith the following code.frominjectorimportsingleton,inject@singletonclassPaypalService:@injectdef__init__(self):passORMZunzun usesSQLAlchemyto implement the ORM features. The framework uses two type of classes.The model represents a single row in the database.The repository is a class to implement the queries to the database.To create the model and its repository we can use the following command.python manager.py orm model_create RoleThe model will befromzunzunimportormfromsqlalchemyimportColumn,IntegerclassRole(orm.BaseModel):__tablename__="Role"id=Column(Integer,primary_key=True)The repository will befrominjectorimportsingletonfromzunzunimportormfromapp.modelimportRole@singletonclassRoleRepository(orm.BaseRepository):defnew(self,**kwargs):returnRole(**kwargs)Dependency injectionThe framework uses this pattern to manage dependencies. To know how you can use see the documentation oninject
zunzuncito
Keep it simple and small, avoiding extra complexity at all cost.KISSCreate routes on the fly or by defining regular expressions.Support API versions out of the box without altering routes.Thread safety.Via decorator or in a defined route, accepts only certainHTTP methods.Follow the single responsibilityprinciple.Be compatible with any WSGI server. Example:uWSGI,Gunicorn,Twisted, etc.Tracing Request-ID “rid” per request.Compatibility with Google App Engine.demoMulti-tenantSupport.Ability to create almost anything easy, example: Supportchunked transfer encoding.InstallVia pip:$ pip install zunzuncitoIf you don’t have pip, after downloading the sources, you can run:$ python setup.py installQuick starthttp://docs.zunzun.io/en/latest/Quickstart.htmlDocumentationdocs.zunzun.iowww.zunzun.ioWhat ?ZunZuncito is a python package that allows to create and maintainRESTAPI’s without hassle.The simplicity for sketching and debugging helps to develop very fast; versioning is inherit by default, which allows to serve and maintain existing applications, while working in new releases with no need to create separate instances. All the applications are WSGIPEP 333compliant, allowing to migrate existing code to more robust frameworks, without need to modify the existing code.Why ?The need to upload large files by chunks and support resumable uploads trying to accomplish something like thenginx upload moduledoes in pure python.The idea of creating ZunZuncito, was the need of a very small and light tool (batteries included), that could help to create and deploy REST API’s quickly, without forcing the developers to learn or follow a complex flow but, in contrast, from the very beginning, guide them to properly structure their API, giving special attention to “versioned URI’s”, having with this a solid base that allows to work in different versions within a single ZunZun instance without interrupting service of any existing APIresources.
zuolar_nester
UNKNOWN
zuoning-lama-cleaner
Failed to fetch description. HTTP Status Code: 404
zuora
UNKNOWN
zuora-aqua-client-cli
zuora-aqua-client-cliRun ZOQL queries through AQuA from the command lineInstallationMacpip3 install zuora-aqua-client-cliThe executable will be installed to/usr/local/bin/zaccLinuxpip3 install zuora-aqua-client-cliThe executable will be installed to~/.local/bin/zaccMake sure~/.local/bin/is added to your$PATHConfigurationConfiguration should be provided by the-c /path/to/fileoption.If option is not provided, will be read from~/.zacc.iniExample config[zacc] # When environement option is ommited the default environment will be used default_environment = preprod [prod] # Use production Zuora endpoints, defaults to `false` production = true client_id = <oauth_client_id> client_secret = <oauth_client_secret> # Optional partner and project fields can be configured per environment, see more on what these do: # https://knowledgecenter.zuora.com/Central_Platform/API/AB_Aggregate_Query_API/B_Submit_Query # partner = partner # project = myproject [mysandbox] client_id = <oauth_client_id> client_secret = <oauth_client_secret>UsageCheatsheet# List fiels for resource $ zacc describe Account Account AccountNumber - Account Number AdditionalEmailAddresses - Additional Email Addresses AllowInvoiceEdit - Allow Invoice Editing AutoPay - Auto Pay Balance - Account Balance ... Related Objects BillToContact<Contact> - Bill To DefaultPaymentMethod<PaymentMethod> - Default Payment Method ParentAccount<Account> - Parent Account SoldToContact<Contact> - Sold To # Request a bearer token, then exit $ zacc bearer Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaa # Execute an AQuA job $ zacc query "select Account.Name from Account where Account.CreatedDate > '2019-01-10'" Account.Name John Doe Jane Doe # Save results to CSV file instead of printing it $ zacc query ~/query_names.zoql -o account_names.csv # Execute an AQuA job from a ZOQL query file $ zacc query ~/query_names.zoql Account.Name John Doe Jane Doe # Use different configurations than default $ zacc -c ~/.myotherzaccconfig.ini -e notdefualtenv query ~/query_names.zoqlCommandszaccUsage: zacc [OPTIONS] COMMAND [ARGS]... Sets up an API client, passes to commands in context Options: -c, --config-filename PATH Config file containing Zuora ouath credentials [default: /Users/janosmolnar/.zacc.ini] -e, --environment TEXT Zuora environment to execute on --project TEXT Project name --partner TEXT Partner name -m, --max-retries FLOAT Maximum retries for query --help Show this message and exit. Commands: bearer Prints bearer than exits describe List available fields of Zuora resource query Run ZOQL Queryzacc queryUsage: zacc query [OPTIONS] Run ZOQL Query Options: -o, --output PATH Where to write the output to, default is STDOUT --help Show this message and exit.zacc describeUsage: zacc describe [OPTIONS] RESOURCE List available fields of Zuora resource Options: --help Show this message and exit.zacc bearerUsage: zacc bearer [OPTIONS] Prints bearer than exits Options: --help Show this message and exit.Useful stuffHas a lot of graphs on Resource relationships:https://knowledgecenter.zuora.com/BB_Introducing_Z_Business/D_Zuora_Business_Objects_Relationshiphttps://community.zuora.com/t5/Engineering-Blog/AQUA-An-Introduction-to-Join-Processing/ba-p/13262
zuora-client
This is a simple Python client designed to communicate with Zuora in SOAP.Handle the session, transport and logging parts to make your API calls.This means that the client is completly agnostic.
zuorapy
No description available on PyPI.
zuoraquery
UNKNOWN
zuora-swagger-client
Zuora API Reference
zuowen
CPM作文生成器项目描述在线体验地址:https://zuowen.wufan.fun/(在这个人的基础上加以改进,做出的新版CPM模型,适用于新手) CPM(Chinese Pretrained Models)模型是北京智源人工智能研究院和清华大学发布的中文大规模预训练模型。官方发布了三种规模的模型,参数量分别为109M、334M、2.6B,用户需申请与通过审核,方可下载。 由于原项目需要考虑大模型的训练和使用,需要安装较为复杂的环境依赖,使用上也较为复杂。 本项目采用了109M的CPM模型(若资源允许也可以考虑334M的模型),并且简化了模型的训练和使用。本项目是基于CPM模型的中文文本生成项目,可用于作文、小说、新闻、古诗等中文生成任务,并且训练和分享了中文作文生成模型,取得了不错的生成效果。 本项目提供了数据预处理、模型训练、文本生成、Http服务等代码模块。 详情可参考CPM模型论文,CPM官网,项目源码。运行环境python>=3.6、transformers==4.6.0、sentencepiece==0.1.94、torch==1.7.0、jieba == 0.42.1、streamlit == 1.10.0、tqdm == 4.64.0模型参数与训练细节由于GPU资源有限,本项目使用cpm-small.json中的模型参数,若资源充足,可尝试cpm-medium.json中的参数配置。本项目的部分模型参数如下:n_ctx: 1024n_embd: 768n_head: 12n_layer: 12n_positions: 1024vocab_size: 30000对26w篇作文进行预处理之后,得到60w+长度为200的训练数据。显卡为三张GTX 1080Ti,batch_size=50,三张卡显存满载,一轮训练大约需要3个小时。训练40轮之后,loss降到2.1左右,单词预测准确率大约为54%。快速启动使用pip进行安装:pipinstallzuowen使用请转到使用篇。使用源码安装(已废弃)gitclonehttps://github.com/WindowsRegedit/zuowencdzuowen pythonsetup.pyinstall使用同Pip篇。使用本模块提供一下入口点:zuowenzuowen-uizuowen-preprocesszuowen-trainer入口点zuowen生成作文的命令行接口。完整介绍如下:PS D:> zuowen --help usage: zuowen [-h] [--device DEVICE] [--temperature TEMPERATURE] [--topk TOPK] [--topp TOPP] [--repetition_penalty REPETITION_PENALTY] [--context_len CONTEXT_LEN] [--max_len MAX_LEN] [--log_path LOG_PATH] [--no_cuda] [--model_path MODEL_PATH] [--title TITLE] [--context CONTEXT] optional arguments: -h, --help show this help message and exit --device DEVICE 生成设备 --temperature TEMPERATURE 生成温度 --topk TOPK 最高几选一 --topp TOPP 最高积累概率 --repetition_penalty REPETITION_PENALTY 重复惩罚参数 --context_len CONTEXT_LEN 每一步生成时,参考的上文的长度 --max_len MAX_LEN 生成的最长长度 --log_path LOG_PATH 日志存放位置 --no_cuda 不使用GPU进行预测 --model_path MODEL_PATH 模型存放位置 --title TITLE 作文标题 --context CONTEXT 作文上文入口点zuowen-ui此程序没有参数。调用后会在本地启动作文生成的服务。 使用Streamlit打造而成。 应用截图:入口点zuowen-preprocess(对于开发者) 每篇作文对应一个txt文件,txt内容格式如下:--- 标题:xxx 日期:xxxx-xx-xx xx:xx:xx 作者:xxx --- 内容对于每个txt文件,首先取出标题与内容,将标题与内容按照"title[sep]content[eod]"的方式拼接起来,然后对其进行tokenize,最后使用滑动窗口对内容进行截断,得到训练数据。 运行如下命令,进行数据预处理。注:预处理之后的数据保存为train.pkl,这是一个list,list中每个元素表示一条训练数据。zuowen-preoprocess --data_path data/zuowen --save_path data/train.pkl --win_size 200 --step 200完整参数如下:PS D:> zuowen-preprocess --help usage: zuowen-preprocess [-h] [--vocab_file VOCAB_FILE] [--log_path LOG_PATH] [--data_path DATA_PATH] [--save_path SAVE_PATH] [--win_size WIN_SIZE] [--step STEP] optional arguments: -h, --help show this help message and exit --vocab_file VOCAB_FILE 词表路径 --log_path LOG_PATH 日志存放位置 --data_path DATA_PATH 数据集存放位置 --save_path SAVE_PATH 对训练数据集进行tokenize之后的数据存放位置 --win_size WIN_SIZE 滑动窗口的大小,相当于每条数据的最大长度 --step STEP 滑动窗口的滑动步幅入口点zuowen-trainer运行如下命令,使用预处理后的数据训练模型。zuowen-trainer --epochs 100 --batch_size 16 --device 0,1 --gpu0_bsz 5 --train_path data/train.pkl超参数说明:device:设置使用哪些GPUno_cuda:设为True时,不使用GPUvocab_path:sentencepiece模型路径,用于tokenizemodel_config:需要从头训练一个模型时,模型参数的配置文件train_path:经过预处理之后的数据存放路径max_len:训练时,输入数据的最大长度。log_path:训练日志存放位置ignore_index:对于该token_id,不计算loss,默认为-100epochs:训练的最大轮次batch_size:训练的batch sizegpu0_bsz:pytorch使用多GPU并行训练时,存在负载不均衡的问题,即0号卡满载了,其他卡还存在很多空间,抛出OOM异常。该参数可以设置分配到0号卡上的数据数量。lr:学习率eps:AdamW优化器的衰减率log_step:多少步汇报一次lossgradient_accumulation_steps:梯度累计的步数。当显存空间不足,batch_size无法设置为较大时,通过梯度累计,缓解batch_size较小的问题。save_model_path:模型输出路径pretrained_model:预训练的模型的路径num_workers:dataloader加载数据时使用的线程数量warmup_steps:训练时的warm up步数所有参数意思如下:PS D:> zuowen-trainer --help usage: zuowen-trainer [-h] [--device DEVICE] [--no_cuda] [--vocab_path VOCAB_PATH] [--model_config MODEL_CONFIG] [--train_path TRAIN_PATH] [--max_len MAX_LEN] [--log_path LOG_PATH] [--ignore_index IGNORE_INDEX] [--epochs EPOCHS] [--batch_size BATCH_SIZE] [--gpu0_bsz GPU0_BSZ] [--lr LR] [--eps EPS] [--log_step LOG_STEP] [--gradient_accumulation_steps GRADIENT_ACCUMULATION_STEPS] [--max_grad_norm MAX_GRAD_NORM] [--save_model_path SAVE_MODEL_PATH] [--pretrained_model PRETRAINED_MODEL] [--seed SEED] [--num_workers NUM_WORKERS] [--warmup_steps WARMUP_STEPS] optional arguments: -h, --help show this help message and exit --device DEVICE 设置使用哪些显卡 --no_cuda 不使用GPU进行训练 --vocab_path VOCAB_PATH sp模型路径 --model_config MODEL_CONFIG 需要从头训练一个模型时,模型参数的配置文件 --train_path TRAIN_PATH 经过预处理之后的数据存放路径 --max_len MAX_LEN 训练时,输入数据的最大长度 --log_path LOG_PATH 训练日志存放位置 --ignore_index IGNORE_INDEX 对于ignore_index的label token不计算梯度 --epochs EPOCHS 训练的最大轮次 --batch_size BATCH_SIZE 训练的batch size --gpu0_bsz GPU0_BSZ 0号卡的batch size --lr LR 学习率 --eps EPS AdamW优化器的衰减率 --log_step LOG_STEP 多少步汇报一次loss --gradient_accumulation_steps GRADIENT_ACCUMULATION_STEPS 梯度积累的步数 --max_grad_norm MAX_GRAD_NORM --save_model_path SAVE_MODEL_PATH 模型输出路径 --pretrained_model PRETRAINED_MODEL 预训练的模型的路径 --seed SEED 设置随机种子 --num_workers NUM_WORKERS dataloader加载数据时使用的线程数量 --warmup_steps WARMUP_STEPS warm up步数更新记录[2022.6.29] 使作文生成器在输入时需要等待的时间变短了很多。
zuoyeji
No description available on PyPI.
zup
zupdependenciesPython 3.8Installation$pipinstallzupInstalling ZigThis will install latest master Zig release and set it as defaultzigcommand in your system.Note that zup never modifies your system configuration and you must add the symlink directory that zup manages to your%PATH%on Windows or$PATHon other platforms.zupinstallmaster-dConfigurationConfig file is a python script that gets executed before any command is ran. It can be opened withzup config. This uses your default program for a filetype; on windows the default ispython.exe, please set it to a proper text editor or it won't open. Zup does not check or configure any system variables and can't know what the config will be opened with and it is your job as the owner of your system to configure it properly.# config.py# windows: Path(os.getenv('APPDATA')) / 'zup/config.py'# macos: Path.home() / 'Library/Preferences/zup/config.py'# other: Path.home() / '.config/zup/config.py'# url where index will be fetched from# default: 'https://ziglang.org/download/index.json'index_url=zup.config.default_index_url()# directory where zig compilers are installed# windows: Path(os.getenv('LOCALAPPDATA')) / 'zup'# macos: Path.home() / 'Library/Application Support/zup'# other: Path.home() / '.local/share/zup'install_dir=zup.config.default_install_dir()# directory where symlinks to compilers are created# windows: install_dir# macos: install_dir# other: Path.home() / '.local/bin'symlink_dir=zup.config.default_symlink_dir()
zupa
Playground for server management.Installationpipinstallzupa
zuper-auth
No description available on PyPI.
zuper-auth-z5
No description available on PyPI.
zuper-auth-z6
No description available on PyPI.
zuper-commons
No description available on PyPI.
zuper-commons-z5
No description available on PyPI.
zuper-commons-z6
No description available on PyPI.
zuper-commons-z7
No description available on PyPI.
zuper-graphs-z7
No description available on PyPI.
zuper-html-plus-z7
No description available on PyPI.
zuper-html-z7
No description available on PyPI.
zuper-ipce-comp
No description available on PyPI.
zuper-ipce-z5
No description available on PyPI.
zuper-ipce-z6
No description available on PyPI.
zuper-ipce-z7
No description available on PyPI.
zuper-loghandle-z7
No description available on PyPI.
zuper-nodes
No description available on PyPI.
zuper-nodes-python2
No description available on PyPI.
zuper-nodes-python2-daffy
No description available on PyPI.
zuper-nodes-python2-z5
No description available on PyPI.
zuper-nodes-z5
No description available on PyPI.
zuper-nodes-z6
No description available on PyPI.
zuper-notes-z7
No description available on PyPI.
zuper-proc-local-z7
No description available on PyPI.
zuper-schemas
No description available on PyPI.
zuper-testint-z7
No description available on PyPI.
zuper-typing-z5
No description available on PyPI.
zuper-typing-z6
No description available on PyPI.
zuper-typing-z7
No description available on PyPI.
zuper-utils
No description available on PyPI.
zuper-utils-asyncio-z7
No description available on PyPI.
zuper-utils-soup-z7
No description available on PyPI.
zuper-zapp-interfaces-z7
No description available on PyPI.
zuper-zapp-z7
No description available on PyPI.
zuqa-agent-python
This is the official Python module for ZUQA.It provides full out-of-the-box support for many of the popular frameworks, including Django, and Flask. ZUQA is also easy to adapt for most WSGI-compatible web applications viacustom integrations.Your application doesn’t live on the web? No problem! ZUQA is easy to use in any Python application.Read thedocumentation.LicenseBSD-3-ClauseMade with ♥️ and ☕️ by Elastic and our community.
zuraaa-vote-checker
Uma forma não oficial de verificar quando alguem votou no seu bot.InstalaçãoÉ necessário Python 3.5.3 ou superior.A instalação pode ser feita via PyPI. Basta executar o seguinte comando:python-mpipinstallzuraaa-vote-checkerModo de usarO uso é simples, basta carregar uma cog chamadazuraaaVoteChecker(case-sensitive)Depois disso é só escutar o eventozuraaa_vote.Ele recebe um único parâmetro do tipodiscord.User, representando quem votou.Exemplo:fromdiscord.ext.commandsimportBotbot=Bot(command_prefix='.')@bot.eventasyncdefon_zuraaa_vote(user):print(f'{user.name}votou!')bot.load_extension('zuraaaVoteChecker')bot.run('TOKEN')Você pode acessar a quantidade de usuários que votaram no bot também!Basta acessar o atributozuraaa_vote_streak, na classe do seu bot. Ele irá contar a quantidade de votos desde que a cog foi carregada.