Writing if GameBalance
963221
def write_game_balance
      write_single_file("analyze")

      dir = File.join("analyze", parser_name)
      dir = File.join(dir, @field.to_s) if @field
      write_analyzed(dir)
    end
94381
function getCardWeight(player, target, card, game) {
  let moves = []
  if (card.validPlays) {
    moves = card.validPlays(player, target, game)
  }
  if (card.validCounters && target.discard.length) {
    moves = card.validCounters(player, target, game)
  }
  if (card.validDisasters) {
    moves = card.validDisasters(player, game)
  }
  // Pick out the highest weight of those moves
  return moves.reduce((acc, move) => {
    return move.weight > acc ? move.weight : acc
  }, 0)
}
327829
def dice_check(self, n, d, target, comparator='<='):
        
        from operator import gt, lt, ge, le, eq, ne

        comps = {
            '>': gt,
            '<': lt,
            '>=': ge,
            '<=': le,
            '=': eq,
            '==': eq,
            '!=': ne
        }
        try:
            comparator = comps.get(comparator, comparator)
        except TypeError:
            pass
        return comparator(sum(self.dice(n, d)), target)
722328
def writeConflicts(self):
        """"""
        if not self._counters_calculated:
            self._counters_calculated = True
            self._extract_counters()

        return self._writeConflicts
1077789
function(){
            // Compute team Wins, Losts, Draws and Goal-Sum
            /*
                // Uses the key as the teamId
                {
                         1: {P: x, S: y, [...]},
                    teamId: {P: x, S: y, [...]}
                 }
            */
            var rawTable = {};
            var _default = {rank: 0, teamId: 0, P: 0, goalsMade: 0, goalsTaken: 0, S: 0, W: 0, D: 0, L: 0, score: 0};

            for(var k in this.matches){
                var match = this.matches[k];

                // Compute game points for both teams
                computeGame(match, match.teamAId, match.teamAScore, match.teamBScore);
                computeGame(match, match.teamBId, match.teamBScore, match.teamAScore);
            }

            // Adds game to the teamId. Should be runned twice for each
            // side of match (teamA and teamB).
            function computeGame(match, teamId, goalsMade, goalsTaken){
                // Skip empty id's
                if(!teamId)
                    return;

                // Generate default template if NOT in array yet
                if(!rawTable[teamId]){
                    var teamRow = _.clone(_default);
                    // Keeps team id under team
                    teamRow.teamId = teamId;
                    // Inserts team in rawTable
                    rawTable[teamId] = teamRow;
                }

                // Get teamRow (it is supposed to exist)
                var teamRow = rawTable[teamId];

                // Compute points ONLY if match is not 'scheduled'
                // logycaly, it's 'ended' or 'playing', so we compute it
                if(match.state == 'scheduled')
                    return;

                // Increment Plays
                teamRow.P++;

                // Compute goals made/taken
                teamRow.goalsMade += goalsMade*1;
                teamRow.goalsTaken += goalsTaken*1;

                // Win
                if(goalsMade > goalsTaken)
                    teamRow.W ++;
                // Loose
                else if(goalsMade < goalsTaken)
                    teamRow.L ++;
                // Drew
                else
                    teamRow.D ++;
            }

            // Compute 'final score' and add column S (goalsMade:goalsTaken)
            // Transfer data to final table array
            var finalTable = [];
            _.forEach(rawTable, function(row){
                row.score = row.W*3 + row.D*1;
                row.S = row.goalsMade*1 + ':' + row.goalsTaken*1;
                row.GD = row.goalsMade*1 - row.goalsTaken*1;

                finalTable.push(row);
            });

            // Sort by 'score' field
            finalTable = _.sortBy(finalTable, 'score').reverse();

            // Rank Table
            var pos = 0;
            var lastScore = -1;

            _.forEach(finalTable, function(row){
                // Keeps the same ranking if scores is the same
                if(lastScore != row.score){
                    pos++;
                    lastScore = row.score;
                }

                row.rank = pos;
            });


            return finalTable;


        }
958424
def compare_balance(self, operator, or_equals, amount):
        """"""
        amount = int(amount)
        if operator == 'less':
            if or_equals:
                self.assertLessEqual(self.balance, amount)
            else:
                self.assertLess(self.balance, amount)
        elif or_equals:
            self.assertGreaterEqual(self.balance, amount)
        else:
            self.assertGreater(self.balance, amount)
612639
def run_game(load_file, selfplay_dir=None, holdout_dir=None,
             sgf_dir=None, holdout_pct=0.05):
    """"""
    if sgf_dir is not None:
        minimal_sgf_dir = os.path.join(sgf_dir, 'clean')
        full_sgf_dir = os.path.join(sgf_dir, 'full')
        utils.ensure_dir_exists(minimal_sgf_dir)
        utils.ensure_dir_exists(full_sgf_dir)
    if selfplay_dir is not None:
        utils.ensure_dir_exists(selfplay_dir)
        utils.ensure_dir_exists(holdout_dir)

    with utils.logged_timer("Loading weights from %s ... " % load_file):
        network = dual_net.DualNetwork(load_file)

    with utils.logged_timer("Playing game"):
        player = play(network)

    output_name = '{}-{}'.format(int(time.time()), socket.gethostname())
    game_data = player.extract_data()
    if sgf_dir is not None:
        with gfile.GFile(os.path.join(minimal_sgf_dir, '{}.sgf'.format(output_name)), 'w') as f:
            f.write(player.to_sgf(use_comments=False))
        with gfile.GFile(os.path.join(full_sgf_dir, '{}.sgf'.format(output_name)), 'w') as f:
            f.write(player.to_sgf())

    tf_examples = preprocessing.make_dataset_from_selfplay(game_data)

    if selfplay_dir is not None:
        # Hold out 5% of games for validation.
        if random.random() < holdout_pct:
            fname = os.path.join(holdout_dir,
                                 "{}.tfrecord.zz".format(output_name))
        else:
            fname = os.path.join(selfplay_dir,
                                 "{}.tfrecord.zz".format(output_name))

        preprocessing.write_tf_examples(fname, tf_examples)
