Saravanan666/pypi-org huggingface dataset:
Package: constgen
NoteThis repo is based on the excellent tool by @aantn:https://github.com/aantn/reconstantIntroductionConstGen lets you share multiple object definitions between multiple programming languages:constantsenumstypesSupported Languages:RustJavascriptGoJavaC/CPPPython2/3VueInstallationpip install git+https://github.com/ymec/constgen.gitORpip install constgenUsageCreate a configuration yaml (for an example seeexample.yaml)constgen example.yamlKnown IssuesCurrently running main only works through pip installing the tool - running directly with python would cause import errors
Package: constituency-tree-converter
成分分析树转换工具介绍这个包的目的在于将数据转换成符合constituency tree输入的格式，解决业界没有此类工具的问题（没发现～）。从NLTK标注出来的数据集来看，有点反直觉，标注起来很麻烦。故提供一个LabelTree类，您可以通过这个类转换成符合nltk标注格式的数据出来。installpipinstallconstituency-tree-converter工作原理图More Usage:更多请参考tests/。convert NLTK tree to LabelTreeconvert NLTK tree to sequence历史项目更名啦，从constituency-tree-labeling-tool改成constituency-tree-converter，方便通过名字直观理解以及通过工作原理图快速理解。
Package: constload
constloadconstload is a package designed to simplify the process of loading settings into Python applications by providing
certain functionality that is frequently reimplemented from project to project. This includes the ability to set
defaults and set certain parameters as required.Usage examplesWhen loading settings, you have a couple of options. You can provide pre-parsed data in a dictionary, or you have have
data parsed for you from a filepath or from a string.fromconstloadimportConstantLoader# Loading JSON from filec=ConstantLoader("/path/to/settings/file.json")# Loading JSON from stringc=ConstantLoader("{'hello': 'world'}")# Using preloaded dictc=ConstantLoader(your_dict)It's also trivial to write your own loaders.defmy_loader(data):# Basic CSV loadermy_dict={}lines=data.split("\n")forlineinlines:vals=line.split(",")my_dict[vals[0]]=vals[1:]returnmy_dictc=ConstantLoader("/path/to/file.csv",loader=my_loader)When you've got your data loaded, you can begin to extract values.This is done by using tuples that contain paths to your values.# ("user", "name") is equivalent to ["user"]["name"]USER_NAME=c.required(("user","name"))USER_PETS=c.default(("user","pets"),[])Any changes made byc.defaultare automatically mirrored to the dictionary as they're being made. This means you can
work directly with the dictionary, if you so choose.c.default(("user","pets"),[])c.data["user","name"]# -> []InstallingWith YAML support -pip install constload[yaml]Otherwise -pip install constloadLicenceLicenced under the Mozilla Public Licence 2.0.Licence text.SupportIf you need help, feel free to open an issue.ContributingIssues/pull requests are welcome. :)
Package: constprotocol
Python is inherently mutable, only a handful of builtin classes enjoy true
immutability such asint,str, andtuple; everything else is up for
grabs. This allows a lot of clever tricks, but it also leads to some
difficult bugs. Just think about code like this:classMyClass:def__init__(self)->None:self._mylist:List[str]=[]defget_mylist(self)->List[str]:returnself._mylistWhat happens when someone gets that list and mutates it? Of course, you get
bugs because MyClass now has something it doesn’t expect. The easiest way to
fix that is of course to do this:classMyClass:def__init__(self)->None:self._mylist:List[str]=[]defget_mylist(self)->List[str]:returnself._mylist.copy()Problem solved, right? What if _mylist has a million entires? That can
quickly become a huge bottle neck in your program. In most statically typed
languages you have some kind of “const” or “immutable” modifier that tells
the compiler/interpreter “don’t let anyone modify this”. Normally that would
be impossible in python, but we have static type checkers like mypy, and
Protocols. We can create a protocol that implements all of the methods that
don’t mutate a class, and expose only those. Then the static type checker can
catch the mutation for us.fromconstprotocolimportConstListclassMyClass:def__init__(self)->None:self._mylist:List[str]=[]defget_mylist(self)->ConstList[str]:returnself._mylistc=MyClass()c.get_mylist().append('foo')# Error: ConstList has not method append!Of course, the underlying python values have not actually become immutable,
but like C and C++ it’s more of a promise that if you take a ConstList or
return one that you’re not going to modify it.One of the goals of const protocol is to have 0 runtime performance impact. You
could create an immutable proxy, that wraps a value and only exposes it’s const
methods, and all of it’s attributes as read only (using properties and more
proxies). But that has runtime overhead and adds code complexity. This approach
adds zero run time overhead and very little complexity to the code.What if I want to mutate the value after all?You don’t.No seriously, if you say you’re not going to modify it, don’t.What you probably want to do is copy the constified value, which will give
you a mutable value:l:ConstList[str]=['a','b','c']ml=l.copy()reveal_type(ml)Which will beList[str]If you really, really, need to, you can usetyping.cast. of course, you get
to keep the pieces.StatusRight now there are four classesConstSetforset,ConstListforlist,ConstMappingformappings, andContDictforDict. There’s
likely bugs, this is alpha quality software, and a kind of crazy idea to get
better error checking in cases where the author knows that someone shouldn’t
be mutating their data.I found a bugCool, file an issue.I want fix something or add somethingEven better, open a Merge Request
Package: constractor
Constractor (derived from “Content Extractor’) allows one to use machine learning for web pages content extraction.
Library provide following functionality:Extendable features api.Gui tools for simple train-set creation.Simple training and testing process.Simple usage of trained model.Models dumping.etcInstallationNOTE: Project was developed and tested under Ubuntu 12.04. Other operation systems may require enhancements of library.Ubuntu >=12.04 instructions:Install apt dependecies:sudoapt-getinstall pip gcc g++python-devpython-qt4Install constractor:sudo pip install constractorUsageFollowing code will run gui train helper:#!/usr/bin/env python
from constractor.train import GuiTrainer

