Ejemplo n.º 1
0
 def change_rules(self, whichNumbers):
     """
     Changes the rules of life, from how many neighbors it takes for a cell to remain alive or become alive
     :param whichNumbers:
     :return:
     """
     if whichNumbers:
         if toolbox.is_integer(whichNumbers) and \
                 1 <= int(whichNumbers) <= len(Rules.ruleSets.keys()):
             whichNumbers = int(whichNumbers)
     else:
         print('**************************************')
         for number, set in enumerate(Rules.ruleSets):
             stayAlive = Rules.ruleSets[set]['stayAlive']
             stayAlive1 = stayAlive[0]
             stayAlive2 = stayAlive[1]
             becomeAlive = Rules.ruleSets[set]['becomeAlive']
             string = f'{number + 1}: Neighbors needed for cell to stay alive: {stayAlive1}, {stayAlive2}     '
             string += f'Neighbors needed for cell to become alive: {becomeAlive}'
             print(string)
         print(f'{number + 2}: pick your own characters')
         print('**************************************')
         prompt = 'What character set would you like to use?'
         whichNumbers = toolbox.get_integer_between(1, number + 2, prompt)
         if whichNumbers == number + 2:
             print()
             string = 'You can pick 2 number amounts of neighbors so that an  alive cell stays alive. '
             string += '\nFor example, typing "23" makes it so if a cell has 2 or 3 neighbors, it stays alive. '
             string += '\nHow many neighbors do you want? Please type a 2 digit number: '
             stay = toolbox.get_string(string)
             become = toolbox.get_string('Which number of neighbors would you like to change a cell from dead to alive? (One digit number)  ')
             Rules.set_rules_user_values(stay, become)
     setString = list(Rules.ruleSets.keys())[whichNumbers - 1]
     Rules.set_rules(setString)
     self.display()
Ejemplo n.º 2
0
class TestMedia(unittest.TestCase):
    def setUp(self):
        self.css = '''@media screen {
@font-face {
  font-family: 'Cantarell';
  font-style: normal;
  font-weight: normal;
  src: local('Cantarell'), \
url('http://themes.googleusercontent.com/font?kit=tGao7ZPoloMxQHxq-2oxNA') \
format('truetype');
}
}'''
        self.parsed = Rules(code=self.css)
        parse(less=self.css, parent=self.parsed)

    def test_is_the_same(self):
        self.assertEqual(str(self.parsed), self.css)

    def test_media_selector(self):
        self.assertEqual(self.parsed.get_selectors(media=['screen']),
                         {'@font-face': {'src': '''local('Cantarell'), \
url('http://themes.googleusercontent.com/font?kit=tGao7ZPoloMxQHxq-2oxNA') \
format('truetype')''',
                                         'font-weight': 'normal',
                                         'font-style': 'normal',
                                         'font-family': "'Cantarell'"}})

    def test_media_selectors(self):
        self.assertEqual(self.parsed.get_media_selectors(),
                         (None, ['screen']))

    def test_none_selector(self):
        self.assertEqual(self.parsed.get_selectors(), {})
Ejemplo n.º 3
0
def findrule(ruletype="", attribute="", value=""):
    """
    debugging: find rules that have a certain ruleType and some 
    attribute-value pair
    
    Example: findrule("Concession", "nucleus", "usermodel_match") finds 
    rules of type 'Concession' where rule.nucleus == 'usermodel_match'.
    """
    rules = Rules().rule_dict
    matching_rules = {}
    
    if ruletype == "":
        for index, (name, rule) in enumerate(rules.iteritems()):
            if getattr(rule, attribute) is value:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    elif attribute == "":
        for index, (name, rule) in enumerate(rules.iteritems()):
            if rule.ruleType is ruletype:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    else:
        for index, (name, rule) in enumerate(rules.iteritems()):
            if rule.ruleType is ruletype and getattr(rule, attribute) is value:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    return matching_rules
Ejemplo n.º 4
0
def findrule(ruletype="", attribute="", value=""):
    """
    debugging: find rules that have a certain ruleType and some 
    attribute-value pair
    
    Example: findrule("Concession", "nucleus", "usermodel_match") finds 
    rules of type 'Concession' where rule.nucleus == 'usermodel_match'.
    """
    rules = Rules().rule_dict
    matching_rules = {}

    if ruletype == "":
        for index, (name, rule) in enumerate(rules.iteritems()):
            if getattr(rule, attribute) is value:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    elif attribute == "":
        for index, (name, rule) in enumerate(rules.iteritems()):
            if rule.ruleType is ruletype:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    else:
        for index, (name, rule) in enumerate(rules.iteritems()):
            if rule.ruleType is ruletype and getattr(rule, attribute) is value:
                print "rule {0} - {1}:\n{2}".format(index, name, rule)
                matching_rules[name] = rule
    return matching_rules
 def __init__(self, page, main):
     """Inits the Container and the claim buffers. Gets the item of a page
      and check if it exists, and if it is already transffered to Wikidata.
     @param page Wikipedia Page object.
     @var self.claims Raw claims as extracted.
     @var self.merged_claims self.claims merged between the languages.
     @var self.validated_claims Merged claims after checks for some
         selected propertys.
     @var self.new_claims Claims, which where not on Wikidata before and
         have no conficts.
     @var self.proceed If the item should be extracted.
     """
     #create variables
     self.lang_claims = []
     self.merged_claims = []
     self.validated_claims = []
     self.new_claims = []
     self.proceed = True
     self.main = main
     #init parents
     pywikibot.ItemPage.__init__(self, page.site, page.title())
     output.Logger.__init__(self)
     Rules.__init__(self)
     self.main = main
     #get the page
     if not self.checkNoItem():
         self.proceed = False
     else:
         self.get()
         #check if the item is untransferred
         if self.checkTransferred():
             self.proceed = False
