dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _get_ready_for_file_operation(self):
'''Handles the necessary checks prior to any file operation.'''
self._confirm_current_working_directory()
self._confirm_dataset_directory()
def resume_version(self, dir:str=None, dev_status:bool=True):
'''Resume the latest version.'''
# Ensure the directories and v... | The function saves an object with version control by appending the current version number to the object's name, serializing it using pickle, and incrementing the version afterward. It ensures directory readiness, retrieves the current version, constructs the file path, writes the object to disk, and updates the version... | def save_version_pk(self, dir:str=None, obj_name:str=None, object=None, dev_status:bool=True):
'''Save the object and assign the version.'''
print(f"Save object ({obj_name}).")
# Check directories.
self._get_ready_for_file_operation()
# Load the current version and get the dev folder.
dev_status, v... |
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def getOutputForHandwritten(video):
# segmentedLines = []
audioKeyFrames, keyframes = keyFrame(video)
print(audioKeyFrames)
# for i in keyframes:
# cv2.imshow('frame', i)
# ... | The main task of this code is to handle image/video uploads via a web request. It checks for a file in the request, validates its type, saves it as 'video.mp4' in the upload folder, processes it using either `getOutputForHandwritten` or `getOutputForPpt` based on a form option, and returns 'uploaded' on success or erro... | def upload_image2():
print("BYE")
if 'file' not in request.files:
# flash('No file part')
print('lll')
return 'aaaa'
return redirect(request.url)
print('ffff')
file = request.files['file']
if file.filename == '':
print('rrrr')
# flash('No video selecte... |
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def getOutputForHandwritten(video):
# segmentedLines = []
audioKeyFrames, keyframes = keyFrame(video)
# print(audioKeyFrames)
# print(audioKeyFrames)
# for i in keyframes:
# ... | The function handles video uploads, processes them based on user-selected options (handwritten or PPT), generates outputs like notes and transcripts, zips the results, and returns the zip file for download. It ensures valid file uploads, saves the file, triggers processing, and sends the compiled output as an attachmen... | def upload_image2():
if 'file' not in request.files:
return redirect(request.url)
file = request.files['file']
if file.filename == '':
return redirect(request.url)
if file and allowed_file(file.filename):
filename = secure_filename("video.mp4")
# print(filename)
... |
def print_update(attempting_all, counters, no_journeys, start_time):
if attempting_all:
print(
"\nAttempting to plot journey number {} of {} ({}% done)".format(
str(counters["n_journeys_attempted"] + 1),
str(no_journeys),
str(round(100 * counters["... | The main task of this code is to process cycling journey files, generate visualizations (plots and video frames), and update counters/status variables. It filters valid journeys, handles errors, sets color schemes, applies map configurations, and saves frames for video creation while tracking progress through counters ... | def make_all_other_frames(
journey_files,
attempting_all,
no_journeys,
start_time,
maps_dict,
runstr,
text_vars,
timestr,
journey_plots,
counters,
map_configs,
):
counters["journey_year"] = counters["first_year"]
plotter_inputs = {
"n_concurrent": n_concurren... |
def EggTurnerGUI():
eggTurner = Toplevel(root)
eggTurner.title("Ovipets Credit Farmer")
width = 620
window = width / 2
CalculateDimensions(width, 600, eggTurner)
root.withdraw()
# Adding friends;
descriptionLabel = Label(eggTurner, text="Add friends and Favorite them to turn their eggs... | The code creates a main menu GUI for an automation tool, welcoming the user and displaying buttons for various bots (Auto Egg Turner, Feeder, Breeder, Hatcher, etc.). It initializes a Toplevel window, sets dimensions, hides the root window, and organizes buttons in a grid layout. Some buttons trigger other GUIs, while ... | def MainMenuGUI(username):
mainMenu = Toplevel(root)
CalculateDimensions(450, 300, mainMenu)
root.withdraw()
mainMenu.title("Ovipets Automation Tool")
#Calling the bot;
#EggTurnerBotStart()
#Frames;
frame = tkinter.Frame(mainMenu)
frame.pack()
# Frame title;
botsFrame = La... |
def copy_tree_in(base, dest, callback=None, attributes=None, chunk_size=1<<20):
"""Copy recursively files and directories under real 'base' path into
virtual 'dest' directory table, 'chunk_size' bytes at a time, calling callback function if provided
and preserving date and times if desired."""
for root... | The main task of the code is to copy files and directories from 'src_list' into a virtual 'dest' directory, handling wildcards by expanding them, preserving file attributes if specified, and transferring data in chunks. It uses a callback function for progress notification, creates target files with preallocated cluste... | def copy_in(src_list, dest, callback=None, attributes=None, chunk_size=1<<20):
"""Copies files and directories in 'src_list' to virtual 'dest' directory
table, 'chunk_size' bytes at a time, calling callback function if provided
and preserving date and times if desired."""
for it in src_list:
# I... |
def copy_tree_out(base, dest, callback=None, attributes=None, chunk_size=1<<20):
"""Copy recursively files and directories under virtual 'base' Dirtable into
real 'dest' directory, 'chunk_size' bytes at a time, calling callback function if provided
and preserving date and times if desired."""
for root, ... | This function copies files and directories from a virtual source (src_list) to a real destination directory (dest), handling wildcards by expanding matching items, preserving attributes if specified, and using a callback for progress. It processes each item by checking if it's a file or directory, recursively copying d... | def copy_out(base, src_list, dest, callback=None, attributes=None, chunk_size=1<<20):
"""Copies files and directories in virtual 'src_list' to real 'dest' directory
'chunk_size' bytes at a time, calling callback function if provided
and preserving date and times if desired."""
for it in src_list:
... |
def transition(self, W, h, U, x, hyp_b):
W_otimes_h = mob_mat_mul_d(W, h, self.d_ball)
U_otimes_x = mob_mat_mul_d(U, x, self.d_ball)
Wh_plus_Ux = mob_add(W_otimes_h, U_otimes_x)
return mob_add(Wh_plus_Ux, hyp_b)
def log_map_zero(y):
diff = project_hyp_vec(y + EPS)
norm_diff = th... | This code performs a forward pass in a neural network that updates the hidden state using hyperbolic geometry operations. It computes gates (z, r) via sigmoid-activated transitions, applies pointwise products and hyperbolic additions, and updates the hidden state (new_h) by combining the input (hyp_x) with the previous... | def forward(self, hyp_x, hidden):
z = self.transition(self.w_z, hidden, self.u_z, hyp_x, self.b_z)
z = th.sigmoid(log_map_zero(z))
r = self.transition(self.w_r, hidden, self.u_r, hyp_x, self.b_r)
r = th.sigmoid(log_map_zero(r))
r_point_h = mob_pointwise_prod(hidden, r)
... |
def transition(self, W, h, U, x, hyp_b):
W_otimes_h = mob_mat_mul_d(W, h, self.d_ball)
U_otimes_x = mob_mat_mul_d(U, x, self.d_ball)
Wh_plus_Ux = mob_add(W_otimes_h, U_otimes_x)
return mob_add(Wh_plus_Ux, hyp_b)
def log_map_zero(y):
diff = project_hyp_vec(y + EPS)
norm_diff = to... | The code computes a new hidden state in hyperbolic space using gated transitions (z, r) and hyperbolic operations (log_map_zero, mob_add, mob_pointwise_prod), implementing a hyperbolic recurrent unit that combines input-hidden interactions with non-linear gating mechanisms. | def forward(self, hyp_x, hidden):
z = self.transition(self.w_z, hidden, self.u_z, hyp_x, self.b_z)
z = torch.sigmoid(log_map_zero(z))
r = self.transition(self.w_r, hidden, self.u_r, hyp_x, self.b_r)
r = torch.sigmoid(log_map_zero(r))
r_point_h = mob_pointwise_prod(hidden, r)
... |
def set_global_video_info(link):
if not network_available():
print('\nRequest timeout! Please check your network and try again...!!')
sys.exit()
if is_valid_url(link):
global video, author, title, thumbnail, views, stream, stream_resolutions, maxres
link = is_valid_url(link)... | The code downloads a video stream based on the chosen resolution/format, validating the stream's availability. It merges video and audio using specific ITAGs for different qualities (e.g., 360p, 720p, 4K), handling formats like MP4/WebM. If 'mp3' is chosen, it converts the video to MP3. It checks for valid streams and ... | def download_stream(link, chosen_stream):
if set_global_video_info(link):
print_short_info(chosen_stream)
allowed_streams = get_allowed_streams(link)
if chosen_stream in allowed_streams:
if chosen_stream in ['360', '360p']:
download_progressive(stream, 18, title, ... |
def show_video_info(link):
if set_global_video_info(link):
table = []
found = False
for res in stream_resolutions.keys():
if found or (res not in ['mp3'] and stream.filter(res=res)) or (res == 'mp3' and stream.get_by_itag(140)):
found = True
if re... | The main task of the code is to create a CLI tool for downloading YouTube videos with customizable settings, such as specifying download streams, folders, and managing configurations. It parses command-line arguments to handle video URLs, stream selections, configuration updates, and utility functions like showing vide... | def main():
parser = argparse.ArgumentParser(description=f'pytubePP (Pytube Post Processor) v{version} - A Simple CLI Tool to Download Your Favorite YouTube Videos Effortlessly!')
parser.add_argument('url', nargs='?', default=None, help='url of the youtube video')
parser.add_argument('-df', '--download-fold... |
def log_string(out_str):
LOG_FOUT.write(out_str+'\n')
LOG_FOUT.flush()
print(out_str)
def get_current_lr(epoch):
lr = BASE_LEARNING_RATE
for i, lr_decay_epoch in enumerate(LR_DECAY_STEPS):
if epoch >= lr_decay_epoch:
lr *= LR_DECAY_RATES[i]
return lr
def train_one_epoch(globa... | The main task of the code is to train a machine learning model over multiple epochs, logging training progress, evaluating model performance periodically, and saving checkpoints that include model states, optimizer parameters, and loss values. The function handles both standard and DataParallel models, ensuring compati... | def train():
global EPOCH_CNT
global_step = 0
loss = 0
for epoch in range(0, MAX_EPOCH):
EPOCH_CNT = epoch
log_string('\n**** EPOCH %03d, STEP %d ****' % (epoch, global_step))
log_string('Current learning rate: %f' % (get_current_lr(epoch)))
log_string('Current BN decay m... |
def back_get_users_registrations(user_id):
replies = google_get_all_records(WOORKBOOK_NAME, REPLY_SHEET_NAME)
user_registrations = [reply for reply in replies if reply.get("User_ID")==user_id and reply.get("Reply")=="register"]
return user_registrations
def google_get_all_records(workbook_name, sheet_name):... | The function retrieves user-specific events from a Google sheet, filters them based on the user's registrations, and further narrows down to events requiring an alarm by checking their timing. It returns a list of relevant alarm-triggered events for the user. | def back_alarm_event(message):
user_id = message.user_id
user_registrations = back_get_users_registrations(user_id)
events = google_get_all_records(WOORKBOOK_NAME, EVENTS_SHEET_NAME)
user_events = [event for event in events if event.get("Event_Id") in [reg.get("Event_Id") for reg in user_registrations]]... |
def change_zero(dataset):
dataset['target'].replace({0: -1}, inplace=True)
def start_svm(scaled_features):
parameters = list()
for i in range(0, len(column_name)):
parameters.append(0)
return gradient_descent(parameters, scaled_features)
def test(scaled_features, parameters):
scaled_features... | The code loads and preprocesses a heart disease dataset by normalizing selected features, splits it into training and test sets, trains an SVM model using the training data, evaluates the model's accuracy on the test set, and prints the accuracy percentage. | def main():
dataset = pandas.read_csv("heart.csv")
dataset = dataset.sample(frac=1).reset_index(drop=True)
change_zero(dataset)
dataset = dataset[
['target', 'cp', 'chol', 'thalach', 'oldpeak'
, 'thal']]
dataset[dataset.columns[1:]] = (dataset[dataset.columns[1:]] - dataset[datas... |
def get_download_mode(self):
if self.bdownloadModePlaylist.isChecked():
self.update_json("mode", "playlist")
elif self.bdownloadModeVideo.isChecked():
self.update_json("mode", "video")
self.set_download_mode()
def get_json(self, key, default):
try:
re... | This code handles the download process by initializing a worker thread with parameters like download mode, URL, and output settings. It disables buttons during the task, connects signals to update progress, and manages thread lifecycle to execute the download asynchronously. | def download(self):
"""Triggered when the download button is pressed."""
self.get_download_mode()
mode = self.get_json("mode", "")
if not mode:
logging.error("Download mode not found.")
self.downloadStatusLog.add_message(
"Download mode not recogni... |
def normalise(x):
return x/np.linalg.norm(x)
def get_tf_idf_vec(query):
query = process_string(query)
cnt_matrix_query = loaded_cnt_vct.transform([query])
cnt_matrix_query = csr_matrix.transpose(cnt_matrix_query)
result = loaded_tfidf_new_matrix * cnt_matrix_query
result... | The code ranks professors based on weighted criteria (TF-IDF, activity, slope, h-index, institution) by normalizing vectors, scaling weights, combining scores, and returning sorted results with document IDs and scores. | def query_subject(user_input):
#parameters
params = ['tfidf', 'active', 'slope', 'hindex', 'insti']
ranks={}
for param in params:
ranks[param]={}
#set weight factors
ranks['tfidf']['wt'] = user_input['tfidf_score']
ranks['active']['wt'] = user_input['... |
def download_files(bucket_name):
try:
# Creating only one session and one client
session = create_session()
client = session.client("s3")
files_to_download = get_bucket_files_array(bucket_name)
# The client is shared between threads
func = partial(download_o... | The code handles downloading files from an S3 bucket via POST requests. If 'file_name' is 'all', it downloads all files from the specified bucket. Otherwise, it downloads a single file, creates a directory, and saves the file locally. It returns JSON responses for success/failure and catches exceptions to return error ... | def download_bucket_file(request):
if request.method == "POST":
try:
if request.POST.get('file_name') == "all":
response = download_files(request.POST.get('bucket_name'))
if response:
return JsonResponse({ "status": "success", "message": "Fi... |
def load(self):
#
# If the build set file ends with .cfg the user has passed to the
# buildset builder a configuration so we just return it.
#
if self.bset.endswith('.cfg'):
configs = [self.bset]
else:
exbset = self.macros.expand(self.bset)
... | The main task of this code is to build a set of configurations (`.bset`/`.cfg` files) by recursively processing dependencies, executing package builds, installing outputs, cleaning up, and generating email reports with build status, logs, and timing. It handles error reporting, macro expansion, and conditional executio... | def build(self, deps = None, nesting_count = 0, mail = None):
build_error = False
nesting_count += 1
if mail:
mail['output'].clear()
log.trace('_bset: %s: make' % (self.bset))
log.notice('Build Set: %s' % (self.bset))
mail_subject = '%s on %s' % (self.bse... |
def load_data(file_path):
"""
Load JSON data from a file.
Args:
file_path (str): Path to the JSON file.
Returns:
dict: Loaded JSON data.
"""
with open(file_path, 'r', encoding="utf-8") as json_file:
return json.load(json_file)
def process_data(data, multipliers):
""... | The main task of the code is to process sentiment data by loading raw JSON data, applying multipliers, calculating mean values, saving the processed data to a JSON file, and exporting sentiment means to a CSV file. The function orchestrates data loading, transformation, storage, and output in a structured workflow. | def main():
"""
Main function to process sentiment data.
Reads raw sentiment data from a JSON file, applies multipliers, calculates mean,
saves the processed data to a JSON file, and writes sentiment means to a CSV file.
"""
# Load raw data
data = load_data(INPUT_FILE)
# Process the da... |
def filled(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return False
return True
def field_with_fewest_possible_candidates(board):
count = 10
x = 0
y = 0
for i in range(9):
for j in range(9):
if board[i][j] == 0:
... | This function solves a Sudoku-like puzzle using backtracking. It selects the cell with the fewest possible candidates, randomly tests values, and recursively fills the board. If a valid configuration is found, it returns True; otherwise, it backtracks by resetting the cell and continues searching until all possibilitie... | def generate_board(board):
if filled(board):
return True
x, y = field_with_fewest_possible_candidates(board)
list_of_candidates = candidates(board, x, y)
while list_of_candidates:
board[y][x] = list_of_candidates[random.randint(0, len(list_of_candidates) - 1)]
list_of_candidates... |
def training_step(self, images, targets, batch_idx) -> torch.Tensor:
loss, loss_p, loss_loc = self.step_common(images, targets, log_prefix="training")
return loss
def validation_step(self, images, targets, batch_idx):
return self.step_common(images, targets, log_prefix="validation")
def validati... | This code trains a neural network model using specified data loaders, configuring loss functions based on hyperparameters. It performs multi-epoch training with validation intervals, logs metrics via TensorBoard, and saves checkpoints periodically. The model alternates between training and evaluation modes, computes lo... | def fit(
self,
train_dataloader: DataLoader = None,
validation_dataloader: DataLoader = None,
test_dataloader: DataLoader = None,
):
assert train_dataloader is not None
num_training_steps = len(train_dataloader)
num_validation_steps = len(validation_dataloader... |
def init_board():
return [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def is_full(board):
result = True
for y in range(0, 3):
for x in range(0, 3):
if board[x][y] == 0:
result = False
break
return result
def print_board(board):
for y in range(0, 3):
l... | The code implements a two-player or computer vs player game on a board, alternating turns to make moves. It checks for a win or tie after each move, displays the board state, and announces the result. The loop continues until the game ends, handling human input or computer-generated moves, and switches turns between pl... | def main():
board = init_board()
won = 0
turn = 1
computer_player = True
while (won == 0) and (is_full(board) is False):
print_board(board)
print_line()
if (turn == 1) or ((turn == 2) and (computer_player is False)):
x, y = input_player_move(turn)
else:
... |
def check_win(self, player):
# TODO: Check win
#check all win cases
if self.check_row_win(player):
return True
elif self.check_col_win(player):
return True
elif self.check_diag_win(player):
return True
return False
def check_tie(self):... | This code implements the Minimax algorithm with Alpha-Beta pruning to determine the optimal move for a player in a Tic-Tac-Toe game. It evaluates game states recursively, prioritizing moves that maximize the current player's advantage ("O") or minimize the opponent's ("X"), while pruning non-optimal branches to improve... | def minimax_alpha_beta(self, player, depth, alpha, beta):
opt_row = -1
opt_col = -1
# base cases
if self.check_win("O"):
return (10, None, None)
if self.check_tie():
return (0, None, None)
if self.check_win("X"):
return (-10, None, Non... |
def check_win(self, player):
# TODO: Check win
#check all win cases
if self.check_row_win(player):
return True
elif self.check_col_win(player):
return True
elif self.check_diag_win(player):
return True
return False
def check_tie(self):... | This code implements the minimax algorithm for a Tic-Tac-Toe game, determining the optimal move for a player ("O" or "X") by recursively evaluating all possible future game states. It returns the best score and corresponding board coordinates for the current player, prioritizing winning moves for "O" and minimizing los... | def minimax(self, player, depth):
opt_row = -1
opt_col = -1
#base cases
if self.check_win("O"):
return (10, None, None)
if self.check_tie():
return (0, None, None)
if self.check_win("X"):
return (-10, None, None)
if depth == 0:... |
def print_instructions(self):
# TODO: Print the instructions to the game
#print welcome message
print("Welcome to TicTacToe! The first player to get 3 in a row wins. X will start!")
def print_board(self):
# TODO: Print the board
#print empty board with row and col numbers
... | The main task of the code is to control a tic-tac-toe game loop, alternating turns between players "X" and "O", checking for win/tie conditions after each move, and displaying results until the game ends. It handles player input, updates the board, and enforces game rules like winning checks and turn switching. | def play_game(self):
# TODO: Play game
#main game control
gameOver = False
player = "X"
self.print_instructions()
self.print_board()
while gameOver is False:
self.take_turn(player, 100)
self.print_board()
if self.check_win(play... |
def calculate_distances_average(cities,distances):
distance_avg = 0
"""
Since we have a symetric and square matrix of distances
First: we sumarize every column
Second: we divide by the total number of rows - 1
Third: we divide again by the total number of rows - 1
"""
for city in cities... | The main task of the code is to evolve an optimal team schedule or arrangement using a genetic algorithm. It iterates through generations, performing selection, crossover, and adaptive mutation based on population diversity. The fitness function evaluates genome quality, tracking the best solution. The algorithm adapts... | def run_evolution(fixture, distances, cities, dates,population, generation_limit, teams, population_size):
distances_avg = calculate_distances_average(cities, distances)
best_value = 0
for i in range(generation_limit):
# SELECCION
selected_population = selection_population_function(popula... |
def calculate_distances_average(cities,distances):
distance_avg = 0
"""
Since we have a symetric and square matrix of distances
First: we sumarize every column
Second: we divide by the total number of rows - 1
Third: we divide again by the total number of rows - 1
"""
for city in cities... | The code implements a genetic algorithm to evolve optimal schedules for sports fixtures, using selection, crossover, and mutation operations. It tracks the best solution's fitness across generations, visualizes progress with a dynamic graph, and exports results to a CSV file. The algorithm iterates up to a specified ge... | def run_evolution_with_graph(fixture,distances,cities, dates,population, generation_limit, teams, population_size):
distances_avg = calculate_distances_average(cities, distances)
fig = plt.figure()
fig.suptitle('Poblacion:'+str(population_size)+'\n'+'Generaciones:'+str(generation_limit))
x,y,z = [],[],[... |
def get_country_pop(name):
replace = {'US':'United States',
'Korea, South': 'South Korea'}
if name in replace:
country = CountryInfo(replace[name])
else:
country = CountryInfo(name)
return country.population()
def get_data_country(name,what,start_days=START_DAYS):
if (... | The main task of the code is to fit an SIR (Susceptible-Infected-Recovered) epidemiological model to country-specific infected data, estimate model parameters (transmission rate and recovery rate), and compute predictions with error margins. It retrieves population data, interpolates to find a starting point for fittin... | def get_model_sir(country):
# intial parameters
N = get_country_pop(country)
alpha = R0_SIR*BETA/N
p0 = [alpha,BETA]
lbound = [0,0]
ubound = [1,1]
print(('initial:'+'%12.4e '*len(p0))%tuple(p0))
# get all data
x,y = get_data_country(country,'Infected',start_days=START_DAYS)
# D... |
def get_country_pop(name):
replace = {'US':'United States',
'Korea, South': 'South Korea'}
if name in replace:
country = CountryInfo(replace[name])
else:
country = CountryInfo(name)
return country.population()
def get_data_country(name,what,start_days=START_DAYS):
if (... | This code fits an SIRX epidemiological model to country-specific infected data, estimating parameters (alpha, BETA, K, K0) via curve fitting. It identifies the day when infections reach a threshold, prepares initial conditions, and performs nonlinear regression with bounds. The function returns model predictions, param... | def get_model_sirx(x,y,country):
#initial parameters
N = get_country_pop(country)
alpha = R0_SIRX*BETA/N
p0 = [alpha,BETA,K,K0]
lbound = [0,0,0,0]
ubound = [0.5,0.5,0.5,0.5]
print(('initial:'+'%12.4e '*len(p0))%tuple(p0))
# get all data
x,y = get_data_country(country,'Infected',star... |
def test_rectangle_area():
print("test_rectangle_area")
result = rectangle_area(3, 4)
print("Result 1 should be 12:", result)
result = rectangle_area(4, 3)
print("Result 2 should be 12:", result)
result = rectangle_area(3, 4.5)
print("Result 3 should be 13.5:", result)
result = rectangl... | The main task of the code is to execute a series of test functions for calculating areas of geometric shapes (rectangle, triangle, and house surface) and print a completion message. It runs `test_rectangle_area()`, `test_triangle_area()`, and `test_house_surface_area()` to validate computations, then signals test compl... | def main():
test_rectangle_area()
test_triangle_area()
test_house_surface_area()
print("end of tests \n")
userinputs() |
def superuser_exists(self):
"""Check if a superuser has been set up."""
return 'superuser' in self.users
def create_superuser(self, username, password):
"""Initiate the superuser creation process if no superuser exists."""
if not self.superuser_exists():
self.create_user(user... | The code's main task is to manage user authentication and access control in a system called FilOS. It checks for an existing superuser, creates one if absent, and enters a loop offering login or user creation. On login, it validates credentials and stores user info; on user creation, it enforces password matching. The ... | def run(self):
if not self.superuser_exists():
print("No superuser found. Setting up now.")
superuser_password = getpass.getpass("Enter superuser password: ")
self.create_superuser('superuser', superuser_password)
while True:
print("\nWelcome to FilOS!")
... |
def read_tags(words_dir, nested_dict):
# files = [os.path.join(words_dir, fi) for fi in os.listdir(words_dir)]
# features_matrix = np.zeros((len(files), 3000))
loc = os.getenv('BASE_ROOT_PATH') + '/tags_with_alias.xlsx'
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
end_row = sheet.n... | The main task of the code is to process job description data and tags to generate matrices for analysis. It loads stopwords, reads job descriptions and tags, builds a word occurrence matrix (matrix_1), computes distance-based (matrix_2) and scoring matrices (matrix_3), and saves results like unrecognized words, column ... | def main():
# here i declare a dictionary of words that occur very often but are not stored in the dictionary
non_recognized_words = {}
nested_dict = {}
if not os.path.isfile(os.getenv('BASE_ROOT_PATH') + 'stopwords.pkl'):
stop = stopwords.words('english')
punctuations = list(string.pu... |
def read_tags(words_dir, nested_dict):
# files = [os.path.join(words_dir, fi) for fi in os.listdir(words_dir)]
# features_matrix = np.zeros((len(files), 3000))
loc = os.getenv('BASE_ROOT_PATH') + '/tags_with_alias.xlsx'
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
end_row = sheet.nrows
docID ... | The main task of the code is to process job description data by reading tags and sentences, constructing keyword-sentence mappings, and serializing structured data (words_dictionary, sentence_dictionary, keyword_to_sentence_dict) into pickle files for later use. It prepares data for analysis by extracting and storing r... | def main():
# this input word will be taken from the front end
nested_dict = {}
doc_id, tags = read_tags('tags', nested_dict)
words= read_jd('premium_sentences', nested_dict)
print(nested_dict)
input_word = 'industry experience, people management experience'
words_dictionary, word_set = read_words('premium_ta... |
def delete_all_entities(self):
self.recursive_delete_child_entites(entity_id='$ROOT')
def delete_all_component_types(self):
resp = self.iottwinmaker_client.list_component_types(workspaceId=self.workspace_id)
component_type_summaries = resp['componentTypeSummaries']
details_map = {} # de... | The main task of the code is to check if a specified IoT TwinMaker workspace exists. If it does, the code deletes all entities, component types, and scenes within that workspace. If the workspace does not exist, the function exits silently without performing any deletions. | def delete_all_content(self):
try:
self.iottwinmaker_client.get_workspace(workspaceId=self.workspace_id)
except self.iottwinmaker_client.exceptions.ResourceNotFoundException as e:
return
self.delete_all_entities()
self.delete_all_component_types()
self.del... |
def frame_to_state( self , frame ):
# === Necessary Imports === #
import numpy as np
# === Process the Frame === #
processed = frame.convert( 'L' ).resize( ( 80 , 64 ) )
img_arr = np.asarray( processed )
self.processedImage = img_arr
img_arr = img_ar... | The code processes a frame into a state, selects an action based on the state, logs training history, propagates rewards when the history reaches a specified length, and returns the selected action. It supports debugging by printing the action and reward information. | def act(self, frame):
# === Convert Frame to State (VFA with State Aggregation) === #
state = self.frame_to_state(frame)
# === Select Action Given the State === #
action_idx = self.select_action(state)
# === If Training, Update History === #
if self.is_training:
... |
def initialise_board():
"""
Creates a 9 element board of blank tiles (represented by .)
Returns
_________
board : list
1D list for empty board
"""
# Initialise board as list of 9 empty tiles
board = np.array(9 * ['.']).reshape(3, 3)
return board
def display_board(board):
"""... | The main task of the code is to run a game loop where players take turns entering row and column positions on a board. It validates moves, updates the board, checks for a win or draw after each turn, and terminates the game when a player wins or the game ends in a draw. The loop continues until the game concludes, disp... | def play_game():
"""
Calls functions 1 to 7 and loops to play a game until the end or a player wins
"""
# Initialises and displays empty starting board and loop counter i
board = initialise_board()
display_board(board)
draw = check_draw(board)
# While the game is not drawn
while not... |
def help():
# script for running model and what camera port to use
print('python classify.py <path_to_model.eim> <Camera port ID, only required when more than 1 camera is present>')
def get_webcams():
# searches for available webcams through port 1 - 4
port_ids = []
port = 0
camera = cv2.VideoCa... | The code performs real-time pill detection using a machine learning model from a webcam feed. It initializes the model, captures video, processes frames for bounding boxes, and returns the detected pill's label if present. | def classify(argv):
global bbox_counter
global max_label
try:
opts, args = getopt.getopt(argv, "h", ["--help"])
except getopt.GetoptError:
help()
sys.exit(2)
for opt, arg in opts:
if opt in ('-h', '--help'):
help()
sys.exit()
# Path to mo... |
def get_all_subject_areas(self):
""" Gets all subject areas from majors.txt file """
majors_txt_file_path = 'GraphicalResourceForEnrollmentGuidance/scraping/majors.txt'
with open(majors_txt_file_path, 'r') as file:
contents = file.read()
self.subject_area_list = contents.... | The code scrapes UCLA Registrar data by iterating through subject areas, using Selenium to extract class details, processing each class to generate RegistrarData objects, and storing them in a dictionary. It saves the processed data into a pickle file for later use. | def scrapeNewData(self):
""" Scrapes UCLA Registrar data """
self.subject_area_list = []
self.STATUS_ERROR = 1
self.STATUS_PROCEED = 0
# temp list
self.class_id_list = []
self.regitsrar_data_objects_dict = {}
self.get_all_subject_areas()
o... |
def coords(pos):
"""
Return a tuple of integer coordinates as keys for the MapObj dict/map.
This is necessary because the MapObj uses a dictionary to store each
attribute.
* pos can be a full point tuple, or just (x, y)
* use floor() to avoid imprecise float issues
"""
x = math.floor(pos... | The main task of the code is to update a spatial map by incorporating new observed points from a point cloud file. It initializes or updates density, canopy, and ground values for each coordinate, ensuring density increments and updating canopy/ground heights based on point elevation. After processing all points, it sm... | def update_spatial(self):
"""
Expand, correct, or maintain map with a new observed point.
Initialize density and filtered_density to 1.
Increment density but do not increment filtered_density - that is done
in function update_colors
"""
# Fill out the spatial info in th... |
def _check_input(fname, ending='.ply'):
"""Checks that the file exists and has the right ending"""
if not os.path.isfile(fname):
raise FileNotFoundError('Cannot read points from a nonexistent file')
if not fname.endswith(ending):
raise ValueError('Tried to read file type {}, expected {}.'.fo... | The main task of the code is to combine multiple Pix4D point cloud files (PLY format) into a unified point cloud by applying coordinate offsets. It corrects each file's XYZ coordinates relative to a reference origin, aligning them as one continuous dataset. The function yields adjusted points, handling the first file's... | def _read_pix4d_ply_parts(fname_list: List[str]) -> Iterator:
"""Yield points from a list of Pix4D ply files as if they were one file.
Pix4D usually exports point clouds in parts, with an xyz offset for the
origin. This means that we can yield the points from each, correcting
for the offset in the ori... |
def init():
global oDate
global pumpkinFile
global hStoreName
global iStorename
try:
pumpkinFile = open(r'pumpkinData\pumpkin.dat','r')
except IOError:
print("File error. Program terminated")
exit(0)
oDate = datetime.datetime.today().strftime('%m/%d/%Y')
cLctr = ... | The main task of the code is to process records, calculate subtotals for store costs when a control break (store name change) occurs, and output results. It initializes variables, iterates through records, checks for store name changes, computes totals using `calcs()`, outputs data, and finalizes processing with `closi... | def main():
global hStoreName
iRec, iStoreName, hStoreName = init()
while iRec !="":
if hStoreName != iStoreName: #check for control break
majorSubtotals(MjStoreCost, hStoreName, cLctr)
MjQuantity, MjStoreCost, cStoreCost = calcs(iRec)
output(iRec,cStoreCost,cLctr)
... |
def read_args():
parser = argparse.ArgumentParser()
parser.add_argument("--img-width", type=int, default=IMG_WIDTH)
parser.add_argument("--img-height", type=int, default=IMG_HEIGHT)
parser.add_argument("--bgcolor", type=str, default="white")
parser.add_argument("--figures", type=str, default="")
... | The main task of the code is to generate multiple images based on specified parameters (width, height, background color) and drawing instructions. It creates `args.count` images, applies drawing operations, saves them sequentially with unique filenames in the designated directory, and outputs confirmation of the genera... | def main():
args = read_args()
paths = []
for i in range(args.count):
img = create_img(args.img_width, args.img_height, args.bgcolor)
img = draw(img, args)
path = save_image(img, i, args)
paths.append(path)
print(f"generated {len(paths)} images in {args.save_path}") |
def read_args():
"""
Parses command-line arguments.
"""
ts = dt.now().strftime("%Y%m%d%H%M%S")
parser = argparse.ArgumentParser(
description="Train a model on a images dataset (single-label)",
)
parser.add_argument("--model-path", type=str, default=f"k{ts}.pth")
parser.add_arg... | The main task of the code is to train a machine learning model using command-line arguments, log training progress and parameters, measure training duration, and output the model's best accuracy and saved path. It initializes logging, executes the training process, and records results in a structured format. | def main():
"""
Somewhere we have to start. Let's start here.
"""
# read cli options
args = read_args()
setup_logging(args)
logging.info("the train is departing right now...")
for k, v in vars(args).items():
logging.info(f"{k}={v}")
# train
tm_start = time.time()
a... |
def _is_page_changed(self, current_last_entry, max_entry):
new_current_last_entry, _ = self._fetch_current_entry()
return new_current_last_entry != current_last_entry
def _fetch_current_entry(self):
try:
browser = self.browser
self.click_feedback_button_if_exist()
... | The main task of the code is to fetch data from a paginated web page by navigating through pages, handling dynamic content updates, and collecting entries into lists. It uses a browser instance to access a target URL, adds a cookie to bypass feedback prompts, iterates through pages by clicking "next" buttons, and waits... | def fetch_data(self):
target_url = self.target_url
browser = self.browser
browser.get(target_url)
browser.add_cookie({"name": "skipFeedback", "value": "1"})
current_last_entry = max_entry = None
fetched_data = {}
WebDriverWait(browser, 20).until(
lambd... |
def rasa_server_button_color(self):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex(('localhost', 5002))
if result == 0:
self.ui.rasa_server.setStyleSheet("background-color: green")
else:
self.ui.rasa_server.setStyleSheet("backgro... | This method updates UI elements by setting button colors for Rasa and action servers, maintaining UI activity, and conditionally updating a graph if the interaction UI is enabled, returning True upon completion. | def compute(self):
self.rasa_server_button_color()
self.action_server_button_color()
self.interaction.button_colors()
self.rasaDialog.action_server_button_color()
self.keepUiActive()
#self.restartChatbot()
if self.interaction.interactionUI == True:
sel... |
def writeToFile(self,id,situation):
self.AGMinit()
try:
src = self.worldModel
person_attributes = src.getNode(id).attributes
attributes = {}
attributes['imGender'] = person_attributes['imGender']
attributes['imSituation'] = situation
... | This code handles agent activation based on received parameters, managing UI interactions, state transitions, and communication with a chatbot. It processes specific actions like requesting permissions or attention, updating internal states, and triggering UI visibility changes or external API calls to manage conversat... | def AGMCommonBehavior_activateAgent(self, prs):
print("------------------------parameters recieved------------------------")
ret = bool()
self.action = prs['action'].value
if not self.ui_lock:
if prs['action'].value != 'none':
if self.interact... |
def get_tv_dates(elem: etree._Element) -> Tuple[datetime, datetime]:
"""Get the date the security was first admitted to the relevant
trading value and, if available, the date the security was removed
from the relevant trading venue.
Time should be reported in UTC, so where a date does not specify a
... | The function processes security data to categorize and track securities based on attributes like maturity, nominal amount, and interest rate type. It updates a tracker dictionary by counting delisted, duplicate, matured, and zero-nominal securities, while aggregating benchmark data for floating-rate instruments and cat... | def parse_security(s, tracker: dict, libors: Tuple[dict] = benchmark_data.libors,
non_libors: dict = benchmark_data.non_libors,
assess_date: datetime = TODAY_UTC) -> None:
_, term_date = get_tv_dates(s)
if (term_date is not None) and (term_date < assess_date):
tra... |
def clustering_MA(state_sequences, n_agents, mapping, n_clusters=None, max_frames=1e5):
'''
Clusters all (or a representative subset) of the frames in trajectories using KMeans. Returns clustering object, which will be used to select the
least counts clusters. The agents that created each frame are remembe... | The function `run_trial` executes a trial of the Multi-Agent REAP algorithm using a Markov State Model (MSM) and Euclidean distance rewards. It simulates multiple epochs, clustering agent trajectories, selecting underrepresented states, optimizing agent weights via reward-based learning, and logging metrics like reward... | def run_trial(msm, initial_states, epochs, output_dir='./', output_prefix='', **kwargs):
'''
Runs a trial of MA REAP with standard Euclidean distance rewards.
Args
-------------
msm (pyemma.msm.models.msm.MSM): Markov State Model that will determine the kinetics of the simulation.
initial_s... |
def collect_initial_data(num_trajectories, traj_len, potential, initial_positions, trajectories):
'''
Collect some initial data before using adaptive sampling.
'''
for _ in range(num_trajectories):
for i, initial_position in enumerate(initial_positions):
traj = run_trajectory(n_steps... | The function runs a trial of Multi-Agent REAP (MA REAP) to explore a potential landscape by simulating agent trajectories, clustering data, computing rewards, and adjusting agent weights iteratively over epochs. It initializes trajectories, clusters data to identify under-explored regions, calculates agent-specific sta... | def run_trial(potential, initial_positions, epochs, output_dir='', output_prefix='', **kwargs):
'''
Runs a trial of MA REAP with standard Euclidean distance rewards.
Args
-------------
potential (str): potential on which to run the trial (currently only two-dimensional potentials are used).
... |
def collect_initial_data(num_trajectories, traj_len, potential, initial_positions, trajectories):
'''
Collect some initial data before using adaptive sampling.
'''
for _ in range(num_trajectories):
for i, initial_position in enumerate(initial_positions):
traj = run_trajectory(n_steps... | This function runs a trial of MA REAP to explore a 2D potential landscape by iteratively clustering trajectories, selecting under-explored regions, computing rewards, optimizing agent weights, and generating new trajectories. It logs cumulative rewards, weights, explored areas, and trajectory data, saving results to th... | def run_trial(potential, initial_positions, epochs, output_dir='', output_prefix='', **kwargs):
'''
Runs a trial of MA REAP with standard Euclidean distance rewards.
Args
-------------
potential (str): potential on which to run the trial (currently only two-dimensional potentials are used).
... |
def collect_initial_data(num_trajectories, traj_len, initial_positions, output_dir, output_prefix, top_file):
'''
Collect some initial data before using adaptive sampling.
Args
-------------
num_trajectories (int): number of trajectories to launch per agent.
traj_len (int): number of simlated s... | The main task of the code is to run a trial of the MA REAP algorithm using Euclidean distance rewards for conformational sampling. It initializes parameters, collects trajectory data, performs clustering to select under-sampled regions, computes rewards, optimizes agent weights, and generates new trajectories iterative... | def run_trial(initial_structures, epochs, output_dir='', output_prefix='', **kwargs):
'''
Runs a trial of MA REAP with standard Euclidean distance rewards.
Args
-------------
initial_structures (list[str]): path to starting structures for simulations. Length of list must match number of agents.... |
def get_repositories(self):
repositories = config.require_object("repositories")
return repositories
def get_repo_config_value(self, repository, key: str, separator: str='.'):
config = self.get_repositories().get(repository)
key_value = Helpers.key_in_dict(config, key, separator)
... | This code creates AWS ECR repositories based on configuration, setting image scanning and tag mutability policies. It attaches repository policies for permissions and lifecycle policies to manage image retention, using Pulumi for infrastructure as code. | def create(self):
# Get all of the repositories from the config.
repositories = self.get_repositories()
for repo_name in repositories:
"""
Create ECR Repo
"""
repository = aws.ecr.Repository(
repo_name,
... |
def _login(self, location: Location):
self.driver.get(LOGIN_URL)
self._find_element("//input[@id='emailAddress-0']").send_keys(self._username)
self._find_element("//input[@id='loginPassword-0']").send_keys(self._password)
self._find_element("//lightning-button/button[text()='Log in']").c... | The code schedules a vaccination appointment by validating the input, handling login based on location, navigating through eligibility and health screening steps, filling personal details, processing insurance info, and submitting the appointment. It returns the generated appointment ID if not in test mode. | def schedule_appointment(self, appt: VaxAppointment):
if appt.canceled:
raise ValueError("Appointment is canceled on Acuity.")
if appt.vax_appointment_id is not None:
raise ValueError("Appointment already registered on VAX.")
# implicit login if current location doesn't... |
def handle_player_move(stones, current_player, game_board):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
... | The code implements a Go game where players take turns placing stones on a board, tracking captured stones and prisoner counts. It alternates between a selected human player and AI moves, enforces stone limits (181 for black, 180 for white), and determines the winner when limits are met by comparing prisoner counts. Th... | def play_game(screen, selected_player):
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption("Go Game")
game_board = GameBoard(screen, BOARD_SIZE)
stones = [["" for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
current_player = "B"
black_stones_limit... |
def check_not_same_numbers(num1,num2):
return bool((num1-num2))
def check_not_continuous_numbers(num1,num2):
return bool((num2-num1)-1)
def infer_result(self, result, num1, num2):
if (result):
self.continuous_range_inference(num1, num2)
return
self.new_range_inference(nu... | This code identifies continuous number ranges and duplicates in a sorted list. It iterates through consecutive elements, checks if they are either the same or part of a continuous sequence, and builds a result dictionary to map these relationships. The function returns this dictionary, which likely categorizes numbers ... | def iterate_numbers(self,number_list):
number_list.sort()
self.continuous_range_not_started = True
self.result = dict()
for i in range(len(number_list)-1):
check_not_same = check_not_same_numbers(number_list[i],number_list[i+1])
check_not_continuous = check_not_co... |
def extractListFromFiles(files, section):
for f in files:
if not os.path.exists(f):
continue
yield from extractListInSection(f, section)
def groupCategory(reasons_to_be_grateful):
grateful_by_reason = defaultdict(list)
for reason in reasons_to_be_grateful:
if reason == "... | This function retrieves and organizes content from specified daily/weekly files based on a section, grouping entries by category. It handles both recent daily entries (750words archives) and weekly reports (week_report), formatting output as markdown/text or plain text. The task involves file path generation, content e... | def dumpSectionDefaultDirectory(section, days, day=True, markdown=False, text_only=False):
# assert section in "Grateful Yesterday if".split()
printHeader = markdown == False and text_only == False
if printHeader:
print(f"## ----- Section:{section}, days={days} ----- ")
# Dump both archive... |
def extractListFromGlob(directory, section):
files = [f for f in glob.glob(directory)]
yield from extractListFromFiles(files, section)
def groupCategory(reasons_to_be_grateful):
grateful_by_reason = defaultdict(list)
for reason in reasons_to_be_grateful:
if reason == "":
continue
... | The code processes a glob pattern by expanding it to a file path, extracting a list of items from the specified file, grouping these items by category, and then printing the categorized results. | def dumpGlob(glob, thelist):
all_reasons_to_be_grateful = extractListFromGlob(os.path.expanduser(glob), thelist)
grouped = groupCategory(all_reasons_to_be_grateful)
printCategory(grouped) |
def addXMLClassCurrency(parent, _dumpDirPath):
#Create XML class
newClass = ET.SubElement(parent, "class", name="Currency")
#Parse through JSON data
json_files_currency = {"/Currency.json"}
json_files_item = {"/Artifact.json", "/Oil.json", "/DeliriumOrb.json", "/Fossil.json", "/Essence.json", "/Via... | The code generates a market index XML file by creating a structured XML tree with metadata and item class data. It initializes a `<snapshot>` root element, adds version and timestamp details, then processes multiple item categories (currency, fragments, gems, etc.) using helper functions. If any category data is missin... | def indexGen(_marketIndexPath, _dumpDirPath):
#Start the marketIndex.xml tree with the root structure <snapshot>
marketSnapshot = ET.Element("snapshot", name="rand_indexGen.py Market Index")
#<snapshot> contains a few meta fields...
#<version> contains the marketIndex.xml structure version
ET.SubEl... |
def _factor(a: int)->tuple:
"""Factors a number n as the product of two primes."""
for i in range(3,int(pow(a,1/2))+1,2):
if not (a%i):
return i, a//i
return _exception(1)
def _getz(a: int,b:int)->int:
"""Returns the lcm of p-1 and q-1."""
return lcm(a-1,b-1)
def _valide(a:int,b:... | The code decrypts a cipher text using RSA by factoring $ n $ into primes $ p $ and $ q $, computing $ z = \phi(n) $, and testing common RSA exponents (and additional generated ones) to find a valid private key $ (d, n) $. It decrypts the cipher text with each candidate $ (e, d) $ pair, returning the plaintext if the re... | def decrypt(n: int,cipher: list):
p,q = _factor(n)
print("p={}, q={}".format(p,q))
print("n={}".format(n))
z = _getz(p,q)
print("z={}\n--".format(z))
# To increase speed I used a list of common exponents found from here:
# https://security.stackexchange.com/questions/2335/should-rsa-public... |
def populate(
self,
table_name, attributes,
func, tables=None, model=None
) -> Table:
"""
Create a new populate table.
The table will be populated with the data returned by the UDF specified as a parameter.
The method can be used to populate sourc... | This function parses a Column-SQL query to determine the operation type (e.g., table creation, calculation, aggregation) and executes the corresponding data processing task using methods like `populate`, `calculate`, or `aggregate`. It handles operations such as defining tables, computing columns, rolling windows, link... | def column_sql(self, query: str, func=None, args=None):
# Parse query and extract parameters
op, entries, func_str, args_str, win_str = parse_column_sql(query)
if func is None:
func = func_str
if args is None:
args = args_str
if op.lower().startswith("ta... |
def error_checker(maze):
""" Combines lines of txt file into single line. Iterates each character
checking for specific parameters. Ends program and reports errors when
identified.
Parameters:
maze: the maze file
"""
lines = maze.readlines()
combined = ''.join(lines)
start_here ... | The main task of the code is to solve a maze by reading a map file, validating its structure, generating maze cells and their connections, constructing a tree for pathfinding, determining the shortest path from start to end points, and passing the solution to a command handler for further processing. | def main():
try:
map_file_name = input()
maze_file = open(map_file_name, 'r')
maze_lines = error_checker(maze_file)
if not maze_lines:
return
except FileNotFoundError:
print('ERROR: Could not open file: NO_SUCH_FILE')
return
cells, start_pt, end_p... |
def disk_flux(self, distance):
"""
Flux of the disk component in units of keV^2 ( Photons / cm^2 / s / keV).
Parameters
----------
distance: float
Distance to the source in cm.
"""
return self.disk_sed / (4*np.pi*distance**2)
def warm_fl... | The function `total_flux` calculates the total flux at a given distance by summing the contributions from three components: disk flux, warm flux, and corona flux. Each component is computed using corresponding methods (`disk_flux`, `warm_flux`, `corona_flux`), all passed the same `distance` parameter. The result is the... | def total_flux(self, distance):
"""
Total flux at distance.
Parameters
----------
distance : float
distance to source in cm.
"""
disk_flux = self.disk_flux(distance)
warm_flux = self.warm_flux(distance)
corona_f... |
def disk_flux(self, distance):
"""
Flux of the disk component in units of keV^2 ( Photons / cm^2 / s / keV).
Parameters
----------
distance: float
Distance to the source in cm.
"""
return self.disk_sed / (4*np.pi*distance**2)
def warm_fl... | The function calculates the total flux from three components (disk, warm, corona) at a given distance, converts their combined flux from arbitrary units to erg/cm²/s/Hz using Planck's constant and energy/frequency ranges, then returns the result as total_flux_erg. | def total_flux_erg(self, distance): # convert flux units to erg/cm^2/s/Hz (added by ASL)
"""
Total flux at distance, in erg/cm^2/s/Hz.
Parameters
----------
distance : float
distance to source in cm.
"""
disk_flux = self.disk_flux(dist... |
def corona_flux(self, distance):
"""
Corona flux computed using donthcomp from Xspec.
Parameters
----------
distance : float
distance to source.
"""
gamma = self.corona_photon_index
kt_e = self.corona_electron_energy
... | The main task of the code is to plot the total flux (sum of corona, disk, and warm flux) as a function of energy on a log-log scale. It sets appropriate axis labels, limits, and a legend, returning the matplotlib axis for further customization. The flux is calculated at a given distance, with energy range and color sch... | def plot_total_only(self, distance, ax = None): # Added by ASL
"""
Plot total flux in energy units.
yaxis: EL_E [ keV keV / s / keV]
xaxis: E [keV]
"""
colors =iter(cm.viridis(np.linspace(0,1,4)))
if(ax is None):
print("creating figure.")
f... |
def corona_flux(self, distance):
"""
Corona flux computed using donthcomp from Xspec.
Parameters
----------
distance : float
distance to source.
"""
gamma = self.corona_photon_index
kt_e = self.corona_electron_energy
... | The function plots the total flux in energy units (EL_E) against energy (E) on a log-log scale, combining corona, disk, and warm components. It visualizes each component separately with distinct colors, sets y-axis limits, labels, and a legend, returning the matplotlib axis for further customization. | def plot_total_flux(self, distance, ax = None):
"""
Plot total flux in energy units.
yaxis: EL_E [ keV keV / s / keV]
xaxis: E [keV]
"""
colors =iter(cm.viridis(np.linspace(0,1,4)))
if(ax is None):
print("creating figure.")
fig, ax = plt.su... |
def sharp_and_smooth(img):
# Unsharp masking technique for shaperning edges
# Helps make edges more 'connected'
#gaussian_blurred = cv2.GaussianBlur(img, (11,11), 9);
#sharpened = cv2.addWeighted(img, 1.5, gaussian_blurred, -0.5, 0);
# Remove salt and pepper noise
median_blurred = cv2.medianBlur(img, 11)
combi... | The code processes an input frame to detect and visualize contours of orange regions. It sharpens/smoothes the image, converts it to LAB color space, applies white balancing and CLAHE enhancement, generates an orange mask, converts it to BGR, and overlays the mask on the enhanced image. Finally, it displays the origina... | def contour_processing(frame):
cv2.namedWindow('frame', cv2.WINDOW_NORMAL)
cv2.resizeWindow('frame', 1000, 1000)
frame = sharp_and_smooth(frame)
LAB_img = cv2.cvtColor(frame, cv2.COLOR_BGR2LAB)
white_balanced_LAB = white_balance(LAB_img)
enhanced_LAB = CLAHE_enhance(white_balanced_LAB)
orange_mask = LAB_mask... |
def parse_args():
parser = argparse.ArgumentParser()
'''train'''
parser.add_argument('--batch_size', type=int, default=512)
parser.add_argument('--warm_up_epoch', type=int, default=5) # epoches for warmup start
parser.add_argument('--num_class', type=int, default=26)#26 modulations for tw... | The main task of the code is to parse command-line arguments, execute a training process via the `trainer()` function, and subsequently perform test analysis using the `test_analysis()` function, likely for evaluating model performance or generating insights from test data. | def main():
args = parse_args()
trainer()
test_analysis() |
def create_model(args, vocab, embedding=None):
"""Creates the model.
Args:
args: Instance of Argument Parser.
vocab: Instance of Vocabulary.
Returns:
An VQGRaD model.
"""
# Load GloVe embedding.
if args.use_glove:
embedding = get_glove_embedding(args.embedding_n... | The code trains a variational model for question generation using image-text pairs, combining generative and variational components. It preprocesses data, loads vocabulary, and builds data loaders with weighted sampling. The model (VQG) is initialized, with optional pretrained weights, and optimized using Adam for gene... | def train(args):
# Create model directory
if not os.path.exists(args.model_path):
os.makedirs(args.model_path)
# Save the arguments.
with open(os.path.join(args.model_path, 'args.json'), 'w') as args_file:
json.dump(args.__dict__, args_file)
# Config logging.
log_format = '%(le... |
def device_repget_edgex(arr):
str_result = ""
origin = random.randint(0, 100)
size = arr[INDEX_SIZE_GET]
arr_values = arr[INDEX_VALUE_GET: (INDEX_VALUE_GET + int(size)) ]
str_values = get_arr_value(arr_values)
if str_values == "":
return ""
else:
pass
str_result ... | The function processes incoming commands from a device, checks if the command is intended for the current device using a global name, and executes corresponding actions like GET, PUT, or device discovery based on the command type. | def receive_proccess_edgex(input):
global my_name
input.strip()
arr = input.split('#')
if str(arr[1]) == my_name:
print("Device nhan duoc yeu cau:\n\t",input)
if (arr[0] == CMD_GET ):
device_repget_edgex(arr)
elif arr[0] == CMD_PUT:
d... |
def prepare_label_mapping(self):
print('preparing label mappings...')
label_mapping = self.config.get('label_mapping', {})
from_map_label: List[Label] = []
to_map_labels: List[List[Label]] = []
for from_id in label_mapping:
to_ids = label_mapping[from_id]
from_map_label.append(Label(self... | The code initializes and configures a bot by preparing label mappings, member/comment data, and list mappings based on configuration. It checks for a 'label_to_list_mapping' parameter: if present, it prepares and starts tasks using this mapping; otherwise, it uses a default list mapping. The core task is to set up data... | def start_bot(self):
self.prepare_label_mapping()
self.prepare_member_via_label()
self.prepare_comment_via_label()
self.prepare_comment_from_list()
if self.config.get('label_to_list_mapping', None):
self.prepare_label_to_list_mapping()
self.start_tasks_via_label_to_list_mapping()
els... |
def _hat_attribute(self, name: str) -> str:
path = f"{self._hat_path}/{name}"
try:
with open(path, "r") as fh:
value = fh.read().rstrip('\x00')
except Exception as e:
raise RevPiHatEEPROMAttributeException(
f"Could not read HAT value for {... | (The code loads and parses specific attributes from a RevPi HAT's EEPROM into instance variables, such as UUID, product details, serial number, and revision data. It checks the existence of the HAT path, raises exceptions for errors, and uses helper methods to extract and format values like integers, dates, and version... | def load(self):
"""
Load values from RevPi HAT EEPROM
:raises: RevPiHatEEPROMAttributeException: if the attribute cannot be read from HAT files
"""
if not os.path.exists(self._hat_path):
raise RevPiHatEEPROMPathException("HAT EEPROM path does not exists")
se... |
def read_plane_data(line, latlon=False):
if latlon:
return [float(line[3]), float(line[4])]
lat = float(line[3])
lon = float(line[4])
hdg = int(line[6].replace('°', ''))
spd = int(line[7])
k = 1 if 'mph' in driver.find_element('xpath', \
'//tr[@class=\'thirdHeader\']').text else ... | The code determines the optimal flight path by parsing HTML data, extracting waypoints, calculating distances using the haversine formula, and selecting the path with the minimal closest approach to predefined waypoints. | def get_plane_app(url):
path_lines = list()
xmin_dists = []
for path in paths:
page = requests.get(url)
tree = html.fromstring(re.sub(
r'<span class="hide-for-medium-up">.+?(?=span>)', '<span><',
str(page.content).replace('\\t', '\t').replace('\\n', '\n')))
... |
def between(text, start, end):
try:
return text.split(start)[1].split(end)[0]
except Exception:
return ''
def find_intercept(tracklog_url):
wait(w=random.uniform(1, 2.5))
driver.get(tracklog_url)
altitude_json = between(driver.page_source, 'altitude_json = ', ';')
alts = al... | The code extracts flight data from a source string, parsing details like aircraft ID, altitude, speed, route, departure/arrival airports, aircraft type, and gate. It handles default values for missing data and retrieves additional tracking info. The result is a structured, comma-separated string of flight parameters. | def get_plane_info(source):
temp_text = source[source.rindex(r'"route"') - 3000:
source.rindex(r'"route"') + 1500]
ident = between(temp_text, r'"displayIdent":"', r'"')
flight_plan = between(temp_text, r'"flightPlan":', r'"fuelBurn"')
alt = between(flight_plan, r'"altitude":', r'... |
def getEmptyTimetable(availabilities, slotSize):
timetable = {}
for name in availabilities.keys():
timetable[name] = [availabilities[name]['starttime'], availabilities[name]['duration'], []]
slotCount = (availabilities[name]['duration'] / slotSize).seconds / 60
timetable[name][2] = [None] * int(slotCoun... | The code schedules meetings by matching feedbacks with available time slots, prioritizing based on startup meetings, total time, start time, and feedback scores. It filters low-feedback entries, shuffles them randomly, and iteratively sorts/schedules them into a timetable. If a coach's schedule is full, it's logged. Fi... | def matchmake(feedbacks,
availabilities,
startupMeetingCount,
slotSize=40,
seed=None):
random.seed(seed)
#timetable: {coach: [start, duration, [null, "startup1", etc]]}
timetable = getEmptyTimetable(availabilities, slotSize)
# filter out elements with too low feedback
sortedList = [x for x in feedbac... |
def nrrd_writer(self):
os.chdir(self.save_file_path)
nrrd.write(self.save_file_name, self.np_array)
def dcm_writer(self):
if self.np_array.ndim == 2:
os.chdir(self.save_file_path)
self.write_dicom(self.np_array, self.save_file_name)
elif self.np_array.ndim == 3:
... | This method determines the file format of a given save file name by checking its extension. If the extension is '.nrrd', '.dcm', or '.nii', it calls the corresponding writer method (nrrd_writer, dcm_writer, or nibabel_writer). If the format is unsupported, it prints an error message and exits the program. | def determine_format(self):
_, file_extension = os.path.splitext(self.save_file_name)
if file_extension == '.nrrd':
self.nrrd_writer()
elif file_extension == ".dcm":
self.dcm_writer()
elif file_extension == ".nii":
self.nibabel_writer()
else:
... |
def drawFirstWin(matrix):
#draw grid
win.setCoords(0, 0, matrix.w, matrix.h)
rectangle = Rectangle(Point(0, 0), Point(matrix.w, matrix.h))
rectangle.setFill("white")
rectangle.draw(win)
for i in range(0, matrix.w):
Line(Point(0, i), Point(matrix.w, i)).draw(win)
for x in range(0, mat... | The code creates a grid (Matrix) with defined polygons as obstacles, sets start and end points, and computes a path from start to end while avoiding obstacles. It visualizes the grid, obstacles, points, and the computed path using graphical drawing functions. | def main():
pointStart = MyPoint(2,2)
pointEnd = MyPoint(19,16)
# pickupPoint = [(15,20),(20,30),(25,60),(35,50),(45,79)]
pickupPoint = []
matrix = Matrix(22,22)
drawFirstWin(matrix)
# draw poly
poly1 = MyPoly([(8,12),(8,17),(13,12)])
poly2 = MyPoly([(4,4),(5,9),(8,10),(9,5)])
p... |
def _set_collection_date(self, date, window):
if not self.stats["collection_date"]:
self.stats["collection_date"] = date
self.log.debug(f"Collection timestamp: {date}")
if not self.stats["window"]:
self.stats["window"] = window * 4
self.log.debug(f"Collect... | This function collects and analyzes GitHub pull request data for a specified repository and time window. It queries all PRs, updates statistics (counts, time metrics, labels, bug fixes), categorizes them by state (open/closed/merged), tracks author contributions, calculates average PR lifetimes, and ensures data is sor... | def load_pull_requests(self, base_date=datetime.today(), window=DEFAULT_WINDOW):
"""
Collect pull request data
Because we want to see older pull requests as well, we don't
filter the initial query based on time here
:returns: None
"""
self._set_collection_date(b... |
def _set_collection_date(self, date, window):
if not self.stats["collection_date"]:
self.stats["collection_date"] = date
self.log.debug(f"Collection timestamp: {date}")
if not self.stats["window"]:
self.stats["window"] = window * 4
self.log.debug(f"Collect... | The main task of the code is to load branch details from a GitHub repository, collect metadata like commit times, author information, and branch protection status within a specified time window, update statistical counters for branches and users, and skip invalid or future-dated branches while logging progress and perf... | def load_branches(self, base_date=datetime.today(), window=DEFAULT_WINDOW):
"""
Because getting branch details requires a second
query, this function will be slower than loading
other endpoints.
Since we're using a generator on the list of branches,
we can't easily show p... |
def _set_collection_date(self, date, window):
if not self.stats["collection_date"]:
self.stats["collection_date"] = date
self.log.debug(f"Collection timestamp: {date}")
if not self.stats["window"]:
self.stats["window"] = window * 4
self.log.debug(f"Collect... | This function retrieves and organizes GitHub repository statistics (code frequency, commit activity, contributors, punch card) into a structured format within a specified time window. It adjusts dates to align with GitHub's Sunday-based week system, filters data by the defined date range, and aggregates results while h... | def load_repo_stats(self, base_date=datetime.today(), window=DEFAULT_WINDOW):
"""
This data is already visible in the "Insights" panel of a repo,
but it's fairly easy to collect, so let's use it
This is also the dataset that doesn't return data on initial calls,
so we may need t... |
def _set_collection_date(self, date, window):
if not self.stats["collection_date"]:
self.stats["collection_date"] = date
self.log.debug(f"Collection timestamp: {date}")
if not self.stats["window"]:
self.stats["window"] = window * 4
self.log.debug(f"Collect... | The main task of the code is to fetch and analyze GitHub workflow runs within a specified time window. It filters out ignored workflows and statuses, processes run metadata, tracks event/user/workflow statistics, calculates run durations, and computes success/failure percentages. The results are aggregated into interna... | def load_workflow_runs(self, base_date=datetime.today(), window=DEFAULT_WINDOW):
"""
Parse through workflow runs and collect results
:returns: None
"""
self.log.info("Loading workflow details...")
self._set_collection_date(base_date, window)
starttime = time.time... |
def _set_collection_date(self, date, window):
if not self.stats["collection_date"]:
self.stats["collection_date"] = date
self.log.debug(f"Collection timestamp: {date}")
if not self.stats["window"]:
self.stats["window"] = window * 4
self.log.debug(f"Collect... | This function aggregates repository statistics by loading pull requests, commits, branches, and release data within a specified time window. It calculates metrics like mean time to repair (MTTR) from bug fixes, tracks release activity via tags or branches, updates user statistics, and records workflow runs. The results... | def load_all_stats(self, base_date=datetime.today(), window=DEFAULT_WINDOW):
"""
Wrapper to execute all stat collection functions
:returns: None
"""
self._set_collection_date(base_date, window)
self.load_pull_requests(base_date, window)
self.load_commits(base_dat... |
def create_time_of_measurement():
"""
This function creates a timestamp of the current time using ISO format
eg. 2021-06-25T15:24:17
:return: time_of_measurement
"""
# empty array list
list_timestamps = []
# current time and import the unix time https://www.unixtimestamp.com/
curren... | The function `write_to_csv` generates synthetic healthcare data (patient, sensor, and emergency alerts) and writes it to a CSV file (`../data/healthcare_data.csv`) for validation if the database fails. It uses `csv.DictWriter` to structure data with predefined fieldnames, combines data from multiple sources (patient, s... | def write_to_csv():
"""
This function writes a payload to csv file to view if information is correct
:return: writes csv file to hard drive - It is an option in case the data base does not works.
"""
# the ./ means that the code will be stored in the same folder that we are running
csv_file = ... |
def get_actions(self, request):
"""
Return a dictionary mapping the names of all actions for this
ModelAdmin to a tuple of (callable, name, description) for each action.
"""
# If self.actions is set to None that means actions are disabled on
# this page.
if self.a... | This code handles Django admin changelist view logic, including bulk actions, pagination, and context setup. It processes POST requests for actions, validates parameters, manages error redirection, prepares media/resources, paginates querysets, and constructs response context with result counts, selections, and forms f... | def index_view(self, request):
response = super().index_view(request)
opts = self.model._meta
# if not self.has_view_or_change_permission(request):
# raise PermissionDenied
try:
cl = self
except admin.options.IncorrectLookupParameters:
# Wack... |
def extractPdf(filePath):
with ZipFile(filePath,'r') as zipobject:
listoffile=zipobject.namelist()
for filename in listoffile:
if filename.endswith('.pdf'):
zipobject.extract(filename,'Extracted_pdf')
def finalFrame(onlyfiles):
# Toaddr=toaddr
final_database=pd.DataFrame()
i = 0
while i < len(onlyfil... | The code processes resumes by extracting PDF content, classifying them using keywords from a CSV file, converting and uploading the data to a specified email address, then clearing temporary directories. It reads resumes, applies classification rules, prepares data for transmission, and ensures cleanup after processing... | def process(filePath,toaddr):
#Extract pdfs
extractPdf(filePath)
#Function to read resumes from the folder one by one
mypath='./Extracted_pdf' #enter your path here where you saved the resumes
uploadedR='./UploadedResume'
onlyfiles = [os.path.join(mypath, f) for f in os.listdir(mypath) if os.path.isfile(os.path.j... |
def batchnorm_relu(inputs):
""" Batch Normalization & ReLU """
x = BatchNormalization()(inputs)
x = Activation("relu")(x)
return x
def residual_block(inputs, num_filters, strides=1):
""" Convolutional Layers """
x = batchnorm_relu(inputs)
x = Conv2D(num_filters, 3, padding="same", strides=st... | The code defines a RESUNET model for image segmentation, constructing an encoder-decoder architecture with residual blocks and skip connections. It processes input images through convolutional layers, downsampling in the encoder, a bridge, and upsampling in the decoder, ultimately outputting a segmented image via a sig... | def build_resunet(input_shape):
""" RESUNET Architecture """
inputs = Input(input_shape)
""" Endoder 1 """
x = Conv2D(16, 3, padding="same", strides=1)(inputs)
x = batchnorm_relu(x)
x = Conv2D(16, 3, padding="same", strides=1)(x)
s = Conv2D(16, 1, padding="same")(inputs)
s1 = x + s
... |
def get_directory_size(path):
sizes = {}
checked_dirs = set()
tree = {"total_size": get_size(path, sizes, checked_dirs)}
try:
with os.scandir(path) as it:
for entry in it:
if entry.is_dir(follow_symlinks=False):
dir_size = sizes.get(entry.path, get... | This code generates an interactive HTML sunburst chart visualizing disk usage in a directory tree. It calculates directory sizes, structures hierarchical data, applies formatting, and exports the visualization to "disk.html" with custom styling and interactivity settings. | def run_scan(path, pre=2):
sizes = {path:get_directory_size(path)}
ids, labels, parents, values = create_trace(sizes)
total = shutil.disk_usage(path)[0]
settings = {"ids": ids,
"labels":labels,
"parents": parents,
"values": values,
"maxdep... |
def writeInt(self, i: int) -> None:
self.write(f"{i: d}")
def writeString(self, s: str) -> None:
self.write(f"{s: s}\n")
def writeObj(self, obj: ObjNum) -> None:
self.write(f"{obj: d}")
def writeFloat(self, f: float) -> None:
self.write(f"{f: f}")
def writeBool(self, b: bool) -> None:
... | This function determines the data type of the input value and delegates the writing process to the corresponding method (e.g., writeInt, writeString, etc.), acting as a type dispatcher for serializing different data types into a structured format. | def writeValue(self, v: Any) -> None:
value_type = type(v)
if value_type == int:
self.writeInt(v)
elif value_type == str:
self.writeString(v)
elif value_type == ObjNum:
self.writeObj(v)
elif value_type == float:
self.writeFloat(v)
... |
def writeString(self, s: str) -> None:
self.write(f"{s: s}\n")
def writePlayers(self) -> None:
self.writeCollection(self.db.players, writer=self.writeString)
def writePending(self) -> None:
pass
def writeClocks(self):
self.writeCollection(self.db.clocks, templates.clock_count)
def writeT... | The `writeDatabase` method writes multiple components of a database by calling several helper methods such as `writePlayers`, `writePending`, and `writeConnections`, ensuring all relevant data is persisted. Its primary task is to systematically save the current state of the database, including players, tasks, clocks, a... | def writeDatabase(self) -> None:
self.writeString(templates.version.format(version=17))
self.writePlayers()
self.writePending()
self.writeClocks()
self.writeTaskQueue()
self.writeSuspendedTasks()
self.writeInterruptedTasks()
self.writeConnections()
... |
def writeString(self, s: str) -> None:
self.write(f"{s: s}\n")
def writeInt(self, i: int) -> None:
self.write(f"{i: d}")
def writeValue(self, v: Any) -> None:
value_type = type(v)
if value_type == int:
self.writeInt(v)
elif value_type == str:
self.writeStr... | This method serializes a MooObject's attributes into a structured format by writing its ID, name, flags, owner, location, last move, contents, parents, children, and verbs to a data stream, likely for storage or transmission. | def writeObject(self, obj: MooObject) -> None:
obj_num = obj.id
self.writeString(f"#{obj_num}")
self.writeString(obj.name)
self.writeInt(obj.flags)
self.writeInt(obj.owner)
self.writeValue(obj.location)
self.writeValue(obj.last_move)
self.writeValue(obj.co... |
def writeInt(self, i: int) -> None:
self.write(f"{i: d}")
def writeString(self, s: str) -> None:
self.write(f"{s: s}\n")
def writeValue(self, v: Any) -> None:
value_type = type(v)
if value_type == int:
self.writeInt(v)
elif value_type == str:
self.writeStr... | This code serializes a task object by writing its attributes—time, verb, object, player, and argument list—to a data stream using specific methods like writeInt, writeString, and writeValue, likely for storage or transmission in a networked application. | def writeQueuedTask(self, task):
self.writeInt(task.time)
self.writeString(task.verb)
self.writeValue(task.object)
self.writeValue(task.player)
self.writeValue(task.arglist) |
def _load_spreadsheet(self, modality, na=None, fix_anon=True):
title = defaults.spreadsheets[modality]['spreadsheet']
key = defaults.spreadsheets[modality]['key']
accept_spreadsheet = False
info = ()
for attempt in range(max(0, defaults.retry_attempts)):
info = self._... | The code imports and processes MDS UPDRS data, handling missing values, mapping session IDs, converting relevant columns to numeric, calculating scores for parts I, II, III, and their missingness. It filters invalid rows, retains selected columns if concise, and returns cleaned data with standardized column names. | def import_mds_updrs(self, concise=True):
data = self._load_spreadsheet(modality='mds_updrs',
na=['na', 'NA', 'NA1', 'NA2', 'NA3', 'NA4', 'NA5', 'NA6', 'UR', '', 'None', None])
data = self._map_to_universal_session_id(data)
for col in data.columns[data.col... |
def _load_spreadsheet(self, modality, na=None, fix_anon=True):
title = defaults.spreadsheets[modality]['spreadsheet']
key = defaults.spreadsheets[modality]['key']
accept_spreadsheet = False
info = ()
for attempt in range(max(0, defaults.retry_attempts)):
info = self._... | This function processes HADS data by loading a spreadsheet, cleaning missing values, dropping redundant total columns, mapping session IDs, calculating anxiety/depression scores from specific questions, renaming columns, and optionally returning a concise version with only session IDs and calculated scores. | def import_hads(self, concise=True):
data = self._load_spreadsheet('hads', na=['NA', 'NA1', 'NA2', 'NA3', 'NA4', 'NA5', 'NA6', '', None])
data = data.drop(columns=['anxiety_total', 'depression_total'])
data = self._map_to_universal_session_id(data)
data = data.assign(HADS_anxiety=data[[... |
def _load_spreadsheet(self, modality, na=None, fix_anon=True):
title = defaults.spreadsheets[modality]['spreadsheet']
key = defaults.spreadsheets[modality]['key']
accept_spreadsheet = False
info = ()
for attempt in range(max(0, defaults.retry_attempts)):
info = self._... | This function imports and processes session data by loading spreadsheet information, filtering and transforming session details, handling exclusions, merging with participant birth dates to calculate age, and returning sorted, structured session data with NaN values filled. | def import_sessions(self, from_study=None, exclude=True):
data = self._load_spreadsheet(modality='sessions', na=('', 'None', None))
data = data.astype({'date': 'datetime64', 'mri_scan_no': 'UInt64'}).astype({'mri_scan_no': str})
data['mri_scan_no'] = data.apply(lambda x: '' if x.mri_scan_no == ... |
def extract_parameters_from_conditions(condition_list: Sequence[Condition]) -> Tuple[str, str, Sequence[Condition]]:
reserved_types = ["__gauge__", "__counter__", "~"]
query_element = [
(condition.key, condition.value.value) for condition in condition_list if condition.key in reserved_types
... | This function generates Prometheus query strings based on the metric type (gauge/counter) and aggregation parameters. It extracts conditions, constructs base queries, and applies time-series aggregations or increases for counters, returning formatted Prometheus expressions for metrics like CPU usage or request counts. | def to_prometheus(self) -> str:
request_type, name, conditions = self.extract_parameters_from_conditions(self.conditions)
if request_type == "__gauge__":
query = name + self.conditions_list_to_query(conditions)
if self.aggregation_method is not None:
translated_ag... |
def insert_item(self, item: StoryItem):
""" Inserts story data, one row at a time. """
self.__insert_tokens(item)
self.__insert_spans(item)
self.__insert_sentiments(item)
def close_connection(self):
""" Gracefully closes the cursor and the connection. """
self.cur.close... | This method inserts half-processed items individually with progress tracking and unprocessed items in batches, also with progress updates. It uses `insert_item()` for single entries and `batch_insert_item()` for bulk processing, closing connections after each operation. The function reports insertion status for both da... | def insert_remaining_items(self, half_processed, unprocessed):
""" Inserts half-processed items row by row and unprocessed items in batches. """
print("")
print("Inserting data for " + str(len(half_processed)) + " half-processed stories ...")
previous_percentage = 0
for i in rang... |
def respawn_if_dead(self):
self.info_lock.acquire()
screenshot = self.screenshot
self.info_lock.release()
match_loc, match_val = self.vision.template_match_alpha(screenshot, utils.get_respawn_needle_path())
if match_loc is not None:
self.send_telegram_message('Respaw... | The code implements an automated game bot that cycles through states to detect and interact with in-game entities ("metin"). It initializes by setting up the environment, searches for targets using computer vision, rotates/calibrates when no matches are found, moves to engage targets, attacks, collects loot, and handle... | def run(self):
while not self.stopped:
if self.state == BotState.INITIALIZING:
self.metin_window.activate()
self.respawn_if_dead()
self.teleport_back()
self.osk_window.recall_mount()
self.turn_on_buffs()
... |
def feedforward(self, x_train):
params = self.params
# input layer activations becomes sample
params['A0'] = x_train
#print(x_train.shape)
# input layer to hidden layer 1 and passed through activation function
params['Z1'] = np.dot(params["W1"], params['A0']) + params['B1']
params['A1'] = self.sigmoid(pa... | The code trains a neural network using backpropagation over multiple epochs. It iterates through training data, computes outputs, adjusts weights via backpropagation, and updates weights. After each epoch, it evaluates validation accuracy and prints progress, including time spent and accuracy percentage. | def train(self, x_train, y_train, x_val, y_val):
start_time = time.time()
for iteration in range(self.epochs):
for x,y in zip(x_train, y_train):
output = self.feedforward(x)
#print("OUTPUT", output.shape)
changes_to_w = self.backpropagation(y, output)
self.update_weights(changes_to_w)
accu... |
def move_unit(self, unit, position_change):
new_position = [unit.position[0] + position_change[0], unit.position[1] + position_change[1]]
"""
Handles out of bound errors
"""
if new_position[0] < 0 or new_position[0] > (len(self.map[0]) - 1):
return
if new_p... | This function handles Pygame events for quitting, player movement via WASD keys, and boss activation via SPACE. It updates player animation, moves the player, checks quiz results for level progression, and triggers win conditions based on quiz scores. | def handle_events(self):
"""
A for loop for detecting events
Because we see that there can be multiple events
"""
for event in pygame.event.get():
#If we quit/ press the X button, then we quit and exit the game
if event.type == pygame.QUIT:
... |
def handle_events(self):
"""
A for loop for detecting events
Because we see that there can be multiple events
"""
for event in pygame.event.get():
#If we quit/ press the X button, then we quit and exit the game
if event.type == pygame.QUIT:
... | The code updates the game screen by clearing it, handling events, loading the appropriate level map, rendering the map, and drawing game objects with camera adjustments. | def update(self):
self.screen.fill(config.BLACK)
self.handle_events()
self.map = []
if self.level == 0:
self.load_map("01")
if self.level == 1:
self.load_map("02")
if self.level == 2:
self.load_map("03")
if self.level == 3:... |
def check_event(self):
for evento in pyg.event.get():
if evento.type == pyg.QUIT:
pyg.quit()
exit()
if evento.type == pyg.KEYDOWN:
if evento.key == pyg.K_a:
self.editor_mode = not self.editor_mode
... | This code defines a game loop that continuously handles events, updates the game state, renders the game grid and block life, maintains a target frame rate, and updates the display with a background color. | def run(self):
while True:
self.fps.tick(self.fps_num)
self.check_event()
self.draw_grid()
self.update_game()
self.draw_block_life()
pyg.display.update()
janela.fill(BG_COLOR) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.