runs a series of fights
420312
def fight(self, moves=10):
        
        for i in range(1, moves):
            # player 1
            result, dmg = self.calc_move(self.c1, self.c2)
            print (self.c1.name + ' ' + result + ' for ' + str(dmg))
            self.c1.sta = self.c1.sta - dmg
            if self.is_character_dead(self.c1):
                print(self.c1.name + ' has died')
                return
            # player 2
            result, dmg = self.calc_move(self.c2, self.c1)
            print (self.c2.name + ' ' + result + ' for ' + str(dmg))
            self.c2.sta = self.c2.sta - dmg
            if self.is_character_dead(self.c2):
                print(self.c2.name + ' has died')
                return
855582
public void runPendingCommands() {
        List<Runnable> commandsToRun = commands;
        commands = new ArrayList<Runnable>();
    
        for (Runnable command: commandsToRun) {
            command.run();
        }
    }
1148947
def run(self):
        
        for cellindex in self.RANK_CELLINDICES:
            self.cellsim(cellindex)

        COMM.Barrier()
1120456
def pawns_at(self, x, y):
        """"""
        for pawn in self.pawn.values():
            if pawn.collide_point(x, y):
                yield pawn
150442
public function adjustFightersGroupWithByes($fighters, $fighterGroups): Collection
    {
        $tmpFighterGroups = clone $fighterGroups;
        $numBye = count($this->getByeGroup($fighters));

        // Get biggest competitor's group
        $max = $this->getMaxFightersByEntity($tmpFighterGroups);

        // We put them so that we can mix them up and they don't fight with another competitor of his entity.
        $fighters = $this->repart($fighterGroups, $max);

        if (!app()->runningUnitTests()) {
            $fighters = $fighters->shuffle();
        }
        // Insert byes to fill the tree.
        // Strategy: first, one group full, one group empty with byes, then groups of 2 fighters
        $fighters = $this->insertByes($fighters, $numBye);
        return $fighters;
    }
125873
function run() {
		$fw=\Base::instance();
		// Assign signal handlers
		declare(ticks=1);
		pcntl_signal(SIGINT,[$this,'kill']);
		pcntl_signal(SIGTERM,[$this,'kill']);
		gc_enable();
		// Activate WebSocket listener
		$listen=stream_socket_server(
			$this->addr,$errno,$errstr,
			STREAM_SERVER_BIND|STREAM_SERVER_LISTEN,
			$this->ctx
		);
		$socket=socket_import_stream($listen);
		register_shutdown_function(function() use($listen) {
			foreach ($this->sockets as $socket)
				if ($socket!=$listen)
					$this->close($socket);
			$this->close($listen);
			if (isset($this->events['stop']) &&
				is_callable($func=$this->events['stop']))
				$func($this);
		});
		if ($errstr)
			user_error($errstr,E_USER_ERROR);
		if (isset($this->events['start']) &&
			is_callable($func=$this->events['start']))
			$func($this);
		$this->sockets=[(int)$listen=>$listen];
		$empty=[];
		$wait=$this->wait;
		while (TRUE) {
			$active=$this->sockets;
			$mark=microtime(TRUE);
			$count=@stream_select(
				$active,$empty,$empty,(int)$wait,round(1e6*($wait-(int)$wait))
			);
			if (is_bool($count) && $wait) {
				if (isset($this->events['error']) &&
					is_callable($func=$this->events['error']))
					$func($this);
				die;
			}
			if ($count) {
				// Process active connections
				foreach ($active as $socket) {
					if (!is_resource($socket))
						continue;
					if ($socket==$listen) {
						if ($socket=@stream_socket_accept($listen,0))
							$this->alloc($socket);
						else
						if (isset($this->events['error']) &&
							is_callable($func=$this->events['error']))
							$func($this);
					}
					else {
						$id=(int)$socket;
						if (isset($this->agents[$id]))
							$this->agents[$id]->fetch();
					}
				}
				$wait-=microtime(TRUE)-$mark;
				while ($wait<1e-6) {
					$wait+=$this->wait;
					$count=0;
				}
			}
			if (!$count) {
				$mark=microtime(TRUE);
				foreach ($this->sockets as $id=>$socket) {
					if (!is_resource($socket))
						continue;
					if ($socket!=$listen &&
						isset($this->agents[$id]) &&
						isset($this->events['idle']) &&
						is_callable($func=$this->events['idle']))
						$func($this->agents[$id]);
				}
				$wait=$this->wait-microtime(TRUE)+$mark;
			}
			gc_collect_cycles();
		}
	}
