Saravanan666/pypi-org huggingface dataset:
Package: pymongolite
mongoliteLite mongodb engine in pythonpipinstallpymongoliteExamplessimplefrompymongoliteimportMongoClientwithMongoClient(dirpath="~/my_db_dir",database="my_db")asclient:db=client.get_default_database()collection=db.get_collection("users")collection.insert_one({"name":"yoyo"})collection.update_one({"name":"yoyo"},{"$set":{"age":20}})user=collection.find_one({"age":20})print(user)# -> {"_id": ObjectId(...), "name": "yoyo", "age": 20}frompymongoliteimportMongoClientclient=MongoClient(dirpath="~/my_db_dir",database="my_db")db=client.get_default_database()collection=db.get_collection("users")collection.insert_one({"name":"yoyo"})collection.update_one({"name":"yoyo"},{"$set":{"age":20}})user=collection.find_one({"age":20})print(user)# -> {"_id": ObjectId(...), "name": "yoyo", "age": 20}client.close()IndexesfrompymongoliteimportMongoClientclient=MongoClient(dirpath="~/my_db_dir",database="my_db")db=client.get_default_database()collection=db.get_collection("users")# Make query with name fastercollection.create_index({"name":1})collection.insert_one({"name":"yoyo"})collection.update_one({"name":"yoyo"},{"$set":{"age":20}})user=collection.find_one({"age":20})print(user)# -> {"_id": ObjectId(...), "name": "yoyo", "age": 20}indexes=collection.get_indexes()print(indexes)# -> [{'id': UUID('8bb4cac8-ae52-4fff-9e69-9f36a99956cd'), 'field': 'age', 'type': 1, 'size': 1}]client.close()SupportThe goal of this project is to create sqlite version for mongodbFor now the library is supporting:actions:databasecreate_databaseget_databasedrop_databasecollectioncreate_collectionget_collectiondrop_collectionget_collection_namesindexcreate_indexdelete_indexget_indexesdocumentinsert_many / insert_oneupdate_many / update_onefind / find_onereplace_many / replace_onefiltering ops:field matching$eq / $ne$gt / $gte$lt / $lte$not$and / $or / $nor$exists$in / $ninmutation ops:$set$unset$inc$addToSet$each$push$each$sort$slice$pull
Package: pymongo_mate
Welcome to pymongo_mate DocumentationA library extend pymongo module, makes CRUD easier.Quick LinksFeaturesquery builder: you don’t have to remember mongodb operator syntax, just select builder fromfrom pymongo_mate import query_builder as qb, for example:qb.Text.startswith("/usr/bin")select helper: writing complexe aggregation pipeline is pain, pymongo_mate provide functional interface to help you, just follow your human instinct.insert helper: a smart insert function helps you for bulk-insert with best performance, and plus, allows to insertpandas.DataFrame.update helper.mongomock support: allows you to dump your mongomock database to a file. With this data persistence layer, you can use mongomock as a rich-featured pure-python faked mongodb.Installpymongo_mateis released on PyPI, so all you need is:$pipinstallpymongo_mateTo upgrade to latest version:$pipinstall--upgradepymongo_mate
Package: pymongo-migrate
pymongo-migrateMongodb migrations using Python.Since mongodb is schema-less most of the time you can do without data migrations.
Sometimes tho you want to create some new entities, or migrate old data instead adding another IF statement to your code.
This is wherepymongo-migratecomes in.UsageUsage: pymongo-migrate [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  downgrade  apply necessary downgrades to reach target migration
  graph
  migrate    automagically apply necessary upgrades or downgrades to reach
             target migration
  show       show migrations and their status
  upgrade    apply necessary upgrades to reach target migrationThe most used command will bemigrate, which works can be called like this:$ pymongo-migrate migrate -u 'mongodb://localhost/test_db' -m tests/migrationsUsepymongo-migrate command --helpto learn more about particular command.Development & contributing to the projectContributions and raising Issues is welcome; standard netiquette rules apply.Usemake initto setup the project for development.
To format your code & test your changes run:make checkAlternativesATM there seem only two active python projects like this:https://github.com/DoubleCiti/mongodb-migrationshttps://github.com/skynyrd/cikilopSo if something already existed, why then another project?Goals of this project, where at least one of them were not fulfilled by above:tests and CI pipeline for ensuring that tool indeed workskeeping it usable both as standalone tool and as python dependencyuse of modern Python version, which allows use of type annotations, dataclasses, f-strings and other goodiesInspiration and designOther than Alternatives mentioned above, bothalembicanddjangowere used as references when designing this tool.For now only linear revision history is supported.
The support for squash migrations is planned.
Package: pymongo-paginate
Pymongo Paginateauthor: github.com/gabrielmrts/Examplefrom pymongo_paginate import PyMongoPaginate

collection = db['your_pymongo_collection']
query = collection.find()

page = 1 ## Current page
pageSize = 10 ## Items per page

pagination = PyMongoPaginate(query, page, pageSize)
paginate = pagination.paginate()

---------------------------------------------------
Output -> dict {
            "page": 1,
            "page_count": 1,
            "item_count": 10,
            "items": []
        }
Package: pymongorm
### mongorm一个简单的基于pymongo的orm### 使用示例```pythonfrom mongorm import MongoModelfrom field import CharField, IntFieldclass User(MongoModel):class Meta:# 设置mongo的数据库名称dbname = "mongoorm"# 设置集合名词collection = "test"user = CharField(is_must=True, default="xxx")age = IntField(is_must=True)if __name__ == "__main__":# 下面两种方法均可以插入一条记录User.objects.create(user="wupengxin", age=10)print User(user="usertest", age=12).create()```
Package: pymongos
pymongos简化了一些pymongo的操作，像操作json一样操作你的数据。
因为日常用增删查改最多，所以简化主要是围绕这三个操作来的。安装先装依赖python -m pip install pymongos
python3 -m pip install pymongos连接数据库无密码连接from pymongos import mongodb
table = mongodb(host='127.0.0.1', db="test", table="test")

# 无日志
table = mongodb(host='127.0.0.1', db="test", table="test", level="debug")密码连接from pymongos import mongodb
table = mongodb(host='127.0.0.1', db="test", table="test", user="admin", passwd="123456789")插入数据不设置_id（MongoDB随机生成）table += {"字段1": "数据1", "字段2": "数据1"}ortable + {"字段1": "数据1", "字段2": "数据1"}因为分配的ID是随机的，不建议使用设置_idtable["设置_id"] = {"字段1": "数据3", "字段2": "数据4"}
table["test"] = {"爱好": "看书", "书名": "鬼吹灯"}删除数据仅支持指定key方式del table["设置_id"]修改table["test"] = {"书名": "鬼吹灯和三体"}
table["test"] = {"书名": "《鬼吹灯》《三体》", "爱好": "看书&游泳"}
table["test"] = {"name" : "e4ting"}取数据表长度len(table)_id是否存在if "test" in table:
    print("yes")获取所有_idtable.keys()根据_id取data = table["test"]
print(data)取整个表数据数据少的时候才可以这么豪横的用table[:]
# 或
table.get()遍历表表太大的时候，迭代取for _ in table:
    print(_)过滤table[::{"name":"e4ting"}]
# 或
table.get(name="e4ting")
# 或 字段名有中文时
table.get(**{"字段1":"数据1"})分段table[:10]
# 或
table[1:10]
# 或
table.get(limit=10, offset=1)排序# 按 _id 倒序
table[::-1]

# 按 _id 倒序，分段
table[0:10:-1]

# 按 name 正序
table[::"name"]

# 按 name 正序，分段
table[0:10:"name"]

# 按 name 倒序
table[::"!name"]

# 按 name 倒序，分段取
table[0:10:"!name"]搜索table.search(name="4ting")搜索分段table.search(limit=10, offset=0, **{"字段1" : "数据"})其他操作关闭连接del table获取所有库名table.dbs获取该库下所有collectiontable.tables获取所有字段名table.colums关闭日志table.none_log()开启日志table.en_log()
Package: pymongo-ssh
ssh-pymongoPython utilities to simplify connection with MongoDB through SSH tunnel.
Note: uri parameter is assumed as local, after ssh.Where to get itThe source code is currently hosted on GitHub at:https://github.com/pualien/pymongo-sshBinary installers for the latest released version are available at thePython package indexpipinstallpymongo-sshExample 1frompymongo_sshimportMongoSessionsession=MongoSession('db.example.com')db=session.connection['db-name']session.stop()# session.start()Example 2session=MongoSession(host='db.example.com',uri='mongodb://user:password@127.0.0.1/?authSource=admin&authMechanism=SCRAM-SHA-256')...session.stop()Example 3session=MongoSession(host='db.example.com',user='myuser',password='mypassword',)...session.stop()Example 4session=MongoSession(host='db.example.com',port='21',user='myuser',key='/home/myplace/.ssh/id_rsa2',to_port='37017',to_host='0.0.0.0')...session.stop()
Package: pymongo-stubs
Experimental stub files forPyMongo3.pymongo-stubs is NOT an officially supported MongoDB product.ExampleInstallationpymongo-stubs can be installed withpip:$ python3 -m pip install pymongo-stubsInstalling from sourcepymongo-stubs’ source code is hosted on Github:mongodb-labs/pymongo-stubs.
To install pymongo-stubs from source:$ git clone git@github.com:mongodb-labs/pymongo-stubs.git
$ python3 -m pip install ./pymongo-stubsDependenciespymongo-stubs is compatible with Python >=3.6 andPyMongo>=3.11,<4.0.Roadmappymongo-stubs adds support for type checkingPyMongo3.X code. This project
will not support PyMongo 4. Instead, PyMongo 4 will add inline type
annotations (inPYTHON-2432) which removes the need to maintain stub files.
This project will reach end-of-life whenPYTHON-2432is completed or when
MongoDB drops support forPyMongo3.X.Support / Feedbackpymongo-stubs is experimental and is not an officially supported MongoDB product.
For questions, discussions, or general technical support, visit theMongoDB Community Forums.Bugs / Feature RequestsThink you’ve found a bug? Please open a case in our issue management tool, JIRA:Create an account and login.Navigate tothe PYTHON project.ClickCreate Issue- Please provide as much information as possible about the issue type and how to reproduce it.Bug reports in JIRA for all driver projects (i.e. PYTHON, CSHARP, JAVA) and the
Core Server (i.e. SERVER) project arepublic.
Package: pymongo-the-sql
A sql wrapper made to mimic the pymongo syntax in order to simplify sql
syntax.DocsUsagefrom pymongo_the_sql.pymongo_the_sql import PyMongoTheSql
PyMongoTheSql("../tests/test.sqlite3")
<pymongo_the_sql.pymongo_the_sql.PyMongoTheSql object at 0x7f60878e8e80>
client = PyMongoTheSql("../tests/test.sqlite3")
client = PyMongoTheSql("../tests")
db = client.get_database("test")
db["users"]
<pymongo_the_sql.pymongo_the_sql.PyMongoTheSql object at 0x7f6087763400>
users = db["users"]
users.find({"id": "1"})ApiUpdateUpdates values for all specified columns where the conditions are True.update(columns_values: dict, conditions: dict[Optional], operator: str[Optional])->boolUpdates values for all specified columns where the conditions are True.
Use the values tuple to update Blob type objects.update_blob(columns_values: dict, values: tuple[Optional], conditions: dict[Optional], operator: str[Optional])Updates values for all specifed columns on the first row where the
conditions are True.update_one(columns_values: dict, conditions: dict[Optional])Updates values for all specified columns on every row.update_all(columns_values: dict[Optional])->boolFindReturns the specified columns on all rows the conditions are True.find(conditions: dict, columns: dict, operator: str)->dictReturns the specified columns on the first row the conditions are True.find_one(conditions: dict, columns: list, operator: str)->dictReturns the whole table. find_all() -> dictReturns the specified columns on the last row the conditions are True.find_last(conditions: dict[Optional], columns: list[Optional], operator: str[Optional])->dictReturns how many rows in the table. findall_and_count() -> intReturns how many rows the conditions are True.find_and_count(conditions: dict[Optional], columns: list[Optional], operator: str[Optional])->intInsertInserts the values in the specified columns. insert(columns_values: dict)->bool
Package: pymonitor-foretls
pymonitormore info including examples can be found herehttps://github.com/noahgrad/pymonitor/Why?Lets say you have a lot of etls that runs in different platforms (airflow, kubernetes etc)  and writes data to different places  (mysql, snowflake, s3 etc) so how do you monitor them? how do you check that each of etls end up correctly and the data reached its destination?
pymonitor come to help discover that the data didn't reach its destination ASAP.The ideaThe idea is to do the same thing pytest is doing for testing just for monitoring.
Run pymonitor.py script on a specific directory it will run all monitoring files - files with specific name and will try to run their monitor method - method with specific name.Lets say we have a directory of etls each etl in its own subdirectory in this case we will add a monitor file to each of the subdirectories. Each monitor file will monitor just its etl.By the end of running the script we will get a covergae of monitor for all the etls that implemented a monitor method in a monitor file (the same as in pytest)Usage examplepython src/pymonitoring/pymonitor.py --dir etls --end_ts 1663064624 --filename "Example*.py"Will try to find all the Example*.py file name in directory etls and run their monitor method.orpip intsall pymonitor-foretlsfrom pymonitoring.pymonitor import monitor
monitor("examples", 1663064624,"Example*.py")The pymonitor.py script or monitor methodNeed to get:end_ts- the timestamp untill it we want to monitor.dir- the directory to run onCan get:filename- seach for files with this name in the given directory default is 'monitor.py'methodname- execute this method with the end_ts paramter default is 'monitor'Get all files name  filename in dirfor each file:execute the method methodname with the end_tsThe PyMonitoring classContains some static methods to help you peform some monitoring currenty we have:send_slack_monitoring_massage- Send message to the slack channelcheck_table_in_sf- Check if there is data in the specified table between the start ts and end ts in the given time_field_nameif there is data return True else can send slack notification and return Falsecheck_query_in_sf- Send query to snowflake and return the query result.send slack message if there is no dataMore method should comeThe examples directoryContains 2 example of how to write and use the PyMonitoring class.
Package: pymonitoring
pymonitoringis a Python package that allows to easily create HTTP monitoring
interfaces for your python services.
Such interfaces can be used by Nagios to query for service status for example.Examplesimport monitoring.http

class ServiceInfo:
        start_time

        def to_json()
                info = {
                        'start_time': self.start_time
                }

                return json.dumps(info)

service_info = ServiceInfo()
service_info.start_time = time.time()

monitoring_server = monitoring.http.Server(8000, service_info)
monitoring_server.start_async()
Package: pymonitors
PyMonitorsA Python library to programatically get your monitor's resolution info.It supports multiple strategies:xrandr: Linux only, requiresx11-xserver-utilsto be installed.appkit: MacOS only, requirespyobjc,AppKit, andcairoto be installed.mswindows: Windows only, requires the Powershell to be installed.Usagefrompymonitorsimportget_monitorsformonitoringet_monitors():width:int=monitor.widthheight:int=monitor.heightprint(f"Monitor{monitor.name}has resolution{width}x{height}.")
Package: pymonkey
pymonkeyA tool for applying monkeypatches to python executables.Installationpip install pymonkeyRegistering a patchMake a module:## mymod/pymonkey.py# Be sure to not import anything at the module scope# This ensures that import-hook patching will work better later# This is your chance to do argument parsing before running the target# executable.# This will be called after all of the patch hooks have been registered.defpymonkey_argparse(argv):# You'll be passed the arguments as a tuple.  Parse your specific arguments# and return your parsed state and the remaining arguments.# If you wish to forgo argparsing, simply `return None, argv`importargparseparser=argparse.ArgumentParser()parser.add_argument('--foo')returnparser.parse_known_args(argv)# This is your entry point.  It will be passed module objects after they have# been imported.  Check the module name and then apply your patch (if# applicable).# This will be called as a post-import hook so you'll have a chance to modify# the module before another module would import from it.# The parsed state computed above will be passed as `args`defpymonkey_patch(mod,args):# This callback will be called with *every* module that gets imported# Guard against the specific module you'd like to patchifmod.__name__!='module_to_patch':return# Apply your patches here to module_to_patchmod.foo=args.fooAnd add the entrypoints to setup.py:setup(...,entry_points={'pymonkey':['mymod = mymod.pymonkey:pymonkey_patch'],'pymonkey.argparse':['mymod = mymod.pymonkey:pymonkey_argparse'],},...)Commandline usageApplying a single patch:$ pymonkey mymod -- pip install simplejsonApplying all the patches available:$ pymonkey --all -- pip install simplejsonViewing the help$ pymonkey --helpMaking entry points with pymonkeyIn a module:## mymod_main.pyfrompymonkeyimportmake_entry_point# The first argument is a list of pymonkey patches to apply# The second argument is the entry point to runmain=make_entry_point(('mymod',),'pip')if__name__=='__main__':exit(main())In setup.pysetup(...,entry_points={'console_scripts':['pip-patched = mymod_main:main'],'pymonkey':['mymod = mymod.pymonkey:pymonkey_patch'],'pymonkey.argparse':['mymod = mymod.pymonkey:pymonkey_argparse'],},...)Then instead of$ pymonkey mymod -- pip ...You can now do$ pip-patched ...Things using pymonkeyhttps://github.com/asottile/pip-custom-platform
Package: pymonntorch
PymoNNtorchPymoNNtorch is aPytorch-adapted version ofPymoNNto.Free software: MIT licenseDocumentation:https://pymonntorch.readthedocs.io.FeaturesUsetorchtensors and Pytorch-like syntax to create a spiking neural network (SNN).Simulate an SNN on CPU or GPU.Define dynamics of SNN components asBehaviormodules.Control over the order of applying different behaviors in each simulation time step.UsageYou can use the same syntax asPymoNNtoto create you network:frompymonntorchimport*net=Network()ng=NeuronGroup(net=net,tag="my_neuron",size=100,behavior=None)SynapseGroup(src=ng,dst=ng,net=net,tag="recurrent_synapse")net.initialize()net.simulate_iterations(1000)Similarly, you can write your ownBehaviorModules with the same logic asPymoNNto; except usingtorchtensors instead ofnumpyndarrays.frompymonntorchimport*classBasicBehavior(Behavior):definitialize(self,neurons):super().initialize(neurons)neurons.voltage=neurons.vector(mode="zeros")self.threshold=1.0defforward(self,neurons):firing=neurons.voltage>=self.thresholdneurons.spike=firing.byte()neurons.voltage[firing]=0.0# resetneurons.voltage*=0.9# voltage decayneurons.voltage+=neurons.vector(mode="uniform",density=0.1)classInputBehavior(Behavior):definitialize(self,neurons):super().initialize(neurons)forsynapseinneurons.afferent_synapses['GLUTAMATE']:synapse.W=synapse.matrix('uniform',density=0.1)synapse.enabled=synapse.W>0defforward(self,neurons):forsynapseinneurons.afferent_synapses['GLUTAMATE']:neurons.voltage+=synapse.W@synapse.src.spike.float()/synapse.src.size*10net=Network()ng=NeuronGroup(net=net,size=100,behavior={1:BasicBehavior(),2:InputBehavior(),9:Recorder(['voltage']),10:EventRecorder(['spike'])})SynapseGroup(src=ng,dst=ng,net=net,tag='GLUTAMATE')net.initialize()net.simulate_iterations(1000)importmatplotlib.pyplotaspltplt.plot(net['voltage',0][:,:10])plt.show()plt.plot(net['spike.t',0],net['spike.i',0],'.k')plt.show()CreditsThis package was created withCookiecutterand theaudreyr/cookiecutter-pypackageproject template.
It changes the codebase ofPymoNNtoto usetorchrather thannumpyandtensorflow numpy.History0.1.4 (2024-03-16)Bug fixes.Src and dst can beNonefor syanpses.Hierarchical structure.0.1.3 (2023-08-16)BREAKING CHANGE:Networkno longer accept settings. Individual setting are now argument for Network.Bug fixes.0.1.2 (2023-06-14)tensormethod for NetworkObject0.1.1 (2023-05-26)Every NetworkObject can have a recorder behavior.Network settings accept “index” entry.Bug fixes and general improvement.0.1.0 (2023-03-17)Repository made public.
Package: pymonocypher
pymonocypherThis python package uses cython to wrap the Monocypher C library.
Monocypher is an easy to use, easy to deploy, auditable crypto library
written in portable C.Normal Python installations have access to a wide
selection of quality crypto libraries.  This python binding is intended to
communicate with other implementations that do use the Monocypher library.
A typical application is to communicate with a microcontroller that
uses Monocypher.pymonocypherSource codeMonocypherofficial siteThe Python binding API mirrors the underlying C API, but with
simplifications to only pass bytes objects, not uint8_t * and length.InstallationYou can install directly from pypi:pip install pymonocypherYou can then use pymonocypher:python
>>> import monocypher
>>> monocypher.blake2b(b'hello world')
Package: pymonome
pymonome is a pure Python library for easy interaction with themonome family <https://monome.org>of devices. It supports grid and arc
controllers (via serialosc) and provides additional facilities for developing
grid- and arc-based applications.Installationpymonome requires at least Python 3.6. It can be installed using pip:pip3 install pymonomeOr use the--useroption to install pymonome to the current user
library directory:pip3 install --user pymonomeBasic usagepymonome does not communicate with any of the devices directly. Like many
monome applications, it relies on serialosc for device detection and hardware
input and output. As serialosc provides OSC (UDP) ports for all the devices
connected to the host system, it is possible to connect to a grid via a known
UDP port as follows:importmonomeGRID_HOST='127.0.0.1'GRID_PORT=16816grid=monome.Grid()awaitgrid.connect(GRID_HOST,GRID_PORT)grid.led_set(0,0,1)Alternatively, it is possible to instantiate the protocol class using theloop.create_datagram_endpoint()event loop method:transport,grid=awaitloop.create_datagram_endpoint(monome.Grid,remote_addr=(GRID_HOST,GRID_PORT))Service discovery APIIn practice UDP ports will be randomly assigned to devices as they
are connected to the host computer. serialosc has a discovery and
notification mechanism to notify clients about connected devices.
It’s possible to connect to the discovery service from pymonome too:grid=monome.Grid()defserialosc_device_added(id,type,port):print('connecting to{}({})'.format(id,type))asyncio.create_task(grid.connect('127.0.0.1',port))serialosc=monome.SerialOsc()serialosc.device_added_event.add_handler(serialosc_device_added)awaitserialosc.connect()Application classesFor extra convenience pymonome provides base classes for developing
grid and arc-based apps, apps on grid sections, or pages on the same grid.
Application base classes provide handler stubs for input events
and member properties for accessing controllers.importasyncioimportmonomeclassHelloApp(monome.GridApp):defon_grid_key(self,x,y,s):self.grid.led_set(x,y,s)asyncdefmain():loop=asyncio.get_running_loop()hello_app=HelloApp()defserialosc_device_added(id,type,port):print('connecting to{}({})'.format(id,type))asyncio.create_task(hello_app.grid.connect('127.0.0.1',port))serialosc=monome.SerialOsc()serialosc.device_added_event.add_handler(serialosc_device_added)awaitserialosc.connect()awaitloop.create_future()# run foreverif__name__=='__main__':asyncio.run(main())In this example, HelloApp application instance will be connected
to the latest discovered grid and pressing a button will light
the corresponding LED.More examplesFor more examples see theexamples/directory.LicenseCopyright (c) 2011-2021 Artem Popov <artfwo@gmail.com>pymonome is licensed under the MIT license, please see LICENSE file for details.