Ejemplo n.º 6
0
def test_calctime400():
    r = Rules("data/rules.txt")
    assert r.calc_time(0, 400) == (0, 60)
    assert r.calc_time(300, 400) == (540, 1200)
    assert r.calc_time(330, 400) == (597, 1320)
    assert r.calc_time(400, 400) == (728, 1620)
    assert r.calc_time(440, 400) == (728, 1620)
Ejemplo n.º 7
0
 def __init__(self, color):
     """
     Initializing the class with its color
     :param color: Disk.DARK or Disk.LIGHT
     """
     super().__init__(color)
     self.rules = Rules()
Ejemplo n.º 8
0
    def __init__(self, dealer):

        self.rules = Rules()

        self.dealer = dealer
        self.game_type = [None, None]
        self.game_player = None
        self.first_player = (dealer + 1) % 4
        self.trick_number = 0
        self.played_cards = 0

        self.game_stage = None

        # who wants to play what
        self.bidding_round = [[None, None] for x in range(4)]

        # who doubled the game (kontra / retour)
        self.contra_retour = []

        # cards ordered by players
        self.course_of_game_playerwise = [[[None, None] for x in range(4)]
                                          for y in range(8)]

        # cards ordered by the time they were played
        self.course_of_game = [[[None, None] for x in range(4)]
                               for y in range(8)]

        # which player took the trick
        self.trick_owner = [None] * 8

        self.scores = [0, 0, 0, 0]

        #for debugging purposes remember probs for picking an action
        self.action_probabilities = [[[None, None] for x in range(4)]
                                     for y in range(11)]
Ejemplo n.º 9
0
 def __init__(self):
     Board.__init__(self)
     Actions.__init__(self)
     Rules.__init__(self)
     self.players = {}
     self.turn = 0
     self.game_over = True
Ejemplo n.º 10
0
 def setSeed(self, seed):
     if seed == None:
         seed = int(time.time() * 1000) % 2**32
     np.random.seed(seed)
     random.seed(seed)
     torch.manual_seed(seed)
     self.rules = Rules()
Ejemplo n.º 11
0
def main():
    rules = Rules()
    rulefunc = getattr(rules, rule)
    lastfld = None
    # t = Thing(fld, cell, Location(0,0))
    # t.program = list("ddrrrull")
    # things.generate()
    rooms = add_rooms()
    # for r in rooms:
    # for l in r.tpoints: fld.put('*', Location(l))
    # print [str(r) for r in rooms]
    corridors = Corridors(fld, rooms)
    corridors.create()
    fld.display()
    return

    for i in range(period):
        rules.n = i
        for thing in things:
            thing.movep()
        # if p: t.movep()
        for location in fld:
            val = fld.value(location)
            rulefunc(fld, location, val, len(fld.live_neighbours(location)))

        fld.display()
        print ' ' + "%d/%d add:%d" % (i + 1, period, rules.add)
        sleep(interval)
        lastfld = fld.field
 def __init__(self, page, main):
     """Inits the Container and the claim buffers. Gets the item of a page
      and check if it exists, and if it is already transffered to Wikidata.
     @param page Wikipedia Page object.
     @var self.claims Raw claims as extracted.
     @var self.merged_claims self.claims merged between the languages.
     @var self.validated_claims Merged claims after checks for some
         selected propertys.
     @var self.new_claims Claims, which where not on Wikidata before and
         have no conficts.
     @var self.proceed If the item should be extracted.
     """
     #create variables
     self.lang_claims = []
     self.merged_claims = []
     self.validated_claims = []
     self.new_claims = []
     self.proceed = True
     self.main = main
     #init parents
     pywikibot.ItemPage.__init__(self, page.site, page.title())
     output.Logger.__init__(self)
     Rules.__init__(self)
     self.main = main
     #get the page
     if not self.checkNoItem():
         self.proceed = False
     else:
         self.get()
         #check if the item is untransferred
         if self.checkTransferred():
             self.proceed = False
Ejemplo n.º 13
0
    def test_reMach(self):
        msg = """
===        
RegExp:%s        
Text:%s
NOT MACH ===
                """
        lanRules = Rules()
        Format = lanRules.get('Format', 'pattern')
#         print(lanRules.get('Filter', 'pattern'))
        Filter = lanRules['Filter']['pattern']
        Blank = lanRules['Blank']['pattern']
        print(Blank)
        testSamples = [
                        # [resault,regExp,Text,re.report]
                        [True, r'hello', 'hello world!'],
                        [True, Format, 'E\tE/_1_=English\tS/_1_=简体中文'],
                        [False, Format, 'E\tE/_2_=English\tS/_1_=简体中文'],
                        [True, Format, 'F\tF/_16_=la touche # pour entrer espace\tS/_16_=#键输入空格\t35'],

                        [True, Filter, 'E\t#E/_1_=English\tS/_1_=简体中文'],
                        [True, Filter, 'E\tE/_1_=English\t#S/_1_=简体中文'],
                        [True, Filter, 'E\tE/_1_=English\tS/1_=简体中文'],  # 基准字段格式检测错误,也会排除
                        [True, Filter, 'G\tF/_16_=la touche # pour entrer espace\tS/_1k6_=#键输入空格    35'],
                        [True, Blank, 'E/_1_=Eng   lish'],
                     ]

        for mustRet, regExp, text in testSamples:
            resault = Rules().Test(regExp, text)
            emsg = msg % (regExp, text)
            self.assertEqual(resault, mustRet, emsg)
        pass
