dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def two_view_reconstruction_general(
p1: np.ndarray,
p2: np.ndarray,
camera1: pygeometry.Camera,
camera2: pygeometry.Camera,
threshold: float,
iterations: int,
) -> Tuple[Optional[np.ndarray], Optional[np.ndarray], List[int], Dict[str, Any]]:
"""Reconstruct two views from point correspondenc... | The main task of the code is to reconstruct a 3D scene from two images (im1 and im2) using their corresponding feature points (p1, p2) and camera models. It performs two-view reconstruction, checks inlier consistency, adds shots to the reconstruction, aligns the model, triangulates points, and applies bundle adjustment... | def bootstrap_reconstruction(
data: DataSetBase,
tracks_manager: pymap.TracksManager,
im1: str,
im2: str,
p1: np.ndarray,
p2: np.ndarray,
) -> Tuple[Optional[types.Reconstruction], Dict[str, Any]]:
"""Start a reconstruction using two shots."""
logger.info("Starting reconstruction with {}... |
def paint_reconstruction(
data: DataSetBase,
tracks_manager: pymap.TracksManager,
reconstruction: types.Reconstruction,
) -> None:
"""Set the color of the points from the color of the tracks."""
for k, point in reconstruction.points.items():
point.color = list(
map(
... | The main task of the code is to incrementally add image shots to an initial reconstruction by resectioning, triangulating new points, refining camera poses through bundling, and managing retriangulation/outlier removal. It iteratively expands the reconstruction, aligns with ground control points, and logs detailed step... | def grow_reconstruction(
data: DataSetBase,
tracks_manager: pymap.TracksManager,
reconstruction: types.Reconstruction,
images: Set[str],
gcp: List[pymap.GroundControlPoint],
) -> Tuple[types.Reconstruction, Dict[str, Any]]:
"""Incrementally add shots to an initial reconstruction."""
config =... |
def compute_image_pairs(
track_dict: Dict[Tuple[str, str], tracking.TPairTracks], data: DataSetBase
) -> List[Tuple[str, str]]:
"""All matched image pairs sorted by reconstructability."""
cameras = data.load_camera_models()
args = _pair_reconstructability_arguments(track_dict, cameras, data)
process... | The function performs incremental 3D reconstruction by processing image pairs from common tracks, bootstrapping initial reconstructions, and expanding them using remaining images and ground control points. It returns a report with timing data, unreconstructed images, and a list of sorted reconstructions based on the nu... | def incremental_reconstruction(
data: DataSetBase, tracks_manager: pymap.TracksManager
) -> Tuple[Dict[str, Any], List[types.Reconstruction]]:
"""Run the entire incremental reconstruction pipeline."""
logger.info("Starting incremental reconstruction")
report = {}
chrono = Chronometer()
images =... |
def get_test_ds(onp_array):
"""Returns a tf.data.Dataset from a numpy array solely for iteration purposes."""
ds = tf.data.Dataset.from_tensor_slices(onp_array)
ds = ds.batch(cfg.batch_size)
return ds
def predict_ds(train_state, ds):
"""Predicts on a dataset."""
jnp_preds = [predict_model(train_state, tf_to... | The code evaluates a generator's performance in a GAN by comparing its generated distribution (G#P) to an optimal Monge map (T#P). It calculates the absolute and relative W2 gaps between these distributions, then computes W1 metrics to assess global transport costs. The goal is to quantify how closely the generator app... | def evaluate(gan_state, onp_P, onp_Q, monge_gt):
"""Evaluate the quality of the generator.
Args:
gan_state: GAN state.
onp_P: numpy.ndarray of shape (n, d) where n is the number of samples and d the dimension.
onp_Q: numpy.ndarray of shape (n, d) where n is the number of samples and d the dimension.
... |
def apply_convex(params, state, inputs):
model_params = {'params': params, 'convex': state.convex_state}
out, variables = state.push(model_params, inputs, train=True, mutable='convex')
return out, variables
def pushforward_loss(gP, Q, disc_state):
"""Computes Wasserstein-2 regularized loss between T#P and Q.
... | The code computes the generator's loss in a GAN by applying convex transformations to parameters, calculating a pushforward loss using the discriminator's state, and returning the loss along with updated convex state variables. | def generator_loss(params):
gP, variables = apply_convex(params, gan_state.gen_state, P)
loss = pushforward_loss(gP, Q, gan_state.disc_state)
return loss, get_convex_state(variables) |
def sample_perf(p):
# Core allocations of each job
app_cores = [""] * NUM_APPS
s = 0
for j in range(NUM_APPS - 1):
app_cores[j] = ",".join(
[str(c) for c in list(range(s, s + p[j]))])
s += p[j]
app_cores[NUM_APPS - 1] = ",".join(
[str(c) for c in list(range(s, NUM... | The code implements Bayesian Optimization to find the optimal configuration by iteratively evaluating new samples using a Gaussian Process surrogate model. It updates the model with performance data, selects the next sample via Expected Improvement (EI), and handles duplicate configurations by modifying existing ones t... | def bayesian_optimization_engine(x0, alpha=1e-5):
global MODEL, OPTIMAL_PERF
x_list = []
q_list = []
y_list = []
# Sample initial configurations
for params in x0:
x_list.append(params)
q, y = sample_perf(params)
q_list.append(q)
y_list.append(y)
xp = np.arr... |
def gen_bounds_and_constraints():
global BOUNDS, CONSTS
# Generate the bounds and constraints required for the optimizer
BOUNDS = np.array([[[1, NUM_UNITS[r] - (NUM_APPS - 1)] for a in range(NUM_APPS - 1)] \
for r in range(NUM_RESOURCES)]).reshape(NUM_PARAMS, 2).tolist()
CONSTS ... | The code performs Bayesian optimization for resource allocation, generating constraints, initial configurations, and baseline performance metrics. It then executes the optimization process to determine the optimal resource distribution, returning the number of iterations and the achieved objective value. | def c_lite():
# Generate the bounds and constraints required for optimization
gen_bounds_and_constraints()
# Generate the initial set of configurations
init_configs = gen_initial_configs()
# Get the baseline performances with maximum allocations for each application
app_cores = get_baseline_pe... |
def _conv_block(self, inputs, filters, kernel, strides, nl):
x = Conv2D(filters, kernel, padding='same', strides=strides)(inputs)
x = BatchNormalization()(x)
return self._return_activation(x, nl)
def _bottleneck(self, inputs, filters, kernel, e, s, squeeze, nl):
input_shap... | This code constructs a convolutional neural network (CNN) model with multiple feature extraction layers, including convolutional blocks and bottleneck layers, to process input data through progressively reduced spatial dimensions. It generates intermediate feature maps (x1–x5) and a final classification output, optiona... | def build(self, plot=False):
inputs = Input(shape=self.shape, name="Attention_Inputs")
x = self._conv_block(inputs, 16, (3, 3), strides=(2, 2), nl='HS') # 128 out
x1 = x
x = self._bottleneck(x, 16, (3, 3), e=16, s=2, squeeze=True, nl='RE') # 64 out
x2 =... |
def calculate_cosine_similarity_matrix():
cosine_sim = linear_kernel(calculate_tfidf(), calculate_tfidf())
return cosine_sim
def create_indices():
# Construct a reverse map of indices and product titles
indices = pd.Series(get_pickle_file().index,
index=get_pickle_file()['product... | The function generates product recommendations by calculating cosine similarity between items, sorting them by similarity scores, and returning the top 10 most similar products based on a given query. | def get_recommendations(query, cosine_sim=calculate_cosine_similarity_matrix()):
# cosine_sim = calculate_cosine_similarity_matrix()
# Get the index of the product that matches the query
# gettin the index of the product that matches the title
idx = create_indices()[query]
# Get the pairwsie simil... |
def readAllData():
train_x = np.loadtxt(sys.argv[1], delimiter=',', converters={11: lambda s: 1 if s == b'R' else 0})
train_y = np.loadtxt(sys.argv[2], delimiter=',').astype(int)
test_x = np.loadtxt(sys.argv[3], delimiter=',', converters={11: lambda s: 1 if s == b'R' else 0})
return train_x, train_y, te... | The code's main task is to preprocess data by normalizing training and test features, apply three classification algorithms (KNN, Perceptron, PA) on the training set, predict test samples, and print each model's predictions for comparison. It loads data, normalizes it, trains models with specified parameters, and outpu... | def main():
train_x, train_y, test_x = readAllData()
train_x, test_x = normilizeData(train_x, test_x)
# checkAlgo(train_x, train_y)
KNN_yhat = KNN(7, train_x, train_y, test_x)
perceptron_yhat = perceptron(train_x, train_y, test_x, 0.6, 19)
pa_yhat = pa(train_x, train_y, test_x, 0.6, 19)
for ... |
def perceptron(train_x, train_y, test_x, eta, epoches):
prediction = []
# train - make w correct according to training
w = trainWPer(train_x, train_y, eta, epoches)
# use w for test_x
for i in range(len(test_x)):
yhat = labelYHat(w, test_x[i])
prediction.append(yhat)
return predi... | The code evaluates the performance of a classification model (perceptron or PA algorithm) by iterating over different learning rates (eta) and epochs. It returns an array of average accuracies for each epoch-eta combination on test data, helping to analyze how varying eta and training iterations impact model effectiven... | def testEpochEta(temp_train_x, temp_train_y, temp_test_x, temp_test_y, index):
accuracy_array = []
eta_range = 25
for epoch in range(20):
accuracy_array.append([])
for eta in range(eta_range):
if index == 0:
yhat = perceptron(temp_train_x, temp_train_y, temp_test_... |
def trainAlgo(train_x, train_y, params, epochs, lr):
w1, b1, w2, b2 = [params[key] for key in ('w1', 'b1', 'w2', 'b2')]
for i in range(epochs):
# print()
# print("*************")
# print(f"epoch: {i+1}")
# print("*************")
# print()
zip_arr = list(zip(train_... | The code tests different learning rates (eta) on a fixed number of training epochs (40) using a specified algorithm. It iterates through a range of eta values, trains the model, evaluates accuracy on test data, and records results in an array. The output includes accuracy, eta, and training time for each iteration. | def testEpochEta(temp_train_x, temp_train_y, temp_test_x, temp_test_y, params):
accuracy_array = []
epoch_to_check = 25
for epoch in range(1):
epoch_to_check = (epoch_to_check * 2)
eta_to_check = 0.005
accuracy_array.append([])
for eta in range(1):
start_time = ti... |
def splitData(data, index):
train = []
test = []
data_size = len(data)
for i in range(data_size):
if (i >= (index*(data_size/5)) and i <= ((index+1)*(data_size/5))):
test.append(data[i])
else :
train.append((data[i]))
return train,test
def testKNN(temp_train_x... | The code evaluates and compares the performance of KNN, PER (perceptron), and PA (passive-aggressive) algorithms on 5 data splits. It splits training data, tests each algorithm, collects accuracy results, averages them, and identifies optimal parameters (best K, epoch, eta) for each model. The main task is to determine... | def checkAlgo(train_x, train_y):
knn_all_arrays = []
per_all_arrays = []
pa_all_arrays = []
for i in range(5):
temp_train_x_arr, temp_test_x_arr = splitData(train_x, i)
temp_train_y_arr, temp_test_y_arr = splitData(train_y, i)
temp_train_x = numpy.array(temp_train_x_arr)
... |
def splitData(data, index):
train = []
test = []
data_size = len(data)
for i in range(data_size):
if (i >= (index*(data_size/5)) and i <= ((index+1)*(data_size/5))):
test.append(data[i])
else :
train.append((data[i]))
return train, test
def testEpochEta(temp_t... | The function `checkAlgo` performs 5-fold cross-validation on training data by splitting it iteratively, training a model with given parameters (`params`), and evaluating accuracy on test splits. It aggregates results, computes the average accuracy, and identifies the optimal combination of training epochs (`best_epoch`... | def checkAlgo(train_x, train_y, params):
all_arrays = []
for i in range(5):
print()
print("**********")
print(f"iter: {i}")
print("**********")
print()
temp_train_x_arr, temp_test_x_arr = splitData(train_x, i)
temp_train_y_arr, temp_test_y_arr = splitData... |
def loadData():
train_x = np.loadtxt(sys.argv[1])
train_y = np.loadtxt(sys.argv[2]).astype(int)
test_x = np.loadtxt(sys.argv[3])
return train_x, train_y, test_x
def normalizeData(train_x, test_x):
for i in range(len(train_x)):
train_x[i] = train_x[i]/255
for i in range(len(test_x)):
... | The main task of the code is to initialize a neural network with random weights and biases, load and normalize training/test data, then evaluate or check an algorithm's performance using the trained parameters on the training data. | def main():
y_hat_array = []
# initialize
w1 = np.random.uniform(-1, 1, (128, 784))
b1 = np.random.uniform(-1, 1, (128, 1))
w2 = np.random.uniform(-1, 1, (10, 128))
b2 = np.random.uniform(-1, 1, (10, 1))
params = {'w1': w1, 'b1': b1, 'w2': w2, 'b2': b2}
# read all data
train_x, trai... |
def findPQValues(lowerBound: int, upperBound: int):
return findRandomPrime(lowerBound, upperBound), findRandomPrime(lowerBound, upperBound)
def findE(m: int):
e = 3
while gcdExtended(m, e)[0] != 1:
e += 2
return e
def cipherText(x: int, e: int, n: int):
return pow(x, e, n)
def decipherText(y... | The main task of the code is to implement RSA encryption and decryption. It generates RSA keys (p, q, n, e, d) within specified bounds, encrypts an input value (integer or text) using the public key, and decrypts it using the private key. The code handles both numeric and text inputs, converting text to integers for en... | def RSA():
rango = [sys.argv[1], sys.argv[2], sys.argv[3]]
lowerBound = 2**int(rango[0])
upperBound = 2**int(rango[1])
isText = False
intToCipher = None
try:
intToCipher = int(sys.argv[3])
except ValueError:
print(f"input {sys.argv[3]} is not an integer, using text mode")
... |
def is_legal_move(self, pos, player=None):
"""
Given the current player and position, returns whether or not the current move is legal.
:param player: The player color from constants.
:param pos: The position to play from.
:return: boolean of whether or not the current player can... | The function attempts to execute a player's move at a specified position on a game board. It validates the move, updates the board state by placing the player's disc, flips adjacent discs, records the move, switches the current player, and updates scores. If invalid, it returns False. | def make_move(self, pos, player=None):
"""
Given a player and position (row, col), attempts to move and returns True.
If it is not a valid move, returns False.
:param player: The player color from constants.
:param pos: The position to play from as tuple (row, col)
:retu... |
def arguments_parser():
parser = argparse.ArgumentParser(
description = "Extract data from DVL TCP stream")
parser.add_argument(
"message_type",
choices = [ "velocity", "dead_reckoning" ],
help = "Type of DVL message to handle")
parser.add_argument(
"-i",
"--i... | The main task of the code is to process messages from a DVL socket, either writing them to a CSV file or not, based on command-line arguments. It parses input parameters, initializes a socket connection, and uses `_process_messages` to handle data, with optional CSV output via `_CSVWriter` if a file path is provided. | def main():
arguments = arguments_parser().parse_args()
csv_file_path = arguments.csv
message_type = _type(arguments.message_type)
time_format = arguments.time_format
if csv_file_path:
with open(csv_file_path, "w") as csv_file:
_process_messages(
_start_dvl_socket... |
def load_checkpoint(self, checkpoint_path: str):
"""Load a checkpoint of the model
Args:
checkpoint_path (str): a path to the checkpoint to load
Returns:
epoch (int): the epoch number of the loaded checkpoint
"""
checkpoint = torch.load(self.checkpoint_p... | The code trains a NeRF model over multiple epochs using provided datasets, with optional checkpoint loading. It tracks training loss and evaluates PSNR at intervals, generating visualizations. | def train(
self,
num_epochs: int,
train_dataset: Dataset,
eval_dataset: Dataset,
checkpoint_to_load: str = None,
):
"""Train the NeRF model.
Args:
num_epochs (int): number of epochs to train for
images (list): a list of images to train ... |
def get_message_functions(self, sensor, sensor_settings):
if sensor_settings.convert_module != None:
get_message_func = sensor_settings.convert_module.convert_function
message_type = sensor_settings.convert_module.message_type
else:
try:
message_type, ... | The main task of the code is to register a CARLA sensor by configuring a publisher for sensor data, optionally creating a subscriber for a sub-topic, and attaching the sensor to a vehicle. It retrieves message handling functions, validates their existence, creates necessary ROS2 publishers/subscribers, and links them t... | def register_sensor(self, sensor: carla.Sensor, sensor_settings, sub_topic=None) -> None:
get_message_func, message_type = self.get_message_functions(sensor, sensor_settings)
if get_message_func == None or message_type == None:
return
publisher = create_publisher(message_type, sensor... |
def get_all_sensors(self):
sensors = self.world.get_actors().filter('*sensor*')
return sensors
def has_sensor(self, sensor: carla.Sensor) -> bool:
if sensor.id in self.registered_sensor_dict:
return True
return False
def add_sensor(self, sensor: carla.Sensor) -> None:
... | This function registers new sensors by iterating through all available sensors, skipping those without a parent or already registered, then adding them and checking their configuration. | def register_new_sensors(self) -> None:
sim_sensor_list = self.get_all_sensors()
for sensor in sim_sensor_list:
if sensor.parent == None:
continue
if self.has_sensor(sensor):
continue
self.add_sensor(sensor)
self.check_for_c... |
def chooseinput():
usrin = input("Please choose one of the input blocking method:\n1.mouse only\n2.keyboard only\n3.both mouse and keyboard\nEnter either 1,2 or 3: ")
if "1" in usrin:
print("disabling mouse")
blockmouse()
elif "2" in usrin:
print("disabling keyboard")
blockkb... | The code allows users to select a time management program (25, 50, or 90 minutes) via input. Depending on the choice, it executes corresponding functions (TFMIN, FTMIN, NTMIN) or prompts retry for invalid inputs, ensuring task-specific time management workflows are initiated. | def choosetime():
usrin = input("Please choose one of the time management programs :D: ")
if "25" in usrin:
print("25min selected")
chooseinput()
TFMIN()
elif "50" in usrin:
print("50min selected")
FTMIN()
elif "90" in usrin:
print("90 min selected")... |
def open_file(fname, cond):
if cond:
import gzip
return gzip.open(fname, 'rt')
return open(fname, 'rt')
def mask_telomeres(seq, pattern):
comp_pattern = complement(pattern, reverse=True)
mask_num = 0
for pat in (pattern*3, comp_pattern*3):
last_hit = 0
seqlis = []
... | The code processes FASTA sequences to identify permutation candidates based on specified patterns and parameters. It masks telomeres if enabled, filters results, and outputs findings as a table and FASTA file. The task includes reading input, performing permutation searches, applying filters, and reporting runtime and ... | def run(args):
st = time.time()
all_perms = []
with open_file(args.infile, args.gzip) as f:
for record in SeqIO.parse(f, 'fasta'):
record_sequence = str(record.seq)
record_header = record.description
if args.mask or args.filter > 0:
record_sequence... |
def usernameexistance(Username): # make sure of existance of a file with the name of the username
if os.path.exists('%s.csv' % Username):
return True
else:
return False
def Password_validation(Name, Password): # make sure that password is valid (not a blank, not the same as username)
while... | The main task of the code is to register a new user by validating a unique username, ensuring a secure password, and collecting budget/saving inputs. It checks for existing usernames, validates password strength, confirms numerical values for budget and savings, and creates a new user profile with adjusted financial pa... | def Sign_up(Name): # This function is called when user decides to sign up(New User)
while usernameexistance(Name) == True:
Name = input("This one already exists, please enter another username: ")
Password = Password_validation(Name,input('Enter your password: '))
Budget = float_validation(input("En... |
def display(self, state):
"""Print or otherwise display the state."""
print(state)
print(state.moves)
board = state.board
for y in range(0, self.w + 1):
print(f"{y}", end=" ")
for x in range(1, self.h + 1):
if x != 0: print('\n', end=f"{x} ")
... | The code simulates an n-player turn-based game by iteratively letting each player choose a move, updating the game state, and checking for a terminal condition. If the game ends, it displays the final state and returns the utility value for the initial player. | def play_game(self, *players):
"""Play an n-person, move-alternating game."""
state = self.initial
while True:
for player in players:
self.display(state)
move = player(self, state)
state = self.result(state, move)
if sel... |
def reset(self):
K.set_value(self.input_modifier.weights[0], np.zeros(K.get_variable_shape(self.input_modifier.weights[0])))
def _begin_train(self, input, target, num_changed_attributes=None, skip_attributes=0,
direction_mask=None):
'''
Initializes the training process and prepares the m... | The code trains a model to generate a CADEX (Counterfactual Explanation) by modifying input attributes under constraints like maximum attribute changes, categorical thresholds, and direction masks. It initializes training parameters, iterates for a set number of epochs, and returns the adversarial example (result) and ... | def train(self, input, target, num_classes, num_changed_attributes=None, max_epochs=1000, skip_attributes=0,
categorical_threshold=0, direction_constraints=None):
'''
Train the model to produce a CADEX explanation.
:param input: original unmodified input vector, as a Pandas dataframe
... |
def cameraPredict_state_idle() :
return
def cameraPredict_state_capturing() :
state_Capturing()
def cameraPredict_state_ml() :
threadFinished = not cameraPredictThreading.is_alive()
if threadFinished :
mqtt_cameraPredict_ml_finished_callback()
def cameraPredict_state_line() :
threadFinished ... | This function manages camera operations by checking the current state of prediction and capture processes. It executes corresponding functions based on states like idle, capturing, machine learning, or line processing, ensuring proper transitions and error handling for invalid states. | def cameraControlLoop() :
# print('predictState' + str(cameraPredictState))
print('captureState' + str(cameraCaptureState))
# cameraPredict
if cameraPredictState == STATE_IDLE :
cameraPredict_state_idle()
elif cameraPredictState == STATE_CAPTURING:
cameraPredict_state_capturing()
... |
def scrape_table_standings(chrome_driver: webdriver.Chrome,
logger: logging.Logger) -> Optional[WebElement]:
try:
log_event(logger, logging.DEBUG, f'>>>> Detecting HTML elements ...')
return chrome_driver.find_element(By.CLASS_NAME, 'leaguetable'... | The main task of the code is to extract Premier League standings data from a webpage using a Chrome driver. It retrieves the standings table, extracts rows, and processes the data into a structured list of lists. The logger records execution details, and the function returns the extracted data or None if unsuccessful. | def extract_data(chrome_driver: webdriver.Chrome,
logger: logging.Logger) -> Optional[List[List[str]]]:
prem_league_table = scrape_table_standings(chrome_driver, logger)
table_rows = scrape_table_rows(prem_league_table, logger)
return scrape_data_... |
def load_training_data(load_exemplars):
training_samples = load_framenet_samples(
exclude_docs=SESAME_DEV_FILES + SESAME_TEST_FILES
)
if load_exemplars:
training_samples += load_framenet_samples_from_exemplars()
return training_samples
def load_validation_data():
return load_framenet... | The main task of the code is to load and structure a FrameNet dataset for sequence labeling tasks, mapping frames to B/I-tagged IDs and organizing training/validation/test splits into a Hugging Face DatasetDict. It downloads NLTK FrameNet data, generates label mappings, loads data with optional exemplars, and returns t... | def load_dataset_nltk(load_exemplars=False):
nltk.download("framenet_v17")
ds = DatasetDict()
global FRAME2ID
FRAME2ID = {}
for i, frame in enumerate(fn.frames(), start=1):
FRAME2ID[f'B-{frame["name"]}'] = i * 2 - 1
FRAME2ID[f'I-{frame["name"]}'] = i * 2
train_data = load_trai... |
def generation(self, gen: int, draw=False):
"""
Creates a new generation of networks from the
current one.
"""
new_generation = []
nets_sorted, values_sorted = self.sort_by_evaluation(draw)
print(f"Generation {gen}: {values_sorted}")
print()
# Sel... | The code's main task is to execute an evolutionary algorithm over a specified number of generations, running the `generation` method iteratively and generating plots to visualize the evolution of the best, worst, average fitness, and diversity metrics across generations. | def evolve(self, generations: int, draw=False):
"""
Implements the evolutionary algorithm.
"""
# progress_bar = tqdm(range(generations), leave=False)
for i in range(generations):
self.generation(i, draw)
# progress_bar.update()
# progress_bar.clo... |
def UpdatePercept( current_position, index, value ):
global percept_state
v, s, w, b, p = percept_state[current_position[0]][current_position[1]]
value = min( value, 5 )
if( index == 0 ): v = value
if( index == 1 ): s = value
if( index == 2 ): w = value
if( index == 3 ): b = value... | The function `ShotArrow` simulates shooting an arrow at a specified position in a game, updating the percept state, deducting score, and checking if the Wumpus is hit. If successful, it toggles the Wumpus's state, updates smell, and returns `True`; otherwise, it returns `False`. The function handles visual updates, del... | def ShotArrow( position ):
global map_state, percept_state, total_score
UpdatePercept( position, W, 0 )
total_score -= 100
print('ACTION States.SHOT ', 9- agent_position[0], agent_position[1])
get_player_direction('Shot')
draw(visited_position, agent_position, map_state)
time.sleep(0.5)
... |
def CheckState( current_position, key ):
current_x, current_y = current_position
if( ( map_state[current_x][current_y] & ( 1 << key ) ) != 0 ):
if key == G or key ==W:
visited_position.add(current_position)
draw(visited_position, agent_position, map_state)
time... | The main task of the code is to process sensory information from the current position in a Wumpus game, updating the percept state, frontier, and neighboring cells' suspicions/dangers. It marks the current cell as visited, checks for game-ending conditions, adjusts frontier exploration, and propagates logical inference... | def ReceivePercept( current_position ):
global percept_state, frontier
current_x, current_y = current_position
visited, stench, wumpus, breeze, pit = percept_state[current_x][current_y]
# print( current_position )
# :333333333333333333333333333 End game :33333333333333333333333333333
if... |
def CollectGold( position ):
global map_state, total_score
if( CheckState( position, G ) ):
map_state[position[0]][position[1]] ^= ( 1 << G )
total_score += 1000
print('ACTION States.COLLECT ',9- agent_position[0], agent_position[1])
print('Score: ', total_score )
... | The code defines a function `MoveOneStep` that moves an agent to a specified position, deducts a penalty score, collects gold if present, updates the environment state, visualizes the movement with delays, and tracks the agent's path. It handles percept input, direction changes, and score tracking during navigation in ... | def MoveOneStep( position ):
global agent_position, total_score
if( position == agent_position ): return
total_score -= 10
agent_position = position
visited_position.add(agent_position)
gold=CollectGold( agent_position )
if gold:
draw(visited_position, agent_position, map_state)
... |
def GetNeighbor( current_position ):
neighbor = []
moveX = [0, 1, 0, -1]
moveY = [1, 0, -1, 0]
current_x, current_y = current_position
for _ in range(4):
_x = current_x + moveX[_]
_y = current_y + moveY[_]
if( not CheckValid( ( _x, _y ) ) ): continue
neighbo... | The main task of the code is to preprocess a map by reading its layout, initializing global states (map_state, percept_state), detecting obstacles (W), player (P), and gold (G) positions, updating adjacent cell states, setting the agent's starting position, and initializing percept data for navigation. It prepares the ... | def PreProcess() :
global map_size, map_layout
global agent_position, map_state, percept_state
global player_direction
player_direction = '>'
# Read map from file
map_size, map_layout = read_file(file_path)
# Initialization
map_state = [[0] * map_size for _ in range(map_size)]
perce... |
def NotKillThisWumpus( current_position ):
current_x, current_y = current_position
if( percept_state[current_x][current_y][W] in [0, None] ): return False
if( len(GetNeighbor( current_position )) < 4 ): return False
for _x, _y in GetNeighbor( current_position ):
if( percept_state[_x][_y][0] ==... | The main task of the code is to select the next safe goal from the frontier, navigate the agent to it, handle potential Wumpus encounters, and update the frontier. It filters unsafe positions, sorts the frontier, moves the agent step-by-step, checks for Wumpus, and either shoots it or proceeds to the goal, then removes... | def FindNextGoal():
global frontier, agent_position
for position in frontier:
if( NotKillThisWumpus( position ) ): frontier.remove( position )
frontier = sorted( frontier, key = functools.cmp_to_key(CustomSort) )
# Get the next goal
Goal = frontier[0]
# Go to that goal
path = Fin... |
def _connect_to_database(self, database_options):
"""
This method is used to connect to the database
Args :
database_options : dictionary containing database options
"""
self.database_options = database_options
self.database = Database(self.database_options)
... | This method initiates a scraping process by connecting to a database, scraping tweets, extracting unique users, and populating database tables (users, queries, tweets) with collected data. It also updates query records with the total number of scraped tweets. | def start_scraping(self, scraper_options = None, database_options = None, **kwargs):
"""
This method is used to start the scraper
step 1 : connect to the database
step 2 : scrape tweets
step 3 : create a list of unique users
step 4 : fill the users tables
step 5 :... |
def savePixel (img):
#SavePixelas01Array
horizontal, vertical = img.size
Y = np.zeros((vertical, horizontal ))
for i in range(vertical):
for j in range(horizontal):
coordinate = j, i
x = transformPixel(img.getpixel(coordinate))
Y[i, j] = x
return Y
def reS... | This function generates a line graph visualizing the error between pixel data from an image and a given array. It extracts pixel values, reshapes them, calculates errors against the array, then plots the error values against the array using matplotlib. | def lineGraphError (img, array):
#DrawError
Y = savePixel(img)
Y_reshape = reShape(Y)
s = errorList(Y_reshape, array)
plt.plot(array, s, lw=2)
plt.show() |
def savePixel (img):
#SavePixelas01Array
horizontal, vertical = img.size
Y = np.zeros((vertical, horizontal ))
for i in range(vertical):
for j in range(horizontal):
coordinate = j, i
x = transformPixel(img.getpixel(coordinate))
Y[i, j] = x
return Y
def reS... | The main task of the code is to transform an input image into a structured matrix by extracting pixel data, reshaping it, determining a width/path parameter, and generating a matrix based on these computations. The function processes the image's pixel information to produce a modified matrix representation for further ... | def finalMatrix (path):
#FinalFunction
img = Image.open(path)
Y = savePixel(img)
Y_reshape = reShape(Y)
d = determineWidthPath(Y_reshape, np.arange(12, 13, 0.05) )
X = makeMatrixWithWidthPath(Y_reshape, d)
return X |
def defineInputData(inputs, force=None, forceVar = None):
#check for duplicate variable names
if max(inputs['varName'].value_counts())>1:
raise ValueError("There are duplicate varNames")
# Create an input dataframe for number of years specified
var_dict=dict()
for row in range(len(inputs)):
... | The code performs a tornado sensitivity analysis on numerical input variables to assess their impact on a specified output variable. It calculates sensitivity metrics (varMin, p10, p50, p90, varMax) by simulating extreme and percentile values, computes the total effect size, filters variables by threshold, and visualiz... | def tornado(outputVar, inputs, maxEffect=0, saveFile=None, maxRound=None):
plt.rcParams.update({'font.size': 16})
#remove categorical variables for now
df_inputs = inputs[inputs['varType']=='numerical'].reset_index(drop=True)
# create a dataframe to house the sensitivity values
senseCols = ['varMin'... |
def _action_with_reward(self, func, action, index):
action_to_take = self._denormalized_action(action[index], index)
reward = 0.0
try:
func(action_to_take)
if not abs(action_to_take - self.last_action[index]) < self._action_discriminator[index]:
self.acti... | The main task of the code is to simulate a single step in an environment where an airplane performs an action (v, h, phi), updating its state, calculating a reward based on altitude constraints, runway proximity, and time limits, and returning the new state, reward, and termination status. The function checks if the ai... | def step(self, action):
"""
Perform a single step in the simulation
:param action: Action in format: v, h, phi
:return: Reward obtained from this step
"""
self.timesteps += 1
self.done = False
reward = -0.05 * self._sim_parameters.timestep
reward... |
def get_top_words(self, tweets,label):
# Return the x most frequent words from a set of tweets for a given label
label_words = self.get_tweet_text(tweets, label) # dictionary of {word: frequency} pairs from all the tweets
top_words = sorted(label_words, key=label_words.get, reverse=True)[:1000]
... | The main task of the code is to enhance a dataset by adding features derived from tweet text, including sentiment analysis, hashtag counts, and word frequency counts for misinformation/debunking terms. It processes each tweet to calculate polarity, subjectivity, and categorizes words into positive/negative sentiments u... | def get_extra_columns(self, data,train_data):
"""Process tweets to add new layers to data object """
analyzer = SentimentIntensityAnalyzer()
misinfo_words = self.get_top_words(train_data,'MISINFO')
debunk_words = self.get_top_words(train_data,'DEBUNK')
for row in data.itertuples():
... |
def edit_tweet_text(self, data):
STOPLIST = ['covid19','covid','coronavirus','https','@','?','-','&','will']
en_stopwords = stopwords.words('english')
for row in data.itertuples():
text = self.remove_punctuation(data.at[row.Index,'tweet_text'])
if self.has_url(text):
... | The main task of the code is to preprocess tweets by cleaning the tweet text, adding extra features from the training data, and incorporating top hashtags from the training data to enhance the dataset for further analysis or modeling. | def preprocess_tweets(self, data,train_data):
data = self.edit_tweet_text(data)
data = self.get_extra_columns(data,train_data)
data = self.add_top_hashtags(data,train_data)
return data |
def save(Data):
# noinspection PyGlobalUndefined
global Folder, Settings_Data
try:
File = open(Folder + '/' + Settings_Data['CurrentLevel'], 'x')
except FileExistsError:
File = open(Folder + '/' + Settings_Data['CurrentLevel'], 'r')
File.writelines(Data)
File.close()
def draw():
... | The code implements a pause menu in a Pygame application, displaying "Resume," "Change Level," and "Quit Editor" buttons. It handles mouse clicks and keyboard input (ESC) to toggle pause state, save game data, or exit. The menu updates the screen with black background, red buttons, and text, checking mouse coordinates ... | def pause():
# noinspection PyGlobalUndefined
global font, click, Running, Pause, screen, color, Textures, x, y, World_Data
while Pause:
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT: save(World_Data); return True
if event.type == pygame.... |
def level_select():
# noinspection PyGlobalUndefined
global Difficulty, DifficultyText, Level, click, Levels_List, screen, World_Data, Settings_Data, Folder
Level = False
Levels_List = []
for i in range(len(os.listdir('Levels'))):
if os.path.isdir('Levels/' + os.listdir('Levels')[i]):
... | The main task of the code is to create a level editor for a game, allowing users to interactively place/remove tiles, scroll through the level, and save changes. It initializes Pygame, loads assets, handles input for block editing, and includes a pause menu. The editor supports loading/saving levels, with real-time ren... | def run(Level=''):
# noinspection PyGlobalUndefined
global screen, font, DIRECTORY, click, clock, Running, Settings_Data, Folder, Pause, music, Track, Track1, Track2, Track3, color, Textures, Texture_Names, x, y, World_Data, scroll
Log.log('Opened Level Editor')
pygame.init()
mixer.init()
pygame... |
def process_texts(self, texts):
"""
Accepts a list of texts and calls tokenize_line() on each, with cache. Returns the list of results and maximum
length, in tokens, of all texts.
"""
token_count = 0
cache = {}
batch_chunks = []
for line in texts:
... | The function processes an array of texts through a transformer network to generate a tensor representation. It returns a (B, T, C) tensor, where B is the batch size, T is token count (multiple of 77), and C is embedding dimension (768/1024). It handles text chunks, applies embeddings, and combines results using torch.h... | def forward(self, texts):
"""
Accepts an array of texts; Passes texts through transformers network to create a tensor with numerical representation of those texts.
Returns a tensor with shape of (B, T, C), where B is length of the array; T is length, in tokens, of texts (including padding) - T w... |
def listFormat():
"""
fungsi untuk format
"""
alist = [datNum, getAccount(), getCaption(), getHastag(), getLikes(), getComment()]
return alist
def csvWriter(alist):
# fungsi untuk menulis ke file csv
# menggunakan separasi pipe(|)
global datNum
row = alist
with open('DataLevel1.c... | The main task of the code is to scrape Instagram user posts by extracting username, caption, hashtags, likes, and comments, then automatically save the data into a CSV file using Selenium and helper functions. It navigates through posts via pagination, handles exceptions for private accounts or missing posts, and write... | def loopPost(userName):
"""
ini adalah fungsi untuk mengloop post
setiap post yang di loop akan diambi username, caption, hastag, likes, dan comment
fungsi ini membutuhkan fungsi-fungsi lain, yaitu:
fungsi listFormat()
fungsi getLikes()
fungsi getCaption()
fungsi getComme... |
def reconnect():
global conn
if not conn.open:
conn = connect()
def close_connection():
if conn.open:
conn.close()
def editColumn(table:str, args:dict):
reconnect()
try:
with conn.cursor() as cursor:
# Create a new record
sql = f"ALTER TABLE {table} "
... | This function dynamically creates a database table named 'title' using columns derived from 'args', with optional safe creation to avoid duplicates. It constructs the SQL query by iterating through 'args' entries, appending each column definition. If an operational error occurs, it closes the connection and edits the c... | def createTable(title:str, args:dict, useSafeCreate:bool = None):
reconnect()
try:
with conn.cursor() as cursor:
# Create a new record
first_row:tuple = getFirstDictionaryRow(args)
createModeSqlQuerry = "IF NOT EXISTS" if useSafeCreate else "... |
def reconnect():
global conn
if not conn.open:
conn = connect()
def close_connection():
if conn.open:
conn.close()
def editColumn(table:str, args:dict):
reconnect()
try:
with conn.cursor() as cursor:
# Create a new record
sql = f"ALTER TABLE {table} "
... | The function dynamically adds multiple columns to a specified database table by generating an ALTER TABLE SQL statement from a dictionary of column definitions. It reconnects to the database, constructs the SQL query by iterating through the dictionary entries, executes the query to modify the table structure, and hand... | def addColumn(table:str, args:dict):
reconnect()
try:
with conn.cursor() as cursor:
# Create a new record
sql = f"ALTER TABLE {table} "
for i in range(args.__len__()):
row = getDictionaryRow(args, i + 1)
sql += f"ADD {row[0... |
def reconnect():
global conn
if not conn.open:
conn = connect()
def get_rows(table:str, columns:list, condition:str = None):
reconnect()
return_rows = None
try:
with conn.cursor() as cursor:
sql = f"SELECT "
###print(sql)
for column in columns:
... | The function inserts rows into a specified database table using provided arguments, checking for duplicates based on specified fields in 'dont_repeat'. If duplicates are found, it raises an error and returns False; otherwise, it executes the INSERT SQL statement and returns True upon successful insertion, ensuring prop... | def insert_rows(table: str, args:dict, dont_repeat:list = None) -> bool:
return_value = True
reconnect()
try:
with conn.cursor() as cursor:
if not dont_repeat == None:
conditionList = ""
for item in dont_repeat:
if item... |
def reconnect():
global conn
if not conn.open:
conn = connect()
def get_rows(table:str, columns:list, condition:str = None):
reconnect()
return_rows = None
try:
with conn.cursor() as cursor:
sql = f"SELECT "
###print(sql)
for column in columns:
... | This function updates rows in a specified database table using provided arguments and a condition. It checks for duplicate entries in specified columns (dont_repeat) to prevent repetition, constructs an SQL UPDATE query dynamically, executes it, and returns a boolean indicating success. If duplicates are detected, it r... | def edit_rows(table: str, args:dict, condition:str, dont_repeat:list = None) -> bool:
return_value = True
reconnect()
try:
with conn.cursor() as cursor:
if not dont_repeat == None:
conditionList = ""
for item in dont_repeat:
... |
def get_fan_network_id_set(settings_obj, FLAG_INCLUDE_BASE, FLAG_INCLUDE_NETWORK):
# limit update to either base_profile, and/or network at depth
fan_set = {}
if FLAG_INCLUDE_BASE:
fan_set = {settings_obj.base_profile_id}
if FLAG_INCLUDE_NETWORK:
depth = settings_obj.max_profile_dep... | This function updates user purchases from Bandcamp's API by syncing fan profiles with existing database records, using flags to control which purchase types (base, fan, new/old, preorder, no-digital) to process. It fetches purchase data, checks for existing entries, creates new purchases where needed, and manages abort... | def update_purchases_subtask(abortable_task, settings_obj, progress_recorder, seen,
FLAG_UPDATE_BASE_PURCHASES, FLAG_UPDATE_FAN_PURCHASES,
FLAG_UPDATE_OLD_PURCHASES, FLAG_UPDATE_NEW_PURCHASES,
FLAG_UPDATE_OLD_PREORDERS, FLAG_UPDATE_OLD_NODIGITAL):
... |
def get_fan_network_id_set(settings_obj, FLAG_INCLUDE_BASE, FLAG_INCLUDE_NETWORK):
# limit update to either base_profile, and/or network at depth
fan_set = {}
if FLAG_INCLUDE_BASE:
fan_set = {settings_obj.base_profile_id}
if FLAG_INCLUDE_NETWORK:
depth = settings_obj.max_profile_dep... | The function updates labelband and release data in a database by syncing with Bandcamp's API, using flags to control updates for base/fan labelbands, old/new discographies, and preorders/no-digital releases. It processes each fan's followed labelbands, creates/updates entries, filters releases based on flags, and adjus... | def update_labelbands_subtask(abortable_task, settings_obj, progress_recorder, seen_releases, new_following_labelband_ids,
FLAG_UPDATE_BASE_LABELBANDS, FLAG_UPDATE_FAN_LABELBANDS,
FLAG_UPDATE_OLD_DISCOGRAPHY, FLAG_UPDATE_NEW_DISCOGRAPHY,
... |
def update_following_fans_subtask(abortable_task, settings_obj, progress_recorder, seen,
new_following_fan_base_ids, new_following_fan_network_ids,
FLAG_UPDATE_NEW_FOLLOWING_FANS, FLAG_UPDATE_OLD_FOLLOWING_FANS):
url = "https://bandcamp.com/api/... | The main task of the code is to orchestrate multiple data update processes based on provided flags, including updating following fans, followers, purchases, labelbands, and release owners. It processes each flag conditionally, executes corresponding subtasks, logs progress, and bulk-creates or updates records in the da... | def main_update_task(self, flags):
# process flags
FLAG_UPDATE_FOLLOWING_FANS = flags.get("update_following_fans", False)
FLAG_UPDATE_FOLLOWERS = flags.get("update_followers", False)
FLAG_UPDATE_NEW_FOLLOWING_FANS = flags.get("update_profile_new", False)
FLAG_UPDATE_OLD_FOLLOWING_FANS = flags.ge... |
def get_vocab_frequency(list_of_strings):
wordSet = ' '.join(list_of_strings)
wordSet = list(set(tokenize(wordSet)))
list_of_dicts = [get_dict(string,wordSet) for string in list_of_strings]
return list_of_dicts
def get_idf(list_of_strings):
wordSet = ' '.join(list_of_strings)
wordSet = list(set(... | The main task of the code is to compute the TF-IDF matrix for a list of strings. It calculates term frequencies, inverse document frequencies, and combines them into a TF-IDF matrix using NumPy and Pandas, returning the result as a matrix. | def get_tfidf(list_of_strings):
tfs = get_vocab_frequency(list_of_strings)
idf = get_idf(list_of_strings)
tfidf = [calculate_tfidf(tf, idf) for tf in tfs]
tfidf = pd.DataFrame(tfidf).values
tfidf = np.asmatrix(tfidf)
return tfidf |
def forward_propagation(self, inputs): # forward propagation (calculating values)
# for hidden layers:
self.update_input(inputs)
for i in range(len(self.hidden)):
if i == 0:
layer = self.input_layer
else:
layer = self.hidden_layers[i - 1]
... | This function performs stochastic gradient descent (SGD) on a neural network by iterating over training data in mini-batches. It computes weight and bias gradients for each sample in a batch, accumulates them, averages the gradients across the batch, and updates model parameters via gradient descent. The process involv... | def stochastic_GD(self, batch_size):
L = len(self.hidden_layers) + 2
w_gradient = np.empty(shape=(L, self.hidden[1], self.input), dtype='float')
b_gradient = np.empty(shape=(L, self.hidden[1]), dtype='float')
for i in range(0,len(self.training_data),batch_size):
batch = self.... |
def forward_prop_vec(self, inputs, activation='sigmoid'):
self.update_input(inputs)
A = inputs
Z_cache = []
for i in range(1, self.L-1):
W = self.hidden_layers[i-1].weights
b = self.hidden_layers[i-1].biases
self.hidden_layers[i-1].z = np.dot(W,A) + b
... | This code trains a neural network using gradient descent with cross-entropy loss, performing forward and backward propagation over multiple epochs while optionally measuring accuracy on test data. It shuffles input data each epoch, tracks training costs, and returns cost history and accuracy metrics. | def train(self, X, Y, epochs = 2000, learning_rate = 1.2, measure_accuracy = False, X_test = [], Y_test = [], activation='sigmoid'):
costs = []
accuracies = {"train" : [], "test" : []}
for i in range(epochs):
X,Y = sku.shuffle(X.T,Y.T)
X = X.T
Y = Y.T
... |
def ReadExcelFile(self,filename,sheetname):
dataframe = pd.read_excel(io=filename, sheet_name=sheetname)
uncorrelated = self.RemoveCorrelated(dataframe)
# nrow = uncorrelated.values.shape[0]
# colheader = list(uncorrelated.columns.values)
# PID = rawdata[:, 0]
ncol = uncorrel... | The main task of the code is to evaluate multiple machine learning models (AdaBoost, Knn, Nb, etc.) on datasets from a given path using cross-validation and jackknife methods. It computes performance metrics (AUC, ACC, Recall, F1, etc.) across multiple runs, stores their mean and variance in structured arrays, and expo... | def ApplyAllData(self,path):
onlyfiles = glob.glob(path)
file_count = len(onlyfiles)
cross_totalAUC = np.zeros((self.runtimes,file_count,8))
cross_totalACC = np.zeros((self.runtimes,file_count,8))
cross_totalRecall = np.zeros((self.runtimes,file_count,8))
cross_totalpreci... |
def ReadExcelFile(self,filename,sheetname):
dataframe = pd.read_excel(io=filename, sheet_name=sheetname)
uncorrelated = self.RemoveCorrelated(dataframe)
# nrow = uncorrelated.values.shape[0]
# colheader = list(uncorrelated.columns.values)
# PID = rawdata[:, 0]
ncol = uncorrel... | The main task of the code is to classify features from multiple datasets using various machine learning models (Ada, KNN, NB, DT, LR, SVM, RF, MLP). It evaluates model performance using cross-validation and Jackknife methods, calculating metrics like ACC, AUC, Recall, Precision, F1, and Matthew's Correlation. Results a... | def DoClassifyAllFeature(self,path):
onlyfiles = glob.glob(path)
cross_totalAUC = pd.DataFrame(
{'Features': [''], 'Ada': [0], 'Knn': [0], 'NB': [0], 'DT': [0], 'LR': [0], 'SVM': [0], 'RF': [0],
'MLP': [0]})
cross_totalACC = pd.DataFrame(
{'Features': [''], '... |
def train(args , dic):
#device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
#device = torch.device('cpu')
#print(device)
dic_word = dic
dic_div = torch.load(args.div_dic)
dic_ch = torch.load(args.ch_dic)
batch_size = args.batch_size
model = EM_BiLSTM_CRF(len(dic_word),len(dic_div),len(dic... | The code's main task is to process command-line arguments, load a pre-trained word dictionary, and execute either training, sentence testing, or general testing based on the specified subcommand. It parses input parameters, validates the subcommand, and delegates tasks to corresponding functions (`train`, `test_sentenc... | def main():
args = Options().parse()
print(args)
if args.subcommand is None :
raise ValueError("ERROR:no detail info ")
dic_word = torch.load(args.word_dic)
if args.subcommand == 'train':
train(args , dic_word )
elif args.subcommand =='sentence':
test_sentence(args , dic_word)
elif args.subcommand ==... |
def drawShips():
alphaSurface = DISPLAYSURF.convert_alpha()
for row in range(10):
for col in range(10):
if player.board[row][col] > 0:
pygame.draw.rect(alphaSurface, GREEN, (40 + row * 60, 40 + col * 60, 60, 60))
DISPLAYSURF.blit(alphaSurface, (0,0))
def getBoxAtMousePos(... | This code initializes event handling in a Pygame game, tracking mouse position and clicks, toggling ship direction with the spacebar, and checking for interactions with grid boxes. It updates game state based on user inputs and triggers events when a box is selected. | def initialize():
global mousex
global mousey
# Event Handling
mouseClicked = False
drawShips()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
... |
def isEmpty(self):
return len(self.elements) == 0
def swap(self, val, other):
# set values position in the list to other and vice versa
self.elements[val], self.elements[other] = self.elements[other], self.elements[val]
# set vals new position to the index it is now at
self.eleme... | This code removes the minimum element from a priority queue (APQ). It swaps the first (min) element with the last, pops the last element, and restores the heap structure by bubbling down the new first element. It returns the key-value pair of the removed element, or an error if the APQ is empty. | def remove_min(self):
# if empty return Error
if self.isEmpty():
return "APQ is empty"
else:
# swap first cell with the last cell
self.swap(0, self.length() - 1)
# pop that element
elt = self.elements.pop(self.length() - 1)
... |
def parent(self, val):
return (val - 1) // 2
def bubbleup(self, val):
# create parent of val
parent = self.parent(val)
# if val index is less than parent index and greater than 0
if self.elements[val] < self.elements[parent] and val > 0:
# swap val and parent
... | This function updates an element's key in a tree-like structure and adjusts its position to maintain heap properties. It first sets the new key, then checks if the element needs to bubble up (if smaller than its parent) or bubble down (otherwise), ensuring correct hierarchical ordering. | def update_key(self, elt, newkey):
# get the index of the new element
i = elt.index
# set elements key to the newkey
elt.key = newkey
# vals index in tree is less than its parent
if i > 0 and self.elements[i] < self.elements[self.parent(i)]:
# bubble up val
... |
def length(self):
return len(self.elements)
def swap(self, val, other):
# set values position in the list to other and vice versa
self.elements[val], self.elements[other] = self.elements[other], self.elements[val]
# set vals new position to the index it is now at
self.elements[va... | This method removes an element from a data structure, swapping it to the end if not last, then popping it. It maintains the structure's integrity by bubbling the element up or down based on its value relative to its parent, ensuring the heap property is preserved. Finally, it returns the element's key and value. | def remove(self, element):
# get elements index
i = element.index
# if the element is the last one in the list
if i == self.length() - 1:
# pop that element
self.elements.pop()
else:
# swap the element at this index to the last position
... |
def distanceMinkowski(p1, p2):
distance = pow(
(pow(abs(p2[0] - p1[0]), 3)
+ pow(abs(p2[1] - p1[1]), 3)
+ pow(abs(p2[2] - p1[2]), 3)), 1/3
)
return distance
def getTabDistanceAllFingers(skeleton):
tab_distance_fingers = []
# distance base, hand point for each hand point
... | This function identifies the label of the most similar skeleton by comparing the input skeleton's finger distances and directional attributes (reverse, bent fingers) with stored skeletons, applying penalties for mismatches, and returning the label with the lowest similarity score. | def getLabelClosestSkeleton(skeleton, dictionary_skeleton, dictionary_reverse, dictionary_bent_fingers):
labels_skeleton = list(dictionary_skeleton.keys())
distance_normal_skeleton = distanceMinkowski(skeleton[0], skeleton[17])
tab_distance_skeleton = getTabDistanceAllFingers(skeleton)
bool_reverse, b... |
def initialize_logger(self):
logging.basicConfig()
self.logger = logging.getLogger()
self.logger.setLevel(self.conf.get('log.level', DEFAULT_LOG_LEVEL))
def configure(self):
# -- look in these folders ...
for folder in self.configuration_folders:
if self.mode == 'debu... | This code initializes a configuration and command dispatcher, setting up logging, loading configurations, and registering command actions (methods starting with 'do_') for processing based on the run mode. It prepares the application to handle commands by parsing attributes, updating defaults, and triggering the run me... | def __init__(self, name=None, run_mode="cli", comargs=['help'], defaults=None, **kwargs):
self.run_mode = run_mode
self.comargs = comargs
self.actions = []
self.dispatches = []
self._name = name
if self.mode == 'debug':
print('\n(i) Configuration Setup')
... |
def addTab(self, title = "untitled", concat_tab_titles = True, switch_to_new = True):
if self.pos_x + len(title) + 3 > self.window.getmaxyx()[1]:
return False
if concat_tab_titles:
self.tab_titles += [title]
self.tabs += [MegaTab(self.maxy, self.maxx, self.window, self.in... | The code handles closing a tab in a GUI application. If only one tab remains, it adds a new "untitled" tab and recursively calls closeTab to ensure at least one tab exists. Otherwise, it deletes the active tab from the list, updates the UI with setupTabs(), activates the next tab, and redraws the interface. | def closeTab(self):
if len(self.tab_titles) == 1:
self.addTab("untitled", True, False)
self.closeTab()
else:
del self.tab_titles[self.active_tab:self.active_tab+1]
self.setupTabs()
self.tabs[self.active_tab].activate()
self.draw() |
def response(sentence, firstName, userID='', debug=False):
# dic to store user information
userDict = {"userName": [], "userResponse": [], "botResponses": []}
# store the result
results = classify(sentence)
# for debugging purposes
if debug: print(results)
if results:
# check if t... | The code creates an interactive chatbot that prompts users for input, allows switching between users, collects conversation data, and stores it in a JSON structure. It runs in a loop until the user types "quit," handling input with color-coded prompts and appending user interactions to a dictionary, which is later clea... | def prompt_user():
print(Fore.YELLOW + 'Type "quit" to exit.', Style.RESET_ALL)
print(Fore.YELLOW + "type 'switch to change users", Style.RESET_ALL)
print(Fore.LIGHTYELLOW_EX + "This is a chatbot that can talk to you about American football.",
Style.RESET_ALL)
print(Fore.GREEN + "ChatBot:" + S... |
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum()
def hard_label_img_search(name_ori,ntar_name, model, tf, blend_img_path,target_list, opt=False):
"""search hard laabel image"""
alpha_min = 0.
alpha_max = 1.
itr = 0... | The code generates hard labels by blending target and non-target images using a pre-trained model. It computes scores, labels, and blending parameters (alpha) for each image pair, aggregates statistics, and returns processed image data. The function evaluates model predictions on blended images, collects label distribu... | def hard_label_gen(tar_sub,nontar_mix, model, tf, blend_img_path,target_list=[895]):
model = model.eval()
with torch.no_grad():
img_data = []
score_list = []
lab_list = []
alpha_list = []
cls_set = set()
# Go through the data set and compute the perturbation incre... |
def data_input_init(xi):
mean = [ 0.485, 0.456, 0.406 ]
std = [ 0.229, 0.224, 0.225 ]
tf = transforms.Compose([
transforms.Resize(osize),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean = mean,
std = std)])
v = (torch.rand(1,3,22... | The function `universal_perturbation_data_dependant` aims to generate a **universal perturbation** that, when added to images, can fool a target neural network into misclassifying them. It leverages a blend of target and non-target images, iteratively optimizing the perturbation to achieve a specified fooling rate (con... | def universal_perturbation_data_dependant(data_list, ntar_list, model, blend_img_path, encoder,encoder1, xi=10, delta=0.2, max_iter_uni = 10, p=np.inf, num_classes=10, overshoot=0.02, max_iter_df=10,init_batch_size = 1,t_p = 0.2):
"""
:data_list: list of image names
:model: the target network
:param xi:... |
def get_parts_perm(device, parts=[]):
"""
Input: everyday thing, (optional) list of parts
Output: permutation of list of parts
"""
macaw_getMM_logfile.write("Everything processed: " + device + "\n")
if not parts:
qns_parts = "What are the parts of a/an {}?".format(device)
ans_par... | The function retrieves and processes Macaw's assessments on specified device parts, returning confidence lists for triplet statements (including those Macaw believes true) and negative answers. It first obtains permissions, queries Macaw's judgments, filters believed truths, and compiles results for analysis. | def run_query_macaw_everyday_thing(device, parts):
# get parts
perm = get_parts_perm(device, parts)
# get macaw judgment
triplet_ans_conf_lst, neg_ans_conf_lst = query_macaw_statements(device, perm)
triplet_ans_conf_lst_true = get_statements_that_macaw_believesT(triplet_ans_conf_lst)
return trip... |
def query_servo(self, is_servo_up: bool):
while not self.check_state():
pass
self.state = False
self.serial.write(bytes(bytearray([2, is_servo_up])))
self.is_servo_up = is_servo_up
def goto_square(self, square: str):
(x, y) = self.calculate_square_pos(square)
... | This function controls a robotic arm to move a piece from a starting position to a target position on a grid. It disables servos, navigates to the starting coordinates, then incrementally adjusts the x and y axes by one step at a time toward the target, updating positions until reaching the destination. Finally, it mov... | def move_piece(self, from_square: str, to_square: str):
self.query_servo(False)
self.goto_square(from_square)
self.query_servo(True)
sleep(3)
x = from_square[0]
y = from_square[1]
self.goto_line(x)
self.goto_line(y)
while ord(x) != ord(to_square[... |
def getUsefulData(exif):
return [exif["Latitude"], exif["Longitude"], exif["RelativeAltitude"], exif["GimbalRollDegree"], exif["GimbalPitchDegree"], exif["GimbalYawDegree"]]
def exiftometers(exif1, exif2):
latlon1 = [exif1["Latitude"], exif1["Longitude"]]
latlon2 = [exif2["Latitude"], exif2["Longitude"]]
... | The function computes the relative transformation between two coordinate frames (anchor and query) by calculating translation and rotation differences. It derives translation (p_x, p_y, p_z) from EXIF data and elevation differences, computes rotation matrices for both frames, transforms the Cartesian translation into t... | def RelativeTransformNew(anchor, query):
anchor_data = getUsefulData(anchor)
query_data = getUsefulData(query)
p_x, p_y = exiftometers(anchor, query)
p_z = query_data[2] - anchor_data[2]
R_A = getRotationMatrixforFrame(anchor_data[3:])
R_B = getRotationMatrixforFrame(query_data[3:])
t_Cart ... |
def getSubkeys(key: int) -> Dict[str, List[str]]:
keys = {"C":[], "D":[] }
key = permute(key, PC1)
key = bin(key)[2:]
key = padBits(key, 56)
# Split into upper and lower halves
upper = key[0:28]
lower = key[28:]
# Shift and add to corresponding list
for i in range(16):
uppe... | The main task of the code is to generate 16 subkeys from an input key using a permutation process. It concatenates corresponding parts of subkeys "C" and "D", converts them to integers, applies the PC2 permutation (reducing to 56 bits), pads the result to 48 bits, and stores each subkey in a list. This is typical in cr... | def getKeys(key: int) -> Dict:
subkeys = getSubkeys(key)
keys = []
for i in range(16):
#concat upper and lower parts
key_concat = subkeys["C"][i] + subkeys["D"][i]
#change to integer for permute function
key_concat_int = int(key_concat, 2)
#permute using PC2
k... |
def getKeys(k):
p = getPrime(k)
g = getGenerator(p)
b = getSecretExponent(p)
a = getPublicValue(g, b, p)
return p, g, b, a
def encryptMessage(message: str, a: int, g: int, p: int):
m = message.encode()
m = int.from_bytes(m, byteorder='big')
return encrypt(m, a, g, p)
def decryptMess... | The code tests the correctness of encryption and decryption functions by generating cryptographic keys (p, g, a, b) with k=1024, encrypting a fixed message "ABCD" 100 times, and verifying each decrypted result matches the original message. If any decryption fails, it prints "Error" and stops. | def test():
message = "ABCD"
k = 1024
p, g, b, a = getKeys(k)
for i in range(100):
c = encryptMessage(message, a, g, p)
if(message != decryptMessage(c, b)):
print("Error")
break |
def permute(data: int, table:List[int], pad=64) -> int:
out = []
bits = bin(data)[2:]
bits = padBits(bits, pad)
for i in range(len(table)):
out.append(bits[table[i]-1])
outBits = "".join(out)
return(int(outBits, 2))
def padBits(bits, l=64):
while(len(bits) < l):
bits = "0" + b... | This function encrypts a 64-bit block using DES-like operations: it applies an initial permutation, splits the block into two 32-bit halves, processes them through a key-dependent XOR chain, and applies the inverse permutation to produce ciphertext. The keys dictionary provides round-specific values for the encryption ... | def encryptBlock(block: int, keys:Dict) -> int:
#permute using Initial Permutation table
ip = permute(block, IP)
ip = padBits(bin(ip)[2:], 64)
#get upper and lower halves
upper = ip[:32]
lower = ip[32:]
#do main part of DES
ciphertext = xorChain(upper, lower, keys)
#undo initial p... |
def permute(data: int, table:List[int], pad=64) -> int:
out = []
bits = bin(data)[2:]
bits = padBits(bits, pad)
for i in range(len(table)):
out.append(bits[table[i]-1])
outBits = "".join(out)
return(int(outBits, 2))
def padBits(bits, l=64):
while(len(bits) < l):
bits = "0" + b... | The function decrypts a DES block using the provided keys by performing an initial permutation, splitting the block into halves, applying a decryption XOR chain with the keys, and reversing the initial permutation to produce the decrypted result. | def decryptBlock(block:int, keys:Dict) -> int:
# perform Initial Permutation
ip = permute(block, IP)
ip = padBits(bin(ip)[2:], 64)
# Get halves
upper = ip[:32]
lower = ip[32:]
# Do main DES
decrypted = xorChain(upper, lower, keys, True)
#undo initial permutation
return permute... |
def getKeys(key: int) -> Dict:
subkeys = getSubkeys(key)
keys = []
for i in range(16):
#concat upper and lower parts
key_concat = subkeys["C"][i] + subkeys["D"][i]
#change to integer for permute function
key_concat_int = int(key_concat, 2)
#permute using PC2
k... | The code encrypts a message using a key by converting the message into 64-bit integer blocks, generating encryption keys from the input key, and encrypting each block individually. The encrypted blocks are collected into a list and returned as ciphertext. | def encrypt(message: str, key:str):
# get keys first
keys = getKeys(getIntKey(key))
#convert message into 64-bit integers
blocks = messageToBlocks(message)
ciphertexts = []
for block in blocks:
#encrypt each block
ciphertexts.append(encryptBlock(block, keys))
return... |
def getKeys(key: int) -> Dict:
subkeys = getSubkeys(key)
keys = []
for i in range(16):
#concat upper and lower parts
key_concat = subkeys["C"][i] + subkeys["D"][i]
#change to integer for permute function
key_concat_int = int(key_concat, 2)
#permute using PC2
k... | The code decrypts a message using a provided key by processing each block of encrypted data, converting them into plaintext. It checks if the decrypted blocks form valid ASCII characters; if not, it returns an error message indicating potential key issues or invalid input. | def decrypt(blocks:List[int], key: str) -> str:
#Get keys
keys = getKeys(getIntKey(key))
outBlocks = []
for block in blocks:
# decrypt each block
outBlocks.append(decryptBlock(int(block), keys))
#convert to plaintext message
message = blocksToMessage(outBlocks)
if(messa... |
def _validate_params(params):
for req_param in REQUIRED_PARAMS:
param_name = req_param['name']
if param_name not in params:
raise RuntimeError("Missing required param '{}'.".format(param_name))
param_value = params[param_name]
for is_valid, error_msg in req_param['valid... | This code initializes a Fat Tree network topology by setting parameters, constructing the network hierarchy, and assigning hosts to root and leaf levels. It validates input parameters, configures levels and host distribution, and invokes methods to build the topology structure and allocate hosts to specific network lay... | def __init__(self, *args, **params):
super(FatTreeTopo, self).__init__(args, params)
_validate_params(params)
self.levels = params['levels']
self.hosts_on_root = 3
self.hosts_per_leaf = 1
self.root_lvl = []
self.leaf_lvl = []
self._build()
self._as... |
def __trackBlobs(self) -> dict:
if len(self.labelBlobs):
self.newLabelBlobs = {} # Make a dict for the next blobs
self.unusedLabels = self.labelBlobs.copy() # Copy labeled blobs
# Loop all previous blobs
for j, prevBlob in enumerate(self.labelBlobs):
... | The code processes input blobs and media by tracking blobs, resetting the tracker, and generating labels. It assigns blobs, analyzes them, resets tracking parameters, and returns labeled output based on the media. | def run(self, blobs, media):
self.blobs = blobs # Set the current frames blobs
self.__trackBlobs() # Analyze the blobs
self.__resetTracker(media) # Reset tracking
return self.__writeLabel(media) |
def process_all(dir_path):
# list to store files
res = []
# Iterate directory
for path in os.listdir(dir_path):
# check if current path is a file
if os.path.isfile(os.path.join(dir_path, path)):
if 'log.xlsx' in path:
res.append(os.path.join(dir_path, path))... | The main task of the code is to process log files in a specified directory based on command-line arguments. It handles three primary operations: processing all logs (`all`), displaying reports (`show`), and generating plots (`plot`). If a file path is provided, it analyzes that specific file. The code acts as a control... | def main():
# folder path
dir_path = 'save_job_log/4627_job_log'
# 'save_job_log/1352_job_log' 'save_job_log/4627_job_log' 'save_job_log/2375_job_log'
# 'save_job_log/2024_job_log' 'save_job_log/5590_job_log' # not good
cmdargs = sys.argv
if(len(cmdargs) < 2): exit("Please input file (with pa... |
def normed_to_average(self, data=None):
"""
First step in the normalisation process is normalisation to the average of each column.
This process includes averaging the data from the different cell lines (not completly sure why
but this is how they have done it).
I would also lik... | This function normalizes protein data by dividing each antibody's values by Coomassie blue staining measurements, accounting for total protein loaded onto gels. It uses pre-normalized data (mean/median) if none is provided, then performs antibody-specific division and concatenates results into a DataFrame. | def normalised_to_coomassie_blue(self, data=None, ):
"""
Second step in normalisation process is to normalise for coomassie blue staining. This stain
provides a metric for the total amount of protein loaded onto a gel.
"""
if data is None:
if self.mean_or_median == 'm... |
def check_nonce(nonce):
# if you can't reuse the nonce, surely you can't explot this oracle!
if(nonce in used_nonces):
print("Sorry, a number used once can't be used twice!")
exit(0)
used_nonces.add(nonce)
def incr(counter):
temp = bytes_to_long(counter)
return long_to_bytes(temp + 1... | The code implements a block cipher encryption using AES-ECB with a custom counter mechanism, combining AES-CTR (for confidentiality) and GHASH (for authentication). It encrypts plaintext in 16-byte blocks, generates a keystream via nonce increments, XORs it with the plaintext, and computes an authentication tag using G... | def encrypt(nonce, pt):
pt = bytes.fromhex(pt)
assert(len(pt) % 16 == 0)
numBlocks = len(pt) // AES_BLOCK_SIZE
if(numBlocks > 3):
print("Sorry, we just don't have the resources to encrypt a message that long!")
exit(0)
nonce = bytes.fromhex(nonce)
assert(len(nonce) == 16)
ch... |
def check_nonce(nonce):
# if you can't reuse the nonce, surely you can't explot this oracle!
if(nonce in used_nonces):
print("Sorry, a number used once can't be used twice!")
exit(0)
used_nonces.add(nonce)
def incr(counter):
temp = bytes_to_long(counter)
return long_to_bytes(temp + 1... | The code decrypts a ciphertext using AES with a nonce, generates an authentication tag via GHASH, and verifies the tag against the provided input. It decrypts data block-by-block using XOR with precomputed encrypted nonce blocks, ensuring authenticity before outputting a flag if valid. | def decrypt(nonce, ct, tag):
ct = bytes.fromhex(ct)
assert(len(ct) % 16 == 0)
numBlocks = len(ct) // AES_BLOCK_SIZE
nonce = bytes.fromhex(nonce)
assert(len(nonce) == 16)
check_nonce(nonce)
tag = bytes.fromhex(tag)
assert(len(tag) == 16)
cipher = AES.new(key, AES.MODE_ECB)
hkey... |
def plot_grid_on_transformed_image(image):
# Define the corners of the image as a 4x2 NumPy array
corners = np.array([[0,0],
[image.shape[0], 0],
[0, image.shape[1]],
[image.shape[0], image.shape[1]]])
# Order the corners of the image in [top-left, top-right, bottom-right, bottom-left]
corne... | The code performs perspective correction on a chessboard image using a pre-trained corner detection model, then detects chess pieces with YOLOv5 on the transformed image. It preprocesses the image, applies perspective transformation to align the board, runs object detection, applies non-max suppression, maps detected b... | def main():
# Load the trained model
model = tf.keras.models.load_model('D:/ComputerVision-Final-Project/corner-detection-models/chessboard_corners_model1010.h5')
# Load the chessboard image
chessboard_image = cv2.imread('D:/ComputerVision-Final-Project/corner-detection-dataset/test/a3863d0be6002c21b20ac88817b2c5... |
def _check_events(self):
# Watch for keyboard and mouse events.
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.KEY... | The code runs the game loop, processes events, updates game elements (ship, bullets, scouts, battleships) if the game is active, and continuously renders the screen to maintain gameplay and visuals. | def run_game(self):
"""Start the main loop for the game."""
while True:
self._check_events()
if self.stats.game_active:
self.ship.update()
self._update_bullets()
self._update_scouts()
self._update_battleships()
... |
def __get_accuracy(self):
correct = 0
for i, hit in enumerate(self.y_class):
if (hit == 1 and self.__is_inside(i, self.X)):
correct = correct + 1
elif(hit == 0 and not self.__is_inside(i, self.X)):
correct = correct + 1
acc... | This method adds a new threshold to the model, updates accuracy metrics (train, test, and overall), calculates the improvement in accuracy from the new threshold, and updates related attributes like threshold indexes and correlated features. | def add_threshold(self, threshold):
temp_accuracy = self.accuracy
self.thresholds.append(threshold)
self.accuracy = self.__get_accuracy()
self.train_accuracy = self.__get_train_accuracy()
self.test_accuracy = self.__get_test_accuracy()
added_accuracy = s... |
def add_threshold(self, threshold):
temp_accuracy = self.accuracy
self.thresholds.append(threshold)
self.accuracy = self.__get_accuracy()
self.train_accuracy = self.__get_train_accuracy()
self.test_accuracy = self.__get_test_accuracy()
added_accuracy = s... | This code initializes a classifier by splitting data into training and test sets, creating binary classification labels based on a threshold (y_cut), and setting up metrics for accuracy evaluation. It also prepares threshold indexes and correlated features for further analysis. | def __init__(self, thresholds, X, y, y_cut, ts=[], vs=[], low_is_good=False):
self.thresholds = []
self.X = X
self.y = y
self.y_cut = y_cut
if(low_is_good):
self.y_class = np.array([0 if i > y_cut else 1 for i in y])
else:
self.y_class = n... |
def sum_over_pixel_range(self):
self.lineout_y = np.sum(self.create_sub_array_px_range(), axis=0)
return self.lineout_y
def set_to_zero_offest(self):
self.lineout_y[::] = self.lineout_y[::] - np.amin(self.lineout_y)
return self.lineout_y
def plot_fit_function(self):
# IMPORTANT s... | The code fits a Gaussian model to a lineout dataset, extracts parameters (sigma, amplitude, center), and returns them. It processes data with preprocessing steps, uses a GaussianModel to guess and refine parameters, stores results in instance variables, and plots the fit. | def fit_gaussian(self):
self.sum_over_pixel_range()
self.set_to_zero_offest()
mod = GaussianModel()
pars = mod.guess(self.lineout_y, x=self.lineout_x)
out = mod.fit(self.lineout_y, pars, x=self.lineout_x)
self.sigma_temp = out.params['sigma'].value
self.amplitude_... |
def energy_range(self):
# rint(self.harmonic_selected)
previous_harmonic = self.lambda_fundamental / (self.harmonic_selected - 0.2)
next_harmonic = self.lambda_fundamental / (self.harmonic_selected + 0.2)
# rint(previous_harmonic, next_harmonic)
self.border_up = np.int(self.nm_in... | This function iterates over harmonic numbers, fits Gaussian profiles to spectral data for each harmonic, records divergence values, energy sums, and energy range parameters, then cleans the result array by removing empty entries. It returns a structured array containing harmonic numbers, divergence, intensity sums, and... | def batch_over_N(self):
for x in range(self.harmonic_selected, self.maximum_harmonic):
self.gaussian_result[x, 0] = x
self.harmonic_selected = x
self.border_up, self.border_down = self.energy_range()
self.fit_gaussian()
# self.plot_fit_function()
... |
def adjust(poly1, poly2):
if len(poly1) != len(poly2):
if len(poly1) > len(poly2):
poly2 = extend(poly2, len(poly1)-len(poly2))
elif len(poly1) < len(poly2):
poly1 = extend(poly1, len(poly2)-len(poly1))
return poly1, poly2
def shift(poly, number):
result = [0]*number
... | The code implements a divide-and-conquer algorithm for polynomial multiplication, specifically a recursive variant of the Karatsuba algorithm. It multiplies two polynomials represented as lists of coefficients by recursively splitting them into halves, computing intermediate products, and combining results through addi... | def conquer(polyA, polyB):
"""
:argument polyA: List
:argument polyB: List
:returns: List
"""
polyA, polyB = adjust(polyA, polyB)
# Base Case
if len(polyA) == 1:
return [polyA[0]*polyB[0]]
# Recursive Case
else:
# Make Polynomials even lengths
if len(pol... |
def processingFunc(self):
"""
-Input:
1: virusRefGenName: virus refernce genome file name, type: string
2: hostRefGenName: host refernce geneome file name, type: string
3: hostRefGenCount: number of host genome to use, type: integer
4: minReadLen: size o... | The code performs sequence alignment using BLAST, processes simulation metadata, and writes matched read results to CSV and text files. It creates a directory for outputs, manages threading for parallel processing, and logs simulation parameters like virus/host ratios, error rates, and fragment counts. The function als... | def sequenceAlignmentFunc(self):
""" write simulation metadata and matched read from blast seach into file"""
start_time= time.time()
global COUNT
processingFuncResult = self.processingFunc()
resultDirectory= f"{self.virusSymbol}_{str(self.threadsNumber)}Threads_{self.errorStat... |
def revert(revert_type):
name = 'revert'
if revert_type == 'rv':
wall_type = platform.system()
if wall_type == 'Windows':
# windows_breacher(os.environ['APPDATA']+'\\Microsoft\\Windows\\Themes\\CachedFiles')
windows_breacher(os.environ['APPDATA']+'\\Microsoft\\Windows\\Th... | The code defines a `retract` function that performs OS-specific actions based on the `retract_type` parameter. On Windows, it triggers `revert()` for 'rr' or downloads an image via `windows_breacher()` for 'r'. Linux/Darwin systems return "unavailable," while other OSes trigger "input_error." Exceptions are logged usin... | def retract(retract_type):
name = 'retract'
try:
wall_type = platform.system()
if wall_type == 'Windows':
if retract_type == 'rr':
revert(retract_type)
# windows_breacher('C://Users/kmcho/OneDrive/Pictures/backgrounds/python.png')
elif retr... |
def saveOrigin():
if not dejavu.is_breached:
origin = os.path.normpath('C://Users/kmcho/AppData/Roaming/Microsoft/Windows/Themes/TranscodedWallpaper')
target = os.path.normpath('C://Users/kmcho/AppData/Roaming/Microsoft/Windows/Themes/TranscodedWallpaper.jpg')
shutil.copyfile(origin, target)... | The main task of the code is to handle user input for system state management, including triggering a breach, reverting changes, aborting actions, or initiating periodic breaches, while updating and checking the 'dejavu' status flags (is_dejavu, is_breached) and executing corresponding functions like set_wallpaper(), r... | def breach_wall():
print("in breach_wall: %s, %s" % (dejavu.is_dejavu, dejavu.is_breached))
name = 'breach_wall'
saveOrigin()
startup = input("start \n")
if startup == 'k':
set_wallpaper()
set_dejavu(False, True)
elif startup == 'rv' or startup == 'rr':
if not dejavu.is_... |
def initialize_with_zeros(dim):
w=np.zeros((dim,1))
b=0
return w, b
def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost=False):
"""
This function optimizes w and b by running a gradient descent algorithm
w -- weights, a numpy array of size (num_px * num_px * 3, 1)
b -- bia... | The code implements a logistic regression model to classify data. It initializes parameters (weights and bias), performs gradient descent to optimize these parameters using training data, and evaluates model performance on both training and test sets. The function returns a dictionary containing optimized parameters, t... | def model(X_train, Y_train, X_test, Y_test, num_iterations=2000, learning_rate=0.5, print_cost=False):
"""
Builds the logistic regression model by calling the function you've implemented previously
X_train -- training set represented by a numpy array of shape (num_px * num_px * 3, m_train)
Y_train -- ... |
def check_purity(data):
label_column = data[:, -1]
unique_classes = np.unique(label_column)
if len(unique_classes) == 1:
return True
return False
def classify_data(data):
label_column = data[:, -1]
unique_class, count_unique_class = np.unique(label_column, return_counts=True)
index =... | This function recursively constructs a decision tree by splitting data based on the best feature-value pair, applying stopping conditions (purity, sample size, depth), and building a nested dictionary structure representing the tree. It classifies data at terminal nodes, tracks depth, and combines sub-trees for splits,... | def decision_tree_algorithm(df, min_samples, max_depth, counter=0):
if counter == 0:
global column_headers
column_headers = df.columns
data = df.values
else:
data = df
if check_purity(data) or len(data) < min_samples or counter == max_depth:
classification = classify_... |
def train_test_split(df, test_size):
if isinstance(test_size, float):
test_size = round(test_size * len(df))
indices = df.index.tolist()
test_indices = random.sample(population=indices, k=test_size)
test_df = df.loc[test_indices]
train_df = df.drop(test_indices)
return train_df, test_df
... | This code determines the optimal decision tree depth and split criterion (Gini/Information Gain) by evaluating 10 random samples. It iteratively trains trees, calculates test accuracy, tracks maximum accuracy, and returns the best-performing tree along with its accuracy and depth. | def calculate_max_accuracy(df, min_samples=2, max_depth=10):
global impurity_analysis_choice
impurity_analysis_choice = input("Enter 1 to use Gini Impurity for Best Split, "
"2 to use Information Gain for Best Split: ")
max_accuracy = 0
max_accuracy_depth = 0
tr... |
def get_tx_success_probabilities(self, W_tx_Q1, W_tx_Q2, power1, successive_decoding):
# Calculate probabilities to have a successful reception at the destinations and the
# potential violation of the security constraint.
Pr_suc_rx_Q1_to_D1 = .0
Pr_suc_rx_Q1_to_D2 = .0
Pr_suc_r... | The code simulates a transmission process in a network, determining the success of packet transmissions from queues Q1 and Q2 based on calculated probabilities. It updates system states (e.g., backlog, throughput) and computes rewards for a reinforcement learning agent. The method handles packet arrivals, departure eve... | def step(self, power1):
W_tx_Q1 = self.scheduled_transmissions[0]
W_tx_Q2 = self.scheduled_transmissions[1]
Pr_suc_rx_Q1_to_D1, Pr_suc_rx_Q1_to_D2, Pr_suc_rx_Q2_to_D2 = self.get_tx_success_probabilities(W_tx_Q1, W_tx_Q2, power1, self.successive_decoding)
# Realization of the transmissi... |
def take_turn(p1, dragon):
global choice
#player casts selected spell
p1.spells[choice](dragon)
if check_life(p1,dragon): return
draw_turn_effects(p1, dragon)
#Boss turn
p1.turn_start(dragon)
if check_life(p1,dragon): return
draw_turn_effects(p1, dragon)
dragon.attack(p1)
if ... | The code implements a game loop where a Wizard player battles a Boss (dragon), handling spell selection via keyboard input, processing game events (boss death, player death, mana depletion), updating the display, and tracking the number of dragons slain until the game ends with a "Game Over" message or player quit. | def run():
p1 = player.Wizard()
dragon = boss.Boss()
p1.turn_start(dragon)
p1.can_cast()
global choice
global dragons_slain
play = True
clock = pygame.time.Clock()
while play:
clock.tick(FPS)
for event in pygame.event.get():
if eve... |
def createboard(self):
themap=list(list())
for i in range(self.sizex):
line=list()
for j in range(self.sizey):
line.append(Node(i,j,"e",self.sizex,self.sizey))
themap.append(line)
themap[0][0].visited=True
themap[0][0].nw=True
t... | The code determines the agent's next move in a grid-based environment by checking pre-defined moves, parsing state information, handling encounter scenarios, collecting gold, and using DFS to explore paths when no immediate moves are available, updating position and move queue accordingly. | def move(self,state):
##TODO: Implement your algorithm here
#time.sleep(1)
if len(self.nextmoves)!=0:
return self.nextmoves.popleft()
if len(self.board)==0:
self.createboard()
self.parsemessage(state[0])
if self.i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.