예제 #1
0
파일: tests.py 프로젝트: atthom/Scxml2Java
 def test_to_string(self):
     A1 = Action("State_1_B1", None)
     A2 = Action("State_1_B1")
     self.assertEqual(A1.to_string(0),
                      "callFunctionForAction(\"State_1_B1\");\n")
     self.assertEqual(A2.to_string(0),
                      "callFunctionForAction(\"State_1_B1\");\n")
예제 #2
0
    def select_dialog_action(self, s):

        # confirm action, then patient, then recipient, then extraneous arguments
        a_name, a_max = arg_max(s.user_action_belief)
        unsure = True if a_max < 1 else False

        missing_params = []
        if a_name is not None:
            a_preds = []
            for i in range(0, s.action_num_expected_params[a_name]):
                p_name, p_max = arg_max(s.user_action_parameters_belief[i])
                if p_name is not None:
                    if p_max < 1:
                        unsure = True
                else:
                    missing_params.append(i)
                a_preds.append(p_name)
            a = Action.Action(a_name, a_preds)
            if unsure:
                if (s.previous_action is not None and s.previous_action[0] == "confirm_action" and
                        s.previous_action[1][0] == a):
                    return "repeat_goal", [], Action.Action()
                else:
                    return "confirm_action", [a], a
            elif len(missing_params) > 0:
                return "request_missing_param", [missing_params[0]], a
            else:
                return "repeat_goal", [], Action.Action()

        else:
            return "repeat_goal", [], Action.Action()
    def choose_action(self, opponent):
        if self.opponent_moves[0] > self.opponent_moves[1] and self.opponent_moves[0] > self.opponent_moves[2]:
            return Action(2)

        elif self.opponent_moves[1] > self.opponent_moves[0] and self.opponent_moves[1] > self.opponent_moves[2]:
            return Action(0)
        else:
            return Action(1)
예제 #4
0
파일: tests.py 프로젝트: atthom/Scxml2Java
    def test_merge(self):
        A1 = Action("State_1_B1", "Ceci est un test avec log")
        A2 = Action("State_1_B2", "Ceci est un test avec second log")

        A2.merge(A1)
        self.assertEqual(
            A2.to_string(0),
            "callFunctionForActionWithLog(\"State_1_B2State_1_B1\",\"Ceci est un test avec second log\nCeci est un test avec log\");\n"
        )
예제 #5
0
 def velg_aksjon(self, motspiller):
     if motspiller not in Spiller.history:
         return Action(rn(0,2))
     else:
         player_history = Spiller.history[motspiller]
         stein = player_history.count(Action(0))
         saks = player_history.count(Action(1))
         papir = player_history.count(Action(2))
         frequence = [stein, saks, papir]
         most_common = frequence.index(max(frequence))
         return Action(self.best_move(most_common))
 def velg_aksjon(self, motspiller):
     if len(Spiller.history[motspiller]) < self.number:
         return Action(rn(0, 2))
     sub_sequence = Spiller.history[motspiller][-self.number:]
     frequency = [0, 0, 0]
     for i in range(
             len(Spiller.history[motspiller]) - self.number - 1, 0, -1):
         if Spiller.history[motspiller][i:i + self.number] == sub_sequence:
             frequency[Action.get_index(
                 Spiller.history[motspiller][i + self.number + 1])] += 1
     if max(frequency) == 0:
         return Action(rn(0, 2))
     else:
         return self.best_move(self.moves[frequency.index(max(frequency))])
 def velg_aksjon(self, motspiller):
     if len(Spiller.history[motspiller]) < self.number:
         return Action(rn(0, 2))
     sub_sequence = Spiller.history[motspiller][-self.number:]
     player_history = self.get_player_history(motspiller)
     frequency = [0, 0, 0]
     for i in range(len(player_history) - self.number - 2, 0, -1):
         if Spiller.history[motspiller][i:i + self.number] == sub_sequence:
             move = player_history[i + self.number]
             frequency[move.get_num()] += 1
     if max(frequency) < 1:
         return Action(rn(0, 2))
     else:
         return self.best_move(frequency.index(max(frequency)))
