dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def run_preprocessing(df, target_col, debug=False):
# Drop the useless features
df = drop_useless_features(df, debug)
# Replace categorical columns that use numerical values with the actual category names
df = convert_numerical_category_columns(df, debug)
# Fill in the missing values
df = fill... | The code's main task is to load house price training data, preprocess it, and perform a grid search over correlation thresholds to identify the optimal threshold for feature selection. It exits early, skipping the final feature selection step, focusing instead on evaluating correlation-based thresholding for predictive... | def pipeline1(debug=False):
# Read in relevant data
train = pd.read_csv('data/house-prices/train.csv')
if debug:
print("Original Train Dataframe:")
print(train.head())
print('Original shape of Training Dataframe: {}'.format(train.shape))
# Run preprocessing
if debug:
... |
def get_ethogram_annotated_files(cfg):
ethogram_results = {}
for dirs in cfg.paths.ethogram_labels:
for root, dirs, files in os.walk(os.path.join(dirs, "DATA")):
for file in files:
if file.endswith(".h5"):
ethogram_results[file[:-11]] = os.path.join(root, ... | The code identifies valid step indices from DeepLabCut and DeepEthogram annotations by filtering based on confidence thresholds and motion detection, then returns the filtered step indices. It also visualizes detected steps if graph_preview is enabled. | def get_valid_step_idx(cfg, trial_name, graph_preview):
# DeepEthogram annotated files
ethogram_results = get_ethogram_annotated_files(cfg)
# DeepLabCut annocated files
dlc_results = get_dlc_annotated_files(cfg)
try:
assert os.path.exists(dlc_results[trial_name])
assert os.path.exi... |
def get_balance_factor(self, node: Node):
# We do have to balance our tree to keep h = O(lg n)
deep_difference = self.get_node_height(node.left) - self.get_node_height(node.right)
balance_factor = self.balance_factor()
if deep_difference == -2:
return balance_factor['UNBALA... | This function inserts a new node with the given key into an AVL tree, recursively adjusting left or right children based on key comparisons. It then checks the tree's balance factor and applies rotations (LL, LR, RL, RR) to maintain AVL balance, ensuring the tree remains height-balanced after insertion. | def insert_node(self, node: Node, key: int) -> Node:
if node is None:
return Node(key)
elif key < node.key:
node.left = self.insert_node(node.left, key)
elif key > node.key:
node.right = self.insert_node(node.right, key)
else:
return node
... |
def gen_years(start=2019):
while True:
yield start
start += 1
def gen_months():
for month in range(1, 13):
yield month
def gen_days(month, leap_year=True):
months = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
if month != 2:
yiel... | The code generates all possible date and time combinations for a given year (default 2019) using nested loops. It iterates through years, months, days, and times, formatting each as "DD/MM/YY HH:MM" via a generator. Helper functions (`gen_years`, `gen_months`, `gen_days`, `gen_time`) provide ranges for each component. ... | def gen_date(year=2019):
for years in gen_years(year):
for month in gen_months():
for days in gen_days(month):
for day in range(1, days + 1):
for time in gen_time():
yield "%02d/%02d/%02d %s" % (day, month, years, time) |
def print_upper_section(self) -> None:
self.clear_window()
print(self.logo)
print("\n\n")
def send_money(self, session, db_operator) -> None:
self.print_upper_section()
user_currency = input("Which currency do you choose? (Currency)")
user_amount = float(
in... | The code displays a user menu with options to send money, exchange currency, view account details, or logout. It loops until the user selects '4 - Logout', calling corresponding methods based on input. The menu greets the user by first name and handles keyboard interrupts gracefully. | def print_menu(self, session, db_operator) -> None:
is_true = True
while(is_true):
self.print_upper_section()
print(f" Welcome back, {session.user.first_name}\n")
print(" What do you want to do today?")
print(" 1 - Send money")
print(" 2 - ... |
def train_epoch(model, data_iterator, optimizer, criterion):
"""
This method operates one epoch (pass over the whole train set) of training of the given model,
and returns the accuracy and loss for this epoch
:param model: the model we're currently training
:param data_iterator: an iterator, iterati... | The main task of the code is to train a machine learning model using the Adam optimizer and track its performance across training and validation sets over multiple epochs. It initializes the optimizer with a specified learning rate and weight decay, uses binary cross-entropy loss, and iteratively trains the model while... | def train_model(model, data_manager, n_epochs, lr, weight_decay=0.):
"""
Runs the full training procedure for the given model. The optimization should be done using the Adam
optimizer with all parameters but learning rate and weight decay set to default.
:param model: module of one of the models impleme... |
def train_model(model, data_manager, n_epochs, lr, weight_decay=0.):
"""
Runs the full training procedure for the given model. The optimization should be done using the Adam
optimizer with all parameters but learning rate and weight decay set to default.
:param model: module of one of the models impleme... | The function trains a log-linear model using one-hot encoded inputs, evaluates it on training, validation, and test datasets, and visualizes training/validation loss/accuracy curves. It also reports test performance, including accuracy on negative and rare word subsets, providing a comprehensive assessment of the model... | def train_log_linear_with_one_hot():
"""
Here comes your code for training and evaluation of the log linear model with one hot representation.
"""
data_manager = DataManager(batch_size=BATCH_SIZE)
embedding_dim = data_manager.get_input_shape()[0]
log_linear_model = LogLinear(embedding_dim)
t... |
def train_model(model, data_manager, n_epochs, lr, weight_decay=0.):
"""
Runs the full training procedure for the given model. The optimization should be done using the Adam
optimizer with all parameters but learning rate and weight decay set to default.
:param model: module of one of the models impleme... | This function trains a log-linear model using pre-trained word2vec embeddings for text classification. It initializes a DataManager with averaged word2vec representations, trains the model over multiple epochs with specified hyperparameters, evaluates performance on training, validation, and test sets, and visualizes l... | def train_log_linear_with_w2v():
"""
Here comes your code for training and evaluation of the log linear model with word embeddings
representation.
"""
data_manager = DataManager(data_type=W2V_AVERAGE, batch_size=BATCH_SIZE, embedding_dim=W2V_EMBEDDING_DIM)
log_linear_w2v_model = LogLinear(W2V_EM... |
def train_model(model, data_manager, n_epochs, lr, weight_decay=0.):
"""
Runs the full training procedure for the given model. The optimization should be done using the Adam
optimizer with all parameters but learning rate and weight decay set to default.
:param model: module of one of the models impleme... | The code trains a Bi-directional LSTM model using pre-trained word2vec embeddings on sequence data. It evaluates the model's performance across training, validation, and test sets, computes accuracy and loss metrics, and visualizes training curves. Additionally, it reports specialized results for negative and rare clas... | def train_lstm_with_w2v():
"""
Here comes your code for training and evaluation of the LSTM model.
"""
data_manager = DataManager(data_type=W2V_SEQUENCE, batch_size=BATCH_SIZE, embedding_dim=W2V_EMBEDDING_DIM)
lstm_model = LSTM(W2V_EMBEDDING_DIM, hidden_dim=100, n_layers=1, dropout=0.5)
train_ac... |
def get(url):
t0 = time.time()
resp = requests.get(url)
if resp.headers["content-type"].lower() == "application/json":
result = resp.json()
else:
result = resp.content
timing_stats.append(time.time() - t0)
return result
def directory_get(url, done):
directory = get(url)
i... | This function retrieves a software revision from a given URL, checks if it's already processed using a set, and if not, yields the revision. It then recursively processes the associated directory and parent revisions, ensuring each unique Software Heritage ID (SWHID) is handled once. The task involves traversing revisi... | def revision_get(url, done):
revision = get(url)
swhid = f"swh:1:rev:{revision['id']}"
if swhid not in done:
done.add(swhid)
yield revision
swhid = f"swh:1:dir:{revision['directory']}"
if swhid not in done:
yield from directory_get(revision["directory_url"], done)... |
def newton_method(
alpha_0: np.ndarray,
K_xx: np.ndarray,
K_xy: np.ndarray,
lambda_: float,
max_iter: int,
a: float,
b: float,
inplace: bool,
tol: float,
input_check: bool,
):
"""
Gradient descent algorithm with line search and positivity constraints
This algorithm i... | The code implements the Kernelized Adaptive Learning Estimator (KALE) optimization, solving a regularized kernel learning problem using methods like Newton, L-BFGS, or coordinate descent. It computes kernel matrices (K_xx, K_xy, K_yy), optimizes over parameters α with warm-starting, and ensures convergence via dual gap... | def kale(
X,
Y,
kernel,
kernel_kwargs,
lambda_,
inner_max_iter,
inner_a,
inner_b,
inner_tol,
inplace,
input_check,
last_iter_info,
penalized,
allow_primal_overflow=False,
optimization_method="newton",
optimizer_kwargs=None,
online=False,
dual_gap_t... |
def _2w(self, x, r):
"""get world-frame joint coords
INPUTS:
x -- state vector
r -- shape vector
OUTPUTS:
array of joint xy coords: [body, L1, L2, R1, R2]
"""
# link rotations
c = ang2cpx(r)
cfg = self.basecfg * asarray([c[0], c... | This code plots configurations derived from inputs x and r by converting complex numbers to Cartesian coordinates. It visualizes points from _2w(), connects specific points with lines, marks the center of mass (_com()) with a black 'X', and plots midpoints (_midpts()) as green dots. The function returns the matplotlib ... | def plot(self, x, r, ax=None):
if ax is None:
ax = plt.figure().gca()
wcfg = self._2w(x, r)
ax.plot(*cpx2cart(wcfg[:3]), '.-')
ax.plot(*cpx2cart(wcfg[[0, 3, 4]]), '.-')
ax.plot(*cpx2cart(self._com(x, r)), 'X', c='k', ms=10)
ax.plot(*cpx2cart(self._midpts(x, r)... |
def sto_data(self, full = False):
# randomly select input data by mini-batch
if full == False:
ind = np.random.randint(0, self.data.shape[1], self.N)
else:
ind = np.random.randint(0, self.data.shape[1], self.M)
sto_data = self.data[:, ind]
success = sto_da... | This function generates samples using a stochastic process with optional preconditioning. It accumulates time intervals, updates sample values via velocity and bounce_t, stores results, and applies an accept-reject mechanism. If preconditioning is enabled, it scales samples with the preconditioner matrix. The loop cont... | def generate_samples(self, sample_interval, store_skip = 1, use_preconditioner = False):
# sample_interval : discretization
# store_skip : thinned factor (not used)
# use_preconditioner : preconditioner used or not, check chapter 5
self.sample_interval = sample_interval
self.accu... |
def sft(args):
assert args.model_name
model, tokenizer = get_model(args.base_model, None, None, False, False)
trainer = Trainer(
model=model,
args=get_training_args(args),
train_dataset=FeedbackSFTDataset(load_dataset("train"), args),
eval_dataset=FeedbackSFTDataset(load_data... | The main task of the code is to set up and execute different training/generation workflows for a feedback generation model. It initializes random seeds, parses command-line arguments (e.g., SFT, PPO, DPO modes, hyperparameters, model paths), and runs the selected task (training or generation) based on flags. It support... | def main():
initialize_seeds(221)
parser = argparse.ArgumentParser()
# Modes
parser.add_argument("--sft", action="store_true", help="Supervised finetuning for feedback generation")
parser.add_argument("--ppo", action="store_true", help="PPO training with reward model for feedback generation")
p... |
def expand_dataset():
df = get_raw_dataset()
df = df.sample(frac=1)
splits = [
("train", df.iloc[:int(len(df) * 0.6)]),
("val", df.iloc[int(len(df) * 0.6):int(len(df) * 0.8)]),
("test", df.iloc[int(len(df) * 0.8):])
]
for split, split_df in splits:
expand_rows(split_... | This code defines a main function that processes command-line arguments to manipulate a feedback reward dataset. It supports expanding datasets, generating feedback via specified methods (random, knn, zs), compiling datasets into single entries or head-to-head matchups, creating subsets, and annotating with LLMs. Param... | def main():
initialize_seeds(221)
parser = argparse.ArgumentParser("Feedback Reward Dataset")
# Modes
parser.add_argument("--expand", action="store_true", help="Expand dataset to have one feedback per data sample and split into train/val/test")
parser.add_argument("--generate", type=str, choices=["... |
def buy_check(self,userId,companyId,numberOfStocks,companyShareValue):
availableStocks=self.companyValues[companyId]["stocksAvailable"]
if availableStocks<=numberOfStocks:
numberOfStocks=availableStocks
transactionAmount=numberOfStocks*companyShareValue
cashInHand=self.userSt... | This function processes a stock purchase for the current player, validating the transaction, updating user holdings and cash balances, adjusting company stock availability, and logging the transaction details before advancing to the next turn. | def buy(self,userId,companyId,numberOfStocks):
if userId!=self.playerOrder[self.currentTurn]:
return
companyShareValue=self.companyValues[companyId]["companyShareValue"]
numberOfStocks=self.buy_check(userId,companyId,numberOfStocks,companyShareValue)
transactionAmount = numbe... |
def sell_check(self,userId,companyId,numberOfStocks,companyShareValue):
stocks_held=self.userState[userId]["holdings"][companyId]
if numberOfStocks>=stocks_held:
numberOfStocks=stocks_held
if companyShareValue==0:
numberOfStocks=0
if "limitTransactionValue" in sel... | This function processes a stock sale for the current player. It checks if the user is active, validates the sale, calculates transaction value, updates user holdings/cash, adjusts company stock availability, logs the transaction, then advances to the next turn. | def sell(self,userId,companyId,numberOfStocks):
if userId!=self.playerOrder[self.currentTurn]:
return
companyShareValue=self.companyValues[companyId]["companyShareValue"]
numberOfStocks=self.sell_check(userId,companyId,numberOfStocks,companyShareValue)
transactionAmount = num... |
def buy_check(self,userId,companyId,numberOfStocks,companyShareValue):
availableStocks=self.companyValues[companyId]["stocksAvailable"]
if availableStocks<=numberOfStocks:
numberOfStocks=availableStocks
transactionAmount=numberOfStocks*companyShareValue
cashInHand=self.userSt... | This code processes a player's "crystal" action in a stock-trading game, handling five types of transactions (fraud, dividend, bonus shares, right issue, loan) by updating user holdings, cash balances, and company stock availability. It validates the user's turn, calculates stock values, executes purchases/sales, recor... | def crystal(self,userId, crystalType,companyId=1,numberOfStocks=0):
if userId!=self.playerOrder[self.currentTurn]:
return
if crystalType=="FRAUD":
companyShareValue=self.companyValues[companyId]["companyShareValue"]
newStockValue = math.floor(int(0.7 * companyShareVal... |
def removeChairman(self,companyId):
if "allowChairman" not in self.configs:
return
if not self.configs["allowChairman"]:
return
if self.chairman[companyId]==None:
return
if self.userState[self.chairman[companyId]]["holdings"][companyId]<100000:
... | The main task of the code is to remove a user from the game by transferring their stock holdings to companies, updating company roles (removing chairman/director status), adjusting player turn order, decrementing player count, and returning the user's data. It handles edge cases for turn order adjustments and role remo... | def kickUser(self,userId):
user=self.userState[userId]
for companyId in self.companyValues:
self.companyValues[companyId]["stocksAvailable"]+=user["holdings"][companyId]
self.userState[userId]["holdings"][companyId]=0
if userId==self.chairman[companyId]:
... |
def get_immediate_reward(board, state, i):
turn_multiplier = 1 if board.turn == chess.BLACK else -1
r = 0
if board.is_checkmate():
r = 100
if board.is_stalemate():
r = -100
if len(board.pieces(chess.ROOK, chess.WHITE)) == 0:
r = -100 # only two kings is an automatic stalemate
if len(board.piece... | This code trains a Q-learning agent to play KRK (King and Rook vs King) chess endgames by simulating random board positions, updating Q-values based on move rewards, and tracking win rates over episodes. It iterates through episodes, generates boards, evaluates moves, updates Q-tables with rewards, records winning posi... | def start():
print("Begin!")
for i in range(num_episodes):
board = generators.random_krk_board(is_4x4_game)
state = q_lookup[satg.board_key(board)]
is_destination = get_immediate_reward(board, state, i) != 0
if is_destination: continue
winner = 0
for j in range(1000):
move, action = ge... |
def _predict_rewards(self, data, x):
if data.size == 0: # if the data is empty, set all rewards to 0
rewards = np.zeros((self.k))
else:
z = self._feature_map(x)
rewards = np.empty((self.k)) # create an empty reward vector
for arm in range(self.k):
data_i = data[data[:,2]==arm,:] # data corresponding... | The main task of the code is to select an optimal "arm" for decision-making by filtering potential options. It first predicts rewards using a greedy strategy (GS), then applies a feature selection (FS) filter to exclude suboptimal arms by comparing GS rewards against a threshold derived from FS rewards. The filtered GS... | def _GS_decision(self, x, FS_filter = True):
GS_rewards = self._predict_rewards(self.GS, x)
if (self.FS.size!=0) & (FS_filter): # if using FS filtering
FS_rewards = self._FS_decision(x)
FS_filter = FS_rewards.max() - self.h/2
GS_rewards[FS_rewards < FS_filter] == GS_rewards.min() - 10 # filter out not-top-... |
def code(self):
code = 0
for i in self.valid_points:
code+= 3*code + self.board[i]
return code
def get_empty_points(self) -> np.ndarray:
"""
Return:
The empty points on the board
"""
return where1d(self.board == EMPTY)
def negamaxBoolean(s... | The main task of the code is to determine if the current player can force a win in a board game by evaluating possible moves using the negamax algorithm with memoization. It checks legal moves, simulates them recursively, and stores results in a table for reuse. If a winning move is found, it returns True and records t... | def firstSolve(self,table,point):
square = (self.size+1)**2
edge = self.size +1
mid = int((square+edge)/2)
frstPoint = mid*2 - point[0]
if time.time()> self.time:
return False
timeEnded = False
codes = self.code()
result = table.lookup(codes)
... |
def findBest(stats: STATS, C: float, n: int) -> int:
best = -1
bestScore = -INFINITY
for i in range(len(stats)):
score = ucb(stats, C, i, n)
if score > bestScore:
bestScore = score
best = i
assert best != -1
return best
def bestArm(stats: STATS) -> int: # Mos... | The function implements the UCB (Upper Confidence Bound) algorithm to select the optimal move in a Go game. It simulates multiple moves, tracks their win rates and visit counts, and balances exploration/exploitation using a confidence parameter C. After simulations, it returns the move with the highest estimated value ... | def runUcb(player: GoSimulationEngine, board: GoBoard, C: float,
moves: List[GO_POINT], toplay: GO_COLOR) -> GO_POINT:
stats = [[0, 0] for _ in moves]
num_simulation = len(moves) * 10
for n in range(num_simulation):
moveIndex = findBest(stats, C, n)
if moves[moveIndex] == -2:
... |
def generate_random_move(self, board):
randMoves, prob = self.simulation_policy(board)
index = random.randrange(len(randMoves))
#print('What are moves?', randMoves)
#print('hello?',randMoves[index])
return randMoves[index]
def generate_pattern_move(self, board):
move, mov... | This function simulates a Go game by selecting moves randomly or via pattern recognition, checking legal moves on the board. It returns the opponent's color when no legal moves remain or after a pass, ensuring proper game flow and termination. | def playGame(self, board: GoBoard, color: GO_COLOR) -> GO_COLOR:
nuPasses = 0
while True:
legalMoves = []
color = board.current_player
empties = board.get_empty_points()
for move in empties:
if board.is_legal(move, color):
... |
def _is_surrounded(self, point: GO_POINT, color: GO_COLOR) -> bool:
"""
check whether empty point is surrounded by stones of color
(or BORDER) neighbors
"""
for nb in self._neighbors(point):
nb_color = self.board[nb]
if nb_color != BORDER and nb_color != c... | The function `play_move` validates and applies a Go move by checking if the target point is unoccupied, ensuring the move doesn't result in immediate capture (suicide) or violate ko rules. It captures opponent stones if applicable, updates the board, switches players, and returns `True` for legal moves while raising er... | def play_move(self, point: GO_POINT, color: GO_COLOR) -> bool:
"""
Play a move of color on point
Returns whether move was legal
"""
assert is_black_white(color)
if self.board[point] != EMPTY:
raise ValueError("occupied")
... |
def walk_in_file_tree():
for root, dirs, files in os.walk(path):
for file in files:
data = open(os.path.join(root, file), "r")
yield data, file
def clean_str(string):
clean_str = ''.join(c for c in string if c.isalnum()).lower()
return clean_str
def insert_line(clean_line, _d... | The function processes text files by reading lines, cleaning them, and storing non-empty lines in a dictionary (`list_auto_complete`) with their file names and indices. It updates the input dictionary (`_dict`) using `insert_line` and uploads the collected sentences via `upload_sent_path_file`. The main task is to gath... | def get_five_fit_sent_from_file(_dict):
list_auto_complete = {}
index_sent = 0
for file, file_name in walk_in_file_tree():
lines = file.readlines()
for line in lines:
clean_line = clean_str(line)
if clean_line:
list_auto_complete[index_sent] = [str(l... |
def get_sentences_by_score(sentences):
for score in losses_points:
yield {i: j for i, j in sentences[score].items()}, score
def init_list_auto(sentences_offsets_pairs, score):
_list = []
for index, offset in get_index_offset_pair(sentences_offsets_pairs):
source_sentence, path = get_source_s... | The function retrieves the top k auto-complete suggestions for a given text by searching a trie for matching sentences, scoring them based on loss points and a basic text score, and returning the highest-scoring completions up to the limit k. | def get_best_k_completions(text):
sentences = offline.search(trie, text) # [{"index of sentence": offset},{i...: offset }... ]
if not sentences: # no match
return []
auto_data = []
for sentence_offset_pair, loss_points in get_sentences_by_score(sentences):
auto_data += init_list_auto... |
def get_best_k_completions(text):
sentences = offline.search(trie, text) # [{"index of sentence": offset},{i...: offset }... ]
if not sentences: # no match
return []
auto_data = []
for sentence_offset_pair, loss_points in get_sentences_by_score(sentences):
auto_data += init_list_auto... | The code continuously takes user input, processes it to get the best k completions, and prints matching sentences. It loops until the input ends with '#', appending inputs dynamically to refine completions iteratively. | def main():
while True:
text = input("ready,Enter your text:")
if not text:
continue
auto = get_best_k_completions(clean_str(text))
print_k_match_sentences(auto)
while text[-1] != '#':
text += input(text)
auto = get_best_k_completions(cle... |
def get_root(filepath):
parser = et.XMLParser(ns_clean=True)
root = et.parse(filepath, parser).getroot()
return root
def get_namespace(self):
return {k if k is not None else 'default': v for k, v in self.root.nsmap.items()}
def create_datasets(self):
datasets = []
for it... | This code initializes a class by parsing an XML file at the given filepath, extracting the study's namespace, creating datasets, and retrieving the Study OID and MetadataVersion OID from the XML structure. | def __init__(self, filepath):
self.filepath = filepath
self.root = self.get_root(filepath)
self.namespace = self.get_namespace()
self.datasets = self.create_datasets()
self.study_oid = self.root.find('default:Study', self.namespace).get('OID')
self.metadata_version_oid = ... |
def __getLineEdit(self, qLineEdit):
'''
TBA
'''
return qLineEdit.text()
def __getCheckBox(self, qCheckBox):
'''
TBA
'''
return qCheckBox.isChecked()
def __getTableWidget(self, qTableWidget):
'''
TBA
'''
keyValue = {}
... | This method gathers UI input values into a dictionary, constructs a JSON file path, and saves the data to a JSON file either by updating an existing one or creating a new file. It then triggers a refresh to reflect changes. | def __onOptionSavePressed(self):
'''
TBA
'''
settingData = {}
settingData['order'] = self.__getLineEdit(self.__optionUi.orderLE)
settingData['name'] = self.__getLineEdit(self.__optionUi.nameLE)
settingData['description'] = self.__getLineEdit(self.__optionUi.descr... |
def create_team(omit_player=None, iterations=1000):
positions = ['Forward']*3 + ['Midfielder']*5 + ['Defender']*5 + ['Goalkeeper']*2
my_players = get_my_players()
for player in players:
if player['full_name'] in my_players and player['full_name'] != omit_player and player['position_name'] ... | The main task of the code is to generate optimal player transfer suggestions by evaluating the expected points of alternative teams formed by omitting each of the user's current players and replacing them with non-owned players. It identifies the highest-scoring transfers, calculates the point difference compared to th... | def get_transfers():
current_team_expected_points = create_team(iterations=1)[1]
max_points = -1
best_transfers = []
my_players = get_my_players()
for y in range(len(my_players) - 1):
omit_player = my_players[y]
best_team, points = create_team(omit_player, iterations=1)
... |
def list_serial_ports():
ports = set([])
serial_ports_iterator = get_serial_port_iterator()()
for (port, _, _) in serial_ports_iterator:
ports.add(port)
return ports
def usb_reset(port):
try:
# open the port at 1200 and set DTR to false
# https://github.com/arduino/Arduino/b... | The main task of the code is to reset a USB-connected MCU device to enter bootloader mode, detect the newly assigned serial port after reset, update the flashing arguments with this new port, and execute the flashing process using the updated port. The function ensures the target port exists initially, triggers a USB r... | def flash_method_usb_reset(args, hex_file):
# This flash method will reset the USB device first
# This causes the mcu to enter the bootloader
# However, it will come up as a new serial port (NOT the specified target port)
# The new port will be detected and assigned when running the flash command
t... |
def find_matching_hex_file(project_name, mcu, search_root):
for parent, _, files in os.walk(search_root):
for f in files:
if re.match(f'{project_name}-{mcu}-{mcu}.*\.hex', f):
return os.path.join(parent, f)
return None
def flash_method_usb_reset(args, hex_file):
# This fl... | The main task of the code is to locate and flash a hex file to a microcontroller unit (MCU) based on provided arguments. It first searches for a matching hex file using project, MCU, and search root parameters. If found, it selects a flashing method: `flash_method_usb_reset` for specific MCUs requiring a reset, or `fla... | def main(args):
hex_file = find_matching_hex_file(args["project"], args["mcu"], args["search_root"])
if not hex_file:
print('No hex file matches the criteria')
return
try:
if args['mcu'] in USB_RESET_REQUIRED and not args['user_override']:
# Some boards need to be reset... |
def get_optimal_guess(word_list):
expected_outcome_for_word = {}
for word in word_list:
word = word.strip('\n')
expected_outcome_for_word[word] = get_expected_outcome(word, word_list)
return min(expected_outcome_for_word, key = expected_outcome_for_word.get)
def rank_words(word_list):
le... | The function suggests a word based on the input list by checking predefined JSON outcomes for specific cases, prioritizing 'salet' for a list of length 2309, and using a ranking method to return the last key in the word ranking when no matches are found in the JSON files. | def suggest_word(word_list):
if len(word_list) == 2309: return 'salet'
with open('data/best_guess_for_salet_outcome.json') as json_file:
salet_outcomes = json.load(json_file)
if str(word_list) in salet_outcomes.keys() and len(word_list)>4:
return salet_outcomes[str(word_list)]
with open(... |
def green(letter, index, word_list):
return [word for word in word_list if word[index] == letter]
def yellow(letter, index, word_list):
new_list = [word for word in word_list if letter in word]
return [word for word in new_list if not word[index] == letter]
def grey(letter, index, word_list):
return [wo... | The code filters a word list based on user inputs (green, yellow, grey letters) to narrow down possible answers, updates UI elements with the count of remaining words and a suggested guess, then displays the filtered words. | def update(event=None):
text.delete(1.0, tk.END)
word_list = []
with open("data/words.txt", encoding="UTF-8") as word_list_f:
for word in word_list_f:
word_list.append(word)
word_list_f.close()
green_letters = [
entry1.get().strip().lower(),
entry2.get().stri... |
def bypass_menu(opt):
global p
p.recvuntil("Menu:")
print("[X] Bypassing menu.")
p.sendline(str(opt))
def give_experience(exp, already_string=False):
global p
if not already_string:
exp = str(exp)
print("[X] Waiting for process to ask about total experience.")
p.recvuntil("earned... | The code automates game tasks by bypassing menus, collecting horcruxes, awarding experience via exploits, and processing signed data. It skips UI elements, executes experience grants, and handles canonicalized totals for progression. | def main():
bypass_menu(3)
give_experience(exploit, already_string=True)
skip_line()
collect_horcruxes()
bypass_menu(3)
prompt()
give_experience(canonize_signed(total)) |
def step_1(self):
#read file:
file = open(self.file, 'r')
text = file.read()
file.close()
traces = text.split('<trace>')
traces.pop(0)
for i in traces:
events = i.split('<event>')
events.pop(0)
trace = []
for event i... | The method `heuristic_net` executes three sequential steps: it first invokes `step_1` and `step_2` (likely for preprocessing or computation), then returns the result of `step_3`, which presumably generates the final output of the heuristic process. This structure suggests a modular approach to solving a problem in stag... | def heuristic_net(self):
self.step_1()
self.step_2()
return self.step_3() |
def authenticate_client(self, client_id: str, secret_key: str) -> tables.OAuthClient:
authentication_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail='Invalid client credentials',
headers={'WWW-Authenticate': 'Bearer'}
)
client = (
... | The main task of the code is to verify the validity of an OAuth token by checking its expiration, client authentication, and presence in the database. It decodes the JWT token, validates its claims, and ensures the token is not revoked. If invalid, it checks for a valid refresh token, revokes expired tokens, and return... | def check_token(self, data: dict) -> IntrospectResponse | dict:
now = datetime.utcnow()
client = self.authenticate_client(
client_id=data.get('client_id'),
secret_key=data.get('secret_key')
)
token = data.get('token')
try:
payload = jwt.deco... |
def get_phi(x_ref):
p_ref = x_ref[:3].copy()
v_ref = x_ref[3]
theta_ref = x_ref[4:7].copy()
omega_ref = x_ref[7:10].copy()
R_ref = Rt.from_rotvec(theta_ref).as_matrix()
M_0 = (R_ref @ u_d).reshape((3, 1))
M_1 = -v_ref * skew_symmetry(R_ref @ u_d)
M_2 = skew_symmetry(omega_ref)
nor... | The code predicts the state (x_ref) and parameters (vartheta) in a probabilistic model by updating their mean (mu) and covariance (Sigma) matrices. It computes Phi and Phi_vartheta for linearization, applies process noise (W, W_vartheta), and updates predictions using matrix operations. The function returns the updated... | def predict(Theta):
ret = Theta.copy()
x_ref = ret.x_ref
mu = ret.mu
Sigma = ret.Sigma
# Predict x
Phi = get_phi(x_ref)
ret.x_ref = f(x_ref)
ret.P = Phi @ Theta.P @ Phi.T + W * dt
# Predict vartheta
k_list = np.ones(N_T) * epsilon
Phi_vartheta = get_phi_vartheta(k_list)
... |
def Star(M):
assert M.ndim == 2 or M.ndim == 3
if M.ndim == 2:
assert M.shape[0] == 3
return np.concatenate(skew_symmetry(M.T), axis=1)
else:
ret = skew_symmetry(M.transpose(0, 2, 1).reshape([-1, 3]))
ret = ret.reshape([-1, 3, 3, 3]).transpose(0, 2, 1, 3).reshape([-1, 3, 9])
... | The code performs an iterative update on the state estimate `Theta` using measurements `z_r` and `z_c`, incorporating constraints from ground, corner, and skeleton knot points. It computes expectations, Jacobians, and covariances to refine the state (position, orientation, etc.) and uncertainty (covariance matrices) th... | def update(Theta, z_r, z_c):
if len(z_c) == 0:
return Theta
z_r = z_r if z_r.ndim == 2 else z_r.reshape((1, -1))
assert z_c.ndim == 2
s_i = z_c[:, 0].astype(np.int64)
ground_det_id = np.intersect1d(ground_id, s_i)
ground_det_id_z = np.where(np.isin(s_i, ground_det_id))[0]
corner_d... |
def get_all_folders(folder):
all_folders = [x[0] for x in os.walk(folder)]
return all_folders
def resize_and_copy_if_new(src_album_folder: str, src_dst_folder: SrcDstFolder):
src_photos = get_all_photos_from_folder(src_album_folder)
files_to_resize = []
for src_photo in src_photos:
dst_photo... | The main task of the code is to process image files in source folders by checking if they need resizing, copying them to a destination folder if they are new, and then resizing the images. It iterates through each album folder, logs the folder name, identifies files requiring resizing, and applies the resize operation ... | def compare_and_resize(src_dst_folder):
src_album_folders = get_all_folders(src_dst_folder.src)
for folder in src_album_folders:
logger.info(folder)
files_to_resize = resize_and_copy_if_new(folder, src_dst_folder)
for item in files_to_resize:
resize_photo(item.src, item.dst) |
def getFolderJSON():
return os.path.join(getProjectDir(), 'DataMikro//JsonTable')
def getAllQuery(jsonTable) :
queryListRow = list()
queryListColumn = list()
queryListAll = list()
queryRoot = query()
if 'weight' in jsonTable :
if 'values' in jsonTable:
for itemValue in json... | The function `doQuery` retrieves and executes SQL queries stored in a JSON file associated with a given UUID. It connects to an SQLite database specified in the JSON, runs each query, processes the results into structured dictionaries, and returns both the original JSON data and the aggregated query results for further... | def doQuery(uuid):
fileJsonPath = os.path.join(getFolderJSON(), uuid+'.json')
result = list()
returnValue = {}
with open(fileJsonPath) as f:
data = json.load(f)
queryList = getAllQuery(data)
conn = sqlite3.connect(getProjectDir()+'//DataMikro//datasource//'+data['datasourceuuid'... |
def register_read(self, addr):
"""
Read a register
"""
data = bytearray()
data.extend(b'\xcc\x01\x00\xf8')
data.append(addr)
data.append(0xcd)
self._port.write(data)
_header, payload = self.read_packet_type(0xF6)
assert payload[0] == addr
... | This function waits for specific bits in a status register to be set, looping until they are detected or a timeout occurs. It reads the status register, checks for errors and timeout limits, and returns once the desired bits are set. | def _wait_status_set(self, wanted_bits, max_time):
"""
Wait for wanted_bits bits to be set in status register
"""
start = time.monotonic()
while True:
status = self.register_read(0x6)
self._check_timeout(start, max_time)
self._check_error(stat... |
def cleanup(self):
global mp_game_data, mp_word, multiplayer_queue, priority, turn, mp_game_over, mp_message
self.sock.close()
conn = connections[self]
if self in multiplayer_queue:
del multiplayer_queue[self]
del priority[self]
if len(multiplayer_queue)... | The main task of the code is to initiate a game by querying the client if they want a two-player mode, sending the query via a socket, and based on the client's response ('y' or 'n'), starting either a 2-player or 1-player game. It also handles termination signals by checking for 'Terminate' messages and performing cle... | def start_game(self):
data = 'Two Player? (y/n): '
message = ServerMessage(len(data), data)
self.sock.sendall(message.to_raw_bytes())
data = self.sock.recv(1024)
if data == b'':
return self.cleanup()
response = ClientMessage.from_raw_bytes(data)
if r... |
def sensors_to_channels(sensor_list):
"""Append the channel postfix to the given sensors"""
channels = []
for sensor in sensor_list:
channels.append(sensor + "_A_x")
channels.append(sensor + "_A_y")
channels.append(sensor + "_A_z")
channels.append(sensor + "_G_x")
ch... | The code trains and tests machine learning models using specified parameters (learning rate, regularization, dropout). It processes sensor data, loads or generates training folds, optionally loads a pre-trained model, trains multiple models, evaluates performance (accuracy, Youden's J, confusion matrices), saves result... | def run_test(args, lr=0.001, reg=0.01, dropout=0.5):
"""Train and test models using given parameters"""
sensors= list(set(args.keep) - set(args.remove))
allowed_channels = sensors_to_channels(sensors)
if args.load_data is None:
folds, to_save = get_data(args.beginning, args.end, allowed... |
def __has_valid_cookie(self) -> bool:
"""Checks if there is a valid digital foundry cookie in the cookie jar"""
df_cookie = None
for cookie in self.__cj:
if cookie.domain == self.__domain:
df_cookie = cookie
break
if df_cookie is None:
... | The code checks the Digital Foundry homepage or a specified collection for new video links using a session cookie, downloads each video, and logs progress. It acquires a lock to prevent concurrency, handles errors by notifying users if the site is unreachable, and releases the lock after processing. | def download(self) -> None:
"""Checks the Digital Foundry homepage for new videos, and downloads them."""
if not self.__has_valid_cookie():
return
self.__lock.acquire()
if self.__collection is None:
checking = 'Digital Foundry Homepage'
url = self.__... |
def sanitize_title(title):
'''
Remove forbidden characters from title that will prevent OS from creating directory. (For Windows at least.)
Also change ' ' to '_' to preserve previous behavior.
'''
forbidden_chars = " *\"/\<>:|(),"
replace_char = "_"
for ch in forbidden_chars:
title... | This code extracts text and images from a Scribd document at the given URL, processes JavaScript for additional content, and saves results. It sanitizes the title, handles image downloads if enabled, and converts the document to PDF if requested. The 'train' variable tracks processing steps, while 'save_content' manage... | def get_scribd_document(url, images, pdf):
response = requests.get(url).text
soup = BeautifulSoup(response, 'html.parser')
title = soup.find('title').get_text()
title = sanitize_title(title)
train = 1
print(title + '\n')
if images:
# sometimes images embedded directly in html as we... |
def testArgument(argument: str, value: str):
AcceptedArguments = {'action' : ('e', 'encrypt', 'd', 'decrypt'), 'values' : ('r', 'g', 'b'), 'encoding' : ('binary', 'trinary', 'quaternary', 'quinary', 'senary', 'septenary', 'octal', 'nonal')}
if argument in AcceptedArguments and value:
if argument == 'val... | The main task of the code is to perform image steganography by encrypting or decrypting data based on user-specified actions. It parses command-line arguments, validates inputs, and uses RGB pixel indices to embed (encrypt) or extract (decrypt) text within an image. The code handles encryption/decryption operations usi... | def main():
print('\n')
Arguments = vars(SteganopyParser.parse_args())
if Arguments['action'] is None: Error('ValueError', 'No "action" specified.')
for argument in Arguments: testArgument(argument, Arguments[argument])
Indexes = [{'r' : 0, 'g' : 1, 'b' : 2}.get(i) for i in Arguments['value... |
def _inner_loop(self, train_batch):
self.model.train()
batch = tuple(x.to(self.device) for x in train_batch)
loss, log_dict = self.training_steps.on_training_step(batch)
self.model.zero_grad()
loss.backward()
self.optimizer.step()
self.lr_scheduler.step()
... | This code executes a training loop over multiple epochs, processing batches with an inner loop, logging metrics after each epoch, and saving checkpoints if enabled. It uses tqdm for progress tracking, invokes training hooks, and stores metrics in self.minmax_metrics. The loop iterates through the training data loader, ... | def run(self):
self.minmax_metrics = {}
for self.epoch_idx in tqdm(range(self.num_epochs), leave=True):
self.training_steps.on_before_training_epoch()
for (self.train_batch_idx, batch) in enumerate(
tqdm(self.dl_train, leave=False),
start=self.tr... |
def orient_top_left_tile(self,edge_vals):
edge_max = -1
found = 0
for i,j in enumerate(self.edges):
if j in edge_vals:
found += 1
if edge_max < i:
edge_max = i
if found < 4:
return False
rot = 8-edge_ma... | This function orients a tile by rotating and flipping it so its edges match specified top and/or left values. If both top and left values are unspecified, it orients the tile as a potential top-left corner. If a left value is provided, it aligns the left edge; if a top value is provided, it aligns the top edge. Returns... | def orient_tile(self,edge_vals, top_val=None, left_val=None):
'''
:param edge_vals: array of all the edge values in the image
:param top_val: what top value we want
:param left_val: what left value we want
:return: True if this tile fits the top and/or left piece(s)
'''
... |
def extractKey(f):
startID_pos = f.find('_ID_') + 4
endID_pos = f.find('_train')
startTag = f.find('_ID_')
endTag = f.find('.pkl')
key = f[startID_pos:endID_pos]
tag = f[startTag:endTag]
return key, tag
def runLinear(tag,key,saveLinear,listLinear,outLinear):
############################... | The code processes simulation data files by loading machine learning models (linear & neural networks), running predictions (LSTM/GRU), and saving results in JSON format. It iterates through input files, skips existing outputs, and limits execution to 3 files. | def main():
prefix = 'SimDATA'
listLinear=['DecisionTree', 'AdaBoost', 'GradientBoosting', 'RandomForest']
NNconfig={\
'C1':{'unitsLayer1':1, 'unitsLayer2':0},\
'C2':{'unitsLayer1':7, 'unitsLayer2':0},\
'C3':{'unitsLayer1':14, 'unitsLayer2':0},\
... |
def construct_sql(
self,
fields: Optional[List[str]] = None,
date_col: Optional[str] = None,
start_date: Optional[Union[date, datetime]] = None,
end_date: Optional[Union[date, datetime]] = None,
filters: Optional[List[str]] = None,
limit: Optional[int] = None,
... | The main task of the code is to query a dataset via the National Grid ESO API by constructing a SQL query from provided parameters (fields, date ranges, filters, etc.), sending a GET request with the SQL, validating the response for errors/missing data, and returning the raw byte content of the API response. | def query(
self,
fields: Optional[List[str]] = None,
date_col: Optional[str] = None,
start_date: Optional[Union[date, datetime]] = None,
end_date: Optional[Union[date, datetime]] = None,
filters: Optional[List[str]] = None,
limit: Optional[int] = None,
) -> by... |
def __calc_terrain_scale(self):
x_scale = self.world_size[0] / (self.hgt_size[0] - 1)
y_scale = 1.0 / 1000
z_scale = self.world_size[1] / (self.hgt_size[1] - 1)
self.scale = (x_scale, y_scale, z_scale)
def __generate_vertices(self, elevation):
elevation = self.__drop_unused_data(... | The code initializes terrain data by calculating terrain scale, generating vertices from elevation data, creating triangular mesh structures, and computing surface normals to form a 3D terrain model. | def __init_terrain_data(self, elevation_data):
self.__calc_terrain_scale()
self.__generate_vertices(elevation_data)
self.__generate_triangles()
self.__generate_normals() |
def make_parsing_state(self, **kwargs):
r"""
Return a new parsing state object that corresponds to the current string
that we are parsing (`s` provided to the constructor) and the current
latex context (`latex_context` provided to the constructor).
If no arguments are provided, ... | The function `get_latex_expression` parses a LaTeX expression from a given string starting at position `pos`, handling tokens like macros, braces, or characters. It returns a tuple `(node, pos, len)` representing the parsed expression, its start position, and length. It uses a `parsing_state` to influence parsing behav... | def get_latex_expression(self, pos, strict_braces=None, parsing_state=None):
r"""
Parses the latex content given to the constructor (and stored in `self.s`),
starting at position `pos`, to parse a single LaTeX expression.
Reads a latex expression, e.g. macro argument. This may be a sing... |
def make_parsing_state(self, **kwargs):
r"""
Return a new parsing state object that corresponds to the current string
that we are parsing (`s` provided to the constructor) and the current
latex context (`latex_context` provided to the constructor).
If no arguments are provided, ... | The function `get_latex_maybe_optional_arg` parses LaTeX content starting at position `pos` to detect an optional argument (enclosed in `[]`). It uses a `parsing_state` (or a default if unspecified) to influence parsing. If successful, it returns a tuple containing a `LatexGroupNode`, the new position, and length; othe... | def get_latex_maybe_optional_arg(self, pos, parsing_state=None):
r"""
Parses the latex content given to the constructor (and stored in `self.s`),
starting at position `pos`, to attempt to parse an optional argument.
Parsing might be influenced by the `parsing_state`. See doc for
... |
def get_relative_fitness(i,pop):
games_won = 0
for adv in pop:
# cache games we've already played.
if(i+"|"+adv not in cached):
cached[i+"|"+adv] = run_game_set(i,adv)
games_won += cached[i+"|"+adv]
return games_won
def mutaten(parent,N):
out = parent
for i in ran... | The code implements an evolutionary algorithm to optimize a population of programs (likely Brainfuck-like instructions) by iteratively selecting, mutating, and retaining the fittest individuals based on their performance against previous generations. It aims to evolve increasingly effective programs through generationa... | def runengine(gen_max):
BEST_GEN_SIZE = 500
POP_RATIO = 3
POP_SIZE = BEST_GEN_SIZE * POP_RATIO
#Generate the initial population
pop = []
# some good starter functions, use at your own risk. (these are pretty good, but could stifle diversity.)
# pop.append("<<<<+[[<<<]+[<]<<<++++<<<++[[<<[<... |
def selectAnimal():
while True:
try:
searchTerm = input("Which animal are you building the cage for? ")
except Exception as detail:
print("Error:", detail)
else:
searchResults = []
for animal in allAnimals:
if searchTerm.lower(... | This function calculates how many of a selected animal a cage can hold based on user-input cage size and predefined animal requirements. It validates the cage size, displays capacity or error messages, and allows repeated checks via a yes/no loop. | def getCageCapacity():
userAnimal = selectAnimal()
cageSize = setCageSize()
if cageSize == 0:
return
elif isValidCageSize(userAnimal, cageSize):
cageCapacity = int(cageSize/animal[userAnimal].getCageSize(1))
print(f"Your cage can hold up to {cageCapacity} {userAnimal.title()}s.")... |
def selectAnimal():
while True:
try:
searchTerm = input("Which animal are you building the cage for? ")
except Exception as detail:
print("Error:", detail)
else:
searchResults = []
for animal in allAnimals:
if searchTerm.lower(... | The code's main task is to determine and display the appropriate environment details for a cage based on the selected animal and cage size, validate the size, warn if invalid, list required terrain details, and recursively allow checking another habitat if requested. | def getCageEnvironment():
userAnimal = selectAnimal()
cageSize = setCageSize()
if cageSize == 0:
return
if not isValidCageSize(userAnimal, cageSize):
print("WARNING: Your cage is too small for this animal.")
details = animal[userAnimal].getTerrainDetails(cageSize)
print(... |
def selectAnimal():
while True:
try:
searchTerm = input("Which animal are you building the cage for? ")
except Exception as detail:
print("Error:", detail)
else:
searchResults = []
for animal in allAnimals:
if searchTerm.lower(... | This function calculates the minimum cage size required for a specified number of a selected animal, ensuring valid user input (1-25 animals). It repeatedly prompts for input until valid, computes the cage size using a predefined method, displays the result, and offers to calculate another cage size. | def getMinCageSize():
userAnimal = selectAnimal()
while True:
try:
numAnimals = int(input(f"How many {userAnimal.title()}s? "))
if numAnimals <= 0 or numAnimals > 25:
raise ValueError()
except ValueError:
print("Error: Quantity must be an inte... |
def batchleastsquares(self, initialdata):
capitalphi = self.populatematrix()
product = np.matmul(capitalphi.transpose(), capitalphi)
self.previousP = np.linalg.inv(product)
Y = self.evaluateY(capitalphi,self.rowlength - 1)
self.previoustheta = np.matmul(self.previousP, np.matmul... | The main task of the code is to compute and store a matrix of model parameters (theta) for each data window using a recursive algorithm. It initializes parameters with a batch least squares estimate, then iteratively updates them for subsequent data points by building the phi matrix, evaluating P, and computing theta. ... | def evaluatemodel(self):
modelparameters = np.matrix(np.zeros((self.numberofeigenvalues, (len(self.data)-self.rowlength+1))))
self.batchleastsquares(self.data[:self.rowlength])
modelparameters[:,0] = self.previoustheta
for i in range(self.rowlength, len(self.data)):
self.phi ... |
def updateScore(self, scoreValue):
self.score += scoreValue
if BONUSLIFE != 0:
self.lifeBonus -= scoreValue # Points deducted from amount needed for bonus life
if self.lifeBonus <= 0:
self.lives += 1
self.lifeBonus = BONUSLIFE + self.lifeBonus
... | The function checks for collisions between the player and interactables, fruits, and ghosts. It updates the score when interactables/fruits are collected, removes them from lists, and triggers ghost flee behavior or life loss based on ghost states, adjusting the ghost bonus multiplier accordingly. | def loopCollisionCheck(self):
# Check to see if player shares a grid with an interactable
for interactable in self.interactables:
if interactable.gridPos == self.player.gridPos:
if interactable.interactableType == 1:
self.ghostBonusMulti = 1
... |
def find_legal_moves(self, location, piece_type):
legal_moves = []
confirmed_legal_moves = []
# todo replace with ternary
color = None
enemy_color = None
if piece_type & Masks.WHITE == Masks.WHITE:
color = Masks.WHITE
enemy_color = Masks.BLACK
... | This function allows a user to move a game piece by determining legal moves, validating input, updating the board state, and handling piece captures. It uses a loop to check for legal moves, confirms valid moves, and updates the game matrix. Temporary fixes and placeholders are included for input handling and capture l... | def user_move_piece(self, location, piece_type):
# displays the correct moves the piece can make
previous_state = copy.deepcopy(self.state1)
making_move = True
legal_moves = self.find_legal_moves(location, piece_type)
light_logic_on(legal_moves)
# Wait for any change in... |
def initialize_extenders():
global bus
global DEVICE_ROW_A
global DEVICE_ROW_B
global DEVICE_ROW_C
global DEVICE_ROW_D
global DEVICE_ROW_E
global DEVICE_ROW_F
global DEVICE_ROW_G
global DEVICE_ROW_H
global IODIRA
global IODIRB
global OLATA
global OLATB
global GPIO... | The main task of the code is to run a game loop for a chess board, continuously displaying the board, checking for piece pickup, processing user input, and updating the board state until the loop terminates. It initializes the chess board, handles input, and manages game interactions in a cycle. | def run_board():
run = True
print("Starting board")
chess_board = ChessBoard()
initialize_extenders()
while run:
chess_board.print_matrix()
chess_board.check_for_pick_up()
sim_input(chess_board.board_matrix)
update_board(chess_board.board_matrix) |
def quadrant(c):
"""Determines the quadrant of given Point in it's base."""
if c.x>=0:
if c.y>=0:
return 1
elif c.y<0:
return 4
elif c.x<0:
if c.y>=0:
return 2
elif c.y<0:
return 3
def next_angle(checklist,step=cc.step):
if ... | This function searches for valid geometric poses by calculating potential positions (Poses) based on angular steps and quadrant checks. It generates point A using trigonometric calculations, adjusts coordinates based on quadrants, and validates configurations via secondary coordinate systems. If valid, it appends poses... | def first_search(c,once=False,step=cc.step):
"""The main search function, returns a list of possible Poses
If once==True, returns only one Pose encapsulated in a list.
Default angle step is cc.step=0.5deg"""
global poseList
poseList=list()
#1 Distance check
if cc.root.dist(c)>3*cc.l:
... |
def quadrant(c):
"""Determines the quadrant of given Point in it's base."""
if c.x>=0:
if c.z>=0:
return 1
elif c.z<0:
return 4
elif c.x<0:
if c.z>=0:
return 2
elif c.z<0:
return 3
def next_angle(checklist,step=cc.step):
if ... | The function `first_search` computes possible 3D poses (positions/orientations) by rotating and checking geometric constraints of a point `c` relative to a reference point. It calculates angles, iterates through configurations, and validates poses using quadrant checks and rotation transformations. If `once=True`, it r... | def first_search(c,once=False,step=cc.step):
"""The main search function, returns a list of possible Poses
If once==True, returns only one Pose encapsulated in a list.
Default angle step is cc.step=0.5deg"""
global poseList
poseList=list()
#1 Distance check
if cc.root.dist(c)>3*cc.l:
... |
def from_B(c,tempB,A,once=False):
#convert point C to point in base z,w
#using vector BC
bc=np.array([c.x-tempB.x,c.y-tempB.y])
#making transition matrix
T=np.array(([tempB.ownBase.x[0],tempB.ownBase.y[0]],[tempB.ownBase.x[1],tempB.ownBase.y[1]]))
#vector BC in base z,w is gotten from equation T... | The function `nextC` searches for the next valid point (C) with minimal movement, prioritizing the current point B, then A, and finally the start. It clears previous pose data, uses helper functions to validate positions, and returns `True` if a valid C is found, otherwise `False`. | def nextC(c,once=False,step=cc.step):
'''Finds the requested next point, with minimal movement.
Search first starts from current point B, if no possible Cs exist, than form A, further from the start'''
global poseList
global poseIndex
#getting all of the Points from the current Pose
curren... |
def from_B(c,tempB,A,once=False):
#convert point C to point in base z,w,v
#using vector BC
bc=np.array([c.x-tempB.x,c.y-tempB.y,c.z-tempB.z])
#making transition matrix
T=np.array(([tempB.ownBase.x[0],tempB.ownBase.y[0],tempB.ownBase.z[0]],[tempB.ownBase.x[1],tempB.ownBase.y[1],tempB.ownBase... | The function `nextC` determines the next valid configuration point (C) with minimal movement by first checking from the current point B, then from A, and finally searching from the start. It clears previous pose data, updates the pose list, and returns `True` if a valid configuration is found, otherwise `False`. The pr... | def nextC(c,once=False,step=cc.step):
'''Finds the requested next point, with minimal movement.
Search first starts from current point B, if no possible Cs exist, than form A, further from the start'''
global poseList
global poseIndex
#getting all of the Points from the current Pose
curren... |
def _add_download_method(self, event):
URL = self.get_download_url(event.url)
name = event.name
def download(path=None):
try:
req = requests.get(URL)
except requests.exceptions.ConnectionError as error:
logger.error('could not get file {!r... | This function processes incoming events by decoding JSON data, parsing the event, handling file-specific logic, and executing an event handler with appropriate arguments. It validates handler inputs/outputs, logs actions, and processes replies if returned. | def _handle_event(self, event, event_handler):
try:
event = json.loads(event)
except json.decoder.JSONDecodeError:
raise ValueError('could not decode chunk')
logger.debug('decoded chunk successfully')
try:
event = parse(event)
except NotImplem... |
def _enrollment(self):
"""Return embedding dictionary
(self.enrollment_set is used for processing)
"""
self.model.eval()
keys = []
embeddings = []
with torch.set_grad_enabled(False):
with self.model.no_sync():
for utt, key in tqdm(self.enrollment_loader, desc='enrollment', ncols=self.args['tqdm_n... | The code evaluates a model's performance on clean and noisy speech data during training. It calculates EER and minDCF metrics for clean data, updates the best EER, and saves the optimal model. If conditions are met, it tests the model across multiple noise levels (0-20 dB) for noise, speech, and music interference, ass... | def test(self, epoch):
# clean test data
self.enrollment_set.Key = 'clean'
self.embeddings = self._enrollment()
if self.args['flag_parent']:
self.cur_eer, min_dcf = self._calculate_eer()
self.logger.log_metric('EER_clean', self.cur_eer, epoch_step=epoch)
print('EER_clean: {}'.format(self.cur_eer*100))
... |
def getcm(filename):
p = PATHDATASETS + filename + '.json'
if os.path.isfile(p) == False:
return None
f = open(p)
return cityjson.reader(file=f, ignore_duplicate_keys=True)
def process_geometry(j, cityobject):
# -- update vertex indices
oldnewids = {}
newvertices = []
for geom i... | The main task of the code is to import and process a CityJSON file into a PostgreSQL database schema, handling spatial transformations (e.g., CRS conversion to EPSG:4326), vertex cleaning, bounding box calculations, and spatial indexing using Hilbert curves. It inserts city objects, metadata, and attributes into databa... | def insert_cityjson(file_name, schema_name):
conn = connect()
cur = conn.cursor()
cm = getcm(file_name)
cm.remove_duplicate_vertices()
cm.remove_orphan_vertices()
cm.update_bbox()
data = cm.j
count_cityobjects = len(data['CityObjects'])
# store cityjson table
metadata = None
... |
def seek(self, target_pos):
dist = self.pos - target_pos
desired_vel = dist.normalize() * self.max_speed
return desired_vel.rotate(180)
def avoid_obstacles(self):
space = 20
ext_rad = self.r + space
# Detection box
angle = self.vel.angle_to(Vector2(1, 0))
... | The main task of the code is to compute and return a normalized velocity vector for an agent based on a specified behavior, combining movement strategies like seeking, fleeing, pursuing, evading, wandering, hiding, and obstacle/wall avoidance. The function dynamically selects behavior logic, adjusts movement patterns o... | def get_vel(self, behavior):
if behavior == 0:
return (self.seek(self.game.player.pos) + 10 * self.avoid_obstacles() + 6 * self.avoid_walls()).normalize()
elif behavior == 1:
return (self.pursuit(self.game.player) + 10 * self.avoid_obstacles() + 6 * self.avoid_walls()).normalize(... |
def conv_layer(self, inputs, num_filters, filter_size, strides, activation=None,
transpose=False, w_size=None, h_size=None):
"""
Add a convolutional layer to the network.
:param inputs: Inputs to the conv layer.
:param num_filters: Num of filters for conv layer.
... | This code implements a conditional GAN generator that combines random noise (z_inputs) with conditional images (conditional_input) to generate new images. It processes inputs through an encoder with convolutional layers, expands noise vectors to match decoder dimensions, and uses a decoder with transposed convolutions ... | def __call__(self, z_inputs, conditional_input, training=False, dropout_rate=0.0):
"""
Apply network on data.
:param z_inputs: Random noise to inject [batch_size, z_dim]
:param conditional_input: A batch of images to use as conditionals [batch_size, height, width, channels]
:para... |
def get_piece(self, pos):
"""
Return the piece at the given square of the board.
Args:
pos: A tuple representing the position of a given square. The first
number is the row, the second is the column.
Returns:
A string representing the piece at a give... | This function moves a chess piece from a start position to an end position, checks if the move is legal (unless undoing), updates the board by replacing the start position with a blank and placing the piece at the end, captures the target piece (including blanks for undo functionality), records the move, and switches t... | def move_piece(self, start_pos, end_pos):
"""
Move a specified piece to a new location.
Additionally, if a move is not an undo move, run the legal move checker.
Args:
start_pos: A tuple representing the start position of the piece
being moved.
end_po... |
def add_controls():
while 1:
qs=open('chatboth.txt','a')
qus=[]
cu=1
x=input('\nAsk/Questions ')
if x=='':
break
qus.append(x)
while x:
x=input('ans'+str(cu)+':')
qus.append(x)
cu+=1
aa=... | The main task of the code is to display a chat bot menu, accept user input for options (add question or chat), and call corresponding functions (add_controls or chat_both) based on the selection, creating a simple interactive chatbot interface. | def main():
if __name__=="__main__":
print('''
##############################################
CHAT BOT MAIN MENU
##############################################
1. Add Question
2. chat both
''')
inp=input('Enter the option:')
if inp=="1":
add... |
def extract_faces(frame : Frame) -> List[Face]:
face_detection = get_face_analyser().get('face_detection')
face_detection_width, face_detection_height = map(int, facefusion.globals.face_detection_size.split('x'))
frame_height, frame_width, _ = frame.shape
temp_frame = resize_frame_dimension(frame, face_detection_wi... | The main task of the code is to retrieve and process faces from a frame by either using a cached result or extracting faces directly. It applies sorting and filtering based on global parameters like direction, age, and gender, then returns the processed list of faces or an empty list on error. | def get_many_faces(frame : Frame) -> List[Face]:
try:
faces_cache = get_faces_cache(frame)
if faces_cache:
faces = faces_cache
else:
faces = extract_faces(frame)
set_faces_cache(frame, faces)
if facefusion.globals.face_analyser_direction:
faces = sort_by_direction(faces, facefusion.globals.face_ana... |
def find_gamma_and_epsilon_rates(matrix: Iterable[Tuple[str]]) -> Tuple[str]:
gamma_r = epsilon_r = ""
for bits in matrix:
g, e = find_gamma_and_epsilon(bits)
gamma_r += g
epsilon_r += e
return int(gamma_r, 2), int(epsilon_r, 2)
def find_oxygen_rate(matrix_input: Iterable[Tuple[str... | The code reads binary data from a file, processes it to calculate the power consumption by determining gamma and epsilon rates, and computes the life support rating by finding oxygen and CO₂ rates. It transposes the binary matrix, splits it for parallel processing, and applies specific functions to derive the required ... | def main():
with open("../data/day3", "r") as inputs:
list_of_strings = inputs.readlines()
matrix = [
[
str(digit) for digit in binary.strip()
] for binary in list_of_strings
]
t_matrix_p1, t_matrix_p2 = tee(zip(*matrix))
gamma_r, ep... |
def compute_total_pages(total_records, size):
return min(math.ceil(total_records / size), PAGE_NUMBER_CAP)
def page_to_cursor_object(page, current_page, size):
return {
"cursor": page_to_cursor(page, size),
"page": page,
"is_current": current_page == page,
}
def page_cursors_to_array... | The function generates paginated navigation cursors based on the current page, total records, and max pages limit. It constructs a dictionary with 'around' (nearby pages), 'first', 'last', 'previous', and 'next' page links, adjusting display logic based on proximity to start/end of results. It handles edge cases like n... | def create_page_cursors(page_options, total_records, max_pages=5):
current_page = page_options["page"]
size = page_options["size"]
# If max_pages is even, bump it up by 1, and log out a warning.
if max_pages % 2 == 0:
print(f"Max of {max_pages} passed to page cursors, using {max_pages + 1}")
... |
def __explore(self, entry, par_loops, visited, waiting, l_set, done):
stack = []
if entry in self.link_out:
for n in self.link_out[entry]:
stack.append((entry, n))
visited.add(entry)
is_sub_loop = set()
while 1:
if self.__until_stack_em... | The code detects loops in a control flow graph by exploring nodes, identifying infinite and false loops, removing invalid loops, and determining loop start/end nodes for analysis. It calculates loop properties, filters non-loop nodes, and logs results with timing. | def __loop_detection(self, ctx, entry):
start = time.clock()
self.__explore(entry, set(), set(), {}, None, set())
self.__search_equiv_loops()
self.__search_false_loops()
for k in self.false_loops:
del self.loops_all[k]
del self.loops_set[k]
# C... |
def update_board_wall(self, move):
wall_type, center_row, center_col = move
previous = self.board[center_row][center_col], self.board[center_row][center_col + 1], self.board[center_row + 1][center_col]
if wall_type == 'H':
if self.board[center_row][center_col] == False... | The function `get_legal_moves` generates all valid moves for the current player, including directional movements (U/D/L/R) and wall placements (H/V). It ensures wall placements do not block both players' paths to their respective goals. It checks board boundaries, existing walls, and simulates wall placement to verify ... | def get_legal_moves(self):
moves = []
current_position = self.player_positions[self.players[self.ply]]
if self.walls[self.players[self.ply]] > 0:
for i in range(0, self.board_size - 1):
for j in range(0, self.board_size - 1):
# Check if a wall can... |
def timestep(self, tstep, volume):
"""Timestep forward
:param tstep: time step
:type tstep: float
:param volume: execution volume
:type volume: int
"""
self.update_price()
self.execute_metaorder(volume)
self.stochastic_timestep()
self.upd... | This function updates an animation by adjusting the heights of ask and bid volume bars based on current data, and updates vertical lines indicating best ask/bid prices. It returns all graphical elements (bars and lines) requiring redraw for the animation frame. | def update_animation(self, tstep, volume):
"""Update function called by matplotlib's FuncAnimation.
Animation counterpart to self.timetsep(tstep, volume)
"""
self.timestep(tstep, volume)
# Update bars
for index in range(self.Nx):
self.ask_bars[index].set_hei... |
def e_t(self, r):
e_temp = np.zeros((2, self.N))
if self.wallshere == False:
for i in range(self.N):
e_temp[:, i] = self.e_0(r[:,i], i)
else:
for i in range(self.N):
j = self.nearest_wall(r[:,i])
e_temp[:, i] = self.directi... | This function calculates acceleration (acc) by combining three terms: a velocity-dependent term, and two force terms (f_ag and f_wa) normalized by mass (m). It uses input parameters r (position) and v (velocity), along with internal variables e_temp, tau, v_0, and m to compute the resultant acceleration. | def f(self, r, v):
e_temp = self.e_t(r)
acc = (self.v_0 * e_temp - v) / self.tau + self.f_ag(r, v) / self.m + self.f_wa(r, v) / self.m
return acc |
def create_board():
board = numpy.zeros((3,3), dtype = int)
return(board)
def random_place(board, player):
possible_places = possibilities(board)
curr_location = random.choice(possible_places)
board[curr_location] = player
return board
def evaluate(board):
winner = 0
for player in [1, 2... | The code simulates a two-player game where players take turns placing their marks randomly on a board until a winner is determined. The `play_game` function initializes the board, alternates turns between players 1 and 2, updates the board with random placements, checks for a winner after each move, and returns the win... | def play_game():
board = create_board()
winner = 0
while winner == 0:
for player in [1,2]:
board = random_place(board, player)
winner = evaluate(board)
if winner != 0:
break
# print(board)
return winner |
def setCamera(self):
cam = bpy.context.scene.camera
cam.data.sensor_fit = 'VERTICAL'
f = 2*cam.data.lens/cam.data.sensor_height
mat = cam.matrix_world
self.data.camera.position = mat.to_translation()
self.data.camera.toWorld = mat.to_3x3()
def addMesh(self, key):
obj = bpy.data.objects[key]
if not len(... | The code's main task is to create a 3D scene by adding visible meshes and spheres from Blender's data, then assigning target IDs based on material bindings. It sets the camera, checks object existence/visibility, adds valid objects, and stores target IDs in self.data.targetIDs for later use. | def create(self, spheres, meshes, targets):
self.setCamera()
bobjects = bpy.data.objects
for m in meshes:
if m in bobjects.keys() and not bobjects[m].hide_get():
self.addMesh(m)
for s in spheres:
if s in bobjects.keys() and not bobjects[s].hide_get():
self.addSphere(s)
tids = []
for t in ... |
def list_dataset_in_space(key, api_url, space_id):
"""
"""
url = f"{api_url}/spaces/{space_id}/datasets"
return _get(url, key)
def _post(url, key, data=None, json_data = None, content_type='application/json'):
"""
POST
"""
#print (f"POST: {url} {data} {content_type}")
return requests... | The function creates a dataset by first checking for duplicates in a specified space. If no duplicate is found, it sends a POST request to create an empty dataset and adds it to the space. It returns the dataset details if successful, otherwise raises an error. | def create_dataset(key, api_url, space_id, dataset_name, check_duplicate=True):
"""
curl -X POST "https://xxxx/api/datasets/createempty"
-H "accept: */*" -H "Authorization: Basic xxxx="
-H "Content-Type: application/json" -d "{\"name\":\"test\"}"
"""
if check_duplicate:
res = list_d... |
def get_file_list(key, api_url, dataset_id):
"""
Get list of files in a dataset as JSON object.
Keyword arguments:
connector -- connector information, used to get missing parameters and send status updates
host -- the clowder host, including http and port, should end with a /
key -- the secret k... | This function uploads a specified file to a dataset on a server via a POST request, checking for duplicates first. If no duplicate is found, it sends the file data in multipart/form-data format, then optionally moves the uploaded file to a specified parent folder. The function handles parameters like API key, dataset I... | def add_server_file(key, api_url, dataset_id, file_path, parent_folderid=None, extract=True, check_duplicate=True):
"""
Add files already in server side
curl -X POST "https://xxxx/api/uploadToDataset/5f3f38e2e4b099e94537da9c?extract=true"
-H "accept: */*"
-H "X-API-Key: 4268f72d-0633-4677-9ecc-4... |
def get_file_list(key, api_url, dataset_id):
"""
Get list of files in a dataset as JSON object.
Keyword arguments:
connector -- connector information, used to get missing parameters and send status updates
host -- the clowder host, including http and port, should end with a /
key -- the secret k... | This function uploads a local file to a specified dataset via an API, checking for duplicates first. If the file exists, it returns the existing ID; otherwise, it uploads the file, extracts it if enabled, and moves it to a parent folder if specified. It handles errors like file absence and API response status. | def upload_client_file(key, api_url, dataset_id, file_path, parent_folderid=None, extract=True, check_duplicate=True):
"""
Add files not in server side
Upload flie to a dataset
"""
if check_duplicate:
ds_files = get_file_list(key, api_url, dataset_id)
if ds_files.ok:
for ... |
def _generate_registers_enum(self):
self._output.append('\n#[derive(Debug, Clone, Copy)]')
self._output.append('pub enum Register {')
self._output.indent()
registers = self._config.registers()
for regname in registers:
self._output.append(f'{regname.capitalize()},')
... | The `generate` method orchestrates the creation of essential data structures by invoking four helper methods: generating register enums, instruction enums, constants, and symbol enums. This likely prepares a system for processing or simulating operations by defining structured representations of hardware components, co... | def generate(self):
self._generate_registers_enum()
self._generate_instructions_enum()
self._generate_constants()
self._generate_symbol_enums() |
def epochAction(self, action, loader):
isBackward = True if action == "train" else False
GradSelection = Grad if isBackward else torch.no_grad
totalLoss, totalCorrect, totalLen = 0, 0, 0
batchLoader = tqdm(loader)
if isBackward:
self.model.train()
else:
... | This method trains a neural network for a specified number of epochs, performing training and validation phases each epoch. It tracks training and validation losses, adjusts the learning rate via a scheduler, and saves the model checkpoint if the validation loss improves. The best model is stored with a filename indica... | def trainEpochs(self, start, end):
self.epoch = start
self.endEpoch = end
for epoch in range(start, end):
self.epoch = epoch
trainLoss, tranCorrect = self.epochAction("train", self.trainloader)
self.trainLosses.append(trainLoss.item())
if (epoch + ... |
def getCheckpointFolder(self):
return PATHS.CHECKPOINTS / f"X{self.configs['scaleFactor']}" / self.getModelName()
def loadParams(self, fileP):
info(f"load model from {fileP.name}")
saveObject = torch.load(fileP)
self.model.load_state_dict(saveObject["model"])
self.scheduler.load_... | This method loads the best model checkpoint from the specified folder. It searches for a file matching "best*.pth", loads its parameters if found, otherwise warns about the missing file and falls back to a default load. | def loadBest(self):
modelFile = getFile(self.getCheckpointFolder(), "best*.pth")
if modelFile:
self.loadParams(modelFile)
else:
warn(f"best model not found under {self.getCheckpointFolder()}\nIs 'bestXXX.pth' exist?")
self.load() |
def printRecords(self):
"""
Prints all records
"""
records = self._service.getAll()
console = Console()
table = self.createTable()
for record in records: # Iterates through each row then calls CSVRow print function for that object's instance
record.ge... | The function `processResponse` routes user input to corresponding actions by checking the `inputMenu` value against predefined options. It triggers methods like `printRecords`, `reload`, `insert`, `update`, `delete`, `saveToDisk`, or exits based on the input. If invalid, it prompts the user for a valid option. | def processResponse(self, inputMenu):
"""
Based on input, triggers the appropriate function
"""
if inputMenu == self._SHOW_ALL:
self.printRecords()
elif inputMenu == self._RELOAD:
self.reload()
elif inputMenu == self._SHOW_ONE:
self.vie... |
def pauseMovie(self):
"""Pause button handler."""
if self.state == self.PLAYING:
#print(self.waitCommand.is_set())
self.waitCommand.wait()
self.waitCommand.clear()
self.getFrame.set()
self.sendRtspRequest(self.PAUSE)
def exitClient(self):
"""Stop button handler."""
if self.state == self.READY or ... | This code handles explicitly closing the GUI window by pausing the video, prompting user confirmation, and either closing the RTSP connection and destroying the window if in initial state, or exiting the client otherwise. If canceled, it resumes playback. | def handler(self):
"""Handler on explicitly closing the GUI window."""
self.pauseMovie()
if tkinter.messagebox.askokcancel("WARNING!!!", "Are you sure you want to stop watching your video and exit?"):
if self.state == self.INIT:
self.rtspSocket.close()
self.master.destroy()
self.startRecvRtspReply.... |
def get_drawing_frame(self, mask, frame, color):
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(contours) > 0:
max_contour = max(contours, key=cv2.contourArea)
M = cv2.moments(max_contour)
if M["m00"] != 0:
cx =... | The code generates a composite frame by processing and combining red, blue, and green camera inputs through nested frame-processing functions, ultimately returning a synthesized drawing frame. | def get_frames(self):
return self.get_drawing_frame(self.get_mask_frame(self._red),
self.get_frame(Camera._blue, self.get_frame(Camera._green)),
self._red) |
def select_parents(population):
total_fitness = sum([fitness_func(schedule) for schedule in population])
probabilities = [fitness_func(
schedule) / total_fitness for schedule in population]
parent1, parent2 = random.choices(population, probabilities, k=2)
return parent1, parent2
def crossover(sc... | The main task of the code is to generate a new child individual in a genetic algorithm by selecting two parents from the population, performing crossover to combine their genetic material, and applying mutation with a 90% probability to introduce diversity. The function returns the newly created child for potential inc... | def create_child(population):
parent1, parent2 = select_parents(population)
child = crossover(parent1, parent2)
if random.random() < 0.9 :
mutate(child)
return child |
def _initialize_metrics(self):
"""
Sets up metrics to be stored.
"""
initial_metrics = np.full((self.num_trials, self.max_iters), np.inf)
self.lmls_labeled = np.copy(initial_metrics)
self.vars_unlabeled = np.copy(initial_metrics)
self.losses_semisup = np.copy(init... | The main task of the code is to run multiple training trials, each involving training a model, tracking metrics, checking learning progress, and repeating trials if learning conditions are not met. It initializes metrics, iterates over a specified number of trials, executes training, checks learning status, and saves r... | def run_trials(self):
"""
Runs multiple trials of training.
"""
self._initialize_metrics()
self.trial = 0
self.check_learning_counter = 0
while self.trial < self.num_trials:
t0 = time.time()
print('Starting trial {}:'.format(self.trial + 1)... |
def end_game(board):
return winning_position(board,MAX_PLAYER) or winning_position(board,MIN_PLAYER)
def heuristic(board):
if winning_position(board, MAX_PLAYER):
score = +1
elif winning_position(board, MIN_PLAYER):
score = -1
else:
score = 0
return score
def available_moves... | This function implements the minimax algorithm to determine the optimal move for a player in a turn-based game. It recursively evaluates all possible moves, alternating between maximizing and minimizing players. The best move is selected based on a heuristic score of the board state, with depth limiting recursion. It r... | def minimax(board, depth, player):
if player == MAX_PLAYER:
best = [None, None, -10000]
else:
best = [None, None, +10000]
if depth == 0 or end_game(board):
score = heuristic(board)
return [None, None, score]
for cell in available_moves(board):
x, y = cell[0], ce... |
def available_moves(board):
moves = []
for row_ind, row in enumerate(board):
for col_ind, col in enumerate(row):
if col == 0:
moves.append([row_ind, col_ind])
return moves
def end_game(board):
return winning_position(board,MAX_PLAYER) or winning_position(board,MIN_PLA... | The function `dumb_computer` selects a random available move on a 3x3 board for the given player, updates the board with the player's symbol, and introduces a 1-second delay. It checks if the game has ended or no moves remain before proceeding. | def dumb_computer(player):
depth = len(available_moves(BOARD))
if depth == 0 or end_game(BOARD):
return
options = [0, 1, 2]
x = choice(options)
y = choice(options)
BOARD[x][y] = player_to_letter(player)
time.sleep(1) |
def available_moves(board):
moves = []
for row_ind, row in enumerate(board):
for col_ind, col in enumerate(row):
if col == 0:
moves.append([row_ind, col_ind])
return moves
def end_game(board):
return winning_position(board,MAX_PLAYER) or winning_position(board,MIN_PLA... | The function `smart_computer` determines the next move for a player in a game (likely Tic-Tac-Toe) by evaluating available moves. If no moves remain or the game ends, it exits. For an empty board (depth 9), it randomly selects a move. Otherwise, it uses the `minimax` algorithm to choose the optimal move. It updates the... | def smart_computer(player):
depth = len(available_moves(BOARD))
if depth == 0 or end_game(BOARD):
return
options = [0, 1, 2]
if depth == 9:
x = choice(options)
y = choice(options)
else:
move = minimax(BOARD, depth, player)
x, y = move[0], move[1]
B... |
def end_game(board):
return winning_position(board,MAX_PLAYER) or winning_position(board,MIN_PLAYER)
def available_moves(board):
moves = []
for row_ind, row in enumerate(board):
for col_ind, col in enumerate(row):
if col == 0:
moves.append([row_ind, col_ind])
return m... | The code implements a tic-tac-toe game where a human player competes against a computer. The player selects 'Easy' or 'Hard' mode to determine the computer's strategy. The game loop alternates human and computer moves, checks for wins/draws, displays the board, and uses random messages for computer responses. It ends w... | def tic_tac_toe():
mode = input("Write 'Easy' to play a dumb computer and 'Hard' to play a smart one: \n")
computer_talking = ["You're not gonna win :)", "mfakkar halak adde?", "AI never loses!"]
while not end_game(BOARD) and len(available_moves(BOARD)) != 0:
human(MIN_PLAYER)
print(np.array... |
def parse_args(args=None):
parser = ThrowingArgumentParser(description='Packer wrapper')
sub_parsers = parser.add_subparsers(dest='cmd', help='sub-command help')
parser_convert = sub_parsers.add_parser('convert', help='Convert between JSON and YAML')
parser_convert.add_argument('template', help='JSON or... | The main task of the code is to parse command-line arguments, execute a command via `run_cmd`, and handle errors: it catches `ArgumentParserError` by launching a packer and `KeyboardInterrupt` by returning a cancelled exit status. The nested try blocks ensure robust argument handling and graceful interruption response. | def main():
try:
try:
args, parser_convert = parse_args()
return run_cmd(args, parser_convert)
except ArgumentParserError as e:
launch_packer()
except KeyboardInterrupt as e:
return Exit.CANCELLED |
def boundary_conditions(x,
y,
Nx,
Ny):
"""
Function to define the boundary conditions of the Nx*Ny matrix. If a border is reached, one goes
to the border on the oposite side.
Parameters
----------
x : TYPE int
DES... | The main task of the code is to update the order parameter $ c $ (composition matrix) by solving the Cahn-Hilliard equations over a time interval $ dt $, simulating two-dimensional spinodal decomposition. It calculates chemical potential gradients, diffusion terms, and mobility effects to compute the time evolution of ... | def update_order_parameter(c,
c_t,
Nx,
Ny,
A,
dx,
dy,
T,
La,
Diff_A,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.