243553
protected function destroyPreviousFights()
    {
        // Delete previous fight for this championship
        $arrGroupsId = $this->championship->fightersGroups()->get()->pluck('id');
        if (count($arrGroupsId) > 0) {
            Fight::destroy($arrGroupsId);
        }
    }
1327963
def _runner(self, classpath, main, jvm_options, args, cwd=None):
    """"""
    command = self._create_command(classpath, main, jvm_options, args)

    class Runner(self.Runner):
      @property
      def executor(this):
        return self

      @property
      def command(self):
        return list(command)

      def run(this, stdout=None, stderr=None, stdin=None, cwd=None):
        nailgun = None
        try:
          nailgun = self._get_nailgun_client(jvm_options, classpath, stdout, stderr, stdin)
          logger.debug('Executing via {ng_desc}: {cmd}'.format(ng_desc=nailgun, cmd=this.cmd))
          return nailgun.execute(main, cwd, *args)
        except (NailgunClient.NailgunError, self.InitialNailgunConnectTimedOut) as e:
          self.terminate()
          raise self.Error('Problem launching via {ng_desc} command {main} {args}: {msg}'
                           .format(ng_desc=nailgun or '<no nailgun connection>',
                                   main=main,
                                   args=' '.join(args),
                                   msg=e))

    return Runner()
939465
def run(self, num_runs, show_trails, log_file_base):
        
        print("--------------------------------------------------")
        print("Starting Simulation - target = ", self.agent_list[0].target_y, self.agent_list[0].target_x)
        self.world.grd.set_tile(self.agent_list[0].target_y , self.agent_list[0].target_x , 'T')
        self.highlight_cell_surroundings(self.agent_list[0].target_y, self.agent_list[0].target_x)
        self.start_all_agents()
        # save the agents results here
        try:
            with open (log_file_base + '__agents.txt', "w") as f:
                f.write("Starting World = \n")
                f.write(str(self.world.grd))
        except Exception:
            print('Cant save log results to ' + log_file_base)
            
        for cur_run in range(0,num_runs):
            print("WorldSimulation:run#", cur_run)
            for num, agt in enumerate(self.agent_list):
                if show_trails == 'Y':
                    if len(self.agent_list) == 1 or len(self.agent_list) > 9:
                        self.world.grd.set_tile(agt.current_y, agt.current_x, 'o')
                    else:
                        self.world.grd.set_tile(agt.current_y, agt.current_x, str(num))
                agt.do_your_job()
                self.world.grd.set_tile(agt.current_y, agt.current_x, 'A')    # update the main world grid with agents changes
            
            # save grid after each run if required
            if log_file_base != 'N':
                self.world.grd.save(log_file_base + '_' + str(cur_run) + '.log')
    
        # save the agents results here
        with open (log_file_base + '__agents.txt', "a") as f:
            f.write("\nWorld tgt= [" + str(self.agent_list[0].target_y) + "," + str(self.agent_list[0].target_x) + "]\n")
            f.write(str(self.world.grd))
            f.write('\n\nAgent Name , starting, num Steps , num Climbs\n')
            for num, agt in enumerate(self.agent_list):
                res = agt.name + ' , [' + str(agt.start_y) + ', ' + str(agt.start_x) + '], '
                res += str(agt.num_steps)  + ' , ' + str(agt.num_climbs) + ' , '
                res += ''.join([a for a in agt.results])
                f.write(res + '\n')
1261193
def _run(self, strategy, parameters=None):
        '''
        
        '''

        choice = self.run_strategy(strategy, parameters)
        self.choices.append(choice)
        payout = self.bandits.pull(choice)
        if payout is None:
            print('Trials exhausted. No more values for bandit', choice)
            return None
        else:
            self.wins[choice] += payout
        self.pulls[choice] += 1
397360
function() {
      if(this.hasInteractions) {
         for(var i = 0 ; i < this.inputs.length ; i++) {
            this.runInteractions(this.inputs[i],this.inputs[i].getValue());
         }
      }
   }