예제 #8
0
    def __init__(self, sx, sy):

        print('init solomon {0},{1}'.format(sx, sy))

        self.current_state["standing"] = True
        self.current_state["crouching"] = False
        self.current_state["walking"] = False
        self.current_state["jumping"] = False
        self.current_state["wandswish"] = False
        self.current_state["falling"] = False
        self.current_state["cwleft"] = False
        self.current_state["cwright"] = False
        self.current_state["canfall"] = False
        self.current_state["headhurt"] = False

        self.x = sx
        self.y = sy

        self.startx = sx
        self.starty = sy

        self.AG_walk = ActionGroup()
        self.AG_walk.append(
            "wobble",
            Action(func=self.wobble,
                   max=5,
                   cycle=True,
                   min=-5,
                   reverseloop=True,
                   init_tick=0))
        self.AG_walk.append(
            "footR", Action(func=self.footR, max=13, cycle=True, min=-1))
        self.AG_walk.append(
            "footL",
            Action(func=self.footL, max=13, cycle=True, min=-1, init_tick=7))

        self.AG_jump = ActionGroup()
        self.AG_jump.append("jump_displacement",
                            Action(func=self.jump_displacement, max=10, min=0))
        self.AG_jump.action("jump_displacement").callback = self.end_jump

        self.AG_walk.speed_scale(2)

        self.A_wandswish = Action(func=self.swish,
                                  min=-8,
                                  max=-1,
                                  cycle=False,
                                  reverseloop=False,
                                  init_tick=-6)
예제 #9
0
 def fadeIn(duration):
     def run(target, deltaTime, totalTime):
         target.opacity = totalTime/duration
         if (target.opacity > 1):
             target.opacity = 1
         return (totalTime >= duration)
     return Action(run)
예제 #10
0
파일: ConfigApi.py 프로젝트: ssnui/pyHueISY
def parse_action(values):
    re_trigger = re.compile(r'trigger\[(\d+)\]')
    re_scene = re.compile(r'scene\[(\d+)\]')
    action = Action.Action()
    if values["name"] != '':
        action.name = values["name"]

    if values["description"] != '':
        action.description = values["description"]

    action.random_scene = "random-scene" in values

    triggers = {}
    scenes = {}
    for value in values:
        m = re_trigger.match(value)
        if m is not None and m.lastindex == 1:
            triggers[int(m.group(1))] = values[value]
        else:
            m = re_scene.match(value)
            if m is not None and m.lastindex == 1:
                scenes[int(m.group(1))] = values[value]

    for trigger_index in sorted(triggers):
        action.add_trigger(triggers[trigger_index])

    for scene_index in sorted(scenes):
        action.append_scene(scenes[scene_index])

    return action
예제 #11
0
파일: TDE.py 프로젝트: npcomet/MagicSPECS
def setup(env):
    Action.simple_action('moc',
                         '${MOC} ${MOC_FLAGS} ${SRC} ${MOC_ST} ${TGT}',
                         color='BLUE')
    Action.simple_action('meinproc',
                         '${MEINPROC} ${MEINPROCFLAGS} --cache ${TGT} ${SRC}',
                         color='BLUE')
    Action.simple_action('po', '${POCOM} ${SRC} ${PO_ST} ${TGT}', color='BLUE')
    Action.simple_action(
        'kidl',
        '${DCOPIDL} ${SRC} > ${TGT} || (rm -f ${TGT} ; false)',
        color='BLUE')
    Action.simple_action('skel', 'cd ${SRC[0].bld_dir(env)} && ${DCOPIDL2CPP} --c++-suffix cpp ' \
     '--no-signals --no-stub ${SRC[0].m_name}', color='BLUE')
    Action.simple_action('stub', 'cd ${SRC[0].bld_dir(env)} && ${DCOPIDL2CPP} --c++-suffix cpp ' \
     '--no-signals --no-skel ${SRC[0].m_name}', color='BLUE')
    Action.simple_action('kcfg', '${KCONFIG_COMPILER} -d${SRC[0].bld_dir(env)} ' \
     '${SRC[0].bldpath(env)} ${SRC[1].bldpath(env)}', color='BLUE')
    Action.Action('uic', vars=uic_vardeps, func=uic_build, color='BLUE')

    Object.register('kde_translations', kde_translations)
    Object.register('kde_documentation', kde_documentation)
    Object.register('kde', kdeobj)

    Object.hook('kde', 'UI_EXT', handler_ui)
    Object.hook('kde', 'SKEL_EXT', handler_skel)
    Object.hook('kde', 'STUB_EXT', handler_stub)
    Object.hook('kde', 'KCFGC_EXT', handler_kcfgc)
