for line in input_file: if (line != "\n") and (line != ""): line = validate.remove_comment(line) line = re.split("\s+", line) line = list(filter(None, line)) line = " ".join(line) if not line: continue if (not check_rule) and (not check_fact_init) and ( not check_query_init): sys.stderr.write("Error - unrecognised line found\n") sys.exit(0) if check_rule: if validate.is_rule(line): rule_found = True rule = Rule(line) rules.append(rule) elif rule_found: check_rule = False check_fact_init = True else: sys.stderr.write("Error - rule not found\n") sys.exit(0) if check_fact_init: if validate.is_fact_init(line): fact_init_found = True for char in line: if char == "=": continue (facts.atoms)[char] = True (facts.is_set)[char] = True
def main(self): """ Main program method """ # $ - numbers [0-9] # ¤ - LED IDs [0-5] # @ - any character rules = [ Rule("init", "read", "@", "A1"), Rule("read", "read", "$", "A2"), Rule("read", "verify", "*", "A3"), Rule("read", "init", "@", "A4"), Rule("verify", "active", "Y", "A5"), Rule("verify", "init", "N"), Rule("active", "read-2", "*"), Rule("active", "duration-entry", "¤", "A9"), # WARNING: only 0-5 work, 6-9 crash Rule("active", "logout", "#"), Rule("read-2", "read-2", "$", "A2"), Rule("read-2", "read-3", "*", "A7"), Rule("read-2", "active", "@", "A6"), Rule("read-3", "read-3", "$", "A2"), Rule("read-3", "active", "*", "A8"), Rule("read-3", "active", "@", "A6"), Rule("duration-entry", "duration-entry", "$", "A10"), Rule("duration-entry", "active", "*", "A11"), Rule("logout", "init", "#", "A12"), Rule("logout", "active", "@"), ] fsm = FSM() fsm.set_rules(rules) fsm.run()
def create_rules(self): self.Rules = [] # response to "how does that make you feel" self.Rules.append( Rule( ['how (does|do) (?P<topic>.+) make you feel'] , ["i feel happy about ?topic .","i feel happy about destroying ?topic .", "i hate ?topic ."], None)) # response to "im a doctor" self.Rules.append( Rule( ['im a doctor'], ['no, i\'m the doctor', 'thats nice','what makes you so smart'], None)) self.Rules.append( Rule( ['what is wrong'], ['everything','nothing','something'], None)) # Ida plays chess. self.Rules.append( Rule( ['do you play chess'], ["why, yes . i do ."], None)) #rule to interpret system exit die_func = lambda instr, bob : sys.exit() self.Rules.append( Rule( ['die'], ["goodbye"], die_func)) ##maybe put your thing here about the short story. self.Rules.append( Rule( ['tell me more'], [' '], self.get_story)) self.Rules.append( Rule( ['why do you feel that way'], ['my dog died', 'i got a job','i need help'], None)) self.Rules.append( Rule( ['how are you'], ['im upset','im happy'], None)) self.Rules.append( Rule( ['do you like computer programming'], ['no, do you', 'yes why do you ask'], None)) self.Rules.append( Rule( ['why do you always wear those sunglasses'], ['i dont want to be here'], None)) self.Rules.append( Rule( ['what is your favorite color'], ['purple, what is yours'], None)) self.Rules.append( Rule( ['what is your name','whats your name'], [self.name + " what is yours"], None)) self.Rules.append( Rule( ['how does playing checkers make you feel'], ['it doesnt, i like chess, lets play....that was fun'], self.cmd_func("xboard"))) self.Rules.append( Rule( ['how did you illness make you feel'], ['i dont get sick'], None)) self.Rules.append( Rule( ['are you beautiful'], ['sometimes','my mommy said i was special','perhaps','what do you think'], None)) self.Rules.append( Rule( ['where are you family'], ['chicago','utah','mars','they live in the interwebs','san francisco'], None)) self.Rules.append( Rule( ['where did you live before you came here'], ['heaven'], None)) self.Rules.append( Rule( ['what happened','where have you been'], ['i got sick', 'my dog died', 'my dad died'], None)) self.Rules.append( Rule( ['call me (?P<topic>.+)','my name is (?P<topic>.+)'],['ok ill call you ?topic'], self.set_other_name)) self.Rules.append( Rule( ['pys'],['here is what i am thinking'],self.print_state)) self.Rules.append( Rule( ['rys'],['im all fresh'],self.refresh)) self.Rules = self.Rules + self.read_rules_from_file()
def test_assimilation(self): self.initialise_segment_table("plural_english_segment_table.txt") rule = Rule([{"cons": "+"}], [{"voice": "-"}], [{"voice": "-"}], [], obligatory=True) rule_set = RuleSet([rule]) self.assertCountEqual(rule_set.get_outputs_of_word("tz"), ["ts"])
def evaluate(parsed): ''' Evaluate a parsed rule, return True/False ''' expr = Rule(parsed, return_bool = True) return expr.match();
def test_vicky(self): self.initialise_segment_table("plural_english_segment_table.txt") rule = Rule([], [{"voice": "-"}], [{"voice": "-"}], [], obligatory=True) rule_set = RuleSet([rule]) self.assertCountEqual(rule_set.get_outputs_of_word("dot"), ["dot" + s for s in ('s', 'k', 't')])
def test_abnese_insertion(self): self.initialise_segment_table("ab_segment_table.txt") rule = Rule([], [{"cons": "-"}], [{"cons": "+"}], [{"cons": "+"}], obligatory=True) rule_set = RuleSet([rule]) self.assertCountEqual(rule_set.get_outputs_of_word("aabb"), ["aabab"])
def __init__(self, input_size: int, rule_count: int): self.__rules = tuple(Rule(input_size) for _ in range(rule_count)) self.__gradient_cache = {i: None for i in range(rule_count)} self.__loss = None
def test_make_mutation_from_empty(self): rule = Rule([], [], [], [], obligatory=True) rule.make_mutation() print(rule)
1) SIGNEXTEND(A, X) -> X if A >= Pattern::WordSize / 8 - 1; 2) SIGNEXTEND(X, SIGNEXTEND(X, Y)) -> SIGNEXTEND(X, Y) 3) SIGNEXTEND(A, SIGNEXTEND(B, X)) -> SIGNEXTEND(min(A, B), X) """ n_bits = 128 # Input vars X = BitVec('X', n_bits) Y = BitVec('Y', n_bits) A = BitVec('A', n_bits) B = BitVec('B', n_bits) rule1 = Rule() # Requirements rule1.require(UGE(A, BitVecVal(n_bits // 8 - 1, n_bits))) rule1.check(SIGNEXTEND(A, X), X) rule2 = Rule() rule2.check( SIGNEXTEND(X, SIGNEXTEND(X, Y)), SIGNEXTEND(X, Y) ) rule3 = Rule() rule3.check( SIGNEXTEND(A, SIGNEXTEND(B, X)), SIGNEXTEND(If(ULT(A, B), A, B), X) )
def __init__(self): super(Grammar, self).__init__() self.digram_index = {} self.root_production = Rule(self)
def fit_var_val(variable, value, positives, negatives): """ Learn minimal rules that explain positive examples while consistent with negatives examples Args: variable: int variable id value: int variable value id positive: list of (list of int) States of the system where the variable takes this value in the next state negative: list of (list of int) States of the system where the variable does not take this value in the next state """ #eprint("Start learning of var="+str(variable)+", val="+str(value)) remaining = positives.copy() output = [] # exausting covering loop while len(remaining) > 0: #eprint("Remaining positives: "+str(remaining)) #eprint("Negatives: "+str(negatives)) target = remaining[0] #eprint("new target: "+str(target)) R = Rule(variable, value) #eprint(R.to_string()) # 1) Consistency: against negatives examples #--------------------------------------------- for neg in negatives: if R.matches(neg): # Cover a negative example #eprint(R.to_string() + " matches " + str(neg)) for var in range(0, len(target)): if not R.has_condition(var) and neg[var] != target[ var]: # free condition #eprint("adding condition "+str(var)+":"+str(var)+"="+str(target[var])) if target[ var] > -1: # Valid target value (-1 encode all value for partial state) R.add_condition( var, target[var] ) # add value of target positive example break # 2) Minimalize: only necessary conditions #------------------------------------------- reductible = True conditions = R.get_body().copy() for (var, val) in conditions: R.remove_condition(var) # Try remove condition conflict = False for neg in negatives: if R.matches(neg): # Cover a negative example conflict = True R.add_condition(var, val) # Cancel removal break # Add new minimal rule #eprint("New rule: "+R.to_string()) output.append(R) remaining.pop(0) # 3) Clean new covered positives examples #------------------------------------------ i = 0 while i < len(remaining): if R.matches(remaining[i]): #eprint("Covers "+str(remaining[i])) remaining.pop(i) else: i += 1 return output
header = line else: # Compute disease = line[0] line = line[1:] achievedScore = 0 bestScore = len(line) # print('Computing for disease: ' + disease) disease = ["{}".format(disease)] symptoms = [] for index, column in enumerate(header[1:]): # print('Parsing {}: {} == {}'.format( # column, line[index], answers[column])) symptoms.append("{}_{}".format(column, line[index])) rules.append(Rule(symptoms, disease)) # if answers[column] == line[index]: # achievedScore += 1 # results[disease] = round(100*float(achievedScore)/bestScore, 2) mode_question = [{ 'type': 'list', 'name': 'mode', 'message': 'Seleccione el modo en que desea correr el programa', 'choices': ['If', 'RETE'], 'filter': lambda val: val.lower() }] mode_answers = prompt(mode_question, style=custom_style_3) if (mode_answers['mode'] == 'if'):
from rule import Rule from generate import generate from validate import validate # 已知:有斑点、长脖子、长腿、有奶、有蹄。 询问:这是什么动物呢? if __name__ == '__main__': file = open('input.txt', 'r') list_lines = file.readlines() target = list_lines[0].split(' ') rules = [] num = int(list_lines[1]) for i in range(2, 2 + num): rule = list_lines[i] condition, result = rule.split('#') condition = condition.split(' ') result = result[:-1] rules.append(Rule(condition, result)) num2 = int(list_lines[2 + num]) for i in range(2 + num + 1, 2 + num + 1 + num2): conds = list_lines[i].split(' ') conds[-1] = conds[-1][:-1] print('generate:') generate(target, rules, conds) print('') print('validate:') validate(target, rules, conds)
def add_rule(self, rule_str=None, rule_structured=None): if rule_str is not None: self.rules.append(Rule(rule_raw=rule_str)) else: self.rules.append(Rule(rule_structured=rule_structured))
filename= "{dir_parts}/mother_front_{abs_lat:02d}{ns}_{lang}_{astrolabe_type}" .format(**subs)) MotherBack(settings=settings).render_all_formats( filename= "{dir_parts}/mother_back_{abs_lat:02d}{ns}_{lang}_{astrolabe_type}" .format(**subs)) Rete(settings=settings).render_all_formats( filename= "{dir_parts}/rete_{abs_lat:02d}{ns}_{lang}_{astrolabe_type}". format(**subs)) Rule(settings=settings).render_all_formats( filename= "{dir_parts}/rule_{abs_lat:02d}{ns}_{lang}_{astrolabe_type}". format(**subs)) # Render the climate of the astrolabe Climate(settings=settings).render_all_formats( filename= "{dir_parts}/climate_{abs_lat:02d}{ns}_{lang}_{astrolabe_type}" .format(**subs)) # Make combined mother and climate for img_format in GraphicsPage.supported_formats(): CompositeComponent( settings=settings, components=[ MotherFront(settings=settings), Climate(settings=settings)
log_file_template = "{}_abnese_lengthening_15_words_10_{}.txt" data = [ u'aabYab', u'abYab', u'abYa', u'aabYa', u'ababababababYa', u'ababYa', u'abababYa', u'bababYab', u'bYab', u'babYab', u'bababYa', u'babababYa', u'babababYab', u'bababababYab', u'babaYa' ] target_hmm = { 'q0': ['q1'], 'q1': (['qf'], [ 'aabb', 'abb', 'aba', 'aaba', 'bbaa', 'bbbb', 'abbba', 'abba', 'bb', 'bbb', 'bbba', 'bbbba', 'bbbbb', 'bbbbbb', 'abbbbbba' ]) } initial_hmm = {'q0': ['q1'], 'q1': (['qf'], data)} rule1 = Rule([], [{"long": "+"}], [], [{}, {"bound": "+"}], obligatory=True) rule2 = Rule([], [{ "syll": "+" }], [{ "cons": "+" }], [{ "cons": "+" }], obligatory=True) target_rule_set = RuleSet([rule1, rule2]) target_tuple = (target_hmm, target_rule_set)
def rule_construction(list_of_terms, min_case_per_rule, dataset, idx_e, idx_i): c_log_file = "log_rule-construction-fnc.txt" f = open(c_log_file, "a+") f.write('\n\n\n=============== RULE CONSTRUCTION LOOP ======================================================================') f.write('\n> Stopping condition: rule cover less than minimum cases or there is no more attributes to be added') f.write('\n> Sequential construction: Sort a term to be added to rule > check number of covered cases ') f.write('\n> IF Stopping condition: set rule consequent') f.write('\n=============================================================================================================') f.write('\n EXTERNAL LOOP ITERATION ' + repr(idx_e)) f.write('\n INTERNAL LOOP ITERATION ' + repr(idx_i)) f.close() idx = 0 new_rule = Rule(dataset) current_list_of_terms = copy.deepcopy(list_of_terms) # Antecedent construction while True: idx += 1 f = open(c_log_file, "a+") f.write('\n\n>>>>>>>>>>>>>>> ITERATION ' + repr(idx)) f.close() f = open(c_log_file, "a+") f.write('\n\n==> SEQUENTIAL CONSTRUCTION:') f.write('\n> List_of_terms size: ' + repr(len(current_list_of_terms))) f.close() previous_rule = copy.deepcopy(new_rule) if not current_list_of_terms: f = open(c_log_file, "a+") f.write('\n\n=============== END CONSTRUCTION') f.write('\n> Condition: empty terms list') f.write('\n - current_list_of_terms size = ' + repr(len(current_list_of_terms))) f.write('\n - iteration number = ' + repr(idx)) f.close() break # Sorting term current_list_of_terms = set_probability_values(current_list_of_terms) term_2b_added, term_2b_added_index = sort_term(current_list_of_terms, c_log_file) if term_2b_added is None: # !!! CHECK NECESSITY f = open(c_log_file, "a+") f.write('\n\n>>>>> END Construction') f.write('\n!! Alternative Condition: empty term_2b_added') f.close() break f = open(c_log_file, "a+") f.write('\n\n> TERM TO BE ADDED: Attribute=' + repr(term_2b_added.attribute) + ' Value=' + repr(term_2b_added.value)) f.close() # Adding term and updating rule-obj new_rule.antecedent[term_2b_added.attribute] = term_2b_added.value new_rule.added_terms.append(term_2b_added) new_rule.set_covered_cases(dataset) f = open(c_log_file, "a+") f.write('\n\n==> CONSTRUCTION ITERATION ' + repr(idx) + ' RESULTS:') f.write('\n- Constructed Rule:') f.close() new_rule.print_txt(c_log_file, 'Class') f = open(c_log_file, "a+") f.write('\n- Previous Rule:') f.close() previous_rule.print_txt(c_log_file, 'Class') if new_rule.no_covered_cases < min_case_per_rule: f = open(c_log_file, "a+") f.write('\n\n=============== END CONSTRUCTION') f.write('\n> Condition: constructed_rule.no_covered_cases < min_case_per_rule') f.write('\n\n> Last constructed rule: (condition = true)') f.close() new_rule.print_txt(c_log_file, 'Class') f = open(c_log_file, "a+") f.write('\n-no_covered_cases: ' + repr(new_rule.no_covered_cases)) f.close() new_rule = copy.deepcopy(previous_rule) f = open(c_log_file, "a+") f.write('\n\n> Previous constructed rule:') f.close() new_rule.print_txt(c_log_file, 'Class') f = open(c_log_file, "a+") f.write('\n-no_covered_cases: ' + repr(new_rule.no_covered_cases)) f.close() break current_list_of_terms = list_terms_updating(current_list_of_terms, term_2b_added.attribute) if not new_rule.antecedent: f = open(c_log_file, "a+") f.write('\n\n>>>>> WARNING') f.write('\n!! No rule antecedent constructed') f.write('\n - Number of iterations: ' + repr(idx)) f.close() return None # Consequent selection new_rule.set_consequent(dataset) new_rule.set_quality(dataset, idx_e, idx_i, p=False) f = open(c_log_file, "a+") f.write('\n\n>>> FINAL RULE ') f.close() new_rule.print_txt(c_log_file, 'Class') f = open(c_log_file, "a+") f.write('\n-no_covered_cases: ' + repr(new_rule.no_covered_cases)) f.write('\n-quality: ' + repr(new_rule.quality)) f.write('\n\n> Number of iterations: ' + repr(idx)) f.close() return new_rule
def test_insertion_with_right_context_only_2(self): configurations["SINGLE_CONTEXT_TRANSDUCER_FLAG"] = True self.initialise_segment_table("ab_segment_table.txt") rule = Rule([], [{"cons": "-"}], [], [{"cons": "+"}, {"cons": "+"}], obligatory=True) rule_set = RuleSet([rule]) self.assertCountEqual(rule_set.get_outputs_of_word('bbbb'), ['abababb'])
def rule_pruning(rule, min_case_per_rule, dataset, idx_e, idx_i): p_log_file = "log_rule-pruning-fnc.txt" f = open(p_log_file, "a+") f.write('\n\n\n================== RULE PRUNING LOOP =========================================================================') f.write('\n> Stopping condition: pruned rule quality be less than best quality so far or if pruned rule antecedent has just one term') f.write('\n> Receives constructed rule > drops each term on antecedent, sequentially from first to last > each term dropped consists on another rule > new pruned rule is the one of higher quality ') f.write('\n> IF no new rules have higher quality than the new pruned rule, or if new pruned rule has oly one term in the antecedent > returns pruned rule') f.write('\n==============================================================================================================') f.write('\n EXTERNAL LOOP ITERATION ' + repr(idx_e)) f.write('\n INTERNAL LOOP ITERATION ' + repr(idx_i)) f.write('\n\n> RULE TO BE PRUNED :') f.close() rule.print_txt(p_log_file, 'Class') f = open(p_log_file, "a+") f.write('\n-Number of covered cases: ' + repr(rule.no_covered_cases)) f.write('\n-Quality: ' + repr(rule.quality)) f.close() idx = 0 new_rule = Rule(dataset) improvement = True while improvement: idx += 1 improvement = False f = open(p_log_file, "a+") f.write('\n\n>>>>>>>>>>>>>>> ITERATION ' + repr(idx)) f.close() if len(rule.antecedent) <= 1: f = open(p_log_file, "a+") f.write('\n\n==> BREAK LOOP:') f.write('\n> Condition: pruned rule antecedent = 1') # f.write('\n - Number of iterations: ' + repr(idx)) f.close() break f = open(p_log_file, "a+") f.write('\n\n==> CURRENT RULE :') f.close() rule.print_txt(p_log_file, 'Class') f = open(p_log_file, "a+") f.write('\n\n==> TERMS DROPPING PROCEDURE:') f.close() antecedent = rule.antecedent.copy() best_quality = rule.quality for term_idx, attr_drop in enumerate(antecedent): f = open(p_log_file, "a+") f.write('\n\n>>> TERM ' + repr(term_idx)) f.write('\n\n> Term_2b_dropped: Attribute=' + repr(attr_drop) + ' Value=' + repr(rule.antecedent[attr_drop])) f.close() # creates another rule deleting a term from its antecedent pruned_rule = Rule(dataset) pruned_rule.gen_pruned_rule(rule, attr_drop, term_idx, dataset, min_case_per_rule, idx_e, idx_i) f = open(p_log_file, "a+") f.write('\n\n> Pruned Rule:') f.close() pruned_rule.print_txt(p_log_file, 'Class') f = open(p_log_file, "a+") f.write('\n-Number of covered cases: ' + repr(pruned_rule.no_covered_cases)) f.write('\n-Quality: ' + repr(pruned_rule.quality)) f.close() if pruned_rule.no_covered_cases < min_case_per_rule: # POSSIBLE TO HAPPEN? f = open(p_log_file, "a+") f.write('\n!!!! WARNING: pruned rule covers less cases!') f.close() if pruned_rule.quality > best_quality: new_rule = copy.deepcopy(pruned_rule) best_quality = pruned_rule.quality improvement = True f = open(p_log_file, "a+") f.write('\n\n!!! Improvement True') f.write('\n!!! Best rule so far') f.close() # end of for attrs in antecedent if improvement: rule = copy.deepcopy(new_rule) # end of while improvement f = open(p_log_file, "a+") f.write('\n\n================== END PRUNING FUNCTION LOOP') f.write('\n> Condition: best quality of new pruned rules < current rule quality') f.write('\n - Improvement: ' + repr(improvement)) f.write('\n - Number of iterations: ' + repr(idx)) f.write('\n\n> Final Pruned Rule:') f.close() rule.print_txt(p_log_file, 'Class') return rule
def test_phi_ro_identity(self): self.initialise_segment_table("ab_segment_table.txt") rule = Rule([{"cons": "-"}], [{"cons": "-"}], [{"cons": "+"}], [{"cons": "+"}], obligatory=True) rule_set = RuleSet([rule]) self.assertCountEqual(rule_set.get_outputs_of_word("bb"), ["bb"]) self.assertCountEqual(rule_set.get_outputs_of_word("bab"), ["bab"])
def loadRules(self): """define the rules""" self.addParameterRules() # must be first! self.addPenaltyRules() self.addHandRules() self.addManualRules() self.winnerRules.add( Rule('Last Tile Completes Pair of 2..8', 'FLastTileCompletesPairMinor', points=2)) self.winnerRules.add( Rule('Last Tile Completes Pair of Terminals or Honors', 'FLastTileCompletesPairMajor', points=4)) self.winnerRules.add( Rule('Last Tile is Only Possible Tile', 'FLastOnlyPossible', points=4)) self.winnerRules.add( Rule('Won with Last Tile Taken from Wall', 'FLastFromWall', points=2)) self.winnerRules.add( Rule('Zero Point Hand', 'FZeroPointHand', doubles=1, description=m18n( 'The hand has 0 basis points excluding bonus tiles'))) self.winnerRules.add(Rule('No Chow', 'FNoChow', doubles=1)) self.winnerRules.add( Rule('Only Concealed Melds', 'FOnlyConcealedMelds', doubles=1)) self.winnerRules.add( Rule('False Color Game', 'FFalseColorGame', doubles=1, description=m18n( 'Only same-colored tiles (only bamboo/stone/character) ' 'plus any number of winds and dragons'))) self.winnerRules.add( Rule('True Color Game', 'FTrueColorGame', doubles=3, description=m18n( 'Only same-colored tiles (only bamboo/stone/character)'))) self.winnerRules.add( Rule('Concealed True Color Game', 'FConcealedTrueColorGame', limits=1, description=m18n( 'All tiles concealed and of the same suit, no honors'))) self.winnerRules.add( Rule('Only Terminals and Honors', 'FOnlyMajors', doubles=1, description=m18n('Only winds, dragons, 1 and 9'))) self.winnerRules.add( Rule('Only Honors', 'FOnlyHonors', limits=1, description=m18n('Only winds and dragons'))) self.winnerRules.add( Rule('Hidden Treasure', 'FHiddenTreasure', limits=1, description=m18n( 'Only hidden Pungs or Kongs, last tile from wall'))) self.winnerRules.add( Rule('Heads and Tails', 'FAllTerminals', limits=1, description=m18n('Only 1 and 9'))) self.winnerRules.add( Rule('Fourfold Plenty', 'FFourfoldPlenty', limits=1, description=m18n('4 Kongs'))) self.winnerRules.add( Rule('Three Great Scholars', 'FThreeGreatScholars', limits=1, description=m18n('3 Pungs or Kongs of dragons'))) self.winnerRules.add( Rule('Four Blessings Hovering Over the Door', 'FFourBlessingsHoveringOverTheDoor', limits=1, description=m18n('4 Pungs or Kongs of winds'))) self.winnerRules.add( Rule('All Greens', 'FAllGreen', limits=1, description=m18n( 'Only green tiles: Green dragon and Bamboo 2,3,4,6,8'))) self.winnerRules.add( Rule('Gathering the Plum Blossom from the Roof', 'FGatheringPlumBlossomFromRoof', limits=1, description=m18n('Mah Jong with stone 5 from the dead wall'))) self.winnerRules.add( Rule( 'Plucking the Moon from the Bottom of the Sea', 'FPluckingMoon', limits=1, description=m18n( 'Mah Jong with the last tile from the wall being a stone 1' ))) self.winnerRules.add( Rule('Scratching a Carrying Pole', 'FScratchingPole', limits=1, description=m18n('Robbing the Kong of bamboo 2'))) # only hands matching an mjRule can win. Keep this list as short as # possible. If a special hand matches the standard pattern, do not put it here # All mjRule functions must have a winningTileCandidates() method self.mjRules.add( Rule('Standard Mah Jongg', 'FStandardMahJongg', points=20)) # option internal makes it not show up in the ruleset editor self.mjRules.add( Rule('Standard Rotation', 'FStandardRotation||Orotate||Ointernal')) self.mjRules.add( Rule( 'Nine Gates', 'FGatesOfHeaven||OlastExtra', limits=1, description=m18n( 'All tiles concealed of same color: Values 1-1-1-2-3-4-5-6-7-8-9-9-9 completed ' 'with another tile of the same color (from wall or discarded)' ))) self.mjRules.add( Rule( 'Thirteen Orphans', 'FThirteenOrphans||Omayrobhiddenkong', limits=1, description=m18n( '13 single tiles: All dragons, winds, 1, 9 and a 14th tile building a pair ' 'with one of them'))) # doubling melds: self.meldRules.add( Rule('Pung/Kong of Dragons', 'FDragonPungKong', doubles=1)) self.meldRules.add( Rule('Pung/Kong of Own Wind', 'FOwnWindPungKong', doubles=1)) self.meldRules.add( Rule('Pung/Kong of Round Wind', 'FRoundWindPungKong', doubles=1)) # exposed melds: self.meldRules.add(Rule('Exposed Kong', 'FExposedMinorKong', points=8)) self.meldRules.add( Rule('Exposed Kong of Terminals', 'FExposedTerminalsKong', points=16)) self.meldRules.add( Rule('Exposed Kong of Honors', 'FExposedHonorsKong', points=16)) self.meldRules.add(Rule('Exposed Pung', 'FExposedMinorPung', points=2)) self.meldRules.add( Rule('Exposed Pung of Terminals', 'FExposedTerminalsPung', points=4)) self.meldRules.add( Rule('Exposed Pung of Honors', 'FExposedHonorsPung', points=4)) # concealed melds: self.meldRules.add( Rule('Concealed Kong', 'FConcealedMinorKong', points=16)) self.meldRules.add( Rule('Concealed Kong of Terminals', 'FConcealedTerminalsKong', points=32)) self.meldRules.add( Rule('Concealed Kong of Honors', 'FConcealedHonorsKong', points=32)) self.meldRules.add( Rule('Concealed Pung', 'FConcealedMinorPung', points=4)) self.meldRules.add( Rule('Concealed Pung of Terminals', 'FConcealedTerminalsPung', points=8)) self.meldRules.add( Rule('Concealed Pung of Honors', 'FConcealedHonorsPung', points=8)) self.meldRules.add(Rule('Pair of Own Wind', 'FOwnWindPair', points=2)) self.meldRules.add( Rule('Pair of Round Wind', 'FRoundWindPair', points=2)) self.meldRules.add(Rule('Pair of Dragons', 'FDragonPair', points=2)) # bonus tiles: self.meldRules.add(Rule('Flower', 'FFlower', points=4)) self.meldRules.add(Rule('Season', 'FSeason', points=4))
### Author: Dan6erbond ### ### Date: 24.05.2019 ### ### Version: 1.1 ### import praw import seedless from rule import Rule reddit = praw.Reddit(user_agent='Seedless', client_id=CLIENTID, client_secret=CLIENTSECRET, username=USERNAME, password=PASSWORD) rules = [ Rule(max_upvotes=0) # anything with under 1 upvote Rule(nsfw=True) # removes all NSFW ] for item in seedless.clear(reddit, rules): if type(item) == praw.models.Submission: print("Submission in /r/{} with {} points: {}".format(item.subreddit, item.score, item.title)) elif type(item) == praw.models.Comment: print("Comment in {} with {} points: {}".format(item.submission.title, item.score, item.body))
def addManualRules(self): """those are actually winner rules but in the kajongg scoring mode they must be selected manually""" # applicable only if we have a concealed meld and a declared kong: self.winnerRules.add( Rule( 'Last Tile Taken from Dead Wall', 'FLastTileFromDeadWall||Olastsource=e', doubles=1, description=m18n( 'The dead wall is also called kong box: The last 16 tiles of the wall ' 'used as source of replacement tiles'))) self.winnerRules.add( Rule( 'Last Tile is Last Tile of Wall', 'FIsLastTileFromWall||Olastsource=z', doubles=1, description=m18n( 'Winner said Mah Jong with the last tile taken from the living end of the wall' ))) self.winnerRules.add( Rule( 'Last Tile is Last Tile of Wall Discarded', 'FIsLastTileFromWallDiscarded||Olastsource=Z', doubles=1, description=m18n( 'Winner said Mah Jong by claiming the last tile taken from the living end of the ' 'wall, discarded by another player'))) self.winnerRules.add( Rule( 'Robbing the Kong', r'FRobbingKong||Olastsource=k', doubles=1, description=m18n( 'Winner said Mah Jong by claiming the 4th tile of a kong another player ' 'just declared'), debug=True)) self.winnerRules.add( Rule( 'Mah Jongg with Original Call', 'FMahJonggWithOriginalCall||Odeclaration=a', doubles=1, description=m18n( 'Just before the first discard, a player can declare Original Call meaning she needs only one ' 'tile to complete the hand and announces she will not alter the hand in any way (except bonus tiles)' ))) self.winnerRules.add( Rule( 'Dangerous Game', 'FDangerousGame||Opayforall', description=m18n( 'In some situations discarding a tile that has a high chance to help somebody to win ' 'is declared to be dangerous, and if that tile actually makes somebody win, the discarder ' 'pays the winner for all'))) self.winnerRules.add( Rule( 'Twofold Fortune', 'FTwofoldFortune||Odeclaration=t', limits=1, description=m18n( 'Kong after Kong: Declare Kong and a second Kong with the replacement ' 'tile and Mah Jong with the second replacement tile'))) # limit hands: self.winnerRules.add( Rule('Blessing of Heaven', 'FBlessingOfHeaven||Olastsource=1', limits=1, description=m18n( 'East says Mah Jong with the unmodified dealt tiles'))) self.winnerRules.add( Rule( 'Blessing of Earth', 'FBlessingOfEarth||Olastsource=1', limits=1, description=m18n( 'South, West or North says Mah Jong with the first tile discarded by East' ))) self.winnerRules.add( Rule( 'East won nine times in a row', 'FEastWonNineTimesInARow||Orotate', limits=1, description=m18n( 'If that happens, East gets a limit score and the winds rotate' )))
def main(): if len(sys.argv) < 3: print(__doc__) sys.exit(1) private_ip = sys.argv[1] dport = sys.argv[2] # Tabela Filter filter_table = Table("filter") # Regra para acesso à rede externa internal_to_external = Rule(description="INTERNAL_TO_EXTERNAL", in_interface="eth1", out_interface="eth0", target="ACCEPT") # Descartar pacotes inválidos drop_invalid_packets = Rule(description="DROP_INVALID_PACKETS", module="conntrack", ctstates=["INVALID"], target="DROP") filter_table.append_rule(internal_to_external, "FORWARD") # filter_table.append_rule(drop_invalid_packets, "INPUT") # filter_table.append_rule(drop_invalid_packets, "OUTPUT") # filter_table.append_rule(drop_invalid_packets, "FORWARD") # Regras SSH ssh_on_firewall_incoming = Rule(description="Aceita novas ou já estabelecidas conexões SSH na porta [dport].", protocol="tcp", dport=dport, module="conntrack", ctstates=["NEW", "ESTABLISHED"], target="ACCEPT") ssh_on_firewall_outgoing = Rule(description="SSH_ON_FIREWALL_OUTGOING", protocol="tcp", sport=dport, module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") ssh_external_to_internal_incoming = Rule(description="SSH_EXTERNAL_TO_INTERNAL_INCOMING", protocol="tcp", dport="22", in_interface="eth0", module="conntrack", ctstates=["NEW", "ESTABLISHED"], target="ACCEPT") ssh_external_to_internal_outgoing = Rule(description="SSH_EXTERNAL_TO_INTERNAL_OUTGOING", protocol="tcp", sport="22", in_interface="eth1", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") # Aplicação das regras para SSH filter_table.append_rule(ssh_on_firewall_incoming, "INPUT") filter_table.append_rule(ssh_on_firewall_outgoing, "OUTPUT") filter_table.append_rule(ssh_external_to_internal_incoming, "FORWARD") filter_table.append_rule(ssh_external_to_internal_outgoing, "FORWARD") # Regras para HTTP http_external_to_internal_incoming = Rule(description="HTTP_EXTERNAL_TO_INTERNAL_INCOMING", in_interface="eth0", protocol="tcp", dport="80", module="conntrack", ctstates=["NEW","ESTABLISHED"], target="ACCEPT") http_external_to_internal_outgoing = Rule(description="HTTP_EXTERNAL_TO_INTERNAL_OUTGOING", in_interface="eth1", protocol="tcp", sport="80", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") http_internal_to_external_outgoing = Rule(description="HTTP_INTERNAL_TO_EXTERNAL_OUTGOING", in_interface="eth1", protocol="tcp", dport="80", module="conntrack", ctstates=["NEW","ESTABLISHED"], target="ACCEPT") http_internal_to_external_incoming = Rule(description="HTTP_INTERNAL_TO_EXTERNAL_INGOMING", in_interface="eth0", protocol="tcp", sport="80", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") # Regras para HTTPS https_external_to_internal_incoming = Rule(description="HTTPS_EXTERNAL_TO_INTERNAL_INCOMING", in_interface="eth0", protocol="tcp", dport="443", module="conntrack", ctstates=["NEW", "ESTABLISHED"], target="ACCEPT") https_external_to_internal_outgoing = Rule(description="HTTPS_EXTERNAL_TO_INTERNAL_OUTGOING", in_interface="eth1", protocol="tcp", sport="443", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") https_internal_to_external_outgoing = Rule(description="HTTPS_INTERNAL_TO_EXTERNAL_OUTGOING", in_interface="eth1", protocol="tcp", dport="443", module="conntrack", ctstates=["NEW", "ESTABLISHED"], target="ACCEPT") https_internal_to_external_incoming = Rule(description="HTTPS_INTERNAL_TO_EXTERNAL_INCOMING", in_interface="eth0", protocol="tcp", sport="443", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") # Aplicação das regras para HTTP e HTTPS filter_table.append_rule(http_external_to_internal_incoming, "FORWARD") filter_table.append_rule(http_internal_to_external_incoming, "FORWARD") filter_table.append_rule(http_internal_to_external_outgoing, "FORWARD") filter_table.append_rule(http_external_to_internal_outgoing, "FORWARD") filter_table.append_rule(https_external_to_internal_incoming, "FORWARD") filter_table.append_rule(https_internal_to_external_incoming, "FORWARD") filter_table.append_rule(https_internal_to_external_outgoing, "FORWARD") filter_table.append_rule(https_external_to_internal_outgoing, "FORWARD") # Regras para SMTP smtp_external_to_internal_incoming = Rule(description="SMTP_EXTERNAL_TO_INTERNAL_INCOMING", in_interface="eth0", protocol="tcp", dport="25", module="conntrack", ctstates=["NEW","ESTABLISHED"], target="ACCEPT") smtp_external_to_internal_outgoing = Rule(description="SMTP_EXTERNAL_TO_INTERNAL_OUTGOING", in_interface="eth1", protocol="tcp", sport="25", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") smtp_internal_to_external_outgoing = Rule(description="SMTP_INTERNAL_TO_EXTERNAL_OUTGOING", in_interface="eth1", protocol="tcp", dport="25", module="conntrack", ctstates=["NEW","ESTABLISHED"], target="ACCEPT") smtp_internal_to_external_incoming = Rule(description="SMTP_INTERNAL_TO_EXTERNAL_INCOMING", in_interface="eth0", protocol="tcp", sport="25", module="conntrack", ctstates=["ESTABLISHED", "RELATED"], target="ACCEPT") filter_table.append_rule(smtp_external_to_internal_incoming, "FORWARD") filter_table.append_rule(smtp_external_to_internal_outgoing, "FORWARD") filter_table.append_rule(smtp_internal_to_external_incoming, "FORWARD") filter_table.append_rule(smtp_internal_to_external_outgoing, "FORWARD") # Regra padrão para a tabela Filter input_policy = Rule(description="FILTER_INPUT_POLICY", # Muito cuidado aqui! ! ! target="DROP") # filter_table.set_policy(input_policy, "INPUT") # filter_table.set_policy(input_policy, "FORWARD") # filter_table.set_policy(input_policy, "OUTPUT") # Tabela NAT nat_table = Table("nat") # Regras NAT # MASQUERADE masquerade_rule = Rule(description="MAQUERADE_RULE", out_interface="eth0", target="MASQUERADE") # DNAT dnat_rule_ssh = Rule(description="DNAT_RULE_SSH", in_interface="eth0", protocol="tcp", dport=dport, target="DNAT", to=private_ip+":22") dnat_rule_http = Rule(description="DNAT_RULE_HTTP", in_interface="eth0", protocol="tcp", dport="80", target="DNAT", to=private_ip+":80") dnat_rule_https = Rule(description="DNAT_RULE_HTTPS", in_interface="eth0", protocol="tcp", dport="443", target="DNAT", to=private_ip+":443") dnat_rule_smtp = Rule(description="DNAT_RULE_HTTP", in_interface="eth0", protocol="tcp", dport="25", target="DNAT", to=private_ip+":25")
def loadRules(self): ClassicalChinese.loadRules(self) # the squirming snake is only covered by standard mahjongg rule if tiles are ordered self.mjRules.add( Rule( 'Squirming Snake', 'FSquirmingSnake', limits=1, description=m18n( 'All tiles of same color. Pung or Kong of 1 and 9, pair of 2, 5 or 8 and two ' 'Chows of the remaining values'))) self.handRules.add( Rule('Little Three Dragons', 'FLittleThreeDragons', doubles=1, description=m18n( '2 Pungs or Kongs of dragons and 1 pair of dragons'))) self.handRules.add( Rule('Big Three Dragons', 'FBigThreeDragons', doubles=2, description=m18n('3 Pungs or Kongs of dragons'))) self.handRules.add( Rule('Little Four Joys', 'FLittleFourJoys', doubles=1, description=m18n( '3 Pungs or Kongs of winds and 1 pair of winds'))) self.handRules.add( Rule('Big Four Joys', 'FBigFourJoys', doubles=2, description=m18n('4 Pungs or Kongs of winds'))) self.winnerRules['Only Honors'].doubles = 2 self.penaltyRules.add( Rule('False Naming of Discard, Claimed for Chow', points=-50)) self.penaltyRules.add( Rule('False Naming of Discard, Claimed for Pung/Kong', points=-100)) self.penaltyRules.add( Rule('False Declaration of Mah Jongg by One Player', 'Oabsolute payees=3', points=-300)) self.penaltyRules.add( Rule('False Declaration of Mah Jongg by Two Players', 'Oabsolute payers=2 payees=2', points=-300)) self.penaltyRules.add( Rule('False Declaration of Mah Jongg by Three Players', 'Oabsolute payers=3', points=-300)) self.penaltyRules.add( Rule('False Naming of Discard, Claimed for Mah Jongg', 'Oabsolute payees=3', points=-300))
def get_random_rule(self): """ generate random rule according to weight definition """ # get random expression # can specify a subset of allowed operations `ops` def rec_get_expression(ops=None): # decide whether to get a value (variable or number) if choice(self.weights["val_exp"]) == 0: # decide whether to get a variable if choice(self.weights["var_num"]) == 0: value = sample(self.variables) # get number else: value = ri(*self.number_range) return { "value": value } # get deeper expression else: # choose operation if ops is not None: op = sample(ops) elif choice(self.weights["add_mul"]) == 0: op = sample(["+", "-"] if ops is None else ops) else: op = "*" # if we have multiplication here, only allow multiplication further to avoid bracketing ops_next = ["*"] if op == "*" else None return { "op": op, "lhs": rec_get_expression(ops=ops_next), "rhs": rec_get_expression(ops=ops_next), } # get random relation (>, <, =, or !=) def get_relation(): # choose between equalities and inequalities if choice(self.weights["eq_ineq"]) == 0: op = "=" else: op = sample([">", ">=", "!="]) return { "op": op, "lhs": rec_get_expression(), "rhs": rec_get_expression(), } # decide whether to use logical operator if choice(self.weights["logic_eq"]) == 0: # generate logical operator with random expressions on both sides rule_structured = { "op": sample(["=>", "<=>"]), "lhs": get_relation(), "rhs": get_relation(), } else: # generate random relation rule_structured = get_relation() r = Rule(rule_structured=rule_structured) return r
def loadRules(self): # TODO: we need a separate part for any number of announcements. Both r for robbing kong and a for # Original Call can be possible together. ClassicalChinese.loadRules(self) del self.winnerRules['Zero Point Hand'] originalCall = self.winnerRules.pop('Mah Jongg with Original Call') originalCall.name = m18nE('Original Call') self.handRules.add(originalCall) del self.mjRules['Nine Gates'] self.mjRules.add( Rule( 'Gates of Heaven', 'FGatesOfHeaven||Opair28', limits=1, description=m18n( 'All tiles concealed of same color: Values 1-1-1-2-3-4-5-6-7-8-9-9-9 and ' 'another tile 2..8 of the same color'))) self.mjRules.add( Rule( 'Wriggling Snake', 'FWrigglingSnake', limits=1, description=m18n( 'Pair of 1s and a run from 2 to 9 in the same suit with each of the winds' ))) self.mjRules.add( Rule( 'Triple Knitting', 'FTripleKnitting', limits=0.5, description=m18n( 'Four sets of three tiles in the different suits and a pair: No Winds or Dragons' ))) self.mjRules.add( Rule( 'Knitting', 'FKnitting', limits=0.5, description=m18n( '7 pairs of tiles in any 2 out of 3 suits; no Winds or Dragons' ))) self.mjRules.add( Rule('All pair honors', 'FAllPairHonors', limits=0.5, description=m18n('7 pairs of 1s/9s/Winds/Dragons'))) del self.handRules['Own Flower and Own Season'] del self.handRules['Three Concealed Pongs'] self.handRules.add(Rule('Own Flower', 'FOwnFlower', doubles=1)) self.handRules.add(Rule('Own Season', 'FOwnSeason', doubles=1)) del self.winnerRules['Last Tile Taken from Dead Wall'] del self.winnerRules['Hidden Treasure'] del self.winnerRules['False Color Game'] del self.winnerRules['Concealed True Color Game'] del self.winnerRules['East won nine times in a row'] del self.winnerRules['Last Tile Completes Pair of 2..8'] del self.winnerRules['Last Tile Completes Pair of Terminals or Honors'] del self.winnerRules['Last Tile is Only Possible Tile'] self.winnerRules.add( Rule( 'Buried Treasure', 'FBuriedTreasure', limits=1, description=m18n( 'Concealed pungs of one suit with winds/dragons and a pair' ))) del self.winnerRules['True Color Game'] self.winnerRules.add( Rule('Purity', 'FPurity', doubles=3, description=m18n( 'Only same-colored tiles (no chows, dragons or winds)'))) self.winnerRules['All Greens'].name = m18nE('Imperial Jade') self.mjRules['Thirteen Orphans'].name = m18nE('The 13 Unique Wonders') del self.winnerRules['Three Great Scholars'] self.winnerRules.add( Rule( 'Three Great Scholars', 'FThreeGreatScholars||Onochow', limits=1, description=m18n( '3 Pungs or Kongs of dragons plus any pung/kong and a pair' ))) self.handRules['All Flowers'].score.doubles = 2 self.handRules['All Seasons'].score.doubles = 2 self.penaltyRules.add( Rule('False Naming of Discard, Claimed for Chow/Pung/Kong', points=-50)) self.penaltyRules.add( Rule('False Declaration of Mah Jongg by One Player', 'Oabsolute payees=3', limits=-0.5)) self.winnerRules.add( Rule('False Naming of Discard, Claimed for Mah Jongg', 'FFalseDiscardForMJ||Opayforall')) self.loserRules.add( Rule('Calling for Only Honors', 'FCallingHand||Ohand=OnlyHonors', limits=0.4)) self.loserRules.add( Rule('Calling for Wriggling Snake', 'FCallingHand||Ohand=WrigglingSnake', limits=0.4)) self.loserRules.add( Rule('Calling for Triple Knitting', 'FCallingHand||Ohand=TripleKnitting', limits=0.2)) self.loserRules.add( Rule('Calling for Gates of Heaven', 'FCallingHand||Ohand=GatesOfHeaven||Opair28', limits=0.4)) self.loserRules.add( Rule('Calling for Knitting', 'FCallingHand||Ohand=Knitting', limits=0.2)) self.loserRules.add( Rule('Calling for Imperial Jade', 'FCallingHand||Ohand=AllGreen', limits=0.4)) self.loserRules.add( Rule('Calling for 13 Unique Wonders', 'FCallingHand||Ohand=ThirteenOrphans', limits=0.4)) self.loserRules.add( Rule('Calling for Three Great Scholars', 'FCallingHand||Ohand=ThreeGreatScholars', limits=0.4)) self.loserRules.add( Rule('Calling for All pair honors', 'FCallingHand||Ohand=AllPairHonors', limits=0.2)) self.loserRules.add( Rule('Calling for Heads and Tails', 'FCallingHand||Ohand=AllTerminals', limits=0.4)) self.loserRules.add( Rule('Calling for Four Blessings Hovering over the Door', 'FCallingHand||Ohand=FourBlessingsHoveringOverTheDoor', limits=0.4)) self.loserRules.add( Rule('Calling for Buried Treasure', 'FCallingHand||Ohand=BuriedTreasure', limits=0.4)) self.loserRules.add( Rule('Calling for Fourfold Plenty', 'FCallingHand||Ohand=FourfoldPlenty', limits=0.4)) self.loserRules.add( Rule('Calling for Purity', 'FCallingHand||Ohand=Purity', doubles=3))
from rule import Rule from opcodes import * """ Rule: SHL(B, AND(X, A)) -> AND(SHL(B, X), A << B) SHL(B, AND(A, X)) -> AND(SHL(B, X), A << B) Requirements: B < BitWidth """ rule = Rule() n_bits = 128 # Input vars X = BitVec('X', n_bits) A = BitVec('A', n_bits) B = BitVec('B', n_bits) # Constants BitWidth = BitVecVal(n_bits, n_bits) # Requirements rule.require(ULT(B, BitWidth)) # Non optimized result nonopt_1 = SHL(B, AND(X, A)) nonopt_2 = SHL(B, AND(A, X)) # Optimized result Mask = SHL(B, A)
def getRule(self) -> Rule: for rule in self.rules['rules']: yield Rule(rule['ruleName'], rule['patterns'], rule['responses'])