Ejemplo n.º 14
0
    def get_move(self, board: Board, player_id: int, rules: Rules) -> int:
        # find out which moves are valid
        possible_moves = []
        for x in range(board.width):
            if rules.check_move(board.get_board(), board.height, x):
                possible_moves += [x]

        # this simple bot checks if it can win by playing a certain column first
        for x in possible_moves:
            board.do_move(x, player_id)
            if rules.check_win(board.get_board(), board.width, board.height,
                               board.get_last_move(), player_id):
                # even though a winning move has been detected, undo it - "game" will handle further process
                board.undo_move()
                return x
            # if bot cannot win with this move, undo it
            board.undo_move()

        # if bot cannot win in this round, it checks if opponent can win and blocks his move
        opponent_player_id = 1 if player_id == 2 else 2
        for x in possible_moves:
            board.do_move(x, opponent_player_id)
            if rules.check_win(board.get_board(), board.width, board.height,
                               board.get_last_move(), opponent_player_id):
                # make sure to undo the latest move - "game" will handle further process
                board.undo_move()
                return x
            # if bot cannot prevent a win by the opponent with this move, undo it
            board.undo_move()
        # if no victory or defeat can be detected with this very limited search depth, play randomly
        return choice(possible_moves)
Ejemplo n.º 15
0
    def put(self, board):
        if board == self.starting_board:
            self.reset()

        if len(self.boards) == 0:
            self.boards.append(board)
            self._board = board
            self.white_to_play = True
        elif board != self.boards[-1]:
            self.boards.append(board)
            self._board = board
            from_square, to_square = Rules.last_move(self.boards[-1],
                                                     self.boards[-2],
                                                     self.en_passant)
            if to_square is not None:
                if Pieces.is_white(self.boards[-1][to_square]):
                    self.white_to_play = False
                else:
                    self.white_to_play = True

                en_passant = Rules.find_en_passant(self.boards[-1],
                                                   self.boards[-2])
                self.en_passant = en_passant

                wk, wq, bk, bq = Rules.castle_rights(board)
                self.wk *= wk
                self.wq *= wq
                self.bk *= bk
                self.bq *= bq

            else:
                self.en_passant = None
                self.white_to_play = None
                self.wk, self.wq, self.bk, self.bq = False, False, False, False
Ejemplo n.º 16
0
    def start_game(self, players, props):
        """Starts the game and calls the rules... return the winner"""
        #Set data on the content
        Players.players_dict = players
        Board.property_dict = props
        #Rounds loop (1000 rounds)
        for round in range(1, 1001):
            if not len(Players.players_dict) == 1:
                #Players loop
                for player_num, player in enumerate(Players.players_dict):
                    result_dice = self.rotate_dice()
                    position = Rules.round_board_count(player, result_dice)
                    #If the property already has an owner, it makes the rent payment rule
                    if Board.property_dict[position].get('owner') and Board.property_dict[position].get('owner') != str(next(iter(player))):
                        owner = [(i) for i in Players.players_dict if next(iter(i)) == Board.property_dict[position].get('owner')]
                        rent_result = Rules.rent_rule(player_num, player, owner, Board.property_dict[position].get('rent_value'))
                    #If the property does not have an owner, enter the purchase mechanism
                    elif player.get('balance') >= Board.property_dict[position].get('price'):
                        Rules.buy_rule(player, Board.property_dict[position])

            else:
                #Ends the game when only one player remains and returns the result with the winning player type and number of rounds
                game_stats = {'winner':next(iter(Players.players_dict[0])),'round':round}
                return game_stats
        #End the game if the number of rounds reaches its limit
        game_stats = {'winner':False,'round':1000}
        return game_stats
Ejemplo n.º 17
0
Archivo: main.py Proyecto: Voder/PBE
def main():
    rules    = Rules()
    rulefunc = getattr(rules, rule)
    lastfld  = None
    # t = Thing(fld, cell, Location(0,0))
    # t.program = list("ddrrrull")
    # things.generate()
    rooms = add_rooms()
    # for r in rooms:
        # for l in r.tpoints: fld.put('*', Location(l))
    # print [str(r) for r in rooms]
    corridors = Corridors(fld, rooms)
    corridors.create()
    fld.display()
    return

    for i in range(period):
        rules.n = i
        for thing in things: thing.movep()
        # if p: t.movep()
        for location in fld:
            val = fld.value(location)
            rulefunc(fld, location, val, len(fld.live_neighbours(location)))

        fld.display()
        print ' ' + "%d/%d add:%d" % (i+1, period, rules.add)
        sleep(interval)
        lastfld = fld.field