예제 #12
0
파일: ConfigApi.py 프로젝트: ssnui/pyHueISY
def show_action(action_id):
    if app.director.hue_bridge is None:
        flash("Hue bridge settings must be saved first", category="error")
        return redirect(url_for('show_settings'), code=302)
    if request.method == "POST":
        action = parse_action(request.values)
        if action_id != action.name and action_id != 'new':  # Rename
            app.director.rename_action(action_id, action.name)
            flash("Action renamed from " + action_id + " to " + action.name +
                  " and updated")
        elif action_id == "new":
            flash("Action " + action.name + " added")
        else:
            flash("Action " + action.name + " updated")
        app.director.update_action(action)
        app.director.save_config()
        return redirect(url_for('show_actions'), code=303)
    else:
        if action_id == 'new':
            action = Action.Action()
        else:
            action = app.director.actions[action_id]
        return render_template('action.html',
                               action=action,
                               triggers=app.director.get_triggers(),
                               scenes=app.director.scenes)
예제 #13
0
    def executePolicy(self, observation):
        # Start the counter
        count = 0
        # Copy the initial observation
        self.workingObservation = self.copyObservation(observation)

        if self.verbose:
            print("START")

        # While a terminal state has not been hit and the counter hasn't expired, take the best action for the current state
        while not self.workingObservation.isTerminal and count < self.numSteps:
            newAction = Action()
            # Get the best action for this state
            newAction.actionValue = self.greedy(self.workingObservation)

            if self.verbose == True:
                print self.gridEnvironment.actionToString(
                    newAction.actionValue)

            # execute the step and get a new observation and reward
            currentObs, reward = self.gridEnvironment.env_step(newAction)
            # update the value table
            if self.calculateFlatState(
                    currentObs.worldState) not in self.v_table.keys():
                self.v_table[self.calculateFlatState(
                    currentObs.worldState)] = self.numActions * [0.0]
            self.totalReward = self.totalReward + reward.rewardValue
            self.workingObservation = copy.deepcopy(currentObs)

            # increment counter
            count = count + 1

        if self.verbose:
            print("END")