if __name__ == '__main__':
    GuiTrainer()And following code will print html of predicted element in DOM:#!/usr/bin/env python
from constractor.parser import Parser

if __name__ == '__main__':
    predicted = Parser('https://pypi.python.org', model_file='model.txt').predicted
    for element in predicted:
        print unicode(element.toInnerXml()).encode('utf-8')ContributionProject is completely open for contribution. See more on bitbucket repo:https://bitbucket.org/dkuryakin/constractor
Package: constrained
Constrained:caution:Not working; not maintained. Useannotated-typesinstead.:caution:A Python library for enforcing type and range constraints.FeaturesFloat and Int types with range constraintsRegex type for string matchingCFG type for context-free grammar matchingenforce_annotation_constraints decorator to enforce constraintsInstallationpipinstallconstrainedUsageFirst, import the necessary types and the decorator from theconstrainedmodule:fromconstrainedimportFloat,Int,Regex,CFG,enforce_annotation_constraintsThen, define your function with type annotations:@enforce_annotation_constraintsdefP(x:Float[0,'inf'])->Float[0,'inf']:returnx/2The decorator will enforce the constraints at runtime and raise a ValueError if any argument or the return value does not match the constraints defined in the function's signature.Alternativesannotated-types(much better thanconstrainedand up-to-date (08/2023);pip install annotated-types)Constrained Types
Package: constrained-attacks
Constrained attacksDescriptionConstrained attacks is a framework for constraints adversarial examples unified across multiple constraints' domain.
It currently supports a large diversity of constraints (linear and non-linear).
We instantiated our framework with two attacks:MoEvA2: a multi-objective genetic based approachC-PGD: a gradient based approach extended from PGD (cite) to support domain constraints.To learn more, check out our paperA Unified Framework for Adversarial Attack and Defense in Constrained Feature
Space.InstallationUsing pippipinstallconstrained-attacksDependenciesconstrained-attacks requires:python = "~3.8"numpy = "^1.22.3"joblib = "^1.1.0"pymoo = "^0.5.0"tqdm = "^4.63.1"pandas = "^1.4.1"Additional optional requirements for C-PGD are:tensorflow = "2.8"adversarial-robustness-toolbox[tensorflow] = "1.10"ExamplesYou can find a usage examplefor MoEvA2:tests/attacks/moeva/test_moeva_run.pyfor C-PGD:tests/attacks/cpgd/test_pgd_run.pyfor the constraints definition:tests/attacks/moeva/url_constraints.py.CitationIf you have used our framework for research purposes, you can cite our publication by:BibTex:@article{simonetto2021unified,
  title={A unified framework for adversarial attack and defense in constrained feature space},
  author={Simonetto, Thibault and Dyrmishi, Salijona and Ghamizi, Salah and Cordy, Maxime and Traon, Yves Le},
  journal={arXiv preprint arXiv:2112.01156},
  year={2021}
}
Package: constrained-linear-regression
constrained-linear-regressionThis is a Python implementation of constrained linear regression in scikit-learn style.
The current version supports upper and lower bound for each slope coefficient.It was developed after this questionhttps://stackoverflow.com/questions/50410037Installation:pip install constrained-linear-regressionYou can use this model, for example, if you want all coefficients to be non-negative:fromconstrained_linear_regressionimportConstrainedLinearRegressionfromsklearn.datasetsimportload_bostonfromsklearn.linear_modelimportLinearRegressionX,y=load_boston(return_X_y=True)model=ConstrainedLinearRegression(nonnegative=True)model.fit(X,y)print(model.intercept_)print(model.coef_)The output will be like-36.99292986145538
[0.         0.05286515 0.         4.12512386 0.         8.04017956
 0.         0.         0.         0.         0.         0.02273805
 0.        ]You can also impose arbitrary bounds for any coefficients you choosemodel=ConstrainedLinearRegression()min_coef=np.repeat(-np.inf,X.shape[1])min_coef[0]=0min_coef[4]=-1max_coef=np.repeat(4,X.shape[1])max_coef[3]=2model.fit(X,y,max_coef=max_coef,min_coef=min_coef)print(model.intercept_)print(model.coef_)The output will be24.060175576410515