Ejemplo n.º 18
0
 def start(self):
     self.log_msgs.append("New game {0}. Starting position is {1}".format(
         self.game_no, self.starting_position))
     if self.game_no % 30 == 0:
         self.match.rl_agent.explore = False
     else:
         self.match.rl_agent.explore = True
     for i in range(self.match.num_players):
         self.match.players[i].game_points = 0
         current_position = (self.starting_position +
                             i) % self.match.num_players
         player = self.match.players[current_position]
         cards_per_player = len(self.deck) // self.match.num_players
         player.cards = self.deck[i *
                                  cards_per_player:i * cards_per_player +
                                  cards_per_player]
         game_type = player.decide_on_game(self)
         self.log_msgs.append("Player {0} wants to play {1}".format(
             current_position, game_type))
         self.games_called.append(game_type)
     self.game_type = Rules.calc_highest_game(self.games_called)
     if self.game_type["game"] == "no_game":
         self.skip = True
     else:
         self.log_msgs.append("We play: {0}".format(self.game_type))
     for player in self.match.players:
         for card in player.cards:
             card.is_trump = Rules.is_card_trump(card, self.game_type)
         Rules.order_cards(player.cards, self)
         self.log_msgs.append("Player: {0}".format(str(player)))
Ejemplo n.º 19
0
class GenerateXML:
    def __init__(self):
        """
        init method
        :return: None
        """
        self.r = Rules("domain")
        self.create_file()

    def create_file(self):
        """
        Creates the xml file
        :return: None
        """
        save = open("/Users/arashsaidi/Blindern/INF5820/oblig3/opendial/domains/my-test-domains/therapist.xml", "w")
        save2 = open("therapist.xml", "w")

        self.rules()

        save.write(self.r.create_xml())
        save2.write(self.r.create_xml())

    def rules(self):
        self.r = Rules("domain")

        self.r.if_("trigger", "u_u", "ta til venstre", "ok")
Ejemplo n.º 20
0
    def __init__(self):
        self.games_board = Board(8)
        self.game_view = View(self.games_board)
        self.rules_game = Rules(self.games_board)

        self.player_one = HumanPlayer(Disk.DARK)
        self.player_two = RandomPlayer(Disk.LIGHT)
Ejemplo n.º 21
0
 def __init__(self):
     """
     init method
     :return: None
     """
     self.r = Rules('domain')
     self.create_file()
Ejemplo n.º 22
0
class GenerateXML():
    def __init__(self):
        """
        init method
        :return: None
        """
        self.r = Rules('domain')
        self.create_file()

    def create_file(self):
        """
        Creates the xml file
        :return: None
        """
        save = open(
            '/Users/arashsaidi/Blindern/INF5820/oblig3/opendial/domains/my-test-domains/therapist.xml',
            'w')
        save2 = open('therapist.xml', 'w')

        self.rules()

        save.write(self.r.create_xml())
        save2.write(self.r.create_xml())

    def rules(self):
        self.r = Rules('domain')

        self.r.if_('trigger', 'u_u', 'ta til venstre', 'ok')
Ejemplo n.º 23
0
 def change_rules(self, parameter):
     """
     Print possible display changes for the user.
     :param parameter: which rule display user wants
     :return: none
     """
     if toolbox.is_integer(parameter) and \
             1 <= int(parameter) <= len(Rules.ruleSets.keys()):
         setNumber = int(parameter)
     else:
         print('**************************************')
         for number, ruleSet in enumerate(Rules.ruleSets):
             bornNum = Rules.ruleSets[ruleSet]['bornNum']
             surviveNum = Rules.ruleSets[ruleSet]['surviveNum']
             print(
                 f'{number+1}: Born Number: {bornNum} Survive Number: {surviveNum}'
             )
         print(f'{number+2}: Choose your own characters! ')
         print('**************************************')
         prompt = 'What character set would you like to use?'
         setNumber = toolbox.get_integer_between(1, number + 2, prompt)
         numberOfSets = number + 2
     if setNumber == numberOfSets:
         setString = 'choice'
     else:
         setString = list(Rules.ruleSets.keys())[setNumber - 1]
     Rules.set_rules(setString)
     print(self.__currentWorld, end='')
Ejemplo n.º 24
0
    def __init__(self, objective, parent=None):
        super(QuestionWidget, self).__init__(parent)
        self.objective = objective
        self.memRules = Rules("rulelist.json")
        self.reasoned = []

        # Get consequents, antecedents and list of rules pertaining the objective
        related = self.memRules.GetRelatedRules(self.objective)
        self.cons = related["CONS"]
        self.ants = related["ANTS"]

        # Generate question list
        self.question_list = []
        for con in self.cons[1:]:
            self.question_list.append(con)
        for ant in self.ants:
            self.question_list.append(ant)
        self.question = ""

        self.ruleHeap = Rules()
        for rule in related["RULES"]:
            self.ruleHeap.CreateRule(rule)

        # Value log will be a workmemory object
        self.valueLog = WorkMemory()

        self.lbl = QLabel('Especifique el valor de "<ID>":')

        self.value_edit = QComboBox()
        self.value_edit.addItem("T")
        self.value_edit.addItem("F")

        self.replace_btn = QPushButton("Replace")
        self.replace_btn.clicked.connect(self.Replace)

        self.rules_heap = QPlainTextEdit()
        self.rules_heap.setReadOnly(True)
        self.value_logs = QPlainTextEdit()
        self.value_logs.setReadOnly(True)

        self.hlayout1 = QHBoxLayout()
        self.hlayout1.addWidget(self.lbl)
        self.hlayout1.addWidget(self.value_edit)
        self.hlayout1.addWidget(self.replace_btn)

        self.hlayout2 = QHBoxLayout()
        self.hlayout2.addWidget(self.rules_heap)
        self.hlayout2.addWidget(self.value_logs)

        self.main_layout = QVBoxLayout()
        self.main_layout.addLayout(self.hlayout1)
        self.main_layout.addLayout(self.hlayout2)

        self.UpdateValueLog()
        self.UpdateRuleHeap()
        self.SetNextQuestion()

        self.setLayout(self.main_layout)
        self.setWindowTitle("Objective Reasoning - Questioning")
        self.show()
