Saravanan666/pypi-org huggingface dataset:
Package: py2gift
py2giftpy2giftis a library meant to writequestion
banksinGIFTformat
(Moodle)programmaticallyin Python.
Ultimately, questions can be written (though this is not a requirement)
from aJupyternotebook. The advantages are:you can use all your Python skills tocomputewhatever is required
for the statement, solution and feedback of a questionit makes easy to write different (random) versions of the same
questionquestions can be previewed (pictures, $\LaTeX$…) in the notebookno need to install anything: you can click this mybinder badge,, open any of the provided examples, and start writing your questions
right now from the browser (the file generated at the end of the
notebook, accesible through a link, can be imported inMoodle).This library relies ongift-wrapperand it has
been created usingnbdev. The latter
fact means you canexplore theactualsource
codethrough jupyter notebooks
and see the inner workings of each individual piece.SetupSince the library is inPyPIpip install py2giftshould do.ManualIf you’d rather clone this repository, the command below should install
all the required packagespip install pandas numpy matplotlib ruamel.yaml gift-wrapperHow to use itWriting a question involves specifying the statement and,optionally,
the feedback in different notebook cells. In any case,variables,
specified with the prefix!, can be included, and those are meant to
befilled infrom within a Python class. This comes very handy when
you want to create different versions of a single question in which some
input data (maybe in the form of a picture)randomlychanges from
question to question. Then, you can instructpy2giftto call your
Python code a number of times, each one giving rise to a different
version of the same question (as long as somevariableis set at
random, e.g., by exploiting the functionality innp.random). The
solution, whose format depends on the question type, must also be set
from within the code.Underneath, images are handled bygift-wrapper, and hencepaths(e.g.,images/scheme.svg) to either.tex(that can be compiled withpdflatex) or.svgfiles can be included in the statement, solution
or feedback of a question. Moreover, they can be included through one of
the variables (prefix!), and hence random (but nonetheless
meaningful) pictures are a possibility.Notice that the difference between two instances of the same question
can be minor or significant. Ultimately, it depends on how sophisticated
your Python code is (if the latter can solve the question/problem in a
very general form, and you are also able to present it in thestatement, then it is fine).Besides the above mentionedcorefunctionality,py2giftprovides
some extra functions to ease the process of writing questions (modulestex,util,time,hash). However, a thorough description of the
functionality would be very dry and you are probably better off by
taking a look at one of thesamplenotebooks
(minimalorexample_1).
Also, you can take a look at thedocumentation.
Package: py2graphql
GraphQLDjango queryset love__getattr__abuse???Profit!!!Whatpy2graphql is a Python GraphQL client that makes GraphQL feel better to use. It almost feels like you’re using Django’s ORM.Installationpipinstallpy2graphqlExampleThis Python equates to the following GraphQL.frompy2graphqlimportQueryQuery().repository(owner='juliuscaeser',name='rome').pullRequest(number=2).values('title','url').commits(last=250).edges.node.commit.values('id','message','messageBody')query{repository(owner:"juliuscaeser",name:"rome"){pullRequest(number:2){titleurlcommits(last:250){edges{node{commit{idmessagemessageBody}}}}}}}You can even use the library to do the HTTP requests:frompy2graphqlimportClientheaders={'Authorization':'token MY_TOKEN',}Client(url=THE_URL,headers=headers).query().repository(owner='juliuscaeser',name='rome').fetch()It also supports Mutations:frompy2graphqlimportClient,Queryheaders={'Authorization':'token MY_TOKEN',}client=Client(url=THE_URL,headers=headers)mutation=Query(name='mutation',client=client)And multiple queries in a single request:frompy2graphqlimportClient,Queryheaders={'Authorization':'token MY_TOKEN',}query=Client(url=THE_URL,headers=headers).query().repository(owner='juliuscaeser',name='rome')query.pullRequest(number=2).values('title','url')query.releases(first=10).edges.node.values('name')query.get_graphql()query{repository(owner:"juliuscaeser",name:"rome"){pullRequest(number:2){titleurl}releases(first:10){edges{node{name}}}}}As well as GraphQL errors:frompy2graphqlimportClient,Queryheaders={'Authorization':'token MY_TOKEN',}result=Client(url=THE_URL,headers=headers).query().repository(owner='juliuscaeser',name='rome').fetch()result._errors[{'message':"Field 'repository' is missing required arguments: name",'locations':[{'line':7,'column':3}]}]
Package: py2hlog
py2hlog (Python to HTML log)https://github.com/houshmand-2005/py2hlogPython logs to HTML formattersimple useage :frompy2hlogimportlogger
importtimeobj1=logger.py2hlog()# create an object from py2hlogobj1.file_name="new_log_file.txt"# here write the log detailtry:ifa==2:print("Iam working!")except:obj1.error("I dont have any 'a' variable")print("print obj1: ",obj1)time.sleep(5)# to see time changingobj1.debug("Add a variable before the 'if' like a = 3")obj1.makehtml("py2hlog.html")# enter the name of output file# you can also use these statuses :# _____________________________# obj1.critical("your message")# obj1.debug("your message")# obj1.info("your message")# obj1.warning("your message")# obj1.error("your message")# _____________________________Also you can mark a part of your code for each status like this:frompy2hlogimportloggerobject_of_py2hlog=logger.py2hlog()object_of_py2hlog.file_name="Py2hlog.txt"object_of_py2hlog.warning("you can also mark a part of code for this status like -->",1,5)# ("msg", start line, end line)object_of_py2hlog.makehtml("Py2hlog.html")https://houshmand-2005.github.io/houshmand2005
Package: py2-ipaddress
This is a Python 2.6 backport of the Python 3.4ipaddressmodule.Please refer to theofficial Python 3.4 documentationfor more information
on the module.Differences from Python 3.4’sipaddressmoduleThe backport should behave identically to 3.4, except as noted here.bytearrayinstead ofbytesSince Python 2 has no distinctbytestype,bytearrayis used
instead for the “packed” (binary) address representation:>>> ipaddress.ip_address(bytearray('\xc0\xa8\x54\x17'))
IPv4Address('192.168.84.23')
>>> ipaddress.ip_address('127.0.0.17').packed
bytearray(b'\x7f\x00\x00\x11')This means py2-ipaddress can accept both Python 2 string types (strandunicode) for the textual address representation.If you prefer semantics closer to Python 3, you may be interested in
Philipp Hagemeister’sipaddress backport, which usesstrfor
the “packed” address representation, but then requires all textual IP
addresses to be given asunicodestrings. That backport also
supports Python 3.0–3.2.Caching ofis_privateandis_globalSince Python 2.7’sfunctoolsmodule does not have Python 3.2’slru_cache, no caching is performed for theis_privateandis_globalproperties; this should be a minor problem as Python 3.3’sipaddressdid not uselru_cacheeither.Changelogpy2-ipaddress 3.4.2Test suite and documentation improvements.py2-ipaddress 3.4.1Python 2.6 support and a bugfix.py2-ipaddress 3.4Since Python 2 does not distinguish betweenbytesandstrlike
Python 3 does, version 2.0.1 and earlier of py2-ipaddress attempted to
interpretstrarguments asbothand do the “right” thing.This unfortunately led to surprising behavior in py2-ipaddress:>>> ipaddress.ip_address('test.example.org')
IPv6Address('7465:7374:2e65:7861:6d70:6c65:2e6f:7267')Theipaddressmodule does not, of course, perform DNS resolution.
Rather, the argument is interpreted as a byte string (of length 16) and
converted bit-for-bit into an IPv6 address. In Python 3,ipaddresscorrectly rejects such a constructor argument (unless thebprefix
is used to explicitly mark the literal as a byte string).Even worse, there is not always a single right interpretation. Python 3
example:>>> ipaddress.ip_address('::1234:5678:9abc')
IPv6Address('::1234:5678:9abc')
>>> ipaddress.ip_address(b'::1234:5678:9abc')
IPv6Address('3a3a:3132:3334:3a35:3637:383a:3961:6263')There is no way to distinguish the two invocations in Python 2. As a
result, py2-ipaddress 3.4 usesbytearrayfor all byte strings, andstrfor text strings only:>>> ipaddress.ip_address('::1234:5678:9abc')
IPv6Address('::1234:5678:9abc')
>>> ipaddress.ip_address(b'::1234:5678:9abc')
IPv6Address('::1234:5678:9abc')
>>> ipaddress.ip_address(bytearray('::1234:5678:9abc'))
IPv6Address('3a3a:3132:3334:3a35:3637:383a:3961:6263')LicenseTheipaddressmodules (both the original and this backport) are licensed
under thePython Software Foundation License version 2.The modifications made for Python 2.6 compatibility are hereby released into
the public domain by the authors.
Package: py2ipynb
ipynb-py-convertAtom/Hydrogen or VSCode/Python allows creating a python files split into cells with# %%separators with the ability to run cells via backend Jupyter session and interactively show results back.More examples:Jupyter Python VSCode examples,Atom/Hydrogen Getting Started.ipynb-py-convertpython module converts files: .ipynb to .py and .py to .ipynb.ipynb-py-convertis a fork of thevscode-ipynb-py-converter.Installcondainstall-cdefaults-cconda-forgeipynb-py-convertorpipinstallipynb-py-convertTroubleshootingIf encoding problems on Windows try usingpython>=3.7, settingset PYTHONUTF8=1in Windows console and useipynb-py-convertfor UTF-8 files only. If usingGit-Bash on Windowssetting:exportLANG=C.UTF-8exportPYTHONIOENCODING=utf-8exportPYTHONUTF8=1should be enough. Also try setting default Bash settings to UTF-8: [Options] - [Text] - [Locale / Character set] - [C / UTF-8]. It might affect all Bash runs so there would be no need to setting encoding every time.Exampleipynb-py-convert examples/plot.py examples/plot.ipynboripynb-py-convert examples/plot.ipynb examples/plot.pyVSCodeMarkdown cells are converted to python multiline strings'''. Code cells are left as is.# %%is used by vscode as the cell marker on which 'Run Cell' action is available.Jupyter ipynb notebook
Package: py2ipynb2py
Py2ipynb2Pypy2ipynb2pyis a python module which aims to bridge the gap between Python scripts and Python notebooks by letting the user convert .py to .ipynb and vice versa and lets the user keep both the files in sync.Why use itPython notebooks and scripts serve almost the same function that is running python code, yet they appear to be such different entities with different pros and cons.Jupyter notebooks disadvantagesDependencies-> In some cases, the notebook imports libraries that are only installed on the computer of a data analyst (locally). The issue with such a scenario is that a programmer using a different version of the same library, such as NumPy, may experience the setback of the actual
production calculations not agreeing with those in the research.Object Oriented Paradigm-> Difficult to follow using notebooksNot possible to reproduce the outcomes from Jupyter Notebook received from a local execution.Cannot give a definite structure we can give by maintaining scriptsNotebook results performed by one machine might differ when running on another computer in the same group bearing in mind that the machines might have some caching differences.Jupyter notebook AdvantagesYou can execute the code and see the magic instantly.You can run cells independently and see several outputs without running all of the program.Easy and coonvinient to use.With py2ipynb2py you can easily convert .py to .ipynb and vice versa, it also then keeps both the files in sync. Markdows are preserved, i.e. even if your jupyter notebook has images these are conserved when you convert it to .py and that .py file is compilable even while maintaining all the markdowns. You can even add markdows in python files using py2ipynb2py's special syntax.While the famouse nbconvert library lets you convert .ipynb to .py, it does not let you convert .py to .ipynb and there is no feature to keep both the file in sync and maintainble.Installationpip3 install py2ipynb2pyDocumentationWhen writing you python script if you leave a blank between two lines those two lines will be indifferent cells.Firstimportpy2ipynb2pyimport py2ipynb2pythen add the following functionpy2ipynb2py.convertor('PATH_OF_FILE')Note thatPATH_OF_FILErepresents path of your notebook or script.One just has to add this path to only one time either to you notebook or script, when you convert the respective one time it automatically takes care of the path.Windows Userswhen adding path use '\' instead of ''One can add this function anywhere in his/her program.MarkdownWhenever one wants to do markdown in his/her python script
Use'''--Markdown--
Whatever you want to 
write in the markdown.
--Markdown--'''Note that this will also be the syntax when a markdown in converted from .ipynb to .py.One additional feature of Notebooks is you can just write variable name at the end of the cell and it will print the value of that variable, this does not serve any purpose in the python script, so these would be removed during conversion.Just Remember to SAVE the file before running it for the purpose of conversion.
Package: py2java
Python to Java language TranslatorInstall: ```pip install py2java```
import:
```python
from py2java import PythonToJava
```
Usage:
```python
sourceText = """
sourceText = "test"
def main():
    print(sourceText)
class lol(object):
    \"\"\"docstring for lol\"\"\"
    _LOL = "test" # test variable
"""
translator = PythonToJava(useRegex=1)
print(translator.compile(sourceText))
```
Package: py2jnb
Features after forking:New token recognized for code cells, defined by#%%, used inSpyderand PyCharm scientific mode.Original source repo readme follows...PY2NB: Python To Notebook ConverterThis is a small utility for turning python scripts into jupyter notebooks and
convert module-level multiline (triple quote) string literals into markdown
cells.Why?I wanted a tool to create user examples that can be executed as normal python
scripts so that they can be copy-and-pasted easily and can be rendered as
notebook for better readability (e.g nice styling, results embedded).Also,Notebooks are nice to look at but slow to writeNotebooks does not play well with version controlInstallpythonsetup.pyinstallUsageTo convert a python script into a notebook:python-mpy2nbinput.pyoutput.ipynbAdditional commandline not from this packageExecute a notebook:ipythonnbconvert--to=notebook--executeinput.ipynbConvert a notebook to a HTML:ipythonnbconvert--to=htmlinput.ipynbSamplesSee "samples" directory.How?Uses pythontokenize(builtin tokenizer library) for tokenization.
String literals with triple quote at column zero are converted into a comment
token with special<markdowncell>and<codecell>to feed into the python
importer in IPython version 3.  The processed tokens are untokenized using thetokenizemodule so that untouched line looks exactly the same as the input.
Package: py2js
Usageimportpy2js@py2js.jsdefmain():# code hereOptions: py2js.jsfunc:t.Optional[t.Callable]as_function:t.Optional[bool]python_compatible:t.Optional[bool]Examplespythonimportpy2jsimporttypingthis=typing.Self@py2js.jsdeftranslated_normal():'generator'defgenerator_func():yield1yield2yield3yield from[9,8,7]return0foritemingenerator_func():console.log(item)'for-else'foriin[0,1,2,3]:ifi>2:breakelse:console.log('else')'f-string'a=4console.log(f'{a}fstring')'class'classMain:a:intdefconstructor():this.a=1deffunc():console.log(this.a)Main().func()'try catch else finally'try:raiseSyntaxError('syntax error')exceptSyntaxErrorase:console.log('syntax error raised')except:console.log('excepted')else:console.log('else')try:ifBoolean(1):raiseSyntaxError('syntax error')except:passfinally:console.log('finally')'while'i=10whilei>0:i-=1'comparator'i=5if0<i<9:console.log('true')@py2js.js(python_compatible=True)deftranslated_compatible():'class with self args'classMain:def__init__(self,value):self.a=valuedeffunc(self):console.log(self.a)Main('hello, world!').func()withopen('translated_normal.js','w')asf:f.write(translated_normal)withopen('translated_compatible.js','w')asf:f.write(translated_compatible)translated_normal.js`generator`;letgenerator_func=function*(){yield1;yield2;yield3;yield*[9,8,7];return0};for(letitemofgenerator_func()){console.log(item)};`for-else`;__else:{for(letiof[0,1,2,3]){if(i>2){break__else}}console.log(`else`)};`f-string`;leta=4;console.log(`${a}fstring`);`class`;letMain=class{constructor(){this.a=1};func(){console.log(this.a)}a}Main=newProxy(Main,{apply:(clazz,thisValue,args)=>newclazz(...args)});;Main().func();`try catch else finally`;__else:{try{throwSyntaxError(`syntax error`)}catch(__err){if(__errinstanceofSyntaxError){e=__err;console.log(`syntax error raised`);break__else}{console.log(`excepted`);break__else}}console.log(`else`)};try{if(Boolean(1)){throwSyntaxError(`syntax error`)}}catch(__err){{/* pass */}}finally{console.log(`finally`)};`while`;leti=10;while(i>0){i-=1};`comparator`;i=5;if(0<i<9){console.log(`true`)}translated_compatible.js`class with self args`;letMain=class{constructor(...args){if('__init__'inthis)this.__init__(...args);returnnewProxy(this,{apply:(target,self,args)=>target.__call__(...args),get:(target,key)=>target.__getitem__(key)})}__init__=(...__args)=>{((self,value)=>{self.a=value})(this,...__args)};func=(...__args)=>{((self)=>{console.log(self.a)})(this,...__args)}}Main=newProxy(Main,{apply:(clazz,thisValue,args)=>newclazz(...args)});;Main(`hello, world!`).func()todomatch statement
Package: py2json
Tools for json serialization of python objectspy2jsonHere we tackle the problem of serializing a python object into a json.Json is a convenient choice for web request responses or working with mongoDB for instance.It is usually understood that we serialize an object to be able to deserialize it to recover the original object: Implicit in this is some definition of equality, which is not as trivial as it may seem. Usuallysomeaspects of the deserialized object will be different, so we need to be clear on what should be the same.For example, we probably don't care if the address of the deserialized object is different. But we probably care that it's key attributes are the same.What should guide us in deciding what aspects of an object should be recovered?Behavior.The only value of an object is behavior that will ensue. This may be the behavior of all or some of the methods of a serialized instance, or the behavior of some other functions that will depend on the deserialized object.Our approach to converting a python object to a json will touch on some i2i cornerstones that are more general: Conversion and contextualization.Behavior equivalence: What do we need an object to have?Say we are given the code below.deffunc(obj):returnobj.a+obj.bclassA:e=2def__init__(self,a=0,b=0,c=1,d=10):self.a=aself.b=bself.c=cself.d=ddeftarget_func(self,x=3):t=func(self)tt=self.other_method(t)returnx*tt/self.edefother_method(self,x=1):returnself.c*xWhich we use to make the following objectobj=A(a=2,b=3)Say we want to json-serialize this so that a deserialized objectdobjis such that for all validobj, resultingdobj, and validxinput:obj.target_func(x) == A.target_func(obj, x) == A.target_func(dobj, x)The first equality is just a reminder of a python equivalence.
The second equality is really what we're after.When this is true, we'll say thatobjanddobjare equivalent onA.target_func-- or just "equivalent" when the function(s) it should be equivalent is clear.To satisfy this equality we needdobjto:Contain all the attributes it needs to be able to compute theA.target_funcfunction -- which means all the expressions contained in that function or, recursively, any functions it calls.Such that the values of a same attribute ofobjanddobjare equivalent (over the functions in the call try of the target function that involve these attributes.Let's have a manual look at it.
First, you need to computefunc(self), which will require the attributesaandb.
Secondly, you'll meed to computerother_method, which uses attributec.
Finally, the last expression,x * tt / self.euses the attributee.So what we need to make sure we serialize the attributes:{'a', 'b', 'c', 'e'}.That wasn't too hard. But it could get convoluted. Either way, we really should use computers for such boring tasks!That's somethingpy2jsonwould like to help you with.
Package: py2k
Welcome to Py2kA high level Python to Kafka API with Schema Registry compatibility and automatic avro schema creation.Free software: Apache2 licenseInstallationPy2K is currently available on PIP:pipinstallpy2kDocumentationYou can view additional documentation on ourwebsite.ContributingPlease see theContribution Guidefor more information.UsageMinimal Examplefrompy2k.recordimportPandasToRecordsTransformerfrompy2k.writerimportKafkaWriter# assuming we have a pandas DataFrame, dfrecords=PandasToRecordsTransformer(df=df,record_name='test_model').from_pandas()writer=KafkaWriter(topic="topic_name",schema_registry_config=schema_registry_config,producer_config=producer_config)writer.write(records)For additional examples please see theexamplesfolderFeaturesSchema Registry IntegrationAutomatic Avro Serialization from pandas DataFramesAutomatic Avro Schema generation from pandas DataFrames and Pydantic objectsLicenseCopyright 2021 ABSA Group Limited

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.Release NotesLatest Changesv1.9.1 (2021-10-04)Bug🐛 Kafka Schema was not extracted from entire Dataframe.#76-@vesely-davidv1.9.0 (2021-05-15)Enhancement✨ Support for dynamic creation to return an iterator.#67-@vesely-davidUser can choose whether to return list (from_pandas) or iterator (iter_from_pandas)KafkaWriter was adjusted accordingly to accept any iterable in it's write methodv1.8.2 (2021-04-06)BugsResolved boolean schema not being converted to the correct avro schema values PR#48-@vesely-davidv1.8.1 (2021-03-31)DocsAdded examples and solved mkdocs gitub.io page build -@DanWertheimer. PR#45v1.8.0 (2021-03-29)FixesAdhering to Kafka and Avro parlance by renaming:models module -> recordKafkaModel -> KafkaRecordDynamicPandasModel -> PandasToRecordsTransformeritem -> recordMove schema knowledge to KafkaRecordIntroduce__key_fields__in KafkaRecord to enable specifying which fields are part of the keyIntroduce__include_key__in KafkaRecord to enable specifying whether key_fields should be part of the value messageBig thank you to@vesely-davidfor this changev1.7.0 (2021-03-11)Minor API change for easier dynamic creation of KafkaModels from a pandas DataFramev1.6.0 (2021-03-01)First commit on Github.