dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def resize_img(self, small_x, small_y, reset_only = False):
self.small_x = small_x
self.small_y = small_y
small_single_shape = (self.small_x, self.small_y, self.num_channels)
if reset_only:
self.real_modifier = np.zeros((1,) + small_single_shape, dtype=np.float32)
... | The code performs an adversarial attack on a batch of images to generate perturbations that mislead a model's classification. It iteratively optimizes a modifier using ADAM or Newton methods, adjusting the perturbation's L2 norm and learning rate. The attack uses binary search on a constant value to balance perturbatio... | def attack_batch(self, gray_img, img, img_id, checkpoint):
"""
Run the attack on a batch of images and labels.
"""
# def compare(x,y):
# if not isinstance(x, (float, int, np.int64)):
# x = np.copy(x)
# if self.TARGETED:
# x[... |
def runBash(self,command,workingDir="./"):
result = subprocess.run(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, cwd=workingDir)
if self.verbose:
print(result)
print("_____________________________________________")
return result
def aver... | The code determines the optimal focus point for an image by iteratively adjusting focus parameters, applying DoG filtering to assess sharpness via energy calculations, and identifying the minimum energy value corresponding to the sharpest focus. It generates temporary images, computes average energy, modifies values be... | def dogFocusing(self):
startTime = time.time()
testDir = self.tmpDir+"dog/"
testImagePath = testDir+"testFocus.png"
testDogPath = testDir+"testDog.png"
avg = 0
values = []
for i in range(0, self.focusSteps):
f = -self.focusRange+i*self.focusStep
... |
def generateSaliencyMaps(self, saliencyDir):
rootSalDir = self.tmpDir+"salTest/"
refSalDir = rootSalDir+"test/"
os.mkdir(rootSalDir)
os.mkdir(refSalDir)
resultingSaliencyMap = self.tmpDir+"saliencyMap.png"
for f in self.inputFiles:
shutil.copy(self.inputDir+f,... | The code generates and exports refocused images by analyzing saliency and focus maps. It creates a saliency map directory, processes deep and dog focus images to identify central coordinates, then exports refocused outputs with specific filenames based on input focus values. | def generateNewDoF(self, dogFocus, deepFocus):
resultingSaliencyMap = self.tmpDir+"saliencyMap.png"
saliencyDir = self.tmpDir+"saliency/"
os.mkdir(saliencyDir)
self.generateSaliencyMaps(saliencyDir)
self.saliency(deepFocus, resultingSaliencyMap, saliencyDir)
dogPoint = se... |
def parseArguments(self):
parser = argparse.ArgumentParser(description='Converts set of 45 images into quilts with...')
parser.add_argument('--inputDir', default="./", help='input directory with numbered images')
parser.add_argument('--inputVideo', default="", help='input video file - overwrite... | The code processes input parameters, generates quilt images, and exports multiple versions with different focus settings. It checks DoF values to generate new images, exports a basic quilt, refocuses based on input settings, and applies DoG and deep focusing techniques, exporting results if enabled. | def run(self):
self.parseArguments()
self.analyzeInput()
if(self.dof[0] > -100):
self.generateNewDoF(self.dof[0], self.dof[1])
return
self.exportQuiltImage(self.inputDir, self.outputDir, "basicQuilt.png")
if(self.inputFocus != 0.0):
self.refocu... |
def empty_cells(self):
empty = []
for x, row in enumerate(self.board):
for y, col in enumerate(row):
if self.board[x][y] == 0:
empty.append([x, y])
return empty
def make_move(self, x, y, player):
self.board[x][y] = player
def mini_max_alph... | The main task of the code is to determine the computer's move in a game (likely Tic-Tac-Toe). If the board is empty, it selects a random cell. Otherwise, it uses the minimax algorithm with alpha-beta pruning to find the optimal move, then executes it and updates the board display. | def computer_move(self, computer_symbol):
if len(self.empty_cells()) == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
self.make_move(x, y, computer_symbol)
else:
result = self.mini_max_alpha_beta_pruning(
len(self.empty_cells()), -math.inf... |
def entropy(rows):
# compute the entropy.
entries = class_counts(rows)
avg_entropy = 0
size = float(len(rows))
for label in entries:
prob = entries[label] / size
avg_entropy = avg_entropy + (prob * math.log(prob, 2))
return -1*avg_entropy
def partition(rows, question):
"""Pa... | The function identifies the optimal feature-value split in a dataset to maximize information gain for a decision tree. It iterates through each feature's unique values, partitions the data based on each potential split, calculates the resulting information gain, and retains the split with the highest gain. This process... | def find_best_split(rows, header):
"""Find the best question to ask by iterating over every feature / value
and calculating the information gain."""
best_gain = 0 # keep track of the best information gain
best_question = None # keep train of the feature / value that produced it
current_uncertainty... |
def initial_population(pop_size, city_list):
pop = []
for i in range(0, pop_size):
pop.append(create_route(city_list))
return pop
def rank_routes(pop):
fitness_results = {}
for i in range(0, len(pop)):
fitness_results[i] = Fitness(pop[i]).route_fitness()
return sorted(fitness... | This code implements a genetic algorithm to optimize a route (likely for the Traveling Salesman Problem) by evolving a population over generations. It initializes a population, iteratively creates new generations using elitism and mutation, and returns the best route found after specified generations, minimizing distan... | def genetic_algorithm(pop, pop_size, elite_size, mutation_rate, generations):
pop = initial_population(pop_size, pop)
print(f"Initial distance: {str(1 / rank_routes(pop)[0][1])}")
for i in range(0, generations):
pop = create_next_generation(pop, elite_size, mutation_rate)
print(f"Final distanc... |
def initial_population(pop_size, city_list):
pop = []
for i in range(0, pop_size):
pop.append(create_route(city_list))
return pop
def rank_routes(pop):
fitness_results = {}
for i in range(0, len(pop)):
fitness_results[i] = Fitness(pop[i]).route_fitness()
return sorted(fitness... | This function implements a genetic algorithm to solve a traveling salesman problem (TSP), tracking progress over generations. It initializes a population, iteratively creates new generations via selection, crossover, and mutation (with elite preservation), and records the inverse of the best route's fitness at each ste... | def genetic_algorithm_track(pop, pop_size, elite_size, mutation_rate, generations):
pop = initial_population(pop_size, pop)
progress = []
progress.append(1 / rank_routes(pop)[0][1])
for i in range(0, generations):
pop = create_next_generation(pop, elite_size, mutation_rate)
progress.app... |
def clear_board(self):
for x, row in enumerate(self.board):
for y, col in enumerate(row):
self.board[x][y] = 0
def is_board_filled(self):
if len(self.empty_cells()) == 0:
return True
return False
def is_game_won(self):
return self.player_won(self.o... | The code allows a user to play a turn-based game (likely Tic-Tac-Toe) against a computer. It prompts the user to choose starting order (1st or 2nd) and symbol (X/O), validates inputs, initializes the game board, and alternates turns between human and AI players until the board fills or a win condition is met. The game ... | def play(self):
while True:
try:
order = int(
input('Would you like to go first or second? (1/2)? '))
if not (order == 1 or order == 2):
print('Please pick 1 or 2')
else:
break
exc... |
def find_best_split(rows, header):
"""Find the best question to ask by iterating over every feature / value
and calculating the information gain."""
best_gain = 0 # keep track of the best information gain
best_question = None # keep train of the feature / value that produced it
current_uncertainty... | The code recursively constructs a decision tree by selecting the best feature to split the data, partitioning rows into true/false branches, and creating child nodes until no further splits are possible (base case: zero gain). It returns a Decision_Node with the split question, child branches, depth, node ID, and origi... | def build_tree(rows, header, depth=0, id=0):
gain, question = find_best_split(rows, header)
# Base case
if gain == 0:
return Leaf(rows, id, depth)
# If we reach here, we have found a useful feature / value
# to partition on.
true_rows, false_rows = partition(rows, question)
# Rec... |
def track_filter(self, df: pd.DataFrame, obs_len: int,
raw_data_format: Dict[str, int]):
"""Pad tracks which don't last throughout the sequence. Also, filter out non-relevant tracks.
Args:
seq_df (pandas Dataframe): Dataframe containing all the tracks in the sequence
... | The code computes social features for a given agent track by calculating minimum distances to front/back vehicles, neighbor counts, and rotation angles. It processes input data, filters relevant tracks, and combines these features into a numpy array. The function handles varying observed and total sequence lengths, ret... | def compute_social_features(
self,
df: pd.DataFrame,
agent_track: np.ndarray,
obs_len: int,
total_len: int,
raw_data_format: Dict[str, int],
):
"""Compute social features for the given sequence.
Social features are meant to cap... |
def _refresh_token_if_need(self, delta: datetime.timedelta):
""" Refresh token when token lifetime go out bound """
if (datetime.datetime.now() + delta) > self._token_expire_date:
self._LOGGER.debug("Need refresh token")
self._refresh_token_request(self._refresh_token_value, self... | The code uploads new local backup files to Yandex Disk, deletes outdated files to maintain a specified storage limit, and returns either the list of newly uploaded files or a deletion status. It refreshes the Yandex token, compares local/remote file lists, uploads new files, and removes the oldest files if the total ex... | def upload_files(self):
""" Upload files to yandex.
Upload new files and delete old files from yandex disk.
Refresh yandex disk directory information
"""
self._refresh_token_if_need(REFRESH_TOKEN_DELTA)
local_backups = self.get_local_file_path_list(self._backup_... |
def _set_response(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def message_window(self, message):
self.wfile.write(bytes('<script type = "text/javascript">', 'utf8'))
self.wfile.write(bytes('alert("{}")'.format(message), 'utf8'))... | This code handles POST requests by processing URL-encoded form data. It checks if the 'pw' parameter matches a stored password, showing a login failure message if not. On success, it renders a graph using the path parameter. If the 'refresh' parameter is present, it refreshes the graph with additional dynamic parameter... | def do_POST(self):
self._set_response()
self.path = parse.unquote(self.path)
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length).decode('utf8').split('&')
post_data = [s.split('=') for s in post_data]
if post_data[0][0] == 'pw'... |
def square_under_attack(self, r, c):
self.white_to_move = not self.white_to_move #switch to opponent's
oppo_moves = self.get_all_possible_moves()
self.white_to_move = not self.white_to_move # to get to original player
for move in oppo_moves:
if move.end_row == r and move.end_... | This function generates valid castling moves for a chess game. It checks if the king is in check, skips castling if so, and adds kingside/queenside castling moves to the 'moves' list based on current castling rights and player's turn. | def get_castle_moves(self, r, c, moves):
if self.square_under_attack(r, c):
return # we can't castle while in check
if (self.white_to_move and self.current_castling_right.wks) or (not self.white_to_move and self.current_castling_right.bks):
self.get_kingside_castle_moves(r, c, m... |
def get_all_possible_moves(self):
moves = []
for r in range(len(self.board)): #number of rows
for c in range(len(self.board[r])): #number of col in the given row
turn = self.board[r][c][0]
if (turn == 'w' and self.white_to_move) or (turn == 'b' and not self.wh... | The code generates all valid moves by checking if each move leaves the king in check, handling castling rights, en passant, and determining checkmate/stalemate. It iterates through possible moves, simulates them, and removes invalid ones. Castling moves are added separately, and original game state is restored before r... | def get_valid_moves(self):
# for debugging
'''for log in self.castle_rights_log:
print(log.wks, log.wqs, log.bks, log.bqs, end=', ')
print()'''
temp_enpassant_possible = self.enpassant_possible
temp_castle_rights = CastlingRights(self.current_castling_right.wks, sel... |
def reset_scene() -> None:
"""Resets the scene to a clean state."""
# delete everything that isn't part of a camera or a light
for obj in bpy.data.objects:
if obj.type not in {"CAMERA", "LIGHT"}:
bpy.data.objects.remove(obj, do_unlink=True)
# delete all the materials
for material... | The code renders multiple images of a 3D object from varying azimuthal angles and randomized elevations, using Blender. It sets up lighting, generates camera poses, and saves rendered images along with metadata (calibration matrix, camera positions, angles) to specified directories. | def save_images(object_file: str) -> None:
# object_uid = os.path.basename(object_file).split(".")[0]
# os.makedirs(args.output_dir, exist_ok=True)
save_path = args.output_dir
reset_scene()
# load the object
load_object(object_file)
# object_uid = os.path.basename(object_file).split(".")[0]... |
def getGameState(gameName):
if gameName not in refreshState:
initializeRefreshState(gameName)
return refreshState[gameName]
def join(request):
if request.method == 'GET':
return render(request, "join.html", {"join_error":''})
if request.method == 'POST':
gameName = str(request.PO... | The code handles a game session by retrieving game and player data, managing game state transitions, and processing player inputs (text or image) during alternating writing/drawing phases. It updates the game state, stores clues, and renders the play interface, redirecting between phases based on the current state. | def play(request):
gameName = request.session['gameName']
playerName = request.session['playerName']
game = Game.objects.get(game_name=gameName)
player= game.player_list_set.get(player_name=playerName)
context = {
"game" : game,
"player" : player
}
request.session['gameState'... |
def collectPasswords(digits, howMany):
i = howMany
passwordList = []
while i > 0:
passwordList.append(generatePassword(digits))
i -= 1
# print list of passwords, each on a new line, without creating a string of all passwords using join.
print(*passwordList, sep = "\n")
def goAgain(a... | The main task of the code is to generate a specified number of passwords using the `collectPasswords` function, then recursively repeat the process if the user consents, creating a loop for continuous password generation. | def theMainFunction(digits, howMany):
# if printing the items of the list directly with collect passwords
collectPasswords(digits, howMany)
again = input("Generate %d more passwords? (Y/N): " %howMany)
if goAgain(again): theMainFunction(digits, howMany) |
def collectPasswords():
i = 10
passwordList = []
while i > 0:
passwordList.append(generatePassword())
i -= 1
# arrange the passwords vertically as a string
allPasswords = '\n'.join(passwordList)
return allPasswords
def goAgain(answer):
while answer != "Y":
if answer ... | The main task of the code is to recursively generate and display passwords. It calls `collectPasswords()` to produce passwords, prompts the user to generate ten more, and uses `goAgain()` to determine if the function should repeat itself, creating a loop for continuous password generation based on user input. | def theMainFunction():
print(collectPasswords())
again = input("Generate ten more passwords? (Y/N): ")
if goAgain(again): theMainFunction() |
def listColonies() -> list[list[tuple[int]]]:
"""Compiles a list of all the bacterial colonies."""
colonies = []
for y in range(length):
for x in range(width):
if petri_dish[y][x] == "#":
# Only look for nearby colonies if there is a bacterium in the cell we are consideri... | The function identifies the optimal empty cell on a grid to place a new colony, maximizing the combined size of nearby existing colonies. It iterates through each cell, checks if it's empty ("."), calculates the total colony size from adjacent colonies, and returns the coordinates (y, x) of the cell that yields the lar... | def bestPlace() -> tuple[int]:
original_colonies = listColonies()
max_size = 0
for x in range(width):
for y in range(length):
if petri_dish[y][x] == ".":
size = sumColonyLengths(lookforNearbyColonies(y, x, nearbyCells(y,x), original_colonies), original_colonies)
... |
def string2board(board_description):
# Split the board into sets, each representing a side
# input should be a space-separated list of strings
sidestrings = board_description.strip().split(' ')
for i in range(len(sidestrings)):
sidestrings[i] = sidestrings[i].strip().upper()
board = [set(x) ... | The main task of the code is to solve a word search puzzle by finding the shortest sequence of letters on a board that forms valid words from a dictionary, then writing the result to an output file. It reads an input board, loads word definitions, computes solutions using dynamic programming, and outputs either the fir... | def ten_point(input_filename, output_filename, words_file="words.txt"):
try:
with open(input_filename, 'r') as input_file:
textline = input_file.readline()
board = string2board(textline.strip())
words_dict = load_words_to_dict(words_file)
except FileNotFoundError... |
def _load_data(data_path=DATA_PATH):
'''
Load Amazon review data from fixed path stored in module.
Optional parameters:
data_path: Path to a file with requested data
Returns:
list: list of dictionaries representing single data entries
'''
# If data does not exist, do... | The function `get_data` retrieves and preprocesses a dataset of Amazon reviews (review text and overall ratings) for an LSTM network. It loads data from a pickle file if it exists and `force` is False; otherwise, it processes raw data by filtering entries, balancing class sizes, converting ratings to integers, tokenizi... | def get_data(one_class_size=None, force=True):
'''
Get review text - overall ranking dataset for our LSTM network
Optional arguments:
one_class_size: Amount of requested data for each overall ranking value
force: Do not try to load the data from pickle file
Returns:
... |
def emb_dict():
'''Load embedding dictionary from pickle file or create one'''
# Load the embedding dictionary, if not found, create it
if not os.path.exists(amznDS.EMBED):
amznDS.create_embedding_dict()
with open(amznDS.EMBED, 'rb') as f:
return pickle.load(f)
def _train_step(self, X, y... | The code trains an LSTM model using provided training data (XX, Y) and evaluates it on test data (testX, testY). It shuffles data per epoch, computes gradients/loss during training, handles numerical instability, saves model checkpoints with epoch-specific names, and plots training losses. The embedding dictionary is l... | def train(self, XX, Y, testX, testY, model_name, epochs=1):
'''
Train the LSTM on given data
Input arguments:
XX: training input data - list of lists of words
Y: training list of ground truth classes - list of ints
testX: evaluate input
... |
def get_data(one_class_size=None, force=True):
'''
Get review text - overall ranking dataset for our LSTM network
Optional arguments:
one_class_size: Amount of requested data for each overall ranking value
force: Do not try to load the data from pickle file
Returns:
... | The code generates a word embedding dictionary where each word's vector represents its probability distribution across classes in a dataset. It counts word occurrences per class, normalizes these counts by class word frequencies, and saves the resulting dictionary as a pickle file. The function processes reviews, trims... | def create_embedding_dict(class_key='overall', data_key='reviewText'):
'''
Create vector for each word in dataset, each element of vector will
correspond to probability of occurance in each class.
Pickle created dictionary into path EMBED
Input arguments:
class_key: Key accessing ... |
def sp_I_0_0 (all_the_P_a):
return (cvxopt.sparse(cvxopt.matrix((calculate_I_0_0(all_the_P_a)))))
def sp_I_0_1 (R):
return(cvxopt.spmatrix([],[],[],(n_rounds,n_bidders*(len(R)))))
def sp_I_1_0 (all_the_P_a,R):
values = []
xindices = []
yindices = []
xindex = 0
for a in range (n_rounds):
... | The code constructs a sparse matrix by aggregating results from multiple sub-functions (sp_I_0_0, sp_I_0_1, etc.) into a 2x3 structure using cvxopt.sparse, combining inputs all_the_P_a and R to form a composite matrix for optimization or linear algebra operations. | def sp_I (all_the_P_a,R):
I_0_0 = sp_I_0_0(all_the_P_a)
I_0_1 = sp_I_0_1(R)
I_1_0 = sp_I_1_0(all_the_P_a,R)
I_1_1 = sp_I_1_1(R)
I_2_0 = sp_I_2_0(all_the_P_a)
I_2_1 = sp_I_2_1(all_the_P_a,R)
return (cvxopt.sparse([[I_0_0,I_1_0,I_2_0],[I_0_1,I_1_1,I_2_1]])) |
def run_1st_module_MASTER(shp, tmp_res_1, bounds_max, bounds_min, radius_1):
shp['BFS_flag'] = 0
shp['rectification_flag'] = 0
shp['seg_exp'] = 1
seg_exp = 1
lm = 0
seg_change = []
seg_flag = []
while len(shp[shp['BFS_flag'] == 0]) > 0:
try:
ret_index_list, ret_seg_li... | The function processes a power line network (span_shp) for a specific feeder, filtering segments by device presence and length. It splits data into device-free and device-containing parts, runs three sequential modules (segmentation, refinement, final segmentation) with specified radii/bounds, then merges device-contai... | def segment_work(span_shp, output_path, bounds_max, bounds_min, radius_1, radius_2, radius_3, feeder_name):
input_shp = span_shp[span_shp['feeder'] == feeder_name]
input_shp["Length(mi)"] = input_shp["length_span"]
input_shp_no_device = input_shp[~((input_shp['has_device'] == 1) & (input_shp['Length(mi)'] >... |
def find_feeder(filePath, columnName, feederName, spanIdColName, lower, upper):
# import ipdb; ipdb.set_trace()
global feeder
global spanIdCol
global lower_limit
global upper_limit
lower_limit = lower
upper_limit = upper
spanIdCol = spanIdColName
feeder.iloc[0:0]
feeder_all = f... | This function performs feeder segmentation by processing input data, identifying leaf nodes and thresholds, constructing a tree, executing an algorithm, post-processing results, and generating a final output file named with the company and feeder name. | def run_the_segmentation_on_feeder(path, feederCol, feederName, spanIdCol, lowerLimit, upperLimit, companyName):
find_feeder(path, feederCol, feederName, spanIdCol, lowerLimit, upperLimit)
feeder = feeder.drop_duplicates(subset = ["feeder_wit"])
find_leaf_nodes()
find_threshold()
make_tree()
a... |
def find_feeder(filePath, columnName, feederName, spanIdColName, lower, upper):
# import ipdb; ipdb.set_trace()
global feeder
global spanIdCol
global lower_limit
global upper_limit
lower_limit = lower
upper_limit = upper
spanIdCol = spanIdColName
feeder.iloc[0:0]
feeder_all = f... | This function performs geographic segmentation on input data by processing each feeder, applying algorithms to identify thresholds, build trees, and generate segmented results. It aggregates outputs into a GeoDataFrame with spatial data, using parameters like feeder columns, span IDs, and value limits to guide the segm... | def run_the_segmentation(path, feederCol, feederName, spanIdCol, lowerLimit, upperLimit, companyName):
# import ipdb; ipdb.set_trace()
global feeder
feeders = set([])
feeder_all = path
for row in feeder_all[feederCol]:
feeders.add(row)
count = 0
result_df = pd.DataFrame(columns=... |
def set_initial_state(self):
# get target infomartion
self.get_targets_info()
# initial state
self.data = self.optimize_data
self.datasize = len(self.data)
self.state.combination = random.sample(self.data.keys(), self.LimitNum)
self.objs = []
... | This code performs an iterative optimization algorithm with a progress bar, applying random 'add' or 'remove' changes to a state, evaluating their validity probabilistically, and updating the best state if improvements are found. It runs until reaching max iterations or time limits, returning the optimal state discover... | def optimization(self):
start = time.time()
with tqdm() as pbar:
while self.MaxIteration > self.state.iteration and self.MaxTime > (time.time() - start):
pbar.update(1)
# initialization
if self.state.initial:
... |
def get_contracts(transaction_hashes):
contracts = {}
if os.path.isfile('contracts_cast.json'):
try:
with open('contracts_cast.json', 'r') as f:
contracts = json.loads(f.read())
except:
contracts = {}
for tx in tqdm(transaction_hashes, desc='getting contracts... '):
if tx not in contracts.keys():
... | The code processes Ethereum transactions involving the 'cast' function by extracting targeted contracts and their attacked functions. It filters relevant transactions from a CSV, retrieves contract data, and logs details like sender, receiver, and attacked functions into 'cast.csv'. Additionally, it collects source cod... | def main():
df = pd.read_csv('attacked_functions.csv', skipinitialspace = True)
df = df[df['Attacked Function'] == 'cast']
transaction_hashes = df['Transaction'].tolist()
contracts = get_contracts(transaction_hashes)
with open('cast.csv', 'a') as f:
f.write('Transaction, Victim Sender, Victim Receiver, Attacke... |
def read(fp: str, full_fp: bool = False) -> Union[dict, str]:
"""
Reads an object from a file.
Parameters
----------
fp : str
The filename of the file to read from.
full_fp : bool, optional
Whether to specift the full path to the file,
by default False
Returns
... | The function `add_to_mutuals` populates a persistent `mutuals.json` file with user data from `survey.csv`, tracking additions and failures. It checks each user's status (protected, banned, nonexistent) and updates the JSON accordingly, limiting additions to a specified number. It prints progress and outcomes, ensuring ... | def add_to_mutuals(limit=None):
"""
### Creates persistent mutuals list.
Users are from the `survey.csv` file.
Mutuals are written into `mutuals.json` file.
Description
-----------
1. We first read the `mutuals.json` file and
store it in the variable mutuals.
2. We then set t... |
def read_model(name : str, full_fp: bool = False) -> sklearn.base.BaseEstimator:
"""
Loads a model from the models folder.
Parameters
----------
name : str
The name of the model to load.
full_fp : bool, optional
Whether to specift the full path to the file,
by default F... | The function retrieves political tweets from a user's mutual followers using a classification model, filters them based on thresholds, and returns a structured DataFrame of the most political tweets from up to 5 mutuals, while handling account validation and tweet limits. | def get_political_tweets_from_mutuals(id : int = 0, handle : str = "",
user_tweet_limit : int = 10_000,
mutual_tweet_limit : int = 1_000,
political_mutual_max : int = 5,
... |
def conditional_resample(self):
# Calculate number of effective particles
if self.n_eff() < self.n_points * self.rejection_threshold:
#print("RESAMPLE")
self.resample()
def update_estimate(self, point, weight, target_arr, measurement_outcome):
'''
... | This code updates particle filter weights based on measurement data and target. It resamples if specified, converts input data to a numpy array, iterates through points to compute new weights using an update estimate method, then renormalizes the updated weights for probabilistic inference. | def measure(self, measurement_data, measurement_target, inversion_arr=None, resample=True):
if resample:
self.conditional_resample()
if inversion_arr is None:
inversion_arr = self.inversion_arr
# Ensure the measurement data is a numpy array
... |
def conditional_resample(self):
# Calculate number of effective particles
if self.n_eff() < self.n_points * self.rejection_threshold:
#print("RESAMPLE")
self.resample()
def update_estimate(self, point, weight, applied_unitary, measurement_outcome):
'''
... | This function updates particle weights in a particle filter based on measurement data. It resamples particles if enabled, converts input data to a numpy array, iterates through each particle to update its weight using the `update_estimate` method, and then renormalizes the updated weights to maintain a valid probabilit... | def measure(self, measurement_data, measurement_target, inversion_arr=None, resample=True):
if resample:
self.conditional_resample()
# Ensure the measurement data is a numpy array
measurement_data = np.array(measurement_data)
new_weights = [... |
def game_1(self):
try:
board = Board(5, 2)
snake = [
Position(0, 4),
Position(0, 3),
Position(0, 2),
Position(1, 2),
Position(2, 2),
Position(2, 3),
Position(3, 3),
... | The main task of the code is to prompt the user to select a game difficulty level (1, 2, or 3) and validate their input. If valid, it executes the corresponding game method (game_1, game_2, or game_3) and breaks the loop. If invalid, it repeatedly asks for a valid option until a correct choice is made. | def choose_difficulty(self):
while True:
print("\nChoose a game")
inp = input("1, 2 or 3: ")
if (str(inp) == '1'):
self.game_1()
break
elif (str(inp) == '2'):
self.game_2()
break
elif (s... |
def download_network_weights(arguments, workload, branch):
# Some tests may not use Neural Networks
network_name = workload['test'][branch]['network']
if not network_name or network_name == 'None': return None
# Log that we are obtaining a Neural Network
pattern = 'Fetching Neural Network [ %s, %-... | The code completes a workload by downloading network weights and engines for 'dev' and 'base' versions, running and verifying benchmarks, reporting performance metrics, downloading an opening book, calculating average NPS, and executing a chess engine comparison via Cutechess with concurrency settings. | def complete_workload(arguments, workload):
dev_network = download_network_weights(arguments, workload, 'dev')
base_network = download_network_weights(arguments, workload, 'base')
dev_name = download_engine(arguments, workload, 'dev', dev_network)
base_name = download_engine(arguments, workload, 'ba... |
def remove_file(file_to_remove, print_failures=True):
try:
os.remove(file_to_remove)
return True
except OSError as err:
if print_failures:
print(f"failed to remove {file_to_remove} - {err}")
return False
def get_remote_agent_list(self):... | This code trains a population of agents across multiple generations using parallel processing. It initializes scores, distributes agent evaluations to worker processes, collects results, updates agent performance, identifies top-performing agents, and resets agents for the next generation. The system handles both local... | def train(self):
print("begin training...")
self.is_training = True
self.scores = [0.0 for _ in range(self.total_population)]
best_agents = []
last_ui_update_time = time()
for e in range(self.generations):
self.current_generation = e
self.waiting_a... |
def get_domain(self, url):
'''
Returns domain domain from a given url
:param url: Pass the url
:return: domain name
'''
parts = urlsplit(url)
base = "{0.netloc}".format(parts)
tld = base.replace("www.", "")
return tld
def save_links_from_url(self, ... | The main task of the code is to scrape recipes from a given website by recursively fetching and processing links. It starts with the provided URL, extracts links, processes each recipe page, saves extracted data, marks links as scraped, and iterates through paginated content until no more links remain. The process incl... | def start(self):
'''
Starts scraping recipes from a given website
:param website_url: Pass the url of the website
:return:
'''
logging.info('Starting scraping: ' + self.website_url)
page = 1
current_url = self.website_url
domain = self.get_domain(s... |
def encode(self, x : torch.Tensor):
'''
Encodes input data
See Also:
:class:`onlinehd.Encoder` for more information.
'''
return self.encoder(x)
def _one_pass_fit(self, h, y, lr, bootstrap):
# initialize class hypervectors from a single datapoint
if b... | The `fit` method trains a model using input data `x` and labels `y`, encoding data if needed. It initializes class hypervectors via a bootstrap sample (or per-class single data points) and performs one-pass learning if enabled, followed by iterative training over specified epochs with configurable batch sizes and learn... | def fit(self,
x : torch.Tensor,
y : torch.Tensor,
encoded : bool = False,
lr : float = 0.035,
epochs : int = 120,
batch_size : Union[int, None, float] = 1024,
one_pass_fit : bool = True,
bootstrap : Union[float, str] = 0.01)... |
def assert_equals(self, actual: int, expected: int, description='No description') -> None:
if actual == expected:
print('PASS [', description, ']')
else:
print('FAIL [', description, ']: expected', expected, ' but got ', actual)
def exchange_money_for_chocolate(self, ppc, wpc, wa... | The main task of the code is to test the `exchange_money_for_chocolate` function by verifying its output against expected values under various scenarios, such as valid calculations, negative prices, insufficient funds, zero prices, and leftover chocolates. It also includes a test for a potentially misspelled method `ex... | def test(self) -> None:
self.assert_equals(self.exchange_money_for_chocolate(3, 5, 20), 7, "It should return the correct amount")
self.assert_equals(self.exchange_money_for_chocolate(2, 2, 16), 15, "It should return the correct amount")
self.assert_equals(self.exchange_money_for_chocolate(1, 3, ... |
def sort2(lst: list, start: int) -> None:
"""
Sorts a list of length 2
:param lst: The list being sorted
:param start: Where the section being sorted starts
:pre: The list lst has not been sorted
:post: The list lst has been sorted for the given section
"""
if lst[start] > lst[1 + start]... | The function `hybrid_sort` sorts a sublist of `data` in-place by selecting an algorithm based on the segment size. For segments of size 2 or 3, it uses `sort2` or `sort3`. If the size is below a global `min` threshold, it applies `smallsort`; otherwise, it uses `bigsort`. The goal is to optimize performance by combinin... | def hybrid_sort( data: list, start: int, end: int ) -> None:
"""
Sort data in-place using one of several algorithms depending
on the size of the data.
:param data: a list of comparable elements
:param start: The first index in the segment to be sorted
:param end: The last index in the segment to... |
def generate_z(cfg, y):
z = torch.zeros(y.size(0), cfg.z_dim * len(cfg.use_atts))
for i in range(y.size(0)):
for j in range(y.size(1)):
if y[i, j] == 1:
if cfg.z_distribution == 'unif_-11':
z[i, j * cfg.z_dim: (j + 1) * cfg.z_dim] = \
... | This code implements a forward pass with conditional logic based on the 'mask' parameter, handling tasks like generating outputs, computing losses (e.g., reconstruction, adversarial), and returning results for training/testing. It uses generator (G) and discriminator (D) networks, applies different loss calculations fo... | def forward(self, y_edit, z, x, y_real, mask=None, get_z_real_x_fake_=False, step=-1, att_name=None):
if mask == 'embedding':
z_real_ = self.D(x)[1][0]
return z_real_.detach()
# how to generate zp
output_real_ = self.D(x)
z_real_ = output_real_[1][0]
# z_... |
def forward(self):
fwd = dict()
for t in self.time_intervals:
fwd[t] = dict()
for state in range(self.n_states):
fwd[t][state] = [0] * len(self.sequence[t])
fwd[t][state][0] = self.init_prob[state] * self.emiss_probs[state][self.sequence[t][0]]
... | The code trains a probabilistic model using an iterative EM-like approach. It computes forward/backward probabilities, updates parameters via expectation-maximization (exp_max), and iterates until log-likelihood convergence (threshold: 0.0001). Post-convergence, it calculates AIC/BIC scores for model evaluation, then r... | def train_model(self):
CONVERGENCE_METRIC = 0.0001
log_likelihood = list()
fwd = self.forward()
bwd = self.backward()
pp = self.posterior_probability(fwd, bwd)
final_loglikelihood = self.likelihood(fwd, bwd)
update_parameters = self.exp_max(pp)
log_likeli... |
def handle_menu(self, action: int) -> bool:
""" Checks if any of the menu keys is pressed
If the quit button is clicked returns True such that the
game terminates directly. Else returns None → which will
do the same as returning False. Since the result is
cathced in an... | This code defines the main loop of a Snake game, handling input, moving the snake, checking collisions, updating the game state, and rendering the game with a score display. It adjusts sleep time based on movement direction to control game speed, ensuring smooth gameplay and proper collision detection. | def __call__(self) -> None:
""" Main Loop of Snake Game instance"""
# draw the border
self.screen.border()
# handle the key inputs
action = self.screen.getch()
self.handle_menu(action)
# allows to skip the sleep timer
if self.handle_move(action)... |
def _run_algorithm_first_base_case(self, graph, e, N, p):
print('running algorithm first base case with graph = {}, e = {}, N = {}, p = {}'.format(graph.name, e, N, p))
t = pow(2, 1)
previous_i_vector = np.zeros(self._number_of_nodes)
continue_running = True
number_of_nodes_staye... | The code runs two base-case algorithms on multiple graphs with varying parameters (p, ε, k), collects results in `runs_data`, and saves them to text and binary files. It iterates through graph datasets, parameter values, and executes algorithm variants, handling exceptions while logging outcomes. | def run(self):
for graph in self._graphs:
for p in self._list_of_p:
N = 1/p
for e in self._list_of_epsilon:
try:
self._run_algorithm_first_base_case(graph, e, N, p)
except Exception as e:
... |
def maskColor(imgs, color, epsilon, grow_size=1):
mask = ~getMask(imgs, color, epsilon, grow_size)
return imgs * mask
def replaceOrPasteColor(imgs1, imgs2, color, epsilon, grow_size=1, paste: bool = False):
assert imgs1.shape == imgs2.shape, f'Shape {imgs1.shape} not equal {imgs2.shape}'
assert color.sh... | The function processes images based on the specified mode (mask, replace, paste, erase) by applying color-related operations like masking, replacing, pasting, or erasing regions. It returns the processed image in RGB format if `type_c` is 'RGB', otherwise converts the result from HSV to RGB using `hsv2rgb`. | def process(mode, type_c, img1, img2, color, epsilon, grow_size, erase_size):
if mode == 'mask':
imgR = maskColor(img1, color, epsilon, grow_size)
elif mode == 'replace':
imgR = replaceOrPasteColor(img1, img2, color, epsilon, grow_size)
elif mode == 'paste':
imgR = replaceOrPasteColo... |
def loadImg(path):
return torch.from_numpy(np.array(Image.open(path).convert('RGB'))).permute(2, 0, 1)
def rgb2hsv(color: torch.Tensor) -> torch.Tensor:
color = color.to(torch.float) / 255
flat = False
if len(color.shape) == 1:
color = color[None, :, None, None]
flat = True
max_c = c... | This function processes two images using specified modes (e.g., replace/paste) and color spaces (RGB/HSV), applies operations like color replacement, erosion/growth, and saves the resulting image as 'replaced.png'. It loads images, converts color spaces if needed, executes processing logic, and outputs the modified ima... | def imageProcess(path1, path2, mode, color, epsilon, grow_size, erase_size, type_c):
img1 = loadImg(path1).to(color.device)[None]
img2 = loadImg(path2).to(color.device)[None] if mode in ['replace', 'paste'] else None
if type_c == 'HSV':
img1 = rgb2hsv(img1)
img2 = None if img2 is None else r... |
def addStatusToMemory(obj, filename = None):
global targets, elements, gnmi_credentials
# From Notification
if filename == None:
#Check if are target config
if obj.config.key.js_path == ".snmp_agent.targets.target":
#Check if exits any config
if not obj.config.data.j... | This function processes configuration operations (add/change/delete) based on the 'op' field in the input object. It updates memory status accordingly, logs operation details, and returns False. | def Handle_Notification(obj) -> bool:
if obj.HasField('config') and obj.config.key.js_path != ".commit.end":
log.info(f"Handle_Notification: Operation:{obj.config.op}")
if obj.config.op == 0: # Add Config Operation
if "snmp_agent" in obj.config.key.js_path:
addStatusToMem... |
def Subscribe_Notifications(stream_id):
if not stream_id:
log.info("Stream ID not sent.")
return False
##Subscribe to Config Notifications - configs added by the snmp-agent
Subscribe(stream_id)
def addStatusToMemory(obj, filename = None):
global targets, elements, gnmi_credentials
... | This code registers an agent, maintains liveness via keep-alives, subscribes to notifications, processes SNMP traps in an infinite loop, and spawns threads for notification streams and GNMI subscriptions. It checks file existence to update memory status, initializes global paths, and handles queued updates. The primary... | def Run():
response = stub.AgentRegister(request=sdk_service_pb2.AgentRegistrationRequest(agent_liveliness=5), metadata=metadata)
log.info(f"Registration response : {response.status}")
# Send Keep Alives
th = threading.Thread(target=send_keep_alive)
th.start()
#Subscribe Notifications
req... |
def questioning_rule(states: dict[Tuple[str], float]) -> str:
"""
:param states: dictionary mapping states (sets of problems/questions) to probabilities
:return: question to be asked
"""
if not np.isclose(1, sum(states.values()), atol=0.01):
raise ValueError('Probabilities do not add up to 1... | The function simulates a stochastic Markov process by iteratively generating questions, responses, and updating states based on correctness. It runs up to 100 iterations, printing states and checking for a terminal state each time. If a final state is reached, it returns it; otherwise, it concludes as non-conclusive af... | def stochastic_markov(states: dict[Tuple[str], float]) -> Tuple[str]:
max_iter = 100
for _ in range(max_iter):
question = questioning_rule(states)
r = response_rule(question, states)
answer_correct = _take_answer(question)
updating_rule(question, answer_correct, r, states)
... |
def gen_first_name():
name = rand_consonant().upper() + rand_vowel()
for i in range(random.randint(1, 2)):
name += rand_consonant()
name += rand_vowel()
return name
def gen_last_name():
name = random.choice(['', '', '', '', '', 'de ', 'el '])
name += rand_consonant().upper() + rand... | The code initializes a class instance by generating and assigning random personal attributes: first name, last name, email (derived from the names), phone number, and hobbies. Each attribute is populated using dedicated generator functions, creating a randomized profile for the object. | def __init__(self):
self.first_name = gen_first_name()
self.last_name = gen_last_name()
self.email = gen_default_email(self.first_name, self.last_name)
self.phone_number = gen_phone_number()
self.pastimes = gen_pastimes() |
def put_user(user_id, obj):
user = get_user(user_id)["data"]
user.pop("user_id")
user.update({key: obj[key] for key in ["first_name", "last_name"]})
return put_to_microservice("user", user_id, user)
def put_contact(user_id, obj):
put_to_microservice("contact", user_id, obj, "/email")
put_to_micr... | The code updates a user's profile by saving their user data and contact information, then retrieves and returns the updated profile. | def put_profile(user_id, profile):
put_user(user_id, profile)
put_contact(user_id, profile)
return get_profile(user_id) |
def get_user(user_id):
return get_from_microservice("user", user_id)
def get_contact(user_id):
return {
**get_from_microservice("contact", user_id, "/email"),
**get_from_microservice("contact", user_id, "/phone"),
**get_from_microservice("contact", user_id, "/address"),
}
def get_pro... | This code handles user profile requests by retrieving or updating data based on HTTP methods. For GET, it fetches user and contact info, merges them, and returns the profile. For PUT, it updates the profile with JSON data from the request. The function uses helper methods to interact with user data and ensures the corr... | def profile():
user_id = current_user.get_id()
if request.method == "GET":
user_obj = get_user(user_id)
contact_obj = get_contact(user_id)
user_obj["data"].update(contact_obj)
return get_profile(user_id)
elif request.method == "PUT":
profile = request.json
ret... |
def negative_point(self, point):
if point is None:
return None
x, y = point
result = x, -y % self.p
assert self.lying_on_curve(result)
return result
def add(self, point1, point2):
assert self.lying_on_curve(point1)
assert self.lying_on_curve(point2)
... | This code performs elliptic curve scalar multiplication, multiplying integer n by a point using the double-and-add algorithm. It handles edge cases like n being a multiple of self.n or None, negates results for negative n, and iteratively computes the product by adding and doubling points based on binary decomposition ... | def multiply(self, n, point):
if n % self.n == 0 or point is None:
return None
if n < 0:
return self.negative_point(self.multiply(-n, point))
result = None
addend = point
while n:
if n & 1:
result = self.add(result, addend)
... |
def find_parameter(self, name, ancestors, global_config):
section, value = self, self.get(name)
if value is None:
if ancestors:
section, value = ancestors[-1].find_parameter(name, ancestors[:-1], global_config)
else:
section, value = None, global_c... | The function interpolates a parameter value by resolving it from ancestors or the global configuration, handling defaults, checking for interpolation loops, and ensuring the result is not a list. It returns the parameter name and interpolated value or raises an error if the parameter is missing, a loop is detected, or ... | def _interpolate(self, ancestors, ancestors_names, name, global_config, refs, escaped, named, braced, default):
if escaped:
return None, '$'
parameter_name = named or braced
if parameter_name.count('/') == 0:
section, value = self.find_parameter(parameter_name, ancestors... |
def _interpolate(self, ancestors, ancestors_names, name, global_config, refs, escaped, named, braced, default):
if escaped:
return None, '$'
parameter_name = named or braced
if parameter_name.count('/') == 0:
section, value = self.find_parameter(parameter_name, ancestors... | This function interpolates a configuration section by resolving references using a regex match. If a match is found, it processes the section name and value recursively, handling nested sections by interpolating them further. If no match, it falls back to parameter interpolation. The result is a resolved section name a... | def interpolate_section(self, name, ancestors, ancestors_names, global_config, refs):
match = FULL_INTERPOLATION.match(name)
if match:
new_name, value = self._interpolate(
ancestors, ancestors_names, name, global_config, refs, **match.groupdict()
)
if ... |
def parse_args():
"""
This function intialises the argumentparser and adds the command line parameters
"""
ap = argparse.ArgumentParser()
ap.add_argument("-ds","--dataset",required=True, help = "The dataset to perform text classification")
ap.add_argument("-es","--embedding_size",required=True, hel... | The main task of the code is to train and evaluate a machine learning model using a specified dataset. It parses command-line arguments, loads and preprocesses data, defines a model architecture based on embedding size and sequence length, and executes training and evaluation with defined hyperparameters like epoch siz... | def main():
"""
The main function defines which functions to run when the script is executed, and which command line parameters should be passed to what functions.
"""
args = parse_args()
X_train_pad, y_train, X_test_pad, y_test, t, MAX_SEQUENCE_LENGTH = load_and_process_data(args["dataset"])
model... |
def evaluate(board):
"""
Evaluates the board state and returns the score
"""
if check_win(board, True) == "X":
return -10
if check_win(board, True) == "O":
return 10
return 0
def isMovesLeft(board):
for i in range(16):
if (board[i] == '-'):
return True
... | The code implements the Minimax algorithm with Alpha-Beta pruning for a game (likely Tic-Tac-Toe on a 4x4 board). It evaluates the board state recursively, choosing optimal moves for the AI (maximizer) and player (minimizer) by exploring all possible moves, pruning unnecessary branches to improve efficiency, and return... | def minimax(board, depth, is_max, alpha, beta):
score = evaluate(board)
# If Maximizer has won the game return his/her
# evaluated score
if (score == 10):
return score
# If Minimizer has won the game return his/her
# evaluated score
if (score == -10):
return score
# If... |
def find_best_move(board):
bestVal = MIN
bestMove = -1
# Traverse all cells, evaluate minimax function for
# all empty cells. And return the cell with optimal
# value.
for i in range(16):
# Check if cell is empty
if (board[i] == '-'):
# Make the move
bo... | This function handles a player's turn in a game, validating human input for player "X" and selecting strategic moves for AI player "O". It ensures valid positions, prevents overwriting, and updates the board with the player's symbol. | def handle_turn(player, board):
if player == "X":
print(player + "'s turn.")
position = input("Choose a number from 1-16: ")
valid_move = False
# prevents one player from over-writing his opponent's move
while not valid_move:
# limits selection to the grid
... |
def show_board(board):
"""
Displays the board in a 4x4 grid
"""
print(board[0] + " | " + board[1] + " | " + board[2] + " | " + board[3])
print(board[4] + " | " + board[5] + " | " + board[6] + " | " + board[7])
print(board[8] + " | " + board[9] + " | " + board[10] + " | " + board[11])
print(b... | This function manages a game loop for a turn-based game (like Tic-Tac-Toe). It displays the board, alternates players, tracks moves, checks for a win/draw after each move (starting from the 7th move), and declares the winner or a draw once the game ends. | def play_game(board):
global moves_made
show_board(board)
while game_is_still_on:
handle_turn(current_player, board)
moves_made += 1
# check if game is over after 7 moves
if moves_made >= 7:
check_if_game_over(board, False)
# give the other player a cha... |
def __get_team_id(self, team_name):
team_id = self.get_cache_value("team_id")
if team_id is None:
team = self.team_api.get_team(team_name=team_name)
team_id = team["id"]
self.set_cache_value("team_id", team_id)
return team_id
def __get_space_id(self, space_n... | The main task of the code is to retrieve tasks from a specified folder or list within a team's space. It obtains team, space, and folder IDs using private methods, then fetches tasks either by folder (if no list is specified) or by list. The function also measures and prints the time taken for each step, ensuring effic... | def get_tasks(self, team_name: str, space_name: str, folder_name: str, list_name):
start_time = time()
team_id = self.__get_team_id(team_name)
space_id = self.__get_space_id(space_name, team_id)
folder_id = self.__get_folder_id(folder_name, space_id)
print(f"Obter Folder --- {(... |
def train_with_set(self, training_set):
images, results = training_set
dataset = list(zip(images, results))
np.random.shuffle(dataset)
for img, result in dataset:
x = img
z = self.get_output(x)
# z is a 1d array of length 10, loops wont affect perform... | The code trains a model for a specified number of iterations, evaluating accuracy on a validation set each time. It tracks the best accuracy achieved, updates the model if improved, and stops early if perfect accuracy (1.0) is reached. The function returns a list of validation accuracies across iterations, including th... | def train(self, iterations):
tests = [self.best_accuracy]
for idx in range(iterations):
self.train_with_set(self.train_set)
accuracy = self.get_accuracy(self.valid_set)
if accuracy > self.best_accuracy:
self.best_accuracy = accuracy
sel... |
def install_package(package: str):
p = subprocess.run(["apt-get", "install", "--no-install-recommends", "-y", package])
if p.returncode != 0:
raise Exception(f"Installation of {package} failed")
def dkms_get_version(package: Package):
p = subprocess.run(["dkms", "status", package.dkms_name], capture... | The main task of the code is to generate Debian packages from configuration data. It iterates through each package in the provided config, installs the package using its Debian name, retrieves the DKMS version, and creates a Debian package with the config, package details, and DKMS version. This automates the process o... | def create_packages(config):
for package in config.packages:
install_package(package.debian_name)
dkms_version = dkms_get_version(package)
create_debian_package(config, package, dkms_version) |
def parse_config():
parser = argparse.ArgumentParser()
parser.add_argument("config_file")
args = parser.parse_args()
with open(args.config_file, 'r') as f:
config = yaml.safe_load(f)
packages = list()
for debian_name in config["packages"].keys():
packages.append(Package(debian_na... | The code's main task is to automate a setup process by parsing a configuration, setting up a local repository, installing a kernel, and generating packages. It handles exceptions by logging errors and exiting with a non-zero status to indicate failure. | def main():
try:
config = parse_config()
setup_local_repo(config)
install_kernel(config)
create_packages(config)
except Exception as e:
logging.exception(e)
exit(1) |
def _check_exists(self) -> bool:
return all(
check_integrity(os.path.join(self.raw_folder, os.path.splitext(os.path.basename(url))[0]+os.path.splitext(os.path.basename(url))[1]))
for url, _ in self.resources
)
def mkdirs(dirpath):
try:
os.makedirs(dirpath)
except ... | The code's main task is to download and process the FEMNIST dataset. It checks if data exists in the processed folder; if not, it creates directories, downloads files from specified URLs with MD5 validation, extracts them, and moves the training/test files to the processed folder for use in machine learning tasks. | def download(self):
"""Download the FEMNIST data if it doesn't exist in processed_folder already."""
import shutil
if self._check_exists():
return
mkdirs(self.raw_folder)
mkdirs(self.processed_folder)
# download files
for url, md5 in self.resources:... |
def getHistoryInsSD(link, start = 'new'):
fighter = getHTMLSD(link)
historyFull = None
for i in fighter.find_all('div', {'class': 'module fight_history'}):
if 'Fight History - Pro' == i.find_all('h2')[0].text:
historyFull = i
historyIns = historyFull.find_all('tr')[1:]
if start =... | The main task of the code is to retrieve and compile detailed fight statistics for a fighter's recent matches into a structured DataFrame. It extracts data such as fighter attributes, opponent details, event names, and fight outcomes (win/loss/draw) with result types (decision/KO/submission). The function processes HTM... | def getFightsSD(fighterALink, sex, ins = 1):
columns = ['ID',
'Aname', 'AisMale', 'Aage', 'Aheight', 'Aweight', 'AtimePro', 'AtimeUFC',
'Awins', 'Alosses',
'AwinStk','AwinGra',
'AwinDec', 'AwinOtr',
'AlossStk', 'AlossGra',
'Al... |
def resetInfo():
global age
global height
global weight
global timePro
global timeUFC
global wins
global losses
global winStk
global winGra
global winDec
global winOtr
global lossStk
global lossGra
global lossDec
global lossOtr
global ufcCount
global a... | The main task of the code is to generate a structured DataFrame containing detailed statistics of two fighters (A and B) for each upcoming fight, including their age, weight, fight record, UFC history, and outcome details (result type, method, and duration) based on event data. It aggregates this information by iterati... | def getUpcomingFightSD(f1, f2, sex, ev = 'None'):
global age
global height
global weight
global timePro
global timeUFC
global wins
global losses
global winStk
global winGra
global winDec
global winOtr
global lossStk
global lossGra
global lossDec
global lossOtr... |
def getHistoryInsUG(link, start = 'new'):
fighter = getHTMLUG(link)
histories = fighter.find_all('div', {'class': 'section-wrapper mma-record'})
historyFull = histories[0].find_all('tbody')[0].find_all('tr')
for ins in histories:
if 'UFC' in str(ins):
historyFull = ins.find_all('tbod... | The main task of the code is to retrieve and process fight data for a given fighter (A) from a UFC-related source, extracting detailed statistics for both fighters (A and B) involved in each fight. It compiles this data into a structured DataFrame, including attributes like names, win/loss records, fight outcomes (e.g.... | def getFightsUG(fighterALink, sex, ins = 1):
columns = ['ID',
'Aname', 'AisMale', 'Aage', 'Aheight', 'Aweight',
'Awins', 'Alosses',
'AtimePro', 'AtimeUFC',
'AwinStk','AwinGra',
'AwinDec', 'AwinOtr',
'AlossStk', 'AlossGra',
... |
def getHistoryIns(html, start = 'new'):
fighter = html
historyFull = None
for i in fighter.find_all('div', {'class': 'module fight_history'}):
if 'Fight History - Pro' == i.find_all('h2')[0].text:
historyFull = i
historyIns = historyFull.find_all('tr')[1:]
if start == 'new':
... | This function extracts and compiles fight records from a fighter's HTML data into a structured DataFrame. It retrieves fight details like opponent stats, event names, and results (win/loss/NC), appending them to a DataFrame with columns for both fighters' attributes, fight outcomes, and event information. The function ... | def getFights(fighterA_html, sex, ins = 1):
columns = ['Aname',
'Adate_born',
'Ais_male',
'Aheight',
'Aweight',
'Adate_of_fight',
'Ais_UFC',
'Aprev_fight_length',
'Awin_stk',
... |
def getHistoryIns(html, start = 'new'):
fighter = html
historyFull = None
for i in fighter.find_all('div', {'class': 'module fight_history'}):
if 'Fight History - Pro' == i.find_all('h2')[0].text:
historyFull = i
historyIns = historyFull.find_all('tr')[1:]
if start == 'new':
... | The main task of the code is to compile historical and upcoming fight data for two fighters into a structured DataFrame. It extracts fighter statistics (e.g., name, birth date, height, win/loss records) from HTML data, processes fight histories, determines fight outcomes, and appends rows to a DataFrame. It also handle... | def getFights(fighterA_html, upcomingFighterB_html, date_of_upcoming_fight, sex, ins = 1):
columns = ['Aname',
'Adate_born',
'Ais_male',
'Aheight',
'Aweight',
'Adate_of_fight',
'Ais_UFC',
'Aprev_fight_len... |
def _create_cells(self):
for i in range(self.num_rows):
row = [Cell(0,0,0,0, self._win) for _ in range(self.num_cols)]
self._cells.append(row)
for i in range(self.num_rows):
for j in range(self.num_cols):
self._draw_cells(i, j)
def _break_entrance_and_... | This code initializes a maze structure by setting up grid parameters, creating cells, breaking walls recursively to form paths, and preparing for traversal. It validates the maze size, sets entrance/exit, and resets visited states. | def __init__(
self,
x1,
y1,
num_rows,
num_cols,
cell_size_x,
cell_size_y,
win=None,
seed=None
):
self.x1 = x1
self.y1 = y1
self.num_rows = num_rows
self.num_cols = num_cols
self.cell_size_x = cell_size_x
... |
def getCurrentEntropy(self, data):
label_dict = classCounts(data)
if label_dict["No"] * label_dict["Yes"] == 0:
# Pure state
return 0
p1 = label_dict["No"]/sum(label_dict.values()) # Pr of rows with Enjoy == "No"
p2 = 1 - p1
currentEntropy = -p1 * math.log... | This function recursively builds a decision tree by selecting the best attribute to split the data, creating child nodes for each subset, and terminating with leaf nodes when the data is pure or no attributes remain. It calculates entropy, checks base cases, splits data, and constructs branches using recursive calls. | def buildTree(self, remainingAttrSet, remainingData):
# Base cases : terminate if pure state/ no more question to ask
# Pure state
current_entropy = self.getCurrentEntropy(remainingData)
if current_entropy == 0:
return Leaf(remainingData)
# No question left
if... |
def trainGmm(self):
clusters = self.initializeClusters() # cluster info, such as mean, covariance
likelihoods = np.zeros((self.epoch, )) # log-likelihood of each epoch
scores = np.zeros((self.total_input, self.total_cluster)) # for each data point, the cluster with highest score is where it belo... | The main task of the code is to train a Gaussian Mixture Model (GMM), compare its parameters (means, amplitudes, covariances) with sklearn's implementation, and visualize clustering results. It computes cluster assignments, evaluates log-likelihoods, and plots clustered data alongside sklearn's output for validation an... | def main(self):
# my implementation
clusters, likelihoods, scores, sample_likelihoods = self.trainGmm()
mean = [cluster['mu_k'].tolist() for cluster in clusters]
amplitude = [cluster['pi_k'].tolist() for cluster in clusters]
covariance = [cluster['cov_k'].tolist() for cluster in ... |
def solvePrimalParameters(self):
G = np.array([[0., 0., 0.], [0., 1., 0.], [0., 0., 1.]]) + np.eye(3) * 1e-3
a = np.array([[0., 0., 0.]]).reshape((3, ))
inequality_C = np.c_[np.ones((100, 1)), self.X] * self.y.reshape(100, 1)
ineq_b = np.ones((100, ))
weights = solve_qp(G, a, ine... | The code's main task is to solve SVM kernel parameters based on the input type (Linear or nonlinear). For "Linear", it computes primal parameters, plots data, and visualizes the linear kernel. For other kernels, it solves dual parameters, calculates support vectors and bias, plots data (with adjustments for Polynomial)... | def solveKernel(self, kernel):
if kernel == "Linear":
bias, w1, w2, sv_index, value = self.solvePrimalParameters()
self.plotData(sv_index)
self.plotlinearKernel(bias, w1, w2)
return sv_index, bias, w1, w2
else:
alpha = self.solveDualParameters(... |
def SetMyLogger(MyName):
from logging import basicConfig, FileHandler, StreamHandler, getLogger
from os import isatty
LogFormat = ('[%(asctime)s] %(levelname)-8s %(name)-12s %(message)s')
if isatty(stdin.fileno()) and LogToFile == 1:
basicConfig(level=LogLevel, format=LogFormat, handlers=[FileHandler(LogFile), St... | The main task of the code is to initialize logging, establish a connection via OpenConnectionWindows(), subscribe to MQTT topics using a client, close the connection window, open a main window, and disconnect the client if connected. It manages logging, client lifecycle, and GUI transitions for an application, ensuring... | def main():
global logger, StatusList, Broker, UserName, Password, client, window_connection
logger = SetMyLogger(path.basename(__file__))
DefName=_getframe( ).f_code.co_name
logger.debug(DefName+'(): Logging active for me: '+str(path.basename(__file__)))
if OpenConnectionWindows():
lo... |
def translateToOrig (geom, origin=(0, 0)):
"""
Translate a shapely geometric object to the origin reference frame
Input:
- geom: Shapely gometric object
"""
# Find the minimum rotation rectangle
#geomMRR = geom.minimum_rotated_rectangle
geomMRR = geom.envelope
#... | The code transforms a geometric object through three steps: translation to origin, rotation relative to a given polygon, and scaling. It returns the scaled, rotated, and translated geometry. | def transform(geom, polygon = 0):
"""
Transfrom a geometric object (Translation, Rotation and scaling)
Input:
"""
# Translation
geomTrans = translateToOrig(geom)
# Rotation
rotdGeom = rotateRef(geomTrans, polygon=polygon)
# Scaling
scldGeom = scale(rotdGeom)
re... |
def checksum_ok(filename: str, checksum: str) -> bool:
"Check that a file conforms to a SHA256 checksum"
return checksum is None or sha256_file(filename) == checksum
def extract_zip(zip_file, dest_dir, csv_file, csv_checksum, info):
with zipfile.ZipFile(zip_file, "r") as z:
z.extractall(dest_dir)
... | The code fetches data files from sources specified in a JSON configuration, using a local cache. It checks file integrity via checksums, skips existing valid files, and downloads/extracts zipped files as needed. The function ensures data consistency by verifying hashes and managing cached versions efficiently. | def fetch(states):
# Load data sources file
sources_file = "data_sources.json"
with open(sources_file, "r") as f:
sources = json.load(f)
# Prepare local cache of downloaded files
dest_dir = "data"
os.makedirs(dest_dir, mode=0o770, exist_ok=True)
# Download/verify each required fil... |
def factorise_lookup(n):
i = prime_or_factor[n]
f=[]
while i :
f.append(i)
n//=i
i = prime_or_factor[n]
if n>1:
f.append(n)
return f
def factorise_large(n, maxBrentTime=1.0):
global brent_failures, brent_calls, brent_avoid, verbose
if verbose:
if verbose: print("calling factorise_l... | The function `factorise(n, maxBrentTime=1.0)` aims to decompose a number `n` into its prime factors. It employs a multi-step approach: checking precomputed small primes, using optimized C++/YAFU/factordb tools for large numbers, and falling back to algorithms like Pollard's Rho (Brent) or ECM for challenging cases. It ... | def factorise(n, maxBrentTime=1.0):
if n<=MAXLOOKUP:
return factorise_lookup(n)
if CPP_available and n<2**64:
return factoriseCPP(n)
factors=[]
for p in smallprimes:
while n%p==0:
factors.append(p)
n//=p
if n ==1:
return factors
if n <= MAXLOOKUP:
return factors+f... |
def read_ndjson(self, path: str):
data = []
with open(path, "r") as reader:
for line in reader:
data.append(json.loads(line))
self.ndjson_data = data
return data
def separate_domains(self):
for line in self.ndjson_data:
if line["type"] == "... | The main task of the code is to extract hostnames from a given NDJSON file by sequentially reading the data, separating domains, attaching subdomain events, identifying subdomains, linking ports, and finally returning the collected hostnames. | def parse_to_host_names(self, path: str):
self.read_ndjson(path)
self.separate_domains()
self.attach_sub_events()
self.find_sub_events()
self.attach_ports()
return self.hostnames |
def show_game_rules(self):
print('********************************************************\n'
'Rock, Paper, Scissors! - "jian dao, shi tou, bu"\n'
'********************************************************\n\n'
'This game will continue until you type "quit,"\n'
... | The main task of the code is to manage a game's lifecycle: clear the screen, display rules, collect player names, start the game, loop through rounds until the game ends, print scores, declare the winner, and reveal the opponent's strategy. It orchestrates game initialization, progression, and conclusion with delays an... | def play_game(self):
os.system('clear')
self.show_game_rules()
self.get_player_names()
print("\n")
print("Game start!")
time.sleep(2)
while not self.game_over():
self.play_round()
print("\n")
print("Game over!")
time.sl... |
def estimate_pose(depth, mask, camera, view_matrix):
"""
In:
depth: Numpy array [height, width], where each value is z depth in meters.
mask: Numpy array [height, width], where each value is an obj_id.
camera: Camera instance.
view_matrix: Numpy array [16,] of float64, representi... | The main task of the code is to perform 3D object pose estimation for validation or test sets using depth maps and masks. It processes each scene, estimates poses with predicted and (for validation) ground-truth masks, exports reconstructed 3D meshes (PLY files), and saves pose data in .npy format. The code ensures dir... | def main():
args = parser.parse_args()
if args.val:
dataset_dir = "./dataset/val/"
print("Pose estimation for validation set")
elif args.test:
dataset_dir = "./dataset/test/"
print("Pose estimation for test set")
else:
print("Missing argument --val or --test")
... |
def load_directory_paths() -> Tuple[str, str]:
"""
Loads the directory paths from the YAML file.
Returns:
Tuple[str, str]: The directory paths for the database and sorting publications.
"""
if not os.path.exists("config.yaml"):
create_yaml_file()
with open("config.yaml", "r") a... | The main task of the code is to provide a command-line interface for managing a publication database, allowing users to add, search, view, modify, remove publications, generate BibTeX files, display the entire database, or exit the program. It interacts with a `Pub` class to handle data operations and maintains a loop ... | def main() -> None:
"""The main function to run the script."""
lib_dir, _ = load_directory_paths()
pub = Pub(lib_dir)
fancy_welcome_message()
while True:
print_commands()
command = get_command()
if command == "add" or command == "a":
handle_add_command(pub)
... |
def end_round(user_data):
del user_data['code']
def check_for_another_game(bot, update, user_data, query):
bot.edit_message_reply_markup(reply_markup=[],
chat_id=query.message.chat_id,
message_id=query.message.message_id)
if query.data == 'Ja':
return start_round(bot, update, user_data, qu... | The main task of the code is to handle user guesses in a game, likely Mastermind, by updating the game state, validating inputs, providing feedback on correct colors/positions, and managing game progression (win/loss, new rounds, or ending the game). It processes callback queries, tracks user data, and interacts with t... | def make_guess(bot, update, user_data):
bot.answer_callback_query(update.callback_query.id)
print('{user} make_guess round {rounds}'.format(
user=user_data.get('user').first_name if user_data.get('user') else '',
rounds=user_data.get('ronde', ''),
))
query = update.callback_query
if quer... |
def generate_players(players_count: int, salt: str, key_len: int, bonus: bool):
return [generate_player(index, salt, key_len, bonus) for index in range(players_count)]
def tell_color_name(index: int) -> str:
return list(colors.keys())[index % len(colors.keys())]
def generate_qr_codes(players: List[Player], base... | The main task of the code is to generate player data based on configuration parameters, print each player's index, key, and color name, and create QR codes for the players using a specified base URL and output directory. | def main(config):
players = generate_players(int(config.players), config.salt, int(config.key_len), config.bonus)
[print(f'{player.index};{player.key};{tell_color_name(player.index)}') for player in players]
generate_qr_codes(players, config.base_url, config.output_dir, config.bonus) |
def check_atlases(atlases):
"""
Checks atlases
Parameters
----------
atlases : str or list
Name of atlas(es) to use
Returns
-------
atlases : list
Names of atlas(es) to use
"""
if isinstance(atlases, str):
atlases = [atlases]
elif isinstance(atlases,... | The function retrieves the label of a given MNI coordinate from a specified atlas. For probabilistic atlases (e.g., Juelich, Harvard-Oxford), it applies a probability threshold, returning a list of [probability, label] pairs sorted by confidence. For deterministic atlases, it returns a single label. It handles coordina... | def read_atlas_peak(atlastype, coordinate, prob_thresh=5):
"""
Returns label of `coordinate` from corresponding `atlastype`
If `atlastype` is probabilistic, `prob_thresh` determines (in percentage
units) the threshold to apply before getting label of `coordinate`
Parameters
----------
atla... |
def check_atlases(atlases):
"""
Checks atlases
Parameters
----------
atlases : str or list
Name of atlas(es) to use
Returns
-------
atlases : list
Names of atlas(es) to use
"""
if isinstance(atlases, str):
atlases = [atlases]
elif isinstance(atlases,... | The function `read_atlas_cluster` identifies brain regions (labels) overlapping with a given cluster from a specified atlas, returning their overlap probabilities. For probabilistic atlases, it applies a threshold (`prob_thresh`) to filter results. It processes the cluster's coordinates, maps them to atlas labels, calc... | def read_atlas_cluster(atlastype, cluster, affine, prob_thresh=5):
"""
Returns label of `cluster` from corresponding `atlastype`
If `atlastype` is probabilistic, `prob_thresh` determines (in percentage
units) the threshold to apply before getting label of `coordinate`
Parameters
----------
... |
def get_peak_coords(clust_img):
"""
Gets MNI coordinates of peak voxels within each cluster of `clust_img`
Parameters
----------
clust_img : 4D-niimg_like
4D image of brain regions, where each volume is a separated cluster
Returns
------
coords : (N, 3) numpy.ndarray
Co... | The function identifies peaks (or sub-peaks) in a 3D cluster image, calculates their coordinates, values, and cluster volume, and maps these peaks to neuroanatomical regions using a specified atlas and probability threshold. It returns structured data including peak locations, values, cluster volume, and anatomical lab... | def get_peak_data(clust_img, atlas='default', prob_thresh=5,
min_distance=None):
"""
Parameters
----------
clust_img : Niimg_like
3D image of a single, valued cluster
atlas : str or list, optional
Name of atlas(es) to consider for cluster analysis. Default: 'default... |
def get_peak_coords(clust_img):
"""
Gets MNI coordinates of peak voxels within each cluster of `clust_img`
Parameters
----------
clust_img : 4D-niimg_like
4D image of brain regions, where each volume is a separated cluster
Returns
------
coords : (N, 3) numpy.ndarray
Co... | The function `get_cluster_data` extracts key information about a 3D cluster image, including its peak coordinates, average value, volume, and overlap percentages with neuroanatomical regions from a specified atlas. It processes the input image, computes voxel volume, identifies cluster metrics, and maps the cluster aga... | def get_cluster_data(clust_img, atlas='default', prob_thresh=5):
"""
Parameters
----------
clust_img : Niimg_like
3D image of a single, valued cluster
atlas : str or list, optional
Name of atlas(es) to consider for cluster analysis. Default: 'default'
prob_thresh : [0, 100] int, ... |
def check_atlases(atlases):
"""
Checks atlases
Parameters
----------
atlases : str or list
Name of atlas(es) to use
Returns
-------
atlases : list
Names of atlas(es) to use
"""
if isinstance(atlases, str):
atlases = [atlases]
elif isinstance(atlases,... | The main task of the code is to extract cluster and peak information from a 4D brain image (`stat_img`) by applying thresholds, clustering, and mapping to anatomical regions defined by an `atlas`. It returns two dataframes: one detailing cluster statistics (e.g., peak coordinates, mean value, volume) and another listin... | def get_statmap_info(stat_img, cluster_extent, atlas='default',
voxel_thresh=1.96, direction='both', prob_thresh=5,
min_distance=None):
"""
Extract peaks and cluster information from `clust_img` for `atlas`
Parameters
----------
stat_img : Niimg_like
... |
def CfCGMY(t,C,G,M,Y,sigma,r,X0=0):
i = np.complex(0.0, 1.0) #assigning i=sqrt(-1)
varPhi = lambda u: np.exp(t * C *stFunc.gamma(-Y)*( np.power(M-i*u,Y) - np.power(M,Y) + np.power(G+i*u,Y) - np.power(G,Y)))
omega = -1/t * np.log(varPhi(-i))
cF = lambda u: varPhi(u) * np.exp(i*u*X0 + i*u* ( r+ omega -0.... | The code calculates European call option prices using the COS method under the CGMY model, plots results, and validates via Monte Carlo simulations by inverting the CDF for random sampling. It sets parameters for the model, computes characteristic functions, evaluates option values across strike prices, and compares an... | def mainCalculation():
#define the range for the expansion points
N = 4096
CP = OptionType.CALL
# setting for the VG-BM model
S0 = 1.0
r = 0.0
sigma = 0.1
T = 2.0
# CGMY
C = 1.0
G = 1.0
M = 5.0
Y = 0.5
# setting for the COS method
L = 15... |
def HW_r_0(P0T,lambd,eta):
# time-step needed for differentiation
dt = 0.0001
f0T = lambda t: - (np.log(P0T(t+dt))-np.log(P0T(t-dt)))/(2*dt)
# Initial interest rate is a forward rate at time t->0
r0 = f0T(0.00001)
return r0
def GeneratePathsHWEuler(NoOfPaths,NoOfSteps,T,P0T, lambd, eta): ... | The code performs a Monte Carlo simulation to price Zero-Coupon Bonds (ZCB) under the Hull-White model, comparing Monte Carlo results with analytical solutions and market data. It generates interest rate paths, computes ZCB prices via path averaging, and plots the outcomes against exact market curves and analytical app... | def mainCalculation():
NoOfPaths = 20000
NoOfSteps = 500
lambd = 0.4
eta = 0.0075
# We define a ZCB curve (obtained from the market)
P0T = lambda T: np.exp(1-np.exp(0.4*T))
r0 = HW_r_0(P0T,lambd,eta)
T_end = 10
# Here we compute the price of ZCB directly ... |
def ChFHestonModel(r,tau,kappa,gamma,vbar,v0,rho):
i = np.complex(0.0,1.0)
D1 = lambda u: np.sqrt(np.power(kappa-gamma*rho*i*u,2)+(u*u+i*u)*gamma*gamma)
g = lambda u: (kappa-gamma*rho*i*u-D1(u))/(kappa-gamma*rho*i*u+D1(u))
C = lambda u: (1.0-np.exp(-D1(u)*tau))/(gamma*gamma*(1.0-g(u)*np.exp(-D1(u)*tau... | The code compares Euler and Almost Exact Simulation (AES) methods for pricing European options under the Heston model. It calculates exact prices using the COS method, generates simulated paths, and evaluates convergence by varying time steps. The results are plotted and analyzed for error against the exact solution, a... | def mainCalculation():
NoOfPaths = 100000
NoOfSteps = 500
# Heston model parameters
gamma = 1.0
kappa = 0.5
vbar = 0.04
rho = -0.9
v0 = 0.04
T = 1.0
S_0 = 100.0
r = 0.1
CP = OptionType.CALL
# First we define a range of strikes and check t... |
def nonterminal(var):
return "<" + var.lower() + ">"
def value_rules(values, prefix):
grammar = {}
for var in values.keys():
arg_name = nonterminal(prefix + "_" + var)
if DEEP_VALUES:
for value in values[var]:
g = deep_value_expansions(... | Your return
The code constructs a grammar from function calls, defining nonterminals for each function and its arguments. It generates production rules for function signatures, parameter names, and value options, merging them into a unified grammar. The start symbol points to all function calls, which are listed as n... | def mine_grammar_from_calls():
all_calls = "<call>"
grammar = {
"<start>": [all_calls],
}
function_nonterminals = []
for function_name in the_args.keys():
if function_name.startswith("_") or function_name.startswith("<"):
# Internal function
continue
... |
def _detect_rust_target(
self, forced_target_triple: Optional[str]
) -> Optional["_TargetInfo"]:
cross_compile_info = _detect_unix_cross_compile_info()
if cross_compile_info is not None:
cross_target_info = cross_compile_info.to_target_info()
if forced_target_triple i... | This function compiles a Rust extension into a shared library, handling cross-compilation and platform-specific configurations. It detects the target architecture, prepares build settings, executes Cargo or Rustc commands with appropriate flags, and locates the generated dynamic library. The result is a list of BuiltMo... | def build_extension(
self, ext: RustExtension, forced_target_triple: Optional[str]
) -> List["_BuiltModule"]:
target_info = self._detect_rust_target(forced_target_triple)
if target_info is not None:
target_triple = target_info.triple
cross_lib = target_info.cross_lib... |
def build_extension(
self, ext: RustExtension, forced_target_triple: Optional[str]
) -> List["_BuiltModule"]:
target_info = self._detect_rust_target(forced_target_triple)
if target_info is not None:
target_triple = target_info.triple
cross_lib = target_info.cross_lib... | This function builds a Rust extension for the specified platform. If on macOS with both x86_64 and arm64 ARCHFLAGS, it compiles separate binaries for each architecture, combines them into a universal2 fat binary, and installs the result. Otherwise, it builds and installs the extension directly for the target platform. | def run_for_extension(self, ext: RustExtension) -> None:
assert self.plat_name is not None
arch_flags = os.getenv("ARCHFLAGS")
universal2 = False
if self.plat_name.startswith("macosx-") and arch_flags:
universal2 = "x86_64" in arch_flags and "arm64" in arch_flags
if ... |
def get_tracks_main(C, NC, TOKEN):
headers = {
'Authorization': 'Bearer {token}'.format(token=TOKEN)
}
# base URL of all Spotify API endpoints
BASE_URL = 'https://api.spotify.com/v1/'
# actual GET request with proper header
C_items = return_tracks_playlist(C, TOKEN)
NC_items = retu... | The code synchronizes two Spotify playlists (C and NC) by continuously monitoring and updating their tracks. It removes duplicates, identifies added/deleted tracks, and balances the playlists by adding missing tracks to NC and removing them from C. The process repeats at intervals to maintain synchronization, ensuring ... | def main():
# Playlists IDs
C = "3xFQXlI7Xf93UzQXpuFqEs"
NC = "28bNg1uPJd9kA4v9F6NuwH"
saved_C_items, saved_NC_items = get_tracks_main(C, NC, refresh_access_token())
# time.sleep(10)
missingTracks = []
while True:
# Refresh token to keep access
TOKEN = refresh_access_token()
... |
def get_input(locations: list):
id = input("Enter your id number: ")
phone_number = input("Enter your phone number: ")
for i in range(len(locations)):
print(str(i), locations[i]['LocationName'])
locations_list = []
print("Enter the numbers of the wanted locations. if you want to stop type '... | The main task of the code is to concurrently monitor multiple services by launching separate threads for each location. It retrieves user-specified locations, iterates through them, and starts a thread to listen to each service using its ID and name. Threads are initiated with a 2-second delay between each, followed by... | def main():
user_data = get_input(get_locations())
locations = user_data['locations']
for location in locations:
threading.Thread(target=lambda: listen_to_service(location['ServiceId'], location['LocationName'])).start()
sleep(2)
sleep(1000000) |
def create_group_widget():
frame = Frame(root)
frame.place(relx=0.6, rely=0.3, anchor=N)
frame.config(background="#FFE2FF")
try:
destroy_groupings()
except:
pass #if there is an error, the widgets dont exist at all and dont need to be destroyed.
global groupings
global groupw... | This function sets the MultiMC path by retrieving user input, validates the path's existence, writes it to a file, disables UI elements, and initializes MultiMC-related components like groups, radio buttons, and sync features. If the path is invalid, it displays an error message. | def use_mc_manual():
global multipath
multipath = findmc.get()
if path.exists("".join(findmc.get()) + "\\instances"):
f = open("mcpath.txt", "w")
f.write(findmc.get())
f.close()
try:
usebutton_browse.config(state="disabled")
mc_label.config(text=findm... |
def create_group_widget():
frame = Frame(root)
frame.place(relx=0.6, rely=0.3, anchor=N)
frame.config(background="#FFE2FF")
try:
destroy_groupings()
except:
pass #if there is an error, the widgets dont exist at all and dont need to be destroyed.
global groupings
global groupw... | The function `use_mc_browse` validates a MultiMC directory path, writes it to a config file, disables UI elements, and initializes application components by checking if the path contains an "instances" folder. If valid, it proceeds with UI setup; otherwise, it alerts the user of an incorrect path. | def use_mc_browse():
global multipath
multipath = directory
check = "".join(directory) + "\\instances"
if path.exists(check):
f = open("mcpath.txt", "w")
f.write(directory)
f.close()
usebutton_browse.config(state="disabled")
usebutton_manual.config(state="disabled... |
def kalmanFilter(y, year,P1,sigma2_epsilon,sigma2_eta):
z = 1.645
v = np.zeros(len(y))
a = np.zeros(len(y))
P = np.zeros(len(y))
F = np.zeros(len(y))
K = np.zeros(len(y))
P[0] = P1
for i in range(len(y)):
v[i] = y[i] - a[i]
F[i] = P[i] + sigma2_epsilon
K[i] = P[i]... | The code performs time series analysis on the Nile dataset using Kalman filtering techniques, including initialization, state-space modeling, smoothing, disturbance decomposition, simulation, forecasting future values, missing data handling, and parameter estimation. It applies Kalman filter and smoother algorithms to ... | def main():
df = pd.read_excel('C:/Users/rafam/Downloads/EOR/Master/P4/TS/Assignment 1/Nile.xlsx')
year = df.iloc[:,0]
y = df['Nile'].to_numpy()
#initialization
P1 = 10e6
sigma2_epsilon = 15099
sigma2_eta = 1469.1
df1 = df
original_years = df1.iloc[:, 0].tolist()
new_years =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.