def pop_card_from_list(self, card_id: str, location: List[Card]): card = util.shrink([card for card in location if card.id == card_id]) other_cards = [card for card in location if card.id != card_id] location.clear() for other_card in other_cards: location.append(other_card) return card
def reject_trade(self, player: Player, trade_id: str): trade: Trade = util.shrink([trade for trade in self.trades if trade.id == trade_id]) if not trade: return util.error("Trade does not exist") if player is not trade.p2: return util.error("You are not in this trade") # Remove trade from trades self.trades = [trade for trade in self.trades if trade.id != trade_id] return util.success("Trade successfully rejected")
def create_trade(self, p1: Player, p2_name: str, card_ids: List[str], wants: List[str]): tcs: List[TradingCard] = self.ids_to_tcs(p1, card_ids) new_trades: List[Trade] = [] p2: Player = util.shrink([player for player in self.players if player.name == p2_name]) if not p2: return util.error("Player chosen is not in game") new_trades += [Trade(p1, p2, tcs, wants)] self.trades += new_trades return util.success('Successfully created trade')
def accept_trade(self, player: Player, trade_id: str, card_ids: List[str]): tcs: List[TradingCard] = self.ids_to_tcs(player, card_ids) trade: Trade = util.shrink([trade for trade in self.trades if trade.id == trade_id]) if not trade: return util.error("Trade does not exist") if player is not trade.p2: return util.error("You are not in this trade") result = trade.accept(tcs) if not result.get('error'): self.trades = [trade for trade in self.trades if trade.id != trade_id] return result
def access() -> Dict: ''' Checks if request has a cookie of a logged in user. If cookie exists it sends user their game info. If not, it takes them to the login page. ''' cookie: str = request.cookies.get('tbg_token') try: game_id: str = clients[cookie] except KeyError: abort(400, util.error('Access denied')) if games[game_id].status == 'Completed': abort(400, util.error('Game already completed')) player: Player = util.shrink([ player for player in games[game_id].players if player.token == request.cookies.get('tbg_token') ]) return jsonify({'game': game_id, "player_name": player.name})
def login() -> Dict: ''' Adds user to the requested game as long as game isn't full or already started, game exists, and user name isn't already used in game. ''' post_data: Dict = request.get_json() try: name: str = post_data['name'] game_id: str = post_data['game'] except KeyError: abort(400, util.error('Incorrect JSON data')) # Get first public game game: Game = util.shrink([ games[game_id] for game_id in games if games[game_id].game_type == 'public' ]) # If game game_id isn't a blank string, use that game if game_id in games: game = games[game_id] if name in [player.name for player in game.players]: abort(400, util.error('User already exists with that name')) if game.status != 'Awaiting': abort(400, util.error('Game has already started or ended')) if game.is_full(): abort(400, util.error('Game is full')) player: Player = Player(name) game.add_player(player) clients[player.token] = game_id response = make_response( jsonify(util.success('Successfully logged into game'))) response.set_cookie('tbg_token', player.token, max_age=6000) update_client(game) return response
def run(): for epoch in range(config.epoch): print(epoch) while config.input_dim + 1 <= len(config.columns): current_feature_name = config.columns[config.input_dim] textLoader = DataLoader(text, batch_size=config.batch_size, shuffle=True, num_workers=config.num_workers, drop_last=config.drop_last) model = netLSTM_withbn() with torch.no_grad(): model = model.cuda() net_enn_train = enn.ENN(model, NE) # If pre_existent epoch found, set net_enn_train parameters with pre_existent epoch record. # Only processed if current epoch count is 0 epoch_list = [ i for i in os.listdir(PATH) if i.startswith( "parameters_{}_epoch_".format(current_feature_name)) ] if len(epoch_list) > 0 and epoch == 0: print("Pre_existent epoch found: {}".format( sorted(epoch_list)[-1])) epoch_pre_existent = pickle.load( open(os.path.join(PATH, sorted(epoch_list)[-1]), 'rb')) net_enn_train.set_parameter(epoch_pre_existent) if epoch > 0: parameter_path = os.path.join( PATH, "parameters_{}_epoch_{}".format(current_feature_name, epoch - 1)) print("Setting checkpoint {}".format(parameter_path)) parameter_checkpoint = pickle.load(open(parameter_path, 'rb')) net_enn_train.set_parameter(parameter_checkpoint) for i, data in enumerate(textLoader): print('#' * 30) print("{}: batch{}".format(time.strftime('%Y%m%d_%H_%M_%S'), i)) # preparing the train data input_, target = data input_ = torch.from_numpy( np.stack(list(shrink(input_, config.shrink_len)), axis=1)) target = torch.from_numpy( np.stack(list(shrink(target, config.shrink_len)), axis=1)) with torch.no_grad(): input_, target = map(Variable, (input_.float(), target.float())) target = target.reshape(-1, config.output_dim) input_ = input_.cuda() target = target.cuda() # train the model net_enn_train, loss, pred_data = train( net_enn_train, input_, target, feature_name=current_feature_name) with torch.no_grad(): params = net_enn_train.get_parameter() filename = PATH + "/parameters_{}_epoch_{}".format( current_feature_name, epoch) save_var(params, filename) del params test(net_enn_train, feature_name=current_feature_name, draw_result=(epoch == config.epoch - 1)) config.input_dim += 1 text.reset_train_dataset() config.input_dim -= 3 text.reset_train_dataset() text.reset_test_dataset()
indices1 = np.where(scores1 > score_threshold1)[0] scores1 = scores1[indices1] boxes_pred1 = boxes_pred1[indices1] boxes_pred1, scores1 = util.nms(boxes_pred1, scores1, nms_threshold) indices2 = np.where(scores2 > score_threshold2)[0] scores2 = scores2[indices2] boxes_pred2 = boxes_pred2[indices2] boxes_pred2, scores2 = util.nms(boxes_pred2, scores2, nms_threshold) boxes_pred = np.concatenate((boxes_pred1, boxes_pred2)) scores = np.concatenate((scores1, scores2)) boxes_pred, scores = util.averages(boxes_pred, scores, wt_overlap, solo_min) util.shrink(boxes_pred, shrink_factor) output = '' for j, bb in enumerate(boxes_pred): x1 = int(bb[0]) y1 = int(bb[1]) w = int(bb[2] - x1 + 1) h = int(bb[3] - y1 + 1) output += f'{scores[j]:.3f} {x1} {y1} {w} {h} ' test_ids.append(fid) test_outputs.append(output) print() end = time.time() # print execution time print(f"Elapsed time = {end-start:.3f} seconds")