Ejemplo n.º 25
0
def clean_rules(i_grammar):
    rules = i_grammar.rules
    print(rules.get_length(), "rules before")
    non_terminals = rules.getNonTerminalsList()
    prev_size = -1
    while len(non_terminals) != prev_size:
        prev_size = len(non_terminals)
        counter = Counter(non_terminals)
        to_remove = set()
        for key in counter:
            if counter[key] == 1 and key != "S":
                to_remove.add(key)
        new_rules = []
        for rule in rules.getRules():
            nts = rule.getNonTerminals()
            if any([nt in to_remove for nt in nts]):
                continue
            new_rules.append(rule)
        for rules_temp in rules.getConsommationRules().values():
            for rule in rules_temp:
                nts = rule.getNonTerminals()
                if any([nt in to_remove for nt in nts]):
                    continue
                new_rules.append(rule)
        rules = Rules(new_rules)
        non_terminals = rules.getNonTerminalsList()
    print(rules.get_length(), "rules after")
    return IndexedGrammar(rules)
    def __init__(self):
        self.train_episodes = 20000  # max number of episodes to learn from
        self.gamma = 1  # future reward discount

        # Exploration parameters
        self.explore_start = 1.0  # exploration probability at start
        self.explore_stop = 0.01  # minimum exploration probability 0.01
        self.decay_rate = 0.0001  # exponential decay rate for exploration prob 0.00001

        # Network parameters
        self.hidden_size1 = 128  # number of units in each Q-network hidden layer 64
        self.hidden_size2 = 64
        self.hidden_size3 = 32
        self.learning_rate = 0.000005  # Q-network learning rate 0.00001

        # Memory parameters
        self.memory_size = 1000  # memory capacity
        self.batch_size = 64  # experience mini-batch size
        self.pretrain_length = self.batch_size * 8  # number experiences to pretrain the memory

        tf.reset_default_graph()
        self.QNetworkCard = QNetworkCard(name='main',
                                         hidden_size1=self.hidden_size1,
                                         hidden_size2=self.hidden_size2,
                                         hidden_size3=self.hidden_size3,
                                         learning_rate=self.learning_rate)

        self.memory = Memory(max_size=self.memory_size)

        self.s = interface_to_states()

        self.rules = Rules()

        self.reward_scale = 210  # lost solo schneider schwarz
Ejemplo n.º 27
0
 def __init__(self, size, session, scope, threads):
     super().__init__(size, session, scope, threads)
     self.autoresolve = False
     self.rules = Rules(size, FLAGS.connections)
     self.test_mode = False
     self.epsilon = 0.0
     self.board = None
Ejemplo n.º 28
0
    def __init__(self, parent=None):
        super(DeveloperInterface, self).__init__(parent)

        self.memRules = Rules("rulelist.json")
        self.variables = WorkMemory()

        self.inst_lbl = QLabel(
            "Escribe una sentencia antecedente->consecuente")
        self.id_lbl = QLabel("Id:")
        self.val_lbl = QLabel("Value:")
        self.solv_lbl = QLabel("No se ha llegado a una solucion")

        self.st_edit = QLineEdit()
        self.var_edit = QLineEdit()

        self.values = QComboBox()
        self.values.addItem("T")
        self.values.addItem("F")

        self.refresh_button = QPushButton("Evaluate!")
        self.propagate_button = QPushButton("Propagate!")

        self.statements = QPlainTextEdit()
        self.rules = QPlainTextEdit()
        self.solutions = QPlainTextEdit()

        self.statements.setReadOnly(True)
        self.rules.setReadOnly(True)
        self.solutions = QPlainTextEdit()

        self.hlayout = QHBoxLayout()
        self.hlayout.addWidget(self.st_edit)
        self.hlayout.addWidget(self.refresh_button)

        self.hlayout2 = QHBoxLayout()
        self.hlayout2.addWidget(self.id_lbl)
        self.hlayout2.addWidget(self.var_edit)
        self.hlayout2.addWidget(self.val_lbl)
        self.hlayout2.addWidget(self.values)
        self.hlayout2.addWidget(self.propagate_button)

        self.main_layout = QGridLayout()
        self.main_layout.addWidget(self.inst_lbl, 0, 0)
        self.main_layout.addLayout(self.hlayout, 1, 0)
        self.main_layout.addWidget(self.statements, 2, 0)
        self.main_layout.addLayout(self.hlayout2, 3, 0)
        self.main_layout.addWidget(self.rules, 4, 0)
        self.main_layout.addWidget(self.solv_lbl, 5, 0)
        self.main_layout.addWidget(self.solutions, 6, 0)

        self.refresh_button.clicked.connect(self.Evaluate)
        self.propagate_button.clicked.connect(self.Propagation)

        self.st_edit.setText("((a ^ b) ^ c) -> d")

        self.setLayout(self.main_layout)
        self.setWindowTitle("My first expert system")
        self.UpdateCache()
        self.PrintWorkMemory()
