Generate First Round Fights.
431003
protected function generateFights()
    {
        //  First Round Fights
        $settings = $this->settings;
        $initialRound = 1;
        // Very specific case to common case : Preliminary with 3 fighters
        if ($this->championship->hasPreliminary() && $settings->preliminaryGroupSize == 3) {
            // First we make all first fights of all groups
            // Then we make all second fights of all groups
            // Then we make all third fights of all groups
            $groups = $this->championship->groupsByRound(1)->get();
            foreach ($groups as $numGroup => $group) {
                for ($numFight = 1; $numFight <= $settings->preliminaryGroupSize; $numFight++) {
                    $fight = new PreliminaryFight();
                    $order = $numGroup * $settings->preliminaryGroupSize + $numFight;
                    $fight->saveFight2($group, $numFight, $order);
                }
            }
            $initialRound++;
        }
        // Save Next rounds
        $fight = new SingleEliminationFight();
        $fight->saveFights($this->championship, $initialRound);
    }
991328
static FightResult getFightResult(Element element) {
        if (element.select(".win").size() > 0) {
            return FightResult.FIGHTER_1_WIN;
        } else if (element.select(".loss").size() > 0) {
            return FightResult.FIGHTER_2_WIN;
        } else if (element.select(".draw").size() > 0) {
            return FightResult.DRAW;
        } else if (element.select(".no_contest").size() > 0) {
            return FightResult.NO_CONTEST;
        } else {
            return FightResult.NOT_HAPPENED;
        }
    }
826975
def prepare(cls, options, round_manager):
    """"""
    super(NodeResolve, cls).prepare(options, round_manager)
    for resolver in cls._resolver_by_type.values():
      resolver.prepare(options, round_manager)
939806
protected function pushGroups($numRounds, $numFighters)
    {
        // TODO Here is where you should change when enable several winners for preliminary
        for ($roundNumber = 2; $roundNumber <= $numRounds + 1; $roundNumber++) {
            // From last match to first match
            $maxMatches = ($numFighters / pow(2, $roundNumber));

            for ($matchNumber = 1; $matchNumber <= $maxMatches; $matchNumber++) {
                $fighters = $this->createByeGroup(2);
                $group = $this->saveGroup($matchNumber, $roundNumber, null);
                $this->syncGroup($group, $fighters);
            }
        }
        // Third place Group
        if ($numFighters >= $this->championship->getGroupSize() * 2) {
            $fighters = $this->createByeGroup(2);

            $group = $this->saveGroup($maxMatches, $numRounds, null);

            $this->syncGroup($group, $fighters);
        }
    }
549000
def generate(number=4, choice=SystemRandom().choice, words=words, joiner=" "):
    
    return joiner.join(choice(words) for each in range(number))
1163301
function generateActions({ generate, ...actions }) {
  return !generate
    ? actions
    : Object.assign(
        generate.reduce((obj, name) => {
          obj[name] = forwardValue;
          return obj;
        }, {}),
        actions
      );
}
1028795
private function generateAllRules(): void
    {
        for ($k = 2; isset($this->large[$k]); ++$k) {
            foreach ($this->large[$k] as $frequent) {
                $this->generateRules($frequent);
            }
        }
    }
902513
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    if self.ord != np.inf:
      raise NotImplementedError(self.ord)
    eta = tf.random_uniform(tf.shape(x), -self.eps, self.eps,
                            dtype=self.tf_dtype)
    adv_x = x + eta
    if self.clip_min is not None or self.clip_max is not None:
      assert self.clip_min is not None and self.clip_max is not None
      adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

    return adv_x
912501
protected function generateFirstMask() {
    $this->mask = array_fill(0, $this->length, 0);
    for ($i = 0; $i < $this->positivesAmount; $i++) {
      $this->mask[$this->length - $i - 1] = 1;
    }
  }
523376
def genslices(n):
    """"""
    def range_with_none():
        yield None
        yield from range(-n, n+1)

    for t in product(range_with_none(), range_with_none(), range_with_none()):
        s = slice(*t)
        if s.step != 0:
            yield s
60524
def mid_generate(self):
        """"""
        self.last_mid += 1
        if self.last_mid == 0:
            self.last_mid += 1
        return self.last_mid
967344
def _random_starts(fun,
                   parameters,
                   jac,
                   args,
                   nstarts,
                   random_state,
                   data_gen=None):
    """"""
    if nstarts < 1:
        raise ValueError("nstarts has to be greater than or equal to 1")

    # Check to see if there are any random parameter types
    anyrand = any(flatten(map_recursive(lambda p: p.is_random, parameters),
                  returns_shapes=False))

    if not anyrand:
        log.info("No random parameters, not doing any random starts")
        params = map_recursive(lambda p: p.value, parameters, output_type=list)
        return params

    log.info("Evaluating random starts...")

    # Deal with gradient returns from objective function
    if jac is True:
        call_fun = lambda *fargs: fun(*fargs)[0]
    else:  # No gradient returns or jac is callable
        call_fun = fun

    # Randomly draw parameters and evaluate function
    def fun_eval():
        batch = next(data_gen) if data_gen else ()
        params = map_recursive(lambda p: p.rvs(random_state), parameters,
                               output_type=list)
        obj = call_fun(*chain(params, batch, args))
        return obj, params

    # Test randomly drawn parameters
    sample_gen = (fun_eval() for _ in range(nstarts))
    obj, params = min(sample_gen, key=lambda t: t[0])

    log.info("Best start found with objective = {}".format(obj))

    return flatten(params, returns_shapes=False)
