dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def base_traj(pos: np.ndarray,
step_height: float,
linear: np.ndarray,
angular: np.ndarray,
margin: float,
t: float) -> np.ndarray:
"""! Generates the the base trajectory
@param pos: Base position of the leg
@param step_height: Step heigh... | This function computes a 3D trajectory point for a robotic leg relative to its mountpoint, considering plane constraints, corpus position, and rotations. It projects a base trajectory onto a specified plane, adjusts for corpus offsets, and applies mountpoint-specific transformations to determine the final coordinates a... | def traj_point(leg_pos: np.ndarray,
mountpoint_no: int,
n: np.ndarray,
linear: np.ndarray,
angular: np.ndarray,
step_height: float,
height: float,
corpus_position: np.ndarray,
yaw: float,
... |
def validate_extension(self, filepath):
ext = filepath.split('.')[-1]
return ext in self.EXTENSIONS, ext
def load_file(filepath):
ext = filepath.split('.')[-1]
if ext == 'csv':
return pd.read_csv(filepath)
if 'xls' in ext:
return pd.read_excel(filepath)
... | The main task of the code is to validate an Excel file's structure and data against specified columns, constraints, and processes. It checks for file existence, valid extensions, required columns, data types, uniqueness, and duplicate entries. If errors are found, it returns detailed error messages; otherwise, it retur... | def validate_df2(self, excel_filepath, process, columns, unique_together: list[str]):
res = {}
result = 0
errors = []
if not excel_filepath:
errors.append('No excel file.')
if not process:
errors.append('No process specified.')
valid, ext = self.... |
def add_distance_data(table, gw_map='', header={}, table_name=''):
if ('DL' not in table.keys() or 'DL_ERR' not in table.keys() and gw_map):
dist_map = gw_map['DISTMU']
sigma_map = gw_map['DISTSIGMA']
nside = header['NSIDE']
area_per_pix = hp.pixelfunc.nside2pixarea(nside, degree... | This function adds redshift (z) and related columns (ra, dec, z_err) to an input table by matching its entries against a reference dataset. It uses either exact name matches or a crossmatch algorithm, populates missing columns with NaNs if needed, and updates the table with new/updated values. It also performs redshift... | def add_z(table, ref, procname, add_type, **kwargs):
redo = kwargs['redo']
# We need distance data for the host_crossmatch algorith, so add
if 'dl' not in table.keys() or 'dl_err' not in table.keys():
table = add_distance_data(table)
coltypes = ['ra','dec','z','z_err']
if any([procname+'... |
def download_yse(yse):
url = 'https://ziggy.ucolick.org/yse/explorer/{0}/download?format=csv'
url = url.format(yse)
data = requests.get(url)
table = ascii.read(data.text)
for key in table.keys():
table.rename_column(key, key.lower())
all_keys = list(table.keys())
use_key = None
... | The main task of the code is to integrate and process photometry data (both internal and external) into a table by formatting dates, coordinates, filters, and applying masks. It combines data sources, standardizes filter names, replaces unknown filters with 'r', adds photometry data to the table, and generates a combin... | def check_photometry(table, **kwargs):
# Import external and internal photometry
photdata = None
if 'photyse' in kwargs.keys() and kwargs['photyse']:
#print('DOWNLOADING YSE \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n')
photdata = download_yse(kwargs['photyse'])
if ('internal' in kwargs.keys() and k... |
def sanitize_table(table, reformat_columns=False, reformat_z=False,
remove_columns=False):
remove=[]
if len(table)>0:
for key in table.keys():
var = table[key][0]
if isinstance(var, (list, np.ndarray)):
remove.append(key)
for r in remove:
table.r... | The function processes an input table by cross-matching it with reference data from specified Redshift methods. It checks if reference files exist, builds them if needed, filters by redshift range, and adds cross-matched redshift values. Finally, it selects the best redshift from all methods and returns the updated tab... | def check_redshift(table, **kwargs):
if kwargs['redshift']['methods'] is None:
return(table)
for procname in kwargs['redshift']['methods']:
m='\tREDSHIFT: {proc}'
print(m.format(proc=procname.upper()))
method = 'crossmatch'
# Otherwise need to grab reference table an... |
def load_initial_data():
df = pd.read_csv('buildLiveDataPT/0_Data/deep_historic/ETH_full_5min.csv', on_bad_lines='skip')
df['DateTime'] = pd.to_datetime(df['DateTime'])
return df[['DateTime', 'Price', '24hr_Rolling_Volume_USD']]
def plot_data(df, is_peak, is_trough, past_peak_indices, past_trough_indices, p... | This code creates a GUI for visualizing cryptocurrency price trends using Tkinter and Matplotlib. It sets up a window with input and plot panels, initializes a price chart with historical data, and schedules periodic updates (every 5 minutes) to refresh the plot and countdown label. The GUI integrates API keys, currenc... | def create_gui(api_key, symbol, convert, csv_file_path):
print("creating tk window object")
window = tk.Tk()
print("setting tk window object title")
window.title("Crypto Price Trend")
# Input pane (left empty for now)
print("making input pane")
input_pane = tk.Frame(window, width=200)
i... |
def extract_case(img, i, j):
return img[i * CASE_WIDTH : (i+1) * CASE_WIDTH,
j * CASE_WIDTH : (j+1) * CASE_WIDTH,
:]
def draw_wall(img, i, j, direction, width, color):
case = extract_case(img, i, j)
if direction == grid.UP:
pixels_to_draw = case[0:width, :, :]
... | The code generates a visual representation of a grid-based game state, creating a 16x16 image where each cell is colored white, walls are drawn based on blocked neighbors, the goal cell is highlighted with a specific color, and robots are marked with distinct colors at their positions. | def create_picture(g):
img = np.empty((CASE_WIDTH * 16, CASE_WIDTH * 16, 3), np.uint8)
for i in range(16):
for j in range(16):
case = extract_case(img, i, j)
case[:] = np.array([255, 255, 255])
for direction in range(4):
... |
def _build_train(self):
print("-" * 80)
print("Build train graph")
logits = self._model(self.x_train, is_training=True)
log_probs = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits, labels=self.y_train)
self.loss = tf.reduce_mean(log_probs)
self.train_preds = tf.argmax(logits... | The code initializes a model's architecture by either sampling from a controller model or using a fixed arc, then constructs training, validation, and test components. It sets `self.sample_arc` based on `fixed_arc` or `controller_model.sample_arc`, followed by building the model's training, validation, and testing fram... | def connect_controller(self, controller_model):
if self.fixed_arc is None:
self.sample_arc = controller_model.sample_arc
else:
fixed_arc = np.array([int(x) for x in self.fixed_arc.split(" ") if x])
self.sample_arc = fixed_arc
self._build_train()
self._build_valid()
self._build_tes... |
def dataSplitter(ratioInt, dataSet):
trainRatio = ratioInt * 0.01
X = dataSet[:, :-1]
y = dataSet[:, -1:].ravel()
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=trainRatio, shuffle=True
)
return X_train, X_test, y_train, y_test
def holdoutHandler(clf, trainRatio... | The function `supervisedHandler` performs supervised learning using classifiers (Logistic Regression, SVM, KNN, Decision Tree) configured via a JSON dictionary. It initializes models with hyperparameters from the input, splits data using methods like holdout, k-fold, or random sampling, and evaluates performance based ... | def supervisedHandler(dataSet, jsonDict, metric):
header = ["Supervised Learning"]
iteration = 0
trainRatio = 0
# Classifier Logistic Regression
if jsonDict["classifier"] == "logisticRegression":
solver = jsonDict["solver"]
cvalue = float(jsonDict["Cvalforlogistic"])
clf = Lo... |
def SetProgress(self, progress):
"""
Wraps the methods used to update the progress bar value.
"""
from PySide import QtCore
self.progress_bar.setTextVisible(True)
self.progress_bar.setValue(progress)
QtCore.QCoreApplication.processEvents()
def ResetProgress(self)... | The main task of the code is to add a new OCCI repository to the application by fetching its metadata from a given URL, validating the response, checking for duplicates, and updating the UI table with a checkbox, repository name, maintainer, and remove button. The function also saves the repository data to persistent s... | def AddRepository(self):
"""
Loads the data for the given repository and adds it to the table.
"""
from functools import partial
import requests
import json
from PySide import QtGui, QtCore
# Get the repository URL entered by the user
repo_url = s... |
def ClearPreviousComponentResults(self):
"""
Wrapper for all the parameter data clean-up methods when a new search is
conducted or new parameter selected.
"""
self.ClearResultsTableHighlights()
self.selected_comp_lbl.setText("No component selected")
self.model_inf... | This function searches selected repositories for components by querying their OCCI servers, aggregates results into a table, handles errors, and updates the UI with progress and outcomes. | def SearchComponents(self):
"""
Searches the specified repositories for the given component.
"""
from PySide import QtGui, QtCore
import requests
import json
# Clear any previous results
self.results_tbl.clearContents()
self.ClearPreviousComponent... |
def ClearPreviousComponentResults(self):
"""
Wrapper for all the parameter data clean-up methods when a new search is
conducted or new parameter selected.
"""
self.ClearResultsTableHighlights()
self.selected_comp_lbl.setText("No component selected")
self.model_inf... | The main task of the code is to load and display parameters of a selected component from search results into a table. It highlights the selected component row, populates the table with parameter names, descriptions, and input widgets (e.g., spin boxes, text fields) based on data types, sets default values, and adds pre... | def LoadParameters(self):
"""
Loads the parameters for the selected component in the component search results table.
"""
from functools import partial
from PySide import QtGui, QtCore
# The stylesheet of the highlighted row
highlighted_row_style = "background-col... |
def LoadComponent(self):
"""
Loads a specific component into the current document.
"""
# Get the information for the selected component
namespace = self.FindSelectedComponent()
json_result = self.FindMatchingJSON(namespace)
# Make sure there was a row selected
... | This function updates an existing FreeCAD component by replacing its shape with a newly downloaded STEP file. It checks for an active document, locates the selected component, downloads the corresponding model, and replaces the component's geometry. If no document exists, it triggers a load instead. The process involve... | def UpdateComponent(self):
"""
Handles the task of updating a component that is already in the view.
"""
# If there is no active document, there is nothing to update
ad = FreeCAD.activeDocument()
if ad == None:
self.LoadComponent()
return
... |
def build_text_features(args):
# load data from gcp bucket, get adid list
config = load_json(args.data_config)
adid_name = config["hash_id"]["adid"]
if args.mode.startswith('train'):
df = read_data_parallel(args.train_path, config["schema"]["trainSchema"], cores=16)
adids = df[df[adid_n... | The main task of the code is to set up and execute a machine learning pipeline for SEM RPC prediction models. It parses input arguments for mode (train/score), model type (convrt/ordersize/rpc), data paths, and logging configurations. The script creates necessary directories, initializes logging, and conditionally runs... | def main():
# Input Arguments: argument parsing
parser = argparse.ArgumentParser(description="SEM rpc prediction model building pipeline.")
parser.add_argument("--mode", type=str, help="Pipeline mode: train, train-5fold, score, score-5fold")
parser.add_argument("--model_type", type=str, help="Model type... |
def new_list():
'''Runs when you press New button on Lists window.'''
t , lst = create_sq_table(simple = True)
layout = [
[sg.Text("Name:", s = (10,None)), sg.Input( key = 'Input', size = (20,4))],
[sg.Text("Description:", s = (10,None)), sg.Multiline( key = 'Description', size = (20,4))],... | The main task of the code is to manage task lists via a GUI, allowing users to view, create, remove, and load lists of tasks. It fetches list data from a database, displays it in tables, and handles interactions like loading selected tasks into another tab, updating totals, and modifying the database. The function retu... | def lists(window, bcolor, tcolor):
'''Runs when you pres Lists button on Curent tab. Returns if some list should be loaded'''
column2 = [[sg.T("Description:")],
[sg.Multiline("", key = "lists description",background_color = bcolor, text_color = tcolor, size = (30,4))],
[sg.Table(values = [[''],['']], ... |
def add_task():
'''
Add task to table Tasks. Returns id (or None if exit). Don't create a layout.
'''
h = 60
v = 1
r = 2
s = 10
# some starting values:
parent_id = None
checkpoints_str = ''
cur = con.cursor()
Data = [
[
sg.Text('Task ', size... | This function handles adding a new task to the database, checks for existing tasks from family members in the 'Curent' table, updates UI tables, inserts the task into 'Curent', adds a new row to the 'Today tasks' tab, and binds hover events to a time element for user interaction. | def add_task_button(window)-> None:
'''
Function that runs when you press add task button.
'''
id_in_tasks = add_task()
# check if the user exited
if not id_in_tasks:
return
# check if somebody from family is in curent
lst_of_parent = db_func.get_parents('Tasks', id_in_tasks)
... |
def get_user_details(self):
headers = self.get_headers()
endpoint = self.base_url
r = requests.get(endpoint,headers=headers)
check_status(r, 'Falied to get user data')
data = r.json()
self.user_name = data['display_name']
self.user_id = data['id']
... | This code initializes a class with an access token to fetch and store user data from an API, including user details, top artists, tracks, playlists, followed users, and recent activities. | def __init__(self,token):
self.access_token = token
self.get_user_details()
self.get_user_top_artists()
self.get_user_top_tracks()
self.get_user_playlist()
self.get_user_following()
self.get_recent() |
def pairwise_corr_sum_Q2(Y):
# returns Q2 matrix - optimization criteria - sum of pairwise Pearson correlations
cr = np.corrcoef(Y.T)
cr2 = cr*cr
return (np.sum(cr2)-cr.shape[0])/2
def split_into_continuos_ordinal(X,var_types):
# split into continuous and ordinal parts
indc = [i for i, x in enum... | The code performs optimal scaling on a data matrix by iteratively adjusting quantification of ordinal variables to maximize Q2 (correlation sum), ensuring monotonicity constraints. It uses gradient descent to update quantification tables, tracks convergence metrics, and optionally generates plots visualizing Q2 evoluti... | def optimal_scaling(X,var_types,verbose=False,producePlots=True,max_num_iterations = 100,tolerance=1e-5,vmax=1,fraction_max_step=0.9):
Q2 = pairwise_corr_sum_Q2(X)
if(verbose):
print('\n','Initial Q2:',Q2)
print('Initial quantification table:')
Xc,Xo,indc,indo = split_into_continuos_ordinal(... |
def make_grid(rows, cols, height):
grid = []
gap = height // rows
for i in range(rows):
grid.append([])
#print("Doing ROWS")
for j in range(cols):
#print("DOing Columns" , j)
spot = Spot(i, j, gap, rows, cols)
grid[i].append(spot)
return grid
def algorithm(draw, grid, start, end):
count = 0
open_s... | This function initializes a grid for pathfinding, sets the robot's starting position and the destination, updates neighboring cells for path calculation, and invokes a pathfinding algorithm to determine the route from the robot's position to the specified end point. | def path_planner_fn(self, win, width, height, end_row, end_column, robot_row_pos, robot_column_pos):
grid = make_grid(self.ROWS, self.COLUMNS, height)
# robot_pos = start
destination_pos = grid[end_row][end_column]
destination_pos.make_end()
robot_pos = grid[robot_row_pos][robot_column_pos]
robot_pos.make... |
def _get_lstm_features(self, sentence):
self.hidden = self.init_hidden()
embeds = self.word_embeds(sentence).view(len(sentence), 1, -1)
lstm_out, self.hidden = self.lstm(embeds, self.hidden)
lstm_out = lstm_out.view(len(sentence), self.hidden_dim)
lstm_feats = self.hidden2tag(lst... | This function computes the negative log-likelihood of a given sentence and its corresponding tags using an LSTM-based model. It calculates the forward score (log probability of the sequence) via the Viterbi algorithm and subtracts the score of the true tags to optimize the model's parameters during training. | def neg_log_likelihood(self, sentence, tags):
feats = self._get_lstm_features(sentence)
forward_score = self._forward_alg(feats)
gold_score = self._score_sentence(feats, tags)
return forward_score - gold_score |
def remove_dots(path: str):
folders = path.split("\\")
if "." in folders[-1]:
folders[-1] = folders[-1].replace(".", " ")
new_path = "\\".join(folders)
os.rename(path, new_path)
log("removed_dots", [new_path])
return new_path
else:
return path
def manage_nfo(p... | The main task of the code is to recursively process media files in a directory structure, handling trailer files, DTS audio detection, and file management based on flags. It checks each item, manages `.nfo` files, applies directory-specific actions (e.g., removing trailers, converting files), and logs DTS audio if enab... | def main_loop(root: str, flags: dict):
print(root)
if flags["remove_dots"]:
root = remove_dots(root)
dir_name = root.split("\\")[-1]
dir_has_files = False
for item_name in os.listdir(root):
item_path = root + "\\" + item_name
if os.path.isdir(item_path):
if os.lis... |
def get_dependencies() -> Dict[str, List[str]]:
res = collections.defaultdict(list)
for dep in DEPENDENCIES_MAPS:
script = dep["script"]
deps = []
if "dependent_files" in dep:
deps.extend(dep["dependent_files"])
if "dependent_dirs" in dep:
for dirc in dep... | (The main task of the code is to check or update checksums for dependencies based on command-line arguments. It reads an existing checksum file, verifies dependencies against it (or forces an update if `--skip_install` is used), and regenerates the checksum file if needed. The process involves parsing arguments, loggin... | def main() -> None:
parser = argparse.ArgumentParser(description="Run on deps changes.")
parser.add_argument(
"--skip_install", action="store_true", help="update checksum only"
)
args = parser.parse_args()
logging.basicConfig(
format="%(asctime)s [%(levelname)-5.5s] [%(process)d] (%... |
def distance_of_point_from_line(vessel: dict, point: np.ndarray):
x1 = vessel['BASIS']
x2 = vessel['TOP']
if is_point_on_line_between_points(start=x1, end=x2, point=closest_point_on_line(start=x1, end=x2, point=point)):
return np.linalg.norm(np.cross(x2 - x1, x1 - point)) / np.linalg.norm(x2 - x1)
... | This function projects a 3D point onto the closest vessel centerline (ILIACA or AORTA) based on distance comparison. It calculates displacement values from predefined reference points, appends these to a list, and stores the projected point coordinates. The decision between vessels depends on which has a shorter distan... | def project_single_point_on_centerline(point: np.ndarray):
if distance_of_point_from_line(vessel=ILIACA, point=point) <= distance_of_point_from_line(vessel=AORTA,
point=point):
closest_point = closest_point_on_vess... |
def predict_conductivity():
init_conductivity_dict()
cell_constant = calculate_cell_constant()
for key in CONDUCTANCES.keys():
for conductance in CONDUCTANCES[key]:
CONDUCTIVITIES[key].append(conductance / cell_constant)
def save_conductance_and_conductivites_as_csv():
"""
save c... | The main task of the code is to calculate cell constant and conductivity by predicting conductivity values, saving conductance/conductivity data as CSV files for analysis, and generating plots of conductances. It integrates prediction, data storage, and visualization steps to analyze electrochemical or material propert... | def calculate_cell_constant_and_conductivity():
predict_conductivity()
save_conductance_and_conductivites_as_csv()
save_data_analysis_conductivity_and_conductance_as_csv()
plot_conductances() |
def create_spark_session():
spark = SparkSession \
.builder \
.config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.0") \
.getOrCreate()
return spark
def process_song_data(spark, input_data, output_data):
df = spark.read.json(input_data)
cleaned_songs = df.where(df.so... | The main task of the code is to process music song and user log data using Apache Spark. It creates a Spark session, loads and processes song metadata from input files, then processes user activity logs while joining with the song data to generate structured outputs stored in the specified output directory. | def run(song_input_path, log_input_path, output_path):
spark = create_spark_session()
songs_df, artists_df = process_song_data(spark, song_input_path, output_path)
process_log_data(spark, log_input_path, output_path, songs_df, artists_df) |
def compute_gradient(self, model, optimizer, x, y_true, trainable_log_sigma, use_optimal_sigma):
def softclip(tensor, min_val):
return min_val + tf.keras.backend.softplus(tensor - min_val)
def gaussian_nll(y_true, y_pred, soft_log_sigma):
return 0.5 * tf.square((y_true - y_pred) ... | This code trains a Variational Autoencoder (VAE) model by iterating over training data, computing gradients with Adam optimizer, adjusting learning rates via a scheduler, and saving model checkpoints along with generated images every 1000 iterations. It prints loss metrics, enables real-time visualization if configured... | def fit(self):
self.model.summary()
print(f'\ntrain on {len(self.train_image_paths)} samples.')
print('start training')
iteration_count = 0
optimizer = tf.keras.optimizers.Adam(lr=self.lr)
os.makedirs(self.checkpoint_path, exist_ok=True)
log_sigma = tf.Variable(-1... |
def classictoquantum(eng, const, q):
for i in range(len(q)):
if (const & 1 == 1):
X | q[i]
const = const >> 1
def copy(eng, a, b):
for i in range(len(a)):
CNOT | (a[i], b[i])
def not_ripple_carry_add(eng, a, b, c0):
MAJ(eng, a[0], b[0], c0)
for i in range(len(a) - 1):... | The code implements the inverse Number Theoretic Transform (NTT) for quantum cryptographic operations in Kyber. It allocates quantum registers, processes data in chunks using modular arithmetic (Barrett/Montgomery reductions), and applies quantum-specific operations like ripple-carry additions and inversion functions. ... | def KyberInvNTT(eng, n):
for i in range(n):
globals()['r' + str(i)] = eng.allocate_qureg(16)
for j in range(n):
for i in range(int(n / 2)):
globals()['t' + str(i) + str(j)] = eng.allocate_qureg(16)
globals()['barrett_a1' + str(i) + str(j)] = eng.allocate_qureg(32)
... |
def classictoquantum(eng, const, q):
for i in range(len(q)):
if (const & 1 == 1):
X | q[i]
const = const >> 1
def FFM1(eng, r, temp1, c, k, n):
for i in range(len(r)):
CNOT | (r[i], temp1[i])
if zetas[k] != 1:
if zetas[k] < 0:
if test_input[n] > 0:
... | This code implements a quantum Number Theoretic Transform (NTT) for Kyber cryptography, allocating quantum registers for polynomial coefficients and performing modular arithmetic operations through Montgomery reduction. It initializes quantum states for input data, executes iterative butterfly operations using FFM1/FFM... | def Kyber_NTT(eng, n):
for i in range(n):
globals()['r' + str(i)] = eng.allocate_qureg(32)
for j in range(n):
for i in range(int(n / 2)):
globals()['t' + str(i) + str(j)] = eng.allocate_qureg(32)
globals()['mont_a' + str(i) + str(j)] = eng.allocate_qureg(16)
g... |
def migratePoms():
print(">>>>>>> Migrating POMs")
for i, module in enumerate(modules_to_build):
migratePomsInModule(i, module)
def migrateJavaFiles():
print(">>>>>>> Migrating Java Files")
for i, module in enumerate(modules_to_build):
migrateJavaFilesInModule(i, module)
def migrateDocke... | The code's main task is to migrate a project to Java 21 by updating Maven POM files, Java source files, Docker configurations, and push trigger scripts. It systematically executes migration steps for build configurations, codebase adjustments, containerization settings, and deployment triggers to ensure compatibility w... | def migrate():
print(f"Migrating to Java 21")
migratePoms()
migrateJavaFiles();
migrateDockerFiles();
migratePushTriggerFiles(); |
def migrate():
print(f"Migrating to Java 21")
migratePoms()
migrateJavaFiles();
migrateDockerFiles();
migratePushTriggerFiles();
def buildAll():
for i, module in enumerate(modules_to_build):
buildModule(i, module)
def addCommitAndPushAll():
for i, repo in enumerate(git_repos):
... | The main task of the code is to execute Git and build operations based on command-line arguments. It checks for flags like `migrate`, `build`, `add`, `commit`, `pushToOrigin`, and others, triggering corresponding functions such as `migrate()`, `buildAll()`, `addCommitAndPushAll()`, `listModules()`, and `gitStatusRepos(... | def main():
print("Args: " + str(args))
if args.migrate is not None:
migrate();
if len(mvnBuildCommand) > 0:
buildAll()
print(">>>>>>> Build completed.")
if args.add is not None or args.commit is not None or args.pushToOrigin is not None:
addCommitAndP... |
def reset(self):
self.startScreen = self.setupStartScreen()
self.mainScreen = self.setupMainScreen()
self.currScreen = "start"
self.currProgress = 0
self.skippedCharts = 0
self.chart = {}
self.mainTextRects = []
self.winTextRects = []
self.complete... | The code initializes an object's state for screen management, setting up initial screen states, countdown timers, color settings, and utility functions. It configures variables for tracking user input errors, screen transitions, and progress, while preparing win screen elements and resetting internal states for operati... | def __init__(self):
self.currScreen = "start"
self.badInpCountdown = [0, 500]
self.bgColor = bgColor
self.flashBrightness = 40
self.flashCountdown = [-500, 500]
self.reset()
self.prevScreenHold = False
self.badInpText = ""
self.util = Utilities()
... |
def init_env(quiet=False):
if os.path.exists(ENV_PATH):
return
print("Initializing Environment...")
write_env(quiet)
def pull_files():
print("Pulling Files...")
for f in FILES_TO_PULL:
get_file(f)
def pull_dockers():
print("Pulling Docker Images...")
for e in IMAGES:
... | The code initializes a METLO environment by creating a directory if it doesn't exist, then calls functions to set up the environment, pull required files, and retrieve Docker images, with an option to suppress output via the 'quiet' parameter. | def init(quiet=False):
if not os.path.exists(METLO_DIR):
os.mkdir(METLO_DIR)
init_env(quiet)
pull_files()
pull_dockers() |
def init(quiet=False):
if not os.path.exists(METLO_DIR):
os.mkdir(METLO_DIR)
init_env(quiet)
pull_files()
pull_dockers()
def init_env(quiet=False):
if os.path.exists(ENV_PATH):
return
print("Initializing Environment...")
write_env(quiet)
def start():
subprocess.run(["dock... | This code defines a command-line interface (CLI) tool with subcommands like 'init', 'start', 'stop', 'status', etc. It uses argparse to parse arguments, supports a '--quiet' flag to suppress prompts, and routes commands to corresponding functions (e.g., init(), start(), stop()). The main task is to provide a flexible C... | def main():
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(dest="command")
init_cmd = subparsers.add_parser("init")
init_cmd.add_argument(
"-q", "--quiet", help="Do not prompt for license key", action="store_true"
)
init_env_cmd = subparsers.add_parser("init-env")... |
def drawAvgFit(directories) :
hashData = {}
print('Reading data...')
for d in directories :
if os.path.isdir(d) :
if RECURSIVE :
tuplesWalk = os.walk(d)
for t in tuplesWalk :
if 'avg.txt' in t[2] :
print('\t->' + t[0])
with open(os.path.join(t[0], 'avg.txt'), 'r') as fileRead :
... | The main task of the code is to process command-line arguments, configure global variables (e.g., recursion, output directory, trials), and execute specific tasks like drawing fitness curves, performance metrics, behavior analysis, or video creation based on flags such as `--avg`, `--comp`, `--behavior`, etc. | def main(args) :
if args.recursive :
global RECURSIVE
RECURSIVE = True
if args.output is not None :
global OUTPUT_DIR
OUTPUT_DIR = args.output
if args.trials is not None :
global TRIALS
TRIALS = args.trials
if args.precision is not None :
global PRECISION
PRECISION = args.precision
if args.sele... |
def getholeheoutput(emaildata):
LoadingScreen("open")
def callback():
l1=holeheoutput(emaildata)
global insert_text
found=[]
notfound=[]
ratelimit=[]
for i in l1:
if "[x]" in i:
ratelimit.append(i)
ratelimit.app... | This function processes user input based on selected services, validating input and triggering corresponding data processing tasks like email lookup, domain/IP analysis, file hashing, or subdomain enumeration. It checks if a service is selected, ensures non-empty input, and executes specific functions (e.g., getholeheo... | def submitbutton(event):
global domain_IP_url, ghunt, file_hash, scylla, sublist, emailtophone, subserviceselection, insert_text
text.delete("1.0","end")
if domain_IP_url or ghunt or file_hash or scylla or sublist or emailtophone or holehe== True:
if subserviceselection==True:
if le... |
def print_board(elements):
for i in range(9):
if i%3 == 0:
print()
if elements[i]==-1:
print("_", end = " ")
else:
print(elements[i], end = " ")
print()
def solvable(start):
inv=0
for i in range(9):
if start[i] <= 1:
contin... | The main task of the code is to solve an 8-puzzle problem by taking user inputs for the start and goal states, checking if the puzzle is solvable, and then finding the solution if possible. It prints the initial board, verifies solvability, and outputs the number of moves required to solve the puzzle or states it's uns... | def main():
global g
start = list()
goal = list()
print("Enter the start state:(Enter -1 for empty):")
for i in range(9):
start.append(int(input()))
print("Enter the goal state:(Enter -1 for empty):")
for i in range(9):
goal.append(int(input()))
print_board(start)
... |
def searchtable(obj,col,table,db):
"""Search-Table function
Connects to the database in input and searches for a object in specific column of a table of that database
:param obj:Generally Username of Client
:type obj:string
:param col:Column name
:type col:string
:param ... | The LOGIN function authenticates users by verifying their username and password against a database. It handles repeated login attempts for invalid credentials, updates user status to "online," records connection details, and retrieves offline messages/images. Upon success, it updates socket mappings, closes prior conne... | def LOGIN(sending_socket, listening_socket):
"""Login function for existing clients
:param listening_socket:Listening socket
:type listening_socket:socket
:param sending_socket:Sending socket
:type sending_socket:socket
"""
#Logging in with username
sending_socket.se... |
def searchtable(obj,col,table,db):
"""Search-Table function
Connects to the database in input and searches for a object in specific column of a table of that database
:param obj:Generally Username of Client
:type obj:string
:param col:Column name
:type col:string
:param ... | This function registers a new client by collecting their username, password, and RSA key components (n, e, d, p, q). It checks for duplicate usernames, stores user data in a database, updates server connection tracking, and adds the client to socket dictionaries before initiating chatroom access. | def REGISTRATION(sending_socket, listening_socket):
"""Registration function for new clients
:param listening_socket:Listening socket
:type listening_socket:socket
:param sending_socket:Sending socket
:type sending_socket:socket
"""
#Registartion for new user
sending... |
def _get_data_loader(self, mode: str):
mum_workers = self.config.num_workers if torch.cuda.is_available() else 0
dataset = AudioDataset(mode, self.config.DATA)
return DataLoader(
dataset,
batch_size=self.batch_size,
shuffle=True,
pin_memory=True,
... | The code trains a machine learning model using a training and validation data loader, sets up the model, optimizer, and scheduler, logs training progress, resumes from a checkpoint if specified, and saves model checkpoints after each epoch. It iterates over epochs, trains the model, evaluates performance, records metri... | def train(self):
train_loader = self._get_data_loader('train')
val_loader = self._get_data_loader('val')
self._setup_model()
self._setup_optimizer()
self._setup_scheduler(self._optimizer, train_loader)
self._workspace = Workspace(self.config.output_dir, mode='train')
... |
def _get_data_loader(self, mode: str):
mum_workers = self.config.num_workers if torch.cuda.is_available() else 0
dataset = AudioDataset(mode, self.config.DATA)
return DataLoader(
dataset,
batch_size=self.batch_size,
shuffle=True,
pin_memory=True,
... | The code sets up and executes a testing pipeline by configuring batch size and shuffling, loading a test data loader, selecting between ONNX runtime or PyTorch model based on hardware availability, initializing a test workspace, logging evaluation start, and invoking the evaluation process on the test dataset. | def test(self):
self.batch_size = self.config.TESTING.batch_size
self.shuffle = self.config.TESTING.shuffle
test_loader = self._get_data_loader('test')
if self.config.TESTING.onnx_runtime and not torch.cuda.is_available():
self._ort_session = onnxruntime.InferenceSession(sel... |
def count_tokens(self):
tokens = word_tokenize(self.text)
return len(tokens)
def break_up_file_chunks(self, filename, chunk_size=500, overlap_size=100):
tokens = word_tokenize(self.text)
return self.break_up_file(tokens, chunk_size, overlap_size)
def convert_to_detokenized_text(self, tok... | The code splits a text into overlapping chunks of 2000 tokens each (with 100-token overlap), counts tokens, and generates prompts by wrapping each chunk in triple quotes and appending it to a list. It prints token counts and chunk lengths during processing. The primary task is to prepare text chunks for sequential proc... | def chunk_text(self):
token_count = self.count_tokens()
print("The text {} has {} tokens".format(self.text, token_count))
chunks = self.break_up_file_chunks(self.text, chunk_size=2000, overlap_size=100)
for i, chunk in enumerate(chunks):
print("Chunk {}: {}".format(i, len(chu... |
def arg_parse():
# Command line is <action.py> [args] -- rustc command line
parser = argparse.ArgumentParser()
parser.add_argument("--mode")
parser.add_argument("--buildscript")
parser.add_argument("--sysroot", type=Path)
parser.add_argument("--output")
parser.add_argument("--package-name")
... | The main task of the code is to execute different functions based on the parsed arguments. It parses command-line arguments, checks the 'mode' parameter, and runs either `run_args` or `run_srcs` accordingly. If the mode is unrecognized, it raises a runtime error. The code serves as a controller to delegate tasks to spe... | def main():
args = arg_parse()
if args.mode == "args":
run_args(args)
elif args.mode == "srcs":
run_srcs(args)
else:
raise RuntimeError("Unknown mode: " + repr(args.mode)) |
def size_covariance_Z_Z(df_int):
formations = list(set(df_int['formation'].to_list()))
ncov = 0
for layeri in formations:
df_resti = df_int.groupby(df_int.formation).get_group(layeri).groupby(df_int.point_type).get_group('rest')
ncov = ncov + len(df_resti)
return ncov
def invert_covaria... | This function calculates an estimated potential field (Z1_est) by inverting a covariance matrix and combining it with drift terms and orientation vectors. It uses geostatistical methods to estimate spatial fields based on input data, covariance structures, and drift models (zero, first-order, or other). The result is a... | def calc_potential_field(self):
nx = np.shape(self.X_grid)[1]
nz = np.shape(self.Z_grid)[0]
ncov = size_covariance_Z_Z(self.df_int)
self.invert_covariance()
self.covariance_Z1new_vector()
self.covariance_Z1new_Z2vector()
self.drift_vector()
if self.dri... |
def initilize_arguments():
""" Setup the command line argument parser """
parser = argparse.ArgumentParser()
# add arguments to the parser
parser.add_argument("-e", "--examples", action="store_true")
parser.add_argument("-i", "--interactive", action="store_true")
parser.add_argument("-m", "--max... | The code's main task is to execute application tasks based on command-line arguments, handling interactive mode, example generation, and user input for color values, while managing screen settings and providing an exit prompt in interactive mode. | def run():
""" Do all the tasks for this application """
args = initilize_arguments()
if args.interactive:
screen_alt()
if args.examples:
examples(args.max_colors)
else:
colors = ask_for_numbers()
print (example_line(colors))
if args.interactive:
input(... |
def get_Ngram(attack_name , N): #create an file that has the N-gram for each attack, then return list of N-grams.
""""
return string of N-grams if txt file os exsit otherwise it crete one and return it.
"""
if classes.os.path.isfile('most_common_{}.txt'.format(attack_name)) == True:
with open('m... | The code computes the maximum average similarity between N-grams of input data and attack patterns using Jacobian and Cosine similarity metrics, returning their average. It iterates through all N-gram pairs, updates the highest similarity scores, and handles division errors. | def get_rate_from_functions(data, attack_name,N):
data_to_Ngram = [data[i:i+N] for i in range(len(data)-N+1)]
attack_Ngram = get_Ngram(attack_name,N)
#print(attack_Ngram)
jacob = 0.1
cosine = 0.1
for i in data_to_Ngram:
#print(i)
for j in attack_Ngram: # there is a bug here with... |
def split_message(packet):
if 'POST' in packet.split('\n')[0]:
split_parts = packet.split('\n\n')
return (split_parts[0], split_parts[1])
return packet.split('\n\n')[0]
def headers_filtration(packet):
"""
this functuin check the headers of packet for "wrong" parameters.
:return... | The function `calc_vulnerability` analyzes a suspicious network packet by splitting it into headers and data, assessing header risks, and evaluating data risks. It determines the threat level using risk scores and returns actions like block, remove, or ignore based on predefined thresholds. | def calc_vulnerability(suspicious_packet):
"""
"""
splited_message = split_message(suspicious_packet)
if len(splited_message) > 1:
headers , data = splited_message[0] , splited_message[1]
else:
headers , data = splited_message[0], None
headers_risk = headers_filtrat... |
def read_input():
data = Path('input05.txt').open('r').read().strip()
stacks_data, moves_data = data.split('\n\n')
return read_stacks(stacks_data), read_moves(m)
def total_score(opponent: Iterable[int], us: Iterable[int]) -> int:
return sum(round_score(a, b) for a, b in zip(opponent, us))
def find_move_... | The code processes input rows into two columns, maps them to rock-paper-scissors moves, calculates the total score for task 1 by comparing opponent and user moves, then remaps the second column to determine user moves based on desired outcomes (win/lose/draw), recalculating the score for task 2. | def main():
rows = read_input()
column0, column1 = zip(*rows)
mapping_abc = {'A': ROCK, 'B': PAPER, 'C': SCISSORS}
moves_opponent = [mapping_abc[key] for key in column0]
mapping_xyz = {'X': ROCK, 'Y': PAPER, 'Z': SCISSORS}
moves_us = [mapping_xyz[key] for key in column1]
print('(task 1) to... |
def read_input(path: str) -> List[List[int]]:
content = pathlib.Path(path).open('r').read()
lines = [line.strip() for line in content.strip().split('\n')]
return [[int(value) for value in line] for line in lines]
def is_visible(grid: List[List[int]], x: int, y: int) -> bool:
own_height = grid[y][x]
... | The code processes a grid of trees from an input file. It calculates two tasks: (1) counting trees visible from the outside edges by checking each cell's visibility, and (2) determining the maximum scenic score for any tree by evaluating views in all four directions. The results are printed for both tasks. | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='input08.txt')
args = parser.parse_args()
grid = read_input(args.input)
num_visible = 0
for y, x in itertools.product(range(len(grid)), range(len(grid[0]))):
num_visible += int(is_visible(grid, x, y))
... |
def read_input(path: str) -> Tuple[Grid, Position, Position]:
content = pathlib.Path(path).open('r').read().strip()
lines = [line.strip() for line in content.strip().split('\n')]
start_position, best_signal = (-1, -1), (-1, -1)
grid = []
for y, line in enumerate(lines):
row = []
fo... | The code's main task is to solve two pathfinding problems in a grid. It reads input data, calculates the shortest path from a start point to a target (best_reception) for Task 1, and determines the shortest trail (possibly with additional constraints) for Task 2, outputting step counts for both. | def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='input12.txt')
args = parser.parse_args()
grid, start, best_reception = read_input(args.input)
print(f'Task 1: Shortest way in {find_shortest_way(grid, start, best_reception)} steps.')
print(f'Task 2: Shortest... |
def parse_rich_text_section(element: dict, bot_user_id: str=None, kv_sep=":", is_bullet=False) -> dict:
if not element['type'] in ['rich_text_section', 'rich_text_quote', 'rich_text_preformatted']:
raise NotImplementedError(pformat(element))
if not bot_user_id and not is_bullet:
raise ... | The function `parse_rich_text` processes a "rich_text" element by iterating through its sub-elements, parsing each based on its type (e.g., section, quote, list), and aggregating results into a dictionary. It stops parsing if a `STOP_PARSING` flag is encountered. Partial results are logged, and conflicting keys are mer... | def parse_rich_text(element: dict, bot_user_id: str=None) -> dict:
if not element['type'] == 'rich_text':
raise NotImplementedError(pformat(element))
d = {}
for e in element['elements']:
etype = e['type']
if etype == 'rich_text_section':
dd = parse_rich_text... |
def get_q(self, state: Dict[str, int], action: int) -> float:
internal_state: Tuple[int, int, int, int] = self.state_to_internal_state(state)
state_action = internal_state
np_state_action = np.array(state_action)
return self.model.predict(np_state_action.reshape(1, -1))
def a... | This function updates Q-values using the Bellman equation during reinforcement learning training. It calculates the next state's maximum Q-value, computes the updated value as reward + discount * best_q, and updates the current state-action pair's Q-value. If the episode ends, it increments the episode counter. | def observe(self, iteration, s1: Dict[str, int], action: int, reward: float, s2: Dict[str, int], end: bool) -> None:
""" this function is called during training on each step of the game where
the state transition is going from state s1 with action a to state s2 and
yields the reward r. I... |
def get_q(self, state: Dict[str, int], action: int) -> float:
# Returns Q(s,a) based on a state and action pair
internal_state: Tuple[int, int, int,
int] = self.state_to_internal_state(state)
if internal_state in self.q_values:
action_reward_pair: Dict... | This function updates the Q-value for a state-action pair in a Q-learning agent based on the observed reward and next state. It calculates the new Q-value using the Bellman equation, incorporating the learning rate and discount factor. If the episode ends, it increments the episode counter. The method is called iterati... | def observe(self, iteration, s1: Dict[str, int], action: int, reward: float, s2: Dict[str, int], end: bool) -> None:
""" this function is called during training on each step of the game where
the state transition is going from state s1 with action a to state s2 and
yields the reward r. I... |
def before_nback(self, answers, i, q):
''' Show the numbers before 'N'th. '''
self.ready_screen(i)
print("{} Ready.".format(q))
answers.append("----")
time.sleep(DEFAULT_TIME)
def after_nback(self, answers, i, q):
''' Show the numbers from N'th to total. '''
ans... | The code processes a sequence of quests in a game, handling two stages: before and after a specified number of back steps (nback). It collects user answers, pauses briefly, clears the screen, and displays the game results by comparing collected answers with correct ones. | def game_start(self):
answers = []
for i, q in enumerate(self.quests):
# Show N-1 numbers.
if i < self.nback:
self.before_nback(answers, i, q)
else:
self.after_nback(answers, i, q)
time.sleep(0.1)
self.clear_screen()
... |
def construct_options(self, start_point, goal_point, sub_dir):
self.env.set_start_and_goal(s=start_point, g=goal_point) # danger: goal_point.is_terminal
self._goal_point = goal_point
sub_dir = os.path.join(self.opt_args.opt_sub_dir, sub_dir)
rl_agent = DQNAgent(env=self.env, args=self.ar... | The main task of the code is to construct a topological map for navigation between cluster centers and sub-goals. It builds an adjacency matrix with weighted edges representing average steps between nodes (centers and sub-goals), connects them using navigation metrics, ensures graph connectivity, and prepares a Network... | def build_topo_map(self):
'''
How to use this topo map: when getting a new (start, goal) pair, we need to first identify the corresponding cluster center pair;
then we need to find the shortest path between the two centers based on this topo map; (so the weights of the ... |
def find_potential(set_of_points):
ans = 0
for i,val in enumerate(set_of_points):
for j in range(i+1,len(set_of_points)):
dist = box_distance(val,set_of_points[j])
ans += (4*eta*((sigma/dist)**12 - (sigma/dist)**6))
return ans
def return_force_arr(set_of_points):
force_ar... | The code iteratively adjusts a set of points by calculating forces and updating their positions until the system's energy stabilizes (within a tolerance of 1e-21). It returns the final configuration after convergence, representing a minimized energy state. | def find_config(set_of_points):
iterations = 0
ini_config = set_of_points.copy()
while(True):
iterations+=1
starting_energy = find_potential(ini_config)
force_arr = return_force_arr(ini_config)
second_state = return_second_state(ini_config,force_arr)
second_state = r... |
def downloadFileFromS3(key,foldername):
isFolderExist(foldername)
path = "./"+foldername+"/"+key;
s3_client.download_file(BUCKET_NAME,key,path)
print("File Downloaded")
def convertPdftoImages(inputPath,outputPath,fileName):
pages = convert_from_path("./"+inputPath+f"/{fileName}.pdf")
isFolder... | The main task of the code is to process PDF files stored in an S3 bucket by downloading them, converting them to images, applying skew correction and text detection, reassembling them into a new PDF, and uploading the processed PDF back to S3 while managing intermediate files. Non-PDF files (e.g., JPEG/JPG) are acknowl... | def main():
try:
for obj in bucket.objects.all():
print(f"obj:{obj}")
# keyname (e.g = Xyz.pdf)
keyname = obj.key
print(f"keyname:{keyname}")
# print(f"obj type: {keyname.split('.')[1]}")
# filename (e.g = Xyz)
filename = k... |
def _level_up(self):
if self.aliens.sprites():
pass
else:
self.gamestats.level += 1
print(f"Level{self.gamestats.level}")
# increase difficulty
self.settings.ship_speed += 0.2
self.settings.bullet_speed += 0.1
self.setti... | The main task of the code is to update the game screen by redrawing elements like the background, ship, bullets, and aliens, handling game logic such as movement, collision checks, and score display, while maintaining a 60 FPS frame rate and managing game state transitions like level progression and ship collisions. | def _update_screen(self):
# make the most recently drawn screen visible
self.screen.blit(self.background,(0,0))
self.ship.blitme()
self._level_up()
self._move_aliens()
for bullet in self.bullets.sprites():
bullet.draw_bullet()
... |
def init_spooler(config):
global _spool_dir
global _credential
global _KVUri
global _logger
_credential = DefaultAzureCredential()
keyVaultName = config["guac"]["vaultname"]
_KVUri = f"https://{keyVaultName}.vault.azure.net"
logging.initialize_logging(config)
_logger = logging.getL... | The main task of the code is to parse a configuration file, initialize system components (spooler, credentials, logging), process a spool directory, update status, and return an exit code. It validates the config path, loads JSON settings, and executes workflow steps for autoscaling. A TODO indicates future dynamic dom... | def main() -> int:
parser = ArgumentParser()
parser.add_argument(
"-c", "--config", help="Path to autoscale config.", required=True
)
global _spool_dir
global _credential
global _KVUri
global _logger
args = parser.parse_args()
config_path = os.path.expanduser(args.config)
... |
def forward_check(self, variable, value, assignment):
if self.do_forward_checking:
self.forward_checking(variable, value, assignment)
def consistent(self, variable, assignment):
for constraint in self.constraints[variable]:
if not constraint.satisfied(assignment):
... | This code implements a backtracking search algorithm for constraint satisfaction problems. It recursively assigns variables using heuristics, checks consistency, applies forward checking, and backtracks when constraints are violated. Solutions are stored when all variables are assigned. | def backtracking_search(self, assignment):
self.visited += 1
if len(assignment) == len(self.variables):
self.results_.append(assignment.copy())
return assignment
variable = self.heuristic_select_variable(assignment)
for value in self.heuristic_select_domain(var... |
def get_func_by_byteseq_from_call(function_name, byte_seq, offset):
seq_addr = find_byte_sequence(byte_seq)
call_addr = seq_addr + offset - 1 # The address of the byte sequence, adding it the length of the byte_seq, but decreasing the pointer by 1 to the begining of the call instruction
found_function_addr = get_ope... | The main task of the code is to analyze a binary using IDA Pro by locating a function based on a byte sequence and offset, determine its address, and record the result in a CSV file. It retrieves input parameters, processes the function location via two methods (depending on the `from_call` flag), updates the CSV with ... | def main():
win_version = idc.ARGV[1]
is_64 = literal_eval(idc.ARGV[2])
function_name = idc.ARGV[3]
byte_seq = idc.ARGV[4]
offset = int(idc.ARGV[5])
output_path = idc.ARGV[6]
from_call = literal_eval(idc.ARGV[7])
idaapi.auto_wait()
if from_call:
result = get_func_by_byteseq_from_call(function_name, byte_... |
def showDeltaPsi(self):
if self.config.spherical:
self.ploeter.plotDeltaPhiSpherical()
else:
self.ploeter.plotDeltaPhi()
def showRes(self):
if self.config.spherical:
self.ploeter.sphericalPlot()
else:
... | This code initializes a GUI interface with buttons for plotting data (DeltaPsi and Results), compiling, and running simulations. It creates a labeled frame containing these buttons, each linked to specific methods (showDeltaPsi, showRes, compileClick, runClick) and positions them using grid and pack layouts for user in... | def btnInit(self):
buttonFrame = LabelFrame(self.root)
deltaBtn = Button(buttonFrame,text="Plot DeltaPsi",command=lambda:self.showDeltaPsi())
deltaBtn.pack(side=LEFT)
showBtn = Button(buttonFrame,text="Plot Results",command=lambda:self.showRes())
showBtn.pack(side=RIGHT)
... |
def resultListInit(self):
#get all file names inside esults path
resultsList = os.listdir(RESULT_P)
resultsFrame = LabelFrame(self.root,text="Results List")
# sort by time
resultsList.sort()
scrollbar = Scrollbar(resultsFrame)
scrollbar.pack( side = L... | The main task of the code is to initialize the user interface components of an application by calling multiple initialization methods. These methods set up elements like result lists, buttons, configuration panels, information boxes, filters, and font options, ensuring the UI is properly structured and functional for u... | def initUi(self):
self.resultListInit()
self.btnInit()
self.configUiInit()
self.infoBoxInit()
self.initFillter()
self.initFontOpt() |
def initialize_population(self):
population = []
for i in range(self.population_size):
population.append(random.sample(range(8),8))
return population
def parents_selection(self, population):
return random.sample(population, 5)
def crossover(self, parent1, parent2):
cr... | The code implements an evolutionary algorithm to iteratively optimize a solution by initializing a population, selecting parents, generating offspring via crossover and mutation, updating the population, tracking the best solution's fitness, and returning the final solution along with execution time. | def evolutionary_algorithm(self):
population = self.initialize_population()
iteration = 0
start_time = time.time()
while iteration < self.termination_limit:
parents = self.parents_selection(population)
offspring = []
for i in range(self.offspr... |
def getAssignment(p1 , p2):
assert(len(p1) == len(p2)) , "p1 and p2 must have same number of points"
num_points = len(p1)
data_ = data_matrix(p1 , p2)
solver= pywraplp.Solver.CreateSolver("SCIP")
# Creatinng the optimization variables
x = {}
for i in range(num_points):
for j in rang... | The code performs interpolation between two points p1 and p2 using varying lambda values (0.1–0.9). It visualizes the original points (labeled "cake" and "tree") and generates intermediate points for each lambda, displaying them. If `getAssignment` returns a valid dictionary, interpolation proceeds; otherwise, it print... | def get_interpolation(p1 , p2):
print("Starting.....\n")
ans_dict = getAssignment(p1 , p2)
visualize_numpy_points(p1 , "cake")
visualize_numpy_points(p2 , "tree")
if ans_dict:
for lmbda in [0.1 , 0.2, 0.3 , 0.4 , 0.5 , 0.6 , 0.7 , 0.8 , 0.9]:
intermediate_point_list = interpolati... |
def send_peer_profile():
username = input("Enter your username: ")
hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)
Port = random.randint(8001, 8100)
print(ip_address,Port)
url = 'http://localhost:8000/send_peer_profile'
data = {
'username': username,
... | This code provides a menu-driven interface for managing user interactions in a peer-to-peer system. It loops, displaying options to signup, view all users, retrieve a user's address, connect to a user, or cancel. Based on user input, it calls corresponding functions like send_peer_profile(), request_get_all_peers(), et... | def main():
while True:
print("--------------------------------")
print("1. Signup")
print("2. Display all users")
print("3. Get address of a user")
print("4. Connect to a user")
print("0. Cancel")
print("--------------------------------\n\n")
choice =... |
def get_days_since_pr_creation(pr):
# date received from api is in utc
created_date = get_date_from_string(pr['created_at'])
date_now = get_utc_now()
return get_days_diff(date_now, created_date)
def get_day_count_for_pr_status(pr):
days_since_creation = get_days_since_pr_creation(pr)
# should n... | The function generates a message summarizing a pull request's health status and age, using emojis. It calculates days since creation and status-specific days, retrieves health data from a store, and appends appropriate emojis. The message format is '_Health_: [days]; [health] [emoji] [age emoji]', with conditional emoj... | def get_pr_status_message(pr):
pr_status_store = slack_store['pr_status']
days_since_creation = get_days_since_pr_creation(pr)
days_for_status = get_day_count_for_pr_status(pr)
pr_health = pr_status_store[days_for_status]['health']
pr_age_emoji = get_emoji_for_number(days_since_creation)
if ... |
def get_labels_info(pr):
pr_labels = []
for label in pr['labels']:
pr_label = label['name']
if label['color'] in slack_store['label_emoji']:
pr_label += emojify(slack_store['label_emoji'][label['color']])
pr_labels.append(pr_label)
return '_Labels_: ' + ', '.join(pr_la... | The function `get_pr_details_text` aggregates and formats details of a pull request (PR) by retrieving its labels, status, and changes. It calls three helper functions to extract this information and combines them into a structured text string with tab-indented lines, providing a concise summary of the PR's key attribu... | def get_pr_details_text(pr):
pr_labels = get_labels_info(pr)
pr_status = get_pr_status_message(pr)
pr_changes = get_pr_changes_message(pr)
return '\n\t%s\n\t%s\n\t%s' % (
pr_labels, pr_changes, pr_status) |
def get_text_section(text):
section = get_section_block()
section['text'] = {
"type": 'mrkdwn',
"text": text
}
return section
def get_pr_message_text(pr, i):
pr_header_text = get_pr_header_text(pr, i)
pr_details_text = get_pr_details_text(pr)
return '%s%s\n' % (pr_header_tex... | This function generates a structured list of message blocks for displaying pull requests (PRs) with optional headers, PR details (author, message), buttons to open each PR, and a "Merge All PRs" button. It formats each PR as a text section with an avatar image, appends action buttons, and includes dividers between entr... | def get_content_blocks(valid_prs, top_header_text=None):
blocks = []
if top_header_text:
blocks.append(get_text_section(top_header_text))
for i, pr in enumerate(valid_prs):
pr_url = pr['html_url']
pr_author = pr['user']['login']
# not using field section for now as long tex... |
def resolve_dynamic_values(pyproject_contents: dict, pyproject_path: Path):
if not (
set(pyproject_contents["project"].get("dynamic", ()))
& CONSIDERED_PROJECT_FIELDS
):
return
if pyproject_contents["build-system"]["build-backend"].startswith("setuptools."):
resolve_dynamic_... | This function generates CFF (Citation File Format) content from a pyproject.toml file by mapping project metadata, applying templates, and sorting fields. It extracts configuration from "tool.cff-from-621", resolves dynamic values, merges static data, renders templates, fills default fields like "date-released", and re... | def generate_cff_contents(pyproject_contents: dict, pyproject_path: Path) -> dict:
tool_tables = pyproject_contents.get("tool", {}).get("cff-from-621", {})
order = tool_tables.pop("order", DEFAULT_FIELD_ORDER)
resolve_dynamic_values(
pyproject_contents=pyproject_contents, pyproject_path=pyproject_pa... |
def forward(self):
self.sparse_real_A = Variable(self.input_A)
if self.opt.nz>0:
self.fake_B = self.netG(self.real_A,self.label,self.noise)
else:
self.fake_B = self.netG(self.real_A,self.label)
self.real_B = Variable(self.input_B)
def backward_D(self):
# F... | This function optimizes the parameters of a GAN model by first performing a forward pass, then alternately updating the discriminator (D) and generator (G) networks. It zeros the discriminator's gradients, computes its loss via backpropagation, and updates its parameters. Next, it zeros the generator's gradients, compu... | def optimize_parameters(self):
self.forward()
self.optimizer_D.zero_grad()
self.backward_D()
self.optimizer_D.step()
self.optimizer_G.zero_grad()
self.backward_G()
self.optimizer_G.step() |
def return_actual_predicted(self, user_ratings):
num_users = len(user_ratings)
num_items = len(user_ratings[0])
all_user_predicted_ratings = []
all_user_actual_ratings = []
for user_index, user_rating in enumerate(user_ratings):
filtered_user_ratings = user_ratings[... | The code evaluates a recommendation system's performance by calculating metrics like MAE, Precision, Recall, and F1 Measure using actual and predicted user ratings. It then visualizes these metrics in a formatted table using matplotlib for clear presentation of evaluation results. | def evaluation(self, user_ratings):
all_user_predicted_ratings, all_user_actual_ratings = self.return_actual_predicted(user_ratings)
mae = self.calculate_mae(all_user_predicted_ratings, all_user_actual_ratings)
precision = self.calculate_precision(all_user_actual_ratings, all_user_predicted_rati... |
def possible_solutions(self, initial_pop_size, no_rec):
missing_items = [index for index, rating in enumerate(self.user_ratings_input) if rating == 0]
population = []
while len(population) < initial_pop_size:
combination = random.sample(missing_items, no_rec)
population.a... | The code implements a genetic algorithm to find the optimal solution by evolving a population over multiple generations. It uses selection, crossover (one-point or uniform), and mutation (swap or inversion) to generate new solutions. Fitness is evaluated based on predicted ratings and semantic similarity (semrating), w... | def genetic_algorithm(self, pop_size, mutation_rate, num_generations, crossover_func, mutation_func, no_rec):
all_recommendations = self.possible_solutions(pop_size * 2, no_rec)
fitness_scores_dict = {} # Initialize the fitness scores dictionary
population = self.generate_initial_population(al... |
def _create_cells(self): # make specified amount of cells in rows & columns
for i in range(0, self._num_cols):
self._cells.append([])
for column in self._cells:
for i in range(0, self._num_rows):
column.append(Cell(self._win))
if self._w... | The code initializes a maze generator by setting up grid parameters, creating maze cells, breaking walls recursively to form paths, setting entrance/exit points, and solving the maze. It uses randomization for maze generation and includes methods for cell creation, wall breaking, and pathfinding. | 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
self._cell_size_y = ce... |
def test_default_policy_simple_win(default_policy):
spy = Spy()
board = SpyingConnectFourBoard(spy)
# Set up a win in a column
board.state = make_tied_state()
board.state[4][2] = ConnectFourBoard.RED
board.state[4][3] = ConnectFourBoard.RED
board.state[4][4] = ConnectFourBoard.RED
board... | The main task of the code is to test the functionality of a default policy under different scenarios, including simple win, simple loss, and termination conditions. It calls three specific test functions to validate the policy's behavior and concludes with a success message using print_ok(). | def test_default_policy(default_policy):
test_default_policy_simple_win(default_policy)
test_default_policy_simple_loss(default_policy)
test_default_policy_termination(default_policy)
print_ok() |
def test_tree_policy_expand_first_node(tree_policy, expand, best_child):
board = ConnectFourBoard()
parent_node = Node(board)
start_len = len(parent_node.children)
expanded_node = tree_policy(parent_node, 3)
expanded_len = len(parent_node.children)
assert_equal(expanded_node.parent, parent_node)... | The code tests the functionality of a tree policy in an algorithm (likely MCTS). It verifies three key aspects: expanding the first node, selecting the best child node, and terminating the process. The test ensures the tree_policy, expand, and best_child functions work correctly together. If all tests pass, it prints "... | def test_tree_policy(tree_policy, expand, best_child):
test_tree_policy_expand_first_node(tree_policy, expand, best_child)
test_tree_policy_select_best_child(tree_policy, expand, best_child)
test_tree_policy_terminate(tree_policy, expand, best_child)
print("test passed")
print_ok() |
def get_newest_local_dataset() -> pd.DataFrame:
"""
Returns the most recent file locally saved data file as a Pandas
dataframe.
Checks for the presence of any data in the folder where daily data
is kept. If one or more files are present, it returns the newsest
file (chronologically, not c... | The main task of the code is to update or create an OHLC (Open-High-Low-Close) DataFrame for a specified currency pair (e.g., GBP to GHS). It checks for an existing local dataset; if found, it extends it with new data from the last recorded date up to the current date. If no dataset exists, it fetches data from 2017 to... | def update_ohlc(
base_currency: str = "GBP",
target_currency: str = "GHS"
) -> pd.DataFrame:
"""
This function checks for an existing dataframe, and updates it.
If it finds, it will update. If it doesn't find it, it will
default to fetching data from the beginning of 2017 till date.
... |
def redraw():
img = generate_viewer_image(pixels, pixels, location, iterations, colorizer)
img.save("explorer.png")
webbrowser.open(f"file://{pathlib.Path('explorer.png').resolve()}")
def update(newloc):
nonlocal location
history.append(location)
location = newloc
... | This code processes user commands to manipulate a location and history stack, handling actions like undoing moves, moving/zooming views, saving/loading locations, and generating GIFs. It updates the interface via redraw() after each operation, with 'undo' restoring previous states from the history. | def command():
nonlocal location
nonlocal history
command, *args = input("m> ").strip().split(" ")
if command == "undo":
if history:
location = history.pop()
redraw()
elif command == "move":
update(move(*args))
... |
def moveR(self):
self.x+=1
self.moveTail(self.x, self.y, 0)
def moveL(self):
self.x-=1
self.moveTail(self.x, self.y, 0)
def moveU(self):
self.y+=1
self.moveTail(self.x, self.y, 0)
def moveD(self):
self.y-=1
self.moveTail(self.x, self.y, 0) | This code defines a method `move` that directs an object to move in a specified direction (`'R'`, `'L'`, `'U'`, or `'D'`) for a given number of steps. It repeatedly calls corresponding movement methods (`moveR`, `moveL`, etc.) based on the direction, executing the action `step` times. | def move(self, dir, step):
if dir=='R':
for _ in range(step):
self.moveR()
elif dir == 'L':
for _ in range(step):
self.moveL()
elif dir == 'U':
for _ in range(step):
self.moveU()
else:
for _ i... |
def readInput(f):
limits = {
'left':999,
'right':0,
'bottom':0
}
grid = [['.'] * GRID_SZ for _ in range(GRID_SZ)]
while True:
ln = f.readline()
if not ln:
break
pts = ln.strip().split('->')
pts = [x.split(',') for x in pts]
... | The code reads input data into a grid and limits, simulates dropping sand onto the grid, prints the modified grid with limits, and outputs the result of the sand drop simulation. | def solv1(f):
grid, limits=readInput(f)
ret = dropSand(grid, limits)
printGrid(grid, limits)
print(ret) |
def readInput(f):
limits = {
'left':999,
'right':0,
'bottom':0
}
grid = [['.'] * GRID_SZ for _ in range(GRID_SZ)]
while True:
ln = f.readline()
if not ln:
break
pts = ln.strip().split('->')
pts = [x.split(',') for x in pts]
... | The code simulates sand dropping in a grid after extending the bottom boundary. It reads input, modifies the grid by adding a barrier at the new bottom, runs the sand simulation, prints the updated grid, and outputs the result of the simulation, likely representing the amount of sand that fell before overflowing. | def solv2(f):
grid, limits=readInput(f)
limits['bottom']+=2
for i in range(GRID_SZ):
grid[i][limits['bottom']] = '#'
ret = dropSand(grid, limits, True)
printGrid(grid, limits)
print(ret) |
def _check_keydown_events(self, event):
if event.key == pygame.K_RIGHT:
self.ship.moving_right = True
elif event.key == pygame.K_LEFT:
self.ship.moving_left = True
elif event.key == pygame.K_SPACE:
self._fire_bullet()
elif event.key == pygame.K_q:
... | This function handles user input events in a Pygame application by checking for quit commands, keyboard presses/releases, and mouse clicks. It delegates specific actions to helper methods like _check_keydown_events, _check_keyup_events, and _check_play_button, which process keyboard and mouse interactions to control ga... | def _check_events(self):
"""Respond to keypresses"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
... |
def _check_fleet_edges(self):
"""respond appropriately if aliens reach edge of window"""
for alien in self.aliens.sprites():
if alien.check_edges():
self._change_fleet_direction()
break
def _ship_hit(self):
"""actions for ship being hit by an enemy ali... | The main task of the code is to update alien positions, check for collisions between the ship and aliens, and detect if any aliens have reached the bottom of the screen. It first checks if the alien fleet hits the screen edges, updates alien positions, checks for ship-alien collisions (triggering a ship hit response), ... | def _update_aliens(self):
"""update all positions of aliens"""
self._check_fleet_edges()
self.aliens.update()
# look for collisions between the ship and alien ships
if pygame.sprite.spritecollideany(self.ship, self.aliens):
# print("Ship has been hit!")
s... |
def _check_events(self):
"""Respond to keypresses"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
self._check_keydown_events(event)
elif event.type == pygame.KEYUP:
... | The code runs the main game loop, continuously checking for events, updating game elements (ship, bullets, aliens) if the game is active, and redrawing the screen to maintain real-time interaction and visual updates. | def run_game(self):
"""start main loop of game"""
while True:
# watch for events that happen ingame
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_aliens()
... |
def get_dicom_roi_seqs(input_dir, roi_set_zip_file):
"""Gets an iterator of ROIs from a .zip file and the list of all DICOM images in the corresponding directory.
:param input_dir: path containing the DICOM images
:param roi_set_zip_file: path to the RoiSet.zip file containing the regions of interest
:r... | The main task of the code is to convert DICOM images and ImageJ ROI contours into NIfTI format. It processes DICOM data from `dicom_dir`, extracts ROI contours from a ZIP file, generates a 3D mask array, and saves it as a NIfTI mask file in `output_dir`. Additionally, it converts the DICOM images into a NIfTI image fil... | def main(dicom_dir, roi_zip_path, output_dir):
"""See file header for description.
:param dicom_dir: Directory of DICOM images
:param roi_zip_path: Path to .zip file of ImageJ contours
:param output_dir: Directory in which to put the NIfTI mask file
"""
# Set up the logging module
log_filena... |
def search(data, val):
"""
A linear search for a value in a list.
:param data: list of data
:param val: the value to search for
:return: True if present, False otherwise
"""
for item in data:
if item == val:
return True
return False
def where(data,val):
"""
A ... | The main task of the code is to test and compare different search methods (e.g., `search`, `where`, and `binSearch`) on both unsorted and sorted lists. It demonstrates how binary search (`binSearch`) only works correctly on sorted data, as shown by the final tests on `sortednums`. The code also explores why the helper ... | def main():
"""
The main function.
:return: None
"""
nums = [4, 7, 2, 1, 8, 3, 6]
print("5?", search(nums,5))
print("1?", search(nums,1))
print("5?", where(nums,5))
print("1?", where(nums,1))
# binary search on unsorted data
print("binary 1?", _binSearchRec(nums,1,0,len(nums)... |
def change_turn(self):
self.valid_moves = {}
if self.turn == RED:
self.turn = WHITE
else:
self.turn = RED
def update(self):
self.board.draw(self.win)
self.draw_valid_moves(self.valid_moves)
pygame.display.update()
def analizeMessage(self, message)... | This function handles a game piece's move validation and execution. If a valid move is made, it updates the board, removes skipped pieces, constructs a network message with move details, sends it via socket, changes turns, and awaits a response. It returns True on successful moves, False otherwise. | def _move(self, row, col):
piece = self.board.get_piece(row, col)
if self.selected and piece == 0 and (row, col) in self.valid_moves:
self.board.move(self.selected, row, col)
skipped = self.valid_moves[(row, col)]
self.board.skippedThisTurn = []
if skipped... |
def build_args():
"""Builds args for ddsp executable."""
if FLAGS.project_id:
project_id = check_project_id(FLAGS.project_id)
else:
project_id = get_project_id()
image_uri = 'gcr.io/' + project_id + '/amadeus-train:latest'
time_diff = datetime.datetime.now() - datetime.datetime(1970, 1, 1)
uid = i... | The code's main task is to build and push a Docker image, submit a job, enable TensorBoard for monitoring, and upload logs. It orchestrates these steps by parsing arguments, constructing the image, pushing it to a registry, initiating a job, configuring TensorBoard, and transferring logs for analysis. | def main(unused_argv):
"""Builds and pushes image, submits job and enables TensorBoard."""
args = build_args()
build_image(args)
push_image(args)
submit_job(args)
enable_tensorboard(args)
upload_logs(args) |
def _createInputs(self):
for i in range(self.n_inputs):
self.graph_obj.add_node(self.counter, type='input')
self.counter += 1
def _addLayer(self):
# Iterate random number of times depending on the nodes per level
for i in range(random.randint(1, self.max_nodes_per_level))... | The main task of the code is to generate a directed graph (DiGraph) using NetworkX, structured as a neural network. It initializes the graph, creates input nodes, adds layers iteratively based on the specified depth, and appends an output layer. A counter ensures unique node naming. The function constructs a layered gr... | def _generateGraph(self):
self.graph_obj = nx.DiGraph()
# Counter is used in the following functions for naming the nodes
self.counter = 0
# Create the inputs of the graph
self._createInputs()
# Add as many layers as given in the depth
for i in range(self.depth):
... |
def _writeModule(self, graph_nodes, graph):
with open(f"{os.path.join(self.directory, self.module_name)}.v","a") as f:
f.write(f"module {self.module_name} (")
f.write(self._getInputOfModule(graph_nodes))
f.write(self._getOutputOfModule(graph_nodes, graph))
def _writeWires(sel... | The main task of the code is to convert a graph representation into a Verilog module file. It extracts module name and directory from the input, processes graph nodes, creates a Verilog file, and writes the module structure, wire declarations, assignment logic, and module closure using helper methods. The code generate... | def convert(self, graph, module_name : str):
self.module_name = module_name.split('/')[-1]
self.directory = module_name.split('/')[0]
# Get all the nodes in the graph as list of tuples
# @0 contains node name
# @1 contains attributes
graph_nodes = graph.nodes(data=True)
... |
def _createInputs(self):
for i in range(self.n_inputs):
self.graph_obj.add_node(self.counter, type='input')
self.counter += 1
def _addLayer(self):
new_nodes = []
# Iterate random number of times depending on the nodes per level
for i in range(random.randint(1, se... | The main task of the code is to generate a directed graph (DiGraph) by creating input nodes, adding layers based on specified depth, connecting nodes, and handling redundancy. If redundancy is disabled, it constructs the full graph with outputs and validation. If enabled, it dynamically adds layers until no further con... | def _generateGraph(self):
self.graph_obj = nx.DiGraph()
# Counter is used in the following functions for naming the nodes
self.counter = 0
# Create the inputs of the graph
if (self.redundancy_free == False):
self._createInputs()
# Add as many layers as giv... |
def reachable(c_num, dest):
pos_loc_d = possible_att(dest)
check = any(c_num in pos_loc_d for loc in pos_loc_d)
return check
def is_next_to(dest, c_num):
distance = d_num(c_num, dest)
if distance == 7 or distance == 9:
return 2
if distance == 8 or distance == 1:
return 3
return None
def closest_nu... | The code calculates the minimum number of moves required to reach a destination position from a source position, likely on a chessboard, by iteratively checking reachability, adjacency, and selecting the closest valid move. It increments a counter ('tries') for each step until the destination is reached, then outputs t... | def solution(src, dest):
tries = 0
c_num = src
while c_num != dest:
if reachable(c_num, dest):
c_num = dest
tries += 1
elif is_next_to(dest, c_num):
tries += is_next_to(dest, c_num)
c_num = dest
else:
c_num = closest_num(possible_att(c_num), dest)
tries += 1
prin... |
def clean_test_defects(defect_ids):
"""
Clean pytest marker containing testrail defects ids.
:param list defect_ids: list of defect_ids.
:return list ints: contains list of defect_ids as ints.
"""
return [(re.search('(?P<defect_id>.*)', defect_id).groupdict().get('defect_id')) f... | This code collects test execution results from pytest, associates them with TestRail test cases using markers, and updates TestRail with test status (pass/fail/skipped), comments, defect IDs, and duration. It handles defect tracking, skip/block reasons, and immediately reports failed tests to TestRail when configured. | def pytest_runtest_makereport(self, item, call):
""" Collect result and associated testcases (TestRail) of an execution """
outcome = yield
rep = outcome.get_result()
comment = rep.longrepr
defects = None
defect_ids = None
if item.get_closest_marker(TESTRAIL_DEFE... |
def __publish_results(self):
""" Publish results in TestRail """
print('\n[{}] Start publishing'.format(TESTRAIL_PREFIX))
tests_list = [str(result['case_id']) for result in self.results]
print('[{}] Testcases to publish: {}'.format(TESTRAIL_PREFIX, ', '.join(tests_list)))
if se... | This method handles post-test session cleanup by publishing test results if not in single-test mode and closing the associated test run or plan based on configured IDs and the 'close_on_complete' flag. | def pytest_sessionfinish(self, session, exitstatus):
if self.results:
if not self.report_single_test:
self.__publish_results()
if self.close_on_complete and self.testrun_id:
self.close_test_run(self.testrun_id)
elif self.close_on_complete and ... |
def packageRetrieve(id):
from Packages import Packages
pacs = Packages()
pacs = pacs.update()
if id in pacs.packageDictionary.keys():
pak = pacs.packageDictionary[id]
if not pak:
return e.unexpected()
pak.metadata = pak.metadata.get_data()
pak.data = pak.data.... | This function handles HTTP requests for a package resource by routing GET, PUT, and DELETE methods to retrieve, update, and delete package data respectively, using the provided 'id' to identify the specific package. | def packagewID(id):
if request.method == 'GET':
return packageRetrieve(id)
if request.method == 'PUT':
return packageUpdate(id)
if request.method == 'DELETE':
return packageDelete(id) |
def get_data(self):
header = {'Authorization': 'token %s' % self.token}
try:
if self.isGithubRepoLink():
self.github_url = self.url
elif self.isNpmLink():
self.github_url = self.convert_toGithub()
else:
logging.warning... | This code initializes an object to retrieve and process data from a GitHub repository. It fetches repository details like contributors, issues, and license using a provided token. The `get_data()` method likely accesses the repository's API, while subsequent methods extract specific metrics. The object stores this data... | def __init__(self,url,token):
self.url = url
self.github_url = None
self.github_api_url = None
self.token = token
self.num_contributors = 0
self.issues = None
self.license = None
self.data = self.get_data()
self.license = None #license is in spdx_i... |
def findPortalOnSolid(solid):
"""Finds a portal on a solid"""
side = None
for child in solid.children:
if child.name == "side":
if child.properties["material"] == OUTSIDE_MATERIAL :
side = child
break
if side is None:
return None
return side.plane
def oppositeDirection(direction... | This code detects loops in a map where players can run in circles by checking pairs of doors positioned in opposite directions with zero translation vectors between their portals. It iterates through doors, identifies matching opposite-direction portals, and triggers a 'mend' process to correct invalid loop configurati... | def detectLoops(self):
"""Detect loops within this map (tiles positioned in such a way that the player can run in circles)"""
print("Detecting loops...")
zeroVector = numpy.array([0,0,0])
for direction in list(self.doors.keys()):
for portalSolidId in self.doors[direction]:
doorNodes = self... |
def detectLoops(self):
"""Detect loops within this map (tiles positioned in such a way that the player can run in circles)"""
print("Detecting loops...")
zeroVector = numpy.array([0,0,0])
for direction in list(self.doors.keys()):
for portalSolidId in self.doors[direction]:
doorNodes = self... | The code's main task is to remove leftover door entities from the map's exterior to make it compilable. It detects loops, iterates through door data, identifies relevant solid nodes, calculates portal bounds, and deletes door entities near those bounds. The function counts and reports removed doors, though some may rem... | def close(self):
"""Remove remaining door entities from the outside of the map so it becomes compilable."""
self.detectLoops()
# TODO: sometimes not all remaining doors are removed
removed = 0
for direction in list(self.doors.keys()):
for portalSolidId in self.doors[direction]:
doorNod... |
def start():
"""prompt user to enter support and confidence values in percent"""
support = int(input("Please enter support value in %: "))
confidence = int(input("Please enter confidence value in %: "))
maxr = int(input("Enter the max number of rules you want to see (enter 0 to see all rules): "))
... | This function generates association rules from frequent itemsets by iterating through each itemset, generating all possible subsets, calculating their support and confidence, and adding rules meeting the confidence threshold. It then prints the top 'maxr' rules sorted by confidence, showing antecedents, consequents, su... | def generate_association_rules():
L1,D, support, confidence, maxr = start()
s = []
r = []
length = 0
count = 1
inc1 = 0
inc2 = 0
num = 1
m = []
L= frequent_itemsets(L1, D, support)
print ("---------------------ASSOCIATION RULES------------------")
print ("----------------... |
def get_real_object_name(self, dict_options):
if dict_options['object'] == 'current':
return self.current()
return dict_options['object']
def object_exists(self, dict_options):
"""
Check if the specific object exists
"""
search_path = "workspace|input|obj... | The function sets an attribute on an object within the workspace using provided values from `dict_options`, updating both input and output object structures if the object exists. If the object does not exist, it fails with an error message indicating the failed attribute assignment. | def set_attribute(self, dict_options):
"""
Set the attribute called on the object with the passed in value
"""
new_attribute = dict_options['attribute']
new_value = dict_options['value']
obj = self.get_real_object_name(dict_options)
if self.object_exists(dict... |
def open_positions(self):
positions = []
for i in range(rows):
for j in range(cols):
if self.board[i,j] == 0:
positions.append((i,j))
return positions
def board_update(self, position):
self.board[position] = self.player_mark
self.pl... | The main task of the code is to train a reinforcement learning agent by simulating multiple rounds of a turn-based game. It alternates between two players (p1 and p2), allowing each to choose moves, updating the board state, checking for a win, and resetting the game upon a win. The process repeats for the specified nu... | def trainer(self, rounds = 100):
for i in range(rounds):
if i % 1000 == 0:
print(f"Rounds: {i}")
while not self.game_over:
options = self.open_positions()
p1_action = self.p1.choose_move(options, self.board, self.player_mark)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.