dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def get_item_by_ds_id_dynamodb(ds_id: str) -> dict:
'''
retreives a single ds_metavar item by its $ds_id
'''
response = table.get_item(Key = {'ds_id': ds_id})
response = jsonify(response)
if 'Item' in list(response.keys()):
response['Item']['meta-attributes']['size']['rows'] = int(response['Item']['meta-attrib... | This function deletes a dataset and its associated metavarset by first deleting the metavarset, then attempting to delete the dataset file via SCP. If dataset deletion fails, it reinserts the metavarset and raises combined error messages to handle inconsistencies between storage systems (DynamoDB, Elasticsearch, SCP). | def delete_dataset_and_metavars(endpoint:str, username:str, password:str, server_host:str, server_storage_path:str, ds_id:str):
'''
this is the create in the crud for the dataset-metavarset pair
'''
ds_metavarset = get_item_by_ds_id_dynamodb(ds_id)
dataset_filename = ds_metavarset['cleaned data file']
if delete_... |
def _get_configuration(project_dir, args):
"""
Get the final configuration to use.
This merges the defaults, file configuration if present, and command line
arguments, in that order of priority.
"""
# Start with the default configuration
config = _default_configuration()
# Update with... | The function `run` executes static analysis checks (include-what-you-use and clang-tidy) on a project's source and header files within a specified build directory. It configures include paths, loads compilation commands, filters excluded files, and runs parallel tasks to validate code consistency, dependencies, and sty... | def run(build_dir, **kwargs):
"""
Run checks on an entire project.
:param bool auto_headers: Automatically include matching language headers
in checks.
:param str build_dir: Path to build directory.
:param str exclude_patterns: List of regular expressions for files to
... |
def getStart():
return db.loadWallet()
def createDeck(deck):
cardDict = {"suits":['Clubs', 'Diamonds', 'Hearts', 'Spades'],
"ranks":['Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King'],
"values":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]}
suits = ca... | The code simulates a Blackjack game, allowing players to bet, play rounds, track their wallet balance, and record session details including start/end times and total money earned. It manages game mechanics, user input for playing again, and logs session data for tracking progress. | def main():
startMoney = 0.0
startMoney = getStart(startMoney)
wallet = startMoney
playAgain = "y"
while playAgain.lower() == 'y':
print("BLACKJACK!")
print("Blackjack payout is 3:2")
startTime = ""
startTime = programtime.getStartTime()
print()
... |
def get_ward_aois(wards_path=os.path.join(RAW_DATA_ROOT,'Ward Shapefiles', 'ward.results.geojson')):
with open(wards_path, 'r') as wards_file:
wards_json = json.load(wards_file)
aois = wards_json['features']
def _set_id_as_name(aoi):
aoi_name = aoi['properties']["NAME"]
aoi_name =... | This function downloads Planet Labs satellite imagery for a specified crop in a given county, processing and saving the data according to parameters like date ranges, cloud cover, and image adjustments. It handles AOI selection from wards or a database, applies seasonal date filters, creates storage directories, and ex... | def download_county_crop_tiles(county_name,
crop_table,
crop_name,
wards,
aoi_selector,
min_date,
max_date,
... |
def write_and_reproject_per_pixel_geojson(aoi_geojson, county_pixel_dir, crop_name):
""" Operates on a single geojson AOI to write out the current
projection and the projection we need to work with planet.
"""
geojson_input = os.path.join(county_pixel_dir, 'geojson_epsg4326_{}.geojson'.format(crop_n... | This function processes satellite data for a specific AOI by creating directories, generating GeoJSON files, querying Planet data, downloading and merging scenes, and resizing images for machine learning models. It handles errors by logging failures and writing diagnostic files. | def create_dirs_query_and_download(county_data,
aoi,
season,
crop_name,
collect_crop_yield_only,
extra_query_kwargs,
... |
def generate_error_sequence(seq, error):
# copied from "main" function in generateTestCases, redundant to make a dict in this
# case but was easiest way to make it work quickly
isoforms = {}
acc = "@sim|correct|full"
isoforms[acc] = seq
acc = "@sim|correct|error"
isoforms[acc] = seq
# 1 ... | The code evaluates and compares the performance of minimizers and syncmers in preserving k-mers and covering sequences under varying error rates (1-10%). It generates random sequences, introduces errors, computes metrics like preserved k-mer ratios and coverage, and visualizes results via bar and box plots to analyze s... | def main():
# presets for easy modification
seq_len = 10000
k = 15
w = k + 10
# syncmer algo in getMinimizersSyncmers was modified to take t parameter. If t = -1 it will still
# use the middle position as previously, otherwise it will use the given positio of t to determine
# s-mer position
... |
def receivePostion(self, s):
header = 64
msg_length = s.recv(header).decode('utf-8')
if msg_length:
msg_length = int(msg_length)
position = s.recv(msg_length).decode('utf-8')
position = int(position)
return position
def shortPath(self, index):
... | The main task of the code is to send a calculated "dose" value and positions along a computed shortest path to a client via a socket connection. It repeatedly retrieves a position until valid, calculates the path, iterates through it to send progressive position-dose pairs, and finally closes the socket connection. | def sendtoclient(self, s):
position = self.receivePostion(s)
while position == None:
position = self.receivePostion(s)
shortPath = self.shortPath(position)
for i in range(1, len(shortPath)):
dose = round((len(shortPath) - i) / len(shortPath), 2)
self.s... |
def _check_paths(self, path: str | Path | None) -> Path:
"""
Check if the path is valid
"""
if path is None:
click.echo("No path specified, defaulting to current working directory.")
path = Path.cwd()
if isinstance(path, str):
path = Path(path... | The code initializes a repository by validating the path, fetching the repository, determining the branch, gathering commit data, generating table rows, and printing the table. It processes version control data to display structured commit information. | def __init__(
self,
path: str | Path | None,
branch: str | None = None,
package: str | None = None,
rev: str | None = None,
) -> None:
path = self._check_paths(path)
self.repo = self._fetch_repo(path)
self.branch = self._pick_branch() if branch is None... |
def _calculate_Y_scores(self, data_set, models):
"""Predict each i-th instance of X given the chosen
weak models and return the Y score of them all"""
if len(models) == 0:
return None
X = data_set.X
Y_scores = np.zeros(len(X))
for i in range(len(X)):
... | This code trains a gradient boosting model by iteratively building weak CART learners, using early stopping based on validation loss. It splits data if no validation set is provided, updates models with gradients/hessians, applies shrinkage (learning rate), tracks best performance, and stops training if validation loss... | def train(self, params, training_set, num_boost_round=20,
validation_set=None, early_stopping_rounds=5):
self.params.update(params)
models = []
shrinkage_rate = 1.
best_iteration = None
best_val_loss = NUMBER_Infinity
# TODO: Should it be optional?
... |
def _calculate_Y_scores(self, data_set, models):
"""Predict each i-th instance of X given the chosen
weak models and return the Y score of them all"""
if len(models) == 0:
return None
return self.predict(data_set.X, models=models)
def _calculate_gradient(self, train... | This code trains an ensemble of gradient-boosted CART models using early stopping. It iteratively builds weak learners, updates parameters, validates performance, and halts training if validation loss stagnates. The function splits data, monitors training/validation loss, and retains the best model iteration. | def train(self, params, training_set, num_boost_round=20,
validation_set=None, early_stopping_rounds=5):
# Update custom params
self.params.update(params)
if self.params['min_samples_split'] < 2 * self.params['min_samples_leaf']:
raise ValueError('Parameter min_sampl... |
def setup_evaluation() -> Tuple[YOLOv1, DataLoader]:
"""
Instantiate the model, the PASCAL VOC test dataset and the corresponding loader. The model's weights are loaded from
the checkpoint file that was updated at the end of the training.
:return: The YOLOv1 (detection) model and the DataLoader of the ... | (The code's main task is to evaluate a machine learning model's performance on a test dataset. It sets up the model and test loader, computes the Mean Average Precision (mAP) and class-specific average precisions, prints the mAP value formatted to one decimal place, and optionally generates a plot visualizing class-wis... | def main():
model, test_loader = setup_evaluation()
mAP, average_precisions = evaluate_model(model, test_loader)
print(f'Mean Average Precision = {mAP:.1f}%')
if PLOT:
plot_class_ap(average_precisions) |
def _lives_ready(self):
curr_time = datetime.datetime.now(tz=TOKYO_TZ)
time_diff = (curr_time - self.__lives_time).total_seconds()
if time_diff > self.__lives_rate:
# core_logger.debug('Time difference of {} is greater than live rate of {}, '
# 'beginnin... | The code's main task is to periodically check and update live content, completed rooms, scheduled items, and perform maintenance. It evaluates readiness flags (`_lives_ready`, `_schedule_ready`, `_maintenance_ready`) to trigger corresponding updates: `update_completed`, `update_lives`, `update_schedule`, and `do_mainte... | def tick(self):
"""Periodic live and schedule check"""
if self._lives_ready():
# core_logger.debug('Checking lives')
# completed is checked before lives so that a completed room
# doesn't prevent a new live from being added
self.update_completed()
... |
def __read_file(self, path):
f = open(path, "r")
enable_reading = True
for line in f:
content = ""
for char in line:
if char == "#":
enable_reading = False
if char == "\n":
enable_reading = True
... | This code initializes a class by reading file content from a given path, setting up optional custom operations, processing the data to calculate results, and writing the outcomes. It manages file input, custom operation configuration, and result generation in a structured workflow. | def __init__(self, path, custom_operators=None):
self.content = list()
self.result_list = []
self.result_list.append(self.content)
self.__read_file(path)
self.custom_operation_enabled = False
if custom_operators is not None:
self.custom_op = self.__setup_custo... |
def get_end_list_to_gen_tree():
input_list = get_list_port("input")
for number, input in enumerate(input_list):
lines = get_line_include_string(input)
if(len(lines) and re.sub(' +', ' ', lines[-1]).split(" ")[1] == "assign"):
input_list[number] = re.sub(' +', ' ', lines[-1]).split(" ... | The code parses a tree structure to generate a boolean expression string. It traverses nodes, constructs parent-child relationships, and replaces operators like 'and', 'or', 'xor', 'inv' with symbols (&, |, ^, ~). The result is a simplified boolean expression printed as output. | def get_boolean(output):
boolean = ""
root_node = Node(output)
end_tree_list = get_end_list_to_gen_tree()
input_list = get_list_port("input")
get_tree(root_node, output, end_tree_list, input_list)
print()
for pre, fill, node in RenderTree(root_node):
print("%s%s" % (pre, node.name))... |
def get_Meta_data(directory_name):
file_path = f"{directory_name}/Meta_data.txt"
metadata = {}
try:
with open(file_path, 'r') as file:
for line in file:
key, value = line.strip().split(' : ')
metadata[key.strip()] = int(value.strip())
except FileNotFou... | This function computes the shortest path from a start node to an end node in a graph stored in a directory, using Dijkstra's algorithm for weighted graphs (Type 2) or BFS for unweighted graphs (Type 1). It reads adjacency lists from binary files, dynamically processes neighbors with edge weights, and returns the minimu... | def dijkstra(directory_name, start, end):
Type = get_Meta_data(directory_name)["Type"]
if Type == 1:
return shortest_distance_bfs(directory_name, start, end)
# Initialize distances dictionary to store shortest distances from start node
distances = {node: float('inf') for node in range(get_Meta_d... |
def get_Meta_data(directory_name):
file_path = f"{directory_name}/Meta_data.txt"
metadata = {}
try:
with open(file_path, 'r') as file:
for line in file:
key, value = line.strip().split(' : ')
metadata[key.strip()] = int(value.strip())
except FileNotFou... | The function calculates PageRank values for all nodes in a specified directory, sorts them in descending order, and stores the ranks and corresponding node indices in binary files. It iterates through nodes, retrieves their PageRank, and writes the sorted results to two types of files: one for node information and anot... | def calculate_rank(directory_name):
pairs = []
for i in range(get_Meta_data(directory_name)["Nodes"]):
rank = get_page_rank(directory_name,i)
pairs.append((rank,i))
sorted_pairs = sorted(pairs, key=lambda x: -x[0])
cnt = 1
for val,key in sorted_pairs:
file_path = get_node_... |
def create_event_data():
"""
Creating a smaller event data csv file called event_datafile_full csv that will be used to insert data into tables
INPUT: None
RETURN: None
"""
csv.register_dialect('myDialect', quoting=csv.QUOTE_ALL, skipinitialspace=True)
with open('event_datafile_new.csv', '... | The main task of the code is to execute an ETL (Extract, Transform, Load) process. It creates event data, initializes database tables, connects to a database, and inserts data from a CSV file into three tables: session_history, user_history, and song_history. Finally, it disconnects the database and confirms completion... | def main():
"""
Main program for etl.py
INPUT: None
RETURN: None
"""
# create event data
create_event_data()
print("Created event_datafile_new.csv")
# create tables
create_tables.main()
print("Created tables")
# connect to db
session, cluster = create_tables.connec... |
def get_section_strs(file_name):
section_str = ""
with open(file_name) as infile:
for line in infile:
if line.strip() == "Start Run":
section_str = ""
elif line.strip() == "End Run":
yield section_str
section_str = ""
el... | This function processes multiple input files to extract and compile x and y data for graphing, based on specified parameters (x_type, y_type, dim). It validates inputs, reads section data, computes time/iteration to meet tolerance, and organizes results into dictionaries for plotting. | def get_graph_info(infile_template, file_numbers, x_type, y_type, dim=1, tolerance=1e-14):
if y_type not in ("time", "iteration"):
raise ValueError("Unexpected Graph y_type")
if x_type not in ("num ranks", "theta"):
raise ValueError("Unexpected Graph x_type")
if dim not in (1, 2):
ra... |
def create_table(table_name):
conn = get_clinet()
create_query = '''CREATE TABLE IF NOT EXISTS login_test (email varchar(128) primary key, user_name varchar(64) not null, password varchar(64) not null);'''
print("Query Triggered: ", create_query)
cur = conn.cursor()
cur.execute(create_query)
con... | The code creates a login table, allows users to either create a new account (by entering email, username, and password) or log in (by verifying username/password against stored data). It handles errors during account creation/login and validates user credentials for successful login, with appropriate feedback for inval... | def get_user_credentials():
# create a table if not exists
create_table("login")
print("Login table created successfully")
login_in = input("Do you want to create a new account[Y/n]:")
if login_in.lower() == 'y':
email = input("Email:")
username = input("Username: ")
passwo... |
def draw_board(self):
self.scr.fill(self.WHITE)
for i in range(self.columns - 1):
pygame.draw.line(self.scr, self.BLACK, (self.rad*(i+1), 0), (self.rad * (i+1), self.height), self.border)
for i in range(self.rows - 1):
pygame.draw.line(self.scr, self.BLACK, (0, self.rad*(... | The main task of the code is to run a game loop that handles user input for a turn-based game, updates the game board, checks for win conditions, and ends the game when all cells are filled or a player wins. It uses Pygame to process events like window closure, mouse clicks, and updates the display accordingly. | def start(self):
self.draw_board()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pr... |
def get_data(feature, dataset, in_file, out_file):
"""
get dataset from file
:return: features, labels
"""
filepath = folder_path + dataset
prepare_file(filepath, out_file,
filename=in_file,
feature=feature)
dataframe = pd.read_csv(filepath + out_file, sep=... | The main task of the code is to create and prepare a gender prediction dataset by cleaning, balancing, and structuring input/output data. It ensures the dataset meets a minimum sample requirement, extracts relevant features (delta, delta2, pitch), and saves processed data files for model training. The output includes f... | def create_gender_dataset(out_data_path, min_samples=0):
"""
create the files holding the data for the gender prediction model
:param out_data_path: where to save the files
:param min_samples: minimum number of samples
"""
if out_data_path[-1] != '/':
out_data_path = out_data_path + '/'
... |
def get_data(feature, dataset, in_file, out_file):
"""
get dataset from file
:return: features, labels
"""
filepath = folder_path + dataset
prepare_file(filepath, out_file,
filename=in_file,
feature=feature)
dataframe = pd.read_csv(filepath + out_file, sep=... | The function processes and prepares an age-related dataset by cleaning input/output data, balancing class distribution using a minimum sample threshold, extracting acoustic features (delta, delta2, pitch), and saving processed features and labels to specified output files for further analysis or model training. | def create_age_dataset(out_data_path, min_samples=0):
if out_data_path[-1] != '/':
out_data_path = out_data_path + '/'
if min_samples <= 0:
min_samples = 2 ** 20
en_input, en_output = get_data("age", english_dataset_path, file_list[5], out_age_file)
inputs, outputs = clean_age_dataset(... |
def phv_calculator(archive, new_pt, ref):
# print(archive, '\n',new_pt, '\n', ref)
ps = deepcopy(archive)
ps.append(deepcopy(new_pt))
# ref = [5,5]
n = min([len(p) for p in ps])
pl = ps[:]
pl.sort(key=lambda x: x[0], reverse=False)
s = [(1, pl)]
for k in range(n - 1):
s_prime ... | The code performs a local search to optimize a multi-objective problem by iteratively generating perturbed solutions, evaluating them using a PHV metric, and maintaining a Pareto front of non-dominated solutions. It updates the best solution and Pareto set by comparing new candidates against the current best, removing ... | def local_search(node, link, obj, traffic, ref):
local_pareto = []
local_pareto.append(obj)
best_phv = phv_calculator(local_pareto, obj, ref)
best_obj = deepcopy(obj)
n_best = deepcopy(node)
l_best = deepcopy(link)
local_node = []
local_link = []
local_node.append(n_best)
local_l... |
def get_fields_by_message_type(self, type):
if type == "SubscriptionConfirmation" or type == "UnsubscribeConfirmation":
return ["Message", "MessageId", "SubscribeURL", "Timestamp", "Token", "TopicArn", "Type"]
elif type == "Notification":
return ["Message", "MessageId", "Subject"... | This code verifies the authenticity of an Amazon SNS message by validating its digital signature. It checks the signature version, constructs a signed string from message fields, loads the certificate's public key, decodes the base64 signature, and verifies it against the signed string using SHA1 and PKCS1v15 padding. ... | def verify_sns_data(self, messagePayload):
if messagePayload["SignatureVersion"] != "1":
return False
messagePayload["TopicArn"] = messagePayload["TopicArn"].replace(" ", "")
signatureFields = self.get_fields_by_message_type(messagePayload["Type"])
strToSign = self.get_payloa... |
def AndFunc(x):
w = np.array([1, 1])
bAND = -1.5
return PModel(x, w, bAND)
def OrFunc(x):
w = np.array([1, 1])
bOR = -0.5
return PModel(x, w, bOR)
def NotFunc(x):
wNOT = -1
bNOT = 0.5
return PModel(x, wNOT, bNOT) | The code computes the XOR of input variables using AND, OR, and NOT operations. It combines the OR of inputs with the negation of their AND, effectively implementing XOR logic: OR(x) ∧ ¬AND(x), which outputs true when exactly one input is true. | def XorFunc(x):
y1 = AndFunc(x)
y2 = OrFunc(x)
y3 = NotFunc(y1)
x1 = np.array([y2, y3])
y1 = AndFunc(x1)
return y1 |
def populate_company_context(
template: DocxTemplate,
company_dataframe: pd.DataFrame,
company_name: str
) -> dict:
"""
This function takes the Dataframe having company information in it along with
the name of the company and returns a dictionary containing the company information
whose name... | The main task of the code is to generate personalized Letters of Intent (LOIs) in PDF format for each candidate of a specified company. It reads company and candidate data from Excel files, populates a Word template with dynamic content (including rich text links and dates), and renders individual LOI PDFs. The process... | def main(company_name: str) -> None:
"""
This function takes the company name and produces LOIs in pdf format for that company.
Find pdf files in `/output/pdf/` directory and
Find document files in `/output/document/` directory inside the root directory
Args:
company_name (str): Name o... |
def get_prediction_and_conf_labels (adata, predicted):
'''
adata is the AnnData object
predicted [str] is the key in adata.obsm for which G corresponds to
Takes in AnnData adata with predicted [str] and returns the arrays:
G = predicted expression of all confidence and target genes
... | The function reinforces predicted gene expressions in spatial transcriptomics data by propagating residuals through a gene correlation network. It adjusts predicted values using neighbor information, optimizing a learning rate (alpha) via cross-validation if specified. The result is a refined expression matrix stored i... | def reinforce_gene (adata, predicted="predicted_expression", update_method="joint",
npcs=None, alpha=0.1, max_iter=100, tol=1e-3, scale="auto_gene", correlation_threshold="auto",
optimization_metric="MAE", savedir=False, cv=5):
'''
Reinforces predicted gene expressions us... |
def get_prediction_and_conf_labels (adata, predicted):
'''
adata is the AnnData object
predicted [str] is the key in adata.obsm for which G corresponds to
Takes in AnnData adata with predicted [str] and returns the arrays:
G = predicted expression of all confidence and target genes
... | The code smooths predicted or raw gene expression data using a spatial graph, optimizing a learning rate (alpha) to minimize a specified metric. It applies joint or PCA-based updates to refine expression values, storing the smoothed results in `adata.obsm` as a new matrix. The function handles both raw data and predict... | def smooth (adata, predicted=None, update_method="joint",
npcs=None, alpha=0.1, max_iter=100, tol=1e-3,
optimization_metric="Ensemble", savedir=False):
'''
Smooths predicted gene expressions using the spatial graph
predicted [str or None] = key in adata.obsm corresponding to pred... |
def error_response(serial_number: List[int], endcode: Endcode) -> bytes:
answer = response_header(serial_number)
answer[-4:-2] = 2, 0
answer[-2:] = endcode.value & 0xFF, (endcode.value >> 8) & 0xFF
return struct.pack("B" * len(answer), *answer)
def write_values(
device: Tuple[str, DeviceType],
s... | This function processes a device write request for specific commands (0x1401, 0x0082) by parsing data fields, validating device mappings, and writing values to target devices if the extension type matches 0xF8 or 0xFA. It returns success or error responses based on data validity and command correctness. | def extension_write_request(command: int, subcommand: int, serial_number: List[int], data: bytes) -> bytes:
if command == 0x1401 and subcommand == 0x0082:
try:
device = device_map[struct.unpack("H", data[6:8])[0]]
extension_specification = struct.unpack("H", data[10:12])[0]
... |
def error_response(serial_number: List[int], endcode: Endcode) -> bytes:
answer = response_header(serial_number)
answer[-4:-2] = 2, 0
answer[-2:] = endcode.value & 0xFF, (endcode.value >> 8) & 0xFF
return struct.pack("B" * len(answer), *answer)
def write_values(
device: Tuple[str, DeviceType],
s... | The code processes write requests for devices and labels based on command and subcommand. It handles bit/word device data unpacking, validation, and updates using `write_values`, or processes label-abbreviation mappings for 0x141B, parsing data to update label values in a dictionary. Errors return specific responses fo... | def write_request(command: int, subcommand: int, serial_number: List[int], data: bytes) -> bytes:
if command == 0x1401:
try:
device = device_map[struct.unpack("B", data[3:4])[0]]
head_device_no = struct.unpack("I", data[:3] + b"\x00")[0]
no_of_devices = struct.unpack("H",... |
def fill_dicts() -> None:
# fill devices and label dicts
devices["M"] = {
**{M_DEVICE[4] + i * 16: v for i, v in enumerate(M_DEVICE[1])},
int(M_BOOL_DEVICE[4] / 16) * 16: int(M_BOOL_DEVICE[1]) << (M_BOOL_DEVICE[4] % 16),
int(M_BOOL_DEVICE[4] / 16 + 1) * 16: 0,
**{
hea... | This code creates a network server on localhost:5007 to simulate a PLC. It handles incoming TCP connections, processes industrial protocol messages with subheader parsing, executes read/write operations based on command codes, and sends appropriate responses. The server supports multiple command types, error handling, ... | def main() -> None:
slmp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
slmp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
slmp.bind(("localhost", 5007))
slmp.listen(2)
print("PLC mockup running on localhost:5007")
while True:
try:
(conn, addr) = slmp.accept()
... |
def _is_legal_check_simple_cases(self, point: GO_POINT, color: GO_COLOR) -> bool:
"""
Check the simple cases of illegal moves.
Some "really bad" arguments will just trigger an assertion.
If this function returns False: move is definitely illegal
If this function returns True: sti... | This function plays a move in a Go game by validating legality, handling captures, ko rules, and updating game state. It checks for pass moves, processes captures of opponent stones, ensures the move isn't suicidal, updates ko recapture points, and switches players. Returns True if the move is legal, False otherwise. | def play_move(self, point: GO_POINT, color: GO_COLOR) -> bool:
"""
Play a move of color on point
Returns whether move was legal
"""
if not self._is_legal_check_simple_cases(point, color):
return False
# Special cases
if point == PASS:
self.... |
def tokenization(self):#create tokens for the query
tokenRequest=tokenization.tokenization(self.value)
returnValue=tokenRequest.token()
for values in returnValue:
ok = get_closest.correct_content(values)
self.tokenvalue=ok
self.sqlKeyword(ok)
def structrued(se... | The code's main task is to decide between tokenization or structured processing based on the receiver's state. It first tokenizes data, then checks if the receiver is empty. If so, it attempts structured processing; if an error occurs during this step, it triggers an apology response. The method handles control flow be... | def controller(self):#determine whether to go for tokenization or structured
self.tokenization()
try:
if self.receiver == []:
self.structrued()
except Exception:
self.sorry() |
def init():
parser = create_parser()
args = parser.parse_args()
# Create logger.
logging.basicConfig(filename=return_logging_path(args), level=logging.DEBUG, filemode='w',
format='%(asctime)s %(message)s')
logger = logging.getLogger()
ch = logging.StreamHandler()
if '... | The main task of the code is to process command-line arguments and execute corresponding actions such as setting up test environments, adding data sources, generating files, running tests, or listing configurations. It handles various sub-commands like 'action', 'run-file', 'run-connectors-test', and 'list' to perform ... | def main():
parser, ds_registry, args = init()
if args.command == 'action':
if args.setup:
print("Creating setup files...")
create_test_environment()
sys.exit(0)
elif args.add_ds:
add_datasource(args.add_ds, ds_registry)
generate_files... |
def countPiece(self, board, player):
count = 0
for i in board:
for j in i:
if j == player: count+=1
return count
def gmove(self, node,player):
pool = []
for i in range(5):
for j in range(5):
if node.board[i][j]==node.player: pool+= self.generateMove((i,j),node.board,node.player,node.dep... | This code implements the Minimax algorithm with alpha-beta pruning to determine the optimal move for a game involving piece placement. It evaluates possible moves recursively, prioritizing defensive strategies when enabled, and returns the best move based on maximizing/minimizing piece counts while adhering to depth li... | def minimax(self,prev_board,node, maxplayer,player,maxDepth,alpha,beta,defensive = 0):
# if node.depth == 0: print("check")
if maxDepth <= node.depth or time.time() - Node.time > 5 or self.countPiece(node.board, player) == 0: return(self.countPiece(node.board, player),node.move)
if maxplayer:
bestVal = 0
... |
def delete_expired(self):
"""Delete expired cache keys and return number of entries deleted.
Returns:
int: Number of entries deleted.
"""
count = 0
if not self._expire_times:
return count
# Use a static expiration time for each key for better co... | The code's main task is to evict cache entries by first removing all expired items, then removing non-expired entries using a cache replacement policy to keep the cache size below `maxsize`. If `maxsize` is 0, only expired entries are removed. It returns the number of evicted entries, ensuring minimal removals to maint... | def evict(self):
"""Perform cache eviction per the cache replacement policy:
- First, remove **all** expired entries.
- Then, remove non-TTL entries using the cache replacement policy.
When removing non-TTL entries, this method will only remove the minimum
number of entries to ... |
def _make_memoize_key(func, args, kargs, marker, typed, argspec, prefix):
kargs = kargs.copy()
key_args = (func,)
# Normalize args by moving positional arguments passed in as keyword
# arguments from kargs into args. This is so functions like foo(a, b, c)
# called with foo(1, b=2, c=3) and foo(1, 2... | This code defines a memoization decorator that caches function results. It generates a unique key from function parameters, checks the cache, computes the result if missing, stores it with a TTL, and returns the value. | def decorated(*args, **kargs):
key = _make_memoize_key(func,
args,
kargs,
marker,
typed,
argspec,
... |
def generateRandomStringFromLenRestriction(restriction):
return generateRandomString(generateRandomInt(restriction.min, restriction.max))
def generateRandomStringFromValuesRestriction(prop_restrictions, property_name):
return generateRandomStringFromArray(prop_restrictions[property_name].values)
def generateRan... | This function populates a model's attribute with a random string, applying specified restrictions if present. It checks if the property has length or value restrictions from prop_restrictions, generating strings accordingly. If no restrictions exist, it creates a random string with a random length. | def _populateModelStr(property_name, test_model, prop_restrictions):
if property_name in prop_restrictions:
restriction = prop_restrictions[property_name]
if restriction.CLASS_NAME == StringGenerationLengthRestriction.CLASS_NAME:
test_model.__setattr__(property_name,
gene... |
def generateRandomStringFromLenRestriction(restriction):
return generateRandomString(generateRandomInt(restriction.min, restriction.max))
def generateRandomStringFromValuesRestriction(prop_restrictions, property_name):
return generateRandomStringFromArray(prop_restrictions[property_name].values)
def generateRan... | This function populates a dictionary (`hash`) with randomly generated strings for a specified property (`property_name`). It checks if restrictions exist in `prop_restrictions` for that property. If so, it applies either a length-based restriction or a value-based restriction to generate the string. If no restrictions ... | def _populateHashStr(property_name, hash, prop_restrictions):
if property_name in prop_restrictions:
restriction = prop_restrictions[property_name]
if restriction.CLASS_NAME == StringGenerationLengthRestriction.CLASS_NAME:
hash[property_name] = generateRandomStringFromLenRestriction(rest... |
def generateRandomURL():
domainExtensions = ['.com', '.edu', '.org', '.info']
return generateRandomStringFromArray(['http', 'https']) +'://' + generateRandomString(10) + generateRandomStringFromArray(
domainExtensions)
def generateRandomPath(numOfSegments):
path = '/'
i = 0
while i < numOfSe... | The function generates a random URL by concatenating a random base URL, a path with a random integer, and a random file name, ignoring the provided parameters. Its main task is to create a placeholder or mock link for a model, likely used in testing or data generation. | def _populateModelLink(property_name, test_model, prop_restrictions):
return generateRandomURL() + generateRandomPath(generateRandomInt(5)) + generateRandomFileName() |
def _populateHashInt(property_name, hash, prop_restrictions):
if property_name in prop_restrictions:
restriction = prop_restrictions[property_name]
hash[property_name] = generateRandomIntFromRestriction(restriction)
else:
hash[property_name] = generateRandomInt()
def _populateHashStr(pro... | This function populates a hash dictionary with property values from a class, using type-specific helper functions. It iterates through each property in class_properties, checks its type (Integer, String, Boolean), and calls corresponding _populateHash* methods to add formatted key-value pairs to the hash, applying prop... | def _populateHashProperties(class_properties, prop_restrictions, hash):
for property_name in class_properties:
property_type = class_properties[property_name]
if isinstance(property_type, db.IntegerProperty):
_populateHashInt(property_name, hash, prop_restrictions)
if isinstance(... |
def _populateModelInt(property_name, test_model, prop_restrictions):
if property_name in prop_restrictions:
restriction = prop_restrictions[property_name]
test_model.__setattr__(property_name, generateRandomIntFromRestriction(restriction))
else:
test_model.__setattr__(property_name, gene... | This function populates a test model's properties with appropriate values based on their data types. It iterates through each property in class_properties, checks its type (e.g., Integer, String, Boolean), and calls corresponding helper functions to assign valid values to the test_model instance, respecting any restric... | def _populateModelProperties(class_properties, prop_restrictions, test_model):
for property_name in class_properties:
property_type = class_properties[property_name]
if isinstance(property_type, db.IntegerProperty):
_populateModelInt(property_name, test_model, prop_restrictions)
... |
def grouping(numVar,numlist):
#to initilize all sorted list
list0,list1,list2,list3,list4=[],[],[],[],[]
#listfornum0,listfornum1,listfornum2,listfornum3,listfornum4=[],[],[],[],[]
sortedlist=[list0,list1,list2,list3,list4]
nolist=[]
for Num in numlist:
... | The code processes EPI terms to generate minimized literals. For each term in EPI, if it is 'or', it directly appends 'or' to the result. Otherwise, it groups variables, iteratively minimizes the grouped terms until no further minimization is possible, and collects non-empty minimized terms. The function returns a list... | def makeliterals(numVar,EPI):
literal=[]
for Number in EPI:
Lastlist=[]
if Number=='or':
Lastlist.append('or')
else:
Minlist,Numb=grouping(numVar,Number)
... |
def setUpGame(self,row,column):
minesToBeLaid = self.mines
while minesToBeLaid > 0:
r = random.randint(0,self.rows-1)
c = random.randint(0,self.cols-1)
if not (r == row and c == column) and self.grid[r][c].mine == False:
self.grid[r][c].mine = True
... | This function handles revealing a tile in a Minesweeper game. It checks if the tile contains a mine (triggering failure) or has zero neighboring mines (recursively revealing adjacent tiles). It also manages the first click setup, ensures tiles are only revealed once, and maintains a backup of the grid state. | def openTile(self,r,c):
self.backupGrid = copy.deepcopy(self.grid)
if self.firstClick:
self.firstClick = False
self.setUpGame(r,c)
if not self.grid[r][c].covered:
return
self.grid[r][c].covered = False
if self.grid[r][c].mine:
self.... |
def sanity_check():
"""Make sure COLUMNS and a default record match up."""
blank = record({'query_appid': '', 'query_appname': '', 'data': {}})
keys = set(blank.keys())
cols = set(COLUMNS)
if len(cols) != len(keys):
print("Column mismatch: expected %d but found %d in blank record" % (
... | The main task of the code is to generate a CSV file named "games-features.csv" by processing game data. It writes header rows using predefined columns (COLUMNS), iterates over game records via game_reader(), converts each game into a structured record with the record() function, and exports the data into the CSV file. ... | def main():
"""Entry point."""
sanity_check()
print("Creating games-features.csv")
with open("games-features.csv", "w") as basefile:
writer = csv.writer(basefile)
writer.writerow(COLUMNS)
count = 0
for game in game_reader():
rec = record(game)
wri... |
def get_arg_parser() -> ArgumentParser:
parser = ArgumentParser(
prog=NAME,
description=(
"Cluster papers into topics according to their titles and/or abstracts"
),
)
parser.add_argument(
"--version", "-V", action="version", version=f"{NAME}, version {get_version... | The main task of the code is to process academic documents by extracting topics and features, then visualize the results. It parses command-line arguments, initializes logging, retrieves documents, generates a model with specified features, and optionally prints feature lists or plots top words. The function handles bo... | def main(**kwargs: Unpack[ParserArgs]) -> None:
parser = get_arg_parser()
if len(kwargs) > 0:
args = Namespace(**kwargs)
else:
args = parser.parse_args()
init_logging(args)
logger.info(
f"Calculating {args.topic_count} topics with {args.feature_count} features"
)
d... |
def get_room_type_code(room):
return room["RoomTypes"]["RoomType"]["RoomTypeCode"]
def get_room_rate_plan(room):
return room["RoomRates"]["RoomRate"]["Rates"]["Rate"]["ChargeType"]
def get_room_rate_rule(room):
return get_rate_rule_from_feature(get_room_rate_feature(room))
def get_room_travel_period(room):
... | The main task of the code is to convert a room object into a Unit type by populating its properties: setting the unit type to a room, assigning vendor code, rate plan, rate rules, price details (including a fixed EUR net value), travel period, traveler counts, remaining units, and remarks. The function constructs and r... | def unit_from_room(room):
"""
Create a Unit type from room and return it
"""
unit = Unit()
unit.type = UnitType.UNIT_TYPE_ROOM
unit.vendor_code = get_room_type_code(room)
unit.rate_plan = get_room_rate_plan(room)
unit.rate_rules.append(get_room_rate_rule(room))
price_detail = Pri... |
def get_all_hotels(response_dict):
return response_dict["HotelStays"]["HotelStay"]
def get_all_rooms(response_dict):
return response_dict["RoomStays"]["RoomStay"]
def get_hotel_code(hotel):
return hotel["BasicPropertyInfo"]["HotelCode"]
def get_hotel_name(hotel):
return hotel["BasicPropertyInfo"]["Hotel... | The code prints detailed information about hotels and their rooms from a response dictionary, including hotel codes, names, and room counts. It calculates and displays totals for all hotels, all rooms, and the sum of rooms across all hotels. | def print_hotels_info(response_dict):
"""
Print hotels and rooms counts
"""
hotels = get_all_hotels(response_dict)
all_rooms = get_all_rooms(response_dict)
total_room_count = all_rooms.__len__()
total_hotels = len(hotels)
total_hotel_rooms = 0
for hotel in hotels:
hotel_... |
def property_info_from_hotel(hotel):
property = PropertyInfo()
property.property_name = get_hotel_name(hotel)
property.city_or_resort = get_hotel_area_id(hotel)
# Put the hotel code to GIATA ID for now
property.giata_id = get_hotel_code(hotel)
property.goal_id = get_hotel_code_context(hotel)... | The code generates a search option for a hotel by initializing a SearchOption object, setting its property information from the hotel, retrieving all the hotel's rooms from the provided list, converting each room into a unit, and appending these units to the search option. The function returns the populated search opti... | def get_search_option(hotel, all_rooms):
"""
Get a hotel and generate a search option with all the rooms of the hotel
"""
so = SearchOption()
# Set PropertyInfo
so.property_info = property_info_from_hotel(hotel)
# Set Units of the Property
hotel_code = get_hotel_code(hotel)
hotel_... |
def get_all_hotels(response_dict):
return response_dict["HotelStays"]["HotelStay"]
def get_all_rooms(response_dict):
return response_dict["RoomStays"]["RoomStay"]
def get_header():
"""
Create a new Header type, populate the fields and return it
"""
header = Header()
header.version.major = 1
... | The function constructs an AccommodationSearchResponse by processing hotel and room data from the input dictionary. It retrieves all hotels and rooms, initializes the response header, and iterates through each hotel to generate search options, appending them to the response. The main task is to transform structured hot... | def get_accommodation_search_response(hotel_data_dict):
"""
Gets the parsed hotel data dict and builds a AccommodationSearchResponse message
"""
all_hotels = get_all_hotels(hotel_data_dict)
all_rooms = get_all_rooms(hotel_data_dict)
accommodation_search_response = AccommodationSearchResponse()... |
def read_train_batch(frompath, batch_index):
return read_batch(os.path.join(frompath, "data_batch_{}".format(batch_index)))
def saveImage(fname, pixData, pad):
if pad > 0:
pixData = _pad_image(pixData, pad)
img = Image.new('RGB', (IMGSIZE + 2 * pad, IMGSIZE + 2 * pad))
pixels = img.load()
f... | The code processes CIFAR-10 training batches, saving individual images to a directory while generating a label map file. It accumulates image data to compute the mean image for normalization, storing the result in an XML file. The main task is to preprocess training data by organizing images, creating a label mapping, ... | def saveTrainImages(topath, map_filename='train_map.txt', mean_filename='CIFAR-10_mean.xml',
frompath='cifar-10-batches-py'):
if not os.path.exists(topath):
os.makedirs(topath)
file_num_generator = count(start=0, step=1)
dataSum = np.zeros((3, IMGSIZE, IMGSIZE)) # mean is in CH... |
def download_data(src):
print('Downloading ' + src)
fname, h = urlretrieve(src, './delete.me')
print('Done.')
return fname
def extract(fname):
try:
print('Extracting files...')
with tarfile.open(fname) as tar:
tar.extractall()
print('Done.')
finally:
o... | The main task of the code is to download and process the CIFAR-10 dataset. It downloads the data, extracts it, organizes training and test images into specified directories, and saves image maps and mean statistics for the training set. The function prepares the dataset for machine learning tasks by structuring files a... | def main(data_dir=DATA_DIR):
fname = download_data(CIFAR_URL)
extract(fname)
train_path = os.path.join(data_dir, 'train')
test_path = os.path.join(data_dir, 'test')
saveTrainImages(train_path,
map_filename=os.path.join(data_dir, 'train_map.txt'),
mean_filename... |
def deduct_amount(self, amount):
if self.balance < amount:
print("Your balance is insufficient for this action.")
bankrupt = self.check_if_bankrupt(amount)
if not bankrupt:
print("You need to sell or mortgage certain properties.")
user... | The main task of the code is to check the player's current board position, handle special properties (e.g., taxes, jail), determine if a property is purchasable, and trigger actions like fines, rent collection, or purchase prompts. It updates the player's status based on the property's state (mortgaged, owned, or avail... | def position_check(self, board):
self.current_pos = self.current_pos % 40
brd_property = board[self.current_pos]
if brd_property.card_cost == "N/A": # this means the player cannot purchase the card
if brd_property.card_name == 'Jail/Visiting Jail':
print(f... |
def _convert_when(when):
# Test to see if when has already been converted to ndarray
# This will happen if one function calls another, for example ppmt
if isinstance(when, np.ndarray):
return when
try:
return _when_to_num[when]
except (KeyError, TypeError):
return [_when_to_n... | The function `ipmt` calculates the interest portion of a periodic payment for a loan or investment, given parameters like interest rate, period number, total periods, present value, and payment timing (begin/end). It computes how much of each payment goes toward interest, using the total payment amount and adjusting fo... | def ipmt(rate, per, nper, pv, fv=0, when='end'):
"""Compute the interest portion of a payment.
Parameters
----------
rate : scalar or array_like of shape(M, )
Rate of interest as decimal (not per cent) per period
per : scalar or array_like of shape(M, )
Interest paid against the loa... |
def h_list(xs):
n = len(xs)
h = [0]*n
for i in range(1, n):
h[i] = xs[i] - xs[i-1]
return h
def m_list(xs, ys):
n = len(xs)
p = [0]*n
q = [0]*n
u = [0]*n
l = l_list(xs)
d = [d_calc(k, xs, ys) for k in range(n)]
for i in range(1, n-1):
... | This code defines a function `get_s` that returns a lambda function. The lambda function, given an input `x`, finds the segment in `xs` where `x` lies (between `xs[i-1]` and `xs[i]`), then applies a `spine` function using precomputed lists `h_ls` and `m_ls` along with segment indices. The result is a piecewise evaluati... | def get_s(xs, ys):
h_ls = h_list(xs)
m_ls = m_list(xs, ys)
return lambda x: next(
(
spine(xs, ys, m_ls, h_ls[i], i)(x)
for i in range(1, len(xs))
if xs[i - 1] <= x <= xs[i]
),
None
) |
def nine_lines():
three_lines()
three_lines()
three_lines()
def three_lines():
new_line()
new_line()
new_line()
def new_line():
print('*') | The code defines a function `clear_screen()` that clears the screen by printing multiple lines. It calls `nine_lines()` twice (printing 9 lines each), `three_lines()` twice (3 lines each), and `new_line()` once (1 line), totaling 25 lines to overwrite the screen content, simulating a screen-clearing effect. | def clear_screen():
nine_lines()
nine_lines()
three_lines()
three_lines()
new_line() |
def read_roots_file(self):
try:
open_file = open(self.roots_path, "rb")
roots = pickle.load(open_file)
open_file.close()
return np.array(roots)
except :
print(" System -> [error] Downloading roots failed ! .")
def learning_network(self):
... | This code initializes a neural network for learning (LTP/LTD) or loads an existing network from a pickle file. It accepts paths for true/false comments, roots, and network name. If `learning` is True, it sets up network parameters, reads roots, executes learning processes, standardizes data, calculates neuron fitness, ... | def __init__(self,true_path,false_path=None,roots_path=None,network_name=None,learning=None,forbidden_roots=None):
#true_path :
# if creating a network : (path:str) true comments -> pickle file path (True class for LTP Learning).
# if reading a network from a network pickle file : (path... |
def kd_loop_teacher(data="mnist", epochs=1, apply_pruning=False, save=lambda f,a: (f,a), load_teacher=False):
teacher, x_train, x_test, y_train, y_test = get_model_and_data('teacher', data)
# optimizer = 'SGD' #if resnet!!
optimizer = keras.optimizers.Adam()
teacher.compile(
optimizer=opti... | The main task of the code is to perform knowledge distillation by training a teacher model, a student model (guided by the teacher's knowledge), and a baseline "scratch" model. It returns these three models after training, with optional pruning and customizable parameters like temperature and alpha for distillation. Th... | def kd_loop(data="mnist", teacher=None, epochs=1, prune_teacher=False, prune_student=False, temperature=7, alpha=0.3, save=lambda f,a: (f,a)):
teacher = kd_loop_teacher(data, epochs, prune_teacher, save)
student = kd_loop_student(data, epochs, teacher, prune_student, temperature, alpha, save)
scratch = kd_l... |
def get_new_username():
"""
Prompt the user to input a new username and check if it already exists.
This function continuously prompts the user to input a new username until a unique one is provided.
:return: A unique username entered by the user.
"""
while True:
username = input("Inpu... | The main task of the code is to register a new user by prompting for a username and strong password, then adding them to the system. It also displays the list of all registered users. | def user_registration():
"""
Perform user registration.
This function prompts the user to input a new username and a strong password and registers the user.
"""
print("User registration:")
username = get_new_username()
password = get_new_strong_password()
user_register(username, passw... |
def read_tnw(self, file):
with open("./intermediate files/" + file) as tnwfile:
self.tnw = json.load(tnwfile)
tnwfile.close()
print("Read an SSI text network's file successfully: {} nodes and {} edges are found.\n".format(len(self.tnw["SSI.TextNetwork"]["node"]),len(self.tnw["SS... | The main task of the code is to analyze linguistic associations between elements in `usm` (user model) and `cwm` (conceptual world model) to identify potential weaknesses. It iterates through components like subjects, data, and operations, comparing them with system components, objects, and functions using `check_la`. ... | def analyze_la(self, usm, cwm, file):
print("----------------------------------------------------------------------")
print(" ANALYZING LINGUISTIC ASSOCIATIONS AND POTENTIAL WEAKNESS")
print("----------------------------------------------------------------------")
self.read_tnw(file)
... |
def file_operation(file_name):
#creating a folder to save the results
pwd = os.getcwd()
pwd = pwd.strip()
path = pwd.rstrip('\\')
file_path = path.replace('\\', '/') + '/' + file_name
#make sure the save path is existed
#note that the existed folder will be deleted
if (os.path.exist... | The code iterates through image files in a benchmark directory, processes each image with a corresponding target mask, evaluates the results, and saves the evaluation outcomes into a text file. It constructs file paths, skips directories, extracts image names, and uses helper functions for file operations and result st... | def files_iteration():
#getting files
current_path = os.getcwd()
image_path = current_path.replace('\\', '/') + '/' + 'benchmark'
#the folder of results
saving_evaluation = current_path.replace('\\', '/') + '/'
#creating the new text file
#!Note: we will delete the existed resu... |
def wek_to_wer(wek):
div=math.sqrt(wek[0]*wek[0]+wek[1]*wek[1]+wek[2]*wek[2])
return [wek[0]/div,wek[1]/div,wek[2]/div]
def ang_to_wek(flat,up):
if int(up)==-90:
return [0,0,-1]
if int(up)==90:
return [0,0,1]
if (int(up)==180 or int(up)==-180):
z=0
else:
z=ma... | This function calculates a minimal number of points required for a geometric configuration, then iteratively samples random positions on the surfaces of a 3D box defined by dimensions a, b, c. It checks if these positions satisfy specific geometric constraints using a helper function eije, returning valid coordinates a... | def aspecialf(p,a,b,c,lgt,zenn):
std_tan=math.tan(math.radians(40))
zet=min([a,b,c])
v_a=a*b*c
v_s=(zet**3)*std_tan**2*math.pi/3
nnn=zenn*v_a/v_s
col_print("Minimal number of points required : "+str(nnn), "I")
for stirr in range(1000):
fov=ran.random()*70+10
tanr=math.tan(mat... |
def loadpoints(fil):
tab=[[],[],[]]
res=[]
f=open(fil,'r')
a=""
b=0
for i in f:
for d in i:
if d=="@":
tab[b].append(float(a))
a=""
b+=1
else:
if d!=";":
a+=d
... | The main task of the code is to decrypt data from an input file using a key file, then save the decrypted result to an output file. It loads input data and key parameters, processes the data with the key via `scan_space`, and stores the decrypted output using `savtofil2d`, with status messages printed during execution. | def decryption(path_input, path_output, path_key):
col_print("Starting decryption.","I")
tab=loadpoints(path_input)
keytab=loadkey(path_key)
res=scan_space(tab,keytab[0],keytab[1],keytab[2],keytab[3],keytab[4],keytab[5],keytab[6])
savtofil2d(res,path_output)
col_print("Decryption finished! Resul... |
def aspecialf(p,a,b,c,lgt,zenn):
std_tan=math.tan(math.radians(40))
zet=min([a,b,c])
v_a=a*b*c
v_s=(zet**3)*std_tan**2*math.pi/3
nnn=zenn*v_a/v_s
col_print("Minimal number of points required : "+str(nnn), "I")
for stirr in range(1000):
fov=ran.random()*70+10
tanr=math.tan(mat... | The main task of the code is to generate a set of 3D points based on geometric transformations, adjusting coordinates using input parameters, and adding noise. It processes a grid (tab) to create points within a cone-shaped region, applies random scaling, and appends additional points outside the cone or as noise, retu... | def encrypting(tab,lgt,a,b,c,p,zenn,noise):
while True:
dud=aspecialf(p,a,b,c,lgt,zenn)
if dud[0]!="z":
break
else:
input("Do you want to try again?")
x=dud[3]
y=dud[4]
z=dud[5]
flat=dud[6]
up=dud[7]
fov=dud[8]
res=[]
stabh=wek_to_wer(a... |
def loadtab(fil):
res=[]
a=0
f=open(fil,'r')
for line in f:
tab=[]
for i in line:
if i!="\n":
tab.append(int(i))
res.append(tab)
return res
def count_points(tab):
a=0
for i in tab:
for d in i:
if d==1:
a+... | The code performs encryption by loading input data, processing points within a cone, generating encrypted points with parameters, and saving results to an output file along with key parameters like coordinates and settings. | def encryption(path_input, path_output, slider, noise):
col_print("Starting encryption.", "I")
tab=loadtab(path_input)
zenn=count_points(tab)
sq_tab(tab,zenn)
lgt=len(tab)
zenn=count_points(tab)
col_print("Points located inside of the cone : "+str(zenn),"I")
points=encrypting(tab,lgt,10,... |
def check_fleet_edges(ai_settings,aliens):
'''Check if the edges of the fleet are touching the edges of the screen,
and if so, drop the fleet some rows down'''
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings,aliens)
def ship_hit(ai_settings,stats... | The function updates the alien fleet's position by checking edges, updating their movement, detecting collisions with the ship, and verifying if aliens reach the screen bottom, triggering responses like ship damage or game over conditions. | def update_aliens(ai_settings,stats,screen,aliens,ship,bullets):
'''Update the position of the alien fleet'''
check_fleet_edges(ai_settings,aliens)
aliens.update()
if pygame.sprite.spritecollideany(ship,aliens):
ship_hit(ai_settings,stats,screen,ship,aliens,bullets)
check_aliens_bottom(ai_se... |
def findNext(x, links, desired):
print("F_x: ", F_x(x,links), "Inv: ", invJacobian(x,links))
print("Find Next: ", np.subtract(x,np.subtract(np.matmul(desired,invJacobian(x,links)),np.matmul(F_x(x, links),invJacobian(x, links)))))
return np.subtract(x,np.subtract(np.matmul(desired,invJacobian(x,links)),np.m... | The function `newtonRaph` implements an iterative method (likely Newton-Raphson) to refine an initial guess (`guess`) toward a solution (`x_new`) that meets a specified relative error tolerance (`error`). It uses `findNext` to compute successive approximations and checks convergence with `currentRelativeError`. If conv... | def newtonRaph(guess, error, desired, max_iter, links):
# guess of x
i = 0
while 1:
#print(guess, i)
x_new = findNext(guess, links, desired)
if(np.less_equal(currentRelativeError(x_new, guess), error).all()):
_ , processed = determineQuadrant(x_new)
return pro... |
def newtonRaph(guess, error, desired, max_iter, links):
# guess of x
i = 0
while 1:
#print(guess, i)
x_new = findNext(guess, links, desired)
if(np.less_equal(currentRelativeError(x_new, guess), error).all()):
_ , processed = determineQuadrant(x_new)
return pro... | The code solves inverse kinematics for a 2-DOF robotic arm using Newton-Raphson and analytical methods, comparing results via forward kinematics against a desired position. It initializes joint angles, link lengths, and target coordinates, runs numerical optimization, validates solutions, and outputs achieved positions... | def main():
theta = [math.pi/2, math.pi/2]
links = [1.0, 1.0]
desired = [0.5, 0.5]
row1 = [math.pi/2]
row2 = [math.pi/3]
maxIter = 1000
errMax = np.array(np.vstack((0.0001, 0.0001)))
print("starting newtonRaph method")
reached, i, unprocessed = newtonRaph(theta, errMax, de... |
def clean_map(self):
try:
self.map.delete(ALL)
except:
self.map = tk.Canvas(
self.mainWindow, bg="green"
)
self.map.grid(row=0, column=1, sticky="nsew")
def option_buttons(self):
xPadding = 5
yPadding = 3
btn_open =... | This code initializes a GUI application for a transport network simulation using Tkinter. It sets up the main window with a top bar, main content area, and sidebar, configures layout parameters, initializes data structures for network objects (hubs, trailers, roads), and starts the simulation. The interface provides a ... | def __init__(self):
tk.Frame.__init__(self)
self.grid()
self.master.title("Transport Network")
self.width = 800
self.height = 500
self.columnconfigure(0, weight=1, minsize=self.width)
self.rowconfigure(1, weight=1, minsize=self.height)
self.topBar = tk.F... |
def get_args():
parser = argparse.ArgumentParser(
description="Trim Illumina reads for adaptor contamination "
"low quality bases and merge reads.\nWritten assuming "
"Trimmomatic v0.36 and Pear v0.9.10.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
... | The main task of the code is to process sequencing data by trimming adaptors, merging paired-end reads, cleaning low-quality regions, and removing temporary files. It uses Trimmomatic for adaptor removal and quality trimming, PEAR for read merging, and performs cleanup to organize output files. The workflow processes i... | def main():
# get arguments
args = get_args()
# get sample info
info, dir = sample_info(args)
# make adaptor file
a_file = adaptor_file(args, info, dir)
# run trimmomatic to remove adaptors
outfiles1 = run_trimmomatic(args, info, a_file, dir)
# run pear to merge reads
outfiles2 =... |
def add_var_to_dict(self, classname):
var_name = chr(self.unicode)
var_name = symbols(var_name)
self.dict_var[classname] = var_name
if 65 <= self.unicode <= 89 or 97 <= self.unicode <= 122:
self.unicode += 1
elif not self.unicode > 122:
self.unicode = 97
... | The main task of the code is to construct a system of linear equations representing production input-output relationships from a data structure, solve this system using matrix operations, and return the computed production rates. It iterates through ingredients, builds equations based on their production data, inserts ... | def get_production(self):
matrix = Matrix([])
classname = list(self.data.keys())[0]
ingredients_unvisited = [classname]
ingredients_visited = []
increment = 0
while increment < len(ingredients_unvisited):
if ingredients_unvisited[increment] not in ingredients_... |
def reload_rewards(self):
self.rewards = sdk.get_rewards(self._config["server"], self._config["auth_code"])
self._commands = {i["command"]: i["name"] for i in self.rewards}
self._reward_buttons = [
[sg.Button(reward["name"], key="cmd_" + reward["command"])] for reward in self.rewar... | This code initializes a class with configuration settings, setting up internal variables for rewards, commands, layout, and UI elements. It loads rewards, initializes additional settings, and starts the application window if specified. The main tasks include configuring the instance, preparing data structures, and opti... | def __init__(self, config: dict, start: bool = True):
self._config = config
self._window = None
self._show_error = False
self._running = True
self._rewards = []
self._commands = {}
self._layout = []
self._reward_buttons = []
self.rewards = []
... |
def _insert_message(self, msg, sender):
if not msg:
return
msg1 = f"{sender}: {msg}\n"
self.text_widget.configure(state=NORMAL)
self.text_widget.insert(END, msg1)
self.text_widget.configure(state=DISABLED)
self.text_widget.see(END)
def visual(self, ms... | The main task of the code is to capture voice input via a microphone, convert it to text using Google's speech recognition, and execute predefined actions based on recognized commands. It inserts the user's message, checks for specific commands (e.g., name, time, weather), and triggers functions like web search, alarm ... | def yakan(self):
with sr.Microphone() as source:
audio = self.r.listen(source)
try:
myText = self.r.recognize_google(audio)
myText = myText.lower()
self._insert_message(myText, "You")
if myText == self._commandsArray[0] or myTe... |
def Parameters():
Weight1 = np.random.rand(10, 784) - 0.5
Bias1 = np.random.rand(10, 1) - 0.5
Weight2 = np.random.rand(10, 10) - 0.5
Bias2 = np.random.rand(10, 1) - 0.5
return Weight1, Bias1, Weight2, Bias2
def ForwardPropagation(Matrix, Weight1, Bias1, Weight2, Bias2):
Z1 = Weight1.dot(Matrix) ... | The main task of the code is to train a two-layer neural network using gradient descent. It initializes parameters, iteratively performs forward and backward propagation to compute derivatives, updates weights/biases with a learning rate, and periodically prints predictions and accuracy. The function returns the optimi... | def LowOnCurve(Mat1, Mat2, Rate, Iteration):
#Initialize our parameters
Weight1, Bias1, Weight2, Bias2 = Parameters()
#Apply all cited steps
for i in range(Iteration):
Z1, A1, Z2, A2 = ForwardPropagation(Mat1, Weight1, Bias1, Weight2, Bias2)
derWeight1, derBias1, derWeight2, derBias2 =... |
def APs_exist(fileName):
if os.path.exists(fileName):
return 1
else:
return 0
def APs_init(fileName):
apsList = {"aps":[]}
with open (fileName, "w+") as jsonFile :
jsonFile.write(json.dumps(apsList))
def get_APs(fileName):
if APs_exist(fileName):
apsList = open(fileNa... | The main task of the code is to append a new access point (AP) entry to a JSON file if it doesn't already exist. It checks for the AP's existence using the BSSID, creates a new entry with provided parameters (SSID, channel, encryption, strength), and updates the file with the new AP data. The function ensures data cons... | def AP_append(fileName, bssid, ssid, channel, encryption, strength):
if not APs_exist(fileName):
APs_init(fileName)
apsList = get_APs(fileName)
aps = apsList["aps"]
select = False
ap = [strength,ssid,bssid,channel,encryption,select]
if not AP_exist(fileName,bssid):
aps.append(ap... |
def APs_show(fileName):
if APs_exist(fileName):
apsList = get_APs(fileName)
aps = apsList["aps"]
ap_table_header = "|"+"ID".ljust(3)+" | "+"Signal".ljust(7)+" | "+"Channel".ljust(8)+" | "+"BSSID".ljust(18)+" | "+"SSID".ljust(30)+" | "+"Encryption".ljust(20)+" | |"
print("_"*len(str(a... | This code provides a menu-driven interface for managing Wi-Fi deauthentication attacks. It displays scanned access points, allows selecting/removing targets, broadcasting deauth packets, or targeting specific clients. The function handles user input, recursively re-displays the menu after actions, and includes error ch... | def target_menu(interface):
os.system('clear')
print('[Interface]: %s' %(interface))
print('[Scanned]:')
APs_show(aps_list)
print('[Function]:')
print('[1]: Select target')
print('[2]: Remove target')
print('[3]: Clear targets')
print('[4]: Broadcast deauth')
print('[5]: Deauth s... |
def read_file(file_name) :
with open(file_name, 'r') as file:
reader = csv.reader(file)
data = list(reader)
data = [int(x[0]) for x in data[:]]
return data
def insert(tree, data) :
i = 0
while tree[i] is not None :
if data <= tree[i] :
i = left(i)
elif d... | The code allows users to construct a Binary Search Tree (BST) and/or Max Heap from selected CSV files. It enables printing the BST, searching values, traversing (inorder/preorder/postorder), finding max/min values, and converting the BST into a Max Heap. Users can repeat the process or exit, with validation for file se... | def main() :
selection = input("Do you want to construct a new BST and/or Max Heap? [y/n] ")
while selection == "y" :
files = ["test1.csv", "test2.csv", "test3.csv"]
tree = [None]
file_choice = input("Please select test file to use: 1, 2, or 3 ")
while (file_choice != "1") and ... |
def get_filename(filepath):
# Extract the base name (e.g., 'example.txt' from '/path/to/example.txt')
base_name = os.path.basename(filepath)
# Split the base name and the extension and return just the base name
file_name_without_extension = os.path.splitext(base_name)[0]
return file_name_without_ext... | The code computes provability training data for theorems in a Lean repository by analyzing theorem states and tactics. It loads models, a repository, and FAISS index, then processes each theorem to generate state pairs using a Dojo environment. Results are saved as pickled files in the specified output path, ensuring c... | def compute_provability_training_data_remote(file_path, output_path):
worker_id = random.randint(0, 100)
print("Worker", worker_id, "on", file_path)
cuda_version = subprocess.run(['nvcc', '--version'], capture_output=True, text=True).stdout
print(cuda_version)
print("CUDA:", torch.cuda.is_available(... |
def _get_serializer_title(self) -> str:
label = self.serializer.label
if label is not None:
return label
if self._is_hidden_serializer():
return ''
if self._is_list_serializer(self.serializer):
class_name = type(self.serializer.child).__name__
... | This code generates a JSON schema dictionary based on the serializer type. If the serializer is a list, it creates an array schema with minItems and item properties; otherwise, it constructs an object schema with required fields and properties. Dependencies are added before returning the schema for validation or docume... | def get_schema(self) -> Dict[str, Any]:
if self._is_list_serializer(self.serializer):
schema = {
'title': self._get_serializer_title(),
'type': 'array',
'minItems': 0 if self._is_serializer_optional() else 1,
'items': {
... |
def _field_order(self) -> List[str]:
if self._is_list_serializer(self.serializer):
return list(self.serializer.child.Meta.fields)
return list(self.serializer.Meta.fields)
def _get_style_dict(self, field) -> Dict[str, Any]:
style_dict = {}
for k, v in field.style.items():
... | The method generates a UI schema dictionary by checking if the serializer is a list type. If true, it returns a nested structure with 'items' containing ordered fields, styles, and UI properties. Otherwise, it returns a flat structure with the same elements, adapting the schema based on the serializer's type to define ... | def get_ui_schema(self) -> Dict[str, Any]:
if self._is_list_serializer(self.serializer):
return {
'items': {
**{'ui:order': self._field_order()},
**self._get_style_dict(self.serializer),
**self._get_all_ui_properties(),
... |
def getAllProductURLs(self, keyword=""):
print("Page:", self.url)
waitClassName = "css-7fmtuv"
page = self.getPageSelenium(self.url, wait=True, waitClassName=waitClassName)
self.getURLs(page, waitClassName, keyword)
next_page = page.findAll("a", {"data-testid" : "btnShopProductP... | This code initiates product data scraping from URLs, extracting details like title, price, and images. It allows saving results to a CSV file and images to a folder. The function processes a specified range of product URLs, uses a browser driver for each request, and outputs progress updates. It handles parameters for ... | def startScraping(self, saveData=False, saveImage=False, start_idx=0, num_of_products=None):
print("Fetching all product URLs...")
print()
self.getAllProductURLs(keyword='puku')
total_products = len(self.url_products)
print("Total url found:", total_products)
print()
... |
def _http_respond(connection: socket.socket, code: str, content: Optional[str] = None) -> None:
"""Send a response code and optional content to the HTTP client."""
# Create a list of components of our response, starting with the HTTP response line.
response = ["HTTP/1.1 " + code]
# If we are sending co... | The main task of this code is to handle HTTP requests for a Twitch OAuth login flow. It processes incoming requests, validates HTTP methods, parses URLs, and responds with appropriate redirects, authentication pages, or error messages. It manages three key paths: initiating login, handling OAuth callbacks, and confirmi... | def _tick_http_server(caller: unrealsdk.UObject, function: unrealsdk.UFunction, params: unrealsdk.FStruct) -> bool:
# Attempt to accept a connection on our HTTP socket. If none is waiting, this will time out.
try:
connection, _ = _http_listener.accept()
log.debug("Received HTTP request attempt")... |
def msgToPointOnCurve(self,message):
X=message
Y=math.sqrt((X**3+self.a*X+self.b)%self.p)
message_point_onCurve=(int(X),int(Y))
return message_point_onCurve
def applyDoubleAndAddMethod(self,x0, y0, k, a, b, mod):
x_temp = x0
y_temp = y0
kAsBinary = bin(k)
kAsBinary =... | This code implements an elliptic curve encryption scheme. It converts a message to a curve point, generates a random scalar $ k $, computes $ c1 = k \times G $ (public key component), and $ c2 = k \times \text{publicKeyOther} $ (shared secret). It then adds the message's curve point to $ c2 $, returning $ (c1, c2) $ as... | def encrypt(self,publickKeyOther,message):
plain_coordinates = self.msgToPointOnCurve(message)
k = random.randint(1, self.p-1)
c1 = self.applyDoubleAndAddMethod(self.G[0], self.G[1], k, self.a, self.b, self.p)
c2 = self.applyDoubleAndAddMethod(publickKeyOther[0], publickKeyOther[1],k, se... |
def findModularInverse(self,a, mod):
while(a < 0):
a = a + mod
x1 = 1; x2 = 0; x3 = mod
y1 = 0; y2 = 1; y3 = a
q = int(x3 / y3)
t1 = x1 - q*y1
t2 = x2 - q*y2
t3 = x3 - (q*y3)
while(y3 != 1):
x1 = y1; x2 = y2; x3 = y3
y1 = t1; y2 = t2; y3 = t3
q = int(x3 /... | This code verifies a digital signature using elliptic curve cryptography. It computes a hash of the message, derives a modular inverse, applies the double-and-add method to generate points, performs point addition, and checks if the resulting x-coordinate matches the signature component 'r' to determine validity. | def verifySignature(self, message, r, s,Qother):
e = hashlib.sha256(message.encode('utf-8')).hexdigest()
e = int(e, 16)
w = self.findModularInverse(s, self.order)
u1 = self.applyDoubleAndAddMethod(self.G[0], self.G[1], (e * w) % self.order, self.a, self.b, self.p)
u2 = self.apply... |
def generate_topics(bagfolder, graph, topics, graph_n, metric):
for topic in topics:
if topic not in graph:
tmp = pd.read_csv(get_file_path(bagfolder, topic))
stamps = tmp['Stamps'].tolist()
period = [s1 - s0 for s1, s0 in zip(stamps[1:], stamps[:-1])]
med_per... | The main task of the code is to construct a graph representation from a ROS bag file, populate it with nodes/edges, calculate metrics (e.g., publishers, subscribers, frequencies), and save these metrics. It initializes a fixed node, generates topics/nodes/edges, and stores results in a metric dictionary for analysis. | def create_graph(bagfolder, graph, topics, nodes, graph_n, metric):
# initialize the metric
metric['Topics'] = {}
metric['Nodes'] = {}
# add fixed nodes
graph.node('/_ros2cli_rosbag2', '/_ros2cli_rosbag2')
metric['Nodes'].update({'/_ros2cli_rosbag2': {'name': '/_ros2cli_rosbag2',
... |
def dall(mps, D, **kwargs):
my_mpd = []
for _ in range(D):
temp_mps = apply_mpd(my_mpd,mps, rev=True)
my_mpd.append(mpd_from_mps(temp_mps))
return my_mpd
def iter_ii_oall(mps, D, maxiter=200, tol=1e-5, **kwargs):
N=mps.num_sites
d=np.random.choice(mps.local_dim)
if not np.al... | This function selects and executes different optimization modes based on the 'ctrl' parameter, routing input 'mps' and 'D' to corresponding functions like dall(), iter_ii_oall(), or oall(). It simplifies switching between analytic, identity, single, batch, or continuous optimization strategies via a case-insensitive 'c... | def get_mpd(mps, D, ctrl="A", **kwargs):
"""function to switch more easily between different optimization modes"""
match ctrl.lower():
case "a" | "analytic":
return dall(mps, D, **kwargs)
case "i" | "identities":
return iter_ii_oall(mps, D, **kwargs)
case "s" | "s... |
def preprocess_val_data(images_V,labels_V):
aug_imgs_V = np.zeros(images_V.shape)
aug_labels_V = np.zeros(labels_V.shape)
for i in range(len(images_V)):
aug_imgs_V[i], aug_labels_V[i]=aug_fu_val(images_V[i],labels_V[i])
return aug_imgs_V,aug_labels_V
def preprocess_train_data(images_T,labels_T):... | The code trains a student UNet model using knowledge distillation from a teacher model and auxiliary student models. It initializes multiple UNet architectures, loads pre-trained weights, and defines custom losses. The student model is trained in sub-batches, guided by frozen teacher/student features and segmentation o... | def train_model(total_epochs, save_dir,train_images,train_labels,val_images,val_labels):
# save log files for disconection of server
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='train_unet_Gtan_status.log', level=logging.DEBUG, format=LOG_FORMAT)
# de... |
def preprocess_val_data(images_V,labels_V):
aug_imgs_V = np.zeros(images_V.shape)
aug_labels_V = np.zeros(labels_V.shape)
for i in range(len(images_V)):
aug_imgs_V[i], aug_labels_V[i]=aug_fu_val(images_V[i],labels_V[i])
return aug_imgs_V,aug_labels_V
def preprocess_train_data(images_T,labels_T):... | This code trains a 2D UNet model for image segmentation using Adam optimizer and IOU loss. It processes training data in subsets, validates on a separate dataset, saves model weights at intervals, and retains the best model based on validation loss. The training logs are recorded in 'small_unet.log', and the model arch... | def train_model(total_epochs, save_dir,train_images,train_labels,val_images,val_labels):
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='small_unet.log', level=logging.DEBUG, format=LOG_FORMAT)
model = models.unet_2d((1024, 1280,3), [4, 6, 12, 32, 32], n_labels=1,... |
def preprocess_val_data(images_V,labels_V):
aug_imgs_V = np.zeros(images_V.shape)
aug_labels_V = np.zeros(labels_V.shape)
for i in range(len(images_V)):
aug_imgs_V[i], aug_labels_V[i]=aug_fu_val(images_V[i],labels_V[i])
return aug_imgs_V,aug_labels_V
def preprocess_train_data(images_T,labels_T):... | This code trains a 2D UNET model for image segmentation using custom loss functions, with data preprocessing, validation, learning rate adjustment, and periodic saving of the best model weights based on validation loss. | def train_model(total_epochs, save_dir,train_images,train_labels,val_images,val_labels):
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
logging.basicConfig(filename='parts_unet.log', level=logging.DEBUG, format=LOG_FORMAT)
# model = models.swin_unet_2d((1024, 1280,3), filter_num_begin=64, n_l... |
def CONV_stack_3D(X, channel, kernel_size=3, stack_num=2,
dilation_rate=1, activation='ReLU',
batch_norm=False, name='conv_stack'):
'''
Stacked convolutional layers:
(Convolutional layer --> batch normalization --> Activation)*stack_num
CONV_stack(X, channel, kernel_size=3... | The code implements a 3D V-Net for volumetric medical image segmentation, using residual blocks, downsampling/up sampling with skip connections. It processes input tensors through convolutional layers, pooling/unpooling, and returns the segmented output tensor. Key features include adjustable filters, residual blocks, ... | def vnet_3d_base(input_tensor, filter_num, res_num_ini=1, res_num_max=3,
activation='ReLU', batch_norm=False, pool=True, unpool=True, name='vnet'):
'''
The base of 2-d V-net.
vnet_2d_base(input_tensor, filter_num, res_num_ini=1, res_num_max=3,
activation='ReLU', batch... |
def output_centroids(self):
with open(self.output_filename, 'w') as file:
line = str()
for centroid in self.centroids:
for coordinate in centroid:
line += str("%.4f" % float(coordinate))
line += ","
file.write(line[:... | The code implements an iterative clustering algorithm (likely K-means) by repeatedly assigning data points to clusters, updating centroids, and checking for convergence. It runs up to `max_iter` times, terminating early if convergence is achieved. Upon completion, it outputs the final centroids to a file. | def run(self): # apply the algorithm and save the result in the output file given
for _ in range(self.max_iter):
if self.is_converged:
self.output_centroids()
return
self.assign_to_clusters()
self.old_centroids = [centroid for centroid in self... |
def _viewMedia(self, mediaType, mediaEntries, row, column):
# Try to execute the command(s)
try:
# Intialize variable
hrefURL = ''
# Set pseudo variable
pseudoURL = self._mediaSearchURL(mediaType, 'pseudo') + mediaEntries[row - 1]
# Open sear... | The function displays RSS feed content in a GUI using tkinter, creating labeled entries with titles, publication dates, and interactive buttons (View/Ignore/Delete) for each media item. It applies styling parameters from `dictHeaderRow` to format UI elements and positions them in a grid layout, incrementing row positio... | def rssFeedContentDisplay(self, mediaType, rssFeedResponse, dictHeaderRow):
# Initialize variables
posVal = 1
# Initialize media array
mediaEntries = []
# Try to execute the command(s)
try:
# Set variables from dictionary
reliefTitleVal = dictHea... |
def send_message_to_client(self, message, client_id, update=False):
"""Send a message to a specific client."""
client = self.clients.get(client_id)
if not client:
return # Client not found
aes_key = client['aes_key']
client_socket = client['socket']
iv = os.... | This code handles a client connection by establishing a secure communication channel using ECDH key exchange and AES encryption. It generates and exchanges keys, derives a shared secret, encrypts a welcome message, and processes incoming encrypted messages. It supports username changes, message broadcasting, and target... | def handle_client(self, client_socket, addr):
"""Handle the client connection."""
print(f"Connection established with {addr}")
# Generate ECDH keys for Diffie-Hellman
server_private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
server_public_key = server_priva... |
def isPure(self, dataSet):
return dataSet[self.targetAttribute].unique().shape[0] == 1
def ErrorSum(self, data):
error = 0
mean = data[self.targetAttribute].mean()
for index, row in data.iterrows():
error = error+ (row[self.targetAttribute] - mean)**2
return error
def... | The code constructs a decision tree recursively by selecting the best attribute to split the dataset, creating leaf nodes when the dataset is pure, below a threshold size, or no attributes remain. It splits data into true/false branches based on attribute values and recursively builds subtrees, returning the root node ... | def makeTree(self, dataSet, threshold, attributes):
root = Tree.MultiSplitTree()
mostCommonLabel = dataSet[self.targetAttribute].mean()
if self.isPure(dataSet) or dataSet.shape[0] < threshold or len(attributes) == 0 :
root.isLeaf = True
root.label = mostCommonLabel
... |
def isPure(self, data):
return data[self.targetAttribute].unique().shape[0] == 1
def getEntropy(self, data):
splits = data[self.targetAttribute].value_counts().to_dict()
entropy = 0.0
for label, c in splits.items():
frequency = c / data.shape[0]
entropy = entropy ... | This function recursively constructs a decision tree by selecting the optimal attribute to split the dataset based on entropy. It creates leaf nodes when the dataset is pure, has no attributes left, or meets a threshold. For binary splits, it divides data into subsets and creates true/false children; for multi-splits, ... | def makeTree(self, dataSet, threshold, attributes):
root = Tree.MultiSplitTree()
mostLabel = dataSet[self.targetAttribute].value_counts().idxmax()
if self.isPure(dataSet) or len(
attributes) == 0 or dataSet.shape[0] < threshold:
root.isLeaf = True
root.lab... |
def normalize(self):
for attribute in self.attributes:
minAtt = self.dataSet[attribute].min()
maxAtt= self.dataSet[attribute].max()
self.dataSet[attribute] = self.dataSet[attribute].apply(lambda x: (x - minAtt) / (maxAtt - minAtt))
def makeTree(self, dataSet, threshold, attri... | The code performs k-fold cross-validation for a regression model. It normalizes data, splits it into folds, and evaluates decision tree performance using mean squared error (SSE) across training and test sets for varying thresholds. It reports average training/test errors, standard deviation, and execution time for eac... | def validate(self):
cols = list(self.dataSet)
self.attributes = cols[0:len(cols) - 1]
self.targetAttribute = cols[len(cols) - 1]
self.normalize()
start = 0
end = 0
rows = self.dataSet.shape[0]
Range = rows // self.fold
shuffledDataSet = se... |
def normalize(self):
if self.binary:
for attribute in self.attributes:
minAtt = self.dataSet[attribute].min()
maxAtt = self.dataSet[attribute].max()
self.dataSet[attribute] = self.dataSet[attribute].apply(lambda x: (x - minAtt) / (maxAtt - minAtt))
def... | The code performs k-fold cross-validation on a dataset, training and evaluating a decision tree for varying nmin thresholds. It normalizes data, splits into folds, calculates training/test accuracy, standard deviation, and prints results including confusion matrix stats and execution time. | def validate(self):
cols = list(self.dataSet)
self.attributes = cols[0:len(cols) - 1]
self.targetAttribute = cols[len(cols) - 1]
self.normalize()
start = 0
end = 0
rows = self.dataSet.shape[0]
Range = rows // self.fold
shuffledDat... |
def _get_simulated_trajectories(self, experiment_name: str = None) -> np.ndarray:
if experiment_name is None:
experiment_name = 'temp'
return simulate_quantum_circuits(qc_stack=[self.get_doobed_quantum_circuit(experiment_name)],
NTRAJ=self._NTRAJ, ho... | The function analyzes the distribution of an observable from simulated trajectories by creating a normalized histogram. If resampling is enabled, it computes error ranges via percentiles of resampled histograms. It returns the histogram and errors, or just the histogram if no resampling is requested. | def analyse_observable_histogram(self, experiment_name: str = None, num_resamples: int = 1) -> Union[
np.ndarray, list[np.ndarray]]:
# prepare data for analysis
trajs_str = self._get_simulated_trajectories(experiment_name=experiment_name)
if trajs_str.size != self._NTRAJ:
p... |
def compute_shape_descriptor(self, mesh):
"""Compute the shape descriptor for each vertex"""
# PCA transformation
pca = PCA(n_components=3)
pca_coordinates = pca.fit_transform(mesh.vertices)
# Vertex normals
normals = mesh.vertex_normals
# Calculate shape diamet... | The code simplifies a 3D mesh by collapsing edges with low error metrics (below a threshold) to reduce vertex count while preserving segmentation boundaries. It computes quadrics, replaces vertices with midpoints, updates face indices, and removes degenerate faces, returning a simplified mesh using trimesh. | def simplify_mesh(self, mesh, path, threshold=200):
"""Simplify the mesh while preserving the segmentation boundaries"""
self.mesh = mesh
self.shape_descriptor = self.compute_shape_descriptor(mesh)
self.probability_matrix = self.compute_probability_matrix(self.shape_descriptor)
... |
def customTopoTree(depth=1, fanout=2 ):
'''
Topo: Tree topology h1 \\
s2 \\
h2 // \\
s1
h3 \\ //
s3 //
hn //
'''... | The code defines a function `customTopo` that selects and configures network topologies based on user input. It checks the input `topo` type (tree, chain, dumbbell), prompts for parameters like depth, fanout, or host count, and calls corresponding helper functions to generate the specified network structure. If an unsu... | def customTopo(topo):
if(topo == "tree"):
print("tree selected")
depth = int(input ("Insert depth of the tree: "))
fanout = int(input ("Insert fanout of the tree: "))
customTopoTree(depth,fanout)
elif(topo == "chain"):
print("chain selected")
n = int(input ("Ins... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.