Saravanan666/pypi-org huggingface dataset:
Package: graphene-pynamodb
APynamoDBintegration forGraphene.InstallationFor instaling graphene, just run this command in your shellpipinstallgraphene-pynamodbExamplesHere is a simple PynamoDB model:fromuuidimportuuid4frompynamodb.attributesimportUnicodeAttributefrompynamodb.modelsimportModelclassUser(Model):classMeta:table_name="my_users"host="http://localhost:8000"id=UnicodeAttribute(hash_key=True)name=UnicodeAttribute(null=False)ifnotUser.exists():User.create_table(read_capacity_units=1,write_capacity_units=1,wait=True)User(id=str(uuid4()),name="John Snow").save()User(id=str(uuid4()),name="Daenerys Targaryen").save()To create a GraphQL schema for it you simply have to write the
following:importgraphenefromgraphene_pynamodbimportPynamoObjectTypeclassUserNode(PynamoObjectType):classMeta:model=Userinterfaces=(graphene.Node,)classQuery(graphene.ObjectType):users=graphene.List(UserNode)defresolve_users(self,args,context,info):returnlist(User.scan())schema=graphene.Schema(query=Query)Then you can simply query the schema:query='''
    query {
      users {
        name
      }
    }
'''result=schema.execute(query)To learn more check out the followingexamples:Full example:Flask PynamoDB
exampleLimitationsgraphene-pynamodb includes a basic implementation of relationships using
lists. OneToOne and OneToMany relationships are serialized as a List of
the ids and unserialized lazyly. The limit for an item’s size in
DynamoDB is 400KB (seehttp://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html)
This means the total “row” size including the serialized relationship
needs to fit within 400KB so make sure to use this accordingly.In addition, scan operations on DynamoDB are unsorted by design. This
means that there is no reliable way to get a paginated result (Cursor
support) on a root PynamoConnectionField.This means that if you need to paginate items, it is best to have them
as a OneToMany relationship inside another Field (usually viewer or
node).ContributingAfter cloningthis
repo, ensure
dependencies are installed by running:pythonsetup.pyinstallAfter developing, the full test suite can be evaluated by running:pythonsetup.pytest# Use --pytest-args="-v -s" for verbose mode
Package: graphene-sa-optimizer
Graphene Sql Alchemy Optmizer(WIP)
inspired byhttps://github.com/tfoxy/graphene-django-optimizerUses graphql schema to generate efficient database access using sql alchemy joinsinstallpip install graphene_sa_optimizerHow to usefromgraphene_sa_optimizerimportget_optimized_options# This will generate all our options# to optimize this query and# pass those optimizations into our queryquery.options(*get_optimized_options(ModelClass,info))Setup for devInstallpipenvrunpipenv installrunpipenv shellrunpytest
Package: graphene-sentry
graphene-sentryThis package is based ongraphene-django-sentry(Github page)
package.Main focus of package was to fix issue with sentry reporting withgraphene_djangopackage.I think this package can be extended to handle nore cases.Survey is needed if you faced similar problem with sentry report with other
frameworks or graphene implementations let me know via issues.Capture Sentry exceptions in Graphene viewsWhen usingGraphene Django,
you sometimes want to raise exceptions and capture them in the API.However, Graphene Django eats the raised exceptions and you won't see it
in Sentry! 😭This package thinly wraps the normal GraphQLView with a handler that
deals with Sentry errors properly.So the results:Sentry will show the true exceptions.Graphene will continue to work like normal.Works with:Python 3.6+Django 2.1+graphene-django 2.2+Installing the project is easy:pip install graphene-sentryExample without file upload:# urls.py

from .schema import schema
from graphene_sentry.views import SentryGraphQLView

urlpatterns = [
    url(
        r'^graphql',
        csrf_exempt(SentryGraphQLView.as_view(schema=schema)),
        name='graphql',
    ),
]Example with graphene file upload:# urls.py

from .schema import schema
from graphene_sentry.views import SentryFileUploadGraphQLView

urlpatterns = [
    url(
        r'^graphql',
        csrf_exempt(SentryFileUploadGraphQLView.as_view(schema=schema)),
        name='graphql',
    ),
]What can I do?Capture Sentry exceptions properly when they are raise-d in Graphene
views.Statusgraphene-sentry is currently stable and suitable for use.CreditsThis package is based ongraphene-django-sentryauthor@phaltThis package was created withCookiecutter.
Package: graphene-sqlalchemy
Please readUPGRADE-v2.0.mdto learn how to upgrade to Graphene2.0.Graphene-SQLAlchemyASQLAlchemyintegration forGraphene.InstallationFor instaling graphene, just run this command in your shellpipinstall"graphene-sqlalchemy>=2.0"ExamplesHere is a simple SQLAlchemy model:fromsqlalchemyimportColumn,Integer,Stringfromsqlalchemy.ormimportbackref,relationshipfromsqlalchemy.ext.declarativeimportdeclarative_baseBase=declarative_base()classUserModel(Base):__tablename__='department'id=Column(Integer,primary_key=True)name=Column(String)last_name=Column(String)To create a GraphQL schema for it you simply have to write the
following:fromgraphene_sqlalchemyimportSQLAlchemyObjectTypeclassUser(SQLAlchemyObjectType):classMeta:model=UserModelclassQuery(graphene.ObjectType):users=graphene.List(User)defresolve_users(self,info):query=User.get_query(info)# SQLAlchemy queryreturnquery.all()schema=graphene.Schema(query=Query)Then you can simply query the schema:query='''
    query {
      users {
        name,
        lastName
      }
    }
'''result=schema.execute(query,context_value={'session':db_session})To learn more check out the followingexamples:Full example:Flask SQLAlchemy
exampleContributingAfter cloning this repo, ensure dependencies are installed by running:pythonsetup.pyinstallAfter developing, the full test suite can be evaluated by running:pythonsetup.pytest# Use --pytest-args="-v -s" for verbose mode
Package: graphene-sqlalchemy-auto
generate default graphene schema from sqlalchemy model base ongraphene-sqlalchemyInstallationjust runpipinstallgraphene_sqlalchemy_autoFeaturesauto addoffsetlimittotalCountto paginationauto adddbIdfor model's database idmutation auto return ok for success,message for more information and output for model dataHow To Useexample :fromgraphene_sqlalchemy_autoimportQueryObjectType,MutationObjectTypefromsqlalchemy.ext.declarativeimportdeclarative_baseimportgraphenefromsqlalchemy.ormimportsessionmakerBase=declarative_base()Session=sessionmaker()classQuery(QueryObjectType):classMeta:declarative_base=Baseexclude_models=["User"]# exclude modelsclassMutation(MutationObjectType):classMeta:declarative_base=Basesession=Session()# mutate usedinclude_object=[]# you can use yourself mutation UserCreateMutation, UserUpdateMutationschema=graphene.Schema(query=Query,mutation=Mutation)Query examplejust equalquery{
  userList(filters:{name: "a"}){
    edges{
      node{
        name
        id
        dbId
      }
    }
  }
}OR
support more exprquery{
  userList(filters:[{key: "name",op: "==", val: "a"}]){
    edges{
      node{
        name
        id
        dbId
      }
    }
  }
}op supports:==!=>=<=><startsendscontainsinnotinanyMutation examplecreateUser(input:{name: "cc",password: "dd"}){
    ok
    output{
      id
      dbId
      name
    }
    message
  }about Schema namesmodel.class.name.lower : query a data by idmodel.class.name.decapitalize[first lower]+"List": query listcreate|update|delete+model.class.name : mutation dataabout many-to-many mutationnow you can use schema everywhere.some like flask,fastapialso more example you can find inexample
Package: graphene-t2
DisclaimerПроект находится на ранней стадии разработкиКак пользоваться?Обязательные поля в инпутахimportgraphenefromgraphene_t2importInputObjectTypeclassAddSomethingInput(InputObjectType):field1=graphene.String(required=True)field2=graphene.String(required=True)classEditSomethingInput(AddSomethingInput):classT2Meta:required={False:'__all__',# или список полейTrue:['id'],}id=graphene.ID()Примечаниянет поддержкиgraphene.Argumentпорядок ключей (True,False) в параметреrequiredважен. Изменения применяются в порядке их объявленияДокументирование изменений (changes.py)Автоматически изменяет описание полей. Может использоваться для генерации документации.importgraphenefromgraphene_t2importInputObjectTypefromgraphene_t2.features.changesimportAlter,DeprecateclassSomeInputType(InputObjectType):classT2Meta:changes=[Deprecate('legacy_field1','03/20',replaced_by='new_field1'),Deprecate('legacy_field2','02/20',comment='Не используется'),Alter('new_field1','03/20',required=True),]legacy_field1=graphene.String()legacy_field2=graphene.String()new_field1=graphene.String()Сортировка (ordering.py)В классе-нследникеObjectTypeнужно объявить классT2Meta.
Внутри него можно создать две переменные:can_order_by- обязательный, список с названием полей, по которым можно производить сортировку;default_ordering- необязательный, сортировка по-умолчанию, строка или список строк с названием полей.Примеры:classModel1Type(DjangoObjectType):classT2Meta:can_order_by=['id']classModel2Type(DjangoObjectType):classT2Meta:can_order_by=['id']default_ordering='id'# или '-id'classModel3Type(DjangoObjectType):classT2Meta:can_order_by=['id','name','date_created']default_ordering='-date_created','name'# или ['-date_created', 'name']Класс с объявлением методов нужно отнаследовать отgraphene_t2.QueriesType, объявить вложенный классT2Meta.
Внутри объявить переменнуюenable_ordering_for.Возможны два вида значения:__auto__- включает возможность сортировки, для методов для которых это возможно сделать;список с названием полейРесолверы в качестве аргумента должны принимать**kwargsилиsort_by.fromgraphene_t2importQueriesTypeclassQuery1(QueriesType):classT2Meta:enable_ordering_for='__auto__'items=graphene.List(Model1Type)defresolve_items(self,info,**kwargs):passclassQuery2(QueriesType):classT2Meta:enable_ordering_for=['items']items=graphene.List(Model1Type)defresolve_items(self,info,sort_by):passПримечанияНет поддержки случаев, когда название поля в модели отличается от названия в API;Нет возможности сортировать по полям вложенных структур;
Package: graphene-tornado
graphene-tornadoA project for runningGrapheneon top
ofTornadoin Python 2 and 3. The
codebase is a port ofgraphene-django.Getting startedCreate a Tornado application and add the GraphQL handlers:importtornado.webfromtornado.ioloopimportIOLoopfromgraphene_tornado.schemaimportschemafromgraphene_tornado.tornado_graphql_handlerimportTornadoGraphQLHandlerclassExampleApplication(tornado.web.Application):def__init__(self):handlers=[(r'/graphql',TornadoGraphQLHandler,dict(graphiql=True,schema=schema)),(r'/graphql/batch',TornadoGraphQLHandler,dict(graphiql=True,schema=schema,batch=True)),(r'/graphql/graphiql',TornadoGraphQLHandler,dict(graphiql=True,schema=schema))]tornado.web.Application.__init__(self,handlers)if__name__=='__main__':app=ExampleApplication()app.listen(5000)IOLoop.instance().start()When writing your resolvers, decorate them with either Tornado’s@coroutinedecorator for Python 2.7:@gen.coroutinedefresolve_foo(self,info):foo=yielddb.get_foo()raiseReturn(foo)Or use theasync/awaitpattern in Python 3:asyncdefresolve_foo(self,info):foo=awaitdb.get_foo()returnfoo
Package: grapheno
graphenoA GPU-accelerated implementation ofPhenoGraphusingNVIDIA RAPIDSfor fast single-cell phenotyping.InstallationInstall RAPIDS into new environment:$ conda create -n rapids-21.12 -c rapidsai-nightly -c nvidia -c conda-forge rapids=21.12 python=3.8 cudatoolkit=11.2Install grapheno:$ pip install grapheno(Optional) Install holoviews for visualization:$ conda install -c pyviz holoviews bokehUsageimport cudf
import cuml
import grapheno

X, _ = cuml.make_blobs(n_samples=100000,n_features=20,centers=5)
X = cudf.DataFrame.from_records(X)
communities, G, Q = grapheno.cluster(X)BenchmarkingSee benchmark.ipynb for comparisons between grapheno (GPU) and phenograph (CPU) and to regenerate the figures below.GPU is orders of magnitude faster than CPU at large data scales. Mean points and error bars are from three replicates:Modularity is comparable between GPU and CPU implementations. t-SNE embeddings of simulated data colored by cluster label:
Package: graphenum
graphenumIntrospect a GraphQL endpoint and generate his specification schema with path enumeration.Getting StartedIt takes only two simple steps to introspect an endpoint using graphenum.pipinstallgraphenum
graphenum-uhttps://example.com/graphql-oschema.jsonOptionsGraphEnum supports the following options:graphenum\# url of the GraphQL endpoint-u/--urlhttps://example.com/graphql\# input schema file (raw GraphQL schema)-s/--schema-pathschema.json\# output file name-o/--output-schemaschema.json\# verbose output-v/--verboseEnvironment VariablesLogger-No effect if you pass your own loggerNameValuesDefaultBehaviorLOG_FORMATconsole,jsonconsoleChange the log format accordinglyDEBUGTrue,FalseFalseEnable debug loggingIntegrationimportloggingfromtypingimportCallable,Dict,Optional,List,TuplefromgraphenumimportIntrospectionSchemafromgraphenum.entities.internalimportCallbacksasyncdefasync_introspect(/defintrospect(url:str,logger:Optional[logging.Logger]=None,headers:Optional[Dict[str,str]]=None,verbose_mode:bool=False,schema_path:Optional[str]=None,callbacks:Optional[Dict[Callbacks,List[Callable]]]=None,json_encode:bool=False)->Tuple[IntrospectionSchema,aiohttp.ClientResponse]:...Local installationgitclonegit@github.com:Escape-Technologies/graphenum.gitcdgraphenum
chmod+x./install-dev.sh
./install-dev.shContributingPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.Please make sure to update tests as appropriate.LicenseMIT
Package: graphenv
graph-envThegraphenvPython library is designed tomake graph search problems more readily expressible as RL problems via an extension of the OpenAI gym API whileenabling their solution via scalable learning algorithms in the popular RLLib library.RLLib provides out-of-the-box support for both parametrically-defined actions and masking of invalid actions. However, native support for action spaces where the actionchoiceschange for each state is challenging to implement in a computationally efficient fashion. Thegraphenvlibrary provides utility classes that simplify the flattening and masking of action observations for choosing from a set of successor states at every node in a graph search.InstallationGraphenv can be installed with pip:pip install graphenvQuick Startgraph-envallows users to create a customized graph search by subclassing theVertexclass. Basic examples are provided in thegraphenv/examplesfolder. The following code snippet shows how to randomly sample from valid actions for a random walk down a 1D corridor:importrandomfromgraphenv.examples.hallway.hallway_stateimportHallwayStatefromgraphenv.graph_envimportGraphEnvstate=HallwayState(corridor_length=10)env=GraphEnv({"state":state,"max_num_children":2})obs=env.make_observation()done=Falsetotal_reward=0whilenotdone:action=random.choice(range(len(env.state.children)))obs,reward,terminated,truncated,info=env.step(action)done=terminatedortruncatedtotal_reward+=rewardAdditional details on this example are given in thedocumentationDocumentationThe documentation is hosted onGitHub PagesContributingWe welcome bug reports, suggestions for new features, and pull requests. See ourcontributing guidelinesfor more details.Licensegraph-envis licensed under theBSD 3-Clause License.
Copyright (c) 2022, Alliance for Sustainable Energy, LLC
Package: graph-envs
GraphEnvsGraph Reinforcement Learning (RL) EnvironmentsInstallationFirst installtorchandpytorch geometric. The simply use pip to install graph_envs:pipinstallgraph-envsSupported EnvironmentsGraphEnvs-Basic:EnvironmentDevelopedAction SpaceShortest Path✅$v \in \mathcal{V}$Steiner Tree✅$e \in \mathcal{E}$MST✅$e \in \mathcal{E}$Minimum Vertex Cover✅$v \in \mathcal{V}$TSP✅$v \in \mathcal{V}$Longest Path✅$v \in \mathcal{V}$Largest Clique✅ (Min Vertex Cover)$v \in \mathcal{V}$Densest Subgraph✅$v \in \mathcal{V}$Node Coloring🛠️$(v, c) \in \mathcal{V} \times \mathbb{Z} $GraphEnvs-Extended:EnvironmentDevelopedAction SpaceMultiCast Routing✅$e \in \mathcal{E}$Distribution Center Selection✅$v \in \mathcal{V}$Persihable Product Delivery✅$v \in \mathcal{V}$Public Transport Navigation🛠️-Exampleimportgymnasiumasgymimportgraph_envsimportnumpyasnpenv=gym.make('LongestPath-v0',n_nodes=10,n_edges=20,weighted=True,is_eval_env=True,parenting=2)forsdinrange(0,10):print(f'====={sd}=====')obs,info=env.reset(seed=sd)mask=info['mask']done=Falsewhilenotdone:valid_actions=mask.nonzero()[0]action=np.random.choice(valid_actions)obs,reward,done,_,info=env.step(action)print('Valid actions:',valid_actions,'  Action:',action,'  Reward:',reward,'  Done:',done)mask=info['mask']print(info['solution_cost'],info['solved'],info['heuristic_solution'])Environment Details:Shortest Path: The goal is to find the shortest path from the source node to the target node. At each step, an edge is added to the path. The episode is over when we reach the target node.Steiner Tree: The goal is to find the tree with the minimum weight that connects a source node to a number of destination nodes.
Package: graphepp
GraphEPPGraphEPP is a collection of functions for multipartite entanglement
purification protocols (EPP) on noisy graph states.InstallationYou can install GraphEEP into your python environment from thePython Package Index:
(possibly overwriting already installed package versions in your
environment with its dependencies):pip install grapheppAs with all python packages, this can possible overwrite already installed
package versions with its dependencies, which is why we recommend installing it
in a dedicated virtual environment.If you encounter any problems, you can try installing it the exact versions of
GraphEPP's dependencies that were used to develop it
(specified inPipfile.lock). This assumes Python 3.8 andpipenvare installed on your system:git clone https://github.com/jwallnoefer/graphepp.git
cd graphepp
git checkout main
pipenv sync
pipenv install grapheppand then usepipenv shellto activate the virtual environmentScopeThis project provides functions for operations on quantum states that are
diagonal in the graph state basis corresponding to a chosen graph state.
(for an introduction to graph states see e.g.arXiv:quant-ph/0602096)
These include:Local Pauli-diagonal noise channels that are applied on qubits of the graph state.Distance measures for states given in the same graph state basis.The ADB protocol for two-colorable graph states introduced inPhys. Rev. Lett.91, 107903 (2003)andPhys. Rev. A71, 012319 (2005).The protocol for all graph states introduced inPhys. Rev. A74, 052316 (2006).as well as auxiliary functions like local complementation of graphs.Example use case: Perform multiple rounds of EPP on a noisy linear cluster state
of 5 qubits when the CNOT operations used in the EPP are themselves imperfect
(e.g. modeled by local depolarizing noise).PublicationsAn earlier (unreleased) version of GraphEPP was used for these publications:Two-dimensional quantum repeatersJ. Wallnöfer, M. Zwerger, C. Muschik, N. Sangouard, and W. DürPhys. Rev. A94, 052307 (2016)Preprint:arXiv:1604.05352 [quant-ph]Measurement-based quantum communication with resource states generated by entanglement purificationJ. Wallnöfer and W. DürPhys. Rev. A95, 012303 (2017)Preprint:arXiv:1609.05754 [quant-ph]
Package: graphery
# GrapheryGraph manipulation to create navigation graphs on on top of Mapstery, using networkx.## InstallationIn your python environment (conda: `source activate my_env`)```pip install graphery```## How to use it```import grapherynav_graph = graphery.```## For developers - install the lastest commitIn your python environment```$ make build$ pip uninstall graphery;$ pip install dist/graphery-X.Y.Z-py2.py3-none-any.whl```where `X.Y.Z` is the lastest version marked in `setup.py`
Package: graphesn
Graph ESN libraryPytorch implementation of echo state networks for static graphs and discrete-time dynamic graphs.InstallationEasiest way to get our library is via python package:pip install graphesnUsageThe library is quite straightforward to use:fromgraphesnimportStaticGraphReservoir,Readout,initializerfromtorch_geometric.dataimportDatadata=Data(...)reservoir=StaticGraphReservoir(num_layers=3,in_features=8,hidden_features=16)reservoir.initialize_parameters(recurrent=initializer('uniform',rho=.9),input=initializer('uniform',scale=1))embeddings=reservoir(data.edge_index,data.x)readout=Readout(num_features=reservoir.out_features,num_targets=3)readout.fit(data=(embeddings,data.y),regularization=1e-3)predictions=readout(embeddings)Code outlookThe library is contained in foldersrc/graphesn:reservoir.pyimplementation of reservoirs for static and discrete-time dynamic graphs;matrix.pyrandom matrices generating functions;readout.pyimplementation of a linear readout for large-scale ridge regression;data.pyclasses to represent temporal and dynamic graphs;dataset.pysome dynamic graph datasets;util.pygeneral utilities.Theexamplesfolder contains demos for our library on some common graph datasets.ContributingThis research software is provided as-is. We are working on this library in our spare time.Code is released under the MIT license, seeLICENSEfor details.If you find a bug, please open an issue to report it, and we will do our best to solve it. For general or technical questions, please email us rather than opening an issue.ReferencesC. Gallicchio, A. Micheli (2010). Graph Echo State Networks. The 2010 International Joint Conference on Neural Networks (IJCNN 2010), pp. 3967–3974.C. Gallicchio, A. Micheli (2020). Fast and Deep Graph Neural Networks. The Thirty-Fourth AAAI Conference on Artificial Intelligence (AAAI-20).C. Gallicchio, A. Micheli (2020). Ring Reservoir Neural Networks for Graphs. The 2020 International Joint Conference on Neural Networks (IJCNN 2020).D. Tortorella, A. Micheli (2021). Dynamic Graph Echo State Networks. Proceedings of the 29th European Symposium on Artificial Neural Networks, Computational Intelligence and Machine Learning (ESANN 2021), pp. 99–104.
Package: graph-et
graph-et[grɑːf iː.tiː.]daskandxarraybased library for loading particle-in-cell simulation data produced by a variety of different codes. The support for arbitrary codes is provided through the so-called plugins. Currently supported (and planned) codes include:Tristan v1Tristan v2Usage examplefromgraphetimportDatafromgraphet.pluginsimportTristanV2# load the metadata using the TristanV2 plugind=Data(TristanV2,# pluginsteps=range(150),# steps to load metadata forpath=f"output/",# path to the datacfg_fname=f"input.cfg",# configuration filecoord_transform={# time/coordinate transformation"t":lambdat,prm:t*prm["output:interval"]*prm["algorithm:c"]/prm["grid:my0"],"x":lambdax,prm:(x-x.mean())/prm["grid:my0"],"z":lambdaz,prm:(z-z.mean())/prm["grid:my0"],"y":lambday,prm:(y-y.mean())/prm["grid:my0"],},swapaxes=[(0,1),(2,1)],# axes swapping "zyx" -> "yxz")# main containers ared.fields# <- fieldsd.particles# <- particlesd.spectra# <- spectra## Examples of doing useful stuff# plot averaged spectra of species #2 between 1.5 < t < 2.2d.spectra.n2.sel(t=slice(1.5,2.2)).mean("t").plot()# plot the density of species #1 and #2 at time t = 2.5 and y = 0.1(d.fields.dens1+d.fields.dens2).sel(y=0.1,t=2.5,method="nearest").plot(cmap="turbo")# compute the distribution function from the particle data for species #3 at 1.5 < t < 2.2cnt,_=np.histogram((np.sqrt(1+d.particles[3].u**2+d.particles[3].v**2+d.particles[3].w**2)-1).sel(t=slice(1.5,2.2)).mean("t"),bins=np.logspace(-1,3,100),)TodoAdd support forTristanV1pluginCoordinate transformations for particlesSupport for coordinate swapping in field namesSupport for custom defined fields