Saravanan666/pypi-org huggingface dataset:
Package: ruled-password-generator
Ruled-Password-GeneratorA password generator with customizable rules.Generate a password of the given length.Generate a password from given letters.Generate non duplicate passwords.Installpipinstallruled-passwd-generatorUsage (Example)Generate a password with 12 letters which have non-duplicate lettersfromruled_password_generatorimportPasswordGeneratorpwg=PasswordGenerator(12,uniques=-1)password=pwg.generate()Generate a password with 10 to 16 letters which have at least 9 non-duplicate letterspwg=PasswordGenerator(10,16,uniques=9)password=pwg.generate()Generate a password with 10 letters which have given lettersPassword has at least 3 letters in 'ABCDEF'.Password has at least 4 letters in '123456789'.Password has at least 1 letters in '-'.rules={'ABCDEF':3,'123456789':4,'-':1}pwg=PasswordGenerator(10,rules=rules)password=pwg.generate()If no rules are given, the default rules are following:It haslowercasesat least one.It hasuppercasesat least one.It hasdigitsat least one.It hassymbolsat least one.Generate 20 unique passwordspasswords=pwg.bulk_generate(20,unique=True)ContributionsContributions are welcomed via PR.LicenseMIT
Package: ruledxml
Given an XML file. Transform it into another XML file using a rules file.
A rules file reads some element, process them and returns a new value
which is written to an XML path. Rules are inspired by Business Rule Engines
such asIntellect.InstallationInstallation with source package:python3 setup.py installpip3 install-rrequirements.txtInstallation from PyPI:pip3 install ruledxmlRun the testsuite:Startpython3Runimport ruledxml.testsRunruledxml.tests.runall()RulesRules are designed to be written with little technical knowledge.
However, not all transformations (comparable to XSLT) are possible.
If elements occur multiple times in the source XML,
the capabilities are limited.Rules are written in the python programming language:@source("/root/body/header")
@destination("/html/body/article/h1")
def ruleFirstHeader(header):
    return header + "!"The first element at XPath/root/body/headeris read, its