651018
def _find_balanced(self, text, start, open_c, close_c):
        
        i = start
        l = len(text)
        count = 1
        while count > 0 and i < l:
            if text[i] == open_c:
                count += 1
            elif text[i] == close_c:
                count -= 1
            i += 1
        return i
1326161
def balance(output):
    """"""
    lines = map(pattern.search, output.splitlines())

    stack = []
    top = []
    for item in map(match_to_dict, itertools.takewhile(lambda x: x, lines)):
        # pop items off stack while current item has indent <=
        while stack and item['indent'] <= stack[-1]['indent']:
            stack.pop()

        # check if this is a top-level item
        if not stack:
            stack.append(item)
            top.append(item)
        else:
            item['parent'] = stack[-1]
            stack[-1]['children'].append(item)
            stack.append(item)

    return top
225371
function(playerCards, dealerCard, handValue, handCount, dealerCheckedBlackjack, options)
    {
        // Can you split?
        if ((playerCards[0] == playerCards[1]) && (playerCards.length == 2) && (handCount < options.maxSplitHands))
        {
            // Split unless 4s, 5s, and 10s
            if ((playerCards[0] != 4) && (playerCards[0] != 5) && (playerCards[0] != 10))
            {
                return "split";
            }
        }

        // Double
        if (((playerCards.length == 2) && ((handCount == 1) || options.doubleAfterSplit)) &&
                ((handValue.total >= options.doubleRange[0]) && (handValue.total <= options.doubleRange[1])))
        {
            // Only on 9-11
            if ((handValue.total == 9) && (dealerCard < 7) && (dealerCard != 1))
            {
                return "double";
            }
            if ((handValue.total == 10) && (dealerCard < 10) && (dealerCard != 1))
            {
                return "double";
            }
            if (handValue.total == 11)
            {
                return "double";
            }
        }

        // Hit and stand
        if (handValue.soft)
        {
            // Hit until you get to 17, 18 against dealer 9-Ace
            if ((handValue.total < 18) || ((handValue.total == 18) && ((dealerCard >= 9) || (dealerCard == 1))))
            {
                return "hit";
            }
        }

        if (handValue.total <= 11)
        {
            return "hit";
        }
        else if (handValue.total >= 17)
        {
            return "stand";
        }
        else
        {
            // Hit on 7 or above, else stand
            return ((dealerCard >= 7) || (dealerCard == 1)) ? "hit" : "stand";
        }
    }
724061
def tictactoe(w, i, player, opponent, grid=None):
    ""
    grid = grid or empty_grid
    while True:
        w.render_to_terminal(w.array_from_text(view(grid)))
        if is_won(grid):
            print(whose_move(grid), "wins.")
            break
        if not successors(grid):
            print("A draw.")
            break
        grid = player(w, i, grid)
        player, opponent = opponent, player
1230469
def parallel_fill(self, games, threads=8):
        
        games.sort(key=os.path.basename)
        # A couple extra in case parsing fails
        max_games = int(self.max_size / self.sampling_frac / 200) + 480
        if len(games) > max_games:
            games = games[-max_games:]

        with mp.Pool(threads) as pool:
            res = tqdm(pool.imap(self.func, games), total=len(games))
            self.examples.extend(itertools.chain.from_iterable(res))
        print("Got", len(self.examples), "examples")
911118
def conditions(self):
        """"""
        for idx in six.moves.range(1, len(self.children), 2):
            yield (self.children[idx - 1], self.children[idx])
806338
def _calc_all_possible_moves(self, input_color):
        
        for piece in self:

            # Tests if square on the board is not empty
            if piece is not None and piece.color == input_color:

                for move in piece.possible_moves(self):

                    test = cp(self)
                    test_move = Move(end_loc=move.end_loc,
                                     piece=test.piece_at_square(move.start_loc),
                                     status=move.status,
                                     start_loc=move.start_loc,
                                     promoted_to_piece=move.promoted_to_piece)
                    test.update(test_move)

                    if self.king_loc_dict is None:
                        yield move
                        continue

                    my_king = test.piece_at_square(self.king_loc_dict[input_color])

                    if my_king is None or \
                            not isinstance(my_king, King) or \
                            my_king.color != input_color:
                        self.king_loc_dict[input_color] = test.find_king(input_color)
                        my_king = test.piece_at_square(self.king_loc_dict[input_color])

                    if not my_king.in_check(test):
                        yield move
1218958
private void diffClique(float[] weights, int p) {
		for (int t = 0; t < orders.length; t++) {
			if (data[p][t] == -1)
				continue;

			if (orders[t] == 0) {
				if (golds[p] != preds[p]) {
					int ts = data[p][t] + golds[p];
					int ps = data[p][t] + preds[p];
					adjust(weights, ts, ps);
				}
			}
			if (p > 0 && orders[t] == 1) {
				int ts = data[p][t] + (golds[p - 1] * ysize + golds[p]);
				int ps = data[p][t] + (preds[p - 1] * ysize + preds[p]);
				adjust(weights, ts, ps);
			}
		}
	}
602628
def p_If(p):
    '''
    
    '''
    if len(p) == 2:
        p[0] = If(p[1], None, None)
    else:
        p[0] = If(p[1], p[5], p[4])
113864
def check_new_round(hours=24, tournament=1):
    """"""
    click.echo(int(napi.check_new_round(hours=hours, tournament=tournament)))