Ejemplo n.º 29
0
 def is_over(self):
     result = Rules.test_victory(self._board.current)
     if result:
         return result
     result = Rules.test_draw(self._board.current)
     if result:
         return result
     return False
Ejemplo n.º 30
0
def test_calctime200():
    r = Rules("data/rules.txt")

    assert r.calc_time(0, 200) == (0, 60)
    assert r.calc_time(100, 200) == (176, 400)
    assert r.calc_time(150, 200) == (265, 600)
    assert r.calc_time(200, 200) == (353, 810)
    assert r.calc_time(220, 200) == (353, 810)
Ejemplo n.º 31
0
def addeRule(group, rule, field, criteria, value):
    obj = Rules(group=group,
                ruleName=rule,
                field=csv_dict[field],
                criteria=criteria,
                value=value)
    response = jsonify({"Response": obj.post()})
    return response
Ejemplo n.º 32
0
def deleteRule(rule):
    try:
        obj = Rules(ruleName=rule)
        response = jsonify({"Response": obj.delete()})
        return response
    except Exception as e:
        response = jsonify({"Response": False, "Reason": f"{e}"})
        return response
Ejemplo n.º 33
0
 def __init__(self, size, board, tree, network):
     self.network = network
     self.size = size
     self.tree = tree
     self.orig = board
     self.rules = Rules(size, FLAGS.connections)
     self.nr_moves = 0
     self.reinitialize()
Ejemplo n.º 34
0
 def test_check_line_false(self):
     x = ["o", "o", ""]
     self.assertFalse(Rules.check_line(x))
     x = ["", "o", ""]
     self.assertFalse(Rules.check_line(x))
     x = ["", "", ""]
     self.assertFalse(Rules.check_line(x))
     x = ["o", "o", "x"]
     self.assertFalse(Rules.check_line(x))
Ejemplo n.º 35
0
def sort_hand(cards, game_type):
    if not game_type:
        return sorted(cards, key=lambda card: Rules().cards.index(card))

    sorted_trumps = Rules().get_sorted_trumps(game_type=game_type)
    trumps = sorted([card for card in cards if card in sorted_trumps], key= lambda card : sorted_trumps.index(card))
    non_trumps = sorted([card for card in cards if card not in sorted_trumps], key=lambda card: Rules().cards.index(card))

    return non_trumps + trumps
Ejemplo n.º 36
0
def update_rules_page(key = None):
    page = Rules(dsn = app.config['dsn'])
    if request.method == 'GET':
        return page.open_updaterules(id = key)
    elif 'updaterules' in request.form:
        the_rule = request.form['the_rule']
        made_by = request.form['made_by']
        date = request.form['date']
        return page.update_rules(key, the_rule, made_by, date)
    else:
        return redirect(url_for('home_page'))
Ejemplo n.º 37
0
    def _build_kill(self):
        for idx, cell in enumerate(self.state):
            if cell != 46:
                child_state = self.state.copy()
                child_state[idx] = 46
                Rules.calculate_next_state(child_state)

                child = Node(child_state, not self.my_turn, self, MoveType.KILL, idx)
                if cell == settings.PLAYER_ID:
                    self.best_kill_moves.append({'idx': idx, 'score': child.minimax_value})
                self.children.append(child)
Ejemplo n.º 38
0
def update_pieces_page(key = None):
    page = Rules(dsn = app.config['dsn'])
    if request.method == 'GET':
        return page.open_updatepieces(id = key)
    elif 'updatepieces' in request.form:
        piece_name = request.form['piece_name']
        piece_move = request.form['piece_move']
        special_move = request.form['special_move']
        return page.update_pieces(key, piece_name, piece_move, special_move)
    else:
        return redirect(url_for('home_page'))
Ejemplo n.º 39
0
def update_captures_page(key = None):
    page = Rules(dsn = app.config['dsn'])
    if request.method == 'GET':
        return page.open_updatecaptures(id = key)
    elif 'updatecaptures' in request.form:
        name = request.form['name']
        capture_direction = request.form['capture_direction']
        starting_place = request.form['starting_place']
        can_start = request.form['can_start']
        return page.update_captures(key, name, capture_direction, starting_place, can_start)
    else:
        return redirect(url_for('home_page'))
Ejemplo n.º 40
0
    def __init__(self, parent, code, name, params, contents):
        Rules.__init__(self, parent=parent, code=code, contents=contents)

        self.__name = name
        self.__params = list()

        for param in params:
            param = Param(code=param['code'],
                          name=param['name'],
                          value=param['value'],
                          parent=self)

            self.__params.append(param)
Ejemplo n.º 41
0
    def _build_birth(self):
        for idx, cell in enumerate(self.state):
            if cell == 46:
                for a, b in itertools.combinations(self.best_kill_moves, 2):
                    a_idx = a['idx']
                    b_idx = b['idx']

                    child_state = self.state.copy()
                    child_state[idx] = settings.PLAYER_ID
                    child_state[a_idx] = 46
                    child_state[b_idx] = 46
                    Rules.calculate_next_state(child_state)

                    child = Node(child_state, not self.my_turn, self, MoveType.BIRTH, idx, (a_idx, b_idx))
                    self.children.append(child)