text content is looked up and passed as argumentheaderto the functionruleFirstHeader.If the source element does not exist, an empty string is supplied.
Be aware that source parameters are always strings.The rule returns the original header appended with an exclamation mark.
The return value is written to the destination XPath/html/body/article/h1. All non-existing elements will be created.
If an element already exists, the first match is taken.Required elementsA source of errors in that design is when elements do not exist
and an empty string is supplied as argument. This is a silent error.You can specify required elements in a variableinput_requiredwhich
is interpreted before the actual processing starts:input_required = [
    "/root/body/header"
]If the element/root/body/headerdoes not exist in the source XML file,
a ValueError is thrown.Non-empty elementsSimilarly to required elements, we have non-empty elements. Paths mentioned
in theinput_nonemptyvariable are required to yield nonempty values.
Otherwise an error is thrown and processing aborted.ImplementationA little bit of lxml and lots of decorator magic ;)License3-claused BSD license. Hence you can use the software
for whatever you like, if you want to mention my name
in your software product, you need to ask me.cheers,
meisterluk <admin@lukas-prokop.at>
Package: rule-engine
A lightweight, optionally typed expression language with a custom grammar for matching arbitrary Python objects.Documentation is available athttps://zeroSteiner.github.io/rule-engine/.Rule Engine expressions are written in their own language, defined as strings in Python. The syntax is most similar to
Python with some inspiration from Ruby. Some features of this language includes:Optional type hintingMatching strings with regular expressionsDatetime datatypesCompound datatypes (equivalents for Python dict, list and set types)Data attributesThread safetyExample UsageThe following example demonstrates the basic usage of defining a rule object and applying it to two dictionaries,
showing that one matches while the other does not. SeeGetting Startedfor more information.importrule_engine# match a literal first name and applying a regex to the emailrule=rule_engine.Rule('first_name == "Luke" and email =~ ".*@rebels.org$"')# => <Rule text='first_name == "Luke" and email =~ ".*@rebels.org$"' >rule.matches({'first_name':'Luke','last_name':'Skywalker','email':'luke@rebels.org'})# => Truerule.matches({'first_name':'Darth','last_name':'Vader','email':'dvader@empire.net'})# => FalseThe next example demonstrates the optional type system. A custom context is created that defines two symbols, one string
and one float. Because symbols are defined, an exception will be raised if an unknown symbol is specified or an invalid
operation is used. SeeType Hintingfor more information.importrule_engine# define the custom context with two symbolscontext=rule_engine.Context(type_resolver=rule_engine.type_resolver_from_dict({'first_name':rule_engine.DataType.STRING,'age':rule_engine.DataType.FLOAT}))# receive an error when an unknown symbol is usedrule=rule_engine.Rule('last_name == "Vader"',context=context)# => SymbolResolutionError: last_name# receive an error when an invalid operation is usedrule=rule_engine.Rule('first_name + 1',context=context)# => EvaluationError: data type mismatchWant to give the rule expression language a try? Checkout theDebug REPLthat makes experimentation easy. After
installing just runpython-mrule_engine.debug_repl.InstallationInstall the latest release from PyPi usingpip installrule-engine. Releases followSemantic Versioningto
indicate in each new version whether it fixes bugs, adds features or breaks backwards compatibility. See theChange Logfor a curated list of changes.CreditsSpencer McIntyre - zeroSteinerLicenseThe Rule Engine library is released under the BSD 3-Clause license. It is able to be used for both commercial and
private purposes. For more information, see theLICENSEfile.
Package: rulekit
RulekitThis package is python wrapper forRuleKitlibrary - a versatile tool for rule learning.Based on a sequential covering induction algorithm, it is suitable for classification, regression, and survival problems.InstallationNOTE:
This package is a wrapper for Java library, it requires Java (version 1.8.0 tested) to be installed on the computer. Both Open JDK and Oracle implementations are supported.pipinstallrulekit# after installationpython-mrulekitdownload_jarThe second command will fetch the latest RuleKit library jar file from its Github releases page. It is required to use this package.Running testsIf you're running tests for the first time (or you want to update existing tests resources) you need to download tests resources from RuleKit repository. You can do it by running:python tests/resources.py downloadRuning tests:In directory wheresetup.pyfile exists.python -m unittest discover ./testsSample usagefromrulekitimportRuleKitfromrulekit.classificationimportRuleClassifierfromsklearn.datasetsimportload_irisX,y=load_iris(return_X_y=True)clf=RuleClassifier()clf.fit(X,y)prediction=clf.predict(X)print(prediction)DocumentationFull documentation is availablehere
Package: rulelearn
rulelearn (v0.1)This package contains a rule induction toolkit to generate readable and editable rules from data. The code was originally released within the largerAIX 360 packageand is provided and extended here separately with less dependencies.It contains the following components:Boolean Decision Rules via Column Generation (Light Edition) (Dash et al., 2018)Generalized Linear Rule Models (Wei et al., 2019)Fast Effective Rule Induction (Ripper) (William W Cohen, 1995)Relational Rule Network (R2N) (Kusters et al., 2022)trxf - Technical Rule Interchange Format - Rule Set Interchange providing common evaluation tools and PMML export for
rule sets.Installationpip install rulelearnAcknowledgementsrulelearn is built with the help of several open source packages. All of these are listed in requirements.txt and include:scikit-learnhttps://scikit-learn.org/stable/about.htmlLicense InformationApache 2.0
Package: ruleminer
ruleminerPython package to discover association rules in Pandas DataFrames.This package implements the code of the paperDiscovering and ranking validation rules in supervisory data.The documentation can be foundhere.Here is what the package does:Generate human-readable validation rules using rule templates containing regular expressions and a Pandas DataFrame datasetavailable functions: min, max, abs, quantile, sum, substr, split, count, sumif and countifincluding parameters for metric filters and rule precisions (including XBRL tolerances)Evaluate rules and calculate association rules metricsavailable metrics: abs support, abs exceptions, confidence, support, added value, casual confidence, casual support, conviction, lift and rule power factorHere are some examples of rule templates with regexes with which you can generate validation rules:if ({“Type”} == “.*”) then ({“.*”} > 0)if ({“.*”} > 0) then (({“.*”} == 0) & ({“.*”} > 0))(({“.*”} + {“.*”} + {“.*”}) == {“.*”})({“Own funds”} <= quantile({“Own funds”}, 0.95))(substr({“Type”}, 0, 1) in [“a”, “b”])The first template generates (with the dataset described in the Usage section) rules likeif ({“Type”} == “non-life_insurer”) then ({“TP-nonlife”} > 0)if ({“Type”} == “life_insurer”) then ({“TP-life”} > 0)These generated validation rules can then be used to validate new datasets.History0.1.0 (2021-11-21)First release on PyPI.0.1.1 (2021-11-23)Added more documentation to the README text0.1.2 (2022-1-20)Bug fixes wrt some complex expressions0.1.3 (2022-1-26)Optimized rule generation process0.1.4 (2022-1-26)Evaluated columns in then part are now dependent on if part of rule0.1.5 (2022-1-30)Rule with quantiles added (including evaluating intermediate results)0.1.6 and 0.1.7 (2022-2-1)A number of optimization in rule generation process0.1.8 (2022-2-3)Rule power factor metric added0.1.12 (2022-5-11)Optimizations: metric calculations are done with boolean masks of DataFrame0.1.14 (2023-4-17)Nested functions addedsubstr and in operators added0.1.16 (2023-8-3)Templates now do not necessarily have to contain a regexBug fix when evaluating rules that contain columns that do not existTemplates now can start with ‘if () then’0.1.17 (2023-8-8)Generate rules now runs without specified data0.1.18 (2023-8-8)Dedicated function added for template to rule conversion without dataExp sign changed from ^ to **0.1.19 (2023-8-27)Small fixes rule conversion without data0.1.20 (2023-8-29)Small fixes in evaluating rules with syntax errors0.1.21 (2023-10-11)changed sum to nansumadded tolerance functionality for ==0.1.22 (2023-10-17)added tolerance functionality for !=, <, <=, > and >=updated docs0.1.23 (2023-10-18)added nested conditions in functions0.1.24 (2023-10-25)added sumif and improved tolerance functionality
Package: rule-mining-algs
Repository for Assocation Rule Mining AlgorithmsSeveral algorithms for mining association rules have been implemented in this repository.NOTE: The algorithms are implemented in pure Python which makes them rather slow.Installationpipinstallrule-mining-algsDifferent Algorithms thus farAISAprioriFP-Growthh-Clique (all-confidence pushed into Apriori-algorithm)Quantitative Association RulesACloseMinimal Non-redundant rulesRule Generation for apriori-like AlgorithmsBrute-Force Mining of Classification RulesClustering to find intervals for numeric attributesEvolutionary Algorithm to Discover Itemsets (GAR)Evolutionary Algorithm to Discover Rules with fixed consequent (GAR-PLUS)Datasetsstore_data.csv:Store dataagaricus-lepiota.data:Mushroom datasetBuild and Run modelsTransformers: static_discretization(equi-depth/width partitioning of numeric attributes),
cluster_interval_data(birch clustering to find intervals for numeric attributes)Itemset_Miners: seeAlgorithmssectionRule_Miners: generate_rules(Standard algorithm to generate rules from itemsets),
min_redundant_rules(only usable with a_close itemset miner)Example for a dataset with a single attributefromalgs.modelsimportStandardMinerfromalgs.dataimportload_store_datadata_df=load_store_data()# Load store dataset# Choose modelm=StandardMiner()# Set parameters for the algorithmsm.set_args(m.itemset_miner,{"min_support":0.005})m.set_args(m.rule_miner,{"min_conf":0.5})# Run the algorithm on the datasetoutput=m.run(data_df)Example for a DB containing several categorical attributesfromalgs.dataimportload_shroom_datafromalgs.quantitativeimportstatic_discretizationfromalgs.rule_genimportget_classification_rulesshrooms=load_shroom_data()mine_quant=StandardMiner(static_discretization)names={name:0fornameinshrooms.columns}# Set arguments for transformer, itemset and rule minermine_quant.set_args(mine_quant.transformer,{"discretization":names})mine_quant.set_args(mine_quant.itemset_miner,{"min_support":0.15})mine_quant.set_args(mine_quant.rule_miner,{"min_conf":0.65})rules=mine_quant.run(shrooms)# Post processing step to obtain rules having only the label in the consequentclassification_rules=get_classification_rules(rules,"label")
Package: rulengine
# rulengine##### Simple Rule Engine for Python##### Rule engine gives an approach to you: "it would valid, if one of the rules can provide necessarry condition"##### You can use in your any project, but remember; you need to make your own data context and generate rules on your side# Installation```bashpip install rulengine```# Usage```bashIn [1]: from rulengine.core import DataType, RuleOperator, ConditionOperator, Rule, ConditionIn [2]: from rulengine import executeIn [3]: condition = Condition(value=1, operator=ConditionOperator.EQUAL, comparison_value=2, data_type=DataType.INTEGER)In [4]: rule =  Rule(operator=RuleOperator.AND, conditions=[condition])In [5]: execute([rule])Out[5]: False```
Package: rulent
RulentRulent is a python in-memory latency events engine that uses a set of declarative rules and triggers actions (outcomes).Quick StartHere is a sample implementation usingrulentwith FastAPI:fromfastapiimportFastAPIfrom.importmodelsimportrulentapp=FastAPI()rulent.load_rules()@app.post("/validate")asyncdefvalidate(request:models.EventRequest):print(request)returnrulent.validate_data(dict(request))@app.get("/reload")asyncdefreload_engine():rulent.load_rules()return{"status":"success","message":"Conditions reloaded successfully",}Make sure you have a folder called "events" with atleast one YAML file like the below example:events:click:rules-operator:"and"rules:-rule:"NameCheck"conditions:-"person.name":"James"-rule:"AgeCheck"conditions:-"person.age":"42"You can programatically create this folder and sample file usingrulent.init(). This needs to be used only once.Key ComponentsThe main components of the event engine are as below.The Web APIThis is for ingesting events. This acts as the entry point for new events to be received and validation against rules.EventsEvents are specific, explicitly sent, pieces of information sent with the payload. This sets the foundation for the rules engine to process rules based on the event.RulesThese are the rules that need to be applied on the JSON payload. This has support for dot notation. The rules can be combined usingrules-operator: "or".A sample rules block:events:click:rules-operator:"and"rules:-rule:"NameCheck"conditions:-"person.name":"James"-rule:"AgeCheck"conditions:-"person.age":"42"OutcomesOnce the payloads have been processed against rules, matched payloads can initiate actions.Actionsare bundled together as outcomes.Note: Actions are executed asynchronously.ActionsActions that are part of outcomes can be extended by navigating to the logic folder and actions.go file. Currently, this has access to outcomes and the payloads that were received.
Package: ruleof40
ruleof40Wrapper API for theruleof40.tradewebapp.  Returns the current and historic list of Rule of 40 stocks and includes scores and relevant dates etc.Has this project saved you time and/or money?  Consider buying me a coffee with the sponser link on the Github homepage.FeaturesGet the current Rule of 40 listGet historic Rule of 40 data:At any date since 2010-01-01The full Rule of 40 history of any symbol since 2010-01-01InstallUse the following pip command:pip install ruleof40Methods & Classesget_current(cookies=None)Returns the current list of Rule of 40 stocks, including their Rule of 40 scoreget_hist_per_date(date:datetime = None, cookies=None)Returns the list of Rule of 40 stocks for the given dateget_hist_per_symbol(symbol:str, cookies=None)Returns the Rule of history for the given symbol since 2010-01-01.NotesRecorded datesALLapply to theSTARTof the trading day on that dateExamplesfrom ruleof40 import ruleof40 as r40
from datetime import datetime, date
import pandas as pd