[ 0.          0.04504673 -0.0354073   2.         -1.          4.
 -0.01343263 -1.17231216  0.2183103  -0.01375266 -0.7747823   0.01122374
 -0.56678676]You can also set coefficientslassoandridgeif you want to apply the
corresponding penalties. Forlasso, however, the output might not be exactly
equal to the result ofsklearn.linear_model.Lassodue to the difference
in the optimization algorithm.
Package: constrainedlr
Constrained Linear Regressionconstrainedlr is a drop-in replacement forscikit-learn'slinear_model.LinearRegressionwith the extended capability to apply constraints on the model's coefficients, such as signs and lower/upper bounds.InstallationpipinstallconstrainedlrExample UsageCoefficients sign constraintsfromconstrainedlrimportConstrainedLinearRegressionmodel=ConstrainedLinearRegression()model.fit(X_train,y_train,coefficients_sign_constraints={0:"positive",2:"negative"},intercept_sign_constraint="positive",)y_pred=model.predict(X_test)print(model.coef_,model.intercept_)Coefficients range constraintsfromconstrainedlrimportConstrainedLinearRegressionmodel=ConstrainedLinearRegression()model.fit(X_train,y_train,coefficients_sign_constraints={0:{"lower":2},# 1st coefficient must be 2 or higher2:{"upper":10},# 3rd coefficient must be smaller than 103:{"lower":0.1,"upper":0.5},# 4th coefficient must be between 0.1 and 0.5},)y_pred=model.predict(X_test)print(model.coef_)See more in thedocumentationLicenceMIT
Package: constrained-matrix-factorization
Advancements on non-negative matrix factorization in PyTorch, with crystallography as a primary use case.Free software: 3-clause BSD licenseDocumentation:https://nsls-ii.github.io/constrained-matrix-factorization.FeaturesTorch enabled non-negative matrix factorizationOptional input components and/or weightsRigidly constrained specific components or weightsPlotting utilitiesUtilities for “elbow method” and automatic iterative cmfWrappers for scientific use casesscattering: XRD, PDF, TS, SAXSDeveloper’s InstructionsInstall from github:$ python3 -m venv cmf_env
$ source cmf_env/bin/activate
$ git clone https://github.com/nsls-ii/constrained-matrix-factorization
$ cd constrained-matrix-factorization
$ python -m pip install --upgrade pip wheel
$ python -m pip install -r requirements-dev.txt
$ pre-commit install
$ python -m pip install -e .Original PublicationThis work was originally published onthe arXiv here of this paper.
It has since been peer reviewd and published inApplied Physics Reviews.AbstractNon-negative Matrix Factorization (NMF) methods offer an appealing unsupervised learning method for real-time analysis of streaming spectral data in time-sensitive data collection, such as in situ characterization of materials. However, canonical NMF methods are optimized to reconstruct a full dataset as closely as possible, with no underlying requirement that the reconstruction produces components or weights representative of the true physical processes. In this work, we demonstrate how constraining NMF weights or components, provided as known or assumed priors, can provide significant improvement in revealing true underlying phenomena. We present a PyTorch based method for efficiently applying constrained NMF and demonstrate this on several synthetic examples. When applied to streaming experimentally measured spectral data, an expert researcher-in-the-loop can provide and dynamically adjust the constraints. This set of interactive priors to the NMF model can, for example, contain known or identified independent components, as well as functional expectations about the mixing of components. We demonstrate this application on measured X-ray diffraction and pair distribution function data from in situ beamline experiments. Details of the method are described, and general guidance provided to employ constrained NMF in extraction of critical information and insights during in situ and high-throughput experiments.
Package: constrainedrandom
constrainedrandomA package for creating and solving constrained randomization problems.Use this package to create SystemVerilog-style "declarative" randomizable objects in Python.This is achieved by providing wrappers around the Pythonrandomandconstraintpackages, and aims to be as efficient as possible in a language like Python.Installation$pipinstallconstrainedrandomDocumentationRead the docs hereTo build the documentation yourself:$cddocs
$makehtmlThe index page is atdocs/_build/html/index.html- you can open this in a web browser.Releases/versioningReleases are created using tags from the repository and can be found onPyPI.Versioning attempts to followSemantic Versioning.ContributionsPlease feel free to contribute to the project, following these guidelines:Please contribute by creating a fork and submitting a pull request.Pull requests should be as small as possible to resolve the issue they are trying to address.Pull requests must respect the goals of the library, as stated in the documentation.Pull requests should maintain backwards compatibility at least as far as Python 3.8.Pull requests should pass all the tests in thetests/directory. Runpython -m tests.Pull requests should take care not to make performance worse except for cases which require bug fixes. Runpython -m testsandpython -m benchmarks.Pull requests should update the documentation for any added/changed functionality.TODOAdd proper CI using tox or similar, testing Python versions 3.8..currentAdd equivalent SystemVerilog testcases for benchmarking.Contact the author(s)Will Keen -william.keen@imgtec.com
Package: constrained-sampler-maffettone
Sampling a high dimensional space under non-linear constraints.Initially composed as a technical challenge for Citrine.OperationAs a python scriptInstall from PyPyScaling and future workSecurity considerations ofeval.Special cases have analytic solutions (linear constraints defining a simplex)The current method works best in continuous spaces.Consider limits of time and memoryImproved uniformnity on sampling after certain number of steps (autocorrelation function) D. Chandler, Introduction to Modern Statistical Mechanics (Oxford University
Press, 1987
Package: constrained_types
Constrained TypesStatement: Nothing should ever really be modelled as any String or any integer.ExampleA user wants to order a number of books. Can it be zero? Can it be negative?@add_constraint(lambdax:x>0,"Order must be at least 1")classOrderQuantity(ConstrainedInt):passnow:quantity=OrderQuantity(5)# works exactly like an inttotal_price=quantity*5# but you can't create sneaky discount booksquantity=OrderQuantity(-1)# !! raises ValueErrorMultiple constraints@add_constraint(lambdax:x>0,"Order must be at least 1")@add_constraint(lambdax:x<200,"Our shipping system can't send more then 200")classOrderQuantity(ConstrainedInt):passIn addition the constraints are guaranteed to execute in order so any
expensive checks to run can be listed further down.Cache resultsIf you expect the same value multiple times you can add caching for
the validation. The actual caching is passed tofunctools.lru_cache.@add_constraint(lambdax:len(x)>0,"The order id must be set")@add_constraint(lambdax:len(x)<10,"Order ids are under 10 chars")@add_constraint(some_really_complicated_checksum,"The order number was invalid")@cache_constraint_results(maxsize=100)classOrderId(ConstrainedString):passWorks well with mypy (or other static type checkers)# The following will type check fine. OrderId is a real typedefretrieve_order(order_id:OrderId):...maybe something further down only accepts strings:def_fetch_item_from_db(table_name:str,item_id:str):...defretrieve_order(order_id:OrderId):# The following will type check fine. OrderId extends strreturn_fetch_item_from_db("orders",order_id)Integrates with pydantic@add_constraint(lambdax:x>0,"Order must be at least 1")classOrderQuantity(ConstrainedInt):pass@add_constraint(lambdax:len(x)==4,"Invalid order id")classBookId(ConstrainedString):passclassOrder(BaseModel):book_quantity:OrderQuantitybook_id:BookIdWhy not use the pydantic version of these constrained types?The pydantic types only really work with pydantic. Invalid instances
can be created by constructing directly. Since constraint checking
is triggered by the constructor the constraints willalwaysbe
true for any instance of the class.
Package: constrainingorder
Constraining Order==================Constraining Order is a pure python library for solving certain classes ofconstraint satisfaction problems. In particular it contains an implementationof IntervalSets to represent fairly general sets of real numbers.Constraining Order is neither very powerful, nor very performant, and forserious problems there are more powerful solutions available:* `gecode <http://www.gecode.org>`_ (which looks amazing and superbly documented)* `or-tools <https://code.google.com/p/or-tools/>`_* `choco <http://www.choco-solver.org/>`_The creation of Constraining Order was sparked by the realisation that severalof my projects require the solution of relatively simple constraintsatisfaction problems, while it was unacceptable to pull in a heavy dependencyfor that.The code is hosted on `GitHub <https://github.com>`_:https://github.com/jreinhardt/constraining-orderDocumentation is hosted on `readthedocs <https://readthedocs.org/>`_:https://constraining-order.readthedocs.org/en/latest/The API of Constraining Order is slightly inspired by gecode (as I had lookedat its documentation before writing it) and the nomenclature I use roughlyfollowsTsang, E. Foundations of Constraint Satisfaction Academic Press, 1996which I used to read up a bit on the topic.The name `constraining order` is a pun on restraining order, as it was not yettaken for a software project and even makes a bit of sense as long as you don'tthink about it.
Package: constraintula
constraintulaimportattrsimportconstraintulaimportnumpyasnpPI=np.piarea,radius=constraintula.symbols('area radius')@constraintula.constrain([area-PI*radius**2])@attrs.define(frozen=True)# or `@attrs.frozen`classCircle:radius:floatarea:floatcircle_from_radius=Circle(radius=2)circle_from_area=Circle(area=42)InstallationUserpip install constraintulaDeveloperpip install -e .[dev]DisclaimerThis is not an officially supported Google product.
Package: constrict
constrict=========Constrict is a framework for adding type checking and constraints to functions.Constraints are declared as function annotations (following the `typespec`format) and type checking is added using function decorators.Constrict also provides a set of assertions for ad hoc type checking an a mixin TestCase class for extending your unit tests.Constrict depends on the ``typespec`` <https://github.com/galini/typespec>module and you should see the documentation of that module for details of howto format function arguments.The Decorators--------------Import the decorators like so::>>> from constrict import checkargs, checkreturn, checkyield, checkAdding type checking for function arguments::>>> @checkargs... def my_func_of_int(i : int) -> int:...     return i + 1>>> my_func_of_int("hello")Traceback (most recent call last):...constrict.ArgumentAssertionError: Invalid value 'hello' for argument i - i must be int.>>> my_func_of_int(1)2Adding type checking for function return values::>>> @checkreturn... def my_func_of_int(i : int) -> int:...     return str(i+1)>>> my_func_of_int("hello")Traceback (most recent call last):...TypeError: Can't convert 'int' object to str implicitly>>> my_func_of_int(1)Traceback (most recent call last):...constrict.ReturnAssertionError: Invalid return value '2' - value must be int.Adding type checking for yielded values::>>> @checkyield... def my_generator() -> int:...     for val in (1, 2, 3, "4", 5, 6):...         yield val>>> for val in my_generator():...     passTraceback (most recent call last):...constrict.YieldAssertionError: Invalid yielded value '4' - value must be int.The ``check`` decorator is the same as using both ``checkargs`` and``checkreturn`` for a function or ``checkargs`` and ``checkyield`` for agenerator.The Assertions--------------Importing all assertions::>>> from constrict import (assert_isa, assert_valid, assert_valid_args,...     assert_valid_return, assert_valid_yield, assert_call_ok,...     assert_iter_ok)The assertions are functions that work like the ``assert`` statement. They dodynamic type checking and raise errors for invalid types. See the documentationof each function for further details.Using With unittest-------------------You can write test cases that check argument, return and yielded values.Simply mix in the constrict.TestCase class into your test cases::import unittestimport constrictclass MyTestCase(unittest.TestCase, constrict.TestCase):def testSomething(self):...if __name__ == '__main__':unittest.main()This makes available extra test assertions that you can use.See the documentation of the ``constrict.TestCase`` class for more details.