Ejemplo n.º 42
0
 def __init__(self):
     """
     init method
     :return: None
     """
     self.r = Rules("domain")
     self.create_file()
Ejemplo n.º 43
0
 def __init__(self,nodeNetwork=None, players={}, bonuses=[], mapString=None, coordinates=None, mapFile=None, settingsMap={}):
     self.mapFile = mapFile
     self.coordinates = coordinates
     self.rules = Rules(map=nodeNetwork, players=players)
     self.whosTurn = self.rules.players[0]
     self.turnStage = 'reinforce'
     self.reinforcementsToPlace = {}
     self.lastAttack = None
     self.fortifies = 1
     if 'fortifies' in settingsMap:
         self.fortifies = int(settingsMap['fortifies'])
     self.fortifiesLeft = self.fortifies
     self.bonuses=bonuses
     for player in self.rules.players:
         self.reinforcementsToPlace[player]=0
     self.reinforced = False
     if not mapString and not (coordinates and mapFile):
         print "this game has no pretty visualization available"
     self.mapString = mapString
     self.settingsMap = settingsMap
     self.fog = False
     if 'fog' in self.settingsMap:
         self.fog = self.settingsMap['fog']
     self.selectionList = []
     self.showAttackResult = False
     self.justMadeFreeMove = False
Ejemplo n.º 44
0
    def load_rules(self, rulesfilename):
        """
        Load the list of rules.

        @param rulesfilename is a file with rules to syllabify.

         """
        self.rules = Rules(rulesfilename)
Ejemplo n.º 45
0
 def __init__(self, state, my_turn, parent, move_type, target=None, sacrifice=None):
     self.state = state
     self.minimax_value = Rules.calculate_heuristic(state, my_turn)
     self.my_turn = my_turn
     self.parent = parent
     self.children = []
     self.move = Move(move_type, target, sacrifice)
     self.best_kill_moves = []
Ejemplo n.º 46
0
    def setUp(self):
        less = '''@var: red;

#page {
  @var: white;
  #header {
    color: @var; // white
  }
}'''
        self.parsed = Rules(code=less)
        parse(less=less, parent=self.parsed)
Ejemplo n.º 47
0
def main(records):
    facts = Data()
    Parser(records, facts)
    g = Graph(facts)
    r = Rules(g)
    vals_keys = facts.get_vals_keys()

    from_target = facts.target["from"]
    to_target = facts.target["to"]
    type_target = facts.target["type"]

    from_ = int(vals_keys[from_target]) - 1
    to = int(vals_keys[to_target]) - 1
    type = Rules.find_link_type(type_target)

    i = 0
    while g.matrix[from_][to] != type:
        r.parse_rules()
        i += 1
    g.parse_matrix()
Ejemplo n.º 48
0
 def initObj(self):
     # 设置大小,用于背景图片的缩放
     self.gameNet = GameNet(self)
     self.gameNet.connectToServer()
     self.menu = Menu((self.width, self.height), self)
     self.rules = Rules(self.width, self.height)
     self.setLevel = SetLevel(self.width, self.height)
     self.matching = Matching((self.width, self.height), self)
     self.game = Game(self)
     # finish 界面的大小和游戏界面一样
     self.finish = Finish((self.game.width, self.game.height))
Ejemplo n.º 49
0
    def load_rules(self, rulesfilename):
        """
        Load the list of rules.

        @param rulesfilename is a file with rules to syllabify.

         """
        try:
            self.rules = Rules(rulesfilename)
        except Exception as e:
            raise IOError("Syll::sppasSyll. Failed in loading rules: %s\n"%str(e))
Ejemplo n.º 50
0
 def test_partita_casuale(self):
     giocatore.input = lambda _: "0"
     giocatore.print = lambda _: ""
     gioco.print = lambda _: ""
     partita = gioco.Gioco(4)
     vincitore = partita.run()
     self.assertGreaterEqual(vincitore, 0)
     self.assertLessEqual(vincitore, 3)
     punti_totale = sum(map((lambda x: Rules.conta_punti(x.prese)), partita.giocatori))
     prese_totale = sum(map((lambda x: len(x.prese)), partita.giocatori))
     self.assertEqual(prese_totale, 40)
     self.assertEqual(punti_totale, 120)
Ejemplo n.º 51
0
    def setUp(self):
        self.css = '''@media screen {
@font-face {
  font-family: 'Cantarell';
  font-style: normal;
  font-weight: normal;
  src: local('Cantarell'), \
url('http://themes.googleusercontent.com/font?kit=tGao7ZPoloMxQHxq-2oxNA') \
format('truetype');
}
}'''
        self.parsed = Rules(code=self.css)
        parse(less=self.css, parent=self.parsed)
