dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_image_top_cam():
# Image from the top camera
return_code, return_value = sim.simxGetStringSignal(clientID=clientID, signalName="top_cam_image",
operationMode=sim.simx_opmode_blocking)
if return_code == 0:
image = sim.simxUnpackFloats(re... | The code navigates a robot to a target object by first rotating to face it using camera feedback, then moving forward while adjusting direction to center the object in the visual field. It handles a specific case for "COMPRESSED" objects by focusing on the image's bottom half. The robot continues moving until it reache... | def go_to_object(object: Entity):
speed = 300
image = get_image_top_cam()
middle = int(len(image)/2)
if object == COMPRESSED:
image = image[middle:,middle-10:middle+10] # only look at the bottom half of the image
# Spin until the target object is in visual field
while not contains_obj... |
def get_image_top_cam():
# Image from the top camera
return_code, return_value = sim.simxGetStringSignal(clientID=clientID, signalName="top_cam_image",
operationMode=sim.simx_opmode_blocking)
if return_code == 0:
image = sim.simxUnpackFloats(re... | This code navigates a robot to align with a designated drop-off point (PLANT_COLLECTOR/TRASH_COLLECTOR) by adjusting movement based on real-time visual feedback. It detects the target location, calculates positional error, avoids obstacles, and adjusts speed to center the object over the drop-off. The function handles ... | def go_to_dropoff(object: Entity):
dropoff = PLANT_COLLECTOR if object.name == "PLANT" else TRASH_COLLECTOR
speed = 30
image = get_image_top_cam()
middle = int(len(image)/2)
status = 0
if object in [TRASH, TRASH_2]:
compress()
print("not carrying object, finding compressed obje... |
def runBaselineMatrices(targetRanks, saveName):
results = {}
names = ['rank = 2', 'rank = 4', 'rank = 6', 'rank = 8']
matPaths = [
'matrices/SPLRI_n4033_r2.mat',
'matrices/SPLRI_n4033_r4.mat',
'matrices/SPLRI_n4033_r6.mat',
'matrices/SPLRI_n4033_r8.mat',
]
results['targetRanks'] = targetRanks
for name, ... | The code defines a `main()` function that executes different computational tasks based on the `ACTION` variable: runs baseline matrices for 'baseline', conducts experiments for 'experiment', plots flop counts for 'flop', or raises an error for invalid actions. | def main():
if ACTION == 'baseline':
runBaselineMatrices(NUM_EMBED_ROWS_LIST, 'baseline')
elif ACTION == 'experiment':
runExperiments(completeInverse=False)
elif ACTION == 'flop':
plot_analytical_flop_counts(n, p_frac_list, r_list, 'flop_{}'.format(n))
else:
raise ValueError('Invalid ACTION: {}'.format(ACTI... |
def move_backwards(board: Board, user_input: str, turn: int, p_boards: Previous):
"""
Move the game a few steps backwards
"""
how_many = handle_backwards_input(user_input, turn)
board = p_boards.roll_back(how_many, board)
# I return turn too because when we roll the playing board back we want th... | The function `player_move` processes and validates a player's move in a board game, ensuring the selected piece belongs to the correct team and the move is legally executable. It checks for syntax errors, movement validity, and updates the game state. After a valid move, it assesses if the opposing king is in check, ch... | def player_move(board: Board, king: Soldier_Classes.King, turn: int, location: Locations, p_boards: Previous, player_input=''):
"""
handles all the functions that happen when a player move is being made,
checking that the move is valid
checking that the piece that is trying to be moved belongs to the pl... |
def handle_input():
user_input = ""
valid = False
while not valid:
user_input = input(OPENING_MSG)
if user_input != '1' and user_input != '2':
print(f"{Colors.RED}Invalid pick.{Colors.END}")
else:
valid = True
return user_input
def connection_input():
... | The code defines a client function that either runs locally or connects to a server. It establishes a socket connection, receives messages, sets a team based on initial data, and processes incoming messages until a mate is identified. The client handles input, manages network communication, and terminates the connectio... | def client_main():
team_set = TEAM_SET
online = handle_input()
team = ""
if online == '1':
main.main()
else:
ip, port = connection_input()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
print(f"Connected to {ip}:{port} successfully... |
def initialize_locations(board: Board):
black = get_all_pieces(board, B)
white = get_all_pieces(board, W)
ls = Locations(black, white)
return ls
def reset_msg(board: Board, team: str):
"""
we want the message that we print to the console to be reset each turn
"""
msg = '%s\n%s' % (str(bo... | This code implements a single-player chess game loop, handling turn-based moves, checkmate detection, and message updates. It initializes the board, tracks previous states, and processes player moves until checkmate is achieved, updating the game state and displaying progress messages each turn. | def main():
"""
main function of the Chess game when it's not multiplayer
"""
playing_board = Board()
team_locations = initialize_locations(playing_board)
p_boards = Previous(playing_board)
turn = 0
mate = False
print(reset_msg(playing_board, TURNS[turn % 2]))
while not mate:
... |
def is_cell_moveable(self, x1, y1, x2, y2):
"""
Checks if the cell in board[x][y] could be moved to
:param x1: the first index of the current cell
:param y1: the second index of the current cell
:param x2: the first index of the wished cell
:param y2: the second index of ... | The function validates a player's move in a board game by checking if the move is permissible according to piece-specific rules, ensuring the path is clear, and verifying king safety. It handles special moves like en passant and castling, returns True for valid moves, and updates the board state (e.g., capturing pieces... | def player_move(self, move_from: list, move_to: list, test_move=False):
"""
Handles the player's move and checking if it is valid
:param move_from: current cell the piece is in
:param move_to: where the player wants the piece to move
:param test_move: if we want to check if it's ... |
def find_total_vertices(G):
default_dictionary = defaultdict(list)
for u, v, weight in G:
default_dictionary[u].append((v, weight))
default_dictionary[v].append((u, weight))
len_of_dict = len(default_dictionary)
return len_of_dict
def find_root(parent, vertex):
if parent[vertex] == v... | This function implements Kruskal's algorithm to compute the Minimum Spanning Tree (MST) of a graph. It sorts edges by weight, uses Union-Find to detect cycles, and selects edges to build the MST while accumulating total weight. It returns the MST's total weight, its edges, and the execution time. | def kruskals_mst(G):
start_time = time.time()
min_spanning_tree = []
mst_weight, index, mst_edges = 0, 0, 0
G = sorted(G, key=lambda edge: edge[2])
parent_list = []
rank_list = []
n_vertices_dict = find_total_vertices(G)
for node in range(n_vertices_dict):
rank_list.append(0)
... |
def north():
print ("To go North press n then enter")
def east():
print ("To go East press e then enter")
def west():
print ("To go West press w then enter")
def control():
#This will create a randomly named Controler to interact with
global npcname
global response
#Below is a list, we can s... | The code defines a game stage where the player chooses a direction (North, East, or West) to explore different environments. It provides feedback based on the choice, handles invalid inputs with retries, and triggers subsequent game functions (control(), enemy(), fight()) after the decision. The player's choices lead t... | def stage1():
print ("\nIn the distance to the North you can see a Forrest, to the East you can see a River and to the West Space.")
#Remember those functions we created at the start of the code? Well here we are using them in the game.
north()
east()
west()
move = input("Where would you like t... |
def prob_CRC_pass(c):
res = 0
if c == 0:
return res
else:
for i in range(1, c+1):
res += prob_CRC_pass_no_decode(i) * prob_com(c, i, DECODE_PASS)
return res;
def fail_all_major_correct(c):
res = 0
if c == 0 or c == 1 or c == 2:
return 0
else:
for i in range (3, c+1):
temp = prob_com(M, M, major_cor... | The function `check_all` aggregates results from multiple error-checking functions: CRC pass verification, major correctness failures, symbol lookup errors for two contexts, and unrecoverable errors. It sums their outputs, likely to assess overall system integrity or error severity by combining individual diagnostic ch... | def check_all(c):
return prob_CRC_pass(c) + fail_all_major_correct(c) + fail_one_symbol_lookup(c , 1) + fail_one_symbol_lookup(c , 2) + unrecover(c) |
def get_params():
"""Returns the command line arguments."""
parser = argparse.ArgumentParser(description="""
This script takes an input of a gff file (usually generated by Proka) with a
##FASTA section containing the sequence data, and outputs a FASTA file of all
the control regions fou... | The main task of the code is to extract specific genomic regions from a GFF file based on predefined gene annotations. It identifies start/end boundaries using prioritized gene markers (e.g., mtRNA-Ile, 12S rRNA) and anchors (e.g., NADH-ubiquinone oxidoreductase chain 2). The tool processes each sequence record, locate... | def main():
"""Main CLI entry point for extract-control.py"""
args = get_params()
# make a new file, either forcing overwrite of the old file or not, depending on the setting.
with open(args.input, "r") as seq_file, open(args.output, "w" if args.force else "x") as out_file:
# highest to lowest... |
def loadImg(self, directory):
''' store img name to list dict '''
try:
foldernames = []
for folder in os.listdir(directory):
if os.path.isdir(os.path.join(directory, folder)):
foldernames.append(folder)
print("folders in data\n... | This code initializes a GUI application for image annotation, enabling users to label lines, polygons, points, and objects on images. It sets up a canvas to display images, provides buttons for adding/deleting labels, navigating through images, and saving annotations. The interface includes options to select label type... | def __init__(self,path):
super(Window,self).__init__()
self.img_path = os.getcwd()+os.sep+path
# a figure instance to plot on
self.figure = Figure(tight_layout=True, dpi=96)
self.axes = self.figure.add_subplot(111)
self.axes.set_axis_off()
self.axes.get_xaxis().s... |
def write_to_output(self, to_write):
'''
write `to_write` both to the output window
and to the log file of the running scripts
'''
if self.output_window_visible:
self.output_text_widget.insert(to_write)
self.running_script.log += to_write
def scroll_output_win... | This function monitors a running script by copying output from `self.line_buffer` to output/log files, checks if the script crashed or ended via `poll()`, and either reschedules monitoring or processes script completion and queues the next script. It also scrolls output windows if autoscroll is enabled. | def monitor_script_process(self):
'''
Whilst the script is running, copy what the
`reader` function has put into the `self.line_buffer`
and write it to the output and log files.
This function will detect when the running script crashed
or ended, append the output/log acc... |
def plot_residual(self):
"""
Plots number of iterations vs. residual and saves the plot
params: none
returns: none
"""
plt.clf()
plt.plot(range(1, self.max_iter+1), self.residual)
plt.xlabel("Number of iterations")
plt.ylabel("Residual "... | The main task of the code is to generate multiple diagnostic plots for model analysis, including residual errors, norm values, sparsity patterns, and non-zero element distributions. It conditionally plots either z_nonzeros or x_nonzeros based on the thresholding parameter, providing visual insights into model behavior,... | def plot_all(self):
self.plot_residual()
self.plot_onenorm()
self.plot_moder()
self.plot_residual_vs_sparsity()
self.plot_t_nonzeros()
if (self.thresholding):
self.plot_z_nonzeros()
else:
self.plot_x_nonzeros() |
def calc_dynamic_window(self, x):
"""
calculation dynamic window based on current state x
"""
# Dynamic window from robot specification
Vs = [self.min_speed, self.max_speed,
-self.max_yaw_rate, self.max_yaw_rate]
# Dynamic window from motion model
Vd... | The main task of the code is to implement the Dynamic Window Approach (DWA) for robot control. It calculates the dynamic window based on the robot's current state, computes optimal control inputs (u) and trajectory to reach the goal while avoiding obstacles, updates the robot's state with the new trajectory, and publis... | def dwa_control(self, x, goal, ob):
"""
Dynamic Window Approach control
"""
dw = self.calc_dynamic_window(x)
u, trajectory = self.calc_control_and_trajectory(x, dw, goal, ob)
self.x = trajectory[1]
[self.x[3], self.x[4]] = u
self.publish_twist_msg()
... |
def _bind_map_event(self):
self._bind_map_id = self._body.bind("<Map>", self._handle_map_event, True)
def _bind_unmap_event(self):
self._bind_unmap_id = self._body.bind("<Unmap>", self._handle_unmap_event, True)
def _bind_destroy_event(self):
command = (lambda event: self._handle_destroy_event(e... | The main task of the code is to bind event handlers for window mapping, unmapping, and destruction in a GUI component. It connects the `_bind_map_event`, `_bind_unmap_event`, and `_bind_destroy_event` methods to manage the component's lifecycle, ensuring proper responses to window state changes like visibility, removal... | def _bind(self):
self._bind_map_event()
self._bind_unmap_event()
self._bind_destroy_event() |
def _check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type==pygame.KEYDOWN:
self._keydown_events(event)
elif event.type==pygame.KEYUP:
self._keyup_events(event)
... | This code defines the main game loop that continuously checks for events, updates game elements (ship, bullets, events), renders the screen with the background color and score, handles active/inactive game states, maintains a 60 FPS frame rate, and displays the updated screen. | def run_game(self):
while True:
self._check_events()
self.screen.fill(self.settings.background_color)
self.sb.show_score()
if not self.game_active:
self.button.draw_button()
if self.game_active:
self.ship.update()
... |
def recieve_data(self):
'''
Recieves the changed world from the server
'''
header = self.conn.recv(8).decode("utf-8")
raw_data = self.conn.recv(int(header)).decode("utf-8")
return raw_data
def update_varables(self):
'''
Updates all self varables to be usf... | This code connects to a server, receives and parses JSON data to initialize game world, player, and entities, sets up physics, and continuously updates game state by processing incoming data while maintaining the connection. | def run(self):
'''
Connects to the server
'''
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as self.conn:
self.conn.connect((self.host, self.port))
self.connected = True
logging.info("Connected to server")
# Gets the first load... |
def initial_setup(limite_externe, voltage_high, **kwargs):
'''Start femm and setup problem definition and set boundary condition.'''
if kwargs.get('hide') is True:
femm.openfemm(1)
femm.main_minimize()
else:
femm.openfemm()
# newdocument(doctype)
# From manual: Creates a new... | This function calculates the capacitance between primary and secondary sides of a planar transformer using FEMM's electrostatic analysis. It sets up the geometry, applies boundary conditions, meshes the model, solves the field distribution, and computes capacitance from the charge on secondary conductors. Optional visu... | def calc_field_distribution(tg, voltage_high=1, view=None, **kwargs):
''' Setup of electro-static problem in femm to calculate capacitance
between primary and secondary side of planar transformer. Additionally,
electric field can be investigated
Args:
tg (:obj:'TransformerGeometry'): tg contain... |
def make_board(dimensions):
"""
if given a dimensions, this creates an empty board with all the values set as
false
"""
if len(dimensions)==1: #base case if dimensions is 1
lst=[]
for item in range(dimensions[0]):
lst.append(False) # we want to make a board with everythin... | The code initializes a new N-dimensional Minesweeper game. It creates a board with bomb placements ('.') and updates adjacent cells with neighbor counts. A mask tracks revealed cells, initially all hidden. The game state dictionary includes dimensions, board, mask, and state ('ongoing'). Bombs are placed, and neighbori... | def new_game_nd(dimensions, bombs):
"""
Start a new game.
Return a game state dictionary, with the 'dimensions', 'state', 'board' and
'mask' fields adequately initialized.
Args:
dimensions (tuple): Dimensions of the board
bombs (list): Bomb locations as a list of lists, each an
... |
def get_value(board,coordinate):
"""
given a coordinate, we want to get the value
"""
if len(coordinate)==1: #basecase is when we are in 1d
return board[coordinate[0]]
return (get_value(board[coordinate[0]],coordinate[1:]))
def set_board(board,coordinate,value):
"""
given a created b... | The function `dig_nd` recursively reveals a square and its neighboring squares in a multi-dimensional Minesweeper-like game, updating the game's mask and state. It starts at given coordinates, revealing squares only if they are not bombs or adjacent to bombs. If a bomb is revealed, the state becomes "defeat"; if all sa... | def dig_nd(game, coordinates, check = True):
"""
Recursively dig up square at coords and neighboring squares.
Update the mask to reveal square at coords; then recursively reveal its
neighbors, as long as coords does not contain and is not adjacent to a
bomb. Return a number indicating how many squ... |
def negate_clauses(clauses):
negative_clauses = []
for clause in clauses:
negative_clauses.append(np.negative(np.array(clause)).tolist())
distributive_clauses = to_CNF(negative_clauses)
negators = []
for element in distributive_clauses:
negators.append(list(set(element)))
nega... | The code implements the **propositional logic resolution algorithm** to determine if a clause `alpha` is entailed by a knowledge base `KB`. It negates `alpha`, combines it with `KB`, and iteratively resolves clause pairs to derive new clauses. If a contradiction (empty clause) is found, it writes "YES" and returns `Tru... | def pl_resolution(KB, alpha, index):
""" Open file stream """
out_file = open(r'..\OUTPUT\output' + str(index + 1) + '.txt', 'w')
""" Negate the alpha clauses to add it into KB """
not_alpha = negate_clauses(alpha)
""" Add KB AND NOT alpha into KB """
# Unpack lists of lists
clauses = [*KB... |
def point_counter(points):
if points >= 1 < 10:
print("Try to get to Maori days next time. Thanks for playing")
elif points >= 10 < 20:
print("You completed Maori numbers well done")
elif points >= 20 < 30:
print("You completed Maori days amazing job")
elif points == 30:
... | The code quizzes the user on Maori month names, awarding points for correct answers, and directs them to next steps based on input. It validates responses, tracks scores, and offers progression to additional content or exit options. | def maori_months(points):
starter = input("Do you want to go through the 10 questions? (Y/N): ").upper()
if starter == 'Y':
print("")
elif starter == 'N':
print("Goodbye")
exit()
else:
print("That is not an answer")
maori_months(points)
september = input("""Qu... |
def point_counter(points):
if points >= 1 < 10:
print("Try to get to Maori days next time. Thanks for playing")
elif points >= 10 < 20:
print("You completed Maori numbers well done")
elif points >= 20 < 30:
print("You completed Maori days amazing job")
elif points == 30:
... | The code presents a quiz where users answer 10 questions about Maori day names, earning points for correct answers, and then decide whether to proceed to Maori months or additional content, with error handling for invalid inputs. | def maori_days(points):
start = input("Do you want to go through the 10 questions? (Y/N): ").upper()
if start == 'Y':
print("")
elif start == 'N':
print("Goodbye")
exit()
else:
print("That is not an answer")
maori_days(points)
tuesday = input("""Question 1
Tu... |
def point_counter(points):
if points >= 1 < 10:
print("Try to get to Maori days next time. Thanks for playing")
elif points >= 10 < 20:
print("You completed Maori numbers well done")
elif points >= 20 < 30:
print("You completed Maori days amazing job")
elif points == 30:
... | The code conducts a 10-question quiz testing knowledge of Maori number words through arithmetic problems, awarding points for correct answers and allowing users to proceed to additional Maori-related content or exit. It validates user input, tracks scores, and branches to other functions based on responses. | def maori_numbers():
starter = input("Do you want to go through the 10 questions? (Y/N): ").upper()
if starter == 'Y':
print("")
elif starter == 'N':
print("Goodbye")
exit()
else:
print("That is not an answer")
maori_numbers()
points = 0
nine = input("""Qu... |
def load_materials(self):
"""
Load materials from a directory. We assume that the directory contains .blend
files with one material each. The file X.blend has a single NodeTree item named
X; this NodeTree item must have a "Color" input that accepts an RGBA value.
"""
for ... | This code initializes a 3D environment by loading shape/material directories, parsing configuration parameters, and adding objects (with shapes, scales, positions, orientations, colors, and materials) to the scene. It processes "objects," "occluders," "desks," and optionally a back wall, applying materials and colors b... | def __init__(self, config, shape_dir, material_dir, back_wall):
self.shape_dir = shape_dir
self.material_dir = material_dir
self.obj_names = []
self.mask_nodes = []
self.shapes = []
self.scales = []
self.colors = []
self.load_materials()
self.colo... |
def _get_path_by_id(self, index):
return list(self._current_music.keys())[index]
def filter(self, filter_seq):
self._current_filter = filter_seq
if filter_seq != '' or self._only_favourite_mode:
self._current_music.clear()
for path, music_data in self._music.items():
... | This method toggles the favorite status of the currently displayed music item in the database and local storage. It updates the music database entry, flips the local music data's favorite flag, resets the display index if in favorite-only mode, then reapplies filters and refreshes the music interface. | def favourite(self):
if self._shown_music_data is None:
return
path = self._get_path_by_id(self._shown_music_index)
data = Query()
music_data = self._music_db.search(data.path == path).__getitem__(0)
self._music_db.update({'favourite': not music_data.get('favourite')... |
def build_C(A, B, C, D, indicies):
"""This function rewrites C and D in the system to correspond to the state variables that were chosen as hidden
or manifest.
:param:
A, B, C, D are state space matricies for an LTI, here D and C should be such that we assume that all the state
variables are manifes... | The function `ret_PQ` processes input matrices (A, B, C, D) and an index list to compute and format matrices P and Q for visualization. It converts matrices to NumPy arrays, modifies them using `build_C`, derives P and Q via `find_PQ`, simplifies them with `simplify_tf`, calculates vulnerability scores for Q using `vul... | def ret_PQ(A, B, C, D, index):
"""
Returns P and Q ready for visualization and with vulnerability scores as well.
:param A: matrix
:param B: matrix
:param C: matrix
:param D: matrix
:param index: list of incidices of exposed variables
:return: P and Q
"""
A = np.matrix(A)
B =... |
def removeLayersByTag(self, tag):
#if tag in ['dem', 'study', 'subcatchment']:
# gid = 'general'
#elif tag in ['landuse']:
# gid = 'landuse'
#elif tag in ['soil']:
# gid = 'soil'
#elif tag in ['linear']:
# gid = 'linear'
#elif tag in ['... | This method resets the project environment by hiding UI elements, removing existing layers/groups tagged with specific steps, and configuring the DEM (Digital Elevation Model) data. It retrieves the DEM file path, extracts its coordinate reference system (CRS) using GDAL, and displays the DEM layer with the 'input' tag... | def checkDEM(self):
self.changeProjectPathButton.setVisible(False)
# reset study and subcatchment
# TODO hide doStep* buttons
#self.doStep1Btn.setVisible(False)
#self.mQgsFileStudyArea.blockSignals(True)
#self.mQgsFileSubcatchment.blockSignals(True)
#self.mQgsFil... |
def doStep1(self, uselessBool, successMethod=None):
#self.generateCatchmentBtn.setVisible(False)
#self.resetLanduse()
#self.resetLinears()
#self.resetSoil()
self.removeLayersByTag('step1')
if successMethod == None:
taskSuccessMethod = self.step1Finished
... | This function automates step execution based on previous progress and checkbox states. It triggers doStep1-doStep4 methods conditionally, passing parameters like auto-launch flags. If all steps complete, it calculates and prints the total process duration since project loading. | def autoLaunch(self, previous=0):
if previous == 0 and self.step1Check.isChecked():
self.doStep1(True, self.step1FinishedAuto)
elif previous < 2 and self.step2Check.isChecked():
self.doStep2(True, self.step2FinishedAuto)
elif previous < 3 and self.step3Check.isChecked():... |
def _infer_data(image_bgr, image_shape, gt_box_new, gt_label, gt_valid_new):
image_shape = image_shape[:2]
input_data = image_bgr, image_shape, gt_box_new
if config.keep_ratio:
input_data = rescale_column_test(*input_data, config=config)
else:
input_data = resize... | This function performs data augmentation on images and ground truth boxes during training. It converts RGB to BGR, pads/truncates boxes, applies random flips, expansions, rescaling, normalization, and transposes data. It returns augmented image data along with labels and validity flags for training, or inference data w... | def _data_aug(image, box, is_training):
"""Data augmentation function."""
pad_max_number = config.num_gts
if pad_max_number < box.shape[0]:
box = box[:pad_max_number, :]
image_bgr = image.copy()
image_bgr[:, :, 0] = image[:, :, 2]
image_bgr[:, :, 1] = image[:,... |
def get_agent_obs(self):
_obs = []
for agent_i in range(self.n_agents):
for row in range(len(self._full_obs[0])):
for col in range(len(self._full_obs[1])):
_obs.append(self._full_obs[row][col])
_obs.append(self.inventory['tree'])
_obs.appe... | The code processes agents' actions in a multi-agent environment, updating their positions and checking for termination conditions. If an agent hits fire or all agents perform a specific action (breaking an item), all agents are marked as done, and rewards are assigned. Otherwise, the step count increments, and the envi... | def step(self, agents_action):
rewards = [0 for _ in range(self.n_agents)]
if (self._step_count >= self._max_steps):
for i in range(self.n_agents):
self._agent_dones[i] = True
return self.get_agent_obs(), rewards, self._agent_dones, self.observation_cntr
... |
def get_valid_name(self, name):
"""
Return a filename, based on the provided filename, that's suitable for
use in the target storage system.
"""
name = str(name).replace("\\", "/")
# name = self._full_path(name)
return name
def delete(self, name):
"""
... | The function generates a unique filename for storing content by either overwriting existing files (if enabled) or creating a new name with an incrementing index. It checks for existing files and their content to avoid duplicates, returning the filename and a status indicating if the file already existed. | def get_available_name(self, name, content, max_length=None):
"""
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
formatted_name = self.get_valid_name(name)
new_name = formatted_name
if self.OVERWRITE_... |
def get_valid_name(self, name):
"""
Return a filename, based on the provided filename, that's suitable for
use in the target storage system.
"""
folder, filename = self.extract_folder_and_filename(name)
filename = self._id_validation(filename)
res = filename.rspli... | The main task of the code is to generate a unique filename for storing content by checking if the target file already exists. If overwriting is enabled, it deletes the existing file; otherwise, it appends an index to the filename until a unique name is found. It also checks content equality to avoid redundant storage i... | def get_available_name(self, name, content, max_length=None):
"""
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
formatted_name = self.get_valid_name(name)
new_name = formatted_name
if self.OVERWRITE_... |
def extract_folder_and_filename(self, path):
path = str(path).replace("\\", "/")
folders = path.split("/")
if len(folders) == 0: # file.txt
last_folder = self.APPWRITE_BUCKET_ID
file_name = path
elif len(folders) == 1: # /file.txt
last_folder = self.... | The function `save` stores content into a specified file, handling file objects and directory creation. It extracts the folder and filename from the given `name`, wraps the content in a `File` object, ensures the folder exists, and generates a valid file path using `get_available_name`. If no conflicts are detected, it... | def save(self, name, content, max_length=None):
"""
Save new content to the file specified by name. The content should be
a proper File object or any Python file-like object, ready to be read
from the beginning.
"""
folder, org_filename = self.extract_folder_and_filename(... |
def filter_extras(t: ipy.OptionType | type) -> ipy.OptionType | type:
if typing.get_origin(t) == typing.Annotated:
temp_t = get_from_anno_type(t)
if temp_t == CONSUME_REST_MARKER:
return filter_extras(typing.get_args(t)[0])
t = temp_t
if is_optional(t):
non_optional_... | This function converts a given Python type or `ipy.OptionType` instance into the corresponding `ipy.OptionType` enum member, handling type unions and fallbacks. It checks if the input is already an `OptionType`, attempts to construct one, or maps built-in types (e.g., `str`, `int`) and Discord-related classes (e.g., `U... | def get_option(t: ipy.OptionType | type):
t = filter_extras(t)
if isinstance(t, ipy.OptionType):
return t
with contextlib.suppress(ValueError):
return ipy.OptionType(t)
if t == str:
return ipy.OptionType.STRING
if t == int:
return ipy.OptionType.INTEGER
if t ==... |
def filter_extras(t: ipy.OptionType | type) -> ipy.OptionType | type:
if typing.get_origin(t) == typing.Annotated:
temp_t = get_from_anno_type(t)
if temp_t == CONSUME_REST_MARKER:
return filter_extras(typing.get_args(t)[0])
t = temp_t
if is_optional(t):
non_optional_... | The function determines channel types from an annotation by checking if it's a subclass of `ipy.BaseChannel` or a union type. It uses `REVERSE_CHANNEL_MAPPING` to map annotations to channel types, returning a list of matched types or `None` if no matches are found. | def resolve_channel_types(anno: typing.Any):
channel_types = []
anno = filter_extras(anno)
if isinstance(anno, ipy.OptionType):
return None
if issubclass_failsafe(anno, ipy.BaseChannel) and (
(chan_type := REVERSE_CHANNEL_MAPPING.get(anno)) is not None
):
channel_types = [... |
def dataset_info_to_dict(dataset_info: tfds.core.DatasetInfo) -> dict:
info_dict = {
'name': dataset_info.name,
'version': str(dataset_info.version),
'description': dataset_info.description,
'homepage': dataset_info.homepage,
'citation': dataset_info.c... | This function converts a TensorFlow Datasets (TFDS) builder into an H5 file format by serializing metadata, shape/dtype information, and episode data. It creates H5 groups for `meta_info`, `shape_type_info`, and `episodes`, populates them with dataset attributes, merged feature shapes/dtypes, and individual episodes. E... | def _add_builder_to_h5(self, h5_file: h5py.File, tfds_builder: tfds.core.dataset_builder.DatasetBuilder):
# |__/meta_info
# |__/shape_info
# |__/episodes
info = tfds_builder.info
info_dict = self.dataset_info_to_dict(info)
info_group = h5_file.create_group(name='meta_i... |
def numtobin(data):
newdata = data.copy()
for col in data.columns:
if col == "label":
break
coll = data[col]
if(coll.dtype == np.int64):
median = coll.median()
for i in range(len(coll)):
num = coll[i]
result = ""
if num >= median:
result = "great... | The code trains an ID3 decision tree using specified gain and depth parameters on a training dataset, cleans and processes the data, constructs the tree, and evaluates its accuracy on a test dataset. It handles command-line arguments for configuration, performs data preprocessing, and outputs the model's performance. | def main():
if(len(sys.argv)< 5):
print("the arguments should be <gain>, <depth>, <training> <testing>")
gainarg = int(sys.argv[1])
deptharg = int(sys.argv[2])
trainarg = str(sys.argv[3])
testarg = str(sys.argv[4])
traindata = numtobin(load_csv(trainarg))
testdata = numtobin(load_csv(testarg))
... |
def arrstodf(dataarr):
check = dataarr[0]
colnames = []
for i in range(len(check) - 1):
name = "A" + str(i)
colnames.append(name)
#colnames.append("weights")
colnames.append("label")
data = np.array(dataarr)
df = pd.DataFrame(data = data, columns = colnames)
##print(df.head())
return df
def s... | The main task of the code is to generate a bagged ensemble of decision trees by subsampling the input data T times, training an ID3-based decision tree (ID3_run) on each subsample, and collecting the resulting trees in a list. This creates multiple models for ensemble learning, leveraging bagging to improve robustness ... | def makebaggedtrees(gainID, data, T):
trees = []
for i in range(T):
sample = arrstodf(subsample(data))
mytree = ID3_run(gainID, 128, sample, "root", "none", 0)
trees.append(mytree)
#def ID3_run(gainID, maxdepth, data, previousAttr, previousValue, currdepth):
#
return trees |
def subsample(data):#, ratio=1.0): #take m' examples from dataset
#print(data.head())
sample = []
size = data.shape[0]
#n_sample = round(size)# * ratio)
while len(sample) < size: #n_sample:
index = randrange(size)
sample.append(data.iloc[index])
return sample
def arrstodf(dataarr):
check = dataarr[0]
coln... | The main task of the code is to generate a random forest of decision trees by subsampling the input data T times, constructing a decision tree for each subsample using the specified gain function (gainID), and collecting all trees into a list for ensemble learning. | def makerandomforest(gainID, data, T):
trees = []
for i in range(T):
#print("IN RANDOM FOREST")
#print(data.head()) #does not have weights -> check out subsample,
sample = subsample(data)
#print(sample[0])
#in arrstodf?
sampledf = arrstodf(sample)
#need w... |
def arrstodf(dataarr):
check = dataarr[0]
colnames = []
for i in range(len(check) - 1):
name = "A" + str(i)
colnames.append(name)
#colnames.append("weights")
colnames.append("label")
data = np.array(dataarr)
df = pd.DataFrame(data = data, columns = colnames)
##print(df.head())
return df
def m... | This code evaluates the variance of predictions from an ensemble of bagged decision trees. It generates bootstrap samples from training data, trains multiple trees per sample, aggregates predictions, and calculates the variance of these predictions to assess model stability or uncertainty. | def testEXP(traindata, testdata, gainarg, T):
sampledf = None
print("tree variance stuff")
treecollection = []
treeboquet = []
for j in range(5):
for i in range(5):
samples = []
dups = set()
while (len(dups) < 1000):
index = randrange(traindata.shape[0])
if not index in d... |
def persist_to_cache(file, this_dict, suffix):
file = str(file)
filename = hashlib.sha256(file.encode('utf-8')).hexdigest()
filename = filename + suffix
filepath = Path.cwd() / "data" / "cache" / filename
with open(filepath, 'wb') as dictionary_file:
pickle.dump(this_dict, dictionary_file)
def file_in_cache(fil... | The code processes each document in both positive and negative sets as a "victim" by iteratively removing one document, building TF-IDF vectors using a dictionary, and computing distances between the single document and the rest. It leverages caching to optimize performance by storing and reusing precomputed dictionari... | def prepare_with_cache_option():
#
# PART 1 : chose one of the pos_docs as victim
#
# this goes through the pos docs picking one out at a time
indexed_neg_set = {v: k for v, k in enumerate(neg_docs)}
for i in range(len(pos_docs)):
print("processing file %s/%s" % (i, len(pos_docs)))
file = pos_docs[i]
s... |
def get_metadata(dataset, metadata_type="problem"):
assert metadata_type in ["problem", "example"]
assert dataset in ["mbxp", "multi-humaneval", "mathqa-x"], f"Unsupported dataset {dataset}"
dataset_dirmap = {"mbxp": "mbxp",
"multi-humaneval": "multilingual_humaneval",
"mat... | The main task of the code is to load a specified number of few-shot examples from the "mbxp" dataset in a given programming language (e.g., Python). It validates the dataset and language, streams JSONL data, and optionally limits the number of examples while attaching corresponding prompts. The function returns either ... | def get_examples(dataset="mbxp", language="python", num_examples=None):
assert dataset in ["mbxp"], f"No fewshot examples in dataset {dataset}"
metadata, datadir = get_metadata(dataset=dataset, metadata_type="example")
if language.lower() not in metadata:
raise ValueError(f"Language {language} not found in me... |
def create_receiver_singleton(image_id="ami-04a4f29a9644e4693"):
instance = create_new_instance(1, security_group='Monitor', image_id=image_id)[0]
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privkey = paramiko.RSAKey.from_private_key_file('../keys/Leo-remote.pem'... | The main task of the code is to execute a remote receiver script for a specified contract and CSV file, handle potential errors, transfer results from a remote server to a local directory, and perform cleanup. It initializes a receiver singleton, runs a bash script on a remote instance, fetches generated data, and ensu... | def test_2(args):
[contract, script_path, csv, skip] = args
[receiver, receiver_client] = create_receiver_singleton("ami-09ee0d630ab37985d")
print(contract+csv + ": " + receiver.public_ip_address)
try:
execute_remote_command(receiver_client,
"bash ~/scripts/bash/ru... |
def create_receiver_singleton(image_id="ami-04a4f29a9644e4693"):
instance = create_new_instance(1, security_group='Monitor', image_id=image_id)[0]
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privkey = paramiko.RSAKey.from_private_key_file('../keys/Leo-remote.pem'... | This function tests a process involving file transfers and remote command execution. It moves specified binaries to a remote server, executes import scripts for contract data, fetches generated logs, and performs cleanup. The task includes handling both secured and non-optimized transfer variants, using a receiver inst... | def test_3(args):
[contract, script_path, csv, skip] = args
[receiver, receiver_client] = create_receiver_singleton("ami-0e05c3ca6e6db9733")
print(contract+csv + ": " + receiver.public_ip_address)
try:
move_files(receiver_client, "/cs/htuser/choi/public_html/results/test_run2_{0}_secured_transfe... |
def create_new_instance(count, security_group='all-open', image_id="ami-0e65a0ccc7550e6f3"):
ec2 = boto3.resource('ec2', region_name='us-west-1')
instances = ec2.create_instances(
ImageId=image_id,
UserData='#cloud-config\nrepo_upgrade: none',
MinCount=count,
MaxCount=count,
... | The code defines a function `test` that launches two EC2 instances, configures them as a receiver and sender, executes synchronization scripts on both, transfers results, and cleans up resources. It tests data synchronization between instances using specified contracts, scripts, and CSV files, handling exceptions and r... | def test(args):
instances = create_new_instance(2, image_id="ami-0e05c3ca6e6db9733")
[contract, script_path, csv] = args
[receiver, receiver_client] = setup_receiver(instances[0])
[sender, sender_client] = setup_sender(instances[1])
print(contract+csv + ": " + receiver.public_ip_address)
print(c... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board) != EMPTY:
return True
else:
return False
def player(board):
"""
Returns player who has the next turn on a board.
"""
if board == [[EMPTY, EMPTY, EMPTY],
[EMPTY, EM... | The code implements a heuristic-based strategy to determine the optimal move in a Tic-Tac-Toe game. It first checks if the game is terminal, returning an empty action if so. For the current player, it prioritizes winning moves, then blocks the opponent's potential win. If neither applies, it selects the center (1,1) fi... | def minimax(board):
"""
Returns the optimal action for the current player on the board.
"""
if terminal(board) == True:
return EMPTY
currentPlayer = player(board)
if moveToWin(board,currentPlayer) != EMPTY:
return moveToWin(board,currentPlayer)
else:
opponent = ... |
def terminal(board):
"""
Returns True if game is over, False otherwise.
"""
if winner(board) != EMPTY:
return True
else:
return False
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
if terminal(board) == True:
ret... | The function `result` generates a new game board state after applying a specified move `(i, j)` to the current board. It validates that the game is not over and the action is permissible, then creates a deep copy of the board, updates the specified cell with the current player's symbol, and returns the modified board. ... | def result(board, action):
"""
Returns the board that results from making move (i, j) on the board.
"""
(i, j) = action
act = [i,j]
if terminal(board):
raise ValueError("Game over.")
elif act not in actions(board):
raise ValueError("Invalid action.")
else:
p = pla... |
def lastOnehourReport(self,store,localTimezone,startTimestamp,endTimestamp):
return self.calculateUptimeDownTime(store,localTimezone,startTimestamp,endTimestamp)
def lastOneDayReport(self,store,localTimezone,startTimestamp,endTimestamp):
uptimeLastOneDay=0
downTimeLastOneDay=0
if startTi... | The code generates a report by initializing a report entry, retrieving all stores, calculating uptime/downtime metrics (last 1 hour, 1 day, 1 week) for each store in their local time zone, compiling results into a structured data list, updating the report status to 'Completed', serializing the data as JSON, saving the ... | def generateReport(self):
# Report Entry into the table with status Runinng
report=Report(reportId=self.reportId,status='R',data='')
report.save()
# Retrieving all stores
self.stores=Store.objects.all()
for store in self.stores:
# Converting ... |
def setSpeed(self):
""" write docstrings """
if Main.keys == [K_DOWN]: self.__speed = 3
else:
score = 30 if self.__screen.getScore() > 9000 else self.__screen.getScore() // 300
self.__speed = 45 - score
def event(self):
""" write docstrings """
self.__clo... | This code manages a game loop for a Tetris-like game, handling piece spawning, user input, game state checks (pause, game over), automatic piece movement, screen updates, and display rendering using Pygame. It continuously processes events, updates game logic, and renders visuals until the game ends or is paused. | def run(self):
""" write docstrings """
self.__screen.spawnPiece()
while self.__isRunning:
self.setSpeed()
self.event()
self.controls()
self.controlsPaused()
self.controlsGameOver()
if not Main.isOver and not Main.isPaused:... |
def erasePiece(self):
""" write docstrings """
for i in range(len(self.__piece.getTabWithIndex())):
row = int(self.__piece.row+(i//sqrt(len(self.__piece.getTabWithIndex()))))
col = int(self.__piece.col+(i%sqrt(len(self.__piece.getTabWithIndex()))))
if 0 not in (self._... | This method attempts to move a piece left by first erasing it, checking if the new position (col-1, row) is valid, moving the piece left if possible, then re-placing it at the updated position. | def moveLeft(self):
""" write docstrings """
self.erasePiece()
if self.canPlacePiece(Piece.col-1, Piece.row): Piece.goLeft()
self.placePiece(Piece.col, Piece.row) |
def erasePiece(self):
""" write docstrings """
for i in range(len(self.__piece.getTabWithIndex())):
row = int(self.__piece.row+(i//sqrt(len(self.__piece.getTabWithIndex()))))
col = int(self.__piece.col+(i%sqrt(len(self.__piece.getTabWithIndex()))))
if 0 not in (self._... | The main task of the code is to move a game piece to the right on a platform. It first erases the current piece, checks if moving right is valid by verifying space and placement conditions, adjusts the piece's column position if valid, and then redraws the piece at its new position. The function ensures the piece stays... | def moveRight(self):
""" write docstrings """
self.erasePiece()
if (Piece.col + sqrt(len(self.__piece.getTabWithIndex())) < Display.WIDTH_PLATFORM and self.canPlacePiece(Piece.col+1, Piece.row)):
Piece.goRight(Display.WIDTH_PLATFORM - sqrt(len(self.__piece.getTabWithIndex())))
... |
def erasePiece(self):
""" write docstrings """
for i in range(len(self.__piece.getTabWithIndex())):
row = int(self.__piece.row+(i//sqrt(len(self.__piece.getTabWithIndex()))))
col = int(self.__piece.col+(i%sqrt(len(self.__piece.getTabWithIndex()))))
if 0 not in (self._... | The `pivot` method rotates the current piece by first erasing it, checking if the rotated piece can be placed at the specified coordinates, and if valid, rotating and re-placing it. | def pivot(self):
""" write docstrings """
self.erasePiece()
if self.canPlacePiece(Piece.col, Piece.row, self.__piece.getTab()[self.__piece.getNextNumTab()]): self.__piece.pivotPiece()
self.placePiece(Piece.col, Piece.row) |
def erasePiece(self):
""" write docstrings """
for i in range(len(self.__piece.getTabWithIndex())):
row = int(self.__piece.row+(i//sqrt(len(self.__piece.getTabWithIndex()))))
col = int(self.__piece.col+(i%sqrt(len(self.__piece.getTabWithIndex()))))
if 0 not in (self._... | This method attempts to move a game piece down by one row. It first erases the current piece, checks if the new position (same column, row+1) is valid, and if so, moves the piece down. Finally, it places the updated piece in the new position. The task involves handling piece movement validation and updating the game st... | def downPiece(self):
""" write docstrings """
self.erasePiece()
if self.canPlacePiece(Piece.col, Piece.row+1): self.__piece.goDown()
self.placePiece(Piece.col, Piece.row) |
def erasePiece(self):
""" write docstrings """
for i in range(len(self.__piece.getTabWithIndex())):
row = int(self.__piece.row+(i//sqrt(len(self.__piece.getTabWithIndex()))))
col = int(self.__piece.col+(i%sqrt(len(self.__piece.getTabWithIndex()))))
if 0 not in (self._... | This method moves a game piece down to its lowest possible position by incrementally checking each row, updating the score for each valid downward move, then placing the piece in its final position after all possible movements are exhausted. | def placePieceInItsFinalPos(self):
""" write docstrings """
self.erasePiece()
while(self.canPlacePiece(Piece.col, Piece.row+1)):
Piece.row+=1
self.__score += 1
self.placePiece(Piece.col, Piece.row) |
def erasePiece(self):
""" write docstrings """
for i in range(len(self.__piece.getTabWithIndex())):
row = int(self.__piece.row+(i//sqrt(len(self.__piece.getTabWithIndex()))))
col = int(self.__piece.col+(i%sqrt(len(self.__piece.getTabWithIndex()))))
if 0 not in (self._... | The main task of the code is to automatically control piece movement in a game. When counter is 0, it erases the current piece, attempts to move it down if possible (increasing score), otherwise places it permanently, updates the game platform, and changes to the next piece. This handles core game mechanics like piece ... | def autoControl(self, counter: int):
""" write docstrings """
if counter == 0:
self.erasePiece()
if self.canPlacePiece(Piece.col, Piece.row+1):
self.downPiece()
self.__score+=1
else:
self.placePiece(Piece.col, Piece.row... |
def __common_label__(self, target):
'''
Counts the highest frequency option in target and returns it
Arguments:
target (ndarray) - array of options for target column
Exceptions:
N/A
Return Value:
(string) ... | This function recursively builds a decision tree by selecting the best feature and threshold for splitting data based on information gain. It checks base cases (max depth, pure node, or insufficient samples) to return a leaf node with the common label. Otherwise, it randomly selects features, splits data, and recursive... | def __grow_tree__(self, data, target, depth=0):
'''
Recursively grows the tree through considering highest info gain and
increasing depth
Arguments:
data (ndarray) - core data samples
target (ndarray) - target data column
depth (int) ... |
def SAGA_To_Arc_Raster(File, Raster):
if File_Cmp_Extension(Raster, 'sdat') == False: # conversion needed
Tool = SAGA_Tool('io_gdal', '2') # 'Export Raster to GeoTIFF'
Tool.Set_Option('GRIDS', File)
if File_Cmp_Extension(Raster, 'tif'):
arcpy.AddMessage('Output GeoTIFF: ' + File + ' >> ' + Raster)
Tool.Se... | The function `Get_Output` converts SAGA files to ArcGIS formats (raster, table, features, points) based on the specified `Type` parameter. It processes multiple ArcFiles split by semicolons, applying corresponding conversion functions (`SAGA_To_Arc_*`) for each item. The task involves conditional data transformation fr... | def Get_Output(self, SagaFile, ArcFile, Type):
if ArcFile != '#' and ArcFile != None:
List = ArcFile.split(';')
for Item in List:
if Type == 'grid' or Type == 'grid_list':
SAGA_To_Arc_Raster (SagaFile, Item)
elif Type == 'table' or Type == 'table_list':
SAGA_To_Arc_Table (SagaFile, Item... |
def v_print(string, verbosity):
"""
Prints the given string according to the program verbosity
(string will be printed only if its verbosity is smaller than the program verbosity)
:param string: String to print
:param verbosity: String verbosity level
:return: None
"""
if verbosity <= pr... | The function attempts to prove queries using a FixedPoint solver by checking if the solver's result is a Z3 quantifier. If proven, it prints "PROVED" and the solution; otherwise, it prints "NOT PROVED" with invariant details, including signature and stack, focusing on sub-expressions marked as 'Invariant' with no varia... | def fixed_point_prove(solver, variables):
"""
Receives a FixedPoint solver with already inserted rules and queries, and tries to prove them
:param solver: FixedPoint solver
:param variables: Program variables
:return: None
"""
v_print('Proving the following:', verbosity=4)
v_print(solver... |
def get_table_instance(
project_id: str, instance_id: str, table_name: str
) -> happybase.Table:
"""Create a table instance according to the given ``project_id``, ``instance_id``, and ``table_name``.
This function create a table instance for reading/writing data.
Args:
project_id (str): The pr... | The main task of the code is to connect to a GCP Bigtable instance using provided credentials and retrieve data either by specific row keys or a row key range. It measures and prints the elapsed time for operations, outputs retrieved records in dictionary format, and handles two modes: fetching individual rows via `get... | def main(
project_id: str,
instance_id: str,
table_name: str,
rowkeys: List[str],
start_rowkey: str,
stop_rowkey: str,
rowkey_sep: str,
) -> None:
"""The main function of ``getrows.py`` program.
This main function connects to a table instance on GCP according to the
provi... |
def create_clspv_symlink(clspv_path, dest_path):
Log().info("Generating clspv symlink")
if not os.path.isfile(clspv_path):
Log().error("Can't find clspv on path: {}".format(os.path.join(os.getcwd(), clspv_path)))
exit(1)
try:
os.symlink(os.path.abspath(clspv_path), os.path.abspath(de... | The main task of the code is to configure and execute a test environment by setting up a working directory, initializing test configurations, downloading resources, creating symbolic links, building a kernel slicer, and running tests. It handles directory validation, logging, and resource preparation to ensure tests ex... | def main():
workdir = os.getcwd()
test_config = TestsConfig(argv=sys.argv[1:])
try:
workdir = os.path.abspath(test_config.workdir)
os.chdir(workdir)
except Exception as e:
print("Wrong working dictionary path:\n", e, file=sys.stderr)
exit(1)
Log().set_workdir(workdir)... |
def _check_if_buffer_is_full(self) -> bool:
return len(self._buffer) == self.batch_size
def submit(self):
if not self._buffer:
return
# POST input
self._upload("input")
# POST annotation
if self._has_annotation:
self._upload("annotation")
#... | This method handles data submission by checking if keyword arguments are provided. If the buffer is full, it submits data. It appends protocol-buffer-converted keyword arguments to the buffer if provided, increments a counter, or forces submission if no arguments are given. It enforces keyword-only arguments and manage... | def __call__(self, *args, **kwargs):
if args:
raise RuntimeError("Only keyword arguments are allowed.")
if self._check_if_buffer_is_full():
self.submit()
if kwargs:
self._buffer.append(self.to_proto(**kwargs))
self.current_count += 1
els... |
def iterate_minibatches(images, labels, batch_size):
"""
Function to create mini batches from the dataset of a certain batch size
:param images: input images
:param labels: labels
:param batch_size: batch size
:return: mini batches"""
assert len(images) == len(labels)
# Generate ran... | The code trains a neural network model using training data, with optional validation, logging metrics via WandB. It configures hyperparameters (loss type, optimizer, learning rate), processes batches, computes loss, performs backpropagation, and evaluates training/validation performance. It saves checkpoints, tracks th... | def train_model(model: torch.nn.Module,
images_tr,
labels_tr,
images_val,
labels_val,
device: torch.device,
optimizer: torch.optim,
log_dir: str,
config_exp):
print("Training model..... |
def compiler_error_with_expansion_stack(token: Token, message: str):
compiler_diagnostic_with_expansion_stack(token, 'ERROR', message)
def expand_func(func: Func, expanded_from: Token) -> List[Token]:
result = list(map(lambda x: copy(x), func.tokens))
for token in result:
token.expanded_from = expan... | This function compiles a list of tokens into a program by processing each token to generate operations (Op), handling control structures (if/else/while), function definitions, macro expansions, and file inclusions. It validates token types, enforces expansion limits, checks for syntax errors like unclosed blocks or und... | def compile_tokens_to_program(tokens: List[Token], include_paths: List[str], expansion_limit: int) -> Program:
stack: List[OpAddr] = []
program: List[Op] = []
rtokens: List[Token] = list(reversed(tokens))
funcs: Dict[str, Func] = {}
ip: OpAddr = 0
while len(rtokens) > 0:
token = rtokens.... |
def not_enough_arguments(op: Op):
if op.typ == OpType.INTRINSIC:
assert isinstance(op.operand, Intrinsic)
compiler_error_with_expansion_stack(op.token, "not enough arguments for the `%s` intrinsic" % INTRINSIC_NAMES[op.operand])
elif op.typ == OpType.IF:
compiler_error_with_expansion_sta... | The main task of the code is to perform type checking on a program's operations, ensuring each instruction (e.g., PUSH, INTRINSIC, control flow) adheres to strict type rules. It validates operand types for arithmetic/logical operations, enforces stack consistency for control structures (IF/ELSE/WHILE), and ensures all ... | def type_check_program(program: Program):
stack: DataStack = []
block_stack: List[Tuple[DataStack, OpType]] = []
for ip in range(len(program)):
op = program[ip]
assert len(OpType) == 8, "Exhaustive ops handling in type_check_program()"
if op.typ == OpType.PUSH_INT:
stack.... |
def read_files(filenames: List[str]) -> Names:
"""
Given list of filenames, build and return a names dict
of all their data.
"""
names: Names = {}
for filename in filenames:
add_file(names, filename)
return names
def search_names(names: Names, target: str) -> List[str]:
"""
... | The code processes command-line arguments to either search for a target name in multiple files or list all names. It reads files, checks for a search flag, and either prints matching names or all names based on the input. | def main():
# (provided)
args = sys.argv[1:]
# Two command line forms
# 1. file1 file2 file3 ..
# 2. -search target file1 file2 file3 ..
# Assume no search, so list of filenames to read
# is the args list
filenames = args
# Check if we are doing search, set target variable
targ... |
def do_whole_grid(grid: GridType, brownian: int):
"""
Given grid and brownian int, do one round
of gravity and brownian over the whole grid.
(tests and code TBD)
"""
for y in reversed(range(grid.height)):
for x in reversed(range(grid.width)):
grid = do_gravity(grid, x, y)
... | This function handles periodic tasks for a sand simulation. It checks for active mouse interactions, applies gravity (with optional brownian motion) to update the grid, redraws the grid on the canvas, and updates the frame rate. Global variables control gravity, mouse functions, and brownian motion parameters. The grid... | def sand_action(grid, canvas, scale):
"""This function runs on timer for all periodic tasks."""
global gravity
global mouse_fn
global brownian_on
global brownian_val
if mouse_fn:
mouse_fn()
if gravity.get():
if not brownian_on.get():
val = 0
else:
... |
def set_top(grid: Grid):
"""
Set random squares at the top row, y=0, to
have water in them.
(provided)
"""
for x in range(grid.width):
if random.randrange(WATER_FACTOR) == 0:
grid.set(x, 0, "w")
return grid
def draw_grid_canvas(grid: Grid, canvas: tkinter.Canvas):
"""... | This function performs one iteration of a simulation by updating the grid's top state, redrawing the grid on a Tkinter canvas, and moving water elements, likely part of an animated simulation or game loop. | def do_one_round(grid: Grid, canvas: tkinter.Canvas):
"""Do one round of the move, call in timer."""
set_top(grid)
draw_grid_canvas(grid, canvas)
move_all_water(grid) |
def make_gui(top, width, height):
"""
Set up the GUI elements for the Sand window, returning the Canvas to use.
top is TK root, width/height is canvas size.
"""
global gravity, content, brownian_on, brownian_val, fps_label
gravity = tkinter.IntVar()
content = tkinter.StringVar()
brownia... | The code creates a GUI application using Tkinter to simulate a grid-based system (e.g., sand physics). It initializes a grid with customizable size and square dimensions via command-line arguments. Mouse interactions (clicks, drags) update the grid, and a timer continuously updates the simulation. The main task is to p... | def main():
args = sys.argv[1:]
# Size in squares of world, override from command line
width = 50
height = 50
if len(args) >= 2:
width = int(args[0])
height = int(args[1])
# Size of one square in pixels, override from command line
global SIDE
SIDE = 14
if len(args) ... |
def init_rocks(grid: Grid):
"""
Set a random selection of squares to be rock 'r'
to initialize the grid.
(provided)
"""
for y in range(grid.height):
for x in range(grid.width):
if random.randrange(ROCK_FACTOR) == 0:
grid.set(x, y, "r")
return grid
def draw... | The main task of the code is to create a visual simulation of a waterfall using a grid-based system. It initializes a grid with specified width and height (default 50x30), populates it with rocks, renders the grid on a canvas, and continuously updates the canvas every 30 milliseconds to animate the waterfall effect thr... | def main():
args = sys.argv[1:]
width = 50
height = 30
# Optional command line setting of -width- -height-
if len(args) == 2:
width = int(args[0])
height = int(args[1])
grid = Grid(width, height)
init_rocks(grid)
canvas = drawcanvas.make_canvas(width * SIDE, height * S... |
def players(self, players):
while True:
for player in players:
yield player
def turn(self, player):
self.refresh()
player.move(self)
def isFull(self):
return all([' ' not in self.table[i] for i in range(3)])
def checkWinner(self):
for i in range(3):
... | The code manages a turn-based game by shuffling players, iterating through them to take turns, and terminating when the game is full or a winner is determined, then printing the winner. | def start(self, players):
random.shuffle(players)
iter_players = self.players(players)
while True:
self.turn(next(iter_players))
if(self.isFull()):
break
if(self.checkWinner()):
break
self.printWinner() |
def get_twint_data(data_filename, local=True, folder='raw_data'):
"""
Download twint data saved on GCP for prediction
"""
if local:
path = os.path.join('green_mood_tracker', folder, data_filename)
else:
path = "gs://{}/{}/{}/{}".format(BUCKET_NAME,
... | The function `twint_prediction` predicts tweet polarities using a specified model, optionally downloads the model from GCP, processes input data, generates predictions, and saves the results as a CSV file. It returns a data sample containing tweets and their predicted polarities. | def twint_prediction(data_filename, model_name=MODEL_NAME, model_version=MODEL_VERSION, download_gcp=False, encode=False, local=True):
tic = time.time()
tic_download = time.time()
if download_gcp:
download_model_files(model_name=model_name,
model_version=model_version)
... |
def get_twint_data(data_filename, local=True, folder='raw_data'):
"""
Download twint data saved on GCP for prediction
"""
if local:
path = os.path.join('green_mood_tracker', folder, data_filename)
else:
path = "gs://{}/{}/{}/{}".format(BUCKET_NAME,
... | The function evaluates a machine learning model's performance on a gold standard dataset by loading test data, encoding if specified, predicting using the model, and returning evaluation metrics comparing true labels (polarity or polarity-neutral) against predicted labels. | def evaluate_model_on_gold_standard(model_name=MODEL_NAME, model_version=MODEL_VERSION, download_gcp=False, encode=True, binary=True):
data_filename = TWINT_TEST_FILE
test_df = get_twint_data(data_filename)
if encode:
encode_data(test_df, data_filename, model_name=model_name)
if binary:
... |
def analyze_message(message):
# if message is "invite shyvana", that means we want to invite that bot.
# we also return true because we want to confirm that the message which was send was an invitation.
if message.lower() == "invite shyvana":
invite_shyvana()
return True
elif message.low... | This function handles client connections in a chatroom by receiving and processing messages. It terminates the connection if the message is "dc", checks if the message is an invitation, and otherwise broadcasts the message to all bots, identifies the verb in the message, and activates relevant bots. It logs each receiv... | def handle_client(conn, addr):
print(f"[NEW CONNECTION] {addr} connected to the chatroom.")
connected = True
while connected:
message = conn.recv(2048).decode(FORMAT)
# if message is "dc" we want to stop the while loop and close the connection.
if message == DISCONNECT_MESSAGE:
... |
def initialize_with_zeros(dim):
w = np.zeros((dim, 1))
b = 0
return w, b
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
costs = []
for i in range(num_iterations):
grads, cost = propagate(w, b, X, Y)
dw = grads["dw"]
db = grads["db"]
... | The main task of the code is to train a logistic regression model using gradient descent on training data, evaluate its performance on both training and test sets, and return model parameters, cost history, and predictions. The function initializes weights, optimizes them iteratively, computes accuracy, and packages re... | def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
w, b = initialize_with_zeros(X_train.shape[0])
parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)
w = parameters["w"]
b = parameters["b"]
... |
def load_json(json_path):
print(f"[*] Loading {json_path}...", end="", flush=True)
with open(json_path) as f:
result = json.load(f)
print("done")
return result
def collect_answers(data):
answers = {}
for qa in data:
answers[qa["id"]] = {"answers": [a["text"] for a in qa["answers... | The code evaluates model predictions against gold answers by loading data, tokenizing text, computing metrics, and saving results. It suppresses logging, loads JSON data and predictions, uses a tokenizer, calculates evaluation metrics, and outputs the results as JSON. The main task is to assess model performance on a d... | def main(data_path, prediction_path, output_path):
# Surpress TensorFlow and OpenMP messages
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
os.environ["KMP_WARNINGS"] = "FALSE"
print(f"[-] Original data file: {data_path}")
print(f"[-] Model prediction file: {prediction_path}")
print(f"[-] Evaluation ... |
def _update(filename, content):
"""Updates file with content if different."""
_LOGGER.debug('Updating %s', filename)
try:
with io.open(filename) as f:
current = f.read()
if current == content:
return
except OSError as os_err:
if os_err.errno != er... | This function recursively copies and renders template files from a package's source directory to a target directory, applying parameters during the process. It handles directory structures, skips swap files, and writes rendered content to destination paths while logging operations. | def _install(package, src_dir, dst_dir, params, prefix_len=None, rec=None):
"""Interpolate source directory into target directory with params."""
package_name = package.__name__
contents = pkg_resources.resource_listdir(package_name, src_dir)
if prefix_len is None:
prefix_len = len(src_dir) + 1... |
def _get_file(file_=None,
arch=None,
arch_extract=True,
arch_extract_filter=None):
"""Return the file pointed by "file_" or extract the specified archive.
Return file_ if the specified file exists or extract the files specified
by 'arch_extract_filter' from 'arch' ... | The function retrieves an application's RRD (Round Robin Database) file by constructing paths and using an archive filter. It returns the file path, handling archive extraction if enabled, for metrics data associated with the given app and unique identifier. | def _app_rrd_file(self, app, uniq, arch_extract=True):
"""Return an application's rrd file."""
return _get_file(
self._abs_met_path(app=app, uniq=uniq),
arch_extract=arch_extract,
arch=_archive_path(tm_env, 'sys', app, uniq),
arch_e... |
def _app_path(tm_env, instance, uniq):
"""Return application path given app env, app id and uniq."""
return os.path.join(tm_env().apps_dir,
'%s-%s' % (instance.replace('#', '-'), uniq))
def _get_file(file_=None,
arch=None,
arch_extract=True,
arch... | This function constructs and returns the correct log file path based on parameters like log type, component, and instance. It determines the relative log path, combines it with absolute paths using environment-specific directories, logs the result, and retrieves the file with optional archive extraction. | def _get_logfile_new(self, instance, uniq, logtype, component):
"""Return the log file according to the newer file layout.
"""
if logtype == 'sys':
rel_log_path = os.path.join('sys', component, 'data', 'log',
'current')
... |
def _app_path(tm_env, instance, uniq):
"""Return application path given app env, app id and uniq."""
return os.path.join(tm_env().apps_dir,
'%s-%s' % (instance.replace('#', '-'), uniq))
def _get_file(file_=None,
arch=None,
arch_extract=True,
arch... | This function retrieves a log file path using an outdated layout by constructing an absolute path based on log type, component, and instance. It differentiates between 'sys' and service logs, handles 'running' vs. other unique identifiers, logs the path, and returns the file with optional archive extraction. The method... | def _get_logfile_old(self, instance, uniq, logtype, component):
"""Return the log file according to the old file layout.
"""
# TODO: method should be deleted once the old containers disappear
if logtype == 'sys':
rel_log_path = os.path.join('sys', compone... |
def _get_logfile(self, instance, uniq, logtype, comp):
"""Return the corresponding log file."""
_LOGGER.info('Log: %s %s %s %s', instance, uniq, logtype, comp)
try:
return self._get_logfile_new(instance, uniq, logtype, comp)
except exc.LocalFileNotFoundErr... | This function retrieves a specified portion of a log file, either in normal or reverse order, based on parameters like start index, limit, and order. It validates input, logs the request, and returns the requested log fragment while handling file operations and error checking. | def _get(log_id, start=0, limit=None, order=None):
"""Get log file.
"""
instance, uniq, logtype, component = log_id.split('/')
with lc.LogContext(_LOGGER, '{}/{}'.format(instance, uniq)):
log_f = self._get_logfile(instance, uniq, logtyp... |
def remove_front(routes , merchs):
del routes[0]
del merchs[0]
def remove_end(routes , merchs):
del routes[len(routes)-1]
del merchs[len(merchs)-1]
def remove_trip_at(ind , routes , merchs):
prev_city = routes[ind-1]
next_city = routes[ind]
common_neighbors = find_common_neigh(prev_city,next... | The function randomly attempts to remove a trip from the given `routes` list by generating a permutation of indices. It tries removing the first, last, or a middle trip (based on the permutation order), using helper functions `remove_front`, `remove_end`, and `remove_trip_at`. The process stops immediately after succes... | def remove_random_trip(routes , merchs):
if len(routes) < 3:
return
permutation = random.sample(range(0, len(routes)-1), len(routes)-1) # Random permutation to try add a trip
for k in permutation:
if k == 0:
remove_front(routes , merchs)
elif k == len(routes)-... |
def dnn_visual():
fig, ax = plt.subplots(figsize=(20, 20))
ax.set_ylim(0, 75)
ax.set_xlim(0, 150)
arr = [makeline(ax, 5, 10, "#AFE1AF")]
xpos = 20
row = makeline(ax, 8, xpos, brk=True)
for a in arr[-1]:
for b in row:
connect(ax, a, b)
arr.append(row)
xpos += 10
... | The main task of the code is to execute three visualization functions: `dnn_visual()`, `ann_visual()`, and `perceptron_visual()`, which likely generate visual representations of deep neural networks, artificial neural networks, and perceptrons respectively. The code orchestrates the sequential execution of these visual... | def main():
dnn_visual()
ann_visual()
perceptron_visual() |
def search_id_url(self, gene_name: str) -> str:
"""Get URL to search for gene ID by gene name."""
return ENTREZ_GENE_ID.format(gene_name=gene_name, key_param=self.api_key_query_param())
def requests_retry_session(
retries: int = 3,
backoff_factor: float = 1.0,
status_forcelist: Collection[in... | This function retrieves the NCBI gene ID for a given gene name by querying the Entrez database. It handles potential JSON parsing errors, validates response structure, and resolves ambiguous matches by checking canonical gene names against returned IDs, caching the result for future use. | def get_gene_id(self, gene_name: str) -> Optional[str]:
"""Get gene ID by gene name."""
url = self.search_id_url(gene_name)
response = requests_retry_session().get(
f"https://{self.host}{url}",
verify=False,
timeout=self.timeout,
)
try:
... |
def ranking_count(votes):
# index for permutation [0,1,...,m-1] is 0
# index for permutation [m-1,...,1,0] is (m!-1)
n,m = votes.shape
all_perms = permutation(list(range(m)))
all_perms = np.array(all_perms)
ranking_count = np.zeros(len(all_perms))
for vote in votes:
for p, ... | The code implements a tie-breaking method for selecting winners in a voting system. It first identifies ranks with unique counts in the votes. If a unique rank exists, it uses a permutation-based selection (singleton_winner) on the corresponding candidate. Otherwise, it defaults to lexicographic tie-breaking. The proce... | def singleton_lex_tiebreaking(votes, winners):
rank_cnt = ranking_count(votes)
rank_srt = np.flip(np.argsort(rank_cnt))
flag = False
for r in rank_srt:
rank = rank_cnt[r]
l = len(np.argwhere(rank_cnt==rank))
if(l==1):
flag = True
break
if(fla... |
def ranking_count(votes):
# index for permutation [0,1,...,m-1] is 0
# index for permutation [m-1,...,1,0] is (m!-1)
n,m = votes.shape
all_perms = permutation(list(range(m)))
all_perms = np.array(all_perms)
ranking_count = np.zeros(len(all_perms))
for vote in votes:
for p, ... | This function determines a singleton winner from voting data by breaking ties. It checks for unique ranks in vote counts, uses a permutation to select a winner if a unique rank exists, otherwise falls back to an alternative tie-breaking method. | def singleton_v1_tiebreaking(votes, winners):
rank_cnt = ranking_count(votes)
rank_srt = np.flip(np.argsort(rank_cnt))
flag = False
for r in rank_srt:
rank = rank_cnt[r]
l = len(np.argwhere(rank_cnt==rank))
if(l==1):
flag = True
break
if(flag... |
def get_events(self):
return set(list(chain(*self.variants)))
def get_direct_succesion(self) -> Dict[str, Set[str]]:
succession = defaultdict(set)
for variant in self.variants:
for inx, event in enumerate(variant[:-1]):
succession[event].add(variant[inx+1])
r... | The code initializes an object by processing input variants to compute event relationships, causal dependencies, parallelism, and other properties. It sets attributes like events, causality, parallel events, start/end events, and derived variables Xl/Yl, likely for analyzing temporal or logical structures in sequences. | def __init__(self, variants) -> None:
self.variants = variants
self.events = self.get_events()
self.direct_succession = self.get_direct_succesion()
self.causality = self.get_causality()
self.inv_causality = self.get_inv_causality()
self.parallel_events = self.get_potentia... |
def open_video_link(self, video_link):
"""
:param video_link: str
:return: Boolean
"""
try:
self.driver = webdriver.Chrome(executable_path=self.driver_path, options=self.options)
self.driver.get(video_link)
except Exception as e:
raise ... | The function scrapes video details from a given link, extracts the youtuber's name, video title, and comments, stores the comment data in MongoDB, and returns the link, youtuber name, title, comment count, and data. It opens the link, waits for page load, retrieves metadata, scrolls to load comments, collects comment d... | def scrap_video_details(self,link):
"""
:param link:link of video
:param video_obj: object of video class
:param document_obj: objject of mongodocument class
:return:None
"""
self.open_video_link(link)
time.sleep(2)
youtuber_name = self.find_youtub... |
def intro():
print("This program is a simple guessing game.")
print("The program will generate a random number.")
print("Between 1 and 1000. You get 10 guesses.")
print("The game will tell you if the guess is to high")
print("too low, or correct. Each time you play is worth")
print("10 points. E... | The main task of the code is to execute a game, collect player scores, calculate their average, and display the result. The `main()` function initializes the game with `intro()`, runs the game to obtain scores via `game()`, computes the average using `getAverageScores()`, and prints it with `printAverage()`. This struc... | def main():
intro()
scores=game()
avg=getAverageScores(scores)
printAverage(avg) |
def valid_signatures(self, high_qc, last_tc):
return True
def _safe_to_vote(self, block_round, qc_round, tc):
if block_round <= max(self.highest_vote_round, qc_round):
return False
return self._consecutive(block_round, qc_round) or self._safe_to_extend(block_round, qc_round, tc)
def... | The function generates a vote message for a block in a consensus protocol. It checks if the block's QC is valid and if voting is safe. If valid, it constructs a vote with vote info, ledger commit data, and a signature, then returns the VoteMsg. Otherwise, returns None. | def make_vote(self, b, last_tc):
if b.qc is None:
self.qc_round = -1
else:
self.qc_round = b.qc.vote_info.round
if self.valid_signatures(b, last_tc) and self._safe_to_vote(b.round, self.qc_round, last_tc):
self._update_highest_qc_round(self.qc_round)
... |
def collect_annotations(venv, policy, num_pairs, clip_size, to_cuda = True):
'''
Collects episodes using the provided policy, slices them to snippets of given length,
selects pairs randomly and adds a label based on which snipped had larger reward
Returns a list of lists [clip0, clip1, label], where lab... | The code trains a reward model using preference data to guide reinforcement learning (RL) in an Atari environment. It initializes arguments, sets up a policy (A2C), collects annotations, trains the reward network, and iteratively improves the policy by updating the reward function. Key steps include data collection, re... | def main():
#check for uncommited changes
commit_check()
##setup args
parser = argparse.ArgumentParser(description='Reward learning from preferences')
parser.add_argument('--env_type', type=str, default='atari')
parser.add_argument('--env_name', type=str, default='BeamRider')
parser.add_ar... |
def uri_validator(x):
'''
code taken from: https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not
'''
try:
result = urlparse(x)
return all([result.scheme, result.netloc, result.path])
except:
return False
def download_ld_file(url_p... | This function performs fine-mapping analysis using the FINEMAP tool to identify likely causal SNPs within a genomic locus. It prepares input files (LD data, z-scores), validates parameters, executes the FINEMAP command, processes output logs, and returns a DataFrame with posterior inclusion probabilities (PIPs), effect... | def finemap(self, locus_start, locus_end, num_causal_snps, use_prior_causal_prob=True, prior_var=None, residual_var=None, hess=False, verbose=False, ld_file=None, debug_dir=None, allow_missing=False, susie_outfile=None):
#check params
if use_prior_causal_prob and 'SNPVAR' not in self.df_sumstats.co... |
def uri_validator(x):
'''
code taken from: https://stackoverflow.com/questions/7160737/python-how-to-validate-a-url-in-python-malformed-or-not
'''
try:
result = urlparse(x)
return all([result.scheme, result.netloc, result.path])
except:
return False
def download_ld_file(url_p... | The code performs SuSiE fine-mapping on a genomic locus using summary statistics and LD data, estimating causal SNP probabilities (PIP), effect sizes, and credible sets. It handles prior probabilities, LD loading, effect sign flipping, HESS variance estimation, and outputs results in a dataframe with PIP, BETA_MEAN, an... | def finemap(self, locus_start, locus_end, num_causal_snps, use_prior_causal_prob=True, prior_var=None, residual_var=None, hess=False, verbose=False, ld_file=None, debug_dir=None, allow_missing=False, susie_outfile=None):
#check params
if use_prior_causal_prob and 'SNPVAR' not in self.df_sumstats.co... |
def yaml_to_json(self):
data = ""
UE_to_UPF_assignment = {}
with open('./config/uerouting.yaml', encoding='utf-8') as file:
data = yaml.safe_load(file)
for info in data:
if info == "ueRoutingInfo":
for UEgroups in data[info]:
U... | This function manages UE-to-UPF assignment in a network environment. It loads configuration data, checks UE availability, and triggers SMF configuration changes (enabling ULCL) when 12 UEs are detected. If active, it calculates progress and executes a modified greedy algorithm for resource allocation. The process runs ... | def DNSA(self):
if DEBUG:
print("DNSA")
print(self.ue_start_time)
self.UE_to_UPF_assignment = self.yaml_to_json()
self.check_ue_status()
if self.available_ue and ((time.time() -self.start_time) <(25*60)):
print("In assignment")
if (len(self... |
def text_create(self, name, msg):
pwd = "/home/minziran/Free5GC-Compose/free5gc-compose/"
full_path = pwd + name + '.txt'
file = open(full_path, 'w')
file.write(msg)
file.close()
def DNSA(self):
if DEBUG:
print("DNSA")
print(self.ue_start_time)
... | The main task of the code is to continuously monitor network devices by periodically requesting statistics from each datapath, checking a flag (MF_Flag) to trigger DNSA operations, and logging timestamps. It maintains a "port_mac_ip" entry and operates in an infinite loop with a 10-second delay between iterations to ma... | def _monitor(self):
self.text_create("port_mac_ip", " ")
while True:
print("=================="+str(time.time())+"===================")
if self.MF_Flag:
self.DNSA()
for dp in self.datapaths.values():
self._request_stats(dp)
... |
def __enable_data_ready_interrupt(self, int_en):
if int_en:
INT_ENABLE = self.regs['INT_ENABLE']
DATA_READY_SHIFT = 7
DATA_READY_INTERRUPT_ENABLE = int(int_en) << DATA_READY_SHIFT
self.__write_data(INT_ENABLE, [DATA_READY_INTERRUPT_ENABLE])
def __odr_setup(self, o... | This method configures an accelerometer by setting its output data rate (ODR), full-resolution mode, and measurement scale (2g/4g/8g/16g), while enabling or disabling the data-ready interrupt. It finalizes setup by activating the sensor to make measurements available in data registers. | def __configure_accelerometer(self, odr, scale, int_en):
# per datasheet, enable interrupt before output
self.__enable_data_ready_interrupt(int_en)
# output data rate
self.__odr_setup(odr)
# sets full resolution mode and scale (2g/4g/8g/16g)
self.__full_res(scale)
... |
def __constants(self, sensitivity, scale, full_resolution, software_cs):
self.__full_resolution = full_resolution
# if self.__full_resolution:
# # according to ADXL345 datasheet
# # in full resolution mode the sensitivity
# # is always 3.9mg/LSB
# s... | This code initializes an ADXL345 accelerometer by configuring hardware settings (GPIO, SPI), loading sensor-specific constants, verifying device identity via WHO_AM_I register, and setting operational parameters like sensitivity, scale, ODR, and interrupt enable. It prepares the sensor for data acquisition with specifi... | def __init__(self, sensitivity=ADXL345_DEFAULT_SENSITIVITY, scale=ADXL345_DEFAULT_SCALE, odr=ADXL345_DEFAULT_ODR, full_resolution=True, software_cs=False, bitrate=ADXL345_DEFAULT_SPI_BITRATE, interrupt_enable=False):
# sets up private constants
self.__constants(sensitivity, scale, full_resolution, softw... |
def train_model(self):
""" explores the hyperparameter space and then trains the best model"""
if self.scale_down:
self.make_new_dataset()
elif self.scale_up:
raise SystemExit('Please refer to the documentation.'
'Requires you to prepare the d... | The code trains a model, evaluates it on input data, and either reconstructs data using an autoencoder (plotting input/output comparisons) or classifies files with a classifier. It handles errors, tracks timing, and saves results. | def run(self):
self.output = make_output_folder(self.input, self.output, self.force)
self.train_model()
if self.input is None:
raise Exception('No input blocks given for inference on trained model.')
model = self.get_model()
print('evaluating model...')
gen... |
def _move_snake_head(self, action: numpy.array):
# [straight, right, left] are possible actions
clock_wise = [Direction.RIGHT, Direction.DOWN, Direction.LEFT, Direction.UP]
index = clock_wise.index(self._direction) # get index of current direction
new_direction = None
if numpy.a... | The code defines a method `play_step` that processes a single game step in a snake game. It handles user input, moves the snake based on the given action, checks for game-over conditions, updates the score and food placement, renders the game state, and returns the reward, game-over status, and current score. The funct... | def play_step(self, action):
self._frame_iteration += 1
# 1. collect user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# 2. move
self._move_snake_head(action) # update the head
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.