dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def crawl(directory):
"""
Parse a directory of HTML pages and check for links to other pages.
Return a dictionary where each key is a page, and values are
a list of all other pages in the corpus that are linked to by the page.
"""
pages = dict()
# Extract all links from HTML files
for f... | The code calculates PageRank for a web corpus using two methods: sampling and iteration. It first validates input, crawls the corpus, computes ranks via sampling with a specified number of samples, and prints results. Then, it calculates ranks iteratively and prints them, comparing both approaches for each page in sort... | def main():
if len(sys.argv) != 2:
sys.exit("Usage: python pagerank.py corpus")
corpus = crawl(sys.argv[1])
ranks = sample_pagerank(corpus, DAMPING, SAMPLES)
print(f"PageRank Results from Sampling (n = {SAMPLES})")
for page in sorted(ranks):
print(f" {page}: {ranks[page]:.4f}")
... |
def simplest_cb(img, percent):
if percent <= 0:
percent = 5
img = np.float32(img)
halfPercent = percent/200.0
channels = cv2.split(img)
results = []
for channel in channels:
assert len(channel.shape) == 2
height, width = channel.shape
vec_size = width * height
... | The code enhances an image using CLAHE (Contrast Limited Adaptive Histogram Equalization) and weighted fusion. It first checks if a preprocessing step (`simplest_cb`) is applied based on the `check` parameter. The image is converted to the Lab color space, and the L-channel is enhanced with CLAHE. Weights are calculate... | def enhance(image, level,check):
if check == 1:
img1 = simplest_cb(image, 5)
else :
img1 = image
img1 = np.uint8(img1)
LabIm1 = cv2.cvtColor(img1, cv2.COLOR_BGR2Lab);
L1 = cv2.extractChannel(LabIm1, 0);
# Apply
result = applyCLAHE(LabIm1, L1)
img2 = result[0]
L2 = re... |
def fitness(self, individual):
"""Evaluate the fitness of an individual."""
# Get the current analysis data
data = self.current_analysis_data
# Start with a base fitness score
fitness_score = 0
# Variables to track sustained good behavior
sustained_speed_bonus ... | This code runs a genetic algorithm for a specified number of generations, evaluating population fitness, evolving new generations, tracking best solutions, saving data, and visualizing results. It updates plots, stores historical data, and finalizes the road map after execution. | def run(self, generations):
"""Run the genetic algorithm for a number of generations."""
for generation in range(self.current_generation, self.current_generation + generations):
# Evaluate the fitness of each individual in the population
fitness_values = [self.fitness(ind) for in... |
def query_api(page):
ENDPOINT = f'https://chain.api.btc.com/v3/block/latest/tx?page={page}'
try:
with urlopen(ENDPOINT) as response:
return json.loads(response.read().decode('utf-8'))
except urllib.error.HTTPError as e:
if e.code != 429:
raise e
log.info(
... | The main task of the code is to continuously query an API for blockchain data, process new blocks/transactions, and send them to a server. It handles pagination, skips already-processed blocks by waiting for updates, validates transaction consistency, and ensures all transactions are successfully processed by the serve... | def main():
"""
Define logic for querying the API and processing reponse data.
"""
WAIT_FOR_NEW_PAGE = 3
WAIT_FOR_NEW_BLOCK = 60 * 5
seen_blocks = set()
page = 1
while True:
response = query_api(page)
total = total_pages(response)
log.info(f'Querying page: {page}... |
def grad(f,x):
'''
CENTRAL FINITE DIFFERENCE CALCULATION
'''
h = np.cbrt(np.finfo(float).eps)
d = len(x)
nabla = np.zeros(d)
for i in range(d):
x_for = np.copy(x)
x_back = np.copy(x)
x_for[i] += h
x_back[i] -= h
nabla[i] = (f(x_for) - f(x_back))/(... | The code implements the Limited-memory BFGS (L-BFGS) optimization algorithm to find the optimal solution of a function $ f $. It iteratively updates the solution using gradient information and stored vectors of past gradients and steps. The algorithm employs a line search for step size, maintains a history of $ m $ pre... | def L_bfgs(f, x0, max_it, m):
'''
INPUTS:
f: function to be optimised
x0: intial guess
max_it: maximum iterations
OUTPUTS:
x: the optimal solution of the function f
'''
d = len(x0) # dimension of problem
nabla = grad(f,x0) # initial gradient
x = x0[:]
... |
def update_data_split(source, data_dir):
"""Match the nuclear segmentation training data split to the tracking split"""
# Load all data splits
X, y, meta, original_split = [], [], [], []
for split in {"train", "test", "val"}:
with np.load(os.path.join(data_dir, f"{split}.npz"), allow_pickle=True... | (The main task of the code is to train a nuclear segmentation model using specified parameters, data paths, and training configurations. It loads tracking data, prepares training/validation generators, trains the model with a given backbone architecture, and saves the trained model and training metrics. The function ha... | def main(
model_path: Annotated[
str, typer.Option(help="Path to save segmentation model")
] = "NuclearSegmentation",
metrics_path: Annotated[
str, typer.Option(help="Path to save training metrics")
] = "metrics.yaml",
train_log: Annotated[
str, typer.Option(help="Path for cs... |
def check_keydown_events(event, infrompy_settings, screen, ship, bullets, stats):
"""Respond to keypresses."""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
elif event.key == pygame.K_p:
if stats.game_active:
... | The function `check_events` processes user inputs and game events in a Pygame application. It handles quitting the game, key presses (e.g., movement, shooting), key releases, and mouse clicks on the play button. Events trigger actions like updating ship movement, firing bullets, starting the game, and updating game sta... | def check_events(infrompy_settings, screen, ship, bullets, stats, score_board, play_button, aliens):
# Respond to key presses and mouse events
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_events... |
def check_fleet_edges(infrompy_settings, aliens):
""" Respond if any aliens have reched the edge of the screen. """
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(infrompy_settings, aliens)
break
def ship_hit(infrompy_settings, stats, score_board, s... | The main task of the code is to update alien positions, check for collisions between aliens and the ship, and detect when aliens reach the screen's bottom. It handles fleet edge detection, alien movement, collision response, and bottom-boundary checks to manage game events like ship hits and game-over conditions. | def update_aliens(infrompy_settings, aliens, ship, stats, score_board, screen, bullets):
""" Check if the fleet has reached the edge and then update the position of all aliens """
check_fleet_edges(infrompy_settings=infrompy_settings, aliens=aliens)
aliens.update()
# Look for alien-ship colision
if... |
def _extract_time_series_at_location(self, lat, lon, years=None, ref_period=DEFAULT_REFERENCE_PERIOD):
"""
Read the data from the data files.
Return a dictionary containing keys:
- temp_series: the extracted temperature series
- demeaned_temp_series: the temperature serie... | The main task of the code is to generate a climate stripes visualization and return a pandas DataFrame containing temperature data and corresponding colors. It fetches temperature data for a given location, processes it to normalize values, maps them to a colormap, creates a vertical stripe plot, and stores the results... | def create(self, lat, lon, n_colours=N_COLOURS, cmap_name=DEFAULT_CMAP, time_range=None,
output_file="climate-stripes.png", range_buffer=0.2):
"""
Creates both a plot and a dataset (as a `pandas DataFrame`) based on input requirements.
NOTE: range_buffer can be modified ... |
def run_bias():
"""
runs the experiment with bias as variable
:return: nothing
"""
data_frame = pd.DataFrame()
parameters = []
values = []
segregations = []
times = []
bias = DEFAULT_BIAS
while bias <= 1:
yellow = EthnicGroup(DEFAULT_Y_NAME, DEFAULT_Y_VALUE, DEFAUL... | The function sequentially executes four experiments (bias, diversity, ratio, occupation), combines their resulting DataFrames into a single dataset, and exports the consolidated data to a CSV file named 'experiment_result.csv' | def run_series():
"""
this function runs all the experiment in a row, one after the other, and creates a proper csv
:return:
"""
df1 = run_bias()
df2 = run_diversity()
df3 = run_ratio()
df4 = run_occupation()
df = pd.concat([df1, df2, df3, df4], ignore_index=True)
df.to_csv("ex... |
def __check_for_satisfaction(self, location, my_value=None):
"""
:param location: tuple with the location inspected
:param my_value - if we check the location for an existing fella, this argument will contain it's value
:return: True if satisfied at the current location, false else
... | This code implements a Schelling model iteration to check and resolve citizen dissatisfaction by moving unhappy agents. It identifies unsatisfied locations, filters mobile agents, and attempts to relocate them. The loop returns True if all unhappy agents are successfully moved, otherwise False. | def __schelling_loop(self):
"""
here is the iteration itself
:return:
"""
location_list = [x for x in self.__location_list if x not in self.__available_space]
unhappy = []
while location_list:
# here we randomly choose location on the board
... |
def book_operations():
print("Book Operations:")
while True:
book_menu_choice = input("1. Add a new book\n2. Borrow a book\n3. Return a book\n4. Quit\n")
if book_menu_choice == "1":
title, author, isbn, genre, publication_date, publisher = get_book_info()
new_book = creat... | The main task of the code is to display a library management system's main menu, allowing users to select operations related to books, members, catalogs, authors, or genres. It processes user input by calling corresponding functions for each choice, loops until "Quit" is selected, and handles invalid inputs by promptin... | def main_menu():
print(f"Welcome to the Library Management System!")
while True:
menu_choice = input(
"Main Menu:\n1. Book Operations\n2. Member Operations\n3.Catalog Operations\n4. Author Operations\n5. Genre Operations\n6. Quit\n")
if menu_choice == "1":
book_operations... |
def read_csv(files):
"""
Read a group of CSV properly formated CSV files and create the program data structures
:param files: dict {file#: ("root", "map_path", "hash_path")}
:return: (mappings dict, file_hash dict)
mappings dict: {(file#,line#): ("old_path", "int_path", "ext_path",...)}
file_ha... | The main task of the code is to validate file mappings and detect inconsistencies across multiple directories. It reads CSV data, compares it against actual file paths, checks for duplicates, and ensures equivalence between map structures and file hashes. Errors are collected and printed, focusing on verifying data int... | def main():
errors = []
# file_info = {file#: ("root", "map_path", "hash_path")}
file_info = {
1: (
r"\\inpakrovmdist\gisdata2",
None,
None,
), # r'data/int_hash'), # Destination: column 2/3 of the map files
2: (
r"\\inpakrovmdist\gis... |
def replica_find_rating_percentage(extracted_text, reference_text):
similarity_dict = find_cosine_similarity_with_keyword_repetition(reference_text, str(extracted_text))
similarity = similarity_dict['total_percentage']
return similarity
def replica_similarity_keyword(text, text2):
"""For total Words of ... | The code processes an event by extracting text and reference text from the request body, computes similarity ratings between them, and adjusts the rating based on an optional purpose parameter. It returns a JSON response with the original rating, adjusted rating, and purpose similarity percentage, handling errors for m... | def handler(event, context):
print(event)
event_body = event.get('body', None)
if not event_body:
return bad_request_error("Missing body")
request_body = json.loads(event_body)
extracted_text = request_body.get('text', None)
purpose = request_body.get('purpose', None)
reference_text ... |
def replica_find_rating_percentage(extracted_text, reference_text):
similarity_dict = find_cosine_similarity_with_keyword_repetition(reference_text, str(extracted_text))
similarity = similarity_dict['total_percentage']
return similarity
def replica_similarity_keyword(text, text2):
"""For total Words of ... | The code calculates a rating by comparing extracted text with a reference text, adjusts it based on a purpose keyword, and returns a combined similarity score. It converts texts to lowercase, computes initial similarity, identifies relevant phrases, and applies cosine similarity for purpose alignment, then rounds the f... | def rate_searched_text(extracted_text, reference_text, purpose):
extracted_text = extracted_text.lower()
reference_text = reference_text.lower()
ratings = replica_find_rating_percentage(extracted_text, reference_text)
word_result = extracted_text
if purpose:
purpose = purpose.lower()
... |
def parse_url(url):
url_text = pathlib.Path(url).suffix
list_of_doc = ['.txt', '.PDF', '.pdf', '.csv', '.odp', '.ods', '.odt', '.rtf', '.docx', '.doc', '.xlsx', '.xls',
'.xlr', '.pptx', '.xml']
if url_text not in list_of_doc:
response = requests.get(url, "lxml", headers={'User-Age... | The main task of the code is to process a DynamoDB event record by extracting data, validating the existence of a related search entry, parsing URL content, filtering text based on technology keywords, rating relevance, and moving valid results from one DynamoDB table to another while handling errors and communication ... | def process_event_record(record, conn):
result_id = int(record['dynamodb']['NewImage'][tmp_results_result_id]['N'])
search_id = int(record['dynamodb']['NewImage'][tmp_results_search_id]['N'])
url = record['dynamodb']['NewImage'][tmp_results_url]['S']
title = record['dynamodb']['NewImage'][tmp_results_ti... |
def initial_clamp(Clamping_dir):
add_plane()
objects_name = []
for obj in bpy.data.objects :
objects_name.append(obj.name)
if not '0000_Clamping' in objects_name :
import_ClampingSystem_obj(Clamping_dir)
def read_subBottomLength(csv_path):
subBottomLength = []
with open(csv_... | The code processes motor models by loading .obj files, configuring camera and clamp positions using CSV data, and generating point cloud scans. It iterates through motor files, applies transformations, and saves results in specified directories. The main task is to automate 3D scanning of motor components with varying ... | def main():
###################################################
###### parameter to set ##########
###################################################
csv_path = "E:\image_dataset_50\TypeB1"
########## the obj not to load ############
filters = ["Motor.obj"]
... |
def create_bbox_csv(save_dir):
if not os.path.exists(save_dir):
os.mkdir(save_dir)
save_dir = save_dir + '\\motor_3D_bounding_box.csv'
with open(save_dir, 'a+', newline='') as f:
csv_writer = csv.writer(f)
head = ["motor_id", "location_x", "location_x", "location_z", "height", "width... | The code processes 3D motor scans using Blender/Blensor, generating TOF data with varying noise levels (original, no-noise, or noisy). It saves processed numpy arrays after applying transformations (cutting, label changes, index reordering) and optionally exports scene/cuboid data. The function handles three motor sequ... | def scan_cut(save_dir, Motor_type, sequence_Motor, list_original, list_noNoise, validation_list, cam_info, motor_info,
save_scene=True, save_cuboid=True, scene_format='numpy', cuboid_format='numpy', save_bbox=False):
bpy.ops.object.select_all(action='DESELECT')
bpy.context.scene.camera = bpy.data.o... |
def _logistic_loss(self,X,y):
# """Given input data X and labels y, create the log-likelihood function.
# Parameters
# ----------
# X : nd-array, shape (n_samples, n_features)
# Training vector, where n_samples is the number of samples and n_features is the number of features... | This code implements a model selection algorithm using coordinate gradient ascent (CGA) with logistic regression. It minimizes a loss function via Newton's method (dogleg), computes likelihoods and information criteria (AIC/HDIC), and iteratively builds paths of model coefficients. The goal is to optimize model paramet... | def MPCGA(self, wn = 1, method='dogleg', tol=1e-8, options=None,ic = 'AIC'):
X = self.X
Y = self.Y
K = self.K
if self.one_path:
self.max_set = 1
self.max_split =1
n,p = X.shape
Jhat = ['beta0']+[None for _ in range(K)]
likelihood = [0 for ... |
def MPCGA_HDIC_Trim(self,c1 = 0.5,ic = 'AIC'):
self.MPCGA(wn = c1,ic = ic)
self.HDIC_Trim(wn = c1,ic = ic)
def cut_set(self,names,X_test):
##################
# generate cut_vector depending on X_test by names
##################
X = self.X
for i, name in en... | The function performs prediction using logistic regression on feature subsets from a trimmed path, applies model trimming based on log-likelihood thresholds, aggregates predictions via mode selection, and returns final predicted labels and probabilities for test data. | def MPCGA_pred(self,X_test,c1 = 1,Trim = False,Mtrim = False,ic = 'AIC'):
if Trim :
try:
path_trim = self.path_trim
except:
self.MPCGA_HDIC_Trim(c1 = c1,ic = ic)
path_trim = self.path_trim
else:
try:
path... |
def gram_schmidt(g, m, mu, B):
row = len(m)
for i in range(row):
# bi* = bi
b_i = get_vector(g, i)
b_i_star = b_i
set_matrix_vector(m, i, b_i_star)
for j in range(i):
# u[i][j] = (bi, bj*)/Bj
b_j_star = get_vector(m, j)
b_i = get_vect... | The code implements the **Lenstra-Lenstra-Lovász (LLL) lattice basis reduction algorithm**. It reduces a given matrix `n` representing a lattice basis into a shorter, more orthogonal basis using Gram-Schmidt orthogonalization and the Lovász condition. The algorithm iteratively applies reduction steps, swaps basis vecto... | def lll_reduction(n, lc=Fraction(3, 4)):
row = len(n)
col = len(n[0])
m = [ [Fraction(0) for j in range(col) ] for i in range(row)]
mu = [ [Fraction(0) for j in range(col) ] for i in range(row)]
g = [ [n[i][j] for j in range(col) ] for i in range(row)]
B = [ Fraction(0) for j in range(row) ]
... |
def discretize_density(density_map, ecotope_name):
# Discretize Density Map
# opt = input(
# "Enter an option:\n"
# "[1] for Floyd-Steinberg Error diffusion \n"
# "[2] for Ordered Dithering\n"
# "[0] to quit\n"
# )
opt = '1'
if opt == '0':
quit()
# Discret... | The code processes user-selected map data by loading height maps, road maps, and ecotopes, combining density maps to procedurally place assets while avoiding overlaps. It generates surface textures, creates JSON files for terrain and placements, and adds predefined landmarks for specific maps, outputting results with t... | def main():
global chosen_option
global config
# Load map names
with open(MAPS_FILENAME, 'r') as f:
cities = json.load(f)
option = int(input(utils.menu_str(cities))) - 1
if option == EXIT_CODE:
sys.exit("You selected to exit the program")
chosen_option = cities[option].lower(... |
def sample_z(self):
return normal(0, 1, (self.num_inducing_points, 1))
def sample_x(self, N):
total_size = self.xTr.shape[0]
if N > total_size:
raise Exception('Exceed size of data')
C = self.num_classes
num_samples = []
for i in range(C):
label_si... | The code implements stochastic gradient descent (SGD) optimization to maximize a probabilistic model's objective function. It iteratively updates parameters using sampled data points, tracks training/testing errors, and visualizes progress if verbose. The loop continues until reaching max iterations or gradient toleran... | def optimize(self):
if self.verbose > 0:
print('start optimizing...')
# initialize parameters
t = 0
z = self.sample_z()
indices = self.sample_x(int(self.alpha*self.xTr.shape[0]))
grad = self.gradient(z, indices)
val = self.objective(z, indices)
... |
def sample_z(self):
return normal(0, 1, (self.num_inducing_points, 1))
def sample_x(self, N):
total_size = self.xTr.shape[0]
if N > total_size:
raise Exception('Exceed size of data')
C = self.num_classes
num_samples = []
for i in range(C):
label_si... | This code performs stochastic variational inference (SVI) by iteratively optimizing model parameters via stochastic gradient descent. It initializes latent variables, samples data points, computes gradients, and updates parameters until convergence or max iterations. It tracks training/test scores, logs progress, and u... | def optimize(self):
if self.verbose > 0:
print('start optimizing...')
# initialize parameters
t = 0
z = self.sample_z()
indices = self.sample_x(int(self.alpha*self.xTr.shape[0]))
grad = self.gradient(z, indices)
val = self.objective(z, indices)
... |
def readConfigFile():
filename = "config.txt"
listOfAddresses = []
ipAddress = {}
location = {}
file = open (filename)
line = file.readline();
rows, columns = line.split()
for line in file:
ip, port = line.split()
ipAddress[int(port)] = ip
location [int(port)... | The main task of the code is to configure a controller by reading a configuration file, creating a 2D grid, establishing a network socket using a specified port/IP, and processing incoming data through the `getDataFromNetwork` function. It handles user input validation, initializes network communication, and prepares a... | def main():
x,y, ipAddress, locations = readConfigFile()
x = int (x)
y = int(y)
try:
myPort = input ("I am the controller\nwhat port do you want to use for controller? ")
except ValueError:
print ("did you enter a port number? ")
quit()
try:
myIPAddr = ipAddress[i... |
def distance_up(self, i: int, j: int) -> int:
start = {"i": i, "j": j, "h": self.height[i, j]}
return self.run_up(i, j, start)
def distance_down(self, i: int, j: int) -> int:
start = {"i": i, "j": j, "h": self.height[i, j]}
return self.run_down(i, j, start)
def distance_left(self, i: int... | The function calculates the product of four directional distances (up, down, left, right) from a given position (i,j) in a grid. It multiplies these distances together to determine a scenic score, likely representing the product of how far one can see in each cardinal direction. | def scenic_score(self, i: int, j: int) -> int:
du = self.distance_up(i, j)
dd = self.distance_down(i, j)
dl = self.distance_left(i, j)
dr = self.distance_right(i, j)
return du * dd * dl * dr |
def create_dir(self, name:str) -> None:
# create new dir
new_dir = Dir(name=name, parent=self.current)
self.current.childs += [new_dir]
print("Create Dir ", name)
def create_file(self, name: str, size: int ) -> None:
# create new file
new_file = File(name=name, parent=sel... | This code processes commands to create directories or files based on the 'Ls' command's results, splitting each entry into size/name or 'dir'/name, and changes directories using 'Cd' | def run_command(self, command: Command) -> None:
if isinstance(command, Ls):
for elt in command.rslt:
pre, suf = elt.split(" ")
if pre == "dir":
self.create_dir(name=suf)
else:
self.cre... |
def get_frame_by_index(self):
self.video_capture.set(1, self.listOfImages[self.iterator][0])
success, frame = self.video_capture.read()
self.changeLabelName(self.listOfImages[self.iterator][1])
self.checkIfSaved()
self.currnentIndexOfClass = self.listOfImages[self.iterator][1]
... | The code saves the currently displayed image frame as a PNG file in a class-specific directory, using a filename generated from command-line input and the image index. It deletes the current image, converts the frame to a PIL image, and triggers the next image display after saving. | def confirm(self):
selected = self.Lb1.curselection()
if len(selected) == 1:
self.currnentIndexOfClass = selected[0]
directoryNum = self.currnentIndexOfClass
_, frame = self.get_frame_by_index()
nameOfFile = sys.argv[1] + str(self.listOfImages[self.iterator][0]).zfill... |
def confirm(self):
selected = self.Lb1.curselection()
if len(selected) == 1:
self.currnentIndexOfClass = selected[0]
directoryNum = self.currnentIndexOfClass
_, frame = self.get_frame_by_index()
nameOfFile = sys.argv[1] + str(self.listOfImages[self.iterator][0]).zfill... | This code initializes a GUI with elements for image navigation and selection, including buttons for confirmation, image navigation (prev/next/delete), a listbox for classes, text labels, and an image display area. It sets up the interface for interacting with a list of images, tracking the current index, and displaying... | def initGuiElements(self):
frame = Frame(self.ws)
frame.pack(side=BOTTOM)
confirm = ttk.Button(frame, text='Confirm', command=lambda: self.confirm())
confirm.pack(side=LEFT)
self.Lb1 = Listbox(frame, selectmode=SINGLE, exportselection=False)
self.loadClassesToList()
... |
def confirm(self):
selected = self.Lb1.curselection()
if len(selected) == 1:
self.currnentIndexOfClass = selected[0]
directoryNum = self.currnentIndexOfClass
_, frame = self.get_frame_by_index()
nameOfFile = sys.argv[1] + str(self.listOfImages[self.iterator][0]).zfill... | The code defines a method `onKeyPress` that listens for keyboard input. When the 's' key is pressed, it calls `self.confirm()`; 'd' triggers `self.nextImgFunc()` for the next image; 'a' invokes `self.prevImgFunc()` for the previous image. The function maps specific keys to corresponding actions, enabling navigation or ... | def onKeyPress(self, event):
if event.char == 's':
self.confirm()
elif event.char == 'd':
self.nextImgFunc()
elif event.char == 'a':
self.prevImgFunc() |
def patient_train(audioFilePath):
audio = AudioSegment.from_file(audioFilePath)
length_ms = len(audio)
print(length_ms)
sub_length=math.floor(length_ms/5)
for i in range (0,5):
tx=i*sub_length
ty=((i+1)*sub_length)
tempaudio = audio[tx:ty]
tempaudio.export(f'conversat... | The main task of the code is to convert a conversation's audio into a structured dialogue format by first processing the patient's audio for training, splitting the conversation audio into segments, and then transforming those segments into a dialogue using speech-to-dialogue conversion. | def main_function(audioPatient, audioConversation): # input the patient's audio path and the conversation's audio path, and output the conversation in the form of a dialogue
patient_train(audioPatient)
temp_labelling=split_audio(audioConversation)
conversation = speech_to_dialogue(temp_labelling)
return... |
def find_most_informative_feature(train_data, label, class_list):
feature_list = train_data.columns.drop(label) #finding the feature names in the dataset
max_info_gain = -1
max_info_feature = None
for feature in feature_list: #for each feature in the dataset
feature_info_gain = calc_info_g... | The function `make_tree_Entropy` recursively constructs a decision tree using entropy-based feature selection. It identifies the most informative feature, generates a subtree for it, and updates the dataset. The tree is built by attaching subtrees to root or intermediate nodes, iterating through expandable branches ("?... | def make_tree_Entropy(root, prev_feature_value, train_data, label, class_list,root_feature):
if train_data.shape[0] != 0: #if dataset becomes enpty after updating
max_info_feature = find_most_informative_feature(train_data, label, class_list) #most informative feature
if(root_feature==max_info_featu... |
def find_most_Gini_feature(train_data, label, class_list):
feature_list = train_data.columns.drop(label) #finding the feature names in the dataset
max_info_gain = -1
max_info_feature = None
for feature in feature_list: #for each feature in the dataset
feature_info_gain = calc_Gini_gain(fea... | The function recursively constructs a decision tree using the Gini index to select the most informative feature at each node. It splits the dataset based on feature values, creates tree branches, and repeats the process for subsets of data until no further splits are possible. The tree is built by updating nodes iterat... | def make_tree_Gini(root, prev_feature_value, train_data, label, class_list):
if train_data.shape[0] != 0: #if dataset becomes enpty after updating
max_info_feature = find_most_Gini_feature(train_data, label, class_list) #most informative feature
tree, train_data = generate_sub_tree(max_info_feature,... |
def find_most_ME_feature(train_data, label, class_list):
feature_list = train_data.columns.drop(label) #finding the feature names in the dataset
max_info_gain = -1
max_info_feature = None
for feature in feature_list: #for each feature in the dataset
feature_info_gain = calc_ME_gain(feature... | The main task of the code is to recursively build a decision tree by selecting the most informative feature (max information gain), generating subtrees, and attaching them to the root or intermediate nodes. It avoids redundant feature reuse at the root level and processes expandable branches by recursively splitting da... | def make_tree_ME(root, prev_feature_value, train_data, label, class_list,root_feature):
if train_data.shape[0] != 0:
max_info_feature = find_most_ME_feature(train_data, label, class_list)
if(root_feature==max_info_feature):
return
tree, train_data = generate_sub_tree(max_info_f... |
def latest_build_image(self, project, image_key):
images = self._get_images_with_tags(
project=project,
image_key=image_key,
)
if images:
# first one is the latest
return self._image_info(images[0])
return None
def session(self, region=Non... | The main task of the code is to publish an EC2 image across specified AWS regions by copying it from a source image, applying tags, launch permissions, and end-of-life settings, then returning the resulting image IDs. It handles region selection, checks for existing images, manages access controls, and waits for image ... | def publish_image(self, ic):
log = logging.getLogger('publish')
source_image = self.latest_build_image(
ic.project,
ic.image_key,
)
if not source_image:
log.error('No source image for %s', ic.image_key)
raise RuntimeError('Missing source im... |
def get_default_region(self, vendor):
if vendor not in self._default_region:
self.get_regions(vendor)
return self._default_region.get(vendor)
def _get(self, path):
self._logger.debug("request: %s", path)
if not self._is_cache_valid(path):
while True: # to han... | The function retrieves credentials for a specified vendor and region. If no region is provided, it fetches the default region for the vendor. It then uses the `_get` method with the selected region's data to obtain and return the credentials. | def get_credentials(self, vendor, region=None):
if not region:
region = self.get_default_region(vendor)
return self._get(self.get_regions(vendor)[region]) |
def getVariables(tree_, elemTypeParam):
'''
Input: Python parse tree object
Output: All expressions as list of tuples
'''
final_list = []
for stmt_ in tree_.body:
for node_ in ast.walk(stmt_):
assignDict = node_.__dict__
if isinstance(node_, ast.Assign) :
... | The main task of the code is to trace data flow through a Python script by analyzing variable assignments and function calls. It constructs a mapping of values to variable names, combines this with function call relationships, and iteratively prints the chain of data transformations starting from an initial value, foll... | def checkFlow(data, code):
#TODO: Complete this method so that the output is 1000->val1->v1->res
if os.path.exists(code):
# create a dictionary to store the flow
flow = {}
full_tree = ast.parse( open( code ).read() )
# for every variable assignment, add it to the flow d... |
def pzl_Tx(T, Tx, RhoV, RhoC, RhoW, Pw):
ke = k_e(T)
h1 = 41840 * 8e-5 * pow((T - Ta)/r, 0.25)
h2 = 41840 * 5.422e-12 * eps * T**3
Qw = 2260871.99622 # J/kg
Sp = RhoV * dat[0,3] + RhoW * 4184 + RhoC * 1046
p1 = Tx * (LBR * Sp - (2 * Dp * pow(phi,1/3) * h2 * Tx/T)) / ke
p2 = pzl_V(T, RhoV)... | The function calculates a value by combining multiple terms derived from input parameters, including pressure (Pw), temperature (T, Tx), and density (RhoV, RhoC, RhoW). It computes intermediate variables (b1–b5) using auxiliary functions (pzl_Tx, pzl_W) and returns a result based on a formula involving these terms. The... | def pzl_Pw(T, Tx, RhoV, RhoC, RhoW, Pw):
b1 = Pw * pzl_Tx(T, Tx, RhoV, RhoC, RhoW, Pw) / T
b2 = 2 * 0.015 * (Pw - (1399.89 * T/Ta)) / (phi_w * r * d)
b3 = LBR * R * T * pzl_W(T, RhoW, Pw) / (phi_w * 0.018 * D_x(T))
b4 = LBR / D_x(T) + (0.25 * Tx / T)
b5 = Pw * Tx / T
return b5 - (b1 + b2 + b3) ... |
def parse_args():
parser = argparse.ArgumentParser(description="Generate C++ or Elm layout description from keyboard-layout-editor.com")
parser.add_argument("-i", "--input",
help="Path to the input file, generated by keyboard-layout-editor.com",
type=Path, require... | The code reads a JSON layout file, optionally additional LED descriptions, parses the layout data, and generates code in either C++ or Elm format based on command-line arguments, writing the output to a specified file. | def main():
args = parse_args()
if not os.path.isfile(args.input):
print(f"Input file {args.input} does not exist.")
sys.exit(1)
json_layout = None
with open(args.input) as f:
json_layout = json.load(f)
extra_led_descriptions = {"direction": 1, "extra_leds": []}
if args... |
def generate_population(self, population_size, chromosome_size):
population = []
for i in range(0, population_size):
chromosome = []
for j in range(0, chromosome_size):
self.populate(j, chromosome)
population.append(chromosome)
return populati... | The code implements an optimization algorithm that generates a population of solutions, evaluates their fitness, and iteratively improves them. It selects the fittest solution, then applies strategies like encircling, searching, or attacking based on random probability and a computed parameter `A`. New solutions are ge... | def optimize(self):
"""solutions randomly encircle, search or attack"""
population = self.generate_population(self.population_size, self.chromosome_size)
counter = 0
fitness = {}
for chromosome in population:
counter += 1
fitness_value = self.fitness(chro... |
def loadConfig(self, configFile):
# load
with open(configFile) as f:
self.config = json.load(f)
# set PhotonBatch, but still not know why.
if self.config["PhotonBatch"] > self.config["PhotonNum"]:
self.config["PhotonBatch"] = self.config["PhotonNum"]
... | The code initializes an object with project and session details, loads a configuration file, creates folders, and generates MCX input files if they are missing. It ensures necessary files for MCX hardware preview and configuration are present by creating them when they don't exist. | def __init__(self, projectName, sessionID):
self.projectName = projectName
self.sessionID = sessionID
self.loadConfig(os.path.join(self.projectName, self.sessionID, "config.json"))
self.createFolder()
if not os.path.isfile(os.path.join(self.projectName, self.sessionID, "output", ... |
def createFolder(self):
# set folder path
# main-path
self.session = os.path.join(self.config["OutputPath"], self.sessionID)
# sub-path
self.plot = os.path.join(self.session, "plot")
self.plot_mc2 = os.path.join(self.session, "plot_mc2")
self.post_... | The main task of the code is to initialize a session by loading configuration files, model parameters, and ensuring required directories/files (e.g., simulation results and MCX input) exist. It sets up the environment for further processing by checking and creating necessary files/folders based on the provided session ... | def __init__(self, sessionID):
# load session ID
self.sessionID = sessionID
# load config and related file
with open(os.path.join(self.sessionID, "config.json")) as f:
self.config = json.load(f)
with open(self.config["MCXInputPath"]) as f:
self.mc... |
def binary_search(q, coord, low, high, dimension, e):
# Check base case
if high >= low:
mid = (high + low) // 2
pmid = [coord[mid]]
qpoint = [q[dimension]]
# If element is present at the middle itself
if coord[mid] == q[dimension]: #we found it, we need the distance bef... | The code implements a k-nearest neighbors (k-NN) search by first extracting coordinates from nodes, partitioning them into dimensional arrays, using binary search to determine spatial ranges, and then applying brute-force search within these ranges to find the closest k neighbors. | def knn(root, node_list, k):
coords_array = []
d1 = []
d2 = []
d3 = []
for x in node_list:
coords_array.append(x.coords)
for y in coords_array:
d1.append(y[0])
d2.append(y[1])
d3.append(y[2])
for z in coords_array:
range = []
e1 = binary_sear... |
def get_output_raster(file):
img_type_map = {
'ersEx_ecos': 'ex_eco_gaps.tif',
'ersIn_ecos': 'in_eco_gaps.tif',
'ga50': 'ex_coll.tif',
'grsEx': 'ex_geo_gaps.tif',
'grsIn': 'in_geo_gaps.tif',
'thrsld': 'distr.tif'
}
for key in img_type_map:
if key in f... | This function recursively processes .tif raster files in input directories, copying them to output directories with specific renaming rules for files containing 'ga50' in their names. It handles 'grs' files via a specialized copy function while using standard copying for others, maintaining directory structure and appl... | def convert_raster(input_dir, output_dir):
for input_file in os.listdir(input_dir):
if input_file.endswith('.tif'):
output_file = input_file
if 'ga50' in input_file:
output_file = f'{os.path.basename(input_dir)}_ga50.tif'
output_rast = get_output_raster(... |
def get_unit_by_id(self, a_id):
return self.agents[a_id]
def unit_sight_range(self, agent_id):
return 9
def get_avail_agent_actions(self, agent_id):
unit = self.get_unit_by_id(agent_id)
if unit.health > 0:
# cannot do no-op as alife
avail_actions = [0] * self.n_ac... | The function constructs an agent's observation vector by aggregating features about movement options, visible enemies, allied units, and self-state. It includes relative positions, health/shield data, unit types, and map-specific details like bunker accessibility. The observation combines these elements into a flattene... | def get_obs_agent(self, agent_id):
unit = self.get_unit_by_id(agent_id)
nf_al = 4 + self.unit_type_bits
nf_en = 4 + self.unit_type_bits
if self.obs_all_health:
nf_al += 1 + self.shield_bits_ally
nf_en += 1 + self.shield_bits_enemy
if self.obs_last_acti... |
def one_hot(self, data, nb_classes):
"""Convert an iterable of indices to one-hot encoded labels."""
targets = np.array(data).reshape(-1)
return np.eye(nb_classes)[targets]
def get_agent_action(self, a_id, action):
unit = self.get_unit_by_id(a_id)
tag = unit.tag
x = unit... | This function processes agent actions in a StarCraft II environment, applies them via the SC2 API, updates the game state, checks for battle/episode termination, calculates rewards based on outcomes, and returns reward, termination status, and additional info. It handles error recovery, tracks steps, and adjusts reward... | def step(self, actions):
actions = [int(a) for a in actions]
self.last_action = self.one_hot(actions, self.n_actions)
# Collect individual actions
sc_actions = []
for a_id, action in enumerate(actions):
if not self.heuristic:
agent_action = self.get... |
def get_obs(self):
agents_obs = [self.get_obs_agent(i) for i in range(self.n_agents)]
return agents_obs
def unit_max_cooldown(self, agent_id):
if self.map_type in ['marines', 'bunker']:
return 15
unit = self.get_unit_by_id(agent_id)
if unit.unit_type == self.marine_... | The main task of the code is to generate a normalized state vector for a reinforcement learning agent, combining ally and enemy unit features (health, position, shield, type), bunker status (if applicable), and last actions. It constructs a flattened array of observations for decision-making, with relative positioning ... | def get_state(self):
if self.obs_instead_of_state:
obs_concat = np.concatenate(self.get_obs(), axis=0).astype(np.float32)
return obs_concat
nf_al = 4 + self.shield_bits_ally + self.unit_type_bits
nf_en = 3 + self.shield_bits_enemy + self.unit_type_bits
ally_sta... |
def _upload_init(self):
'''
Initializes Upload
'''
request_data = {
'command': 'INIT',
'media_type': self.media_type,
'total_bytes': self.total_bytes,
'media_category': self.media_category
}
req = requests.post(url=self.MED... | This code uploads a video file by initializing the upload process, appending the file data, and finalizing the upload. It retrieves and returns the media ID after resetting internal state variables for subsequent uploads. | def upload(self, file_name):
self.video_filename = file_name
self.total_bytes = os.path.getsize(self.video_filename)
self._upload_init()
self._upload_append()
self._upload_finalize()
media_id = self.media_id
self.media_id = None
self.total_bytes = None
... |
def decile_table(y_true, y_prob, change_deciles=10, labels=True, round_decimal=3):
"""Generates the Decile Table from labels and probabilities
The Decile Table is creared by first sorting the customers by their predicted
probabilities, in decreasing order from highest (closest to one) to
lowest (... | The function generates a decile table and four evaluation plots (Lift, Lift@Decile, Gain, and KS) to assess classifier performance using true labels and predicted probabilities. It returns a dataframe containing decile-wise metrics. The plots visualize cumulative lift, decile-specific lift, cumulative gains, and KS sta... | def report(y_true, y_prob, labels=True, plot_style = None, round_decimal=3,
title_fontsize=14, text_fontsize=10, figsize=(16, 10)):
"""Generates decile table and 4 plots (Lift, Lift@Decile, Gain and KS)
from labels and probabilities
Args:
y_true (array-like, shape (n_samples)):
... |
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takecommand(self):
r=sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold=1
audio=r.listen(source)
try:
print("Recognizing..")
self.q... | The code listens for voice commands. If "wake up" is detected, it executes tasks via `taskexecution()`. If "good bye" is detected, it exits the program after a farewell message. The loop continuously waits for user input to trigger these actions. | def run(self):
#self.taskexecution()
speak("please say wakeup to continue")
while True:
self.query=self.takecommand()
if "wake up" in self.query:
self.taskexecution()
elif "good bye" in self.query:
speak("ok bye sir i am going h... |
def speak(audio):
engine.say(audio)
engine.runAndWait()
def takecommand(self):
r=sr.Recognizer()
with sr.Microphone() as source:
print("Listening...")
r.pause_threshold=1
audio=r.listen(source)
try:
print("Recognizing..")
self.q... | The code's main task is to handle voice commands for different modes: detection (triggering taskexecution() after a "wake up" command), face recognition (calling fillattendancenew() and executing taskexecution() if recognition succeeds), and sample input (invoking sample() and opening a main window). It continuously li... | def run(self):
#self.taskexecution()
while True:
speak("tell me the mode in which you want to unlock me or you want to add samples first")
self.query=self.takecommand()
if "detection" in self.query:
speak("Please say wake up to continue")
... |
def geod2geoc(gdlat, height, Bn, Bu):
"""
Convert from geocentric to geodetic coordinates
Example:
--------
theta, r, B_th, B_r = geod2lat(gdlat, height, Bn, Bu)
Parameters
----------
gdlat : array
Geodetic latitude [degrees]
h : array
Height above ellipsoid [km]
... | The code calculates the IGRF (International Geomagnetic Reference Field) model's magnetic field components (eastward, northward, upward) at specified geodetic coordinates (longitude, latitude, height) and dates. It converts inputs to geocentric coordinates, computes field values using the IGRF model, then transforms re... | def igrf(lon, lat, h, date, coeff_fn = shc_fn):
"""
Calculate IGRF model components
Input and output in geodetic coordinates
Broadcasting rules apply for coordinate arrays, and the
combined shape will be preserved. The dates are kept out
of the broadcasting, so that the output will have shape
... |
def isDeep(self, depth):
return depth > self.haT()
def sizeOf(self, x):
if x == None:
return 0
return 1 + self.sizeOf(x.left) + self.sizeOf(x.right)
def brotherOf(self, node, parent):
if parent.left != None and parent.left.key == node.key:
return parent.right
... | This code inserts a node into a tree, tracks traversal depth and parents, and maintains balance by checking if the insertion depth exceeds a threshold. If so, it identifies an unbalanced "scapegoat" node, rebuilds its subtree, and replaces it to restore balance. The method updates tree size and ensures structural integ... | def insert(self, key):
z = Node(key)
y = None
x = self.root
# keep track of the depth and parents (so we don't have to recalculate
# them)
depth = 0
parents = []
# find where to place the node
while x != None:
parents.insert(0,x)
... |
def configure_env():
global PORTAL_URL
if "portal" in CLOUD_CONFIG:
PORTAL_URL = CLOUD_CONFIG["portal"]
else:
PORTAL_URL = os.getenv("YB_PORTAL", "https://localhost")
def setup_customer():
global CUSTOMER_ID
global USER_ID
global API_TOKEN
global AUTH_TOKEN
if "customer" not in CLOUD_CONFIG:
... | The main task of the code is to initialize and configure the application environment, including setting up customer details, authentication, Key Management Service (KMS) configurations, general configurations, and service providers, ensuring the system is properly prepared for operation. | def main():
configure_env()
setup_customer()
authenticate()
setup_kms_configs()
setup_configs()
setup_providers() |
def _process_args():
parser = argparse.ArgumentParser(
prog="cloud-config-generator",
description="This program generated automation TF scripts for cloud accounts. Currently AWS only"
)
parser.add_argument(
"--az-list",
dest="az_list",
type=_az_list,
required=False,
default=DEFAULT_AZ... | The main task of the code is to generate infrastructure configuration outputs based on command-line arguments. It processes input parameters, checks the 'generate' flag, and conditionally executes functions to output JSON-formatted availability zones, provider configurations, VPC settings, or peering configurations, de... | def main():
arg =_process_args()
az_list = arg.az_list
generate:str = arg.generate.lower()
if generate == "default-az-list" :
from json import dumps,loads
print(dumps(loads(DEFAULT_AZ_LIST), indent=2))
if generate == 'all' or generate == 'providers':
print(generate_provider(az_list, arg.tag... |
def allSameClass(self, data):
for row in data:
if row[-1] != data[0][-1]:
return False
return data[0][-1]
def getMajClass(self, curData):
freq = [0]*len(self.classes)
for row in curData:
index = self.classes.index(row[-1])
freq[index] += 1
maxInd = freq.index(max(freq))
return self.classes[maxI... | This function recursively builds a decision tree by selecting the best attribute to split the data, creating nodes with the chosen attribute and threshold, and recursively generating child nodes for each subset until termination conditions are met (e.g., all same class, no data, or no attributes remain). | def recursiveGenerateTree(self, curData, curAttributes):
allSame = self.allSameClass(curData)
if len(curData) == 0:
#Fail
return Node(True, "Fail", None)
elif allSame is not False:
#return a node with that class
return Node(True, allSame, None)
elif len(curAttributes) == 0:
#return a node with t... |
def filter_files(self, path, file_pattern="vasprun.xml"):
"""
Find the files that match the pattern in the given path and
return them in an ordered dictionary. The searched for files are
filtered by the run types defined in self.runs. e.g. ["relax1", "relax2", ...].
Only 2 scheme... | The code's main task is to parse VASP calculation data from a directory containing `vasprun.xml` and `OUTCAR` files, generate a structured task dictionary, and add post-processed information. It validates the data and returns the task document if both required files are present; otherwise, it raises an error. The proce... | def assimilate(self, path):
"""
Adapted from matgendb.creator
Parses vasp runs(vasprun.xml file) and insert the result into the db.
Get the entire task doc from the vasprum.xml and the OUTCAR files in the path.
Also adds some post-processed info.
Args:
path (... |
def pecl_information(self, package):
"""
"""
_name = package.lower()
_version = None
args = []
args.append(self.pecl_bin)
args.append("info")
args.append(package)
# self.module.log(msg=f" - args {args}")
rc, out, err = self.__exec(args,... | This code installs or uninstalls PECL packages based on configuration, checking their current state, installing if absent, and managing module enablement/disabling with priority settings. It returns installation status results. | def __install(self):
"""
"""
result_state = []
package_name = None
for p in self.packages:
"""
"""
res = {}
package_name = p.get("name", None)
package_state = p.get("state", "present")
package_priority = p.g... |
def __create_directory(self, dir):
"""
"""
try:
os.makedirs(dir, exist_ok=True)
except FileExistsError:
pass
if os.path.isdir(dir):
return True
else:
return False
def php_information(self, command=None):
"""
... | This code manages PECL package installation and validation. It creates directories, checks PHP extensions, and processes package states ('install' or 'check'). For 'install', it executes installation, aggregates results, and determines if changes/failures occurred. For 'check', it verifies package status and identifies... | def run(self):
"""
"""
_failed = True
self.__create_directory(self.cache_directory)
self.checksum = Checksum(self.module)
result_state = []
# checksum_file = os.path.join(self.cache_directory, "pecl.checksum")
rc, self.php_extension_dir, err = self.ph... |
def get_filter():
filter = answer(
"Only generate the doc for specific functions/classes. Comma seperated list. Leave empty to generate all.",
default=""
# getChat, leaveChat, getChatAdministrators, getChatMember, getChatMembersCount, Message, MessageEntity"
)
if filter.strip():
... | The code parses HTML content from an API response to extract structured data about functions and classes, including their names, descriptions, links, parameters, and return types. It processes sibling elements of `<h4>` tags to gather details, handles text splitting for return values, applies filters, and uses whitelis... | def load_from_api(folder):
filter = get_filter()
document = requests.get(BASE_URL)
bs = BeautifulSoup(document.content)
results = []
for h in bs.select("#dev_page_content > h4"):
print("------")
anchor = h.find(lol1)
if not anchor or not anchor.has_attr("name"):
c... |
def get_folder_path():
file = answer("Folder path to store the results.", default="/tmp/pytgbotapi/")
if file:
try:
file = abspath(file)
mkdir_p(file)
with open(path_join(file, "__init__.py"), "w") as f:
f.write(FILE_HEADER)
# end with
... | The main task of the code is to determine whether to load data from an API or a dump file based on user confirmation, then load the data into a specified folder. It first retrieves the folder path, prompts the user for input, and executes either `load_from_api` or `load_from_dump` accordingly. | def main():
folder = get_folder_path()
mode = confirm("Load from a dump instead of the API Docs?")
if not mode: # API
load_from_api(folder)
else: # Dump
load_from_dump(folder) |
def heuristic_one(graph_prime, num_buses, size_bus, constraints, rowdy_number):
#Sort students into buses
buses = [[] for _ in range(num_buses)]
best_bus = 0
best_score = 0
for student in sorted(rowdy_number, key=rowdy_number.get, reverse=True):
for bus_num in range(num_buses):
i... | The code assigns students to buses using graph-based heuristics, optimizing for constraints. It calculates student "rowdiness" and popularity metrics, modifies the graph to prioritize constraints, and applies three heuristics to generate bus assignments. Post-processing optimizes bus configurations via swaps and ensure... | def solve(graph, num_buses, size_bus, constraints):
#TODO: Write this method as you like. We'd recommend changing the arguments here as well
#Inputs: graph, num_buses, size_bus, constraints
#Heuristic Order #1
rowdy_number = {}
for rowdy_list in constraints:
for student in rowdy_list:
... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of an approximation algorithm (approx1) for the minimum vertex cover (MVC) problem on random graphs. It iterates over 1–30 edges, generating 1000 random graphs per edge count, computes the MVC size and approx1's solution size, and calculates the ratio of their averages. The result is ... | def test1_edge():
approx1_perf=[]
for num_edges in range (1,31):
sum_approx1=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(8,num_edges)
sum_mvc+=size_mcv(MVC(G1))
sum_approx1 += size_mcv(approx1(G1))
expected_performance1=sum_ap... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of an approximation algorithm (approx2) for finding a vertex cover compared to the optimal solution (MVC) in random graphs. It iterates over graph edge counts (1-30), generates 1000 random graphs per count, computes the average size of MVC and approx2 solutions, and stores the ratio o... | def test2_edge():
approx2_perf=[]
for num_edges in range (1,31):
sum_approx2=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(8,num_edges)
sum_mvc+=size_mcv(MVC(G1))
sum_approx2 += size_mcv(approx2(G1))
expected_performance2=sum_ap... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of the 'approx3' algorithm for vertex cover approximation by comparing its results to the exact MVC solution across 1000 random graphs with 8 nodes and varying edge counts (1-30). It calculates the average ratio of approx3's solution size to MVC's size for each edge count, storing the... | def test3_edge():
approx3_perf=[]
for num_edges in range (1,31):
sum_approx3=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(8,num_edges)
sum_mvc+=size_mcv(MVC(G1))
sum_approx3 += size_mcv(approx3(G1))
expected_performance3=sum_ap... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of an approximation algorithm (approx1) for the vertex cover problem by comparing its average results against the optimal solution (MVC) across varying numbers of nodes (5 to 10). It runs 1000 trials per node count, computes the ratio of approx1's performance to MVC, and returns a lis... | def test1_node():
approx1_perf=[]
for num_nodes in range (5,11):
sum_approx1=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(num_nodes,14)
sum_mvc+=size_mcv(MVC(G1))
sum_approx1 += size_mcv(approx1(G1))
expected_performance1=sum_a... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of an approximation algorithm (approx2) for the Minimum Vertex Cover (MVC) problem compared to the exact MVC solution. It iterates over graph sizes (5–10 nodes), generates 1000 random graphs per size, computes the average MVC size and approx2's result, then calculates the ratio of app... | def test2_node():
approx2_perf=[]
for num_nodes in range (5,11):
sum_approx2=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(num_nodes,14)
sum_mvc+=size_mcv(MVC(G1))
sum_approx2 += size_mcv(approx2(G1))
expected_performance2=sum_a... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | This function evaluates the performance of the 'approx3' algorithm for vertex cover problems by comparing its results to the exact minimum vertex cover (MVC) solution across 1000 random graphs for each node count from 5 to 10. It calculates the average ratio of approx3's solution size to MVC size for each node count, r... | def test3_node():
approx3_perf=[]
for num_nodes in range (5,11):
sum_approx3=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(num_nodes,14)
sum_mvc+=size_mcv(MVC(G1))
sum_approx3 += size_mcv(approx3(G1))
expected_performance3=sum_a... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The main task of the code is to evaluate the performance of an approximation algorithm (approx1) for the minimum vertex cover problem compared to the optimal solution (MVC). It iterates over 1 to 30 edges, generates 1000 random graphs with 8 nodes each, computes the average ratio of approx1's solution size to the optim... | def test1_edge():
approx1_perf=[]
for num_edges in range (1,31):
sum_approx1=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(8,num_edges)
sum_mvc+=size_mcv(MVC(G1))
sum_approx1 += size_mcv(approx1(G1))
expected_performance1=sum_ap... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The main task of the code is to evaluate the performance of the `approx2` algorithm for finding vertex covers compared to the exact minimum vertex cover (MVC) solution. It iterates over 1–30 edges, generates 1000 random graphs with 8 nodes, computes the average size of `approx2` and exact MVC solutions, and stores the ... | def test2_edge():
approx2_perf=[]
for num_edges in range (1,31):
sum_approx2=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(8,num_edges)
sum_mvc+=size_mcv(MVC(G1))
sum_approx2 += size_mcv(approx2(G1))
expected_performance2=sum_ap... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of the `approx3` algorithm for finding a vertex cover compared to the exact minimum vertex cover (MVC) solution. It iterates over graph edge counts (1–30), generates 1000 random graphs each with 8 nodes, computes the average size ratio of `approx3`'s solution to the exact MVC, and ret... | def test3_edge():
approx3_perf=[]
for num_edges in range (1,31):
sum_approx3=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(8,num_edges)
sum_mvc+=size_mcv(MVC(G1))
sum_approx3 += size_mcv(approx3(G1))
expected_performance3=sum_ap... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of an approximation algorithm (approx1) for the Minimum Vertex Cover (MVC) problem compared to the exact solution. It iterates over graph sizes (5-10 nodes), generates 1000 random graphs per size, computes the MVC size and approx1's result, and calculates the ratio of their averages. ... | def test1_node():
approx1_perf=[]
for num_nodes in range (5,11):
sum_approx1=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(num_nodes,14)
sum_mvc+=size_mcv(MVC(G1))
sum_approx1 += size_mcv(approx1(G1))
expected_performance1=sum_a... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | The code evaluates the performance of an approximation algorithm (approx2) for the minimum vertex cover problem by comparing its results to the exact solution (MVC) across graphs with varying node counts (5–10 nodes). It runs 1000 trials per node count, calculates the average ratio of approx2's solution size to the exa... | def test2_node():
approx2_perf=[]
for num_nodes in range (5,11):
sum_approx2=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(num_nodes,14)
sum_mvc+=size_mcv(MVC(G1))
sum_approx2 += size_mcv(approx2(G1))
expected_performance2=sum_a... |
def create_rand_graph_safe (num_nodes, num_edges):
lst_tups = []
G = Graph(num_nodes)
for x in range (num_nodes):
for y in range (x , num_nodes):
lst_tups.append((x,y))
for i in range (num_edges):
if len(lst_tups) == 0 :
print ("You added to many edges.")
... | This code evaluates the performance of an approximation algorithm (approx3) for the minimum vertex cover problem compared to the exact solution (MVC). It iterates over graph sizes with 5 to 10 nodes, runs 1000 trials per size, computes the average ratio of approx3's solution size to the exact MVC size, and returns a li... | def test3_node():
approx3_perf=[]
for num_nodes in range (5,11):
sum_approx3=0
sum_mvc=0
for j in range (1000):
G1= create_rand_graph_safe(num_nodes,14)
sum_mvc+=size_mcv(MVC(G1))
sum_approx3 += size_mcv(approx3(G1))
expected_performance3=sum_a... |
def allGraphs(numNodes):
# list of all potential edge pairs for a graph with numNodes-number of nodes
c = []
for i in range(0, numNodes-1):
for j in range(i+1, numNodes):
c.append((i,j))
# generating all possible groups of edge pairs for a graph with numNodes-number of nodes
... | This code evaluates the performance of an approximation algorithm (approx1) for the Minimum Vertex Cover (MVC) problem across graphs with varying numbers of nodes (1 to 5). It calculates the ratio of the average approximate solution size to the exact MVC size for each node count, returning a list of performance metrics... | def nTest1_node():
approx1_perf=[]
for num_nodes in range (1,6):
sum_approx1=0
sum_mvc=0
graphs = allGraphs(num_nodes)
for G1 in graphs:
sum_mvc += size_mcv(MVC(G1))
sum_approx1 += size_mcv(approx1(G1))
if sum_mvc > 0:
... |
def allGraphs(numNodes):
# list of all potential edge pairs for a graph with numNodes-number of nodes
c = []
for i in range(0, numNodes-1):
for j in range(i+1, numNodes):
c.append((i,j))
# generating all possible groups of edge pairs for a graph with numNodes-number of nodes
... | The main task of the code is to evaluate the performance of an approximation algorithm (approx2) for the minimum vertex cover problem compared to the optimal solution (MVC). It iterates over graphs with 1 to 5 nodes, calculates the average ratio of approx2's solution size to the optimal MVC size for each node count, an... | def nTest2_node():
approx2_perf=[]
for num_nodes in range (1,6):
sum_approx2=0
sum_mvc=0
graphs = allGraphs(num_nodes)
for G1 in graphs:
sum_mvc += size_mcv(MVC(G1))
sum_approx2 += size_mcv(approx2(G1))
print(size... |
def allGraphs(numNodes):
# list of all potential edge pairs for a graph with numNodes-number of nodes
c = []
for i in range(0, numNodes-1):
for j in range(i+1, numNodes):
c.append((i,j))
# generating all possible groups of edge pairs for a graph with numNodes-number of nodes
... | The code evaluates the performance of an approximation algorithm (approx3) for the Minimum Vertex Cover (MVC) problem across graphs with 1 to 5 nodes. It computes the average ratio of approx3's solution size to the optimal MVC size for each graph count, storing results in a list for analysis. | def nTest3_node():
approx3_perf=[]
for num_nodes in range (1,6):
sum_approx3=0
sum_mvc=0
graphs = allGraphs(num_nodes)
#print(1)
for G1 in graphs:
#print(G1.adj)
sum_mvc += size_mcv(MVC(G1))
#print(G1.adj)
... |
def generate_images(infer_path):
"""
:param infer_path:
:return: generator of image paths
"""
if os.path.isdir(infer_path):
for dir_path, _, files in os.walk(infer_path):
for file in files:
if file.split(".")[-1].lower() in ['jpg', 'jpeg', 'png', 'bmp']:
... | This code performs image segmentation using a Mask R-CNN model on input images, saving detected masks, visualizations, and contours. It optionally compares predictions against ground truth annotations to compute IoU scores, evaluates model performance, and outputs results to specified directories. The task involves loa... | def infer(args):
from mrcnn import model as mrcnn_lib
infer_path = args.path
output = args.output
do_pictures = not args.no_pictures
do_contours = not args.no_contours
model_path = args.model
should_save_masks = not args.no_masks
gt_adapter = args.gt
task_id = args.task
compare_t... |
def starting_messages():
"""
Prompts the user for board dimensions, knight's starting position, and choice to try the puzzle.
Returns:
tuple: A tuple containing the row position, column position, row dimension, column dimension, and puzzle choice.
"""
# Loop to get valid board dimensions
... | The main task of the code is to initialize a game by retrieving user inputs and checking if a solution exists. If valid, it creates a game instance, allows player or AI to play based on the input, and displays the final board state. | def main():
"""
The main function to start the game.
"""
row_position, col_position, row_n, col_n, ai = starting_messages()
if not solution_exists(row_n, col_n):
print("No solution exists!")
else:
game = Game(row_position, col_position, row_n, col_n, ai)
if not game.ai:
... |
def read_dict(self):
'''
:return:
'''
rf = codecs.open(os.path.join(self.data_path, 'entity2id.txt'), 'r', encoding='utf8')
self.ent_num = int(rf.readline().strip())
rf.close()
rf = codecs.open(os.path.join(self.data_path, 'relation2id.txt'), 'r', encoding='utf8')
self.rel_num = int(rf.readline().... | The main task of the code is to prepare and structure training, testing, and validation data for a machine learning model. It reads dictionary and dataset files, initializes type constraints, generates negative samples, and unpacks positive triples into subject-predicate-object formats for training and evaluation. | def make_data(self):
'''
:return:
'''
print('read dict')
self.read_dict()
print('read data')
self.read_data()
print('init type constrain')
self.init_type_constrain()
print('init sample')
self.init_sample()
print('make neg samples')
self.make_neg_samples()
self.train_ph, self.train_pt, ... |
def check_n_steps(self):
# If count of steps is bigger than treshold; game over
if self.steps > (self.row**2//2):
self.done = True
self.reward = self.reward_dict["a lot of steps"]
def check_hit_self(self):
# Check if set of body isn't long as it had eaten apples
s... | The code handles snake movement by updating direction based on input actions, calculating new head position, checking collisions/self-hit, boundaries, and executing the snake algorithm if the game continues. | def move(self, action):
# handling whole logic
# snake can kill himself by going opposite
if action == 0: direction = self.moves_dir["up"]
elif action == 1: direction = self.moves_dir["right"]
elif action == 2: direction = self.moves_dir["down"]
elif action == 3: ... |
def reset(self):
# Reset/set up game parameters
self.second_init()
# Generate and refresh board
self.generate_grid()
self.generate_snake()
self.generate_apple()
self.compute_state()
return self.state
def move(self, action):
# handling whole logic... | The code executes a given action in an environment, updates the state, calculates the reward, checks if the episode is done, and returns the new state, reward, done status, and additional info for the next step. It increments the step count, resets if done, moves the agent, refreshes the environment, and computes the u... | def step(self, action):
# Perform action, whole back up logic and return results of action
self.reward = self.reward_dict["step"]
self.steps += 1
if self.done:
self.reset()
self.move(action)
self.refresh_board()
self.compute_state()
return se... |
def detect_corners(image: np.ndarray) \
-> tuple[tuple[int, int], tuple[int, int],
tuple[int, int], tuple[int, int]]:
"""
Detect the four corners of a document in an image and return their
coordinates. The coordinates are sorted in clockwise order starting from
the top-left corn... | The main task of the code is to perform corner detection on each image in the test directory, visualize the detected document by drawing corners, resize the image, and display the result. The process iterates through all test images, showing each processed image sequentially with a key press to proceed. | def main():
"""
Run corner detection on each image in the test images directory. Press any
key to continue to the next image.
"""
for image_path in glob.glob('../test/image/*'):
image = cv2.imread(image_path)
corners = detect_corners(image)
detected_document_image = draw_dete... |
def read_spectra(self,xlsx):
xlsx = pd.read_excel(xlsx, index_col=0, engine='openpyxl')
spectra = xlsx.values
wavelengths = xlsx.index.to_numpy()
return wavelengths, spectra.T
def evaluate_batch(self, xb, yb):
logging.debug('Current experiment id : %d'%self.expt_id)
... | This code updates a Gaussian Process (GP) model by incorporating new spectral data from an Excel file. It initializes or updates wavelength/spectra data, evaluates new training points, appends them to existing training data, re-fits the GP surrogate model, and logs model parameters like output scale, noise, mean, and l... | def update(self, xlsx, read_spectra=None):
# re-initialize
if read_spectra is None:
self.wavelengths, self.spectra = self.read_spectra(xlsx)
else:
self.wavelengths, self.spectra = read_spectra(xlsx)
self.new_obj = self.evaluate_batch(self.wavelengths, self.spectra... |
def load_dataset(filename):
df = pd.read_csv(filename, sep=";")
return prepare_dataset(df)
def plot_density(df, param, name):
sb.displot(data=df, x=param, kde=True)
plt.title("Distribution of {} in {}".format(param, name))
def K_fold_cross_val(df, K=10, y_param='power/energy-pkg/'):
kf = KFold(n_spl... | The code performs data loading, cross-validation, model training, and evaluation. It loads datasets, plots density distributions, trains a model using K-fold cross-validation, predicts on training/validation data, computes RMSE, and visualizes results. If prediction mode is enabled, it applies the model to new data, ad... | def run(args):
y_param = args.y
print("{} Features".format(len(features)))
df = load_dataset(args.train)
if not no_plot and not no_plot_train:
plot_density(df, y_param, "the training dataset")
plt.show()
print("Training dataset {} x {}".format(df.shape[0], df.shape[1]))
print... |
def ligand_centroid(traj, ligand_id):
""" Get the centroid of the ligand with the given id."""
indices = get_ligand_atom_indices(traj, ligand_id)
coords = traj.xyz[:, indices, :]
return np.mean(coords, axis=1)[0]
def ligand_maximum_extent(traj, ligand_id):
""" Computes the maximum extent of the liga... | This function extracts the binding site around a ligand in a molecular dynamics trajectory. It calculates the ligand's centroid and extent, identifies surrounding atoms, and slices the trajectory to include only these atoms. It then removes residues with incomplete atom counts compared to the original trajectory, retur... | def extract_binding_site(traj, ligand_id):
""" Extract the binding site with the ligand.
Parameters
----------
traj : mdtraj.Trajectory
ligand_id : str
Returns
-------
bsite : mdtrajTrajectory
"""
lig_center = ligand_centroid(traj, ligand_id)
lig... |
def load_datasets_info():
""" Loads datasets.yaml into a dictionary"""
with open("./data/datasets.yaml") as fp:
db = yaml.load(fp, Loader=yaml.FullLoader)
return db
def fetch_pdbs(pdb_codes_file, pdb_dir):
""" Fetch and write pdb files to disk.
Parameters
----------
pdb_... | (The code downloads required PDB files for multiple datasets, organizing them into labeled folders and generating README files. It creates a directory structure, retrieves PDB codes from specified files or single entries, and populates each dataset folder with corresponding files while adding metadata via READMEs. The ... | def fetch_all_datasets():
""" Downloads all the pdbs necessary for each dataset.
It downloads all the required pdb files, organizes into appropriate
folders and writes a readme for each dataset.
"""
download_path = "./test_cases"
pdb_codes_path = "./data/pdb_codes"
if not os.path.i... |
def get_assignment_data() -> dict:
"""
Load the assignment metadata out from the assignment yaml file
:return:
"""
# Figure out filename
assignment_filename = None
for assignment_filename_option in ['assignment.yml', 'assignment.yaml']:
if os.path.isfile(assignment_filename_option)... | The main task of the code is to process a student's programming assignment by retrieving data, setting up the environment, executing build and test processes, and reporting results. It handles errors by logging panic states via API or Redis if the API fails, ensuring error tracking even in critical failure scenarios. | def main():
try:
assignment_data = get_assignment_data()
setup()
os.chdir('./student')
run_build(assignment_data)
run_tests(assignment_data)
report_state('Finished!', params={'processed': '1'})
except Panic as e:
try:
report_panic(repr(e), tr... |
def get_synsets_for_word(s, pos=None):
if pos is None:
return wordnet.synsets(s)
return wordnet.synsets(s, pos=pos)
def get_window_of_context(word, phrase):
word = word.lower()
phrase_tokens = tokenize_and_preprocess(phrase)
target_index = phrase_tokens.index(word.lower())
left_window =... | The code identifies the most contextually appropriate synset for a given word within a phrase by filtering candidate synsets, calculating their relevance scores based on context, and returning the synset with the highest score along with its definition. | def predict(word, phrase, filter_function = lambda x : True):
synsets = list(filter(filter_function, get_synsets_for_word(word, POS)))
context = get_window_of_context(word, phrase)
scores = [calculate_synset_score(context, word, phrase, synset) for synset in synsets]
max_score = max(scores)
m... |
def get_synsets_for_word(s, pos=None):
if pos is None:
return wordnet.synsets(s)
return wordnet.synsets(s, pos=pos)
def get_window_of_context(word, phrase):
word = word.lower()
phrase_tokens = tokenize_and_preprocess(phrase)
target_index = phrase_tokens.index(word.lower())
left_window =... | The main task of the code is to categorize a given word based on its semantic relations and context. It filters relevant synsets, calculates scores for each synset using contextual analysis, normalizes these scores, aggregates them into predefined categories, and returns the category with the highest accumulated score,... | def predict_eval(word, phrase):
print(phrase)
synsets = list(filter(filter_eval, get_synsets_for_word(word, POS)))
context = get_window_of_context(word, phrase)
words = []
for synset in synsets:
words.append(len(" ".join([relation(rel, synset) for rel in RELS[POS]]).split()))
scores ... |
def checkuser(message):
if isowner(message): return True
user_id = str(message.from_user.id)
if AUTHUSERS and user_id not in AUTHUSERS: return False
if user_id in BANNEDUSERS: return False
return True
def ismemberpresent(id):
if TARGET == "" or LINK == "": return True
try:
app.get_ch... | This function processes MDisk link downloads by first verifying user authorization and membership status. It extracts a MDisk link from the message, validates its format, and triggers processing if valid. If checks fail or format is incorrect, it sends appropriate error messages and instructions to the user. | def mdiskdown(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
if not checkuser(message):
app.send_message(message.chat.id, '__You are either not **Authorized** or **Banned**__',reply_to_message_id=message.id)
return
if not ismemberpresent(message.fro... |
def checkuser(message):
if isowner(message): return True
user_id = str(message.from_user.id)
if AUTHUSERS and user_id not in AUTHUSERS: return False
if user_id in BANNEDUSERS: return False
return True
def ismemberpresent(id):
if TARGET == "" or LINK == "": return True
try:
app.get_ch... | The function handles user interactions in a Telegram bot, checking authorization, membership, and processing MDisk links. It blocks unauthorized/banned users, prompts to join a chat if not a member, directs to /help for commands, and processes valid MDisk links for further actions while rejecting invalid inputs. | def mdisktext(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
if isPremmium and message.chat.id == temp_channel: return
if not checkuser(message):
app.send_message(message.chat.id, '__You are either not **Authorized** or **Banned**__',reply_to_message_i... |
def checkuser(message):
if isowner(message): return True
user_id = str(message.from_user.id)
if AUTHUSERS and user_id not in AUTHUSERS: return False
if user_id in BANNEDUSERS: return False
return True
def getlock(uid): return locks.get(str(uid), None)
def handlethumb(msg,id):
setlock(msg.from_us... | This code handles setting a user's thumbnail by checking authorization, downloading media, renaming it with the user's ID, and either processing it via `handlethumb` or confirming the thumbnail is set. | def ptumb(client: pyrogram.client.Client, message: pyrogram.types.messages_and_media.message.Message):
if not checkuser(message):
app.send_message(message.chat.id, '__You are either not **Authorized** or **Banned**__',reply_to_message_id=message.id)
return
file = app.download_media(mes... |
def get(id): return msgsdata.get(str(id), [None,None,None])
def getformatmsg(filename,status,procs,size,firsttime=False):
if firsttime:
previous_progress = 0
previous_time = time.time()
else:
previous_progress = prev[filename]
previous_time = prevtime[filename]
progress = pr... | The main task of the code is to handle file downloading, merging, splitting (if needed), and uploading with progress tracking. It checks for valid links, manages errors, uses threads for status updates, and sends media files (video/document) with captions, thumbnails, and restrictions alerts, while cleaning up temporar... | def startdown(call):
msg = call.message
message,alldata,link = get(call.data.split()[-1])
if message is None:
app.edit_message_text(msg.chat.id, msg.id,"__Expired__")
return
# checking link and download with progress thread
app.edit_message_text(msg.chat.id, msg.id, getformatmsg(a... |
def ismemberpresent(id):
if TARGET == "" or LINK == "": return True
try:
app.get_chat_member(TARGET,id)
return True
except: return False
def startdown(call):
msg = call.message
message,alldata,link = get(call.data.split()[-1])
if message is None:
app.edit_message_text(m... | This function handles callback queries in a Telegram bot, verifying user membership and executing actions like file download, renaming, thumbnail management, and data swapping. It ensures only the message sender interacts, checks membership status, and initiates threads for downloads or requests user input for renaming... | def handle(client: pyrogram.client.Client, call: pyrogram.types.CallbackQuery):
if call.from_user.id != call.message.reply_to_message.from_user.id: return
if not ismemberpresent(call.from_user.id):
app.send_message(call.message.chat.id, '__You are not a member of our Chat\nJoin and Retry__',reply_to_m... |
def __convert_to_pid__(self, pID):
if(isinstance(pID, string_types)):
return self.get_portfolio_id(pID)
else:
return pID
def urljoiner(baseurl, path_or_pathlist):
if isinstance(path_or_pathlist, string_types):
if(baseurl.rsplit('/', 1)[-1] == "rest"):
retu... | This function deletes all positions associated with a specified portfolio for a given date by sending a DELETE request to the corresponding API endpoint, converting the portfolio identifier to an ID, constructing the URL, and handling potential errors. | def delete_positions_for_date(self, portfolio, date):
"""Deletes all Positions from the Portfolio for a given date (Auth policies: Users)
Endpoint:
/portfolios/{id}/positions/{date}
Keyword arguments:
portfolio: portfolio name or id
date: date to delete
... |
def __convert_to_pid__(self, pID):
if(isinstance(pID, string_types)):
return self.get_portfolio_id(pID)
else:
return pID
def urljoiner(baseurl, path_or_pathlist):
if isinstance(path_or_pathlist, string_types):
if(baseurl.rsplit('/', 1)[-1] == "rest"):
retu... | The code retrieves a specific portfolio by converting the input (name or ID) to a portfolio ID, constructs a URL, sends a GET request to the endpoint /portfolios/{id}, handles potential errors, and returns the portfolio data in JSON format. | def get_portfolio(self, portfolio):
"""Returns a single portfolio. (Auth policies: Users)
Endpoint:
/portfolios/{id}
Keyword arguments:
portfolio: portfolio name or id
"""
portfolio_id = self.__convert_to_pid__(portfolio)
portfolio_position_url ... |
def __convert_to_pid__(self, pID):
if(isinstance(pID, string_types)):
return self.get_portfolio_id(pID)
else:
return pID
def urljoiner(baseurl, path_or_pathlist):
if isinstance(path_or_pathlist, string_types):
if(baseurl.rsplit('/', 1)[-1] == "rest"):
retu... | The main task of the code is to retrieve a portfolio's benchmark data by sending a GET request to a specified API endpoint. It converts the input portfolio identifier to a standardized ID, constructs the request URL, handles debug logging, executes the HTTP request, processes potential errors, and returns the JSON-form... | def get_portfolio_benchmark(self, portfolio):
"""Returns a portfolio benchmark. (Auth policies: Users)
Endpoint:
/portfolios/{id}/benchmark
Keyword arguments:
portfolio: portfolio name or id
"""
portfolio_id = self.__convert_to_pid__(portfolio)
... |
def __convert_to_pid__(self, pID):
if(isinstance(pID, string_types)):
return self.get_portfolio_id(pID)
else:
return pID
def urljoiner(baseurl, path_or_pathlist):
if isinstance(path_or_pathlist, string_types):
if(baseurl.rsplit('/', 1)[-1] == "rest"):
retu... | The main task of the code is to retrieve valuation dates for a specified portfolio from an API endpoint, sorted by latest first. It converts the portfolio identifier, constructs the request URL, sends a GET request with authentication headers, checks for errors, and returns the JSON-formatted response containing valuat... | def get_portfolio_valuations(self, portfolio):
"""Lists dates there are Valuations for the Portfolio, latest first (Auth policies: Users)
Endpoint:
/api/v1/portfolios/{id}/valuations
Keyword arguments:
portfolio: portfolio name or id
"""
portfolio_id = ... |
def __convert_to_pid__(self, pID):
if(isinstance(pID, string_types)):
return self.get_portfolio_id(pID)
else:
return pID
def urljoiner(baseurl, path_or_pathlist):
if isinstance(path_or_pathlist, string_types):
if(baseurl.rsplit('/', 1)[-1] == "rest"):
retu... | This function retrieves a portfolio's valuation data for a specific date by constructing an API endpoint URL, sending a GET request with authentication headers, handling potential errors, and returning the JSON response. It converts the portfolio identifier to an ID, assembles the request URL, and processes the server'... | def get_portfolio_valuations_for_date(self, portfolio, date):
"""Retrieves portfolio valuation for a given id+date (Auth policies: Users)
Endpoint:
/api/v1/portfolios/{id}/valuations/{date}
Keyword arguments:
portfolio: portfolio name or id
date: date for va... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.