1008072
protected function generateAllTrees()
    {
        $this->minFightersCheck(); // Check there is enough fighters to generate trees
        $usersByArea = $this->getFightersByArea(); // Get fighters by area (reparted by entities and filled with byes)
        $this->generateGroupsForRound($usersByArea, 1); // Generate all groups for round 1
        $numFighters = count($usersByArea->collapse());
        $this->pushEmptyGroupsToTree($numFighters); // Fill tree with empty groups
        $this->addParentToChildren($numFighters); // Build the entire tree and fill the next rounds if possible
    }
381330
def run(self, once=False):
        """"""
        self._once = once
        self.start()
        while self.running:
            try:
                time.sleep(1.0)
            except KeyboardInterrupt:
                self.stop()
                self.join()
1044636
function runGame() {
    var totalReward = 0;
    var environment = new exampleWorld.Environment();
    var lastReward = null;

    function tick() {
        //Tell the agent about the current environment state and have it choose an action to take
        var action = sarsaAgent.decide(lastReward, environment.getCurrentState());

        //Tell the environment the agent's action and have it calculate a reward
        lastReward = environment.takeAction(action);

        //Log the total reward
        totalReward += lastReward;
    }

    for (var i = 0; i < 100; i++) {
        tick();
    }

    return totalReward;
}
1300974
function (size, p, last, isLong) {
  var matches = [];
  // first WB round to initialize players
  for (var i = 1; i <= Math.pow(2, p - 1); i += 1) {
    matches.push({ id: gId(WB, 1, i), p: woMark(seeds(i, p), size) });
  }

 // blank WB rounds
  var r, g;
  for (r = 2; r <= p; r += 1) {
    for (g = 1; g <= Math.pow(2, p - r); g += 1) {
      matches.push({id: gId(WB, r, g), p: blank() });
    }
  }

  // blank LB rounds
  if (last >= LB) {
    for (r = 1; r <= 2*p - 2; r += 1) {
      // number of matches halves every odd round in losers bracket
      for (g = 1; g <= Math.pow(2, p - 1 - Math.floor((r + 1) / 2)); g += 1) {
        matches.push({ id: gId(LB, r, g), p: blank() });
      }
    }
    matches.push({ id: gId(LB, 2*p - 1, 1), p: blank() }); // grand final match 1
  }
  if (isLong) {
    // bronze final if last === WB, else grand final match 2
    matches.push({ id: gId(LB, last === LB ? 2*p : 1, 1), p: blank() });
  }
  return matches.sort(Base.compareMatches); // sort so they can be scored in order
}
222894
def run_simulation(self):
        
        for _ in range(self.num_fights):
            # restore health between each fight
            self.c1.stats['Health'] = self.c1.stats['max_health']
            self.c2.stats['Health'] = self.c2.stats['max_health']
            
            # run the Battles
            b = Battle(self.c1, self.c2, self.traits, self.rules, print_console='No')
            #print(b)
            if b.status == self.c1.name:
                self.num_c1 += 1
            else:
                self.num_c2 += 1
                
        # tag winner        
        if self.num_c1 > self.num_c2:
            self.winner = self.c1.name
        else:
            self.winner = self.c2.name
171054
def run_thread(agent_classes, players, map_name, visualize):
  """"""
  with sc2_env.SC2Env(
      map_name=map_name,
      players=players,
      agent_interface_format=sc2_env.parse_agent_interface_format(
          feature_screen=FLAGS.feature_screen_size,
          feature_minimap=FLAGS.feature_minimap_size,
          rgb_screen=FLAGS.rgb_screen_size,
          rgb_minimap=FLAGS.rgb_minimap_size,
          action_space=FLAGS.action_space,
          use_feature_units=FLAGS.use_feature_units),
      step_mul=FLAGS.step_mul,
      game_steps_per_episode=FLAGS.game_steps_per_episode,
      disable_fog=FLAGS.disable_fog,
      visualize=visualize) as env:
    env = available_actions_printer.AvailableActionsPrinter(env)
    agents = [agent_cls() for agent_cls in agent_classes]
    run_loop.run_loop(agents, env, FLAGS.max_agent_steps, FLAGS.max_episodes)
    if FLAGS.save_replay:
      env.save_replay(agent_classes[0].__name__)