dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def remove_empty(centroids, centers, data_length, centers_length):
modified_centroids = {}
modified_labels = np.zeros(data_length)
modified_centers = []
counter = 0
for i in range(len(centroids.keys())):
inner_points_no = len(centroids[i])
if inner_points_no > 0:
modified... | The function `handle_empty` manages empty clusters in a clustering algorithm by applying a specified procedure. Depending on the `empty_procedure` parameter, it either removes empty clusters, moves the largest/farthest/random data points to fill them, or splits clusters. It delegates to helper functions for each strate... | def handle_empty(centroids, centers, deux_list, labels, data_length, features_length, centers_length,
threshold, metric, circular, empty_procedure):
if empty_procedure == 'remove':
return remove_empty(centroids, centers, data_length, centers_length)
elif empty_procedure == 'biggest':
... |
def begin_function(metric,initial_state,k,max_iteration, n, method, threshold, isCircularData,
addInitial, addDistance, addComunities):
print("Search for {0} clusters for at most {1} iterations:".format(k, max_iteration))
if n==k:
print("As the number of requested communities is equ... | The function implements a K-means clustering algorithm to partition input data into `k` clusters. It initializes centroids using specified methods (e.g., '++'), iteratively assigns data points to nearest centroids, and updates centroids until convergence or max iterations. It handles circular data, distance metrics, an... | def Naive_k_means(data_list,k,max_iteration=300,initial_state='++',metric='euclidean',threshold=0, method='none',
isCircularData=False, addInitial=False, addDistance=False, addCommunities=False):
old_centroids={}
new_centroids={}
centers=[]
communities=[]
labeled = []
distances... |
def centers_initialization(data_list, k, way, feature_length, threshold, metric, circular):
n = np.shape(data_list)[0]
if way == 'first':
return np.asarray(data_list[:k], dtype=np.ndarray)
elif way == 'random':
randomize = np.random.choice(range(n), k, replace=False)
return np.asar... | The function performs K-means clustering on a dataset, initializing centroids using specified methods (e.g., '++'), iterating up to a maximum number of times, and stopping early if centroid changes fall below a saturation threshold. It assigns data points to clusters, updates centroids, handles circular metrics, and re... | def final_kmeans(datalist, k, max_iteration=300, initialization_type='++', metric='euclidean', threshold=0,
circular='on', empty_procedure='ignore', saturation='approx',
plot_initial='off', plot_asdictionary=False, report_process=False):
n = np.shape(datalist)[0]
L = np.shape(d... |
def get_player():
return Player.query.filter_by(id=session['player_id']).first()
def get_game():
game_session = get_game_session()
return Game.query.filter_by(session_id=game_session.id).order_by(Game.id.desc()).first()
def check_for_interrupted_game():
game = get_game()
if game.outcome is None:
... | This function manages a player's session in a game, resuming an existing game if available or starting a new one. It retrieves the player, checks for an ongoing session, loads the game state if present, and broadcasts the board state. If no game exists, it checks for interruptions and initiates a new game, ensuring ses... | def handle_check_session():
player = get_player()
session['player'] = player
if player.sessions and player.sessions[-1].outcome is None:
game = get_game()
session['game_id'] = game.id
if game_state.get(player.id) is not None:
tttgame = TTTGame()
tttgame.board ... |
def process_par(node):
if isinstance(node.par_expr, list):
parameters[node.var_par_identifier] = node.par_expr[0]
def process_decl(node):
if not('output_array' in node.annotations):
decision_vars[node.var_par_identifier] = tuple(node.basic_var_type[0])
subexprs[node.var_par_identifier] =... | The code parses a FlatZinc model into structured optimization components. It extracts decision variables, constraints (inequality/equality), and the objective function. It processes declarations, constraints, and objective directives, then constructs matrices (A_le, b_le, A_eq, b_eq) and a dictionary for the objective ... | def parse_flatzinc(flatzinc):
global objective
tree = ProcessFlatZinc().transform(
Lark.open("parse/grammar.lark").parse(flatzinc.read())
)
# First pass for parameters and boolean variables
for item in tree.children:
if item == None:
continue
else:
ite... |
def get_current_player(self):
if self.turn == "white":
return self.white_player
return self.black_player
def get_mouse_board_pos(self):
mouse_pos = pygame.mouse.get_pos()
col = mouse_pos[0]//constants.SQUARE_WIDTH
row = mouse_pos[1]//constants.SQUARE_WIDTH
row... | This code handles a human player's move in a board game. It checks if the clicked position is a valid move for the selected piece, executes the move if valid, or deselects the piece if clicked again. If no piece is selected, it selects a new piece of the current player's color at the clicked position. | def on_click(self):
if self.get_current_player() == constants.PlayerType.HUMAN and self.human_timer.get() == 0:
moves = []
if self.selected_piece:
moves = self.board.get_moves(self.selected_piece)
if self.get_mouse_board_pos() in moves:
selecte... |
def is_over(self):
if self.board.is_game_over():
return True
return False
def _change_turn(self):
if self.turn == "white":
self.turn = "black"
else:
self.turn = "white"
if self.get_current_player() != constants.PlayerType.BOT:
... | The code updates the game state by checking if the game is over, managing human and bot timers to switch turns, and executing the bot's move using the chessbot algorithm when the bot's turn arrives, while recording the move time and board score. | def update(self):
if self.is_over():
return
if self.human_timer.passed(constants.HUMAN_DELAY):
self.human_timer.reset()
self._change_turn()
if self.human_timer.get() == 0:
if self.get_current_player() == constants.PlayerType.BOT and self.... |
def clear() -> None:
"""
Clears the screen
"""
# Check if GUI clear
if DISPLAY_TYPE == "GUI":
eel.clear_screen()
else:
if not in_ide:
os.system("cls")
def render_header(title: str, enclose_bottom: bool = True) -> None:
"""
Renders a title header to the console... | The main task of the code is to display a menu by printing its items, optionally clearing the screen first. It uses either `show_menu_double` or `show_menu` based on the `multi_dimensional` flag, renders a header with the title, and returns the list of menu items. The function adapts its rendering method dynamically de... | def show_menu(self) -> list:
"""
Prints the menu to a clear screen. Automatically uses the multi_dimensional variable to determine if the menu
should use show_menu_double or show_menu
"""
menu_items = self.items
# Check if the screen should be cleared
if self.cle... |
def round_zero(state_matrix,all_keys):
key_zero=list_to_array(all_keys[0], 4, 4)
return add_round_key(state_matrix,key_zero)
def intermediate_round(state,all_keys):
for i in range(1,10):
result=subbytes(state)
result2=shift_row(result)
result3=mix_coloumn(result2)
result4=add... | The code performs encryption by sequentially applying three rounds of transformation—initial round, intermediate rounds, and final round—using the provided state matrix and all keys, returning the final encrypted state. | def encryption(state_matrix,all_keys):
round1 = round_zero(state_matrix,all_keys)
round2 = intermediate_round(round1,all_keys)
final = round_ten(round2,all_keys)
return final |
def inv_round_zero(state_matrix,all_keys):
key_zero=list_to_array(all_keys[10], 4, 4)
return add_round_key(state_matrix,key_zero)
def inv_intermediate_round(state,all_keys):
for i in range(1, 10):
result=inverse_shift_row(state)
result2=add_round_key(inverse_subbytes(result),list_to_array(al... | The main task of the code is to decrypt a given 'state' using a series of inverse cryptographic rounds. It applies the inverse initial round (inv_round_zero), followed by inverse intermediate rounds (inv_intermediate_round), and concludes with the inverse final round (inv_round_ten), all using the provided 'all_keys'. ... | def decryption(state,all_keys):
round1=inv_round_zero(state,all_keys)
round2=inv_intermediate_round(round1,all_keys)
final=inv_round_ten(round2,all_keys)
#print(final)
return final |
def compute_summed_area_table(image):
# image is a 2-dimensional array containing ints or floats, with at least 1 element.
height = len(image)
width = len(image[0])
new_image = [
[0.0] * width for _ in range(height)
] # Create an empty summed area table
for row in range(0, height):
... | The function evaluates and compares adaptive thresholding methods (Choquet, Sugeno, Bradley) on test images against ground truth, calculating metrics like MSE and SSIM for each technique, while collecting results for analysis. | def compute_multi_thresh(test_images, gt_images, opt=0, T=0, a1=2, a2=2):
count = 0
resc = []
elapsed_time = 0
for i in test_images:
test_image = i
# plot_it(test_image)
S1 = np.asarray(compute_summed_area_table(test_image))
# S1 = get_int_img_m1(test_image)
choq... |
def mbrl(rg, Nsa, tP, p_ix=0, ess=False):
'''
Computes empirical model of opponent's policy and a best
response (stateful fictitious play)
'''
oppol = Nsa / Nsa.sum(axis=1)[:,None]
oppol = np.nan_to_num(oppol, nan=1/oppol.shape[1])
if ess:
return oppol, bestresp(oppol, tP, rg.sfp, rg... | This function implements the S++ algorithm for decision-making in a multi-agent environment, selecting actions based on expert strategies, safety overrides, and potential values. It updates policies, tracks historical actions, and adjusts expert indices using MBR and MR calculations. The algorithm balances exploration/... | def algo_spp(t, s, rg, inst, p_ix=0, init=False, name=False):
'''
S++
'''
if init:
return 1
if name:
return 'S++'
# Safety override check
weight = 1
if t > 0 and inst.running_avg[p_ix] + inst.C/t < rg.vsec[p_ix]:
inst.unsafe[p_ix] = True
try:
a1 = inst... |
def transition(S, A, geom_states, K, probs_1, probs_2):
'''
We suppose that each player publicly shares their randomization signal.
Transition probabilities based on two possibly differing randomization
devices. If players disagree, they're still responding to the same
randomization device, so ... | This code initializes a multi-agent reinforcement learning system with two agents, setting up policies, transition models, reward tracking, and exploration strategies like M-Qubed and S++. It configures parameters for learning rates, discount factors, and safety constraints, while initializing data structures for state... | def __init__(self, rg, algo_1, algo_2, lr=LEARN, lam=0.99, zeta=0.05,
gam=0.95):
self.subepoch = floor(rg.tee**(1/4))
self.Nsa = {0: np.zeros((rg.S, rg.A)), 1: np.zeros((rg.S, rg.A))}
self.reward_list = {0: [], 1: []}
self.running_avg = {0: 0, 1: 0}
self.rolling_avg = {0: ... |
def bargain(game_1, game_2, solution='ebs', eps=0.001,
p_ix=0, K=1):
'''
Given two game matrices (not yet converted to advantages), computes EBS or Bully
'''
best_val = -np.inf
best_a1 = 0
best_a2 = 0
best_b1 = 0
best_b2 = 0
best_p = 0
ag = adv_convert(game_1, game_2)... | The function computes a 'Godfather' policy and value for a game-theoretic scenario involving two agents, using either EBS (Efficient Bargaining Solution) or Bully strategies. It calculates optimal actions based on negotiated targets, evaluates cooperation vs. defection outcomes, and adjusts policies with parameters lik... | def godfather(rg, p_ix=0, solution='bully', eps=0.1, generosity=0):
'''
Godfather policy and value with respect to EBS or Bully
'''
try:
target_1, target_2, w, vebs = bargain(rg.rewards_1[0],
rg.rewards_2[0], solution=solution, eps=eps, p_ix=p_ix, K=rg.K)
except:
return rg.... |
def nsa_range(states, actions, num_act, t1, t2, p_ix=0):
'''
Computes a history matrix for [t1, t2]
'''
Nsa = np.zeros((len(states), num_act))
for t in range(t1, t2+1):
Nsa[states[t], actions[p_ix][t]] += 1
return Nsa
def policynorm(M1, M2):
'''
Norm used for Manipulator's statio... | This function implements a "Bully Manipulator" strategy that dynamically adjusts an agent's behavior over time by switching between strategies (e.g., bully, follower, maximin) based on rolling averages, policy comparisons, and predefined time intervals. It uses thresholds (eps0, eps1, eps3) and probabilistic transition... | def algo_manipulator_bully(t, s, rg, inst, p_ix=0, p=0.00005,
eps0=0.025, eps1=0.025, eps3=0.025, init=False, name=False):
'''
Manipulator
'''
if name:
return 'Bully Manipulator'
temp_ei = -1
if init:
return 1
if t < TAU1:
inst.exp_ind[p_ix] = 2
inst.strateg... |
def simple_tp(S, A, geom_states):
'''
Transition probs for 1-memory fictitious play
'''
tP = np.zeros((S, A, A, S))
for s in range(S):
for a1 in range(A):
for a2 in range(A):
for sp in range(S):
end = geom_states[sp]
if end[... | This code initializes a multi-agent game environment by setting up state spaces, reward structures, and expert strategies. It processes input reward matrices, constructs geometric and S++ states, computes equilibrium solutions (e.g., maximin, bargaining), and prepares transition probabilities for different strategies. ... | def __init__(self, base_1, base_2, tee, K=1, eps=0.05, delta=0.005,
fair_val_1=-1, fair_val_2=-1):
self.eps = eps
self.base_1 = base_1
self.base_2 = base_2
self.tee = tee
self.K = K
self.A = base_1.shape[0]
self.S = 2**(2*(K+1))*self.A**(2*K)
sel... |
def metric(self, partitions, siblings=None):
if self.criterion == 'avg':
return self.__avg_emd(partitions, siblings)
elif self.criterion == 'min':
return self.__min_emd(partitions, siblings)
else:
return self.__max_emd(partitions, siblings)
def __worst_attribu... | This function recursively selects partitions by evaluating the 'worst' attribute, comparing metric values between current partitions and their children. If the current partition's metric is not worse than its children's, it is added to the output list. Otherwise, the function recursively processes each child partition,... | def __unbalanced_recursive(self, current, siblings, A, output=None, random_attribute=False):
"""
:param current:
:param siblings:
:param A:
:param output:
:param random_attribute:
:return:
"""
if output is None:
output = []
at... |
def file_exists(path):
return path and os.path.exists(path)
def get_target_vuls():
if Args.targets:
diff = set(Args.targets) - set(ALL_VULS)
if diff:
raise ValueError("undefined vulnerability '%s'" % diff)
return Args.targets
else:
return ALL_VULS
def to_train(dat... | The code's main task is to handle different commands for training, predicting, and testing models. It processes input data files, validates required arguments, loads vulnerability and operation data, trains specified algorithms, and performs predictions on Solidity files. It also includes a CNN training test and result... | def main():
if Args.subcmd == 'train':
if not file_exists(Args.datafile) and not (file_exists(Args.vulfile) and file_exists(Args.opfile)):
logging.error("Need to specify the data file or vul/op files to read.")
logging.error(" For example: %s train -d %s [ -u %s -o %s ]" %
... |
def compute_end_history(dates: List[datetime], start_monitor: datetime) -> int:
"""Return value of the first date of the monitoring period.
Raises exception it the start of the monitoring period is not witin the history period.
"""
for i in range(len(dates)):
if start_monitor <= dates[i]:
... | The code detects structural breaks in time series data by analyzing residuals (measurements minus predictions). It computes cumulative sums of residuals, applies a MOSUM-based statistic scaled by residual volatility, and compares this against thresholds derived from the given level and parameters. The function returns ... | def break_detection(
measurements: np.array,
predictions: np.array,
start_monitor: datetime,
dates: List[datetime],
hfrac: float,
level: float,
k: int,
full_predictions: bool = True,
) -> Tuple[np.array, np.array]:
"""Detect breaks in time seroes, returns the breaks in the monitoring... |
def build_contextual_commit_offsets_callback(logger):
def on_commit_offsets(err, partitions):
if err:
if err.code() == KafkaError._NO_OFFSET:
logger.info("End of partition event.")
else:
logger.error(str(err))
raise RuntimeError("Error ... | The main task of the code is to initialize and run a Kafka event processor. It parses command-line configuration, sets up logging, creates a Kafka consumer for ingesting avro-formatted events, builds output producers, and enters a processing loop to consume, process, and produce events based on the provided configurati... | def main():
configuration = EventProcessorConfiguration(sys.argv[1:])
logger = get_logger(configuration.event_processor_id, configuration.log_level)
logger.info("Parsed Configuration")
logger.info("Building Kafka Consumer")
consumer = KafkaConsumer(
configuration.schema_registry_url,
... |
def led_on():
led.value(1)
def sense_and_publish():
(temp, pressure, moisture, rain_intensity, hum) = sense_and_print()
publish_data(temp, pressure, moisture, rain_intensity, hum)
def sense_and_show():
(temp, pressure, moisture, rain_intensity, hum) = data = sense_and_print()
oled_text_line('T: {:0.2f}'.form... | The function handles a button press interrupt by activating an LED, sensing data (publishing if WiFi is enabled or displaying otherwise), waiting for the button release, then deactivating the LED, clearing the display, and resetting the button state. | def btn_int(pin):
global btn_pressed
btn_pressed = True
led_on()
if ENABLE_WIFI:
sense_and_publish()
else:
sense_and_show()
sleep(1)
while btn.value():
pass
led_off()
oled_clear()
btn_pressed = False |
def check_file(filepath: str) -> None:
if not is_file_exists(filepath):
raise FileNotFoundError
if not is_file(filepath):
raise IsNotFile
def get_last_update(filepath: str) -> float:
stats = os.stat(filepath)
return stats.st_mtime
def tail(file: BinaryIO, lines: int) -> str:
# Chan... | The code monitors a file for changes in real-time, printing its last 'lines' of content whenever updates are detected. It uses a loop to check the file's modification time, refreshing the displayed content upon changes. If the file is deleted, it raises a FileDeleted exception. | def tail_observer(filename: str, lines: int):
check_file(filename)
last_update = get_last_update(filename)
try:
with open(filename, "rb") as file:
print(tail(file=file, lines=lines))
while True:
new_update = get_last_update(filename)
if last... |
def GSS(f):
t = 0.5
n = 3
num_iter = 1*np.max([np.ceil(len(f)/n),3])
#First, define scale-space kernel (discrete Gaussian kernel)
ker = np.exp(-t)*iv(np.arange(-n,n+1),t)
ker = ker/np.sum(ker)
#Initialize place to store result of each layer GSS
plane = np.zeros([len(f), num_iter.astype(... | This function detects significant components in a signal using Gaussian scale-space (GSS) and thresholding. It computes persistence lengths of minima, applies symmetry reduction if enabled, then uses methods like Otsu, mean, or k-means to threshold lengths, identifying indices where values exceed thresholds. The result... | def ewt_GSSDetect(f,params,sym):
#Apply gaussian scale-space
plane = GSS(f)
#Get persistence (lengths) and indices of minima
[lengths, indices] = lengthScaleCurve(plane)
if sym == 1:
lengths = lengths[indices < len(f)/2-1] #Halve the spectrum
indices= indices[indices < len(f)/2-1] #H... |
def ewt_GSSDetect(f,params,sym):
#Apply gaussian scale-space
plane = GSS(f)
#Get persistence (lengths) and indices of minima
[lengths, indices] = lengthScaleCurve(plane)
if sym == 1:
lengths = lengths[indices < len(f)/2-1] #Halve the spectrum
indices= indices[indices < len(f)/2-1] #H... | This function detects boundaries for Empirical Wavelet Transform (EWT) by preprocessing the input signal (log transformation, trend removal, spectrum regularization) and applying a selected boundary detection method (scale-space, local maxima, adaptive). It returns the cleaned boundary indices after removing zeros, ess... | def ewt_boundariesDetect(absf,params,sym = 1):
if params.log == 1: #apply log parameter
preproc = np.log(absf)
else:
preproc = np.copy(absf)
if params.removeTrends.lower() != 'none': #apply removeTrend parameter
preproc = removeTrends(absf,params)
if params.spectrumReg... |
def get_cluster_list(cluster_id):
try:
response = table.query(
IndexName= dynamoDB_index_name,
ScanIndexForward = True,
FilterExpression=Attr(dynamoDB_column).eq(cluster_id),
KeyConditionExpression=Key('pk').eq('externaoficial')
)
... | The main task of the code is to process an incoming event by generating a file name from the cluster ID, deleting an existing file if it exists, and conditionally uploading a report to an S3 bucket based on cluster list validation. It handles errors by printing exception details and returns the original event. The func... | def lambda_handler(event, context):
# TODO implement
print("Received Event: ", event)
global file_name
file_name = event['cluster_id']+".txt"
try:
if os.path.isfile(file_uri+file_name):
os.remove(file_uri+file_name)
if get_cluster_list(event['cluster_id']) and n... |
def _check_conditional(self, when, variables):
conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}"
return self.template(conditional % when, variables)
def template(self, data, variables, convert_bare=False):
if isinstance(data, Mapping):
templated_data = {}
f... | The code processes template files to generate configuration lines. It copies variables, searches for template files, loads tasks from them, and executes each task. It handles conditions, loops, and registration of results. Tasks are processed by removing metadata, evaluating conditions, iterating loops, and collecting ... | def run(self, terms, variables, **kwargs):
self.ds = variables.copy()
config_lines = list()
for term in to_list(terms[0]):
display.debug("File lookup term: %s" % term)
lookupfile = self.find_file_in_search_path(variables, 'templates', term)
display.vvvv("Fi... |
def _check_conditional(self, when, variables):
conditional = "{%% if %s %%}True{%% else %%}False{%% endif %%}"
return self.template(conditional % when, variables)
def template(self, data, variables, convert_bare=False):
if isinstance(data, Mapping):
templated_data = {}
f... | This code processes a block of tasks by evaluating conditions, handling loops (both key-value and iterable), and recursively executing context blocks. It aggregates results from each processed task, applying data substitutions and conditional checks, then returns the collected outcomes. | def do_context(self, block):
results = list()
for entry in block:
task = entry.copy()
task.pop('name', None)
task.pop('register', None)
when = task.pop('when', None)
if when is not None:
if not self._check_conditional(when, s... |
def check_alphabetical_order(lines: List[str]) -> List[str]:
err_msgs = []
categories, category_line_num = get_categories_content(contents=lines)
for category, api_list in categories.items():
if sorted(api_list) != api_list:
err_msg = error_message(
category_line_num[c... | The code validates the format of a structured document (likely Markdown) by checking: 1) alphabetical order of sections, 2) presence of category headers in the index, 3) minimum entries per category, 4) correct formatting of table rows (pipe characters, spacing, column count), and 5) proper segment formatting. It colle... | def check_file_format(lines: List[str]) -> List[str]:
err_msgs = []
category_title_in_index = []
alphabetical_err_msgs = check_alphabetical_order(lines)
err_msgs.extend(alphabetical_err_msgs)
num_in_category = min_entries_per_category + 1
category = ''
category_line = 0
for line_num,... |
def find_links_in_file(filename: str) -> List[str]:
"""Find links in a file and return a list of URLs from text file."""
with open(filename, mode='r', encoding='utf-8') as file:
readme = file.read()
index_section = readme.find('## Index')
if index_section == -1:
index_sectio... | The main task of the code is to check for duplicate links in a given file and optionally verify if the links are functional. It first identifies all links in the file, initiates a duplicate link checker, and if `only_duplicate_links_checker` is `False`, also runs a working link checker to ensure the links are active. T... | def main(filename: str, only_duplicate_links_checker: bool) -> None:
links = find_links_in_file(filename)
start_duplicate_links_checker(links)
if not only_duplicate_links_checker:
start_links_working_checker(links) |
def _build_encoder(self):
encoder_input = self._add_encoder_input()
conv_layers = self._add_conv_layers(encoder_input)
bottleneck = self._add_bottleneck(conv_layers)
self._model_input = encoder_input
# The bottleneck is also the encoder output
self.encoder = Model(encoder... | The main task of the code is to construct a neural network model by building its encoder, decoder, and autoencoder components. The `_build` method orchestrates three sub-methods: `_build_encoder()` initializes the encoder, `_build_decoder()` sets up the decoder, and `_build_autoencoder()` integrates these parts into a ... | def _build(self):
# Three methods:
self._build_encoder()
self._build_decoder()
self._build_autoencoder() |
def clockoverlay(cx,cy,sx,sy):
global TIME,hour,minute,second,shade
#Datetime = datetime.datetime.now()
hour = 0#Datetime.hour
minute = 0#Datetime.minute
second = 0#Datetime.second
TIME = 11.5#hour + (minute/60) + (second/360)
if TIME >= 24:
TIME = 0
if 0 <= TIME <= 11.5:
... | This code defines a settings menu in a Pygame application, allowing users to adjust music and sound volumes via sliders, navigate options using a controller or mouse, and save configurations. It handles input events, updates UI elements, and exits the menu when settings are applied or canceled. | def settings():
global Settings,mvol,svol,CX,CY,MOUSE
s = pygame.Surface((150,150))
s.set_alpha(140)
s.fill(grass)
vol = 0
Settings = 1
while Settings == 1:
if controller > 0 and MOUSE == 0:
cx = CX
cy = CY
else:
cursorpos = pygame.mouse.g... |
def genground():
if x >= 1155:
if 1125 < y:
screen.blit(topcornerL,(x-1500,y-1500))
if 375 < y:
screen.blit(sidewallL,(x-1500,y-1125))
if -375 < y < 1125:
screen.blit(sidewallL,(x-1500,y-375))... | The code's main task is to render a game scene by checking grid/building collisions to restrict player movement, drawing environmental elements (buildings, lakes, flora), handling player interactions with structures, and rendering UI components like time, coordinates, and a hotbar. It also manages dynamic shading and t... | def draw():
global moveup,movedown,moveright,moveleft,x,y,W,A,S,D
genground()
moveup,movedown,moveright,moveleft = 1,1,1,1
## gx = int(((x-1500)/-15))
## gy = int(((y-1500)/-15))
## for i in range(11):
## if buildingsA[i] <= x-225 <= buildingsD[i] and... |
def network(layers, n_inps, wts=None):
global adj_rt
global mid
network = [0 for _ in layers]
rand_wts = lambda layer: [2 * r.random() - 1 for n in layer]
if wts:
network[0] = [sig_neur(w, adj_rt, mid) for w in wts[0]]
else:
network[0] = [sig_neur(rand_wts(n_inps * [0]), adj_rt... | The main task of the code is to train and test a neural network for controlling light configurations based on input features. It uses command-line arguments to switch between training (--train) and testing (--test) modes. During training, it builds a network with specified layers, reads target data, and saves weights. ... | def main():
n_features = 8 # eight possible corner configurations
# a common rule of thumb is features^2 neurons on the hidden layer
# this is simple enough that I don't think I need that many so I'm doing half
n_hidden = n_features ** 2 // 2 # the addition of the hidden layer actually hurt performance ... |
def _init_analytics(self, metricObj):
"""
Description:
This method will initialize analytics on the provided metrics object, adding derived metrics to the metricObj.
Args:
metricObj (object): The object containing the metrics to be analyzed.
Returns:
None
... | The main task of the code is to analyze time-series metrics for anomalies around a specified timestamp. It processes the metric data into a dataframe, calculates temporal bounds, detects anomalies, generates a structured GPT input string for anomaly details, interacts with OpenAI's GPT model, and visualizes the results... | def analytics(self, metricObj, queryTimestamp):
"""
Description:
This method initializes analytics based on the metric object, prepares a dataframe from the metric object, calculates bounds, and then checks if there is an anomaly.
If an anomaly is found, it calculates the anomaly, create... |
def calculateADJMatrix(self, nodes):
adjMatrix = []
for i in range(len(nodes)):
row = []
for j in range(len(nodes)):
dist = np.linalg.norm(nodes[i] - nodes[j])
row.append(dist)
adjMatrix.append(row)
return adjMatrix
def DisplayB... | The code initializes a GUI frame for a TSP solver, loading city coordinates from 'Berlin52.txt' and population data from 'population.txt'. It constructs an adjacency matrix, sets up interactive buttons/sliders, and prepares to visualize paths on a graph. The main task is to create an interface for exploring traveling s... | def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
# To remove and replace with openCity class
node_array = []
with open('Berlin52.txt', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=' ')
for row in reader:
... |
def initialPopulation(popSize, cityList, citiesPopulation):
population = []
for i in range(0, popSize):
population.append(createRoute(cityList, citiesPopulation))
return population
def rankRoutes(population, cityList, citiesPopulation):
fitnessResults = {}
for i in range(0, len(population))... | The code implements a genetic algorithm to optimize a route through cities, aiming to minimize distance. It initializes a population, iteratively evolves it over generations using selection, crossover, and mutation, then applies the TwoOPT heuristic and local search to refine the best route. The final route, adjusted t... | def geneticAlgorithm(cities, population, popSize, eliteSize, mutationRate, generations):
pop = initialPopulation(popSize, cities, population)
print("Initial gain: " + str(rankRoutes(pop, cities, population)[0][1]))
progress = []
progress.append(rankRoutes(pop, cities, population)[0][1])
for i in ra... |
def search_and_process_manga(self) -> bool:
"""
Searches for a manga and processes the search results.
Returns:
bool: True if the search was successful, False otherwise.
"""
manga = self.search_manga()
if manga:
Logger.DEBUG(f"Search results for m... | The function retrieves manga IDs by checking a cache first. If not cached, it searches with retries, handles errors, and caches results upon success. If all retries fail, it logs an error and returns the found IDs or an empty list. | def get_manga_id(self) -> list[int]:
"""
Gets the ID of the manga.
Returns:
list: A list of manga IDs.
"""
Logger.INFO("Function get_manga_id called.")
result: list = []
# Check if the manga ID is in the cache
cached_result_str: Optional[str]... |
def compute_price(rental):
car = find_car(rental)
rental_days = number_of_days(rental)
price_per_day = car['price_per_day']
# compute the distance component of the price
distance_component = rental['distance']*car['price_per_km']
# compute the time component of the price
if rental_days > ... | The code calculates and returns a list of financial transactions for a rental, including driver's debit, owner's credit, insurance/assistance fees, and drivy's share, based on computed price, deductible, and commission details. | def compute_actions(rental):
price = compute_price(rental)
deductible = compute_deductible(rental)
commission_details = compute_commission(rental)
commission = sum(commission_details.values())
driver = {"who": "driver", "type": "debit", "amount": price + deductible}
owner = {"who": "owner", "ty... |
def get_firefox_driver():
""" This method is used to get the Firefox driver """
options = FirefoxOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--start-maximized')
options.add_argument('--disable-infobars')
options.add_argument('--dis... | The main task of the code is to scrape eBay for product details and reviews based on a keyword. It retrieves product links, extracts data (including reviews) from each product page using a Firefox driver, and returns the collected information as a list. The function handles search, data extraction, and cleanup, ensurin... | def scrap_ebay(keyword, number_of_products, number_of_reviews):
""" This method is used to scrap ebay information """
print(f"[+ Ebay +] Search Keyword: {keyword}")
driver = get_firefox_driver()
product_links = scrap_product_urls(keyword, number_of_products)
print(f"[+ Ebay +] Product Link is fou... |
def get_firefox_driver():
""" This method is used to get the Firefox driver """
options = FirefoxOptions()
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--start-maximized')
options.add_argument('--disable-infobars')
options.add_argument('--dis... | The main task of the code is to scrape Amazon product data, including product details and reviews, based on a given keyword. It uses a Firefox driver to search for products, extract their URLs, and collect information for a specified number of products and reviews. The function returns a list of product data, including... | def scrap_amazon(keyword, number_of_products, number_of_reviews):
""" This is the main method of the scrapper """
print(f"[+ Amazon +] Search Keyword: {keyword}")
driver = get_firefox_driver()
product_links = scrap_product_listing_url(driver, keyword, number_of_products)
print(f"[+ Amazon +] Pro... |
def create_widgets(self):
self.win = tk.Frame(self.master,borderwidth=2,relief="flat",background="white")
self.win.pack(side="top")
self.buttons=tk.Frame(self.master,borderwidth=2,relief="flat",background="white")
if Persist.SUBSIZE > 2:
tk.Label(self.buttons,text=" {0}x{0} "... | This code initializes a GUI application by setting up window properties, configuring boolean variables for settings (X, Window, Debug), and creating widgets and menus. It uses persistent values to configure the interface, updates the window, and adjusts its size for proper display. | def __init__(self, master=None):
super().__init__(master)
self.SIZE = Persist.SUBSIZE * Persist.SUBSIZE
self.TOTALSIZE = self.SIZE * self.SIZE
self.master = master
self.font = tkfont.Font(weight="bold",size=Persist.Fsize)
#self.pack()
self.X = tk.BooleanVar()
... |
def PlotCS_axis(zoom):
# Define variabels
CS_val = []
CS_err = []
x_val = []
x_err = []
# Compute the cross section
for i in rapidity_range:
CS_val.append(0)
CS_err.append(0)
x_val.append(0)
x_err.append(0)
# Create cross section graph
CS_graph = ROOT.TGraphErrors(3, np.array(x_val), np.array(CS_va... | This code generates and saves cross-section plots for J/ψ production in heavy-ion collisions using ALICE data, with options to compare different trigger configurations, AD veto settings, and ZDC conditions. It customizes plot styles, overlays published results, and saves outputs as PNG files with specific naming based ... | def Run(trigger, ADveto, opt):
# ---------------------------
# Set general options
ROOT.gStyle.SetOptTitle(0)
ROOT.gStyle.SetOptStat(0)
ROOT.gStyle.SetPaintTextFormat("4.3f")
ROOT.gStyle.SetFrameLineWidth(1)
ROOT.gStyle.SetLabelSize(0.045,"xyz")
ROOT.gStyle.SetTitleSize(0.05,"xyz")
ROOT.gStyle.SetTextSize(0.04... |
def data_process(data, batch_size):
env_input = {'ego_state': [], 'ego_map': [], 'neighbors_state': [], 'neighbors_map': []}
batch_plan = []
batch_ground_truth = []
# process a mini batch
while len(batch_plan) < batch_size:
id = random.choice(list(data.keys())) # sample a episode
ep... | This function performs a training step for a predictive model by processing input data, converting it into tensors, feeding it to the model to generate predictions, calculating the loss relative to ground truth, and computing metrics ADE (Average Displacement Error) and FDE (Final Displacement Error) to evaluate predic... | def predictor_train_step(model, data, batch_size, device):
env_input, plan, ground_truth = data_process(data, batch_size)
env_input = {key: torch.as_tensor(_obs).float().to(device) for (key, _obs) in env_input.items()}
plan = torch.as_tensor(plan).float().to(device)
ground_truth = torch.as_tensor(ground... |
def generate_routes(self, paths):
cs_routes = []
goal = np.array(self.ego_state.mission.goal.position)
self.routes = []
self.speed_limit = paths[0][0].speed_limit
for path in paths:
# path extrapolation if not enough waypoints
while len(path) < 51:
... | The main task of the code is to perform trajectory planning for autonomous driving by generating and evaluating candidate paths. It adjusts cost function weights based on training mode, evaluates trajectories for collisions and costs, selects the safest/best trajectory, and outputs the target pose as a list of global p... | def plan(self, obs, env_input, training=False):
# set cost function weigths
if training:
self.cost_weights[-3:] = np.zeros(shape=(3,))
else:
self.cost_weights[-3:] = np.array([1, 5, 10])
# generate trajectories
self.ego_state = obs.ego_vehicle_state
... |
def get_mona_index(self, mona):
if mona == MONA1:
return self.get_matrix_index(self.maze.mona1[0] // 2, self.maze.mona1[1] // 2)
else:
return self.get_matrix_index(self.maze.mona2[0] // 2, self.maze.mona2[1] // 2)
def get_coords(self, index):
return divmod(index, self.wid... | This function determines the next exploration target for a specified agent (mona) in a maze by finding the closest unvisited node, excluding the other agent's target. It calculates distances using a precomputed matrix, selects the nearest valid node, computes the shortest path to it, reverses the path for traversal, an... | def get_next_explore_target(self, mona):
min_dist_to_travel=float("inf")
best_node = self.maze.get_coords(mona)# Best thing to do is to stay in place
mona_index = self.get_mona_index(mona)
other_mona_target = self.mona2_target if mona == MONA1 else self.mona1_target
# print(f'M... |
def get_mona_index(self, mona):
if mona == MONA1:
return self.get_matrix_index(self.maze.mona1[0] // 2, self.maze.mona1[1] // 2)
else:
return self.get_matrix_index(self.maze.mona2[0] // 2, self.maze.mona2[1] // 2)
def update_distance_matrix(self, mona):
# print(f"updating... | The code explores and updates shortest paths for two entities (MONA1/MONA2) in a grid, checking if they can move toward targets. If no path exists, it seeks new exploration targets. It ensures both entities navigate toward unvisited cells by updating distance matrices and managing their movement paths, printing errors ... | def solve(self):
#Explore Current cell & shortest distances & paths to every unexplored cell
# self.pretty_print_matrix()
if self.get_mona_index(MONA1) not in self.visited_ids:
self.update_distance_matrix(MONA1)
if self.get_mona_index(MONA2) not in self.visited_ids:
... |
def getHunger(self):
return self.hunger
def getType(self):
return self.type
def moveDown(self, dist=9999):
if self.energy > 0 and self.rect.y <= dist:
self.energy -= self.speed / 5
self.rect.y += self.speed * self.speed / 10
self.currentAnimation = self.walkSp... | The code defines a `hunt` method that directs an entity's movement based on its type and hunger status. If hungry, it moves in a specific direction (down, up, left, or right) depending on its type ('doux', 'mort', 'tard', 'vita'), then moves randomly. If not hungry, it returns home. The method combines conditional move... | def hunt(self):
if self.getHunger():
if self.getType() == 'doux':
self.moveDown()
if self.getType() == 'mort':
self.moveUp()
if self.getType() == 'tard':
self.moveLeft()
if self.getType() == 'vita':
s... |
def prepare_data(sleep, window):
'''
Prepares data in a format accessible by the model.
:param sleep: sleep data generated by the load_data.get_sleep function
:param window: number of 10-minute steps which are included in a given
example which are used to make a forecast
:return:... | The function generates a sleep/awake time-series forecast using a trained LightGBM model. It prepares data, trains a model, applies weighted predictions, aligns timestamps starting from `time0`, and returns a binary time-series DataFrame with forecasted states over the specified period. | def forecast(sleep, time0, forecast_period):
'''
This function uses the result of the lgbm_avg_prediction function
to generate a sleep/awake timeseries in an appropriate format
:param sleep: sleep data generated by the load_data.get_sleep function
:param time0: timestamp after which the forecast is... |
def _convert_tasks_to_worklogs(self, input:Iterable) -> List[Task]:
output_tasks = [];
for task in input:
output_tasks.append(self._convert_task_to_worklog(task))
return output_tasks
def filter_unreported(self, input:Iterable) -> Iterable:
filtered_inputs = []
for tas... | The main task of the code is to retrieve and process Jira tasks by applying filters (unreported, Jira-specific, and comment marking), converting them to worklogs, and returning them unless recent edits within a cutoff window exist, in which case it returns an empty list. | def get_outstanding_jira_tasks(self) -> List[Task]:
tasks = self._convert_tasks_to_worklogs(
self.filter_unreported(
self.filter_jira_tasks(
self.mark_for_comment(
self.get_all_timing_tasks()
)
)
... |
def __separate_from_strings(self, line: str):
tokens = line.split('"')
if (len(tokens) % 2 == 0):
return False, tokens[-1]
return True, tokens
def __parse_elem(self, elem):
# split the line into words by space
words = elem.split()
for word in words... | The main task of the code is to parse a line by separating string constants, process non-string elements with _parse_elem, return the first valid result, and handle remaining string parts by quoting them. It processes alternating elements, returns parsed results if found, otherwise handles strings and ends with 'endlin... | def _parse_line(self, line: str):
# separate string constants from the rest of the parse
res, string_sepp = self.__separate_from_strings(line)
if not res: return string_sepp
for i, elem in enumerate(string_sepp):
if (i % 2 == 0):
res = self.__parse_elem(elem... |
def create_train_val_dataset(mode, data, precs, atom_feature, edge_feature, ms_transformation, max_mz, resolution,instrument_on_node, self_loop, num_virtual_nodes, element_list, fp_size, noise):
mol_dict, pos_train, neg_train = data
pos_prec, neg_prec = precs
if mode == 'positive':
prec_types = pos_... | The code loads training, validation, and test datasets from CSV files and a molecular dictionary, creates graph datasets using specified parameters, splits data into indices, saves these indices, and converts the combined dataset into a different format for further processing. | def load_trvate(hp):
print('Loading Data...')
pos_train = pd.read_csv(os.path.join(data_dir_prefix+'data', hp['data_dir'], "pos_train.csv"))
neg_train = pd.read_csv(os.path.join(data_dir_prefix+'data', hp['data_dir'], "neg_train.csv"))
with open(os.path.join(data_dir_prefix+'data', hp['data_dir'], "mol_... |
def next_waypoint(self, skip_num):
self.skip_waypoint_num.publish(skip_num)
rospy.wait_for_service('waypoint_manager/waypoint_server/next_waypoint')
try:
self.skip_waypoint()
except rospy.ServiceException as err:
rospy.logfatal("Service call failed: %s" %... | This code implements a ROS-based navigation loop for area selection and delivery tasks. It handles waypoint progression, area selection (a/b/c), delivery completion checks, and dynamic skipping of predefined areas. The loop manages timing, logs progress, and adjusts navigation sequences based on flags like search statu... | def loop(self):
if self.select_exec:
rospy.loginfo_once("---- area select process execute ----")
# timer
if self.time % 5 == 0:
rospy.loginfo("job progress")
# leave collect box
if self.search_box_next and (not self.area_search_flag)... |
def sparse_dropout(x, dropout, noise_shape):
"""Dropout for sparse tensors"""
keep_porb = 1 - dropout
random_tensor = (keep_porb + torch.rand(noise_shape)).floor()
dropout_mask = torch.FloatTensor(random_tensor).type(torch.bool) #tf.cast
i = x._indices()[:, dropout_mask]
v = x._values()[dropout_... | This code performs a forward pass in a graph neural network, applying dropout to inputs, encoding features via a dot product with learned weights, and using GRU units to iteratively convolve over graph structures defined by 'support'. The process incorporates masking and sparse input handling to refine feature represen... | def forward(self, inputs, support, mask):
self.support = support
self.mask = mask
if self.sparse_inputs:
x = sparse_dropout(inputs, self.dropout, self.num_features_non)
else:
x = F.dropout(inputs, self.dropout)
# encode inputs
x = dot(x, self.... |
def __identify_object_details(self):
# reading the file so that if updated, those changes can be accessed as well
self.all_entities_array = file_handler.binary_file_reader()
# creating a string that will be used later to perform date operations
self.class_start_date = self.start_day_dro... | The main task of the code is to validate user input for a registration form, verify the consistency of the start date with the selected schedule's day of the week, generate a registration object, save it to a binary file, and update the UI with success messages and enabled fields. It ensures all required fields are fil... | def __save_registered(self):
# fetching details that have been entered by the user
self.course_dropdown_content = self.course_dropdown.get()
self.student_entrybox_content = self.student_entrybox.get()
self.schedule_dropdown_content = self.schedule_dropdown.get()
self.start_day_dr... |
def apple_generator():
position_apple_X = round(random.randrange(0, display_width - block_size)/10.0)*10.0
position_apple_Y = round(random.randrange(0, display_height - block_size)/10.0)*10.0
return position_apple_X, position_apple_Y
def message_to_screen(msg, color, y_displace = 0, size = 'small'):
textSurf, text... | This code implements a Snake game loop where the player controls a snake to eat apples, increasing its length. The game detects collisions with walls or the snake's own body to trigger a "Game Over" state, allowing the player to restart or quit. The loop handles input, updates the snake's position, renders graphics, an... | def gameloop():
global direction
snake_list = []
snake_length = 1
gameExit = False
gameOver = False
lead_x_change = 0
lead_x = int(display_width/2)
lead_y = int(display_height/2)
lead_y_change = 0
position_apple_X, position_apple_Y = apple_generator()
while not gameExit:
if gameOver == True:
message_... |
def list_connections():
output=""
for i,conn in enumerate(all_connections):
try: # sending a dummy request to client to check whether connection is active or not
conn.send(str.encode(" ")) # sending an empty string
conn.recv(20480) ... | This code creates a server shell (KD) to manage connected clients. It allows listing active clients, selecting a target client by ID to send commands, exiting the server, and displaying help. The loop processes user input, handles client connections, and terminates sessions gracefully when exiting. | def start_KD():
while True:
cmd=input('KD> ')
# list command -> it will be used to list all connected clients on prompt
if cmd == "list" :
list_connections() # funtion to list all the connected clients
# KD> list
... |
def create_socket():
try:
global host # global variable storing host/ip of server
global port # global variable storing port on which server will be listening
global s # global variable for socket on which server will be listening
host="" # initialize with static ip of ser... | The code defines a function `work()` that processes tasks from a queue in a loop. If the task is `1`, it creates, binds, and accepts connections on a socket. If the task is `2`, it initiates an interactive shell for targeting and command execution. Each task marks the queue item as done after processing, ensuring coord... | def work():
while True:
x=queue.get() # retrieves and removes element at front of queue
if x == 1: # it indicates job number 1 i.e thread 1
create_socket() # creating socket
bind_socket() # binding socket to host and port
accept_co... |
def constraintCheckFunction(vector):
## We have the following cases:
## 1. the nonnegativity constraints are satisfied and the sum
## of fracVacs does not exceed 1. No repair needed.
## 2. the nonnegativity constraints are satisfied but the sum
## of the fracVacs exceeds 1. Repair to ... | This function evaluates the objective function for Nelder-Mead optimization by checking constraints on `fracVacs`, repairing invalid values, and returning the specified output index from `objectiveFunctionICU_HospPeak`. It ensures valid inputs through constraint checks and repairs, then computes and returns the target ... | def objectiveFunction_NM(fracVacs, extraParamsNM):
'''
This is the objective function that will be passed to Nelder-Mead. It evaluates the function objectiveFunctionICU_HospPeak
for the decision variable fracVacs given. Depending on the variable myIndex, it returns the appropriate objective.
Because NM ... |
def constraintCheckFunction(vector):
## We have the following cases:
## 1. the nonnegativity constraints are satisfied and the sum
## of fracVacs does not exceed 1. No repair needed.
## 2. the nonnegativity constraints are satisfied but the sum
## of the fracVacs exceeds 1. Repair to ... | The function evaluates the objective function for each particle in a Particle Swarm Optimization algorithm. It checks constraints on input fractions, repairs them if necessary, and computes the objective value at a specified index. It returns an array of objective values after processing all particles with constraint h... | def particleSwarmsObjectiveFunction_General(fracs, extraParamsPS):
'''
general function that will be used in the Particle Swarms algorithm. For each particle in the swarm, it first "repairs
the particle and then evaluates the function objectiveFunctionICU_HospPeak. Depending on the given myIndex parameter
... |
def parse_args():
"""
Parse arguments
argv[1] in_file
:return: args
"""
arg = ""
try:
arg = sys.argv[1]
except IndexError:
pass
if "youtube" in arg:
# user asked for a specific url
urls = [arg]
else:
try:
num_vids = int(arg... | The main task of the code is to process video URLs sequentially by extracting time-series facial data and frame rates, then visualize the results. It first parses input URLs, iterates through each URL to handle video analysis, and generates plots for each processed video's facial data. The function operates in a single... | def main_single_thread():
urls = parse_args()
for uid, url in enumerate(urls):
faces_time_series, frame_rate = handle_url(url)
plot_faces(faces_time_series, frame_rate, uid) |
def parse_args():
"""
Parse arguments
argv[1] in_file
argv[2] out_file
:return: args
"""
in_file = None
out_file = None
try:
in_file = sys.argv[1]
out_file = sys.argv[2]
except IndexError:
pass
print(f"{in_file}, {out_file}")
return in_fil... | The main task of the code is to process a video file using the `discofy_single` function. It handles default input/output file paths: if no input is provided, it uses `'videos/short.mp4'`, and if no output is specified, it generates a default output name based on the input file. The code ultimately executes `discofy_si... | def main():
in_file, out_file = parse_args()
if in_file is None:
# default file
in_file = 'videos/short.mp4'
out_file = out_file or default_output_name(in_file)
discofy_single(in_file, out_file) |
def solvePath(self, id):
counter = 0
currentRoom = self.solvedRooms[id]
while counter < (2 * (boardWidth + boardHeight)):
possibleDirections = self.findPossibleDirections(currentRoom)
if len(possibleDirections) == 0:
break
dir = (random.choice(... | The code solves dungeon corridors by initially finding a path, iteratively exploring alternative paths until half the rooms are solved, then verifying exit placements in the map. | def solveCorridors(self, dungeonsMap):
self.solvePath(0)
while len(self.solvedRooms) < (boardHeight * boardWidth) // 2.5:
self.solveAlterPaths()
self.verifyExits(dungeonsMap) |
def defineStartingPoint(self, dungeonsMap, entranceDirection: int):
entranceRoomId = random.choice(self.boardLimits[entranceDirection])
dungeonsMap[entranceRoomId].isEntrance = True
dungeonsMap[entranceRoomId].roomStatus = RoomStatus.Solved.name
return entranceRoomId
def solveCorridors(s... | This code initializes a dungeon solver by setting the board limits, determining the entrance room based on direction and the dungeon board, solving corridors to map accessible rooms, and spawning items in designated rooms. | def __init__(self, entranceDirection, dungeonsBoard, boardLimits):
self.boardLimits = boardLimits
self.entranceRoomId = self.defineStartingPoint(dungeonsBoard, entranceDirection)
self.solvedRooms = [self.entranceRoomId]
self.solveCorridors(dungeonsBoard)
self.roomsWithItems = s... |
def create_altair_ascii(name, lcid, lcid_str):
fname = name + '_' + lcid_str + ".hwascii"
if not os.path.exists(fname):
fascii = open(fname, 'w')
fascii.write("ALTAIR ASCII FILE\n")
fascii.write("$TITLE = " + lcid_str + "\n")
fascii.write("$SUBCAS... | This function processes a file (fpch) to extract element stress data, identifies analysis types (static, sine, random), and generates output files (ASCII) based on element types and subcases. It iterates through lines, detects supported elements, computes MOS values, and updates a stress table (s_table) with results, h... | def process_pch(deffile, fout, fpch, s_table):
Lines = fpch.readlines()
stressflag = False
analtype = 0
etypefound = False
looptodo = True
# for i in range(len(Lines)):
i = 0
while i < len(Lines):
line = Lines[i]
if line.startswith(... |
def render_board(self, for_player):
for i in range(8):
for j in range(8):
gameboard_space = ""
if for_player == "w":
gameboard_space = self.gameboard[7-i][j]
else:
gameboard_space = self.gameboard[i][7-j]
... | This method handles user clicks on a chessboard GUI, determining legal moves for the current player's selected piece, including castling and en passant. It updates the board state, highlights possible moves, manages pawn promotion, switches turns, and checks for game-over conditions. The function also handles piece sel... | def click_tile(self, event):
if not self.can_click:
return
info = event.widget.grid_info()
coords = (-1, -1)
if self.turn == "w":
coords = (7 - info["row"], info["column"])
else:
coords = (info["row"], 7 - info["column"])
if s... |
def get_last_text_execute_query(connection = create_connection(), query = "SELECT whole_text FROM Text ORDER BY id DESC LIMIT 1;"):
cursor = connection.cursor(dictionary=True)
cursor.execute(query)
result = cursor.fetchall()
cursor.close()
return result[0]["whole_text"]
def questions_generator_drive... | The main task of the code is to retrieve data using `get_last_text_execute_query()`, generate curated questions from the data via `questions_generator_driver()`, and display them using `display_questions()`. The function `GetQuestions()` handles fetching, processing, and presenting questions in a Streamlit interface. | def GetQuestions():
st.header("Curated Questions")
data = get_last_text_execute_query()
if data:
questions = questions_generator_driver(data)
answers = display_questions(questions) |
def uploadpdf():
st.title("Simple PDF Text Extractor")
uploaded_file = st.file_uploader("Choose a PDF file", type=["pdf"])
if uploaded_file is not None:
with open("temp.pdf", "wb") as temp_file:
temp_file.write(uploaded_file.getvalue())
extracted_text = extract_text_from_pdf("tem... | The main task of the code is to implement a Streamlit web app with a sidebar navigation system. It allows users to select between "Login," "Upload," or "Questions" pages, storing the choice in session_state. Based on the selected page, it dynamically displays corresponding functionality: uploading files, handling login... | def main():
# st.title("Welcome to AI Powered Test")
page = st.sidebar.radio("Select Page", ["Login", "Upload", "Questions"])
session_state['page'] = str(page)
# if navigation() == "login":
# loginPage()
# if navigation() == "upload":
# uploadpdf()
# if navigation() == "questions... |
def replace_jcamp_strings(string):
pos_stop = 0
elements = []
str_list = []
index = 0
while True:
pos_start = string.find('<', pos_stop)
if pos_start < 0:
elements.append(string[pos_stop:])
break
elements.append(string[pos_stop:pos_start])
pos_... | The function `get_array_values` parses and reshapes input data into a NumPy array based on its format. It handles three cases: (1) string arrays enclosed in `<...>`, (2) structs/array-of-structs starting with `(`, and (3) numeric arrays. It uses regex for string extraction, checks dimensional consistency, and reshapes ... | def get_array_values(label, sizes, data):
# Removing whitespaces at the edge of strings
#data = data.replace('< ', '<')
#data = data.replace(' >', '>')
if data.startswith('<'): # Checking if array is a single string or an array of strings ...
#data = data.replace('> <', '><')
#values = r... |
def strtok(string, delimiters=None):
token = ''
remainder = ''
len_str = len(string)
if len_str == 0:
return (token, remainder)
if delimiters is None: # whitespace characters
delimiters = list(map(chr, list(range(9, 14)) + [32]))
i = 0
while string[i] in delimiters:
... | The code reads and parses a parameter file, extracting headers and structured data. It validates the file format (e.g., JCAMP-DX version), processes lines with `##` (parameters) and `$$` (comments), handles nested data types (strings, arrays, structs), and ensures proper termination with an "END" tag. It returns a tupl... | def read_param_file(filename):
# Open parameter file
try:
fid = open(filename, 'r')
except IOError as V:
if V.errno == 2:
sys.exit("Cannot open parameter file %s" % (filename,))
else:
raise
# Generate header information
header = collections.OrderedDic... |
def pc_settings_read(settings_file_name=None, settings_file_version=None):
settings_file_name = user_or_default_settings_file(settings_file_name)
if settings_file_version is None:
settings_file_version = DEFAULT_SETTINGS_FILE_VERSION
if os.path.isfile(settings_file_name):
pc_settings = pc_f... | The function generates or retrieves PC login settings by either reading from a specified file or using provided credentials and URL base. It validates required parameters and constructs a settings dictionary with username, password, API base, and a placeholder for JWT, returning it for authentication purposes. | def pc_login_get(username, password, uibase, settings_file_name=None):
pc_settings = {}
if username is None and password is None and uibase is None:
pc_settings = pc_settings_read(settings_file_name)
elif username is None or password is None or uibase is None:
pc_exit_error(400, 'Access Key ... |
def initialize(self):
'''Get transactions and initialize database'''
# Flags
is_disk_initialized = False
is_new_transaction = True
# Counters
transaction_count = 0
current_transaction = None
with open(self.filename, 'r') as file:
for line in ... | The code's main task is to execute the logging process by initializing resources, processing data, appending an empty string to the logs list, and writing the log entries. This method orchestrates preparation, data handling, log formatting, and storage in a structured sequence. | def log(self):
self.initialize()
self.process()
self.logs.append('')
self.write_log() |
def compile():
command = "g++ ../src/ptm.cpp -std=c++11 -O3 -o pmt"
subprocess.call(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
def assert_algorithms_match(pattern, text_file, algorithms):
for edit_distance in range(3):
occurrences_counts = {}
for algorithm in algo... | The code tests and compares the performance of two approximate string matching algorithms ('se' and 'uk') on various patterns and text files. It verifies correctness, measures execution times for different pattern lengths and edit distances, and visualizes the results. | def main():
compile()
aprox_algorithms = ['se', 'uk']
patterns = sorted(['aba', 'abacaba', 'beauty', 'mediumsizepatterntotest', 'gentleman', 'gentlewoman'], key=len)
text_files = ['shakespeare.txt']
number_executions = 10
max_pattern_len = 30
# assert correctness
for text_file in text... |
def choose_sample(sample):
text_file = {}
patterns = {}
text_file['english'] = 'samples/english.txt'
patterns['english'] = [
'by', 'this', 'compose', 'footnote', 'appendices', 'word-processing', 'Provisional Government',
'The Committee for Salvation', 'But the reader must realize that',... | The main task of the code is to benchmark exact and approximate string matching algorithms on protein data. It compiles a C++ program (`ptm`), runs exact algorithms (grep, KMP, etc.) and approximate algorithms (SE, UK) with varying edit distances, and plots results. The code processes patterns from a sample text file, ... | def main():
text_file, patterns = choose_sample('proteins')
print('patterns -> count: %d:' % len(patterns))
for pattern in patterns:
print('(%d): %s' % (len(pattern), pattern))
print('compiling program')
ptm_source = '../src/ptm.cpp'
ptm = 'ptm'
compile_command = '%s %s %s -o %s' %... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION') | This code creates a feature store in Google's AI Platform using the provided ID and configuration. It initializes a client, constructs a request with online serving settings, submits the creation request, and prints the operation name and final response. The function handles asynchronous operations with a timeout, retu... | def create_featurestore_sample(
featurestore_id: str,
fixed_node_count: int = 1,
timeout: int = 600,
):
client_options = {"api_endpoint": api_endpoint()}
client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_options)
parent = f"projects/{project()}/locations/{location()}"
... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION') | This function creates an entity type within a specified feature store using the AI Platform's FeaturestoreServiceClient. It constructs a request with provided parameters, initiates the creation, and waits for completion with a timeout. Key steps include setting up the client, forming the parent path, building the entit... | def create_entity_type_sample(
featurestore_id: str,
entity_type_id: str,
description: str,
timeout: int = 300,
):
client_options = {"api_endpoint": api_endpoint()}
client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_options)
parent = f"projects/{project()}/locations/{... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION') | This function creates a feature in a feature store using the provided parameters (feature ID, value type, description) and the FeaturestoreServiceClient. It constructs a request, submits it to the API, waits for the operation to complete within a timeout, and returns the response. | def create_feature(
featurestore_id: str,
entity_type_id: str,
feature_id: str,
value_type: aiplatform.gapic.Feature.ValueType,
description: str,
timeout: int = 300,
):
client_options = {"api_endpoint": api_endpoint()}
client = aiplatform.gapic.FeaturestoreServiceClient(client_options=c... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION')
def import_input_uri():
return getenv('IMPORT_INPUT_URI') | This code imports feature values from a CSV file stored in Google Cloud Storage (GCS) into a specified entity type within a Google Cloud AI Platform feature store. It configures the import request with entity and feature identifiers, specifies the data source, and uses an asynchronous operation to handle the import pro... | def import_feature_values(
featurestore_id: str,
entity_type_id: str,
entity_id_field: str,
feature_time_field: str,
worker_count: int = 1,
timeout: int = 600,
):
client_options = {"api_endpoint": api_endpoint()}
client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION') | This function retrieves specific feature values from a Google Cloud AI Platform feature store for a given entity by constructing an API request with provided identifiers and a feature selector. | def read_online_feature_values(
featurestore_id: str,
entity_type_id: str,
entity_id: str,
feature_ids: List[str],
):
client = aiplatform.gapic.FeaturestoreOnlineServingServiceClient(
client_options={"api_endpoint": api_endpoint()}
)
entity_type = f"projects/{project()}/locations/{lo... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION')
def batch_input_uri():
return getenv('BATCH_INPUT_URI')
def batch_output_uri_prefix():
return getenv('BATCH_OUTPUT_URI_PREFIX') | This function retrieves feature values from a specified feature store in batch mode. It uses the provided feature IDs, entity type, and input/output GCS paths to request data, which is then saved as CSV files. The function initializes a client, constructs a batch read request, and waits for the operation to complete wi... | def batch_read_feature_values(
featurestore_id: str,
entity_type_id: str,
feature_ids: List[str],
timeout: int = 300,
):
client_options = {"api_endpoint": api_endpoint()}
client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_options)
featurestore = (
f"projects... |
def api_endpoint():
return '{}-aiplatform.googleapis.com'.format(location())
def project():
return getenv('PROJECT')
def location():
return getenv('LOCATION') | This function deletes a specified feature store and its underlying entities using the provided featurestore_id. It initializes a FeaturestoreServiceClient, constructs the feature store's name path, and invokes the delete operation with force=True to ensure deletion of all associated entities. The function waits for the... | def delete_featurestore(
featurestore_id: str,
timeout: int = 300,
):
client_options = {"api_endpoint": api_endpoint()}
client = aiplatform.gapic.FeaturestoreServiceClient(client_options=client_options)
name = client.featurestore_path(
project=project(), location=location(), featurestore=f... |
def handleKeys(self, key):
# handler for jump key
if key[self.controls["jump"]] and self.airjumps > 0 and self.jumptick == 0: # self.airtime == 0:
self.vel[1] = -self.jump
self.u = -self.jump
# print(self.airjumps)
self.airtime = self.time
... | This method updates a player's state in a game, including health, ammo/rocket bars, movement, collisions, and death/respawn logic. It handles input, physics (gravity, deceleration), collision checks, tick counters for actions like jumping and reloading, and regenerates health during respawn. If dead, it triggers a resp... | def update(self, keys, time):
# update hp bar
self.stats.update(self.hp)
# if not out of ammo update ammo bar else reload bar
if self.clip > 0:
self.bulles.update(self.clip)
else:
self.bulles.update(self.reloadTick / gameVariables.reload_speed * gameVariab... |
def get_book(path:str or Path, return_path=False) -> xw.Book:
"""Returns `xw.Book` object.
Parameters
----------
path : str | Path | xw.Book
Path to Excel workbook.
return_path : bool, optional
If True, returns tuple (`xw.Book`, `Path`), else returns `xw.Book`.
"""
if is... | This code initializes a class instance to process Excel workbook data by importing named ranges from a specified sheet. It creates attributes for the workbook, sheet, and ranges, then converts each range into a dictionary with options for handling headers, units, trimming None values, and key casing. Custom arguments o... | def __init__(self, book_name:str or Path, sheet_name:str, rg_list:list[str], rg_args:dict=None, custom_rg_args:dict=None) -> None:
"""Returns an instance with attributes matching named ranges provided in `rg_list` on `sheet`.
Parameters
----------
book_name : str or Path
... |
def t_player_bid(self,lastBid):
if self.code_pos < 4 and len(self.bids_diff[self.who_am_i]) >= 3:
code = self.engine.math.floor(self.tv/pow(16,3-self.code_pos))
self.tv %= pow(16,3-self.code_pos)
self.engine.makeBid(lastBid + code + 8)
self.bids += 1
... | This code determines a player's bidding strategy in a multi-phase game, using pre-defined rules for phases 1 and 2. It selects between NPC, normal, or true-player bidding based on round number, known true values, and team roles. In phase 2, bots communicate via bids until all true values are identified, then use fake v... | def onMyTurn(self,lastBid):
# lastBid is the last bid that was mad
#choose 1 player if true value not known based on betting position
if self.round == 8 and self.ph2 == False:
if self.who_am_i == self.normal_team_list[0]:
self.acts_as_npc... |
def run_simulation(env, output_layer, max_steps, rand):
steps = []
state = env.reset()
for i in range(max_steps):
env.render()
(next_action, action_val) = get_next_action(env, state, output_layer, rand)
step = list(env.step(action_val))
step.append(state)
step.appe... | The main task of the code is to run a trained simulation in the environment, track episode count, update exploration parameters periodically, log average steps using TensorFlow summaries, and return the simulation's step data for analysis. | def run_and_store_simulation(env, output_layer, max_steps, tf_objs):
global num_episodes
global recent_episodes
num_episodes += 1
steps = []
writer = tf_objs[wr]
avg_steps_summ = tf_objs[sm]
print("Running Trained Simulation")
steps = run_simulation(env, output_layer, max_steps, False... |
def run_and_store_simulation(env, output_layer, max_steps, tf_objs):
global num_episodes
global recent_episodes
num_episodes += 1
steps = []
writer = tf_objs[wr]
avg_steps_summ = tf_objs[sm]
print("Running Trained Simulation")
steps = run_simulation(env, output_layer, max_steps, False... | The function `train_model` executes multiple simulation episodes to train a model. For each episode, it runs a simulation, stores the steps, calculates cumulative rewards, and updates coefficients using the provided TensorFlow objects. The process iterates for a predefined number of episodes, aiming to optimize the mod... | def train_model(env, output_layer, tf_objs, max_steps=1000):
print("Running Simulations")
for i in range(EPISODES):
print("")
print("Episode", i + 1)
steps = run_and_store_simulation(env, output_layer, max_steps, tf_objs)
calculate_cum_reward(steps)
update_coef(steps, tf... |
def simplified(self, sentence):
part_of_speech = ['adj', 'adv', 'adp', 'conj', 'det', 'noun', 'num', 'pron', 'prt', 'verb', 'x', '.']
parts_of_speech = []
speech_temp = ''
for word in sentence:
value = 0
if word in self.word_count:
for pos in part_... | The code defines a `solve` method that selects and executes a specific algorithm based on the input `model` parameter. If the model is "Simple," it uses a simplified approach; if "HMM," it applies the Viterbi algorithm for Hidden Markov Models; if "Complex," it employs a Markov Chain Monte Carlo (MCMC) method. For unkn... | def solve(self, model, sentence):
if model == "Simple":
return self.simplified(sentence)
elif model == "HMM":
return self.hmm_viterbi(sentence)
elif model == "Complex":
return self.complex_mcmc(sentence)
else:
print("Unknown algo!") |
def version():
return execute("PRAGMA user_version", fetchone=True)['user_version']
def schema_versions():
schemas = []
for file in sorted(PATH_SCHEMAS.iterdir()):
if not file.suffix == ".py":
continue
if not file.stem.isdigit():
continue
version = int(file.s... | This function handles database schema upgrades or downgrades to a specified version. It checks compatibility, validates the target version's availability, applies the corresponding migration (upgrade/downgrade), and reverts to the current version on failure. | def set_schema(ver):
current = version()
versions = schema_versions()
upgrade = ver > current
print(f"Preparing to do a schema {'upgrade' if upgrade else 'downgrade'}.")
if ver == current:
print("Already at version {current}, aborting.")
return
migration_version = ver if upgr... |
def schema_versions():
schemas = []
for file in sorted(PATH_SCHEMAS.iterdir()):
if not file.suffix == ".py":
continue
if not file.stem.isdigit():
continue
version = int(file.stem)
schemas.append((version, file))
return dict(sorted(schemas))
def versio... | The code checks the current database version against available schema versions. If an update is needed, it performs migrations iteratively until the database reaches the latest version. | def init():
versions = schema_versions()
current_version = version()
version_max = max(versions)
if current_version >= version_max:
return
print(
f"Current database version is {current_version}, {version_max}" +\
" available, performing database migrations."
)
while... |
def create_parquets(data_bucket_folder, train_path, valid_path):
cupy.random.seed(seed=0)
rmm.reinitialize(managed_memory=True)
documents_meta_path = os.path.join(data_bucket_folder, 'documents_meta.csv')
clicks_train_path = os.path.join(data_bucket_folder, 'clicks_train.csv')
events_path = os.path.... | The main task of the code is to execute a data processing pipeline by creating required directories, generating parquet files from specified data paths, saving statistical information to output folders, and cleaning temporary files. It uses configuration parameters to manage input/output paths and ensures necessary fol... | def execute_pipeline(config):
required_folders = [config['temporary_folder'], config['output_train_folder'], config['output_valid_folder']]
for folder in required_folders:
os.makedirs(folder, exist_ok=True)
create_parquets(
data_bucket_folder=config['data_bucket_folder'],
train_path... |
def validation_step(self, batch, batch_idx):
if self.current_epoch < self.args.skip_first_n_eval:
return None
img, lbl = batch["image"], batch["label"]
pred = self._forward(img)
loss = self.loss(pred, lbl)
self.dice.update(pred, lbl[:, 0])
return {"val_loss": ... | This method processes a batch during testing. If in evaluation mode, it delegates to validation_step. Otherwise, it performs forward inference on images, applies softmax, and saves predicted masks. It adjusts predictions to original image dimensions using metadata, resizing if necessary, before storing results. | def test_step(self, batch, batch_idx):
if self.args.exec_mode == "evaluate":
return self.validation_step(batch, batch_idx)
img = batch["image"]
pred = self._forward(img)
if self.args.save_preds:
meta = batch["meta"][0].cpu().detach().numpy()
original_s... |
def create_food(self):
x = random.randint(0, 18) * 20
y = random.randint(0, 18) * 20
food = self.canvas.create_rectangle(x, y, x + 20, y + 20, fill="red", tags="food")
return food
def create_colliders(self):
colliders = []
for _ in range(2):
x = random.randint... | This code initializes a Snake game GUI using Tkinter. It sets up the main window/frame, creates a black canvas for the game area, initializes the snake's starting position and direction, places food, sets up collision detection components, binds keyboard controls for direction changes, and starts the game loop to updat... | def __init__(self, master):
if isinstance(master, tk.Tk):
self.master = master
self.master.title("Snake Game")
self.master.geometry("400x400")
self.master.resizable(False, False)
elif isinstance(master, tk.Frame):
self.master = master
... |
def create_colliders(self):
colliders = []
for _ in range(2):
x = random.randint(0, 19) * 20
y = random.randint(0, 19) * 20
collider = self.canvas.create_rectangle(x, y, x + 20, y + 20, fill="purple", tags="collider")
colliders.append(collider)
ret... | The main task of the code is to reset the game state by clearing the canvas, reinitializing game elements like the snake, food, and colliders, canceling ongoing animations, and resetting the score to prepare for a new game session. | def reset_game(self):
self.canvas.delete("all")
self.collider = self.create_colliders()
self.collider_positions = self.canvas.coords(self.collider)
self.master.after_cancel(self.after_id)
self.snake = [(100, 300), (90, 300), (80, 300)]
self.direction = "Right"
sel... |
def generate_segments(polygons):
# generate list of segments
segments = []
for polygon in polygons:
for i in range(0, len(polygon)):
segments.append((polygon[i-1], polygon[i]))
return segments
def intersection(seg1, seg2):
# find the intersection point of two segments
# assum... | The code implements the Bug 1 algorithm for path planning, navigating from a start point to an end point while avoiding obstacles. It moves directly toward the goal until hitting an obstacle, then traces the obstacle's perimeter until a clear line of sight to the goal is found, repeating this process iteratively to con... | def bug1(polygons, start, end):
# algorithm which implements bug 1
# start by moving toward the goal until we hit an obstacle
segments = generate_segments(polygons)
path = []
path.append(start)
# check intersection with segment start/end
midline = (start,end)
midline_intersections ... |
def initialize():
# get arguments
args = get_args()
# init bmt
torch.cuda.set_device(args.local_rank)
dist.init_process_group(backend="nccl")
# init save folder
if args.save != None:
os.makedirs(args.save, exist_ok=True)
return args
def setup_model_and_optimizer(args):
# get ... | This code initializes training parameters, sets up a model with optimizer and scheduler, prepares a dataset for distributed training, and executes fine-tuning on a specified SuperGLUE dataset using the configured components. | def main():
args = initialize()
tokenizer, model, optimizer, lr_scheduler = setup_model_and_optimizer(args)
dataset = prepare_dataset(
args,
tokenizer,
f"{args.base_path}/down_data/superglue/",
args.dataset_name,
dist.get_rank(),dist.get_world_size(),
)
finetu... |
def check_stepped_outside(self, fromxy: tuple) -> bool:
if fromxy[0] < 0 or \
fromxy[1] < header_height or \
fromxy[0] > resolution_X - sizex or \
fromxy[1] > resolution_Y + header_height - sizey:
return True
return False
def check_snake_eat_himself(self,... | This code moves a snake in a specified direction, calculates its new head position, checks for collisions with boundaries or itself, and updates the snake's position. If the snake dies or collides with itself, it returns the original position; otherwise, it updates the snake's body and returns the new head position. | def move(self, fromxy: tuple):
new_head_pos = ()
if self.direction == 'L':
new_head_pos = (fromxy[0] - sizex, fromxy[1])
elif self.direction == 'R':
new_head_pos = (fromxy[0] + sizex, fromxy[1])
elif self.direction == 'U':
new_head_pos = (fromxy[0], f... |
def super_access(password, command):
sleep(0.5)
ssh = ssh_connect(ip, user_name, password)
stdin, stdout, stderr = ssh.exec_command(f'echo {password} | sudo -S {command}')
res = stdout.read().decode().strip('\n')
if res != '':
return res
else:
pass
def usb_eject():
try:
... | This function renames a USB drive to its original name using the 'mlabel' command, then ejects and reconnects the device to apply the change. It waits briefly, executes the renaming with elevated access, and logs the action. | def usb_rename_to_original():
sleep(1)
super_access(password, f"mlabel -i {dev} ::{current_usb_name}")
usb_eject()
usb_reconnect()
print(green("USB renamed to it's original name"))
logger.info("USB renamed to it's original name") |
def unmount(path):
exec_command(f"umount {path}")
logger.info('USB Unmounted')
print(green('USB Unmounted'))
def super_access(password, command):
sleep(0.5)
ssh = ssh_connect(ip, user_name, password)
stdin, stdout, stderr = ssh.exec_command(f'echo {password} | sudo -S {command}')
res = stdou... | The function formats a USB drive as FAT by unmounting it, executing a formatting command with superuser access, logging and printing a confirmation, then ejecting and reconnecting the USB device to finalize the process. | def fat_file_format():
unmount(dev)
super_access(password, f"mkfs.fat {dev}")
logger.info('USB Formatted')
print(green('USB Formatted'))
usb_eject()
usb_reconnect() |
def unmount(path):
exec_command(f"umount {path}")
logger.info('USB Unmounted')
print(green('USB Unmounted'))
def super_access(password, command):
sleep(0.5)
ssh = ssh_connect(ip, user_name, password)
stdin, stdout, stderr = ssh.exec_command(f'echo {password} | sudo -S {command}')
res = stdou... | The function formats a USB device to NTFS by unmounting it, executing a password-protected NTFS formatting command, logging the action, ejecting the USB, and reconnecting it to ensure the changes take effect. | def ntfs_file_format():
unmount(dev)
super_access(password, f"mkfs.ntfs {dev}")
logger.info('USB Formatted')
usb_eject()
usb_reconnect() |
def unmount(path):
exec_command(f"umount {path}")
logger.info('USB Unmounted')
print(green('USB Unmounted'))
def super_access(password, command):
sleep(0.5)
ssh = ssh_connect(ip, user_name, password)
stdin, stdout, stderr = ssh.exec_command(f'echo {password} | sudo -S {command}')
res = stdou... | The main task of the code is to format a USB device with the exFAT file system. It unmounts the device, executes a formatted command with a password, logs the formatting action, ejects the USB, and reconnects it to ensure the changes take effect. | def exfat_file_format():
unmount(dev)
super_access(password, f"mkfs.exfat {dev}")
logger.info('USB Formatted')
usb_eject()
usb_reconnect() |
def _calculate_teleport_heuristic(self, board):
start_time = time.time()
front_heuristic = 0
back_heuristic = 0
for x in range(len(board)):
for y in range(len(board[x])):
current = board[x][y]
if current == 0:
continue
... | The function calculates and returns the minimum heuristic value (front or back) based on the specified heuristic type (teleport, slide, or learned), along with the computation time. It delegates to specialized methods for each heuristic type, ensuring the smallest heuristic is selected for optimization. | def _calculate_heuristic(self, board):
if self.heuristic_type == HEURISTIC_TELEPORT:
front_heuristic, back_heuristic, calc_time = self._calculate_teleport_heuristic(board)
return min(front_heuristic, back_heuristic), calc_time
elif self.heuristic_type == HEURISTIC_SLIDE:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.