dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def create_population(n):
population = []
for i in range(POPULATION_SIZE):
individual = list(range(n))
random.shuffle(individual)
population.append(individual)
return population
def fitness(individual, distances):
total_distance = 0
for i in range(len(individual)):
to... | This code solves the Traveling Salesman Problem (TSP) using a genetic algorithm. It evolves a population of potential paths over multiple generations, selecting and recombining the fittest individuals (shortest routes) to iteratively improve solutions. The best path found is adjusted to form a closed loop, and the func... | def tsp_ga(distances):
n = len(distances)
population = create_population(n)
best_path = None
best_dist = -1
for i in range(GENERATIONS):
population_fitness = [fitness(individual, distances) for individual in population]
max_index = np.argmax(population_fitness)
max_fitness = ... |
def num_wins(self, col):
"""
designed for score based events with multiple entrants
every player that you score higher than, counts as a win (1 point)
players that score higher than you count as a loss (0 points)
players that tie your score you will get half (.5 points)
... | This function processes player Elo ratings by calculating wins, initializing starting Elo values (defaulting to 1500 for new players), collecting competitor Elo data, and updating Elo scores using the `get_new_elo` method. It ensures all players' Elo ratings are adjusted based on their game outcomes and competitors' cu... | def process_elo(self, df):
"""
takes in a df of score objects
df.index = player names
df.column (one column only) player scores
1) gets number of wins (1=win, 0=loss, .5=draw)
2) initialize starting_elo and elo_comp (list of all compteitors elos) columns
Loop th... |
def set_key(self, key):
self._key = key
def process_elo(self, df):
"""
takes in a df of score objects
df.index = player names
df.column (one column only) player scores
1) gets number of wins (1=win, 0=loss, .5=draw)
2) initialize starting_elo and elo_comp (list o... | The code processes a DataFrame to update ELO ratings for players based on scores from unique game dates. It filters data by each date, removes duplicates, sets player names as indexes, calculates ELO changes using `process_elo`, displays updated ratings, and tracks completed dates to avoid reprocessing. | def run(self, df, score_column):
"""
takes in a pd.df and we need 3 required columns
1)date: can be upper or lower case (we will change to lower) any date format works
2)player: name of player, needs to be the same each time, as well as unique
3)score_column: can be n... |
def read_config(config_yaml, debug):
with pelican.utils.pelican_open(config_yaml) as text:
config_data = yaml.safe_load(text)
if debug:
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(config_data)
return config_data
def process_eccn(fname, debug):
if debug:
prin... | The function reads ASF_DATA configuration from Pelican settings, processes its contents (including ECCN, Twitter, blog, release, URL, and file data), injects processed data into metadata, and debug-prints metadata structure and values. It handles specialized data types with specific processing functions, then outputs m... | def config_read_data(pel_ob):
print('-----\nasfdata')
asf_data = pel_ob.settings.get('ASF_DATA')
if not asf_data:
print('This Pelican installation is not using ASF_DATA')
return
debug = asf_data['debug']
if debug:
for key in asf_data:
print(f'config: [{key}] =... |
def on_session_started(session_started_request, session):
print("Starting new session.")
def on_launch(launch_request, session):
return get_welcome_response()
def on_intent(intent_request, session):
intent = intent_request["intent"]
intent_name = intent_request["intent"]["name"]
if intent_name == "... | This code handles Alexa skill requests by validating the application ID, initializing new sessions, and routing requests to appropriate handlers for launch, intent, or session end events. | def lambda_handler(event, context):
#TODO(rwales): Change this
if (event["session"]["application"]["applicationId"] != "amzn1.ask.skill.51ab8847-6dd1-425e-a4b4-82cbcd200789"):
raise ValueError("Invalid Application ID")
if event["session"]["new"]:
on_session_started({"requestId": event["... |
def mac_to_two(mac):
"""
Convert MAC format encoding into TWO format
This is an inverse of two_to_mac done with remarkably little understanding.
It seems to assume that 'reverse cycles' occur in odd numbered images which
seems unreasonable, but I can't see an obvious way to detect this otherwise
... | The main task of the code is to decode vessel locations from encoded data by validating input dimensions, generating encoding matrices (TWO/MAC), processing modulation matrices, and performing iterative decoding inference on each time interval (PLD) with fixed or adjusted vessel positions. It logs process steps, handle... | def _decode(wsp):
if wsp.veslocs.ndim != 2 or wsp.veslocs.shape[0] != 2:
raise ValueError("Vessel locations should have two rows (XY co-ordinates) and one column per vessel")
wsp.log.write("\nPerforming vessel decoding\n")
wsp.log.write(" - Initial vessel locations:\n")
wsp.log.write(" X:... |
def _decode(wsp):
if wsp.veslocs.ndim != 2 or wsp.veslocs.shape[0] != 2:
raise ValueError("Vessel locations should have two rows (XY co-ordinates) and one column per vessel")
wsp.log.write("\nPerforming vessel decoding\n")
wsp.log.write(" - Initial vessel locations:\n")
wsp.log.write(" X:... | (The code processes vessel-encoded ASL data by decoding vessel locations, modeling perfusion parameters for each vessel across PLDs, and combining results. It uses initial vessel locations and an encoding matrix to generate sub-workspaces with perfusion-weighted signals, vessel probabilities, and parameter maps in nati... | def run(wsp):
"""
Do vessel decoding and modelling on vessel-encoded ASL data
:param wsp: Workspace object
Required workspace attributes
-----------------------------
- ``asldata`` - ASLImage containing vessel-encoded data
- ``veslocs`` - Initial vessel locations as 2xN matrix
... |
def draw_board(self):
self.draw_background()
self.draw_lines()
pygame.display.update()
def draw_piece(self, x, y, send_move=True):
coord = (x * self.size + self.size//2, y * self.size + self.size//2)
x_coord = (coord[0]*self.cols-1)//self.w
y_coord = (coord[1]*self.rows-1... | The code's main task is to manage a game loop that continuously draws the game board, processes tasks (coordinates) from a queue to update the board, handles user events via `event_handler`, and terminates when the game ends, calling `quit_game` to conclude the session. | def play(self):
self.draw_board()
can_play = True
while not self.game_over:
if not tasks.empty():
can_play = True
msg = tasks.get()
x, y = msg
self.draw_piece(x, y, False)
for event in pygame.e... |
def load_data():
"""
Load and prepare the data.
Returns:
data (pd.DataFrame): The preprocessed data.
"""
# Load data
data = get_data()
# Preprocess data
data = transform_data(data)
return data
def get_summary(data):
"""
Get a complete summary of data.
Args:
... | (The main task of the code is to perform Exploratory Data Analysis (EDA) by loading dataset, generating summaries (if verbose), exploring data, extracting positive cases (if verbose), and concluding with "Done!". It executes data analysis steps conditionally based on the `args.verbose` flag.) | def main():
"""Run the EDA."""
# Load data
data = load_data()
# Get summary
if args.verbose:
print(get_summary(data))
# Explore data
explore_data(data)
# Get positives dataframe
if args.verbose:
print(get_positives(data))
print("Done!") |
def decrement_quality_if_not_in_catalog(self, item: Item) -> Item:
if self.__is_item_not_in_catalog(item):
self.decrement_quality(item)
return item
def __update_based_on_catalog(self, item: Item, catalog: ItemCatalog):
if catalog == ItemCatalog.Backstage:
if item.name == ... | The code updates an item's quality and sell_in attributes based on catalog rules. It first reduces quality if the item isn't in any catalog, then applies catalog-specific updates iteratively, and finally adjusts the item if its sell_in value drops below zero, ensuring proper degradation logic for inventory management. | def update_item(self, item: Item):
self.decrement_quality_if_not_in_catalog(item)
for cat in ItemCatalog: self.__update_based_on_catalog(item, cat)
self.update_item_if_sell_in_below_zero(item) |
def _read_input(self, prompt, *, choices=None, lowercase=True):
while True:
value = input(prompt).strip()
if lowercase:
value = value.lower()
if choices and value not in choices:
print(f'Invalid choice, expected one of {", ".join(repr(c) for c ... | This function allows users to program scenes by assigning them to sliders. It disables the mixer, lets users set a scene or select a slider, checks for existing assignments, and confirms overrides. Scenes are stored in the mixer, with options to quit or continue. The mixer state is restored upon exit. | def _program_scene(self):
print('****** Entering scene programming ******')
print('')
scene = None
mixer_prev = self.mixer.enable
self.mixer.enable = False
while True:
if scene is None:
print('Set the scene you want and hit Enter (or [Q]uit)')
... |
def _read_input(self, prompt, *, choices=None, lowercase=True):
while True:
value = input(prompt).strip()
if lowercase:
value = value.lower()
if choices and value not in choices:
print(f'Invalid choice, expected one of {", ".join(repr(c) for c ... | This code runs a user interface for controlling DMX data via a menu, allowing users to print data, program scenes, toggle mixer status, save configurations, or quit. It subscribes to DMX updates, processes user choices, and handles saving changes before exiting. | def run(self):
try:
self.controller.subscribe('ui-control', self._on_dmx_data)
while True:
print('******** Main menu ********')
mixer_status = 'enabled' if self.mixer.enable else 'disabled'
print('You can do the following:')
... |
def calculate_edam_topic_statistics(tools: list) -> dict:
"""
Calculate the statistics for EDAM topics.
:param tools: The tool list.
:return: The dictionary with the terms, the IDs and counts for strict (Only the specific term)
and total (for parent terms).
"""
# Create the dictionary t... | The main task of the code is to process a list of tools by cleaning and analyzing their EDAM topic statistics, generate dataframes with varying cutoffs and depths, and create multiple visualizations (plots) to represent the statistics for different parameters like "Total" and "Strict" counts. The function organizes res... | def calculate_statistics(raw_tools: list, collection_name: str):
"""
Calculate the statistics (Main function).
:param raw_tools: The raw list of tools.
:param collection_name: The name of the collection.
:return:
"""
# Clean the list
drop_false = lambda path, key, value: bool(value)
... |
def check_goal(self, goal):
if not (goal and goal.via_points):
self.log_message('No via points provided! This service will be aborted!')
self._as.set_aborted()
return False
return True
def log_message(self, message):
rospy.loginfo(str(anm.tag_log(mess... | The code executes a control callback by validating the goal, generating feedback, logging progress, navigating through specified via points, and marking the task as succeeded with the feedback. | def execute_callback(self, goal):
if not self.check_goal(goal):
return
feedback = ControlFeedback()
self.log_message('Server is controlling...')
self.navigate_through_points(goal.via_points, feedback)
self.set_succeeded(feedback) |
def extract_actions(self, action_list):
action_each_agent = []
time_till_next_control_each_agent = []
all_idx = []
ratio = np.sum(self.state_each_agent[:, 1:3], axis=1) / (
sum(np.sum(self.state_each_agent[:, 1:3], axis=1)) + 1e-10)
if self.weighted_action: # r... | The `step` method processes agent actions, simulates environment dynamics, computes rewards, and updates observations. It handles different configurations (e.g., 'pomfc', 'na_dec') to generate observations based on true states, belief particles, or channel data. It updates time, checks episode termination, and returns ... | def step(self, action_list):
if self.config in ('rnd', 'a1', 'thr'):
action_each_agent = action_list[0]
time_till_next_contol_each_agent = action_list[1]
else:
action_each_agent, time_till_next_contol_each_agent = self.extract_actions(action_list)
reward, mean... |
def get_saved_num_batches(self):
return self.__saved_checkpoint_batch.item()
def do_forward_batch_and_get_loss(self, examples_per_batch, is_training):
if is_training is True:
self.train()
else:
self.eval()
#loss_function = torch.nn.MSELoss()
loss_... | This code trains a neural network model using batched data, optimizing parameters with Adam optimizer. It iterates through batches, computes training loss, updates weights via backpropagation, and tracks elapsed time and speed. After each batch, it saves model checkpoints and generates synthetic data from gold-standard... | def train_model(self, num_batches, examples_per_batch, save_every, lr) :
optimizer = optim.Adam(self.parameters())
#optimizer = optim.SGD(self.parameters(), lr, momentum=0.9)
for p in optimizer.param_groups : p['lr'] = lr
start = time.time()
for batch in range(self.get_s... |
def get_saved_num_batches(self):
return self.__saved_checkpoint_batch.item()
def get_initial_state(self, examples_per_batch) :
#(cell state vector, hidden (output) state vector)
# first argurment is num_layers
# For LSTM
return (torch.zeros(self.num_lstm_layers, examples_per_batc... | This code trains a neural network model using batches of examples, optimizing parameters with Adam optimizer. It iterates over batches, computes loss, performs backpropagation, updates weights, tracks training time, and saves checkpoints periodically while generating samples. | def train_model(self, num_batches, examples_per_batch, save_every, lr) :
optimizer = optim.Adam(self.parameters())
#optimizer = optim.SGD(self.parameters(), lr, momentum=0.9)
for p in optimizer.param_groups : p['lr'] = lr
start = time.time()
#todo: how often to init stat... |
def sliceData(data: pd.DataFrame, printHeading=True, changeColor=False):
if printHeading:
printSeparation('Slicing The Required Data', changeColor)
return data[requiredFeatures]
def processAndModifyData(data: pd.DataFrame, printHeading=True, changeColor=False):
if printHeading:
printSeparat... | The main task of the code is to load and preprocess a dataset, split it into training and test sets, train a linear regression model on the training data, evaluate its accuracy, and calculate the mean squared error (MSE) for predictions on the test set. The code includes data cleaning, feature selection, model training... | def main():
os.system('cls')
# printSeparation('Loading Data')
data = pd.read_csv(dataFile, sep=',')
# print(data.head())
# If There is a NAN value in the .csv file; .dronna() Drops All the nan values and returns the new dataset
# print(data.isnull().sum())
# data = data.dropna()
# prin... |
def cuadradoBajoAtaque(self, f, c):
self.movimientoBlanca = not self.movimientoBlanca
movEnemigo = self.traerMovimientosPosibles()
self.movimientoBlanca = not self.movimientoBlanca
for movimiento in movEnemigo:
if movimiento.filaFinal == f and movimiento.columnaFinal == c:
... | This method checks if a square is under attack and returns if so. It then generates castling moves for the king or queen side based on the current player's turn and enroque status, adding valid moves to the provided list. | def movimientosEnroque(self, f, c, movimientos):
if self.cuadradoBajoAtaque(f, c):
return
if (self.movimientoBlanca and self.enroque.ReyBlanco) or (
not self.movimientoBlanca and self.enroque.ReyNegro):
self.traerMovimientosReyAdyacenteTorre(f, c, movimientos)
... |
def validarClavadasyJaques(self):
clavadas = []
posiblesJaques = []
enJaque = False
if self.movimientoBlanca:
colorEnemigo = "n"
colorAliade = "b"
filaInicial = self.ubicacionReyBlanco[0]
columnaInicial = self.ubicacionReyBlanco[1]
... | This function generates valid chess moves for the current player, considering check status, piece constraints, and castling. It filters moves to escape check if applicable, checks for checkmate/stalemate, and includes castling moves when allowed. The result is a list of legal moves, updating game states like checkmate ... | def traerMovimientosValidos(self):
enroqueTemp = Enroque(self.enroque.ReyBlanco, self.enroque.ReyNegro,
self.enroque.ReinaBlanca, self.enroque.ReinaNegra)
movimientos = []
self.enJaque, self.clavadas, self.posiblesJaques = self.validarClavadasyJaques()
if ... |
def eigensolver(pos):
# warnings.filterwarnings("error")
# First calculate the fast Hamiltonian at point
# Initialize empty matrix
ham = np.zeros((3, 3), dtype=numba.complex64)
# Find the values of B, theta_B and phi_B at point
Barray = oppositecoils(field, pos)
B = Barray[3]
thetaB =... | The code calculates the acceleration of a particle in a complex system involving quantum states and synthetic fields. It computes forces from eigenstates, scalar fields, and energy gradients using finite differences. The function handles different modes (synthetic magnetic field, scalar derivatives, energy derivatives)... | def acc(t, posvel, n, norot, nosyn, noclass):
# Extract pos and vel:
pos = posvel[0:5]
vel = posvel[5:10]
stepr = lablength/nr
# Initialize forces
Fa = np.zeros(5)
dscalar = np.zeros(5)
denergy = np.zeros(5)
if nosyn == "False" or nosyn == "Noscalar":
# Find energies and e... |
def in_stalemate(self):
return not self.in_check() and not self.generate_moves()
def insufficient_material(self):
pieces = {}
bishops = []
num_pieces = 0
sq_color = 0
i = SQUARES.a8.value - 1
while i <= SQUARES.h1.value:
i += 1
sq_color = ... | The function checks if a chess game is in a draw state by evaluating three conditions: stalemate, insufficient material, or threefold repetition. It returns True if any of these conditions are met, indicating the game is drawn. | def in_draw(self):
return (self.in_stalemate() or
self.insufficient_material() or
self.in_threefold_repetition()) |
def go_back_home(self):
self.frame_view_all_playlists.pack_forget()
self.home_screen()
def display_progress_dialog(title):
global progress_dialog
progress_dialog = tk.Toplevel(window)
progress_dialog.title(title)
progress_dialog.geometry("300x100")
global label_songs_loaded
labe... | The main task of the code is to display a "View Playlists" interface by switching frames, configuring a listbox to show playlists, adding a back button, and fetching playlists if none exist, ensuring a user-friendly navigation and data loading experience. | def view_playlists(self):
self.window.title("View Playlists")
self.frame_home.pack_forget()
self.frame_view_all_playlists.pack(expand=True)
self.listbox_playlists.pack(
side="top", fill="both", expand=True, padx=20, pady=20
)
self.button_back_home.config(comm... |
def method_playlist_image(self):
self.playlist_image_url = (
self.playlist["images"][0]["url"] if self.playlist["images"] else None
)
response = requests.get(self.playlist_image_url)
original_image = Image.open(BytesIO(response.content))
resized_image = original_ima... | The main task of the code is to display a playlist's information, including its name, image, track count, and interactive buttons for shuffling songs, viewing tracks, or returning to the playlist list. It updates UI elements with dynamic data and arranges them with specific layouts and styling. | def display_playlist_information(self, playlist_uri, playlist_name, num_of_tracks):
self.playlist = self.sp.playlist(playlist_uri)
self.method_playlist_image()
self.playlist_name = playlist_name
self.button_shuffle_playlist.config(command=lambda: self.shuffle_playlist_songs())
... |
def idx2spot(j):
if side == 'double':
return ceil(j / 2)
else:
assert side == 'single'
return j
def spot2blk(j):
if nUnit == 1:
return idx2spot(j)
else:
return ceil( idx2spot(j) / nUnit)
def i_in(j):
if angle == 0 and mode == 'long':
# i.e. if the vehicle enters a boarding spot by going forward
retur... | This function assigns a parking spot to an object by validating availability, updating its status to 'occupied', recording entry time, and determining related attributes like stop position, block index, and destination. It sets internal variables for tracking the object's placement and movement within the parking syste... | def assign_spot(self, j):
assert vs_mat[self.type][self.sys.spot_types[j - 1]] > 0
assert self.status == 0
self.status = 1
self.idx = self.sys.inCount
self.j = j
self.enter_time = self.sys.curr
self.stop = idx2spot(j)
self.block_idx = spot2blk(j)
self.dest_to_stop = i_in(j) |
def add_event(self, event):
heappush( self.eventheap, event)
def i_out(j):
if (angle == 90 and not spmatch):
return i_in(j)
else:
return spot2blk(j) * CAR_LENGTH
def idle_time_calc(self, curr_vehicle):
total = self.curr - curr_vehicle.enter_time
if (total < curr_vehicle.prod_time) and np.abs(total - curr_... | The main task of the code is to handle a vehicle's departure from the system. It updates the vehicle's location, checks if it has reached its destination, removes the vehicle from the queue, increments the departure count, calculates production and idle times, and records the last departure time. The function also adds... | def leave_system(self, curr_vehicle):
curr_vehicle.update_loc()
if np.abs( curr_vehicle.curr_loc - curr_vehicle.dest_to_stop ) > 1e-5:
if curr_vehicle.end_time <= self.curr + SMALL_INTERVAL:
import pdb; pdb.set_trace()
self.add_event( event( curr_vehicle.end_time, curr_vehicle, 'leave_system') )
ret... |
def leave_system(self, curr_vehicle):
curr_vehicle.update_loc()
if np.abs( curr_vehicle.curr_loc - curr_vehicle.dest_to_stop ) > 1e-5:
if curr_vehicle.end_time <= self.curr + SMALL_INTERVAL:
import pdb; pdb.set_trace()
self.add_event( event( curr_vehicle.end_time, curr_vehicle, 'leave_system') )
ret... | The code simulates a discrete-event system by processing events from a priority queue, handling vehicle state transitions (e.g., entering/leaving system, pulling in/out, service), updating system state, and debugging specific vehicle instances. The loop runs until the simulation time unit is reached, then returns the c... | def run(self):
while self.curr - self.start_time <= SIM_UNIT:
# if self.curr - self.start_time >= self.debug_unit:
# import pdb; pdb.set_trace()
curr_event = heappop(self.eventheap)
curr_vehicle = curr_event.vehicle
curr_typ = curr_event.typ
self.curr_vehicle = curr_vehicle
self.curr ... |
def perform_login(self, session):
loginUrl = self.configData._loginUrl.format(self.configData._username, self.configData._password)
#_LOGGER.debug("CMEE Login URL: " + loginUrl)
loginRequest = session.get(loginUrl)
#_LOGGER.debug("CMEE Login Data retrieved: " + loginRequest.text)
... | The main task of the code is to retrieve device and alarm data from a CMEE system by logging in, fetching the data via HTTP requests, and logging out. It uses a session for authentication, stores device data in `self.devices`, and returns it upon success, or `None` if an exception occurs during the process. | def fetch_data(self):
_LOGGER.debug("Requesting CMEE Data")
try:
with requests.Session() as session:
session.verify = self.configData._verifySSL
usermd5 = self.perform_login(session)
self.perform_fetch_alarm_data(session, usermd5)
... |
def _import_class(
cid: str,
) -> type:
# parse the class identifier
if ":" not in cid:
raise ValueError(f"invalid format, cannot import '{cid}'")
module_name, cls_name = cid.split(":", 1)
# import the module
mod = importlib.import_module(module_name)
# get the cls
cls = getatt... | The main task of the code is to generate Mermaid.js diagrams visualizing Python class inheritance structures (MRO) based on CLI arguments. It parses inputs like root class, graph depth, and formatting options, then either outputs the Mermaid code, opens it in an editor, downloads it as an image, or executes a visualiza... | def main(
cli_args: list[str] | None = None,
test: bool = False,
) -> None | list[str] | str:
"""
Main entry hook of the mermaidmro cli.
The arguments to parse can be configured via *cli_args* and default to ``sys.argv[1:]``. When
*test* is *True*, no command is executed by created texts and / ... |
def detectx(frame, model):
frame = [frame]
print(f"[INFO] Detecting...")
results = model(frame)
labels, cordinates = results.xyxyn[0][:, -1], results.xyxyn[0][:, :-1]
return labels, cordinates
def plot_boxes(results, frame, classes):
labels, cord = results
n = len(labels)
x_shape, y_shap... | The main task of the code is to process images in a specified folder using a custom YOLOv5 model to detect and extract text, add metadata (date/time), save annotated images to an output folder, and store extracted text data along with metadata in a JSON file. | def main(img_folder_path):
img_out_folder = "./output-images"
json_file_path = "./json-files/extracted_text.json"
# Load the custom trained model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='./last.pt')
classes = model.module.names if hasattr(model, 'module') else model.names
#... |
def dbg(msg):
write_to_build_log(msg + "\n")
if logging_verbose:
print("(D) {}".format(msg))
def write_to_build_log(msg):
# The log file is opened early in the process, but possibly not early
# enough. In this case, messages only go to stdout/stderr.
if not build_log_fp:
return
... | The main task of the code is to execute a shell command, capture its output, log it to a build log, and handle errors by raising exceptions if the command fails. It uses subprocess.Popen to run the command, streams output line-by-line, and returns the result while forwarding verbose output to the user for debugging. | def run_command(cmd, **kwargs):
try:
dbg("Executing command:\n{}".format(cmd))
popen = subprocess.Popen(cmd, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
universal_newlines=True,
shell=True, **kw... |
def check_dir_accessible_rw(directory):
return os.access(directory, os.F_OK | os.R_OK | os.W_OK | os.X_OK)
def fatal(msg):
error(msg)
build_log_fp.close()
exit(1)
def dbg(msg):
write_to_build_log(msg + "\n")
if logging_verbose:
print("(D) {}".format(msg)) | The main task of the code is to ensure a directory exists and is writable. It checks if the directory already exists, verifies write permissions, and creates it recursively if needed. If the directory cannot be created or accessed, it raises a fatal error with detailed messages. | def ensure_directory(dirpath, recursive=True):
if os.access(dirpath, os.F_OK):
# Directory exists, check for correct permissions
if not check_dir_accessible_rw(dirpath):
fatal("Cannot write to '{}'."
"You need full permissions.".format(dirpath))
return
# Th... |
def check_program(program, version_arg='--version'):
try:
cmd = "{} {}".format(program, version_arg)
return subprocess.check_output(cmd, stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True).strip()
except sub... | The code checks if the installed FuseSoC version meets a specified minimum version requirement. It retrieves the current FuseSoC version, parses it, and compares it to the provided `min_version`. If the installed version is outdated, it raises a fatal error prompting the user to upgrade FuseSoC. Otherwise, it logs a de... | def check_fusesoc(min_version):
found_version_str = check_program("fusesoc")
found_version = version.parse(version.parse(found_version_str).base_version)
if found_version < version.parse(min_version):
fatal("OpTiMSoC requires at least FuseSoC version {}, version {} found. "
"Use 'pip3... |
def check_program(program, version_arg='--version'):
try:
cmd = "{} {}".format(program, version_arg)
return subprocess.check_output(cmd, stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True).strip()
except sub... | The code checks if the installed Xilinx Vivado version meets a specified minimum requirement. It retrieves Vivado's version string, extracts the version number using regex, compares it to the provided `min_version`, and triggers a fatal error if the installed version is too low. Otherwise, it logs the detected version.... | def check_vivado(min_version):
ver_str = check_program('vivado', '-version')
m = re.search('Vivado v(\d{4}\.\d(.\d)?) ', ver_str)
found_version = m.group(1)
if version.parse(found_version) < version.parse(min_version):
fatal("OpTiMSoC requires at least Xilinx Vivado {}, {} found. "
... |
def check_program(program, version_arg='--version'):
try:
cmd = "{} {}".format(program, version_arg)
return subprocess.check_output(cmd, stderr=subprocess.STDOUT,
shell=True,
universal_newlines=True).strip()
except sub... | The function `check_verilator` verifies if the installed Verilator version meets a specified minimum requirement. It retrieves Verilator's version string, extracts the version number using regex, and compares it to the provided `min_version`. If the installed version is insufficient, it triggers a fatal error prompting... | def check_verilator(min_version):
ver_str = check_program("verilator")
m = re.search('^Verilator ([^\s]+) ', ver_str)
found_version = m.group(1)
if version.parse(found_version) < version.parse(min_version):
fatal("OpTiMSoC requires at least Verilator version {}, version {} "
"foun... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def file_linktree(srcdir, destdir):
dbg("Linking fi... | The function `build_hw_modules` constructs hardware modules by either creating symbolic links or copying files from a source directory to a destination directory, based on the `options.link_hw` flag. It sets source and destination paths, then uses `file_linktree` or `file_copytree` to handle the module files accordingl... | def build_hw_modules(options):
dist = os.path.join(options.objdir, "dist")
src = options.src
info("Build hardware modules")
modsrcdir = os.path.join(src, "src", "soc", "hw")
moddistdir = os.path.join(dist, "soc", "hw")
if (options.link_hw):
file_linktree(modsrcdir, moddistdir)
els... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def file_linktree(srcdir, destdir):
dbg("Linking fi... | The function builds the 'lisnoc' external component by copying or linking its source files from the specified source directory to a distribution directory within the object directory. The choice between copying (file_copytree) or linking (file_linktree) depends on the 'link_hw' option in the provided options. | def build_externals_lisnoc(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
info("Build lisnoc")
srcdir = os.path.join(src, "external", "lisnoc")
distdir = os.path.join(dist, "external", "lisnoc")
if (options.link_hw):
file_linktree(srcdir, di... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def file_linktree(srcdir, destdir):
dbg("Linking fi... | The function copies or links the 'mor1kx' external files from the source directory to the distribution directory based on the 'link_hw' option. If enabled, symbolic links are created; otherwise, files are copied. This prepares the external dependencies for the 'mor1kx' component during the build process. | def build_externals_mor1kx(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
info("Copy mor1kx")
srcdir = os.path.join(src, "external", "mor1kx")
distdir = os.path.join(dist, "external", "mor1kx")
if (options.link_hw):
file_linktree(srcdir, dis... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def file_linktree(srcdir, destdir):
dbg("Linking fi... | The function `build_externals_glip` copies or links GLIP hardware modules from a source directory to a distribution directory based on the `link_hw` option. It avoids copying the full tree, focusing only on hardware components. If `link_hw` is true, it creates symbolic links; otherwise, it copies files. The source and ... | def build_externals_glip(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
info("Copy/link GLIP hardware modules")
# XXX: Only copy hardware, not the full tree.
srcdir = os.path.join(src, "external", "glip")
distdir = os.path.join(dist, "external", "gli... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_program(program, version_arg='--version'):
... | The main task of the code is to build and install documentation by compiling LaTeX files into PDF format using `make`, then copying the generated PDF and associated files (README, COPYING) to a distribution directory. It leverages parallel processing with CPU threads for efficiency, ensuring the build artifacts are org... | def build_docs(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
nthreads = multiprocessing.cpu_count()
info("Build and install documentation")
check_program("python3")
check_program("pdflatex")
doc_srcdir = os.path.join(src, "doc")
doc_objdir... |
def ensure_directory(dirpath, recursive=True):
if os.access(dirpath, os.F_OK):
# Directory exists, check for correct permissions
if not check_dir_accessible_rw(dirpath):
fatal("Cannot write to '{}'."
"You need full permissions.".format(dirpath))
return
# Th... | This function builds and packages Python bindings for the 'opensocdebug' software, handling versioning workarounds. It sets up directories, overrides setuptools_scm's version detection with a fake "0" to bypass git-based versioning, then runs 'setup.py sdist' to create a Python source distribution in the specified outp... | def build_externals_opensocdebug_software_pybindings(options, env):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
src = os.path.join(src, "external", "opensocdebug",
"software", "src", "python")
objdir = os.path.join(objdir, "external",
... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_make():
check_program("make")
def ensure_... | The code builds host tools by compiling source files using make and copying binaries/scripts to designated distribution directories. It constructs 'utils' (e.g., bin2vmem) and 'optimsoc-pgm-fpga' tools, ensuring directories exist, compiling with parallel threads, then copying resulting binaries to 'host/bin' and associ... | def build_tools(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
nthreads = multiprocessing.cpu_count()
info("Build host tools")
check_make()
# Create tools folder in dist
toolsdistdir = os.path.join(dist, "tools")
ensure_directory(toolsdistd... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_autotools():
check_program("autoconf")
... | The code builds and installs SoC software libraries using Autotools. It sets up directories, checks dependencies, configures each library with `--host=or1k-elf`, compiles in parallel, and installs artifacts. The target is to prepare bare-metal software for an SoC, ensuring correct paths and cross-compilation settings f... | def build_soc_software(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
nthreads = multiprocessing.cpu_count()
info("Build SoC software")
check_autotools()
check_or1kelf()
# List of libraries to build
libs = {}
libs["baremetal-libs"] = {}
... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_autotools():
check_program("autoconf")
... | This function builds the GLIP software for the host system by configuring, compiling, and installing it using Autotools. It sets up directories, escapes the prefix path for pkg-config, runs autogen.sh, configures with options like Cypress FX2/FX3, JTAG, UART, and TCP support, compiles using parallel make, and installs ... | def build_externals_glip_software(options):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
nthreads = multiprocessing.cpu_count()
src = os.path.join(src, "external", "glip")
objdir = os.path.join(objdir, "external", "glip")
dist = os.path.join(dist, "host")
... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_autotools():
check_program("autoconf")
... | This function builds and installs the 'opensocdebug' host software from an external source. It sets up directories, runs autotools to generate build files, configures the build with logging and GLIP support, compiles using multiple threads, and installs artifacts to a specified 'dist' directory. The process ensures the... | def build_externals_opensocdebug_software(options, env):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
nthreads = multiprocessing.cpu_count()
src = os.path.join(src, "external", "opensocdebug", "software")
objdir = os.path.join(objdir, "external", "opensocdebug",... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_fusesoc(min_version):
found_version_str =... | (The code builds FPGA examples for different configurations using Fusesoc and Vivado. It checks required tools, sets up directories, and iterates through predefined examples. For each example, it constructs the project, ensures build directories exist, runs Fusesoc with specified options, and copies generated bitstream... | def build_examples_fpga(options, env):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
info("Build FPGA examples")
check_fusesoc(options.requirement_versions['fusesoc'])
check_vivado(options.requirement_versions['vivado'])
exsrc = os.path.join(src, "examples",... |
def info(msg):
write_to_build_log(msg + "\n")
# we only print bold in verbose mode to make our messages more visible
if console_colors and logging_verbose:
print("\033[1m(I) {}\033[0m".format(msg))
else:
print("(I) {}".format(msg))
def check_fusesoc(min_version):
found_version_str =... | The code builds simulation examples for hardware designs using FuseSoC and Verilator. It compiles multiple configurations (e.g., single/dual/quad-core, debug modes) of "compute_tile_sim" and "system_2x2_cccc_sim" examples, handling compatibility across FuseSoC versions. Artifacts are built, verified, and copied to a di... | def build_examples_sim(options, env):
src = options.src
objdir = options.objdir
dist = os.path.join(objdir, "dist")
info("Build examples (Verilator-based simulation)")
check_fusesoc(options.requirement_versions['fusesoc'])
check_verilator(options.requirement_versions['verilator'])
exsrc = ... |
def CycleDial(step=1, delay=0.5):
# Increment
for i in range(0,101,step):
UpdateGauges(i, i, i, i)
time.sleep(delay)
# Decrement
for i in range(0,101,step):
UpdateGauges(100-i, 100-i, 100-i, 100-i)
time.sleep(delay)
def UpdateGauges(dial1, dial2, dial3, dial4):
if in... | The code initializes a serial connection, continuously updates system metrics (CPU, memory, GPU usage), and displays them on gauges. It runs indefinitely, refreshing data at intervals, while maintaining a serial link for potential external communication or control. | def main():
global ser
ser = serial.Serial('COM9', 115200, timeout=10)
#while True:
# CycleDial(5, 0.1)
#exit()
CycleDial(10, 0.2)
while True:
UpdateGauges(cpu_usage(), memory_usage(), gpu_usage(), gpu_mem())
#UpdateGauges(100, 100, 100, 100)
time.sleep(SLEEP_SEC... |
def get_label(existing_labels: Set[str]) -> str:
label = inquirer.list_input(
'Please choose a label to apply to this message',
choices=[IGNORE_LABEL] + sorted(existing_labels) + [CREATE_LABEL],
render=INQUIRER_RENDER
)
if label == CREATE_LABEL:
label = create_label(existing_... | The function processes a batch of messages, updating or adding classifications based on user input. It checks existing classifications, compares message text, and prompts for label changes. It returns dictionaries of added and updated classifications after user confirmation. | def classify_batch(messages: List[dict], data: Dict[str, dict], all_labels: Set[str],
ignore_user_ids: Optional[Set[str]] = None) -> Tuple[Dict[str, dict], Dict[str, dict]]:
messages_len = len(messages)
added = {}
updated = {}
for i, message in enumerate(messages):
message_tex... |
def load_data(data_file: str, append: bool = True) -> Tuple[dict, Optional[str], Optional[str]]:
print(f'Using data file at {data_file}')
if not os.path.exists(data_file):
return {}, None, None
if not append:
raise Exception(
f'The data file ({data_file}) exists and append is di... | The function classifies a given text by assigning a label based on user input or existing labels, then stores the result in a dataset. It generates a unique ID, checks for reserved labels, prompts for label selection if needed, and updates the dataset with the classification. | def classify_single(args):
print(f'Classifying text: {args.text}')
message_id = f'{str(time.time())}-manual-text'
classification = {
'text': args.text,
'label': None,
}
data, start_timestamp, end_timestamp = load_data(args.data_file, args.append)
if args.label:
if args.la... |
def get_data_labels(data: Dict[str, dict]) -> Set[str]:
"""
Retrieves all labels that have already been classified.
:param data:
:return:
"""
# Always remove the ignore label
return set(data[elem]['label'] for elem in data).difference([IGNORE_LABEL])
def get_messages(
token: str, cha... | The function continuously retrieves and classifies messages from a channel in batches, updating a data dictionary with classifications. It uses timestamps to paginate through messages (older/newer) and asks the user if they want to continue after each batch. It returns the final start/end timestamps. | def classify_messages(token: str, channel_id: str, data: Dict[str, dict], start_timestamp: Optional[str],
end_timestamp: Optional[str], direction: bool,
ignore_user_ids: Optional[Set[str]], batch_size: Optional[int] = None,
session: Optional[Session] = N... |
def get_channel_id(token: str, name: str, session: Optional[Session] = None) -> str:
# Strip off # prefix if specified
if name.startswith('#'):
name = name[1:]
client = get_client(token, session=session)
start_query = True
cursor = None
while start_query or cursor:
start_query =... | The main task of the code is to classify Slack channel messages by processing data, filtering out specified users, and updating timestamps based on parameters like direction and batch size, then saving the results back to a file. | def classify(args):
# Parse ignore user ids from comma-separated list
if args.ignore_user_ids:
ignore_user_ids = set(args.ignore_user_ids.split(','))
else:
ignore_user_ids = None
# with Session() as session:
channel_id = get_channel_id(args.slack_token, args.slack_channel)
data,... |
def expand_key(key: bytes) -> bytes:
num_rounds = 10
rcons = [bytearray(4 * [0]) for _ in range(num_rounds)]
rcons[0][0] = 1
for i in range(1, num_rounds):
rcons[i][0] = gmul(rcons[i-1][0], 2)
rcons[i] = bytes(rcons[i])
def S_word(word):
return bytes([Sbox[b] for b in word]... | This code implements a 10-round AES encryption block. It expands the input key into round keys, then applies XOR with the initial key, followed by 10 rounds of substitution (subBytes), row shifting (shiftRows), column mixing (mixColumns, except final round), and XOR with round keys. The block is modified in-place throu... | def enc_block(block: bytearray, key: bytes):
rkeys = expand_key(key)
for i in range(16):
block[i] ^= rkeys[i]
for rnd in range(1, 11):
subBytes(block)
shiftRows(block)
if rnd != 10: mixColumns(block)
for i in range(16):
block[i] ^= rkeys[16*rnd + i] |
def expand_key(key: bytes) -> bytes:
num_rounds = 10
rcons = [bytearray(4 * [0]) for _ in range(num_rounds)]
rcons[0][0] = 1
for i in range(1, num_rounds):
rcons[i][0] = gmul(rcons[i-1][0], 2)
rcons[i] = bytes(rcons[i])
def S_word(word):
return bytes([Sbox[b] for b in word]... | This function decrypts a 16-byte block using AES decryption with the provided key. It applies inverse transformations (ShiftRows, SubBytes, and MixColumns) in reverse encryption order across 10 rounds, XORing the block with expanded round keys at each stage. The final round omits MixColumns. The process reverses AES en... | def dec_block(block: bytearray, key: bytes):
rkeys = expand_key(key)
for rnd in range(10, 0, -1):
for i in range(16):
block[i] ^= rkeys[16*rnd + i]
if rnd != 10: imixColumns(block)
ishiftRows(block)
isubBytes(block)
for i in range(16):
block[i] ^= rkeys... |
def heap_insert(A, key):
A.append(key)
index = len(A) - 1
while A[index][2] > A[(index + 1) // 2 - 1][2] and index > 0:
A[index], A[(index + 1) // 2 - 1] = A[(index + 1) // 2 - 1], A[index]
index = (index + 1) // 2 - 1
def heap_extract_max(A):
A[0] = A[-1]
A.pop()
max_heapify(A, ... | The code computes the skyline of a set of buildings by processing their start and end points. It uses a max-heap to track the current maximum height of active buildings. For each point (sorted by x-coordinate), it adds start points to the heap and removes end points. Key points are recorded when the maximum height chan... | def get_skyline(buildings):
heap = []
points = []
key_points = []
# extract the value of the upper left point and upper tight point of the building
# "0" means it is the starting point and "1" means it is an ending point
# for sorting purpose
for b in buildings:
points.append([b[0], ... |
def compute_mean_with_CI(data, confidence):
"""
Computes the mean and confidence interval for a dataset.
Args:
- data (Series): The data to compute the mean and CI for.
- confidence (float): The confidence level for the CI. Value between 0 and 1.
Returns:
- tuple: Mean and confidence i... | The function computes and displays anthropometric analysis by calculating mean z-scores and malnourishment prevalence rates with confidence intervals for weight-for-age, height-for-age, and BMI-for-age data. It uses provided axes to visualize results, including mean z-scores and prevalence indicators like stunting, was... | def compute_and_display_analysis(wfa_series, hfa_series, bmifa_series, over_60_mo_bmifa_series, wfa_ax, hfa_ax, bmifa_ax, over_60_mo_bmifa_ax):
"""
Computes and displays the analysis of anthropometric data including mean z-scores and malnourishment prevalences.
Calculates the mean z-scores and their confid... |
def import_and_prepare_data(data_file_name):
"""
Imports data from a CSV file and prepares it for analysis by creating pandas Series for various anthropometric indicators.
Args:
- data_file_name (str): The name of the CSV file containing the data.
Returns:
- Tuple[pd.Series, pd.Series, pd.Seri... | The main task of the code is to orchestrate a workflow for analyzing and visualizing anthropometric data. It imports and prepares data, creates plotting figures, generates visualizations, computes statistical analysis, applies styling, and saves results as PDFs. The function manages data handling, figure creation, plot... | def main():
"""
Main function to orchestrate the data import, preparation, plotting, and analysis.
This function manages the workflow of the script, which includes importing and preparing data,
creating figures and grid specifications for plotting, plotting the data, and performing as well
as disp... |
def get_empty_board(board_dim: int = 6, player_start: int = 1) -> np.ndarray:
board = np.zeros((board_dim, board_dim))
if board_dim < 2:
return board
coord1 = int(board_dim / 2 - 1)
coord2 = board_dim // 2
initial_squares = [
(coord1, coord2),
(coord1, coord1),
(coord... | This code resets a game environment by initializing the board, randomly selecting the starting player, and returning the initial board state along with reward, done status, and info. It also handles rendering if enabled and sets up game parameters for a new episode. | def reset(self) -> Tuple[np.ndarray, int, bool, Dict]:
"""Resets game & takes 1st opponent move if they are chosen to go first."""
self._player = random.choice([-1, 1])
self._board = get_empty_board(self.board_dim, self._player)
self.running_tile_count = 4 if self.board_dim > 2 else 0
... |
def has_legal_move(board: np.ndarray, current_player: int) -> bool:
"""True if current_player has legal move on the board."""
board_dim = len(board)
for row, col in itertools.product(range(board_dim), range(board_dim)):
move = (row, col)
if is_legal_move(board, move, current_player):
... | This function processes a single turn in a game by applying a move to the board, updating game state, checking for win/loss/tie conditions, switching players, and returning 1 if the current player wins or 0 otherwise. It validates moves, handles game over states, and manages rendering and logging when enabled. | def _step(self, move: Optional[Tuple[int, int]]) -> int:
"""Takes 1 turn, internal to this class.
Do not call
"""
assert not self.done, "Game is over, call .reset() to start a new game"
if move is None:
assert not has_legal_move(
self._board, self._p... |
def _get_pfx_declarations(self, pfx_fmt, base):
results = [pfx_fmt % (pfx, ns)
for pfx, ns in self.prefixes.namespaces()
if pfx.startswith(base)]
if not results:
ns = self.prefixes.lookup(base)
if ns:
results = [pfx_fmt % (base, ns)]
... | This code generates XML namespace or prefix completion suggestions by parsing context, filtering results based on a base value, and returning formatted entries for autocompletion. It distinguishes between 'prefix' and 'xmlns' contexts, extracts relevant declarations, and ensures results match the specified base. | def get_completions(self, buffer, context, base):
prefix = context.split(':')[0]
pfx_fmt = ('%s: <%s>' if prefix.lower() == 'prefix'
else '%s="%s"' if prefix == 'xmlns'
else None)
if pfx_fmt:
results = self._get_pfx_declarations(pfx_fmt, base)
... |
def line_row():
# GOAL: put beeper on every spot except corners
# Pre-condition: bottom west corner, facing EAST
# Post-condition: bottom east corner, facing WEST
while front_is_clear():
move()
put_beeper()
pick_beeper()
return_west_wall()
def check_one():
#pre-condition: bot... | The main task of the code is to place beepers along the bottom row (excluding corners), then iteratively check and manage the remaining beepers by removing edge beepers until specific conditions (1 or 2 beepers left) are met, finally returning a beeper. The loop continues while the right side is clear, ensuring structu... | def main():
line_row() #Place beepers all along bottom row, except in corners
while right_is_clear():
#Pre-condition: K is at bottom west wall, facing west
#Post-condition: K is at bottom west wall, facing west
check_one() #Check if there's only 1 be... |
def line_row():
# GOAL: put beeper on every spot except corners
# Pre-condition: bottom west corner, facing EAST
# Post-condition: bottom east corner, facing WEST
while front_is_clear():
move()
put_beeper()
pick_beeper()
return_west_wall()
def check_one():
# p... | The code's main task is to locate and return the midpoint beeper in a row by iteratively removing edge beepers. It checks for 1 or 2 remaining beepers to terminate the loop, ensuring K stays at the bottom west wall facing west. The `clear_edges()` function removes west-most and east-most beepers, restarting the process... | def find_midpoint():
line_row()
while right_is_clear():
# Pre-condition: K is at bottom west wall, facing west
# Post-condition: K is at bottom west wall, facing west
check_one() # Check if there's only 1 beeper left. If yes, end loop.
check_two() # Check if there's onl... |
def find_midpoint():
line_row()
while right_is_clear():
# Pre-condition: K is at bottom west wall, facing west
# Post-condition: K is at bottom west wall, facing west
check_one() # Check if there's only 1 beeper left. If yes, end loop.
check_two() # Check if there's onl... | The main task of the code is to construct a symmetrical structure by repeatedly finding midpoints, turning right, painting a side, returning to the bottom, and repeating the process. It orchestrates movement and painting actions to create a pattern or shape, likely involving a robot or drawing mechanism. | def build_panes():
find_midpoint()
turn_right()
paint_side()
return_bottom()
turn_right()
find_midpoint() |
def paint_world_blue():
#pre-condition: bottom west corner, facing east (left is clear)
#post-condition: top east corner, facing east (left is blocked)
while left_is_clear():
paint_row()
next_row()
paint_row()
def build_frame():
#pre: top east corner, facing east
#post: top east ... | The main task of the code is to initialize a 3x3 grid world, paint it blue, construct a frame, and add panes. It ensures the world meets size requirements before executing these steps to create a structured, visual layout with defined boundaries and internal sections. | def main():
"""
requires world to be at least 3 wide and tall
"""
paint_world_blue()
build_frame()
build_panes() |
def create_grid(start_index, goal_index, width):
start_x = start_index % width
start_y = int(start_index / width)
goal_x = goal_index % width
goal_y = int(goal_index / width)
x_init = min(start_x, goal_x)
y_init = min(start_y, goal_y)
x_end = max(start_x, goal_x)
y_end = max(start_y, go... | The code implements a Q-learning algorithm to train an agent to navigate from a start to a goal position in a grid. It initializes a Q-table, iterates through multiple episodes, and updates the table using rewards and the Bellman equation. After training, it retrieves the optimal path indices and visualizes them on the... | def q_learning(start_index, goal_index, width, height, costmap, resolution, origin, grid_viz, previous_plan_variables):
'''
Uses Q Learning Algorithm to find a path from start to goal
'''
grid = create_grid(start_index, goal_index, width)
original_grid = np.copy(grid)
q_table = np.zeros((4, ) +... |
def initialize(start_index, goal_index, width):
# create an open_list
open_list = []
# km variable
km = 0
# dict for mapping g costs (travel costs) to nodes
g_costs = dict()
# dict for mapping rhs costs
rhs_costs = dict()
# set the goal node's g_cost and f_cost
g_costs[goal_i... | This code implements the LPA* algorithm for dynamic path planning. It initializes or updates a path based on a changing costmap, computes the shortest path from start to goal using weighted neighbors, and reconstructs the path by backtracking from the goal. The function returns the optimized path and state variables fo... | def dstar(start_index, goal_index, width, height, costmap, resolution, origin, grid_viz, previous_plan_variables):
open_list, g_costs, rhs_costs = [], [], []
if previous_plan_variables is None:
open_list, km, g_costs, rhs_costs, shortest_path = initialize(start_index, goal_index, width)
r... |
def initialize(start_index, goal_index, width, costmap):
# create an open_list
open_list = []
# dict for mapping g costs (travel costs) to nodes
g_costs = dict()
# dict for mapping rhs costs
rhs_costs = dict()
# set the start's node g_cost and f_cost
for i in range(len(costmap)):
... | The code implements the LPA* algorithm for dynamic path planning, updating the shortest path in a changing environment. It initializes or resumes from previous state variables, checks for costmap changes, updates affected vertices, and reconstructs the path from start to goal. The function returns the computed shortest... | def lpastar(start_index, goal_index, width, height, costmap, resolution, origin, grid_viz, previous_plan_variables):
open_list, g_costs, rhs_costs = [], [], []
if previous_plan_variables is None:
open_list, g_costs, rhs_costs, shortest_path = initialize(start_index, goal_index, width, costmap)
... |
def get_max_depth(self, root=None, depth=0):
depths = []
if root is None:
root = self.decision_tree
if type(root) is Leaf:
depths.append(depth)
else:
for child in root.children:
depths.append(self.get_max_depth(child, depth + 1))
... | This code prunes a decision tree by replacing leaf nodes with majority-voted labels to improve validation accuracy. It iteratively checks each leaf, replaces its parent node with a Leaf node using majority vote, and recursively prunes if accuracy improves. If not, it reverts changes and tries the next leaf, ensuring th... | def prune(self, validation_dataset):
tree_before = self.decision_tree.__str__(label_dict=self.label_dict)
max_depth = self.get_max_depth()
lowest_leafs = self.get_leaf_nodes_at_depth(max_depth)
# Check accuracy of tree
pre_acc = self.check_accuracy(validation_dataset)
... |
def calc_num_buckets(self, dataset):
return min(len(dataset), self.DEFAULT_BUCKETS)
def h(self, samples):
labels = set([a[-1] for a in samples])
sum = 0
for label in labels:
rows = [s for s in samples if s[-1] == label]
pc = len(rows) / len(samples)
s... | The code finds the optimal partitioning of a dataset's specified column into buckets that maximizes information gain. It evaluates all possible combinations of split points, partitions the data, computes information gain for each, and selects the partitioning with the highest gain to enhance data segmentation for decis... | def find_best_partitioning(self, dataset, column):
assert column < len(dataset[0])
num_buckets = self.calc_num_buckets(dataset)
parent_entropy = self.h(dataset)
# We want a list not a set? np.distinct?
sorted_col = set([a[column] for a in dataset])
possible_partitioni... |
def find_best_partitioning(self, dataset, column):
assert column < len(dataset[0])
num_buckets = self.calc_num_buckets(dataset)
parent_entropy = self.h(dataset)
# We want a list not a set? np.distinct?
sorted_col = set([a[column] for a in dataset])
possible_partitioni... | This function identifies the feature in a dataset that provides the highest information gain for decision tree splitting. It iterates through each feature, partitions the data based on potential splits, calculates information gain using entropy, and selects the feature with the maximum gain to determine the best attrib... | def find_best_attribute(self, dataset):
num_features = len(dataset[0]) - 1
best_info_gain = 0
best_feature = -1
# Iterate through every attribute in dataset
for i in range(num_features):
partitioning = self.find_best_partitioning(dataset, i)
if len(partit... |
def find_best_attribute(self, dataset):
num_features = len(dataset[0]) - 1
best_info_gain = 0
best_feature = -1
# Iterate through every attribute in dataset
for i in range(num_features):
partitioning = self.find_best_partitioning(dataset, i)
if len(partit... | This code recursively builds a decision tree by selecting the best attribute to split the dataset, partitioning it into child datasets, and creating leaf or intermediate nodes based on class uniformity. It sets node properties like attribute index, entropy, and class distribution, handling edge cases like pruning when ... | def build_tree(self, dataset, root):
best_column = self.find_best_attribute(dataset)
best_partitioning = self.find_best_partitioning(dataset, best_column)
# If we can't partition then convert parent to leaf
if len(best_partitioning) == 0:
self.parent_to_leaf(root, dataset)
... |
def create_tree():
return Intermediate([], -1)
def build_tree(self, dataset, root):
best_column = self.find_best_attribute(dataset)
best_partitioning = self.find_best_partitioning(dataset, best_column)
# If we can't partition then convert parent to leaf
if len(best_partitioning) == ... | The main task of the code is to train a decision tree classifier by constructing a decision tree from input features (x) and labels (y). It encodes labels as integers, combines data into a dataset, builds the tree structure using `build_tree`, and sets a trained flag. Optionally, it displays the tree's depth and struct... | def train(self, x, y, show_diagram=False):
""" Constructs a decision tree classifier from data
Parameters
----------
x : numpy.array
An N by K numpy array (N is the number of instances, K is the
number of attributes)
y : numpy.array
An N-dimen... |
def update_system(self):
self.__sys_cmd(self.update_cmd, sudo=True)
if self.has_extra_cmd():
self.__sys_cmd(self.extra_cmd)
def update_shell_plugins(self):
msg = "updating {} plugins..."
return self.__run_items(msg, self.__shell_plugin_cmds, name_as_shell=True)
def update_oth... | The code's main task is to update a system by sequentially executing four operations: updating the system core, shell plugins, other components using provided output, and finally cleaning up the system to ensure optimal performance and resource management. | def update_all(self, output):
self.update_system()
self.update_shell_plugins()
self.update_other(output)
self.cleanup_system() |
def get_valid_customer_id(self):
"""Get a valid customer_id attribute by checking the error_status attribute"""
while not hasattr(self, "error_status") or self.error_status == True:
self.get_customer_id()
self.customer_id_validation()
delattr(self, "error_status")
... | The code retrieves and validates customer order details by calling methods to get the customer ID, delivery date, list of articles, total cost, and then displays the compiled order summary. | def get_whole_customer_order(self):
"""Get all the information needed for the customer's order"""
self.get_valid_customer_id()
self.get_valid_delivery_date()
self.get_all_articles()
self.get_total_cost()
self.display_order_summary() |
def update_state(self, action: Action) -> Tuple[bool, float, float, float, LineString, float, float, float, float, float, float]:
"""
Function to update the state of the ego vehicle based on the action (Accleration)
Returns difference in position and current speed
"""
angle = tra... | The main task of the code is to simulate a single step of the ego-vehicle's movement in a traffic environment based on a given action. It updates the vehicle's position, checks for collisions or out-of-network events, computes observations, and returns the next state, reward, termination status, and debug information. ... | def step(self, action: Action) -> Tuple[dict, float, bool, dict]:
"""
Function to take a single step in the simulation based on action for the ego-vehicle
"""
# next state, reward, done (bool), info (dict)
# dict --> useful info in event of crash or out-of-network
# bool ... |
def create_order(self, domains: list[str], account_url: str) -> AcmeOrder:
response = self.__do_signed_post(
endpoint=self.__directory.new_order,
identification=AcmeManagerIdentification(kid=account_url),
body=AcmeNewOrderBody(
identifiers=[
... | The code generates a DNS-01 ACME challenge for a specified domain by creating an order, retrieving authorization details, and constructing a DNS record with a base64-encoded token and thumbprint hash. It returns structured challenge data for domain validation. | def request_dns_challenge(self, domain: str, account_url: str) -> AcmeManagerDnsChallenge:
""" DNS-01 challenge for a single domain """
order = self.create_order(account_url=account_url, domains=[domain])
authorization = self.__get_authorization(authorization_url=order.authorizations[0], accoun... |
def get_order(self, order_url: str, account_url: str) -> AcmeOrder:
response = self.__do_signed_post(
endpoint=order_url,
identification=AcmeManagerIdentification(kid=account_url)
)
return AcmeOrder(
url=order_url,
**response.json()
)
def ... | This function validates a DNS-01 ACME challenge for a single domain by loading a private key, retrieving an order/authorization, sending a signed validation request, waiting for approval, generating a CSR with the domain name, finalizing the order, and ensuring both challenge and order statuses reach "valid" within a t... | def validate_dns_challenge(self, order_url: str, certificate_signing_key_pem: str, account_url: str) -> None:
""" Validate DNS-01 challenge for a single domain """
rsa_signing_private_key: RSAPrivateKey = load_pem_private_key(certificate_signing_key_pem.encode("utf-8"), password=None)
order = s... |
def readJsonData (self):
with open(self.jsonFile,encoding="utf8") as f:
self.data = json.loads(f.read())
with open(self.jsonParams,encoding="utf8") as f:
self.cardParams = json.loads(f.read())
self.print_debug("readJsonData done")
def customColors (self):
colors =... | The code's main task is to process card data by reading JSON input, applying custom color settings, listing cards for processing, executing the card processing logic, and finally generating a TeX output file. | def doTheThing (self):
self.readJsonData()
self.customColors()
self.listCardsToProcess()
self.processCards()
self.writeTexFile() |
def set_state(s):
print(s)
global state
state = s
def expand2square(img):
width, height = img.size
if width == height:
return img
elif width > height:
result = Image.new(img.mode, (width, width), "white")
result.paste(img, (0, (width - height) // 2))
else:
re... | The function generates a 3D mesh from text or image input using a specified model. It converts the output to a point cloud, saves it as a PLY file, converts to a mesh, and exports as GLB and GIF. Key steps include input validation, model sampling with guidance scale, point cloud conversion, mesh generation, and multi-f... | def generate_3D(input, model_name='base40M', guidance_scale=3.0, grid_size=128):
set_state('Entered generate function...')
if isinstance(input, Image.Image):
input = expand2square(input)
# if input is a string, it's a text prompt
sampler = get_sampler(model_name, txt2obj=True if isinstance(inp... |
def find_model(src_dir):
model_files = [
f for f in listdir(src_dir)
if f.endswith(".c") and "model" in f.lower()
]
for fname in model_files:
includes = parse_cpp_includes(join(src_dir, fname))
if "AutoTilerLib.h" not in includes:
continue
generator = find... | The main task of the code is to configure and build Autotiler kernels for a specified model. It checks if the model requires recompilation, sets up build directories, configures compiler flags, and compiles both basic and user-specific kernels. The code ensures dependencies are up-to-date, manages include paths, and ex... | def main():
model = find_model(env.subst("$PROJECTSRC_DIR"))
if not model:
return
env.SetDefault(SRC_FILTER=SRC_FILTER_DEFAULT)
env.Append(SRC_FILTER=["-<%s>" % basename(model['model_path'])])
env.PrintConfiguration()
env.AddMethod(lambda *arg, **args: None, "PrintConfiguration")
... |
def __get_files_to_check(self):
files = self.__get_all_files()
marker = self.__read_check_marker()
i = 0
if not marker:
# No check marker so return all files to check
return files
try:
i = files.index(marker)
return files[i+1:]
... | The code initializes a class to check and fix media files (e.g., MP4s) missing the 'moov' atom, crucial for playback. It processes files in a directory, skips empty files, identifies missing 'moov' atoms, uses a reference "good" file to repair affected files, and logs results. The core task is ensuring valid file struc... | def __init__(self, cam_dir):
self.cam_dir = cam_dir
self.good_file = None
self.total_num_files = 0
self.ignored_file = None
os.chdir(cam_dir)
files = self.__get_files_to_check()
for f in files:
logging.info('Checking: %s, size=%d [total: %s files]' % ... |
def interpolation(row, indices, slice_before, slice_after, learn_before, learn_after, interpolation_type, test):
# define interpolated regions and x,y axises for the interpolation function, and calls the interpolation
# retruns the updates row with the values in tms-pulse areas replaced after interpolation
... | The code interpolates event-related data in raw EEG/MEG signals by replacing specified event indices (from annotations or detected pulses) with interpolated values using a chosen method. It processes each channel, creates a new Raw object with modified data, and optionally logs results or plots comparisons. | def implement_interpolation_raw(raw, find_events, slice_before, slice_after, plot, learn_before, learn_after,
events_to_interpolate, interpolation_type):
# returns a new raw object with the interpolated values
mat = raw.get_data()
if find_events: # if user want us to find tm... |
def interpolation(row, indices, slice_before, slice_after, learn_before, learn_after, interpolation_type, test):
# define interpolated regions and x,y axises for the interpolation function, and calls the interpolation
# retruns the updates row with the values in tms-pulse areas replaced after interpolation
... | This function performs interpolation on EEG/MEG epoch data by replacing missing values in specified segments using either TMS pulse detection or MNE event indices. It iterates through each data channel, applies the chosen interpolation method with configurable parameters, and logs results. A random test segment is vali... | def implement_interpolation_epoch(epoch, find_events, slice_before, slice_after, plot, learn_before, learn_after,
interpolation_type):
# Modifies the data of the original Epochs object with the interpolated values
intered_epoch = epoch.copy()
mat = intered_epoch.get_data()
... |
def get_shoppinglist_id(self):
create_shoppinglist_resource = self.create_shoppinglist_resource()
# get id of shoppinglist created
json_shoppinglist_resource = json.loads(
create_shoppinglist_resource.data.decode('utf-8').replace(
"'", "\"")
)
shopping... | This test verifies that the API can successfully retrieve a shopping list by ID, checking that the response status is 200 and confirming the presence of expected data fields like 'title' and the current timestamp in the returned data. | def test_retrieve_shoppinglists(self):
shoppinglist_id = self.get_shoppinglist_id()
# test API can update shoppinglist
response = self.client().get(
'/shoppinglist/{}'.format(shoppinglist_id),
headers=self.get_authorization_header()
)
# assert shoppinglis... |
def get_shoppinglist_id(self):
create_shoppinglist_resource = self.create_shoppinglist_resource()
# get id of shoppinglist created
json_shoppinglist_resource = json.loads(
create_shoppinglist_resource.data.decode('utf-8').replace(
"'", "\"")
)
shopping... | This test function verifies that the API can successfully update a shopping list by sending a PUT request with a new title. It checks if the response status code is 200 (success), confirms the updated title "weekend party" is present in the response data, and validates the inclusion of the current timestamp in the resp... | def test_update_shoppinglists(self):
shoppinglist_id = self.get_shoppinglist_id()
# test API can update shoppinglist
response = self.client().put(
'/shoppinglist/{}'.format(shoppinglist_id),
data={'title': "weekend party"},
headers=self.get_authorization_head... |
def get_shoppinglist_id(self):
create_shoppinglist_resource = self.create_shoppinglist_resource()
# get id of shoppinglist created
json_shoppinglist_resource = json.loads(
create_shoppinglist_resource.data.decode('utf-8').replace(
"'", "\"")
)
shopping... | This test method verifies the functionality of searching items in a shopping list. It creates a test item, sends a GET request with a search query ('tour'), and checks if the response status is 200 and contains the search term in the returned data. | def test_search_item(self):
shoppinglist_id = self.get_shoppinglist_id()
self.create_item_resource(shoppinglist_id)
# search items
search_items_resource = self.client().get(
'/shoppinglist/{}/items/?q=tour'.format(
shoppinglist_id),
headers=self.g... |
def get_authorization_header(self):
token = self.get_authorization_token()
header = {
'Authorization': 'Bearer ' + token
}
return header
def get_shoppinglist_id(self):
create_shoppinglist_resource = self.create_shoppinglist_resource()
# get id of shoppinglist ... | This test case verifies the pagination functionality of retrieving items from a shopping list. It creates an item, requests items with a limit of 1, checks the response status code (200 OK), and confirms exactly one item is returned in the JSON data. | def test_items_pagination(self):
headers = self.get_authorization_header()
shoppinglist_id = self.get_shoppinglist_id()
self.create_item_resource(shoppinglist_id)
# get items with pagination
get_paginated_items_resource = self.client().get(
'/shoppinglist/{}/items/?l... |
def get_shoppinglist_id(self):
create_shoppinglist_resource = self.create_shoppinglist_resource()
# get id of shoppinglist created
json_shoppinglist_resource = json.loads(
create_shoppinglist_resource.data.decode('utf-8').replace(
"'", "\"")
)
shopping... | This test case verifies that updating a shopping list item with a duplicate name returns a 409 Conflict status code and an "already exist" error message, ensuring the system correctly handles duplicate item name conflicts during updates. | def test_update_item_with_duplicate_name(self):
shoppinglist_id = self.get_shoppinglist_id()
# test API can update shoppinglist item
update_item_resource = self.client().put(
'/items/{}'.format(self.get_item_id(shoppinglist_id)),
data={
'name': 'touring ... |
def get_sessions_from_args(args: argparse.Namespace, create_if_missing: bool = False):
"""
Generate session objects from arguments passed along with the input command
:param args: the input arguments
:param create_if_missing: if no session object exists for a SEID specified in the input arguments,
c... | This function creates PFCP sessions by iterating over session configurations from command-line arguments, crafting session establishment packets, sending them, waiting for responses, and introducing delays between operations. It handles session creation, packet generation, response handling, and sleep intervals as spec... | def create_pfcp_sessions(args: argparse.Namespace) -> None:
for session in get_sessions_from_args(args, create_if_missing=True):
if verbosity > 0:
print("Creating session with SEID %d" % session.our_seid)
pkt = craft_pfcp_session_est_packet(args, session)
send_recv_pfcp(pkt, MSG_... |
def get_sessions_from_args(args: argparse.Namespace, create_if_missing: bool = False):
"""
Generate session objects from arguments passed along with the input command
:param args: the input arguments
:param create_if_missing: if no session object exists for a SEID specified in the input arguments,
c... | This function modifies existing PFCP sessions by crafting and sending session modification packets. It iterates through sessions retrieved from arguments, prints progress if verbosity is enabled, sends PFCP messages with expected response types, and introduces delays between operations using the specified sleep time. | def modify_pfcp_sessions(args: argparse.Namespace) -> None:
for session in get_sessions_from_args(args, create_if_missing=False):
if verbosity > 0:
print("Modifying session with SEID %d" % session.our_seid)
pkt = craft_pfcp_session_modify_packet(args, session)
send_recv_pfcp(pkt,... |
def get_sessions_from_args(args: argparse.Namespace, create_if_missing: bool = False):
"""
Generate session objects from arguments passed along with the input command
:param args: the input arguments
:param create_if_missing: if no session object exists for a SEID specified in the input arguments,
c... | This function deletes PFCP sessions based on command-line arguments. It iterates over sessions retrieved from arguments, crafts and sends PFCP session deletion packets, waits for responses, removes sessions from tracking, and pauses between operations using a specified sleep time. | def delete_pfcp_sessions(args: argparse.Namespace) -> None:
for session in get_sessions_from_args(args, create_if_missing=False):
if verbosity > 0:
print("Deleting session with SEID %d" % session.our_seid)
pkt = craft_pfcp_session_delete_packet(session)
send_recv_pfcp(pkt, MSG_TY... |
def prev_screen(self, channel):
if not self.screen_transition_in_progress:
self.screen_transition_in_progress = True
new_index = (self.current_screen_index - 1) % len(self.screens)
self._deactivate_screen(self.current_screen_index)
self._activate_screen(new_index)... | The main task of the code is to continuously monitor a button queue for input events, trigger screen navigation (previous/next) based on specific button pins, and handle image refresh requests by updating the display when needed. The loop ensures responsive handling of user interactions and visual updates while maintai... | def _loop(self):
while self.is_running:
if not self.button_queue.empty():
channel = self.button_queue.get()
if channel == self.button_prev_pin:
self.prev_screen(channel)
elif channel == self.button_next_pin:
self... |
def get_valid_moves(board):
return [col for col in range(COLS) if is_valid(board, col)]
def is_terminal_node(board):
# is draw
valid_cols = get_valid_moves(board)
isDraw = len(valid_cols) == 0
if isDraw:
return 'D', True
# check horizontal
for c in r... | The code implements the minimax algorithm with alpha-beta pruning for a game, evaluating optimal moves by recursively exploring possible board states. It selects the best move for the current player, considering heuristic scores and terminal game states, while tracking paths and results for analysis. | def minimax(board, depth, maximizing_player, printPaths=False):
# if it's over return as such
# get possible moves
valid_moves = get_valid_moves(board)
# run minmax staring with one of the possibilities at random
random.shuffle(valid_moves)
# return board , true if we have reached a win OR a ti... |
def get_valid_moves(board):
return [col for col in range(COLS) if is_valid(board, col)]
def is_terminal_node(board):
# is draw
valid_cols = get_valid_moves(board)
isDraw = len(valid_cols) == 0
if isDraw:
return 'D', True
# check horizontal
for c in r... | This function implements the alpha-beta pruning algorithm for a game AI, recursively evaluating possible moves on a board to determine the optimal action. It maximizes/minimizes heuristic scores, prunes suboptimal branches, and returns the best move, score, and auxiliary data for analysis. | def alphabeta(board, depth, maximizing_player, alpha, beta, printPaths=False):
# if it's over return as such
# get possible moves
valid_moves = get_valid_moves(board)
# run minmax staring with one of the possibilities at random
random.shuffle(valid_moves)
# return board , true if we have reache... |
def get_valid_moves(board):
return [col for col in range(COLS) if is_valid(board, col)]
def is_terminal_node(board):
# is draw
valid_cols = get_valid_moves(board)
isDraw = len(valid_cols) == 0
if isDraw:
return 'D', True
# check horizontal
for c in r... | The code implements a Minimax algorithm with **alpha-beta pruning** and **move ordering** to determine the optimal move for a player in a turn-based game (likely Connect Four). It evaluates valid moves, sorts them by heuristic value to prioritize promising paths, and recursively explores game states while pruning subop... | def moveorder(board, depth, maximizing_player, alpha, beta, printPaths=False):
# if it's over return as such
# get possible moves
valid_moves = get_valid_moves(board)
# Sort moves for move ordering
# return board , true if we have reached a win OR a tie OR a full board
result, is_terminal = is... |
def parse_first_line(self) -> tuple:
first_line = self.http_message_factory.message_temp.split('\n')[0]
err = Exception(f'[parse_first_line] failing to parse first line. \'{first_line}\'')
first_line_tokens = [x for x in re.split('\s+',first_line) if x]
if len(first_line_tokens) == 3:
... | The code parses HTTP requests by extracting method, path, query parameters, headers, and protocol version. It processes the request line, splits the URL path from query string, unescapes URLs, and populates a structured `args` dictionary. It configures response settings (e.g., HTTP/1.1 keep-alive), analyzes headers, se... | def parse(self) -> None:
try:
self.args = {
'query_string':{},
'flags':[],
'template_args':{},
'cookies': {},
'address': self.http_message_factory.a... |
def allowed_actions(self,location,board,turn):
# It also uses possible_actions function
# Returns List of possible moves for AI Agent
if turn == 1:
pos = copy.deepcopy(location)
slime = 10
else:
pos = copy.deepcopy(location)
slime = 20
... | The code determines the optimal move for a bot in a grid-based game by evaluating allowed actions (empty spaces and slime blocks). It uses the minimax algorithm with a depth of 8 to assess potential moves, prioritizing positions that maximize the bot's advantage. If only slime moves are available, it checks their valid... | def findBestMove(self):
copied_board = copy.deepcopy(self.grid)
best_value = -9999
best_move = copy.deepcopy(self.bot_position)
# Allowed action return all allowed actions bot slime plus empty
zero_blocks,slimed = self.allowed_actions(self.bot_position,copied_board,0)
sel... |
def findBestMove(self):
copied_board = copy.deepcopy(self.grid)
best_value = -9999
best_move = copy.deepcopy(self.bot_position)
# Allowed action return all allowed actions bot slime plus empty
zero_blocks,slimed = self.allowed_actions(self.bot_position,copied_board,0)
sel... | The code handles a bot's movement in a grid-based game, updating its position, score, and visual elements. It checks if the bot's best move is valid or blocked, updates the grid with new positions, triggers splash effects, and resets the turn. If the move is "slimed," it adjusts the bot's position through a special mov... | def bot_playing(self):
self.BOT_POS = copy.deepcopy(self.bot_position)
print(self.bot_position)
move,is_slimed = list(self.findBestMove())
self.BOT_TURNS += 1
if move == self.bot_position:
# print("Blocked, No score awarded")
self.turn = 1
elif is_... |
def evaluateBoard(self,board):
player_score = 0
bot_score = 0
for row in range(len(board)):
for col in range(len(board[row])):
if board[row][col] == 0:
return 0
elif board[row][col] == 1 or board[row][col] == 10 :
... | Your return This code handles mouse press events in a turn-based game, evaluating the game board to check for win/loss conditions. It updates the player's move if valid, tracks scores, switches turns, and triggers a game-over screen when conditions (e.g., 100/200/50 result) are met. It also includes logic to determine ... | def on_mouse_press(self, x, y, button, modifiers):
"""
Called when the user presses a mouse button.
"""
result = self.evaluateBoard(self.grid)
print(self.NUMBER_OF_TURNS)
print(self.BOT_TURNS)
if result == 0:
print("Continue State")
print(s... |
def TREEPOLICY(node):
#a hack to force 'exploitation' in a game where there are many options, and you may never/not want to fully expand first
#print 'len(node.children)',len(node.children)
while node.fully_expanded():
node = BESTCHILD(node,SCALAR)
#print 'best child',node.state.moves
if no... | The code implements the UCT (Upper Confidence Bound) algorithm for Monte Carlo Tree Search (MCTS). It iteratively selects nodes via TREEPOLICY, simulates outcomes with DEFAULTPOLICY, updates rewards via BACKUP, and finally returns the best child of the root node based on accumulated values, optimizing exploration-explo... | def UCTSEARCH(budget,root):
for iter in range(int(budget)):
#print iter
front=TREEPOLICY(root)
#print 'len(node.children)',len(front.children)
for child in front.children:
#print "computing reward"
reward=DEFAULTPOLICY(child.state)
BACKUP(child,reward)
return BESTCHILD(root,0) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.