예제 #14
0
def test_creature_create():
    attributes = {}
    senses = {}
    action_set = []

    #Create Attributes
    attributes.__setitem__('STR', 16)
    attributes.__setitem__('DEX', 15)
    attributes.__setitem__('CON', 18)
    attributes.__setitem__('INT', 22)
    attributes.__setitem__('WIS', 17)
    attributes.__setitem__('CHA', 13)

    #Create Senses
    senses.__setitem__('DarkVision', 'DarkVision 60ft.')
    senses.__setitem__('TremorSense', '')
    senses.__setitem__('BlindSense', '')

    myAction = Action.Action('Test_Action', 'Melee 5ft slash', '+5 to hit', '2d12 + 3 damage')
    action_set.append(myAction)

    #created_creature = Creat       (name, size, specification, alignment, ac, hp, speed, attributes, senses,
    #                                languages, challenge_rating, action_set)
    myCreature = Creature.Creature('Test', 'Small', 'Dragon', 'LG', 16, '100', '35 ft.', attributes, senses,
                                   'Draconic Common', '4', action_set)
    myCreature.save(True)
    def add(self, action,actionRecover=None,args=(),kwargs={},die=True,stdOutput=False,errorOutput=True,retry=0,serviceObj=None,\
            deps=None,executeNow=True,selfGeneratorCode="",force=True,showout=None,actionshow=True,dynamicArguments={}):
        '''
        self.doc is in doc string of method
        specify recover actions in the description

        name is name of method

        @param name if you want to overrule the name

        @param id is unique id which allows finding back of action
        @param loglevel: Message level
        @param action: python function to execute
        @param actionRecover: link to other action (same as this object but will be used to recover the situation)
        @param args is dict with arguments
        @param serviceObj: service, will be used to get category filled in e.g. selfGeneratorCode='selfobj=None'
            needs to be done selfobj=....  ... is whatever code which fill filling selfobj
            BE VERY CAREFUL TO USE THIS, DO NEVER USE IN GEVENT OR ANY OTHER ASYNC FRAMEWORK

        @param dynamicArguments are arguments which will be executed before calling the method e.g. 
           dargs={}
           dargs["service"]="j.atyourservice.getService(\"%s\")"%kwargs["service"]
        '''

        # from pudb import set_trace; set_trace()

        if showout==True:
            stdOutput=True
        if showout==False:
            stdOutput=False

        l=traceback.format_stack()
        tbline=l[-2].split("\n")[0].replace("'","")
        fpath,linenr,remaining=tbline.split(",",2)
        fpath=fpath.split("\"")[1].strip()
        linenr=int(linenr.split(" ")[-1])

        if j.data.types.dict.check(args):
            raise j.exceptions.RuntimeError("cannot create action: args should be a list, kwargs a dict, input error")

        action=Action(action,runid=self.runid,actionRecover=actionRecover,args=args,kwargs=kwargs,die=die,stdOutput=stdOutput,errorOutput=errorOutput,\
            retry=retry,serviceObj=serviceObj,deps=deps,selfGeneratorCode=selfGeneratorCode,force=force,actionshow=actionshow,dynamicArguments=dynamicArguments)

        action.calling_linenr=linenr
        action.calling_path=fpath


        while len(self.lastOnes)>100:
            self.lastOnes.pop()
        self.lastOnes.append(action)

        self._actions[action.key]=action
        self.last=action
        if executeNow:
            # print ("ACTION ADD:%s"%action.key)
            action.execute()
        else:
            action.save(True)
        return action
예제 #16
0
 def fadeOut(duration):
     def run(target, deltaTime, totalTime):
         # print( target.opacity )
         target.opacity = 1 - totalTime/duration
         if (target.opacity < 0):
             target.opacity = 0
         return (totalTime >= duration)
     return Action(run)
예제 #17
0
 def destroyOutsideScreen(screenWidth, screenHeight):
     def run(target, deltaTime, totalTime):
         if not target.isOnScreen(screenWidth, screenHeight):
             target.remove()
             return True
         else:
             return False
     return Action(run)
예제 #18
0
    def pre_renommage(self):
        """
        Au début un peu de débug


        :return:
        """
        #DEBUG SI JAMAIS QUELQU'UN MET DANS LE APARTIRDE
        if self.var_texte_amorce.get() == "Lettre":

            verif = self.var_texte_apartirde.get()
            h = []

            for c in verif:
                h.append(ord(c))

                for i in h:
                    if i >= 91 or i < 65:
                        self.message_erreur()
                        pass

        if self.var_texte_amorce.get() == "Chiffre":

            verif = self.var_texte_apartirde.get()
            h = []

            for c in verif:
                h.append(ord(c))

                for i in h:
                    if i >= 57 or i < 48:
                        self.message_erreur()
                        pass

        #Trie de la variable "nomfichier"
        if self.var_texte_nomfichier.get() == ("2"):
            self.nomfichier = self.var_texte_entrynom.get()
        else:
            self.nomfichier = "Original"

        #La règle contient : 'AMORCE' ; 'APARTIRDE' ; 'PREFIXE' ; ' NOMFICHIER' ; 'POSTFIXE' ; 'EXTENSION'
        regle = []
        regle.append(self.var_texte_amorce.get())
        regle.append(self.var_texte_apartirde.get())
        regle.append(self.var_texte_prefixe.get())
        regle.append(self.nomfichier)
        regle.append(self.var_texte_suffixe.get())
        regle.append(self.var_texte_extension.get())

        Action.regle = regle

        original, final = Action(Action.nomdurepertoire, Action.regle).simule()

        r = Renommage(Action.nomdurepertoire, Action.regle)
        r.original = original
        r.modifie = final
        r.renommer()