Ejemplo n.º 52
0
class TestConstantScope(unittest.TestCase):
    def setUp(self):
        less = '''@var: red;

#page {
  @var: white;
  #header {
    color: @var; // white
  }
}'''
        self.parsed = Rules(code=less)
        parse(less=less, parent=self.parsed)
        
    def get_page(self):
        for item in self.parsed.items:
            try:
                if item.names == ['#page']:
                    return item
            except AttributeError:
                pass
        else:
            self.fail()
        
    def get_header(self):
        for item in self.get_page().items:
            try:
                if item.names == ['#page #header']:
                    return item
            except AttributeError:
                pass
        else:
            self.fail()

    def test_root_value(self):
        self.assertEqual(self.parsed.get_value('@var'), 'red')

    def test_page_value(self):
        self.assertEqual(self.get_page().get_value('@var'), 'white')

    def test_header_value(self):
        self.assertEqual(self.get_header().get_value('@var'), 'white')
Ejemplo n.º 53
0
class Game(object):
	"""docstring for Game"""
	def __init__(self, board):
		super(Game, self).__init__()
		self.rules = Rules()
		self.board = board
		self.xSize = board.getXSize()
		self.ySize = board.getYSize()


	def iterate(self):
		newBoard = Board(self.xSize, self.ySize)
		
		for i in xrange(self.xSize):
			for j in xrange(self.ySize):
				count = self.board.getAliveNeiburghs(i,j)
				state = self.board.isAlive(i,j)
				newState = self.rules.apply(count, state)
				newBoard.setState(i,j,newState)


		self.board = newBoard

	def playGame(self):
		while(not self.board.isAllDead()):
			self.iterate()
			self.printBoard()

	def printLines(self):
		line = '\n'
		for i in xrange(self.ySize):
			line += '-'

		print line + '\n'

	def printBoard(self):
		os.system('clear')
		self.printLines()
		print self.board.toString()
		self.printLines()
Ejemplo n.º 54
0
 def setUp(self):
     Config.get_config('conf/main.test.conf')
     from rules import Rules
     self.rules = Rules('conf/speech.test.xml')
Ejemplo n.º 55
0
class TestTakkRules(unittest.TestCase):
    __dummy_file = 'test_action_dummy_file'

    def setUp(self):
        Config.get_config('conf/main.test.conf')
        from rules import Rules
        self.rules = Rules('conf/speech.test.xml')

    def test_pattern_matched(self):
        patterns = self.rules.pattern_match('play some music artist Led Zeppelin')
        self.assertGreater(len(patterns), 0)
        self.assertEqual(patterns[0]['id'], 'play-music')
        self.assertEqual(patterns[0]['attributes']['artist'], 'Led Zeppelin')

    def test_pattern_not_matched(self):
        patterns = self.rules.pattern_match('this will never be matched by any of my rules')
        self.assertEqual(len(patterns), 0)

    def test_non_existing_action(self):
        self.assertRaises(KeyError, self.rules.run_action, 'non-existing-action')

    def test_get_rules_by_pattern(self):
        rules = self.rules.get_rules_by_patterns(['create-file'])
        self.assertEqual(len(rules), 1)
        self.assertEqual(rules[0], 'create-test-file-shell-on-create-file')

        action_ids = self.rules.get_actions_by_rule(rules[0])
        self.assertEqual(len(action_ids), 1)
        self.assertEqual(action_ids[0], 'create-test-file-shell')

    def test_get_rules_by_multiple_patterns(self):
        rules = self.rules.get_rules_by_patterns(['create-file', 'remove-file'])
        self.assertEqual(len(rules), 1)
        self.assertEqual(rules[0], 'create-and-remove-test-file-shell-on-double-command')

        action_ids = self.rules.get_actions_by_rule(rules[0])
        self.assertEqual(len(action_ids), 2)
        self.assertEqual(action_ids[0], 'create-test-file-shell')
        self.assertEqual(action_ids[1], 'remove-test-file-shell')

    def test_get_rules_by_non_existing_pattern(self):
        rules = self.rules.get_rules_by_patterns(['i-dont-exist'])
        self.assertEqual(len(rules), 0)

    def test_shell_action(self):
        self.rules.run_action('create-test-file-shell',
            {'filename': self.__dummy_file }
        )

        self.assertTrue(os.path.isfile(self.__dummy_file))

        self.rules.run_action('remove-test-file-shell',
            {'filename': self.__dummy_file }
        )

        self.assertFalse(os.path.isfile(self.__dummy_file))

    def test_python_action(self):
        self.rules.run_action('create-test-file-python',
            {'filename': self.__dummy_file }
        )

        self.assertTrue(os.path.isfile(self.__dummy_file))

        self.rules.run_action('remove-test-file-python',
            {'filename': self.__dummy_file }
        )

        self.assertFalse(os.path.isfile(self.__dummy_file))

    def tearDown(self):
        if os.path.isfile(self.__dummy_file):
            os.remove(self.__dummy_file)
Ejemplo n.º 56
0
 def test_vincitore_no_briscola(self):
     c1 = Carta(Seme.SPADI, 1)
     c2 = Carta(Seme.SPADI, 2)
     self.assertEqual(Rules.vincitore([c1, c2], Seme.BASTONI), c1)
Ejemplo n.º 57
0
 def test_punteggio(self):
     c = [Carta(Seme.SPADI, 1), Carta(Seme.SPADI, 2), Carta(Seme.SPADI, 3)]
     self.assertEqual(Rules.conta_punti(c), 21)
Ejemplo n.º 58
0
 def test_vincitore_pari(self):
     c1 = Carta(Seme.SPADI, 1)
     c2 = Carta(Seme.BASTONI, 1)
     self.assertEqual(Rules.vincitore([c1, c2], Seme.DENARI), c1)