205147
async def selfplay(state, flagfile='selfplay'):
  

  output_dir = os.path.join(fsdb.selfplay_dir(), state.output_model_name)
  holdout_dir = os.path.join(fsdb.holdout_dir(), state.output_model_name)

  lines = await run(
      'bazel-bin/cc/selfplay',
      '--flagfile={}.flags'.format(os.path.join(FLAGS.flags_dir, flagfile)),
      '--model={}'.format(state.best_model_path),
      '--output_dir={}'.format(output_dir),
      '--holdout_dir={}'.format(holdout_dir),
      '--seed={}'.format(state.seed))
  result = '\n'.join(lines[-6:])
  logging.info(result)
  stats = parse_win_stats_table(result, 1)[0]
  num_games = stats.total_wins
  logging.info('Black won %0.3f, white won %0.3f',
               stats.black_wins.total / num_games,
               stats.white_wins.total / num_games)

  # Write examples to a single record.
  pattern = os.path.join(output_dir, '*', '*.zz')
  random.seed(state.seed)
  tf.set_random_seed(state.seed)
  np.random.seed(state.seed)
  # TODO(tommadams): This method of generating one golden chunk per generation
  # is sub-optimal because each chunk gets reused multiple times for training,
  # introducing bias. Instead, a fresh dataset should be uniformly sampled out
  # of *all* games in the training window before the start of each training run.
  buffer = example_buffer.ExampleBuffer(sampling_frac=1.0)

  # TODO(tommadams): parallel_fill is currently non-deterministic. Make it not
  # so.
  logging.info('Writing golden chunk from "{}"'.format(pattern))
  buffer.parallel_fill(tf.gfile.Glob(pattern))
  buffer.flush(os.path.join(fsdb.golden_chunk_dir(),
                            state.output_model_name + '.tfrecord.zz'))
1127164
async function initiateGame(team1, team2, pitchDetails) {
  validate.validateArguments(team1, team2, pitchDetails)
  validate.validateTeam(team1)
  validate.validateTeam(team2)
  validate.validatePitch(pitchDetails)
  let matchDetails = setVariables.populateMatchDetails(team1, team2, pitchDetails)
  let kickOffTeam = setVariables.setGameVariables(matchDetails.kickOffTeam)
  let secondTeam = setVariables.setGameVariables(matchDetails.secondTeam)
  kickOffTeam = setVariables.koDecider(kickOffTeam, matchDetails)
  matchDetails.iterationLog.push(`Team to kick off - ${kickOffTeam.name}`)
  matchDetails.iterationLog.push(`Second team - ${secondTeam.name}`)
  secondTeam = setPositions.switchSide(secondTeam, matchDetails)
  matchDetails.kickOffTeam = kickOffTeam
  matchDetails.secondTeam = secondTeam
  return matchDetails
}
344666
def main():
    """"""

    # test example below taken from GMMRA by Azari, Chen, Parkes, & Xia
    cand_set = [0, 1, 2]
    votes = [[0, 1, 2], [1, 2, 0]]

    mmagg = MMPLAggregator(cand_set)
    gamma = mmagg.aggregate(votes, epsilon=1e-7, max_iters=20)
    print(mmagg.alts_to_ranks, mmagg.ranks_to_alts)
    assert([mmagg.get_ranking(i) for i in cand_set] == [1,0,2])
    print(gamma)
952022
def prepare_defenses(self):
    """"""
    print_header('PREPARING DEFENSE DATA')
    # verify that defense data not written yet
    if not self.ask_when_work_is_populated(self.defense_work):
      return
    self.defense_work = eval_lib.DefenseWorkPieces(
        datastore_client=self.datastore_client)
    # load results of attacks
    self.submissions.init_from_datastore()
    self.dataset_batches.init_from_datastore()
    self.adv_batches.init_from_datastore()
    self.attack_work.read_all_from_datastore()
    # populate classification results
    print_header('Initializing classification batches')
    self.class_batches.init_from_adversarial_batches_write_to_datastore(
        self.submissions, self.adv_batches)
    if self.verbose:
      print(self.class_batches)
    # populate work pieces
    print_header('Preparing defense work pieces')
    self.defense_work.init_from_class_batches(
        self.class_batches.data, num_shards=self.num_defense_shards)
    self.defense_work.write_all_to_datastore()
    if self.verbose:
      print(self.defense_work)
1194807
def generate(self, x, g, **kwargs):
    

    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    g_feat = self.model.fprop(g)[self.layer]

    # Initialize loop variables
    eta = tf.random_uniform(
        tf.shape(x), -self.eps, self.eps, dtype=self.tf_dtype)
    eta = clip_eta(eta, self.ord, self.eps)

    def cond(i, _):
      return tf.less(i, self.nb_iter)

    def body(i, e):
      new_eta = self.attack_single_step(x, e, g_feat)
      return i + 1, new_eta

    _, eta = tf.while_loop(cond, body, (tf.zeros([]), eta), back_prop=True,
                           maximum_iterations=self.nb_iter)

    # Define adversarial example (and clip if necessary)
    adv_x = x + eta
    if self.clip_min is not None and self.clip_max is not None:
      adv_x = tf.clip_by_value(adv_x, self.clip_min, self.clip_max)

    return adv_x