current = r40.get_current()
print(current)

histdate = r40.get_hist_per_date(datetime(2021, 1, 1, 0, 0))
print(histdate)

histsym = r40.get_hist_per_symbol('ADBE')
print(histsym)
Package: ruleset
Bayesian Rule Set MiningFind the rule set from the dataThe input data should follow the following format:X has to be a pandas DataFrameall the column names can not contain '_' or '<'and the column names can not be pure numbersThe categorical data should be represented in string(For example, gender needs to be 'male'/'female',or '0'/'1' to represent male and female respectively.)The parser will only recognize this format of data.So transform the data set first before using thefunctions.y hass to be a numpy.ndarrayreference:Wang, Tong, et al. "Bayesian rule sets for interpretable classification."Data Mining (ICDM), 2016 IEEE 16th International Conference on. IEEE, 2016.The program is very picky on the input data formatX needs to be a pandas DataFrame,y needs to be a nd.arrayParameters----------max_rules : int, default 5000Maximum number of rules when generating rulesmax_iter : int, default 200Maximun number of iteratations to find the rule setchians : int, default 1Number of chains that run in parallelsupport : int, default 5The support is the percentile threshold for the itemsetto be selected.maxlen : int, default 3The maximum number of items in a rule#note need to replace all the alpha_1 to alpha_+alpha_1 : float, default 100alpha_+beta_1 : float, default 1beta_+alpha_2 : float, default 100alpha_-beta_2 : float, default 1beta_-alpha_l : float array, shape (maxlen+1,)default all elements to be 1beta_l : float array, shape (maxlen+1,)default corresponding patternSpacelevel : int, default 4Number of intervals to deal with numerical continous featuresneg : boolean, default TrueNegate the featuresadd_rules : list, default emptyUser defined rules to addit needs user to add numerical version of the rulescriteria : str, default 'precision'When there are rules more than max_rules,the criteria used to filter rulesgreedy_initilization : boolean, default FalseWether start the rule set using a greedyinitilization (according to accuracy)greedy_threshold : float, default 0.05Threshold for the greedy algorithmto find the starting rule setpropose_threshold : float, default 0.1Threshold for a proposal to be acceptedmethod : str, default 'fpgrowth'The method used to generate rules.Can be 'fpgrowth' or 'forest'Notice that if there are potentially many rulesthen fpgrowth is not a good method as it willhave memory issue (because the rule screening isafter rule generations).Sample usagefrom ruleset import *df = pd.read_csv('data/adult.dat', header=None, sep=',', names=['age', 'workclass', 'fnlwgt', 'education', 'educationnum', 'matritalstatus', 'occupation', 'relationship', 'race', 'sex', 'capitalgain', 'capitalloss', 'hoursperweek', 'nativecountary', 'income'])y = (df['income'] == '>50K').as_matrix()df.drop('income', axis=1, inplace=True)model = BayesianRuleSet(method='forest')model.fit(df, y)
Package: rules-extraction
Rules extractionRules extraction for eXplainable AIDocumentationCoverageContributionInstall dependenciesUsing pippython-mvenv.venvsource.venv/bin/activate
pipinstall-rrequirements.lockUsing RyeInstallRyeandadd shimsto your PATH.Ensureryeis accessible in the$PATHenvironment variable.
Rye will automatically download the suitable Python toolchain as needed.To check the installation, check the following commands return an output:rye--versionInstall python dependencies and activate the virtualenv:ryesync
ryeshellInstall Pre-commit hooksGit hooks are used to ensure quality checks are run by all developers every time
before a commit.pre-commitinstallPre-commit hooks can be run manually with:pre-commitrun--all-filesReleaseTo publish the package onPyPI, refer toRELEASE.
Package: rulexai
RuleXAIRuleXAI is a rule-based aproach to explain the output of any machine learning model. It is suitable for classification, regression and survival tasks.InstalationRuleXAI can be installed from PyPIpipinstallrulexaiOr you can clone the repository and run:pipinstall.Model agnostic examplefromsklearn.datasetsimportload_irisfromsklearn.model_selectionimporttrain_test_splitfromsklearn.svmimportSVCimportpandasaspdfromrulexai.explainerimportExplainer# load iris datasetdata=load_iris()df=pd.DataFrame(data['data'],columns=data['feature_names'])df['class']=data['target']# train a SVM classifierX_train,X_test,y_train,y_test=train_test_split(df.drop(columns=["class"]),df["class"],test_size=0.2,random_state=0)svm=SVC(kernel='rbf',probability=True)svm.fit(X_train,y_train)# use Explainer to explain model outputexplainer=Explainer(X=X_train,model_predictions=y_train.astype(str),type="classification")explainer.explain()Sample notebooksClassification- in this notebook, the data fromhttps://www.kaggle.com/c/titanicis analysed to show the advantages and possibilities of using the RuleXAI library for in-depth analysis of the dataset for classification task. The use of RuleXAI to explain rule-based and tree-based models was also compared.Regression- notebook showing the use of RuleXAI to explain rule-based regression modelSurvival- notebook showing the use of RuleXAI to explain rule-based survival modelBlack-box modelexplainability - the purpose of this notebook is to demonstrate the possibility of using RuleXAI to explain any black box models.Transformation- notebook showing the use of RuleXAI to transform a dataset. Often datasets contain missing values and nominal values. Most available algorithms do not support either missing values or nominal values. Many algorithms require the data to be rescaled beforehand. The RuleXAI library is able to convert a dataset with nominal and missing values into a binary dataset containing as attributes the conditions describing the dataset and as values “1” when the condition is satisfied for the example and “0” when the condition is not satisfied.DocumentationFull documentation is availablehere
Package: rulez
Documentation:https://rulez.rtfd.orgChangelog0.1.5 (2020-12-24)reject field name with spacesfix ‘~’ operator support when using ‘and’ and elasticsearchallow typecasting of value to date/datetimeallow ‘+’ character in string dslfixed datetime handling in field dslupdate to elasticsearch 7relicense to Apache License0.1.4 (2020-11-14)added docsDeprecaterulez.field__getitem__method in favor of__call__0.1.3 (2020-11-12)Added documentationImproved DSL parsingEnhancerulez.fieldwith more operations