dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def open_file():
'''
Using user's input, attempts to open .txt file (try/except)
Returns txt file
'''
# driver loop for user's file input #
while True:
file_input = input("Enter a filename: ")
try:
# while file exists, attempt opening #
fp = open(file_i... | The code's main task is to recommend a Facebook friend for a given user ID based on a similarity matrix derived from a social network. It reads user-friend data from a file, calculates pairwise similarities, and suggests the most compatible friend for a specified user. The program interactsively prompts users to input ... | def main():
print("\nFacebook friend recommendation.\n")
# prompts user for file and attempts to open #
fp = open_file()
# creates list of lists (user's and their friends) from file provided #
network = read_file(fp)
# creates similarity matrix from network #
similarity_matrix = calc_similar... |
def createPart():
parts = dict()
showVersions()
versionNum = input('\nInsert the number of the template you wish to use: ')
for template in pvers.templateList:
if template["version"] == versionNum:
parts = template
for key in parts.keys():
if key != 'versi... | The code presents a menu-driven interface for managing a parts database, allowing users to create, delete, search, or print records, with options to exit the program. It loops until the user selects "Exit", executing corresponding functions based on input choices. | def menu():
while True:
print('******************************')
print('\tPART DATABASE')
print('******************************')
print('Options: ')
print('1. Create a record')
print('2. Delete a record')
print('3. Search for a record')
print('4. Print ... |
def move(self, x=1, y=1):
screen_x, screen_y = self._to_screen_coordinate(x, y)
x_high, x_low = self._to_byte(screen_x)
y_high, y_low = self._to_byte(screen_y)
self.report[3] = x_low
self.report[4] = x_high
self.report[5] = y_low
self.report[6] = y_high
se... | The main task of the code is to perform a smooth panning motion from a starting coordinate (start_x, start_y) to an ending coordinate (end_x, end_y) using a specified number of steps. It calculates incremental x and y movements, updates the position step-by-step with a delay, and applies pressure at the start and relea... | def pan(self, start_x, start_y, end_x, end_y, input_steps=30):
steps = float(input_steps)
step_x = (end_x - start_x) / steps
step_y = (end_y - start_y) / steps
current_x = start_x
current_y = start_y
self.move(start_x, start_y)
self.press()
while steps > ... |
def get_validation_accuracy(self):
validation_trains = []
for k in range(len(self.validation_features)):
input_train = np.array(self.rate_encoding(self.validation_features[k], self.total_time))
validation_trains.append(input_train)
decoded_outputs = self.test_step_mnist(... | The code trains and evaluates a neural network on the MNIST dataset, using rate-encoded input features. It optionally loads pre-saved weights, trains iteratively while validating accuracy at specified intervals, visualizes learned weights, and computes test accuracy. The function handles both training from scratch and ... | def execute_mnist(self, execution_name, use_saved_weights=True, visualize_weights=False, validation_gap=100):
print("\n{} EXECUTION".format(execution_name))
n_iterations = 1
input_trains = []
for i in range(len(self.train_features)):
input_train = np.array(self.rate_encoding(... |
def get_predicted_apds(predicted_traces, actual_traces):
pred_widths_test = []
raw_widths_test = []
for pred_test,raw_test in zip(predicted_traces,actual_traces):
w1_test, h1_test, l1_test = get_apds(pred_test, 2800)
pred_widths_test.append(w1_test)
w2_test, h2_test, l2_test = get_apds(raw_test, 280... | The code calculates accuracy metrics by determining percent and absolute errors between predicted and correct APD values. It computes percentile distributions (10th to 90th) for each of 10 APD categories, returning predicted/correct APDs, error percentiles, and cutoff values for analysis. | def calculate_accuracy(intra_predictions, intra_correct):
pred_apds, correct_apds = get_predicted_apds(intra_predictions[:,:,0], intra_correct[:,:])
apds_percent_errors, apds_absolute_errors = get_apd_errors(pred_apds, correct_apds)
new_length = len(get_percentile_data(apds_percent_errors[0], 10, 90))
apds_per... |
def _draw_maze(self):
for row_index in range(self._env.get_maze_length()):
for col_index in range(self._env.get_maze_width()):
self._draw_cell(row_index, col_index)
def _draw_goal(self):
target = self._env.get_target()
shift = 2 * self._WALL_WIDTH
left = targe... | The code processes user input events (arrow keys and 'g') to control game elements, updates the game environment, and renders the game state by redrawing the maze, player, goal, and information if visible. It exits on quit events and toggles visibility with 'g' | def step(self):
self._input_manager.clear()
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
self._input_manager.up = True
elif... |
def make_guess(self, startingwords=None):
"""
Makes another guess
"""
if isinstance(startingwords, list) and self.game_attrs["guess_count"] < len(
startingwords
):
self.guess_word = startingwords[self.game_attrs["guess_count"]]
elif isinstance(star... | The play function manages a Wordle game session by initializing game attributes, processing guesses using the evaluator, updating game state iteratively, and tracking the number of guesses until the game ends. It accepts parameters for initial guesses, evaluation logic, and a target word, returning the total guess coun... | def play(self, startingwords=None, evaluator=None, final_word=None):
"""
The play function plays the game of Wordle against the human
"""
self.game_attrs["game_over"] = False
self.game_attrs["game_list"] = self.wordlist
self.counter = Counter([j for i in self.game_attrs["... |
def update_scope_prefix(scope, line, prefix):
scope = scope + line
if strbalance.is_unbalanced(scope) == None:
scope = ""
prefix = prefix_remove(prefix)
return scope, prefix
def find_str_after(line, keyword):
toks = list(filter(None, line.split(' ')))
for i in range(0, len(toks)):
... | This function parses a file to extract procedures, tracking their scope (module, class, datatype) and type. It identifies procedures using proc_type_list, updates their content and location, and populates a dictionary (`data`) with procedure details. It skips comments, handles nested scopes, and uses helper functions t... | def parse_file(file, filename, proc_type_list):
data = {}
prefix = ""
# tracks content of lines within scope
module_scope = ""
datatype_scope = ""
class_scope = ""
proc_scope = ""
proc_loc = 0
proc_name = ""
proc_type = ""
for line in file:
# continues until the f... |
def set_label(self, label):
if label is not None:
self.set_field('label', label)
self.label = self.get_field('label')
self._label = self.label
return self
def get_label(self):
if self.label is None:
self.label = self.get_field('label')
retu... | This function initializes parameters and processes input data by setting categorical features, labels, and applying transformations. It checks if 'categorical_feature' exists in the data columns, updates parameters accordingly, sets the label if provided, and triggers a full data transformation. The method ensures prop... | def _lazy_init(self, data, label=None, params=None,
categorical_feature=None):
if data is None:
return self
params = {} if params is None else params
if isinstance(categorical_feature, list) and categorical_feature:
categorical_feature = pd.Index(catego... |
def clear_temp_dir():
#Select the temporary directory for the data.
path = tempfile.gettempdir()
current_directory = os.getcwd()
os.chdir(path)
temp_zips = glob.glob("*.zip")
temp_csvs = glob.glob("*.csv")
temp_zip_paths = [os.path.join(path, names) for names in temp_zips]
temp_csv_pa... | The main task of the code is to retrieve and verify LEAD-data files from the DoE website by extracting relevant links, comparing them with local files, and handling errors. It filters links containing "LEAD-data", checks for matches against local files, and reports discrepancies or errors, ensuring data consistency whi... | def main():
try:
#Get the links from the DoE website.
session = HTMLSession()
r = session.get(site_url)
links= r.html.links
#Parse out the data for just LEAD-data files.
clear_temp_dir()
LEAD_data=[]
substring = "LEAD-data"
for link in... |
def get_terrestrial():
mass_epsi = (7/9)*(20/22)
mass = np.random.f(9,20)*(1.43e-5/mass_epsi)
if 9.5459e-6 <= mass <= 2.8638e-5:
diff = mass - 1.43e-5
mass += 0.05*diff
elif mass > 2.8638e-5:
diff = mass - 2.8638e-5
move = np.random.random()
if move <= 1/7:
... | This code generates a stable planetary system with specified parameters, calculating probabilities for terrestrial, cold Jupiter, and hot Jupiter planets based on star mass. It randomly adds planets, checks orbital stability using Hill radii, removes unstable configurations, and returns sorted system parameters and sim... | def generate_system(num_planets, star_mass, only_terr):
sim = rebound.Simulation()
sim.units = ("day", "AU", "Msun")
sim.add(m=star_mass)
sys_param = np.zeros((num_planets+1,7))
sys_param[0,0] = star_mass
if only_terr:
cold_jup_odds = 0.0
hot_jup_odds = 0.0
else:
if 0... |
def distrobuteCostumersToDepot(costumers: list[Costumer], depots:list[Depot]) -> bool:
"""
Calclate the closes depot to a costumer and add that costumer to that depot
"""
for costumer in costumers:
isBorderCostumer = False
depotsDistance = dict()
shortestDistance = sys.maxsize
... | The code implements a genetic algorithm (GA) to optimize vehicle routing by distributing customers to depots and minimizing total travel distance. It initializes customer-depot assignments, calculates initial route lengths, evaluates fitness based on distance, and iteratively refines solutions through GA operations (se... | def GA():
global costumersDistribute, depots, shortestDistance, iterations
# NOTE: Can change edge costumers to another depot randomly?
initialLengths = []
# 2. Random distribution
distrobuteCostumersToDepot(costumersDistribute, depots)
for depot in depots:
depot.distrubuteVehiclesRan... |
def parseFile(fileName):
global totalVehicles
with open(f'DataFiles/{fileName}.txt') as file:
# Parse first line
m, n, t = file.readline().split()
totalVehicles = int(m) * int(t)
# Set up depots
for i in range(int(t)):
D, Q = file.readline().split()
... | The code `testThing(fileNum)` processes a dataset (via `parseFile`) to run a Genetic Algorithm (GA) for optimizing depot-customer route distribution. It initializes global variables, sets up a matplotlib plot for visualization, executes the GA, calculates the optimal solution's total cost and routes, and returns the to... | def testThing(fileNum):
global depots, costumers, costumersDistribute, fig, ax, xMax, xMin, yMax, yMin, borderLineThreshold
depots = []
costumers = []
costumersDistribute = []
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
xMax = 0
xMin = 0
yMax = 0
yMin = 0
borderLineThre... |
def create_parser():
parser=argparse.ArgumentParser()
parser.add_argument('input_image')
parser.add_argument('initial_snake')
parser.add_argument('output_image')
parser.add_argument('alpha', type=float)
parser.add_argument('beta', type=float)
parser.add_argument('tau', type=float)
parser... | The code performs active contour (snake) segmentation on an input image using specified parameters. It loads a grayscale image and initial contour, configures energy function weights, evolves the contour via the `move_snake` function, visualizes the result, and saves the segmented mask as an output image. | def main():
namespace=create_parser().parse_args()
input_image=np.array(skimage.io.imread(namespace.input_image, as_gray=True), dtype=float)
initial_snake=np.loadtxt(namespace.initial_snake, dtype=float)[:-1]
alpha=namespace.alpha
beta=namespace.beta
tau=namespace.tau
w_line=namespace.w_line... |
def warmup(model, optimizer, data_loader, test_loader, criterion):
for w_i in range(args.warmup_epochs):
for iters, batch in enumerate(data_loader):
model.train()
input, target, _ = batch
input_var = to_var(input, requires_grad=False)
target_var = to_var(targ... | The code trains two neural networks alternately on the mini-ImageNet dataset using pseudo-labeled data from each other, with periodic evaluation and ensemble testing. It initializes models, loads data, performs warmup training, and iteratively updates both models through labeled/unlabeled splits. Accuracy is tracked, s... | def main():
global args, best_acc
best_acc = -1
args = parser.parse_args()
print()
args.num_classes = 100
args.data_root = './dataset/mini-imagenet/'
args.train_split_file = '{}/split/{}'.format(args.data_root, args.split)
args.train_path = '{}/training_s32/{}'.format(args.data_ro... |
def leerArchivo(archivo, laberinto):
lineas = archivo.readlines() # Leo las lineas del archivo
numeroLinea = 0
for linea in lineas: # Recorro las lineas leidas
if 'I' in linea:
coordenadasSalida = numer... | The main task of the code is to generate a maze using a C program, process it in Python to find a path from start to end, and output the result. It repeatedly runs the C program with random parameters until a valid maze is generated, reads the maze data, computes the path, and writes it to an output file. If the C prog... | def main():
# Si paso la cantidad correcta de argumentos
if(len(sys.argv) == 4):
caminoObtenido = []
error = False
# Se guardan los nombres de los archivos que se pasan por terminal al ejecutar el programa
nombreArchivoEntrada = sys.argv[1]
nombreArchivoSalida = sys.argv[... |
def StringToFunc(sFun_ML):
"""
Purpose:
Transforms provided string into appropriate function name for machine learning algorithm
Inputs:
sFun_ML String, provides name for the function
Return value:
fun_ML function, after transformation from stri... | The function `Estfun_ML` trains a machine learning model (e.g., Random Forest or Logistic Regression) with fairness-aware preprocessing, evaluates its performance, and returns metrics. It applies specified fairness techniques (e.g., Reweighting, DisparateImpactRemover) to the training data, trains the model, and assess... | def Estfun_ML(
sFun_ML,
dfX,
iDepth,
iRandom,
protected_attribute_name,
unprivileged_num,
privileged_num,
sFairnessMetric,
IncludeProtected,
):
"""
Purpose:
Performs a Random Forest machine learning calculation.
sFairnessMetric:
[0] DisparateImpact... |
def getLineText(self):
return self.console_line_input.text()
def setOutText(self, outputText):
self.console_text_output.setText(outputText)
def setup_scan(self):
target, state_target = QInputDialog.getText(self, "Target Network ", "Target Network To Scan")
if state_target:
re... | The code processes user commands in a command-line interface, handling tasks like displaying help menus, scanning devices, setting targets/domains, launching ARP/DNS spoofing, generating malware, and clearing outputs. It maps commands to specific functions, outputs descriptions, and executes actions based on user input... | def executeCommands(self):
commands = [
"help",
"banner",
"shortcut",
"generateMalware",
"scan",
"setTargets",
"setDomains",
"arper",
"DNSspoofer",
"clear",
"exit"
]
... |
def text2matrix(text):
matrix = []
for i in range(16):
byte = (text >> (8 * (15 - i))) & 0xFF
if i % 4 == 0:
matrix.append([byte])
else:
matrix[i // 4].append(byte)
return matrix
def add_round_key(s, k):
for i in range(4):
for j in range(4):
... | The code encrypts plaintext using a process similar to AES. It converts the text to a matrix, applies initial round key addition, performs 9 rounds of encryption with substitution and row shifts, adds a final round key, and converts the matrix back to text. | def encrypt(plaintext):
plain_state = text2matrix(plaintext)
add_round_key(plain_state, round_keys[:4])
for i in range(1, 10):
round_encrypt(plain_state, round_keys[4 * i : 4 * (i + 1)])
sub_bytes(plain_state)
shift_rows(plain_state)
add_round_key(plain_state,round_keys[40:]... |
def _read_poker_hands(self):
f = open(self.filename)
player1_hands = []
player2_hands = []
for line in f:
all_cards = line.split()
player1_hands.append(all_cards[:5])
player2_hands.append(all_cards[5:])
f.close()
return (player1_hands, player2_hands)
def _get_transformed_hand(self, hand):
for ... | The code evaluates poker hands for two players across multiple rounds, comparing their hand values to count how many times Player 1 wins. It reads hand data, transforms and calculates each player's hand strength, and increments a counter when Player 1's hand outranks Player 2's, finally reporting the total wins out of ... | def run(self):
player_hands = self._read_poker_hands()
p1_wins = 0
for i in range(self.n_hands):
player1_hand_ranks, player1_hand_suits = self._get_transformed_hand(self._get_truncated_hand(player_hands[0][i]))
player2_hand_ranks, player2_hand_suits = self._get_transformed_hand(self._get_truncated_hand(pla... |
def avg_matrix(dataset):
matrix = createzero(len(dataset[0]))
for i in range(len(dataset)):
matrix = add_matrix(matrix, dataset[i])
matrix = divide_matrix(matrix, len(dataset))
return matrix
def nilai_tengah(matrix, listt,dataset):
for i in range(len(dataset)):
temp = ((subtrac... | The code performs face recognition using Eigenfaces (PCA). It processes a dataset of images, computes eigenfaces, and matches an input image to the closest one in the dataset by calculating Euclidean distances between feature vectors. The main tasks include image resizing, mean matrix calculation, covariance matrix der... | def answer(datasets,filename):
start = time.time()
newIMG = cv2.imread(filename, 0)
newIMG = cv2.resize(newIMG, (256,256), interpolation = cv2.INTER_AREA)
count = 0
dataset = []
imagee = []
nama_folder = []
list_subfolders_with_paths = [f.path for f in os.scandir(datasets) if f.is_dir()... |
def _construct(self):
if self.task_object.state != BuildingState.BUILT:
self.target_destination = self.task_object.get_position()
if not self._is_at_target():
self._move()
self.task_object.add_worker(self)
else:
self.task_object.remove_... | The code defines a method `custom_update` that overrides a parent class's method to handle state-specific behaviors of a unit. Depending on the unit's state (`CONSTRUCTING`, `GATHERING`, or `DEPOSITING`), it triggers corresponding actions: construction, resource gathering, or resource depositing. The method ensures the... | def custom_update(self):
super().custom_update()
if self.state == UnitState.CONSTRUCTING:
self._construct()
elif self.state == UnitState.GATHERING:
self._gather()
elif self.state == UnitState.DEPOSITING:
self._deposit_resources() |
def pad(arr):
tmp = [[9] + row + [9] for row in arr]
pad_row = [9] * len(tmp[0])
return [pad_row, *tmp, pad_row]
def part1(data):
min_vals = [data[y][x] for y, x in find_minima(data)]
return sum(min_vals) + len(min_vals)
def part2(data):
minima = find_minima(data)
basins = []
for pos in ... | The main task of the code is to read input data, convert each line into a list of integers, pad the data (likely to standardize row lengths), compute results for two problem parts using `part1` and `part2` functions, then print both results. | def main():
data = pad([list(map(int, list(line.rstrip()))) for line in fileinput.input()])
print(part1(data))
print(part2(data)) |
def get_data_partition(partition_file) -> Tuple[Dict[str, str], Dict[str, List[str]]]:
"""
Reads mappings from subject ids to their partition and vice versa
:param partition_file: path to the partition file (csv with two columns: id, partition)
:return: dicts subject2partition, partition2subject
"""... | The function `load_data` loads and preprocesses datasets for tasks like personalization, humor, or mimic, returning structured data (features, labels, metadata) for train, devel, and test partitions. It checks for cached `.pkl` files, applies segmentation, normalization, and handles task-specific data loading. Paramete... | def load_data(task:str,
paths:Dict[str, str],
feature:str,
emo_dim: Optional[str],
normalize: Optional[Union[bool, StandardScaler]] = True,
win_len=200,
hop_len=100,
save=False,
segment_train=True,
... |
def fit_normalizer(task:str, feature:str, feature_idx=2) -> StandardScaler:
"""
Fits a sklearn StandardScaler based on training data
:param task: task
:param feature: feature
:param feature_idx: index in the feature csv where the features start
(typically 2, features starting after segment_id, t... | This function loads and preprocesses personalized data for a specified feature and emotion dimension, either using cached data or generating it by processing raw data. It normalizes features, segments data, and partitions it into train/devel/test sets per subject. The result is saved as a pickle file and returned as a ... | def load_personalisation_data(paths,
feature,
emo_dim,
normalize=True,
win_len=200,
hop_len=100,
save=True,
se... |
def initialize_config(self, config):
# set default parameters if not specified
self.set_default_value(config, "depth_map_type", "redwood")
self.set_default_value(config, "n_frames_per_fragment", 100)
self.set_default_value(config, "n_keyframes_per_n_frame", 5)
self.set_default_v... | The code initializes a class by loading a configuration file, validating the dataset folder structure, setting parameters like debug mode and device, and retrieving lists of RGB-D (color and depth) files from the dataset path specified in the config. It prepares the dataset for subsequent processing or analysis. | def __init__(self):
path_to_config = "./data/readrosbag.json"
with open(path_to_config) as json_file:
config = json.load(json_file)
self.initialize_config(config)
self.check_folder_structure(config['path_dataset'])
config['debug_mode'] = False
config[... |
def register_blueprints(app):
dirs = get_directory_structure(
root=join(root, 'app'),
ignore=[
'env',
'Env',
'venv',
... | The main task of the code is to create and configure a Flask application by registering blueprints, extensions, and templates, initializing login management, minifying assets, and setting up Sass compilation for static files. The function returns the fully configured Flask app instance. | def create():
app = register_blueprints( \
register_extensions( \
config( \
Flask('__main__', \
st... |
def is_startroom(game_id, room_tag):
sql = "SELECT start_room FROM games WHERE id=:game_id"
result = db.session.execute(sql, {"game_id": game_id})
start_room = result.fetchone().start_room
return True if start_room == room_tag else False
def get_current_room(game_id, user_id):
""" First look up the... | The function `can_enter` determines if a user is allowed to enter a specific room in a game by checking three conditions: whether the room is the start room, if it's the user's current room, or if the user meets any predefined conditions that allow access to that room. It returns `True` if any of these criteria are sat... | def can_enter(game_id, user_id, room_tag):
""" Check if user is allowed to enter to the particular room
"""
if is_startroom(game_id, room_tag):
return True
if room_tag == get_current_room(game_id, user_id):
return True
conditions = get_condition_results(game_id, user_id)
f... |
def can_enter(game_id, user_id, room_tag):
""" Check if user is allowed to enter to the particular room
"""
if is_startroom(game_id, room_tag):
return True
if room_tag == get_current_room(game_id, user_id):
return True
conditions = get_condition_results(game_id, user_id)
f... | The function `enter_room` allows a user to enter a game room by checking permissions, updating visit status, and retrieving room descriptions. It returns a dictionary with room details, including first-time or subsequent visit text, and possible choices based on game conditions for rendering in the game interface. | def enter_room(game_id, user_id, room_tag):
""" First check, if user is allowed to enter the room.
If user has not visited the room before, visited_rooms table is updated,
and return description is constructed based on if this is first visit or not.
Possible choices are returned as a list of description... |
def receive(conn):
return conn.recv(2048).decode(FORMAT)
def signupExe(conn, username, password):
out = signupChecker(username, password)
send(conn, out)
if out == "0":
writeFile(username, password)
def loginExe(username, password):
login = openFile("users")
for i in login:
if i[... | The main task of the code is to handle client-server interactions for a system allowing user registration, login, and file operations. It processes client commands like "Sign up," "Log in," "Add," "Show," and "Download," managing data storage, file transmission, and connection termination. Upon login, it sends data to ... | def handle_client(conn, addr):
# Server waiting loop
while True:
# Receive user's option
list = receive(conn)
list = eval(list)
if list[0] == "Sign up": # Sign up
signupExe(conn, list[1], list[2])
elif list[0] == "Log in": # Log in
out = loginExe... |
def display_welcome(self):
print ("Welcome to Rock, Paper, Scissors, Lizard, Spock")
def display_rules(self):
print('''Remember the rules: Scissors cuts Paper, Scissors decapitates Lizard Paper covers Rock, Paper disproves Spock Rock crushes Lizard, Rock crushes Scissors Lizard poisons Spock, Lizard eat... | The `run_game` method initializes and starts the game by displaying a welcome message, explaining the rules, and then executing the main gameplay loop. | def run_game(self):
self.display_welcome()
self.display_rules()
self.play_game() |
def is_inventory_open():
return(is_icon_present('image_keys/inventory_tab_key.png'))
def toggle_inventory():
return(click_on_icon('image_keys/inventory_ui_1_key.png'))
def move_mouse_to_safe_spot():
pyautogui.moveTo(80,10)
return PASS
def select_ore_hold():
return(click_on_icon('image_keys/ore_hold_... | The code automates transferring ore from an inventory to a designated hangar by locating items via image recognition, dragging them to the deposit location, and managing inventory state. It checks if the inventory is open, selects the ore hold, identifies the hangar, and repeatedly transfers ore until none remain, clos... | def transfer_inventory():
print('transferring inventory')
# move mouse to inventory slot
#invx = 26
#invy = 271
#pyautogui.moveTo(invx,invy)
#pyautogui.click(invx,invy)
if(is_inventory_open() == False):
toggle_inventory()
move_mouse_to_safe_spot()
time.sleep(5)
... |
def click_on_icon(img_filepath):
val = pyautogui.locateCenterOnScreen(img_filepath,confidence=CONFIDENCE)
if(val != None):
pyautogui.moveTo(val.x,val.y)
time.sleep(1)
pyautogui.click(val.x,val.y)
time.sleep(1)
move_mouse_to_safe_spot()
return PASS
else:
... | The main task of the code is to automate reconnecting to a game client (likely EVE Online) by launching the launcher, navigating through game windows, dragging the game window, claiming items, closing pop-ups, managing inventory, and ensuring specific UI elements are active or minimized, with delays and image recogniti... | def reconnect_client():
print('reconnecting')
#pval = click_on_icon(restart_filepath+'quit_key.png')
#if(pval == PASS):
# open the launcher window
click_on_icon(restart_filepath+'eve_launcher_key.png')
#
click_on_icon(restart_filepath+'play_now_key.png')
time.sleep(40)
click_on... |
def make_conditional_generator(self, latent_size):
# # style mapping
# self.S = Sequential()
# self.S.add(Dense(self._latent_size, input_shape=[self._latent_size]))
# self.S.add(LeakyReLU(0.2))
# for i in range(self._mapping_size-2):
# self.S.add(Dense(self._... | This code initializes a conditional GAN (Generative Adversarial Network) with configurable parameters for image generation. It sets up a generator (G), discriminator (D), latent encoder (L), style network (style_net), and synthesis generator (G_synth). The architecture uses a style-based approach with parameters contro... | def __init__(self, latent_size=64,
start_size=16, kernel_len=16,
n_filters=1024, n_classes=16, n_chan=1, num_res=10, scale_base=2,
embedding_dim=50, mapping_size=3):
#param
self._latent_size = latent_size
self._label_in_dim = emb... |
def get_umap_emedding():
global umap_embedding
umap_embedding = umap_spaces[drum_var.get()]
def generate_drum():
global waveform_and_w_spaces
waveform_and_w_spaces = synth(drum_var.get(), [slider_vars[0].get(),
slider_vars[1].get(),
... | The code defines a function `on_slider_change` that updates a global variable `umap_ratio` with a slider's value, triggers UMAP embedding generation, drum pattern creation, and waveform plotting. Its main task is to dynamically adjust UMAP parameters and regenerate visual/audio outputs in real-time as the slider is mov... | def on_slider_change(value):
global umap_ratio
umap_ratio = float(value)
get_umap_emedding()
generate_drum()
do_plot(waveform=waveform_and_w_spaces) |
def get_umap_emedding():
global umap_embedding
umap_embedding = umap_spaces[drum_var.get()]
def clear_cross():
global cross_lines
for line in cross_lines:
xy_canvas.delete(line)
def draw_cross(x, y):
global cross_lines
line1 = xy_canvas.create_line(x - cross_s... | This function maps a canvas click to a 10x10 grid, retrieves the corresponding UMAP embedding value, and uses it to generate and plot a drum sound waveform. It adjusts click coordinates to grid indices, validates the index, and triggers audio visualization if successful. | def on_canvas_click(event):
global umap_w
global umap_index
get_umap_emedding()
x = event.x
y = event.y
# Adjust the clicked coordinates to the desired range (0-99)
adjusted_x = int((x / canvas_width) * 9)
adjusted_y = int((y / canvas_height)... |
def get_umap_emedding():
global umap_embedding
umap_embedding = umap_spaces[drum_var.get()]
def generate_drum():
global waveform_and_w_spaces
waveform_and_w_spaces = synth(drum_var.get(), [slider_vars[0].get(),
slider_vars[1].get(),
... | The function updates drum parameters, retrieves UMAP embeddings, modifies global variables, generates drum sounds, and plots waveforms based on input values. | def change_snare(val, text):
# global snare_var
global drum_var
global waveform_and_w_spaces
global umap_index
global umap_w
drum_var.set(val)
get_umap_emedding()
umap_value = umap_embedding[umap_index]
umap_w=umap_value
generate_drum()
... |
def getAliasStruct(self, aliasTokens):
# Variables
aliasStruct = {}
# Loop through aliases
for alias in aliasTokens:
alias_split = alias.split(" ")
if len(alias_split) == 1: # No alias found
aliasStruct[alias] = alias
else: # Alias fou... | This function processes a SQL-like SELECT command by validating table existence, handling joins, applying filters, and outputting query results. It checks table paths, creates table objects, processes WHERE/ON clauses, and prints metadata and content based on selected attributes. | def selectCommand(self, commStruct):
# Variables
selectTokens = commStruct["select"]
fromTokens = commStruct["from"]
whereTokens = commStruct.get("where")
aliasStruct = self.getAliasStruct(fromTokens)
tablePaths = self.getTablesStruct(aliasStruct)
# Test for non-... |
def inverse_constraints(self, kernel_params_t, sn_t):
"""
Return a dict containing the original kernel parameters and signal noise, given their transformed values.
self.kernel_params_limits is used to read the limit of the parameters and self.sn_range_limits for the limits of sn
self.ker... | The main task of the code is to compute the log marginal likelihood for a Gaussian process model by calculating in-sample and (optional) out-of-sample components, perform backpropagation to update model parameters, and log intermediate values like fit, complexity, and likelihood terms during training iterations. | def closure():
optimizer.zero_grad()
kernel_params, sn = self.inverse_constraints(kernel_params_t, sn_t)
inv_k_in, k_cholesky_in = self.compute_inv_k(dist_mat=dist_mat_in, sn=sn,
... |
def create_dataloader(data, batch_size, shuffle = True, device = None, **kwargs):
ds = ExperienceDataset(data, device = device)
return DataLoader(ds, batch_size = batch_size, shuffle = shuffle, **kwargs)
def shift(t, value = 0, shift = 1, dim = -1):
zeros = (0, 0) * (-dim - 1)
return F.pad(t, (*zeros, s... | The code performs PPO training on stacked memory sequences, updating an actor-critic model. It processes batches, computes action logits/values, calculates policy loss with entropy and KL divergence penalties, applies PPO clipping, and optimizes both actor and critic networks. Rewards are adjusted by KL penalties, and ... | def learn(
self,
memories: Deque[Memory]
):
# stack all data stored in the memories
all_memories_stacked_and_padded = list(map(partial(pad_sequence_fixed, batch_first = True), zip(*memories)))
# prepare dataloader for policy phase training
dl = create_dataloader(al... |
def shift(t, value = 0, shift = 1, dim = -1):
zeros = (0, 0) * (-dim - 1)
return F.pad(t, (*zeros, shift, -shift), value = value)
def log_prob(prob, indices):
assert prob.shape[:2] == indices.shape, f'preceding shapes of prob {prob.shape[:2]} and indices {indices.shape} must match'
return log(prob.gathe... | The code trains a reinforcement learning (RL) model using human feedback (RLHF) by generating sequences with an actor-critic model, calculating rewards via a reward model, and updating the policy through stored memories. It iteratively samples prompts, predicts actions, computes rewards, and performs gradient updates e... | def train(
self,
num_episodes = 50000,
max_timesteps = 500,
update_timesteps = 5000,
max_batch_size = 16,
max_seq_len = 2048,
eos_token = None,
temperature = 1.
):
device = self.device
time = 0
memories = deque([])
for... |
def generateBoard(pieces = []):
X = 0
Y = 1
NAME = 2
board = [["." for i in range(8)] for i in range(8)]
for i in range(len(pieces)):
board[pieces[i][Y]][pieces[i][X]] = pieces[i][NAME]
return board
def king(badBoard, yPos, xPos):
#checks all spots around the king
badBoard = chec... | This function determines valid moves for a chess piece at position (y,x) on the board. It updates blackSpots or whiteSpots based on the piece type (king, queen, rook, etc.) by calling corresponding movement functions. Each piece's function calculates legal positions, modifying the respective spot board. The function re... | def pieceLogic(board, y, x, blackSpots = generateBoard(), whiteSpots = generateBoard()):
if board[y][x] == "k":
blackSpots = king(blackSpots, y, x)
elif board[y][x] == "K":
whiteSpots = king(whiteSpots, y, x)
elif board[y][x] == "q":
blackSpots = queen(board, blackSpots, y, x)
el... |
def generateBoard(pieces = []):
X = 0
Y = 1
NAME = 2
board = [["." for i in range(8)] for i in range(8)]
for i in range(len(pieces)):
board[pieces[i][Y]][pieces[i][X]] = pieces[i][NAME]
return board
def king(badBoard, yPos, xPos):
#checks all spots around the king
badBoard = chec... | The code processes a chessboard to determine if either white or black is in checkmate. It initializes attack boards for both sides, updates them based on each piece's movement rules (e.g., king, queen, rook, etc.), and checks for checkmate conditions. Finally, it prints the board and attack positions, returning the che... | def gameLogic():
board = []
for y in range(8): #map gen
board.append([x for x in input()])
#initialized and sets up white attack board and black attack board.
whiteSpots = generateBoard()
blackSpots = generateBoard()
#loops through the board and checks if a piece is there or not.
... |
def map_vectors(fname, chain, pcs, PAPS_def=False):
"""Maps the reference frames (planes) onto to VH and VL domains of an Fv structure (fname is chothia numbered pdb file
with VH as H chain and VL as L chain.
"""
# coefs to map centroids onto plane formed by PC1 and PC2
coefs = np.array([-5, 0.5, 1... | The code calculates orientation angles (HL, HC1, LC1, HC2, LC2) and the separation distance (dc) between structural domains in a given file. It maps vectors from Light (L) and Heavy (H) domains, computes unit vectors, projects them onto a plane perpendicular to the centroid vector, and determines angles using cross pro... | def find_angles(fname):
"""Calculate the orientation measures for the structure in fname"""
RADIAN = 180.0 / math.pi
# HL is the angle between the L1 and H1 vectors looking down the C vector (the centroid vector)
# Map the vectors on the Heavy and Light domains of the structure
Lpoints, Hp... |
def calc_effective_text_len(self, node):
"""
Calc the total the length of text in a child, same as
sum(len(s) for s in cur_node.stripped_strings)
"""
if node.text_len is not None:
return node.text_len
text_len = 0
for child in node.children:
... | The code's main task is to identify and score the main content of a document by calculating effective text length, prioritizing title-related elements, assigning article tag scores, and computing overall node scores to determine the primary content area. | def find_main_content(self):
self.calc_effective_text_len(self.doc)
self.set_title_parents_point(self.doc) # Give them the highest score
self.set_article_tag_point(self.doc)
self.calc_node_score(self.doc)
logger.info('Score of the main content is %s', self.article.score or 0) |
def get_favicon_url(self):
if not hasattr(self, '_favicon_url'):
fa = self.doc.find('link', rel=re.compile('icon', re.I))
favicon_path = fa.get('href', '/favicon.ico') if fa else '/favicon.ico'
self._favicon_url = urljoin(self.url, favicon_path)
return self._favicon_u... | This code initializes a class to analyze HTML content by parsing the document, extracting metadata like title and favicon, identifying main content, and calculating metrics such as image area and text length using caching for efficiency. | def __init__(self, html, url=''):
# see http://stackoverflow.com/questions/14946264/python-lru-cache-decorator-per-instance
self.calc_img_area_len = lru_cache(1024)(self.calc_img_area_len)
# self.calc_effective_text_len = lru_cache(1024)(self.calc_effective_text_len)
self.max_score = -1... |
def is_fpf_involution(adj):
"""Test whether adj defines a fixed-point free involution."""
for x, a in enumerate(adj):
if a < 0 or a >= len(adj) or x == a or adj[a] != x:
return False
return True
def connected_components(adj):
"""Calculate the number of connected components of the tri... | The function `is_sphere_triangulation` checks if a given adjacency list `adj` represents a triangulation of the 2-sphere. It verifies three conditions: the adjacency must define an fpf involution, the graph must be connected, and Euler’s formula $ V - E + F = 2 $ must hold, where $ V $, $ E $, and $ F $ are the numbers... | def is_sphere_triangulation(adj):
'''Test whether adj defines a triangulation of the 2-sphere.'''
if not is_fpf_involution(adj) or connected_components(adj) != 1:
return False
num_vert = number_of_vertices(adj)
num_face = len(adj)//3
num_edge = len(adj)//2
# verify Euler's formula for th... |
def checkGoal(self,direction,action):
Complete = False
# visited = 0
x = self.hero_[0]-1
y = self.hero_[1]-1
reward = 0
# print([x-1,y-1],self.LC_loc,'\n',isin_index([x-1,y-1],self.LC_loc))
if (self.LC_[x,y]==True):
if (self.locations_visited[x,y]==Tru... | This code defines a 'step' function in a reinforcement learning environment. It processes an action, determines a direction (random if unspecified), updates the character's position, checks for goal achievement, records reward/action history, captures the new game state, and returns the state, reward, done flag, and di... | def step(self, action, direction =-1):
self.last_reward_and_action.pop(0)
reward, done = self.checkGoal(0,action)
if direction == -1:
direction = np.random.randint(0,4)
self.moveChar(direction)
state = self.get_screen(direction)#
self.last_rewa... |
def get_clips_id():
clips = teams.find_team_by_abbreviation('lac')
clips_id = clips["id"]
return clips_id
def get_latest_game_id(clips_id):
# contains summer league and preseason games
games = game_finder(clips_id, 10).get_data_frames()[0]
latest_game_id = games['GAME_ID'].iloc[0]
return ... | The main task of the code is to retrieve and return the latest game data from a selected database (local or AWS RDS). It identifies the latest game ID using a clips ID, fetches corresponding data via the `pull_last_game_db` function, prints the result, and returns the DataFrame. The code prioritizes flexibility by allo... | def main():
# local db
db_choice = 'local'
# AWS RDS db
# db_choice = 'AWS'
clips_id = get_clips_id()
latest_game_id = get_latest_game_id(clips_id)
# pull data from db, only what you need (?)
last_game_df = pull_last_game_db(db_choice, latest_game_id)
print(last_game_df)
retur... |
def get_final_inputs_and_outputs():
input_slices, output = generate_uniform_inputs_with_output()
expanded_output = expand_output_arr(output)
return input_slices, output
def divide_input_slices(input_slices):
divided_slices = []
for slice in input_slices:
divided_slices.append(recursive_divid... | This code generates training data by creating input-output pairs. It iterates `total_samples` times, processing each to divide input slices and adjust outputs via recursive division and value normalization, returning lists of processed inputs and outputs for machine learning tasks. | def get_data():
inputs = []
outputs = []
for _ in range(total_samples):
input_slices, expanded_output = get_final_inputs_and_outputs()
inputs.append(divide_input_slices(input_slices))
outputs.append(start_arr_at_lowest_value(
recursive_divide(expanded_output, symbol_ceili... |
def clear_console():
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def line_break(size=1):
print("" * size)
def print_matrix(matrix, label="Matrix"):
print(f"{label}:")
line_break()
for row in matrix:
print(row)
def inverse(matrix):
det... | This code prompts the user to input a square matrix's size and elements, constructs the matrix, computes its inverse, and displays both the original matrix and its inverse. It includes console clearing, formatted output, and a delay before returning to the main menu. | def user_defined_matrix():
clear_console()
print("---------------------------------")
print("| Matriks dengan Input Pengguna |")
print("---------------------------------")
line_break()
while True:
print("- Masukkan ukuran matriks")
matrix_size = int(input("> Input: "))
p... |
def clear_console():
if platform.system() == "Windows":
os.system("cls")
else:
os.system("clear")
def line_break(size=1):
print("" * size)
def user_defined_matrix():
clear_console()
print("---------------------------------")
print("| Matriks dengan Input Pengguna |")
print("-... | This code provides a menu-driven interface for an inverse matrix calculator. It allows users to create their own matrix, refresh the console, or exit with confirmation. The program handles user input validation, displays options, and manages navigation between menus while maintaining a clear interface for matrix invers... | def main():
clear_console()
print("-----------------------------")
print("| Inverse Matrix Calculator |")
print("-----------------------------")
while True:
print("----------------------------------")
print("Pilih opsi yang tersedia!")
print("[1] Buat Matriks Anda Sendiri")
... |
def git_changed_recipes(git_rev, stop_rev=None, git_root=''):
"""
Get the list of files changed in a git revision and return a list of
package directories that have been modified.
git_rev: if stop_rev is not provided, this represents the changes
introduced by the given git rev. It is equi... | The code constructs a directed graph of dependencies from a directory of recipes, using build or run/test requirements to avoid cycles. It processes subdirectories, identifies recipe packages, and adds nodes/edges based on dependencies, with metadata for each package. The graph helps visualize dependency relationships ... | def construct_graph(directory, platform, bits, folders=(), deps_type='build',
git_rev=None, stop_rev=None):
'''
Construct a directed graph of dependencies from a directory of recipes
deps_type: whether to use build or run/test requirements for the graph. Avoids cycles.
values... |
def usage(script):
text = f"""VCV Rack Plugin Helper Utility
Usage: {script} <command> ...
Commands:
createplugin <slug> [plugin dir]
A directory will be created and initialized with a minimal plugin template.
If no plugin directory is given, the slug is used.
createmanifest <slug> [plugin dir]
Creates a `plug... | This code parses command-line arguments for a script that handles creating plugins, modules, or manifests. It extracts the script name, checks for valid commands ('createplugin', 'createmodule', 'createmanifest'), and executes corresponding functions. If no arguments or invalid commands are provided, it displays usage ... | def parse_args(args):
script = args.pop(0)
if len(args) == 0:
usage(script)
return
cmd = args.pop(0)
if cmd == 'createplugin':
create_plugin(*args)
elif cmd == 'createmodule':
create_module(*args)
elif cmd == 'createmanifest':
create_manifest(*args)
else:
print(f"Command not found: {cmd}") |
def calculateStringSimilarity(sourceApi, targetApis, apiVectorDict: dict, classNameVectorDict: dict):
global stringSimThreshold
targetApiSimDict = dict()
sourceApiVec = apiVectorDict[str(sourceApi[0])]
for targetApi in targetApis:
targetApiVec = apiVectorDict[str(targetApi[0])]
targetAp... | This function maps source APIs to target APIs by sequentially checking string similarity, token-related similarity, and method documentation similarity. It appends the first valid match found for each source API, using vectorized representations of APIs, classes, and method comments to compute similarities and generate... | def calculateApiMappings(sourceApis, targetApis,
apiVectorDict,
classVectorDict,
classCommentVectorDict,
methodCommentVectorDict,
methodParamReturnVectorDict
):
"""
... |
def rmdir(directory):
"""Recursively remove a directory and contents, ignoring exceptions
# Arguments:
dir: Path of directory to recursively remove
"""
try:
shutil.rmtree(directory)
except:
pass
def mkdir(directory):
"""Create a directory, ignoring exceptions
# Arguments... | The main task of the code is to prepare the Omniglot dataset by unzipping raw files, organizing background and evaluation sets, and processing individual alphabets. It cleans previous data, extracts zipped files, and structures images for machine learning tasks like few-shot learning. | def prepare_omniglot(prepare=False):
if prepare:
# Clean up previous extraction
rmdir(prepared_omniglot_location)
mkdir(prepared_omniglot_location)
# Unzip dataset
for root, _, files in os.walk(raw_omniglot_location):
for f in files:
if f in datas... |
def Station():
Stations[0]["rent"]=250
Stations[1]["rent"]=250
Stations[2]["rent"]=250
Stations[3]["rent"]=250
if Players[Player_no]["position"]==5:
Station_no=0
if Players[Player_no]["position"]==15:
Station_no=1
if Players[Player_no]["position"]==25:
Station_no=2
... | This function simulates drawing a Chance card in a board game, applying effects like moving players, adjusting balances, handling property transactions, and triggering special events. It randomly selects a card from a predefined list, executes its action (e.g., paying fines, advancing spaces, collecting bonuses), and i... | def Chance():
Chance_cards=[{"text":"Another player files a court case against you. Choose which player and pay them 500."},
{"text":"Advance to GO."},
{"text":"Advance to the nearest station space. If unowned, you may buy it from the bank. If owned, pay the owner twice the rent... |
def fight(x, y, area):
global your_dragon
global dl
#0 = xsmall 1 = xbig 2 = ysmall 3 = y big
if x>=area[0] and x<=area[1] and y>=area[2] and y<=area[3]:
battlechance = random.randrange(0, 20)
if battlechance == 1:
Battle()
def Battle():
global Yellow_boss1
glob... | The code defines a game loop for a Pygame-based RPG, handling player movement across multiple maps (1-8), rendering environments, managing inventory interactions, and transitioning between areas. It processes keyboard inputs for navigation, triggers battles, updates game states, and displays items, quests, and characte... | def gameloop():
global Yellow_boss1
global Yellow_boss1_fight
global knife_count
global knife_giver
global knife_get
global mission1_part_1
global mission1
global mission1_dragons
area = [0, 0, 0, 0]
global dl
items = False
IDstart = False
moneystart = False
glob... |
def Chance():
Chance_cards=[{"text":"Another player files a court case against you. Choose which player and pay them 500."},
{"text":"Advance to GO."},
{"text":"Advance to the nearest station space. If unowned, you may buy it from the bank. If owned, pay the owner twice the rent... | The function checks a player's position on a board game and triggers specific actions: drawing Chance or Community Chest cards, paying fines, entering jail, or handling utilities/stations/properties based on the player's location. | def Position_check():
if Players[Player_no]["jail"]==False:
if Players[Player_no]["position"]==7 or Players[Player_no]["position"]==22 or Players[Player_no]["position"]==36:
Chance()
elif Players[Player_no]["position"]==2 or Players[Player_no]["position"]==17 or Players[Play... |
def clusterPolylinesByCut(polylines, print_progress=False):
for i in range(len(polylines)):
line_cluster_idx_lists = getCutLineClusterIdxLists(polylines, i)
print(line_cluster_idx_lists)
print(np.array(line_cluster_idx_lists).shape)
if i > 0:
exit()
exit()
return... | The function `clusterPolylines` clusters a list of polylines using different strategies based on the `mode` parameter. It delegates to three methods: `clusterPolylinesByCut`, `clusterPolylinesByMerge`, or `clusterPolylinesByAngle`, depending on whether `mode` is 'cut', 'merge', or 'angle'. However, the code contains an... | def clusterPolylines(polylines, print_progress=False):
assert mode in mode_list
if mode == 'cut':
return clusterPolylinesByCut(polylines, print_progress)
if mode == 'merge':
return clusterPolylinesByMerge(polylines, print_progress)
if mode == 'angle':
return clusterPolylinesByAn... |
def updateTransform(self, polyline):
self.resetTransform()
self.updateViewBox(polyline)
self.origin_translate = np.array([
-(self.x_min + self.x_max) / 2.0, -(self.y_min + self.y_max) / 2.0
],
dtype=float)
self.scale = min(
... | This function updates an image based on a polyline and specified rendering mode. It handles composite modes by splitting and processing sub-modes recursively. Depending on the 'render_mode' parameter, it delegates to either 'updateImageBySource' or 'updateImageByCluster' methods, applying line/text styling parameters. ... | def updateImage(self,
polyline,
render_mode='source',
line_width=1,
text_color=[0, 0, 255],
text_size=1,
text_line_width=1,
save_into_list=False):
self.updateTransform(poly... |
def reset_random_seeds():
# https://stackoverflow.com/questions/32419510/how-to-get-reproducible-results-in-keras
os.environ["PYTHONHASHSEED"] = str(1)
tf.random.set_seed(1)
np.random.seed(1)
random.seed(1)
def load_data(kmer_counts_file):
"""
Loads kmer counts from an input file, returns th... | The main task of the code is to perform dimensionality reduction on k-mer count data using specified methods (e.g., autoencoders, neighbors-based techniques). It loads k-mer counts, skips processing if only one row exists, applies selected methods to generate embeddings, merges results across methods, and saves the com... | def main(kmer_counts_file, out_folder, selected_methods, n_neighbors_setting, autoencoder_epochs_count):
reset_random_seeds()
df, seq_names = load_data(kmer_counts_file)
df_row_count = df.shape[0]
if df_row_count == 1:
sys.stderr.write(
"Skipping the dimensionality reduction of kmer... |
def train_test_split(self, inlinks_fn=None, outlinks_fn=None):
'''
Description:
Given a specified test ratio, this splits the inlink and outlink file into training and test files
Input parameters:
- inlink_file: Compressed inlink file
- outlink_file: Compress... | This code initializes a model for processing data with inlinks/outlinks, splits data into train/val/test sets, loads ground truth, computes initial IDF biases, iteratively trains the model, evaluates performance, updates IDF dynamically, and saves the final model. It handles data splitting, iterative training with earl... | def __init__(self, groundtruth_fn, inlink_file, outlink_file, data_dir,
train_ratio, val_ratio, test_ratio, skip_splits,
threshold, iteration, updated_model_fn):
'''
Description:
This contains the default values passed into the model
Input parameters:
... |
def _find_parent_table(self, table: Optional[str] = "") -> str:
"""
Find the parent table from a given table name
:param table: table name
:return: table: the parent table name(if it is not partitioned table, it is just the input
"""
if self.part_tables is not None:
... | This function traverses a database query execution plan recursively, mapping table aliases, tracking possible columns, and handling CTEs/subqueries. It processes scan nodes to link aliases to tables, extracts output/columns, resolves filters/index conditions, and manages CTE definitions. For subqueries and unions, it r... | def _traverse_plan(self, plan: Optional[dict] = None) -> None:
"""
Traversing the plan using recursion and go into Plans if it is present
:param plan: the given execution plan
:return: None
"""
if plan["Node Type"] in [
"Seq Scan",
"Parallel Seq Sc... |
def _handle_union(self, sql_ast: expressions = None) -> None:
if (
isinstance(sql_ast, exp.Union)
or isinstance(sql_ast, exp.Except)
or isinstance(sql_ast, exp.Intersect)
):
self._handle_union(sql_ast=sql_ast.left)
self._handle_union(sql_ast=sq... | This method processes SQL AST to resolve data lineage by identifying tables, columns, and their relationships. It handles unions, resolves projections, tracks column origins, and manages subquery columns, ensuring accurate lineage tracking with table prefixes and deduplication. | def _run_lineage(
self, sql_ast: expressions = None, subquery_flag: bool = False
) -> None:
"""
Run the lineage after all the cte and subquery are resolved
:param sql_ast: the ast for the sql
:param subquery_flag: check if it is a subquery
"""
if not subquery_... |
def _resolve_table(self, part_ast: expressions = None) -> List:
"""
Find the tables in the given ast
:param part_ast: the ast to find the table
"""
temp_table_list = []
for cond in from_join_exp:
# Resolve FROM and JOIN
for table_sql in part_ast.fi... | This function processes subqueries within a Common Table Expression (CTE) by resolving shared conditions (e.g., WHERE, GROUP BY) and extracting column/table mappings. It identifies subquery tables, resolves column aliases, handles aggregate stars (*), and builds dictionaries for CTE projections. The result includes lis... | def _sub_shared_col_conds_cte(
self, sql_ast: expressions = None
) -> Tuple[List, List, List, str]:
"""
Run the subquery inside the cte first that is with the shared conditions(WHERE, GROUP BY, etc)
:param sql_ast: the ast for the cte
"""
all_cte_sub_table = []
... |
def _find_cte_col(self) -> dict:
"""
Find the column names for each cte since it does not show in the execution plan
:param sql: the sql that needs to be analyzed
:return: the dict with table name as keys and list of columns as child
"""
cte_col_dict = {}
for cte ... | This code initializes an SQL query analyzer by parsing input SQL, setting up data structures to track columns, tables, CTEs, and subqueries, and resolving column mappings. It processes query plans, identifies schema elements, and prepares for further analysis or execution by organizing parsed components into internal d... | def __init__(
self,
plan: Optional[dict] = None,
sql: Optional[str] = "",
columns: Optional[List] = None,
conn: Any = None,
part_tables: Optional[dict] = None,
search_schema: Optional[str] = "",
) -> None:
self.split_regex = re.compile(r"[^a-zA-Z0-9._]... |
def _resolve_table(self, part_ast: expressions = None) -> List:
"""
Find the tables in the given ast
:param part_ast: the ast to find the table
"""
temp_table_list = []
for cond in from_join_exp:
# Resolve FROM and JOIN
for table_sql in part_ast.fi... | This function processes subqueries in an SQL AST by resolving shared conditions (WHERE, GROUP BY), extracting subquery tables, handling projections, updating CTE mappings with aliases, and executing lineage analysis for each subquery. It iterates through conditions, resolves table structures, maps projections to CTEs, ... | def _sub_shared_col_conds(self, sql_ast: expressions = None) -> None:
"""
After the cte are resolved, run the subquery ast that is with the shared conditions(WHERE, GROUP BY, etc)
:param sql_ast: the ast without the cte
"""
# add in more conditions, including FROM/JOIN
fo... |
def _sub_shared_col_conds_cte(
self, sql_ast: expressions = None
) -> Tuple[List, List, List, str]:
"""
Run the subquery inside the cte first that is with the shared conditions(WHERE, GROUP BY, etc)
:param sql_ast: the ast for the cte
"""
all_cte_sub_table = []
... | This method processes Common Table Expressions (CTEs) in SQL to map lineage information. It resolves CTE tables, handles shared conditions, manages set operations (union/except/intersect), and builds dictionaries tracking dependencies between CTEs and their source tables/columns, enabling data flow analysis across SQL ... | def _run_cte_lineage(self):
"""
Run the lineage information for all the cte
"""
for cte in self.sql_ast.find_all(exp.CTE):
(
all_cte_sub_table,
all_cte_sub_cols,
potential_cte_sub_table,
sub_name
) = ... |
def parse_one_sql(sql: Optional[str] = "") -> expressions:
"""
The function to try different dialects for parsing the SQL
:param sql: the input sql
:return: the parsed sql AST
"""
dialects = ["postgres", "oracle", "mysql", ""]
parsed_sql = None
for dialect in dialects:
try:
... | This code initializes a SQL analyzer by parsing input SQL into an AST, processing CTEs, tracking column/table lineage, and preparing for further query analysis by removing CTEs and identifying shared columns. It sets up data structures to map tables, columns, and subqueries for downstream operations like lineage tracin... | def __init__(
self,
sql: Optional[str] = "",
dialect: str = "postgres",
input_table_dict: Optional[dict] = None,
):
self.column_dict = {}
self.table_alias_dict = {}
self.cte_table_dict = {}
self.cte_dict = {}
self.unnest_dict = {}
self.... |
def get_user_choice():
#user_choice = input("Enter rock, paper or scissors: ").lower()
user_choice = get_prediction ()
#if user_choice in options:
return user_choice
def get_computer_choice():
computer_choice = random.choice(options)
#print(f"\nYou chose {user_choice}, and the computer chose {co... | The main task of the code is to simulate a game round where a user and computer each select an option (e.g., rock, paper, scissors), then determine the winner based on their choices. It orchestrates user input retrieval, computer choice generation, and winner evaluation to complete a single game iteration. | def play():
user_choice = get_user_choice()
computer_choice = get_computer_choice()
get_winner(computer_choice, user_choice) |
def draw_on_display(data):
global data_write
global test
draw.rectangle((0, 0, width, height), outline=0, fill=0)
draw.text((5, 10), "> "+data, font=font, fill=255)
rotated_image = image.rotate(180) # Rotate the image by 180 degrees
disp.image(rotated_image)
disp.display()
def take_off(heig... | The function directs a drone to follow a predefined 2D path by adjusting its orientation and movement direction based on relative coordinate changes between consecutive path points, taking off at a specified height and landing after completing the route. | def follow_path(path,height,cell_length):
draw_on_display("Drone Starting!!!") # x + > forward
take_off(height) # y + > go right
# 0 -> x z + > go down
prev_cord = path[0] # 1 -> y ... |
def remove_null_bytes(data):
return data.replace('\x00', '')
def draw_on_display(data):
global data_write
global test
draw.rectangle((0, 0, width, height), outline=0, fill=0)
draw.text((5, 10), "> "+data, font=font, fill=255)
rotated_image = image.rotate(180) # Rotate the image by 180 degrees
... | This code processes received data by clearing interrupt flags, decoding payload, checking for a 'correct' keyword, parsing JSON path data, and initiating path-following if valid. It then resets the receiver for continued operation. | def on_rx_done(self):
self.clear_irq_flags(RxDone=1)
self.set_modem_config_1()
payload = self.read_payload(nocheck=True)
data =remove_null_bytes(bytearray(payload).decode('utf-8', 'ignore').strip())
if 'correct' in data: # Correct data is received and path is ready
d... |
def initialize_directories():
current_dir = Path(__file__).parent
root_dir = current_dir.parent # Set the root directory one level up
log_dir = root_dir / 'logs'
config_dir = root_dir / 'configs'
return log_dir, config_dir
def restart_litellm_proxy(log_file_path, config_file_path):
# Start the ... | The code defines a Streamlit web interface to manage the LiteLLM Proxy, enabling users to start/restart the proxy, monitor logs, configure models, poll for updates, terminate processes, free ports, and test the proxy. It centralizes control over LiteLLM operations, including logging, process management, and dynamic con... | def show_litellm_proxy_page():
global scheduler
log_dir, config_dir = initialize_directories()
log_file_path = log_dir / 'litellmlog'
config_file_path = config_dir / 'config.yaml'
st.title('OPENAI API Proxy')
st.text("Start Litellm With the button below to convert Ollama traffic to Openai Traff... |
def _avg_qos(reqs):
return _avg([qos(r) for r in reqs])
def _avg_tries(reqs):
return _avg([r.tries for r in reqs])
def _avg_latency(reqs):
return _avg([r.latency() for r in reqs])
def _avg_queue_t(reqs, q_name):
return _avg([r.queue_t[q_name] for r in reqs])
def _avg_dep_t(reqs):
return _avg([r.depe... | This function prints a formatted row of statistics for a given label and list of requests, including the count of requests, average QoS, average tries, latency, queue times for 'q1' and 'q2', and dependency time. The output uses fixed-width fields and decimal precision for structured display. | def _stats_row(label, reqs):
print("%9s %5d %6.2f %6.1f %6.1f %6.1f %6.1f %6.1f" %
(label, len(reqs),
_avg_qos(reqs),
_avg_tries(reqs),
_avg_latency(reqs),
_avg_queue_t(reqs, 'q1'),
_avg_queue_t(reqs, 'q2'),
_avg_dep_t(reqs))) |
def _avg_qos(reqs):
return _avg([qos(r) for r in reqs])
def _avg_tries(reqs):
return _avg([r.tries for r in reqs])
def _avg_latency(reqs):
return _avg([r.latency() for r in reqs])
def _avg_queue_t(reqs, q_name):
return _avg([r.queue_t[q_name] for r in reqs])
def _avg_dep_t(reqs):
return _avg([r.depe... | The function `stats` calculates and returns average metrics for a list of requests, including count, QoS, number of tries, latency, queue times (q1/q2), and dependency times. If no requests are provided, it defaults to a predefined `completed` list. The output is a dictionary with these computed values. | def stats(reqs=None):
if not reqs:
reqs = completed
return {
'count': len(reqs),
'qos': _avg_qos(reqs),
'tries': _avg_tries(reqs),
'latency': _avg_latency(reqs),
'q1': _avg_queue_t(reqs, 'q1'),
'q2': _avg_queue_t(reqs, 'q2'),
'dependency': _avg_de... |
def _stats_header():
print('-' * 57)
print("%9s %5s %6s %6s %6s %6s %6s %6s" %
('type', 'count', 'qos', 'tries', 'time', 'q1', 'q2', 'dep'))
print('-' * 57)
def _stats_row(label, reqs):
print("%9s %5d %6.2f %6.1f %6.1f %6.1f %6.1f %6.1f" %
(label, len(reqs),
_avg_qos(reqs)... | This function generates and prints statistical reports on completed requests, categorizing them by type (e.g., rejected, cached) and calculating cache hit ratios. It first outputs overall stats, then breaks down metrics by request types. If TTL is active, it further analyzes cache performance by calculating hit rates a... | def report():
# Leaving this as an inefficient bunch of loops until we know what we want to report
_stats_header()
_stats_row('all', completed)
for t in ['rejected', 'cached', 'live', 'fallback']:
_stats_row(t, _by_type(completed, t))
print()
if Server.ttl > 0:
reqs = [r for r... |
def configure():
pass
def complete(workers):
return [w for w in workers if w.is_done()]
def not_complete(workers):
return [w for w in workers if not w.is_done()]
def respond(r, response_type=None):
if not r.responded:
r.response_type = response_type if response_type else response(r)
r.en... | The main task of the code is to simulate a task processing system with two stages (p1 and p2), handling completions, retries, and abandonment decisions. It processes tasks from queues, manages worker states, updates caches, and enqueues/rejects new requests based on system limits and conditions, iterating until a speci... | def main(ticks):
global p1, p2
while clock.ts < ticks:
clock.tick()
configure()
# Process existing p2 work (ie, check on workers waiting on dependency)
#
p2_complete = complete(p2)
p2 = not_complete(p2)
for w in p2_complete:
w.r.tries += 1
... |
def getClickedCell(data, event):
row=event.y//50
col=event.x//50
return [row,col]
def clickUserBoard(data, row, col):
if data["noOfUserShips"]==5:
return
for coordinate in data["tempShip"]:
if coordinate==[row,col]:
return
data["tempShip"].append([row,col])
if len... | The function handles mouse clicks in a turn-based game. If no winner exists, it determines the clicked cell and triggers user or computer actions based on the 'board' parameter. For the user's board, it updates their state; for the computer's board, it initiates a game turn only if the user has placed all 5 ships. The ... | def mousePressed(data, event, board):
if data["winner"]==None:
row,col=getClickedCell(data, event)
if board=="user":
clickUserBoard(data,row,col)
if board=="comp" and data["noOfUserShips"]==5:
runGameTurn(data,row,col)
return |
def makeModel(data):
data["numberOfRows"]=10
data["numberOfCols"]=10
data["boardSize"]=500
data["cellSize"]=50
data["numberOfShips"]=5
data["userBoard"]=emptyGrid(data["numberOfRows"],data["numberOfCols"])
data["computerBoard"]=emptyGrid(data["numberOfRows"],data["numberOfCols"])
da... | The main task of the code is to create a two-player ship placement and guessing game using Tkinter. It initializes two boards (user and computer), allows the user to place ships on their board via clicks, and lets the computer make guesses on the user's board. Event handlers manage keyboard/mouse interactions, while th... | def runSimulation(w, h):
data = { }
makeModel(data)
root = Tk()
root.resizable(width=False, height=False) # prevents resizing window
# We need two canvases - one for the user, one for the computer
Label(root, text = "USER BOARD - click cells to place ships on your board.").pack()
userCanva... |
def getSubject(self, verb):
# first, we check if there is a direct subject, i.e. a dependent
# labelled as nominal subject (active or passive)
for child in verb.children:
if 'nsubj' in child.dep_:
return child
# if there is no direct subject, we check if their... | The code initializes an object to process a verb and associated nouns, identifying a subject from the input. It uses coreference and alternative name data to determine the full subject and any additional subject details if a subject is found. If no subject is detected, it defaults to None. The task involves natural lan... | def __init__(self, verb, nouns, doc, coref):
self.nouns, self.doc, self.coref = nouns, doc, coref
self.alt_names, self.all_alts = driverAltNames(), allAltNames()
self.subj = self.getSubject(verb)
# only run below lines if a subject has been found
if self.subj:
self.fu... |
def penalty(self):
p_objs = [m for m in self.rc_objs if 'penalty' in m['message'].lower()]
if len(p_objs) == 0: return None
# print(p_objs)
data_objs = []
for pm in p_objs:
msg, msg_obj = pm['message'], {}
d = self.__driverInMsg(msg)
if d: msg_... | The code aggregates messages from various event types (penalties, off-track, flags, incidents, etc.) into a list, prioritizing certain message types. It returns the list if any messages are found, otherwise returns None after checking all possible sources, including a random chance to include additional messages. | def messages(self):
msgs = []
# ce, sc = self.carEvents(), self.safetyCar()
ps, ot = self.penalty(), self.offTrack()
# if ce: [msgs.append(c) for c in ce]
# if sc: [msgs.append(s) for s in sc]
if ps: [msgs.append(p) for p in ps]
if ot: [msgs.append(o) for o in ot]... |
def defineModel(self, return_type=''):
model = AutoModelForSeq2SeqLM.from_pretrained(self.mn)
peft_config = LoraConfig(
task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8,
lora_alpha=8, lora_dropout=0.1, target_modules=['q_proj', 'v_proj']
)
peft_model = g... | This code fine-tunes a pre-trained model on a tokenized dataset using specified training arguments. It initializes a Trainer, executes training, saves the fine-tuned model to a designated directory, and stores model parameters. The process involves defining the model, preparing data, configuring training settings, and ... | def finetuneModel(self):
model, tokenizer = self.defineModel()
ds = self.getTokenizedDataset()
tr_args = self.trainingArguments()
trainer = Trainer(model=model, train_dataset=ds,
tokenizer=tokenizer, args=tr_args)
fn = './FinetunedModels/' + self.mn.repl... |
def _test_connectivity(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
self.save_progress("Checking connectivity with Cyware CTIX Platform")
# REST endpoint for retrieving all Threat Intel sources from CTIX
endpoint = "/source/?Expires={}&AccessID={}&Sig... | The code defines a method `handle_action` that dispatches actions based on the `action_id` retrieved from the instance. Depending on the action identifier, it executes corresponding methods like `_test_connectivity`, `_handle_lookup_domain`, etc., and returns their results. The primary task is to route incoming actions... | def handle_action(self, param):
ret_val = phantom.APP_SUCCESS
# Get the action that we are supposed to execute for this App Run
action_id = self.get_action_identifier()
if action_id == phantom.ACTION_ID_TEST_ASSET_CONNECTIVITY:
ret_val = self._test_connectivity(param)
... |
def get_model_dir(self):
cfg = self.cfg
return os.path.join(cfg['root_folder'], cfg['model_subfolder'], cfg['model_name'])
def get_train_val_dataset(self, return_file_names=False):
cfg = self.cfg
x_train_fnames, x_val_fnames, y_train_fnames, y_val_fnames = \
data_io.get_data... | This code trains a machine learning model, either from scratch or via transfer learning, using specified datasets. It handles checkpoint resumption, user input for resuming training, and saves model weights while logging training progress with TensorBoard. The function configures training parameters, datasets, callback... | def train_model(self, transfer=False, src_model_yaml=''):
cfg = self.cfg
monitor = cfg['monitor']
epochs = cfg['epochs']
model_dir = self.get_model_dir()
if not os.path.isdir(model_dir):
os.makedirs(model_dir, exist_ok=True)
# get training data
train... |
def get_cfg_from_yaml(self, yaml_name):
# get common paths
with open(self.get_yaml_path_from_name(COMMON_YAML)) as f:
common_cfg = yaml.safe_load(f)
with open(self.get_yaml_path_from_name(yaml_name)) as f:
cfg = yaml.safe_load(f)
# merge these two configs
... | The code tests a model using configurations from a YAML file. It prepares input data, retrieves image and answer files, sets output directories, and generates predictions, optionally overlaying answers. The function orchestrates data loading, configuration parsing, and result storage based on specified parameters. | def test_model(self, test_yaml):
# Prepare inputs
test_cfg = self.get_cfg_from_yaml(test_yaml)
file_dir = test_cfg['test_img_dir']
file_type = test_cfg['test_data']['file_type']
filter_patter = test_cfg['test_data']['filter_patter']
chunk_size = test_cfg['chunk_size']
... |
def verify_dlg_sdk_proj_env_directory(path):
"""
Drive letter is not allowed to be project environment.
Script checks in parent of 'path': a drive letter like C: doesn't have a parent.
"""
if(path.find(":\\")+2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\").
return False
else:
return ... | The main task of the code is to validate the provided SDK path and KEIL5 project environment, ensuring they meet requirements. If valid, it either cleans the project environment (if "clean" is specified) or sets up the KEIL5 project using the provided SDK path, handling edge cases like invalid directories, drive-letter... | def run_application(sdk_path):
"""
Verify if the sdkpath is valid
Verify if the KEIL5 uvprojx file is valid
If both are verified then setup KEIL5 project environment
"""
global DLG_SDK_ROOT_DIRECTORY, DLG_WORKING_PROJECT_DIRECTORY, CLEAN_PROJ_ENV
#os.system('cls') #works only in windows for linux it is 'clear'
... |
def isEmpty(self):
return self.head == None and self.tail == None
def setHead(self, node):
isEmpty = self.isEmpty()
if isEmpty:
self.head = node
self.tail = node
return
self.insertBefore(self.head , node)
def insertAfter(self, node, nodeToInsert):
... | The main task of the code is to add a given node to the end of a linked list. If the list is empty, it sets the node as both the head and tail. Otherwise, it inserts the node after the current tail, ensuring the tail pointer remains at the last node. This maintains the linked list structure by updating pointers appropr... | def setTail(self, node):
isEmpty = self.isEmpty()
if isEmpty:
self.setHead(node)
return
self.insertAfter(self.tail , node) |
def setHead(self, node):
isEmpty = self.isEmpty()
if isEmpty:
self.head = node
self.tail = node
return
self.insertBefore(self.head , node)
def insertBefore(self, node, nodeToInsert):
# Write your code here.
if nodeToInsert == self.head and node... | The code inserts a node at a specified position in a linked list. If the position is 1, it sets the node as the new head. Otherwise, it traverses to the target position, then inserts the node before the current node or appends it as the tail if the position exceeds the list length. | def insertAtPosition(self, position, nodeToInsert):
# Write your code here.
if position == 1:
self.setHead(nodeToInsert)
return
currentPosition = 1
currentNode = self.head
while currentNode is not None and currentPosition != position:
currentNo... |
def remove_crypto_pair(self, value):
env_vars = self.get_config_vars()
cryptos = json.loads(env_vars[CRYPTOS])
cryptos.remove(value)
env_vars[CRYPTOS] = cryptos
return self.get_confirmation_config(CRYPTOS, True)
def add_crypto_pair(self, value):
env_vars = self.get_confi... | The code updates a cryptocurrency pair by first removing the existing 'fromValue' pair and then adding the new 'toValue' pair. It subsequently retrieves and returns a confirmation configuration related to cryptocurrency settings, ensuring the update is properly validated or acknowledged. | def update_crypto_pair(self, fromValue, toValue):
self.remove_crypto_pair(fromValue)
self.add_crypto_pair(toValue)
return self.get_confirmation_config(CRYPTOS, True) |
def print_board(board, replace_old=False):
if replace_old: # Replace old board printout (update it in place)
sys.stdout.write("\033[F"*(NUM_ROWS + 1))
print()
for row in reversed(range(NUM_ROWS)):
print('|', end='')
for col in range(NUM_COLUMNS):
t... | The code implements a two-player game loop where Player 2 uses Monte Carlo Tree Search (MCTS) for strategic moves, while Player 1 acts randomly. It initializes a game board, alternates turns, updates the board state, and checks for terminal conditions (win/draw). The game displays progress if enabled, determines the wi... | def run_game(display=True):
# Board Setup
board = np.zeros((NUM_ROWS, NUM_COLUMNS), dtype=int)
last_move = None
player = 1
# Example starting state
# board = np.array([[1,2,2,2,1,1,2],
# [0,2,1,1,2,1,0],
# [0,2,2,2,1,2,0],
# ... |
def get_matches(img1, img2, visualize=False, lowe_ratio=0.6):
# Find the keypoints and descriptors with SIFT
sift = cv2.SIFT_create()
kp1, des1 = sift.detectAndCompute(img1, None)
kp2, des2 = sift.detectAndCompute(img2, None)
# FLANN parameters
FLANN_INDEX_KDTREE = 1
index_params = dict(alg... | This function uses RANSAC to robustly estimate the homography between two images by iteratively sampling matches, computing transformations, and selecting the homography with the highest consensus. It then stitches the images using the optimal homography to create a seamless panorama, saving the result as "Stitched_wit... | def stitch_with_RANSAC(img1, img2):
matches = get_matches(img1,img2)
best_score = 0
best_H = None
for _ in range(500):
score = 0
sample = random.sample(matches, 4)
points = [pair[1] for pair in sample]
points_dest = [pair[0] for pair in sample]
H = homography(poin... |
def _update_height(self, node: TreeNode) -> None:
"""
Update the height value for the input node assuming height of child node have already been updated
:param node: the input node on which we want to update teh height
:return: the updated height of the input node
"""
if ... | This function inserts a value into a self-balancing binary search tree (AVL tree), updating node heights and performing rotations (left/right or double rotations) to maintain balance. It handles four cases based on the balance factor: left-left, left-right, right-right, and right-left, ensuring the tree remains height-... | def _insert(self, node: TreeNode, value: object) -> TreeNode:
"""
Detailed implementation of node insertion followed by self balancing when necessary
Average complexity O(log N), worst case O(log N)
:param node: root of the subtree on which to insert the input value
:param value:... |
def _get_smallest_node(self, node: TreeNode) -> TreeNode or None:
"""
Traverse down from input node and return the smallest node in the subtree
:param node: the root of the subtree in which we want to find the smallest node
:return: the smallest node in the subtree
"""
if... | This code deletes a node with the specified value from an AVL tree, maintaining balance through rotations. It first follows BST deletion logic, then updates node height, checks balance, and applies left/right rotations to resolve imbalances, ensuring O(log N) complexity. | def _delete(self, node: TreeNode, value: object) -> TreeNode:
"""
Detailed implementation of node deletion followed by self balancing when necessary
Average complexity O(log N), worst case O(log N)
:param node: root of the subtree on which to delete the input value
:param value: ... |
def get_hostname():
return get_config_value('Hostname', socket.gethostname())
def get_records_from_config(hostname):
factory = DnsRecordFactory()
with open(get_relative_file('config.json')) as json_data:
config = json.load(json_data)
for bearer in config['bearers']:
factory.set_bearer(... | The main task of the code is to retrieve configuration records based on the hostname, fetch current data associated with those records, and update the records accordingly. The function `main()` orchestrates these steps by first obtaining the hostname, then retrieving relevant records, fetching current data, and finally... | def main():
hostname = get_hostname()
records = get_records_from_config(hostname)
fetch_current_data(records)
update_records(records) |
def _validate_msgs(self, msgs: List[MailMessage]) -> List[dict]:
month = date.today().strftime("%B").upper()
parsed_msgs = []
for msg in msgs:
if msg.from_ not in self.ALLOWED_SENDERS or msg.subject.upper() != self.ALLOWED_SUBJECT.format(month):
continue
p... | The code processes email attachments by validating messages, parsing Excel files into DataFrames, converting them to processed files with "_procesado" in their names, and returning updated message objects with new attachments. | def execute(self, msgs: List[MailMessage]) -> List[dict]:
parsed_msgs = self._validate_msgs(msgs)
if not parsed_msgs:
logger.info("No padron excel files found in messages")
return
for parsed_msg in parsed_msgs:
new_attachments = []
for attachment i... |
def get_log_path(self):
r = self.run_wrapper("DOESNOTEXIST")
full_path = r.json()["file"]
if not full_path:
log.error("Unable to find full path")
path = full_path[: full_path.index("/vendor/")] + "/storage/logs/laravel.log"
r = self.run_wrapper(path)
if r.s... | The main task of the code is to exploit a vulnerability by clearing logs, injecting a payload, converting it to a Phar file, and executing it. If an error occurs, it retries the payload injection and execution steps. Finally, it ensures logs are cleared regardless of success or failure. | def exploit(self):
if not self.log_path:
self.log_path = self.get_log_path()
try:
self.clear_logs()
self.put_payload()
self.convert_to_phar()
self.run_phar()
except:
self.clear_logs()
self.put_payload(True)
... |
def __check_deletion_of_config(self):
try:
if self.original_arguments.delete_schedule:
pass
if self.is_configured():
list_of_configs = self.__read_yaml()
list_of_configs.pop(self.original_arguments.delete_schedule)
if lis... | This method processes configuration settings by updating the configuration status, checking for deletions and listing all configurations, reading YAML data if configured, applying configuration changes if enabled, and returning the collected configurations from the file. | def process(self, to_configure):
self.arguments.configure = to_configure
self.__check_deletion_of_config()
self.__check_list_all_configs()
if self.is_configured():
try:
self.settings = self.__read_yaml()[self.original_arguments.file_alias]
except ... |
def sort_suffixes(text):
return _sort_suffixes(text, 0, len(text))
def check_suffix_array(suffix_array):
from itertools import izip, islice
pairs = izip(suffix_array, islice(suffix_array, 1, None))
for (prev_text, prev_offset, _), (text, offset, shared) in pairs:
prefix = shared... | The main task of the code is to test the correctness of combining and verifying sorted suffixes of the string "abba". It sorts the suffixes, combines three copies of them, and checks if the resulting suffix array meets expected properties, likely validating the combine function's behavior with repeated suffix lists. | def test_same_string(self):
suffixes = sort_suffixes("abba")
check_suffix_array(combine(suffixes, suffixes, suffixes)) |
def sort_suffixes(text):
return _sort_suffixes(text, 0, len(text))
def combine(*suffix_arrays):
if not suffix_arrays:
return list()
if len(suffix_arrays) == 1:
return suffix_arrays[0]
cut = len(suffix_arrays) / 2
left = combine(*suffix_arrays[:cut])
right = combine(*suffix_arra... | This code tests the correctness of suffix array sorting and combination functions by generating random byte sequences of varying sizes (1, 10, 100, 1000, 10000), sorting their suffixes separately, combining results, and validating the output using check_suffix_array. | def test_random_strings(self):
import random
for size in (1, 10, 100, 1000, 10000):
text = [random.randint(0, 255) for _ in xrange(size)]
left = sort_suffixes(text)
text = [random.randint(0, 255) for _ in xrange(size)]
right = sor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.