예제 #19
0
파일: Listener.py 프로젝트: festutz/lemma9
 def exitAction(self, ctx):
     self.variables_pattern = set()
     limit = self.state.pop()[1]
     if not limit.is_proc():
         raise Exception(
             'Attempt to have a definition with a limit instead of a process'
         )
     inputprefix = self.state.pop()
     self.state.append(Action(inputprefix, limit))
예제 #20
0
 def forever(action):
     foreverAction = Action()
     def apply(target, deltaTime):
         finished = action.apply(target, deltaTime)
         if (finished):
             action.reset()
         return False
     foreverAction.apply = apply
     return foreverAction
예제 #21
0
    def create_pawns(self):
        pawns = []
        x1 = 1
        x2 = 1
        for y in range((self.board_size // 2)-1):
            for x in range(self.board_size):
                if not x % 2 == 0:
                    checker = Checkers_Pawn.CheckersPawn(x-x1, y, "red")
                    self.place(Action.Action(x-x1, y, checker))
                    pawns.append(checker)

            for x in range(self.board_size):
                if x % 2 == 0:
                    checker = Checkers_Pawn.CheckersPawn(x+x2, self.board_size - y - 1, "black")
                    self.place(Action.Action(x+x2, self.board_size - y - 1, checker))
                    pawns.append(checker)
            x1 = 1 if x1 == 0 else 0
            x2 = 1 if x2 == 0 else 0
        return pawns
예제 #22
0
 def setUp(self):  # appelée à chaque exécution d'une function test_
     '''
          Function appelée au début d'un  d'un test
     '''
     # print('test started')
     self.myRule1 = Regle()
     self.myRule2 = Regle(amorce='chiffre',
                          nomFichier='nomFichierModifé',
                          extensions=[])
     self.myRule3 = Regle(amorce='lettre',
                          apartirde='abc',
                          prefixe='-prefixe-',
                          postfixe='--sufixe--',
                          nomFichier=True,
                          extensions=['.txt, .png'])
     self.myAction1 = Action('./tests', self.myRule1)
     self.myAction3 = Action('./tests', self.myRule3)
     self.myRenommage1 = Renommage('./tests', self.myRule1)
     self.testFile = 'test_bkp'
     self.myList = ListeRegles(self.testFile)
예제 #23
0
 def repeat(action, totalTimes):
     finishedTimes = 0
     repeatAction = Action()
     def apply(target, deltaTime):
         finished = action.apply(target, deltaTime)
         if (finished):
             finishedTimes += 1
             action.reset()
         return (finishedTimes == totalTimes)
     repeatAction.apply = apply
     return repeatAction
예제 #24
0
 def possible_moves(self, player):
     actions = []
     board = self.get_board()
     x, y = 0, 0
     for pos in board:
         y = 0
         for value in pos:
             if not value:
                 actions.append(Action.Action(x, y, player))
             y += 1
         x += 1
     return actions
예제 #25
0
 def parseCommand(self,command):
     command = command.split(" ")
     print(command)
     checkInput = TaskManager.checkUserInput(self,command)
     if checkInput is True :
         commandSize = len(command)
         commandAction = ""
         if(command[0] == "+") :
             for i in range(1,commandSize) :
                 if i != 1 :
                     commandAction = commandAction + " " + command[i]
                 else:
                     commandAction = command[i]
             return Action.Action("add",commandAction)
         elif (command[0] == "-"):
             return Action.Action("del", command[1])
         elif (command[0] == "x"):
             return Action.Action("done", command[1])
         elif (command[0] == "o"):
             return Action.Action("toDo", command[1])
     else:
         return False
예제 #26
0
    def addAction(self, actionName):

        actionElements = self.actionsXmlFile.getElementsByTagName("action")
        # Get them
        actionName = actionName.replace('_', ' ')
        found = filter(lambda w: w.getAttribute("name") == actionName,
                       actionElements)
        if len(found):
            self.actions += [Action.Action(found[0])]
        else:
            self.logManager.error("No action called " + actionName +
                                  " was found for " + self.getName() + " in " +
                                  self.actionsLocation + ".")
예제 #27
0
    def __init__(self, sx_sy):

        sx = sx_sy[0]
        sy = sx_sy[1]
        print('init solomon {0},{1}'.format(sx, sy))

        self.solx = sx * self.tile
        self.soly = sy * self.tile

        ##self.startx=sx
        ##self.starty=sy

        self.AG_walk = ActionGroup()
        self.AG_walk.append(
            "wobble",
            Action(func=self.wobble,
                   max=5,
                   cycle=True,
                   min=-5,
                   reverseloop=True,
                   init_tick=0))
        self.AG_walk.append(
            "footR", Action(func=self.footR, max=13, cycle=True, min=-1))
        self.AG_walk.append(
            "footL",
            Action(func=self.footL, max=13, cycle=True, min=-1, init_tick=7))

        ##self.AG_jump=ActionGroup()
        ##self.AG_jump.append("jump_displacement",Action(func=self.jump_displacement,max=10,min=0))
        ##self.AG_jump.action("jump_displacement").callback=self.end_jump

        self.AG_walk.speed_scale(2)

        self.A_wandswish = Action(func=self.swish,
                                  min=-8,
                                  max=-1,
                                  cycle=False,
                                  reverseloop=False,
                                  init_tick=-6)
예제 #28
0
    def getActions(self, state):
        actions = []
        wrigglers = state.wrigglers

        self.clearMaze()
        self.updateAllMaze(state.wrigglers)

        for i in range(len(wrigglers)):
            moves = wrigglers[i].getPossibleMoves()

            for move in moves:
                actions.append(Action(wrigglerID=i, movedCoord=move[0], headMoved=move[1]))

        return actions
예제 #29
0
 def train_parser_from_utterance_action_pairs(self,
                                              pairs,
                                              epochs=10,
                                              parse_beam=10):
     for e in range(0, epochs):
         print "training epoch " + str(e)
         random.shuffle(pairs)
         train_data = []
         num_correct = 0
         for t, r, a in pairs:
             n_best_parses = self.parser.parse_tokens(t, n=parse_beam)
             if len(n_best_parses) == 0:
                 print "WARNING: no parses found for tokens " + str(t)
                 continue
             a_chosen = None
             a_candidate = None
             correct_found = False
             for i in range(0, len(n_best_parses)):
                 try:
                     # print "parse: " + self.parser.print_parse(n_best_parses[i][0])  # DEBUG
                     # print self.parser.print_semantic_parse_result(n_best_parses[i][1])  # DEBUG
                     a_candidate = self.get_action_from_parse(
                         n_best_parses[i][0].node)
                     # print "candidate: "+str(a_candidate)  # DEBUG
                 except SystemError:
                     a_candidate = Action.Action()
                 if i == 0:
                     a_chosen = a_candidate
                 if a_candidate.__eq__(a):
                     correct_found = True
                     self.parser.add_genlex_entries_to_lexicon_from_partial(
                         n_best_parses[i][1])
                     break  # the action matches gold and this parse should be used in training
             if not correct_found:
                 print "WARNING: could not find correct action '" + str(
                     a) + "' for tokens " + str(t)
             if a_chosen != a_candidate:
                 train_data.append([
                     t, n_best_parses[0], a_chosen, t, n_best_parses[i], a
                 ])
             else:
                 num_correct += 1
         print "\t" + str(num_correct) + "/" + str(
             len(pairs)) + " top choices"
         if num_correct == len(pairs):
             print "WARNING: training converged at epoch " + str(
                 e) + "/" + str(epochs)
             return True
         self.parser.learner.learn_from_actions(train_data)
     return False
예제 #30
0
    def choose_action(self, opponent):
        if len(self.opponent_moves) + 1 <= self.memory:
            hold = random.randint(0, 2)
            return Action(hold)
        else:
            sequence = self.opponent_moves[-self.memory:]
            for i in range(0, len(self.opponent_moves) - self.memory):
                if sequence == self.opponent_moves[i:i + self.memory]:
                    self.next_move.append(self.opponent_moves[i + self.memory])

            if self.next_move == []:
                hold = random.randint(0, 2)
                return Action(hold)

            else:
                action = str(max(self.next_move, key=self.next_move.count))
                self.next_move = []
                if action == "scissor":
                    return Action(2)
                elif action == "rock":
                    return Action(1)
                else:
                    return Action(0)