dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def generate_batch(data, batch_size):
batches = []
start_margin = 0
end_margin = batch_size
while end_margin < len(data):
batches.append(data[start_margin:end_margin])
start_margin += batch_size
end_margin += batch_size
batches.append(data[start_margin:len(data)])
print("... | This function trains a neural network model using triplet loss for a task involving question-answer pairs. It iterates over epochs, processes data in batches, generates question-positive-negative triplets, computes similarity scores, applies a margin-based loss, and updates the model via backpropagation. After each epo... | def train_batch(model, data, test_data, optimizer, word_2_id, id_2_answer_text, max_sentence_len, n_epochs,
batch_size, margin, neg_pos_rate, checkpoint_path):
for epoch in range(n_epochs):
model.train()
print("============================= Epoch {} =============================".for... |
def classifications_dataframe_fill_individual_classifications(skipNonExpertClassifications=False):
""" This will look at the requested stain and grab all the classifications that correspond to it.
Returns this as a dataframe with sensible names for columns
:param skipNonExpertClassifications: bool indicati... | The function generates bootstrap samples to compute the correlation (rho) between user classifications and expert scores, storing results in a database. It processes multiple user counts per subject, skips existing entries, and iteratively calculates rho for each bootstrap, updating the database with new results while ... | def run_bootstrap_rho_ignoring_segments():
ix = 0
clnAll = classifications_dataframe_fill_individual_classifications(skipNonExpertClassifications=True)
dbBootstraps = dbConnection.results.bootstraps
for N in numberOfClassificationsPerCore:
t = time.time()
# check how many bootstrap entri... |
def run_full_cores():
""" Main function of this script.
Will run a single pass through analysis, collecting classifications, forming dataframe, writing to excel and mongodb
:return: cores
"""
if aggregate == 'segment_aggregation':
# this code should only be ran when including all users
... | The main task of the code is to execute different aggregation workflows based on the `bootstrap` and `aggregate` flags. If `bootstrap` is False, it runs `run_full_cores()` to generate classifications. If `bootstrap` is True, it executes either `run_bootstrap_rho_segment_aggregation()` or `run_bootstrap_rho_ignoring_seg... | def main():
if not bootstrap:
cores, cln = run_full_cores() # will also generate the .pkl file with classifications if it doesn't exist
elif (aggregate == 'segment_aggregation') & bootstrap:
run_bootstrap_rho_segment_aggregation() # requires run_full_cores to have run; requires rto_mongodb_utils... |
def encode_channels(version: str, *, channels: torch.Tensor):
if version == "v1":
freqs = get_scales(0, 10, channels.dtype, channels.device).view(1, -1)
freqs = channels.reshape(-1, 1) * freqs
return torch.cat([freqs.cos(), freqs.sin()], dim=1).reshape(*channels.shape[:-1], -1)
elif vers... | The code processes input tensors by encoding channels, position, and direction using specified methods, concatenates them, and passes the result through a neural network. It reshapes inputs, applies encoding functions, combines features, and returns transformed outputs with adjusted dimensions for further processing. | def forward(
self, channels: torch.Tensor, position: torch.Tensor, direction: torch.Tensor
) -> torch.Tensor:
"""
:param channels: [batch_shape, inner_batch_shape, n_channels, height, width]
:param position: [batch_shape, inner_batch_shape, 3, height, width]
:param direction:... |
def _get_chrome_driver(self, is_grid_test, is_linux, is_headless, platform, init_msg):
if is_grid_test:
chrome_options = webdriver.ChromeOptions()
if is_headless:
init_msg = f'{init_msg[:-1]} - Headless)'
chrome_options.add_argument("--headless")
... | The code initializes a Selenium web driver based on configuration settings, handling Chrome, Firefox, or Safari. It suppresses unnecessary logs, determines platform and headless mode, selects the appropriate driver, sets implicit waits, and adjusts window size (maximizing for non-headless modes, with additional Chrome-... | def __init__(self, session):
super().__init__(session)
import logging
from selenium.webdriver.remote.remote_connection import LOGGER as seleniumLogger
seleniumLogger.setLevel(logging.WARNING)
logging.getLogger("urllib3").setLevel(logging.WARNING)
platform = self.config.... |
def test_is_prime():
cnt = 0
for v in gen_prime(__N, is_prime):
# print(v)
cnt += 1
print(f"Total: {cnt}")
def test_prime_py():
cnt = 0
for v in gen_prime(__N, primes.check):
# print(v)
cnt += 1
print(f"Total: {cnt}")
def test_sym_py():
cnt = 0
for v in ge... | The main task of the code is to execute test functions (`test_is_prime`, `test_prime_py`, `test_sym_py`) to validate implementations related to prime number checks or symbolic computations, while printing the value of the `__N` variable for context or debugging. | def main():
print(f"__N = {__N}")
test_is_prime()
test_prime_py()
test_sym_py() |
def get_profile(self, pk):
try:
return Profile.objects.get(pk=pk)
except Profile.DoesNotExist:
raise Http404
def charge_tier_usage(self, pk):
profile = Profile.objects.get(pk=pk)
prop = profile.user_property
hcf_water = prop.hcf_usage
lot_size =... | This code generates a user's water bill by calculating charges based on their profile and county-specific rates, creating a bill record with associated charges, and sending a notification. It retrieves user data, computes tiered usage and charges, links relevant county charges to the bill, and notifies the user of the ... | def bill_user(self, pk):
user_profile = self.get_profile(pk=pk)
final_charge = self.charge_tier_usage(user_profile.pk)
profile_tier_usage = self.get_property_tier_usage(user_profile.pk)
county_charge_total = self.get_county_charge_total(user_profile.pk)
create_bill = Bill.obje... |
def populate_tiles(self):
mapContainer = [x.strip() for x in open('src/map/MAPS.txt', encoding='utf-8-sig')]
for i in range(int(self.gameMap.mapHeight / self.gameMap.entityHeight)):
for j in range(int(self.gameMap.mapWidth / self.gameMap.entityWidth)):
temp = Entity()
... | The main task of the code is to initialize game entities by populating tiles, the hero (using inputHero), skeletons, and a boss within a game environment. This method orchestrates the setup of foundational game elements, ensuring all necessary entities are created and integrated into the game world for subsequent inter... | def populate_entities(self, inputHero):
self.populate_tiles()
self.populate_hero(inputHero)
self.populate_skeletons()
self.populate_boss() |
def configure_socket(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if self.status == ClientStatus.GROUP_CREATOR:
self.chat_creator_socket_configurations()
print("Identifier: ", self.generate_identifier())
else:
while True:
... | The code's main task is to configure a socket, initiate a separate thread for receiving data, send data, and handle cleanup on interruption. It starts a thread to continuously receive data while sending data, ensuring proper socket closure and a friendly exit message if interrupted by the user. | def processing(self):
try:
self.configure_socket()
_thread.start_new_thread(self.receive, ())
self.send()
except KeyboardInterrupt:
self.close_socket()
print("\nGoodbye") |
def model_satisfies_clauses(self):
"""Returns:
satisfied - True if the current assignment satisfies all the clauses
num_satisfaction - int, the number of clauses satisfied by the current assignment
false_clause_indices - list of ints, a list of indices of the clauses... | The code implements the WalkSAT algorithm to find a satisfying assignment for a Boolean formula. It randomly initializes variable assignments and iteratively flips variables to satisfy clauses, using probabilities to decide between random flips or guided choices based on clause evaluations. The process returns True if ... | def walksat(self):
"""Returns the correct value assignments if found. """
p = 0.3
q = 0.1
max_flips = 100000
self.assignment = [random.choice([1, 0]) for i in range(self.num_vars)]
for i in range(max_flips):
self.flips += 1
sati... |
def _git_initialize_repo(self):
"""Initialize a git repository in the current directory."""
git = get_git()
git("init", retcode=None)
git("add", ".")
git("config", "user.name", "Copier")
git("config", "user.email", "copier@copier")
# 1st commit could fail if any p... | This function updates a subproject by applying template changes, handling conflicts, and cleaning up old files. It uses temporary directories to copy and compare old/new versions, generates diffs, applies updates with Git, resolves conflicts via 3-way merging, and triggers post-migration tasks. The process ensures seam... | def _apply_update(self):
git = get_git()
subproject_top = Path(
git(
"-C",
self.subproject.local_abspath,
"rev-parse",
"--show-toplevel",
).strip()
)
subproject_subdir = self.subproject.local_abspath.... |
def _render_path(self, relpath: Path) -> Optional[Path]:
"""Render one relative path.
Args:
relpath:
The relative path to be rendered. Obviously, it can be templated.
"""
is_template = relpath.name.endswith(self.template.templates_suffix)
templated_si... | This function renders a source file by either processing it through a Jinja2 template engine (if it matches the template suffix) or copying it directly. It calculates source/destination paths, checks rendering permissions, creates necessary directories, handles symlinks, and writes the processed content to the target l... | def _render_file(self, src_abspath: Path) -> None:
"""Render one file.
Args:
src_abspath:
The absolute path to the file that will be rendered.
"""
# TODO Get from main.render_file()
assert src_abspath.is_absolute()
src_relpath = src_abspath.re... |
def _render_path(self, relpath: Path) -> Optional[Path]:
"""Render one relative path.
Args:
relpath:
The relative path to be rendered. Obviously, it can be templated.
"""
is_template = relpath.name.endswith(self.template.templates_suffix)
templated_si... | This method renders a symbolic link by converting a source symlink's path within a template to a destination path, checks if rendering is allowed, and creates the symlink at the destination. If not in pretend mode, it removes existing files/symlinks at the destination before creating the new symlink. On macOS, it also ... | def _render_symlink(self, src_abspath: Path) -> None:
"""Render one symlink.
Args:
src_abspath:
Symlink to be rendered. It must be an absolute path within
the template.
"""
assert src_abspath.is_absolute()
src_relpath = src_abspath.rel... |
def _check_unsafe(self, mode: Literal["copy", "update"]) -> None:
"""Check whether a template uses unsafe features."""
if self.unsafe:
return
features: Set[str] = set()
if self.template.jinja_extensions:
features.add("jinja_extensions")
if self.template.ta... | This method updates a Git-tracked subproject by verifying prerequisites like clean repository state, valid template references, and version compatibility. It checks if downgrades are attempted, requires overwrite permission, and applies the update if all conditions are met, displaying relevant messages during the proce... | def run_update(self) -> None:
"""Update a subproject that was already generated.
See [updating a project][updating-a-project].
"""
self._check_unsafe("update")
# Check all you need is there
if self.subproject.vcs != "git":
raise UserMessageError(
... |
def _render_path(self, relpath: Path) -> Optional[Path]:
"""Render one relative path.
Args:
relpath:
The relative path to be rendered. Obviously, it can be templated.
"""
is_template = relpath.name.endswith(self.template.templates_suffix)
templated_si... | This function recursively processes a source folder by converting its relative path within a template, creating corresponding directories in the destination, and handling files/symlinks. It checks rendering permissions, creates directories if allowed, and recursively processes subfolders/files, preserving symlinks when... | def _render_folder(self, src_abspath: Path) -> None:
"""Recursively render a folder.
Args:
src_abspath:
Folder to be rendered. It must be an absolute path within
the template.
"""
assert src_abspath.is_absolute()
src_relpath = src_absp... |
def _check_unsafe(self, mode: Literal["copy", "update"]) -> None:
"""Check whether a template uses unsafe features."""
if self.unsafe:
return
features: Set[str] = set()
if self.template.jinja_extensions:
features.add("jinja_extensions")
if self.template.ta... | This method generates a subproject by copying a template, ignoring existing content in the destination folder. It creates the destination path if missing, renders the template directly into it, executes associated tasks, and handles errors by cleaning up on failure. The process includes safety checks, user prompts, and... | def run_copy(self) -> None:
"""Generate a subproject from zero, ignoring what was in the folder.
If `dst_path` was missing, it will be
created. Otherwise, `src_path` be rendered
directly into it, without worrying about evolving what was there
already.
See [generating a ... |
def function_update_data_population(self, data_population_dict, t, phase_choice):
""" """
for i in range(self.lineages_num):
if phase_choice == 'growth':
data_population_dict[i] = self.function_growth_lineage(data_population_dict[i])
elif phase_choice... | The code simulates the growth and evolution of cell populations over generations, tracking cell numbers, fitness, and sequencing read counts. It models deterministic growth, stochastic sampling at bottlenecks, DNA extraction, PCR amplification, and sequencing processes. Data is stored across lineages and time steps to ... | def function_main(self):
"""
"""
# Step 1: growth (to simulate the whole process of the pooled growth)
self.cell_num_seq_dict = dict()
self.bottleneck_cell_num_seq_dict = dict()
self.read_num_seq_bundle_dict = {i: dict() for i in range(self.bundle_num)}
... |
def function_sum_term(self):
"""
Pre-calculate a term (i.e. sum_term) to reduce calculations in estimating the number of reads.
"""
self.sum_term_t_seq = np.zeros(self.seq_num-1, dtype=float) # from tkminus1 to tk
sum_term_extend_t_seq_tmp = 0
for k in range(self.seq_num-... | The function performs iterative optimization to estimate lineage fitness values and log-likelihoods using linear regression and convergence checks. It initializes parameters, computes mean fitness values, updates log-likelihoods, and tracks iteration times. The loop runs up to max_iter_num times, saving results if conv... | def function_main(self):
"""
main function
"""
start = time.time()
self.calculate_error = False
self.prior_loglikelihood_list = []
self.iter_timing_list = [] # running time for each iteration
#####
self.result_s = np.zeros(self.lineages_nu... |
def function_sum_term(self):
"""
Pre-calculate a term (i.e. sum_term) to reduce calculations in estimating the number of reads.
"""
self.sum_term_t_seq = np.zeros(self.seq_num-1, dtype=float) # from tkminus1 to tk
for k in range(self.seq_num-1):
sum_term_t_seq_tmp = (... | The main task of the code is to iteratively estimate lineage fitness values and cell numbers using a probabilistic model. It initializes parameters, runs optimization iterations to update estimates, computes log-likelihoods, checks for convergence by monitoring likelihood changes, and records timing data. The process s... | def function_main(self):
"""
main function
"""
start = time.time()
self.calculate_error = False
self.prior_loglikelihood_list = []
self.iter_timing_list = [] # running time for each iteration
#####
self.result_s = np.zeros(self.lineages_nu... |
def get_video_parameters(capture: cv2.VideoCapture) -> dict:
"""Get an OpenCV capture object and extract its parameters.
Args:
capture: cv2.VideoCapture object.
Returns:
parameters: dict. Video parameters extracted from the video.
"""
fourcc = int(capture.get(cv2.CAP_PROP_FOURCC))... | This function stabilizes a video using the Lucas-Kanade optical flow algorithm with pyramid decomposition. It reads an input video, computes motion vectors between consecutive frames via faster LK optical flow, accumulates average motion estimates to correct frame shifts, and writes the stabilized frames to an output v... | def lucas_kanade_faster_video_stabilization(
input_video_path: str, output_video_path: str, window_size: int,
max_iter: int, num_levels: int) -> None:
"""Calculate LK Optical Flow to stabilize the video and save it to file.
Args:
input_video_path: str. path to input video.
outpu... |
def get_video_parameters(capture: cv2.VideoCapture) -> dict:
"""Get an OpenCV capture object and extract its parameters.
Args:
capture: cv2.VideoCapture object.
Returns:
parameters: dict. Video parameters extracted from the video.
"""
fourcc = int(capture.get(cv2.CAP_PROP_FOURCC))... | This function stabilizes a video using the Lucas-Kanade optical flow algorithm with multi-level pyramids. It reads input video frames, computes motion vectors between consecutive frames, accumulates these vectors to correct frame shifts, and applies warping to produce a stabilized output video. The process includes res... | def lucas_kanade_faster_video_stabilization_fix_effects(
input_video_path: str, output_video_path: str, window_size: int,
max_iter: int, num_levels: int, start_rows: int = 10,
start_cols: int = 2, end_rows: int = 30, end_cols: int = 30) -> None:
"""Calculate LK Optical Flow to stabilize the ... |
def set_NVCC_COMMAND(MAX_REG=64):
global NVCC_COMMAND
NVCC_COMMAND = NVCC_PATH + " -ccbin " + CXX_COMPILER + " "
get_command_output(NVCC_COMMAND + APPS_DIRECTORY + "/obtain_gpu_cc.cu -o obtain_gpu_cc")
output = get_command_output(GPU_PREFIX+"./obtain_gpu_cc").split()
if len(output) != 2:
print ("Cannot obta... | The code's main task is to execute a series of test suites for validating system correctness, performance, and compatibility. It initializes the GPU environment via NVCC setup, then runs tests including sanity checks, performance regression (PR), compilation checks (CC), data structure (DS), binary compatibility (BC), ... | def run_tests():
# get the GPU properties first
set_NVCC_COMMAND()
run_sanity_check()
run_pr()
run_cc()
run_ds()
run_bc()
run_bfs() |
def read_default_path(message, default):
print(message + " [" + default + "]: ", end="")
val = input().strip().rstrip("/")
if val == "":
val = default
return val
def get_gpu_count():
gpus = os.popen("nvidia-smi -L").read().strip()
return len(gpus.split("\n"))
def find_dataset_files():
global ORKUT
global TWI... | The main task of the code is to configure paths and GPU settings for artifact evaluation, execute tests on a dataset, and generate a table. It initializes directories, sets CUDA environments, retrieves GPU information, and runs functions to process datasets, execute tests, and produce output in a structured format. | def main():
global SCRATCH_PATH
global GRAPHIT_BUILD_PATH
global DATASET_PATH
global APPS_DIRECTORY
global GPU_ID
global NVCC_PATH
global CXX_COMPILER
global GPU_PREFIX
print("Starting artifact evaluation in directory: ", DIR_PATH)
SCRATCH_PATH = read_default_path("Please choose a output directory to use", D... |
def getWords(length = 5): # http://www.gwicks.net/dictionaries.htm
"""
Accesses site and gathers all english words of specific length. Also saves words in .txt file
Parameters
----------
length : int
The length of words to gather
Returns
-------
allWords : list
A list o... | The code implements a Wordle-style word-guessing game with automated suggestions. It randomly selects a target word, allows up to `n` attempts, checks guess validity, provides feedback patterns (correct letters/positions), eliminates invalid words, and suggests optimal next guesses. The game ends with a win/loss messag... | def play(n = 6):
"""
Play a game of Wordle. Answer is randomly selected, and suggestions are given throughout
of the word to use.
Parameters
----------
n : int, optional
The number of rounds to find the correct word. The default is 6.
Raises
------
ValueError
If gue... |
def getWords(length = 5): # http://www.gwicks.net/dictionaries.htm
"""
Accesses site and gathers all english words of specific length. Also saves words in .txt file
Parameters
----------
length : int
The length of words to gather
Returns
-------
allWords : list
A list o... | The code solves Wordle by iteratively suggesting optimal guesses based on user feedback. It starts with the best first guesses, narrows down possible words using elimination, and updates suggestions after each round. The user inputs their guess and result pattern (0,1,2), and the code adjusts remaining words accordingl... | def solver(n = 6):
"""
Solves a game of wordle by giving best guess suggestions
Parameters
----------
n : str, optional
The number of rounds to find the correct word. The default is 6.
"""
# Initialize
wordsLeft = getWords()
bestFirstGuess = getBestFirstGuess()
solv... |
def psi_trial(self, x):
return (self.psi_hat(x) + self.F(x) * self.net(x))
def dpsiTrial_dx(self, x):
psi_trial_ = self.psi_trial(x)
psi_trial_.backward(create_graph=True)
return x.grad
def diff_equation(self, x, dpsi_dx, psi):
if not(self.diff_equation_):
raise Excep... | The code defines a function `G` that computes a differential equation using a trial function and its derivative. It takes input `x`, calculates the trial function `psi_trial` and its derivative `dpsiTrial_dx`, then evaluates the differential equation via `self.diff_equation` with these values, returning the result. Thi... | def G(self, x):
psi_trial_ = self.psi_trial(x)
dpsiTrial_dx_ = self.dpsiTrial_dx(x)
return self.diff_equation(x, dpsiTrial_dx_, psi_trial_) |
def psi_trial(self, x, t):
return (self.psi_hat(x, t) + self.F(x, t) * self.net(torch.tensor([x, t])))
def dpsiTrial_dx_dt(self, x, t):
x.requires_grad_(True)
t.requires_grad_(True)
psi_trial_ = self.psi_trial(x, t)
psi_trial_.backward(create_graph=True)
grad_x = x.grad
... | This function computes the residual of a differential equation using a trial solution and its derivatives. It takes inputs x and t, calculates the trial solution ψ_trial and its spatial (dψ/dx) and temporal (dψ/dt) derivatives, then evaluates the differential equation's residual by passing these values to the diff_equa... | def G(self, x, t):
psi_trial_ = self.psi_trial(x, t)
dpsiTrial_dx_, dpsiTrial_dt_ = self.dpsiTrial_dx_dt(x, t)
return self.diff_equation(x, t, dpsiTrial_dx_, dpsiTrial_dt_, psi_trial_) |
def psi_trial(self, x, y):
return (self.psi_hat(x, y) + self.F(x, y) * self.net(torch.tensor([x, y])))
def dpsiTrial_dx2_dy2(self, x, y):
x.requires_grad_(True)
y.requires_grad_(True)
psi_trial_ = self.psi_trial(x, y)
grad_x, = torch.autograd.grad(psi_trial_,x,create_graph=True)... | The main task of the code is to compute the residual of a differential equation by evaluating the trial solution `psi_trial` and its second derivatives with respect to `x` and `y`, then passing them to `diff_equation` to calculate the equation's output. This function likely supports solving partial differential equatio... | def G(self, x, y):
psi_trial_ = self.psi_trial(x, y)
dpsiTrial_dx2_, dpsiTrial_dy2_ = self.dpsiTrial_dx2_dy2(x, y)
return self.diff_equation(x, y, dpsiTrial_dx2_, dpsiTrial_dy2_, psi_trial_) |
def handle_start_button(self, b):
'''Determine what button was pressed. If it is the start scan button then populate
the criteria dictionary and call the scanning function.'''
for key in list(self.criteria_dict.keys()):
self.criteria_dict[key] = self.centralwidget.findChild(QtWid... | The code initializes a GUI application for Sparx automation, connecting UI buttons to functions that handle tasks like extracting comments, retrieving requirements, stopping processes, updating diagrams, saving results, and interacting with Jira. It sets up a SparxAutomator instance, authenticates with Jira, and prepar... | def __init__(self):
QtWidgets.QMainWindow.__init__(self)
self.ui = uic.loadUi("sparx_auto_ui.ui", self)
# self.ui = Ui_MainWindow()
# self.ui.setWindowIcon(QtGui.QIcon("./app_icon.ico"))
# Handle when button clicked. Sends to scan function.
self.extract... |
def computeValueFromQValues(self, state):
"""
Returns max_action Q(state,action)
where the max is over legal actions. Note that if
there are no legal actions, which is the case at the
terminal state, you should return a value of 0.0.
"""
return 0 if len(state.getLegalActions(self.in... | This code updates the weights of a reinforcement learning model using the Temporal Difference (TD) error. It calculates the difference between the expected reward and the current Q-value, then adjusts each feature's weight proportionally to this error, scaled by the learning rate (alpha). This process refines the model... | def update(self, state, action, nextState, reward):
"""
Updates weights based on transition
"""
difference = reward + self.discount*self.computeValueFromQValues(nextState) - self.getQValue(state, action)
for feature in self.getFeatures(state, action).sortedKeys():
self.weights[feature] = ... |
def evaluationFunction(self, state):
return self.computeValueFromQValues(state)
def cutoffTest(self, t, limit, depth):
timeElapsed = time.time() - t
if timeElapsed >= limit:
return True
elif depth >= self.depth:
return True
return False
def generateSuccessorPosition(s... | This code implements a minimax algorithm with alpha-beta pruning for a game state. It alternates between maximizing (turn 0/1) and minimizing (turn ≥2) players, recursively evaluating legal actions to determine optimal moves. The function returns the best score based on game state evaluation, depth limits, and cutoff t... | def minimax(self, s, t, turn, alpha, beta, depth, time_depth):
if s.isOver():
return self.evaluationFunction(s)
if self.cutoffTest(t, time_depth, depth):
return self.evaluationFunction(s) + random.random()*0.005
teams = self.getTeam(s) + self.getOpponents(s)
if turn == 0 o... |
def observeState(self):
global static_particles
self.particles = static_particles
state = self.getCurrentObservation()
pacmanPosition = state.getAgentPosition(self.index)
oppList = self.getOpponents(state)
noisyDistances = [state.getAgentDistances()[x] for x in oppList]
food = ... | The code implements a decision-making algorithm for an agent in a game, using either minimax with alpha-beta pruning and particle filtering for ghost tracking or Q-learning. It selects actions based on the agent's state, food count, and time constraints, prioritizing returning home when carrying enough food. It updates... | def chooseAction(self, state):
start = time.time()
self.debugDraw([(0,0)], [0,0,0], clear = True)
self_agent = state.getAgentState(self.index)
actions = state.getLegalActions(self.index)
food = state.getBlueFood().count(True) if self.isOnRedTeam else state.getRedFood().count(True)
... |
def find_temporal_neighbor(self, search_idx_all, ts_idx_all, offset_all, got_node_emb_all, neighbors,
num_neighbors):
search_idx_l = search_idx_all[-1]
ts_idx_l = ts_idx_all[-1]
out_ngh_node_batch, out_ngh_eidx_batch, out_ngh_t_batch, offset_l, got_node_emb_l = \
... | The main task of the code is to compute a score for a batch of input data by aggregating embeddings from multiple temporal neighbors in a graph. It iteratively finds temporal neighbors, extracts node and relation embeddings, aggregates them through a neighbor encoder, and finally decodes the aggregated embeddings using... | def forward(self, batch, num_neighbors=20):
search_idx_all = [batch.src_idx]
rel_idx_all = [batch.rel_idx]
ts_idx_all = [batch.ts]
offset_all = []
got_node_emb_all = [] # whether we have got the node embedding before aggregation
neighbors = []
# find multi-hop t... |
def showNewPhoto(direction=NEXT):
# Blank the screen
screen.displaySurface.fill((0, 0, 0))
while True:
try:
if direction == NEXT:
photo = album.getNextPhoto()
if direction == PREVIOUS:
photo = album.getPreviousPhoto()
break
... | This code runs a Pygame application that displays photos periodically using a timer, allowing user interaction via keyboard controls (navigation, pause, show year). It handles events like photo updates, window close, and key presses to manage photo transitions, pause state, and quit the application. | def run():
global pauseState
global showYearState
# Creates a periodically repeating event on the event queue
pygame.time.set_timer(PHOTO_EVENT, PHOTO_INTERVAL)
showNewPhoto()
while True:
event = pygame.event.wait(LOOP_INTERVAL)
if event.type == pygame.NOEVENT:
conti... |
def determine_if_should_post() -> tuple[bool, Optional[dict]]:
today_datetime = datetime.utcnow()
most_recent_post = raid_posts.find().sort({"resetId":-1}).limit(1)
if not most_recent_post.alive:
print("No recent posts. Please initialize with at least 1 post.")
return (False, None)
nex... | The main task of the code is to determine if a raid schedule should be posted based on the number of raid days (`numberOfDaysRaiding`). If valid (2 or 3 days), it executes corresponding handling functions (`handle_2_raid_reset` or `handle_3_raid_reset`). If invalid or posting is unnecessary, it exits early, printing st... | def main():
print("Running raid-planner script...")
should_post, next_reset = determine_if_should_post()
if not should_post or next_reset is None:
return
if next_reset['numberOfDaysRaiding'] == 2:
print("Posting 2 raid days")
handle_2_raid_reset(next_reset)
elif next_reset[... |
def irt(data, val_data, lr, iterations):
""" Train IRT model.
You may optionally replace the function arguments to receive a matrix.
:param data: A dictionary {user_id: list, question_id: list,
is_correct: list}
:param val_data: A dictionary {user_id: list, question_id: list,
is_correct: list}... | The main task of the code is to implement and evaluate an Item Response Theory (IRT) model by tuning learning rates and iterations. It loads training, validation, and test data, trains the model with different hyperparameters, tracks log-likelihoods, and evaluates validation/test accuracy. It also visualizes training/v... | def main():
train_data = load_train_csv("../data")
# You may optionally use the sparse matrix.
# sparse_matrix = load_train_sparse("../data")
val_data = load_valid_csv("../data")
test_data = load_public_test_csv("../data")
#####################################################################
... |
def __Is_Visited_Already(self, cookedMeal):
clonedVisitedCombinations = self.visitedCombinations.copy()
cookedSet = set(cookedMeal)
if len(cookedMeal) in clonedVisitedCombinations:
shouldAddToCombination = True
for combinations in clonedVisitedCombinations[len(cookedMeal)... | This function generates new nodes for a search algorithm by exploring unvisited meal combinations. It iterates through recipes not yet cooked, creates new states with updated baskets, costs, and meal counts, and adds valid nodes to the agent's fringe. Nodes are sorted by cumulative cost (including heuristic) to priorit... | def __Generate_Nodes(self, currentNode):
for_sort_nodes = []
if currentNode["mealNumber"] < self.agent.numberOfMeal:
for recipe in self.globalRecipe:
if recipe not in currentNode["cookedMeal"]:
selectedRecipe = self.globalRecipe[recipe]
... |
def Generate_Purchased_Item(recipe, basket):
purchaseList = {}
for ingredient in recipe["ingredients"]:
if ingredient not in basket:
ingredientObject = ingredientList[ingredient]
purchaseList[ingredient] = purchaseableList[ingredient]
return purchaseList
def Generate_Basket(recipe, basket, purchas... | The code generates successor nodes for a meal planning algorithm by iterating through uncooked recipes, calculating new states (basket, cost, heuristic), and adding valid unvisited combinations to the agent's frontier, sorted by cumulative cost for efficient search. | def Generate_Successor_Node(currentNode, agent):
for_sort_nodes = []
if currentNode["mealNumber"] < agent["numberOfMeal"]:
for recipe in recipesList:
if recipe not in currentNode["cookedMeal"]:
cookedMeal = currentNode["cookedMeal"] + [recipe]
purchasedList = Generate_Purchased_Item(recip... |
def class_dot_all(self, cls_name):
'''Gets all instances of class.'''
if cls_name in CLASSNAMES:
_list = [
str(obj) for key, obj in storage.all().items()
if key.startswith(cls_name)
]
print(_list)
else:
super().d... | This method processes commands like `<cls name>.all()`, delegating to specific handlers for `.all()`, `.count()`, `.show()`, `.destroy()`, and `.update()` based on the command suffix. If no match is found, it falls back to the parent class's `default()` method for further processing. | def default(self, line):
'''Handles commands like <cls name>.all().'''
cmd = line.strip()
# if cmd not like <cls name>.all() delegate to super().default()
if cmd.endswith('.all()'):
self.class_dot_all(cmd.split('.')[0])
elif cmd.endswith('.count()'):
self... |
def logprior(self,pars):
log10Ml = pars[0]
if (log10Ml < self.minlogMl) or (log10Ml>self.maxlogMl):
return -np.inf
if self.usefraction:
frac = pars[-1]
if (frac < 0) or (frac>1.):
return -np.inf
if self.massprofile.type == 'gaussian':
... | This function computes the log-likelihood of a model given parameters `pars`. It first checks if the prior is finite, then generates model predictions (`alphal`). For 'ps' mass profiles, it enforces signal-to-noise constraints. It validates `alphal` (no NaNs) and calculates the chi-square statistic comparing model pred... | def lnlike(self,pars):
if ~np.isfinite(self.logprior(pars)):
return -np.inf
alphal = self.samplealphal(pars)
if self.massprofile.type == 'ps':
## if ps, need to do snr check and re-sample if any have too high snr. this stops walkers from getting too stuck.
alp... |
def section_header(text):
log()
time = get_timestamp()
time_str = dim('(' + time + ')')
header = bold_yellow_underline(text)
print(header + ' ' + time_str, file=sys.stderr, flush=True)
def log(message='', end='\n'):
print(message, file=sys.stderr, flush=True, end=end)
def load_fasta(fasta_filena... | The main task of the code is to validate two assemblies by checking they contain the same number of sequences, ensuring no zero-length sequences, and verifying sequence lengths are within 10% of each other. If valid, it returns both assemblies; otherwise, it exits with errors. | def load_assemblies(assembly_1_filename, assembly_2_filename):
section_header('Loading assemblies')
log(assembly_1_filename)
assembly_1 = load_fasta(assembly_1_filename)
for name, seq in assembly_1:
log(f' {name}: {len(seq):,} bp')
log()
log(assembly_2_filename)
assembly_2 = load_fa... |
def log(message='', end='\n'):
print(message, file=sys.stderr, flush=True, end=end)
def get_aligned_seqs(assembly_1_seq, assembly_2_seq, aligner):
cigar = get_cigar(assembly_1_seq, assembly_2_seq, aligner)
expanded_cigar = get_expanded_cigar(cigar)
i, j = 0, 0
assembly_1_aligned, assembly_2_aligned,... | The function `output_differences` aligns two sequences using a specified aligner, identifies differences between them, and logs metrics like difference count and worst-case identity percentages over varying window sizes. It then processes alignment positions into ranges, validates consistency, and prints formatted diff... | def output_differences(assembly_1_name, assembly_1_seq, assembly_2_name, assembly_2_seq, padding,
merge, longest_label, aligner):
log(f'Aligning {assembly_1_name} to {assembly_2_name}:')
assembly_1_aligned, assembly_2_aligned, differences, assembly_1_pos, assembly_2_pos, diff_pos, \
... |
def section_header(text):
log()
time = get_timestamp()
time_str = dim('(' + time + ')')
header = bold_yellow_underline(text)
print(header + ' ' + time_str, file=sys.stderr, flush=True)
def get_longest_label(assembly_1, assembly_2):
longest_name, longest_seq = 0, 0
for name, seq in assembly_1... | The main task of the code is to align sequences from two assemblies and output their differences using a specified aligner. It iterates through paired sequences, formats them with padding/merging options, and uses the longest label for consistent alignment display. | def align_sequences(assembly_1, assembly_2, padding, merge, aligner):
section_header('Aligning sequences')
longest_label = get_longest_label(assembly_1, assembly_2)
for b, a in zip(assembly_1, assembly_2):
assembly_1_name, assembly_1_seq = b
assembly_2_name, assembly_2_seq = a
output... |
def parse_config(self, config_file):
config_data = self.read_file(config_file).replace(" ","").split("\n")
config = []
for item in config_data:
info = re.split("[:,]", item)
config += [info]
return config
def parse_program(self, program_file):
pro... | The code initializes an object by parsing configuration, program, and memory data from specified files, and loading register values. It reads a configuration file, parses an input program, loads memory starting at hex address 100 from a data file, and reads register values from a register file to set up the object's st... | def __init__(self, input_file, data_file, reg_file, config_file):
self.config = self.parse_config(config_file)
self.program = self.parse_program(input_file)
self.memory = self.read_memory(int("100",16), data_file)
self.registers = self.read_registers(reg_file) |
def send_email_verification(self, email1, usern):
verification_code = random.randint(1000, 9999)
subject = "Verification Code"
message = f"Verification code <br> <h1>{verification_code}</h1><br>Your username:<h2>{usern}<h2>"
email_send = sendEmail(email1, message, subject)
send_v... | This code initiates email verification by sending a confirmation code, then creates a UI window for users to input the received code. If verification succeeds, it hides the main window, opens a new dialog with an entry field for the code, a disabled validation field, and a submit button. The button triggers code valida... | def start_verifying_email(self, email1, usern):
verify_email = self.send_email_verification(email1, usern)
if verify_email != None and verify_email:
self.top.withdraw()
newTop = Toplevel()
self.center_window(newTop, 250, 150)
newTop.resizable(0,0)
... |
def calc_height(self, node):
if not node:
return -1
return node.height
def settle_violation(self, data, node):
balance = self.calc_balance(node)
# case 1: left left heavy situation
if balance > 1 and data < node.left_child.data:
print("Left left heavy sit... | This function inserts a new node with given data into a binary tree recursively. It updates the height of the current node and checks for balance violations, which are resolved by the settle_violation method to maintain tree properties like AVL balance. | def insert_node(self, data, node):
if not node:
return Node(data);
if data < node.data:
node.left_child = self.insert_node(data, node.left_child)
else:
node.right_child = self.insert_node(data, node.right_child)
node.height = max(self.calc_height(node.... |
def display_rules():
"""
This fuction will display the rules if the user inputs y and skips this
section if n is inputted
"""
while True:
question = input("Would you like to see the rules, y/n?\n")
if question.lower() == "y":
typing(txtcolor.HEADER +
"\... | The main task of the code is to execute a Hangman game loop by displaying rules, capturing the user's name, running the game, and prompting the user to play again or exit. The function sequentially calls `display_rules()`, `users_name()`, `hangman()`, and `play_again()` to manage game flow and user interaction. | def main():
"""
This function runs the game loop by displaying the rules, then requesting
the users name followed by the current game function and finally the
function to allow the user to exit the gae or play again
"""
display_rules()
users_name()
hangman()
play_again() |
def init_sha1_state(copy: bool = False):
global h0_start_tree, h1_start_tree, h2_start_tree, h3_start_tree, h4_start_tree
init_registry()
h0_start_tree = UInt32Tree.from_int(H0_START, 'H0')
h1_start_tree = UInt32Tree.from_int(H1_START, 'H1')
h2_start_tree = UInt32Tree.from_int(H2_START, 'H2')
h... | The main task of the code is to reverse-engineer a SHA-1 hash by generating potential input values using a probability mask derived from specified symbols. It initializes the SHA-1 state, calculates a mask for allowed characters, and employs forward and backward movement functions to predict and validate hash candidate... | def sha1_rev(sha: str, limit_length: int, used_symbols: list[str]):
init_sha1_state()
probability_mask = calc_symbols_mask(used_symbols)
print(f'Probability mask: {probability_mask}\nFor charset: "{"".join(used_symbols)}"')
w, *predicted_h = forward_move(limit_length, probability_mask)
backward_mov... |
def makeIdentityToken(curr: str, i: int):
return {
"type": translate(curr),
"start": i,
"end": i + len(curr)
}
def isVariableStart(inputStr, i):
return tryReadVariableName(inputStr, i) is not None
def scanVariable(inputStr, i, variableSet):
variableName = tryReadVariableName(inpu... | The function `preliminaryScan` tokenizes an input string by identifying variables, operators, and EOF markers. It appends an EOF marker to the input, iterates through each character, and classifies elements into tokens. Variables and operators are scanned and added to the token list, while whitespace is skipped. Upon e... | def preliminaryScan(inputStr: str):
# Append the $ marker to the end of input, this means a EOF marker.
inputStr += scannerConstantEOF
# Run the scan
i = 0 # index
variableSet = {} # Set of variables
tokens = [] # List of tokens
while True:
curr = inputStr[i]
# Stop on ... |
def IPHostCallback (self, variable):
if ":" in config['GPS1']["Address"]:
config['GPS1']["Address"] = variable.get() + ":" + config['GPS1']["Address"].split(":")[1]
else:
config['GPS1']["Address"] = variable.get()
def IPPortCallback (self, variable):
config['GPS1']["Addre... | (The main task of the code is to initialize a GUI interface for configuring and monitoring EM (Electromagnetic) data collection. It sets up input fields for GPS/EM device settings, operator details, data file paths, and real-time tracking. The UI includes comboboxes for device mode selection, entry fields for IP/port c... | def initUI(self):
global config
self.master.title("EM")
self.style = ttk.Style()
self.style.configure('CommError.TFrame', background="red", foreground="white")
self.style.configure('CommOK.TFrame', background=root.cget("bg"), foreground="black")
self.style.configure('Com... |
def GPSQualityCode(self):
code = self.GPSQualityVal.get()
if (code == 0):
return "Invalid"
if (code == 1):
return "GPS"
if (code == 2):
return "Diff. GPS"
if (code == 3):
return "NA"
if (code == 4):
return "... | The code logs real-time GPS data, including coordinates, speed, track information, and quality metrics, into a CSV file by appending timestamped records. It also updates a map display with the current tracking position. | def doit(self):
time_now = datetime.datetime.now().strftime('%Y-%m-%d,%H:%M:%S.%f')
line = time_now + "," + \
str(self.X1Val.get()) + "," + str(self.Y1Val.get()) + "," + str(self.H1Val.get()) + "," + \
str(self.SpeedVal.get()) + "," + str(self.TrackVal.get()) + "," + self.GPSQua... |
def GPSQualityCode(self):
code = self.GPSQualityVal.get()
if (code == 0):
return "Invalid"
if (code == 1):
return "GPS"
if (code == 2):
return "Diff. GPS"
if (code == 3):
return "NA"
if (code == 4):
return "... | The code logs timestamped sensor data (including coordinates, speed, track, GPS quality, and E1 values) to a file, then updates tracking visuals and records EM parameters via two methods. | def doit(self):
time_now = datetime.datetime.now().strftime('%Y-%m-%d,%H:%M:%S.%f')
line = time_now + "," + \
str(self.X1Val.get()) + "," + str(self.Y1Val.get()) + "," + str(self.H1Val.get()) + "," + \
str(self.SpeedVal.get()) + "," + str(self.TrackVal.get()) + "," + self.GPSQua... |
def getE1(self):
return("," + str(self.EM_PRP1Val.get()) + "," + str(self.EM_PRP2Val.get()) + "," + str(self.EM_PRPHVal.get())+ \
"," + str(self.EM_HCP1Val.get()) + "," + str(self.EM_HCP2Val.get()) + "," + str(self.EM_HCPHVal.get()) + \
"," + str(self.EM_PRPI1Val.get()) + "," + s... | The main task of the code is to log real-time data into a CSV file, including timestamps, coordinates, sensor values, and operator information. It appends a new data line to the file, updates a plot with current coordinates, and records EM sensor data. The function ensures the file exists, writes headers if necessary, ... | def doitPlot(self):
if not os.path.exists(self.savePlotFile.get()):
with open(self.savePlotFile.get(), 'w') as the_file:
the_file.write('YYYY-MM-DD,HH:MM:SS.F,Plot,Longitude 1,Latitude 1,Height 1,E1_PRP1,E1_PRP2,E1_PRPH,E1_HCP1,E1_HCP2,E1_HCPH,E1_PRPI1,E1_PRPI2,E1_PRPIH,E1_HCPI1,E1_HC... |
def IPHostCallback (self, variable):
config['GPS1']["Address"] = variable.get()
def getAddresses(self, currentMode ):
if (currentMode == "IP"):
return(config['IP']["Recent"])
if (currentMode == "Serial"):
return(self.getSerialAddresses())
if (currentMode == "Bluet... | The code initializes a graphical user interface (GUI) for a data collection application, configuring input fields for GPS and EM device settings, tracking data visualization, sequence number controls, and operational parameters. It sets up widgets for saving data files, operator input, GPS/EM mode and baud rate selecti... | def initUI(self):
global config
self.master.title("EM")
self.style = ttk.Style()
frame1 = ttk.Frame(self)
frame1.grid(row=0, column = 0, columnspan=4, sticky=tk.W+tk.E)
# Default filenames
today = datetime.datetime.now().strftime("%d-%m-%Y")
self.saveFi... |
def doGPSUI(self, w):
for c in w.winfo_children():
c.grid_forget()
self.X1Val.set(0)
self.Y1Val.set(0)
self.GPSQualityVal.set(0)
self.GPSModeLab.grid(row=0, column = 0, padx=5, pady=6)
self.GPSModeBx.grid(row=0, column = 1, padx=5, pady=6)
#self.GPSMo... | This method handles selecting a GPS mode by capturing the selected value from an event widget, updating the 'GPS1' mode in a configuration dictionary, clearing GPS-related error messages, refreshing the GPS UI, setting a restart flag, saving the updated configuration, and clearing messages. | def onSelectModeGPS(self, evt):
value = "Undefined"
try:
w = evt.widget
value = w.get()
except:
pass
with lock:
config['GPS1']['Mode'] = value
while "GPS" in self.errMsgSource: self.errMsgSource.remove("GPS")
self.doGPSUI(... |
def _creatingItemsets(self):
self._transactionsDB, self._fuzzyValueDB, self._Database = [], [], []
if isinstance(self._iFile, _ab._pd.DataFrame):
if self._iFile.empty:
print("its empty..")
i = self._iFile.columns.values.tolist()
if 'Transactions' in i:... | This code performs fuzzy-frequent pattern mining by processing transactions to calculate item frequencies across three fuzzy regions (low, mid, high). It aggregates counts, filters items meeting minimum support, and generates frequent itemsets using FFLIST structures. The process involves transaction iteration, fuzzy r... | def startMine(self):
"""
fuzzy-Frequent pattern mining process will start from here
"""
low = 0
mid = 1
high = 2
self._startTime = _ab._time.time()
self._creatingItemsets()
#print(self._mapItemsLowSum.keys(), self._mapItemsMidSum.keys(), self._ma... |
def _mapNeighbours(self):
self._mapItemNeighbours = {}
if isinstance(self._nFile, _ab._pd.DataFrame):
data, items = [], []
if self._nFile.empty:
print("its empty..")
i = self._nFile.columns.values.tolist()
if 'items' in i:
i... | The main task of this code is to mine fuzzy periodic-frequent patterns from transactional data by calculating item support, filtering patterns based on minimum support thresholds, and generating candidate patterns using a maximum scalar cardinality strategy. It processes transactions, computes fuzzy regional membership... | def startMine(self):
""" Frequent pattern mining process will start from here
"""
self._startTime = _ab._time.time()
self._mapNeighbours()
self._creatingItemSets()
self._fuzzyMembershipFunc()
self._finalPatterns = {}
recent_occur = {}
for line in r... |
def flatten_params(m, numpy_output=True):
total_params = []
for param in m.parameters():
total_params.append(param.view(-1))
total_params = torch.cat(total_params)
if numpy_output:
return total_params.cpu().detach().numpy()
return total_params
def validate_direction(w0, direction... | The code loads the MNIST dataset, trains a neural network model, and evaluates parameter sensitivity by perturbing model weights in specific directions. It computes accuracy bounds and boundaries for these perturbations, saving results for analysis. | def main():
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize((0.5), (0.5))])
trainset = torchvision.datasets.MNIST(root='./data', train=True,
download=True, transform=transform)
trainloader = torch.utils.... |
def AoI(plane, event_number, thresholding=True, no_std=0.2):
if plane=="u":
AoI_x = u_x[event_number]
AoI_z = u_z[event_number]
AoI_adc = u_adc[event_number]
AoI_truevtxz = u_truevtx_z
AoI_truevtxx = u_truevtx_x
elif plane=="v":
AoI_x = v_x[event_number]
A... | The main task of the code is to optimize and find the optimal (z, x) coordinates that maximize the phi score for a given event in a particle detection plane. It calculates scores using a histogram method over regions of interest (AoI), identifies the highest-scoring point, and optionally visualizes the result. The func... | def optimise_phi(plane, event_number, thresholding=True, no_std=0.2, no_sectors=20, centre=0, plot=True):
AoI_x, AoI_z, AoI_adc, AoI_truevtxz, AoI_truevtxx = AoI(plane, event_number, thresholding, no_std)
no_points = len(AoI_x)
score_arr = np.zeros(no_points)
for i in tqdm(range(no_points)):
cen... |
def drawBackground():
global backgroundPoints
glColor3f(0.7,0.7,0.7)
glPointSize(2)
glBegin(GL_POINTS)
for x,y in backgroundPoints:
glVertex2f(x, y)
glEnd()
def Player1():
global o, l
#Drawing player 1
# Drawing mouth
glColor3f(1,1,1)
mtopRight = midp... | The function `drawPlayer()` renders the player character in a game by selecting between three different player representations (Player1, Player2, Player3) based on the current score. It first draws the background, then uses conditional logic to determine which player sprite to display: Player1 for scores ≤500, Player2 ... | def drawPlayer():
global playerOffset, L, R, gameOver, score
#draw the player
drawBackground()
if score <= 500:
Player1()
elif score <= 1000:
Player2()
else:
Player3() |
def drawPlayer():
global playerOffset, L, R, gameOver, score
#draw the player
drawBackground()
if score <= 500:
Player1()
elif score <= 1000:
Player2()
else:
Player3()
def drawIdleEnemy():
global dropOffset, left, gameOver, score, count, pause,a,b,c, d, L , R
p... | The main task of the code is to render the player, idle enemy, and control buttons in a graphics display, clear the buffer, swap buffers for rendering, and check for collisions. It combines drawing elements and collision detection to update the visual state of the game or application during an idle frame. | def IdleDisplay():
drawPlayer()
# drawIdleEnemy()
glutSwapBuffers()
glClear(GL_COLOR_BUFFER_BIT)
# drawPlayer()
drawIdleEnemy()
drawControlsBtns()
hasCollided() |
def iterate():
glViewport(0, 0, 500, 800)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-300, 300, -300, 300, 0.0, 1)
glMatrixMode (GL_MODELVIEW)
glLoadIdentity()
def drawControlsBtns():
global pause
# Draw restart button
glColor3f(0, 0.8667, 1)
topLeft = midpoint_line.Mi... | The main task of the code is to render a graphics frame by clearing buffers, setting up the view, drawing UI controls, background, enemies, and the player, then swapping buffers to display the rendered scene in an OpenGL application. | def showScreen():
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
iterate()
drawControlsBtns()
drawBackground()
# glColor3f(1,0,0)
drawEnemy()
drawPlayer()
glutSwapBuffers() |
def LoadShiftData(InputFile):
hFile = open(InputFile, "r")
Shift_data = []
while True:
line = hFile.readline()
item = line.split()
if not line:
hFile.close()
return Shift_data
elif len(item) > 1:
Shift_data.append(item[0])
... | The function `DisplayPoorFits` processes and compares shift and shielding data from NMR files, performs a linear fit to assess correlation, calculates statistical metrics (R², RMS error), and logs results to a file. It iteratively processes data, transforms values, and identifies discrepancies, focusing on evaluating t... | def DisplayPoorFits(Num, FileName, ShiftFile, TheMap):
InputFile = FileName + '.' + str(Num) + ".nmr"
shift_data = LoadShiftData(ShiftFile)
shielding_data = LoadShieldingData(InputFile)
shift = shift_data[:]
shielding = shielding_data[:]
R2, m, b, MaxDiff = LinearFit(shift, shielding, TheMap)
... |
def LoadShiftData(InputFile):
hFile = open(InputFile, "r")
Shift_data = []
while True:
line = hFile.readline()
item = line.split()
if not line:
hFile.close()
return Shift_data
elif len(item) > 1:
Shift_data.append(item[0])
... | This function identifies the best-fitting NMR data set by comparing experimental shift data with calculated shielding values across multiple files. It iterates through a specified number of files, performs linear regression, and evaluates fit quality using either maximum difference (MaxDiff) or root-mean-square deviati... | def FindBestFit(NMRFileBase, NMRExpFile, NumOfPoints, TheMap, Debug = False, RMSD = False):
shift_data = LoadShiftData(NMRExpFile)
BestFit = []
MinDiff = 1000000
global ZeroDetect
MinRMS = 1000000
for i in range(NumOfPoints):
NMRFile = NMRFileBase + "." + str(i) + ".nmr"
... |
def rankRoutes(population):
fitnessResults = {}
for i in range(0,len(population)):
fitnessResults[i] = Fitness(population[i]).routeFitness()
return sorted(fitnessResults.items(), key = operator.itemgetter(1), reverse = True)
def selection(popRanked, eliteSize):
"""
Fitness proportionate sele... | This function generates the next generation of a population in a genetic algorithm by ranking individuals, selecting elites, creating a mating pool, breeding offspring, and applying mutation to produce a new generation. | def nextGeneration(currentGen, eliteSize, mutationRate):
popRanked = rankRoutes(currentGen)
selectionResults = selection(popRanked, eliteSize)
matingpool = matingPool(currentGen, selectionResults)
children = breedPopulation(matingpool, eliteSize)
nextGeneration = mutatePopulation(children, mutationR... |
def createCities(noOfCities=100,file=""):
"""
Cities are either loaded from a sample cities file or
generate randomly
"""
cityList = []
if file !="":
## Loading the cities from sample file
with open(file,'r') as cities_file:
tmp_cities = pd.read_csv(cities_file,d... | The main task of the code is to solve the Traveling Salesman Problem (TSP) using a genetic algorithm. It evolves a population of routes over generations, applying elitism, mutation, and selection to optimize the shortest path. The algorithm stops either after a fixed number of generations or if fitness stagnates for 10... | def geneticAlgorithm(noOfCities, popSize, elitismPercent, mutationPercent, generations,file=""):
"""
For each generation the best child is picked based on fitness and the next generations is stopped
if the past 100 generations are choosing the same child as best option.
Here, algorithm uses both fixed... |
def _require_valid_column_number(column_number: int) -> None:
'''Raises a ValueError if its parameter is not a valid column number'''
if type(column_number) != int or not _is_valid_column_number(column_number):
raise ValueError('column_number must be int between 0 and {}'.format(BOARD_COLUMNS - 1))
def ... | The function `drop` processes a player's move in a game by placing a piece in the specified column of the game board. It validates the column number, checks if the game is active, and ensures the column isn't full. If valid, it identifies the lowest empty row in the column, updates the board with the current player's p... | def drop(game_state: GameState, column_number: int) -> GameState:
'''
Given a game state and a column number, returns the game state
that results when the current player (whose turn it is) drops a piece
into the given column. If the column number is invalid, a ValueError
is raised. If the game is ... |
def _require_valid_column_number(column_number: int) -> None:
'''Raises a ValueError if its parameter is not a valid column number'''
if type(column_number) != int or not _is_valid_column_number(column_number):
raise ValueError('column_number must be int between 0 and {}'.format(BOARD_COLUMNS - 1))
def ... | The function `pop` modifies a game state by removing the bottom piece from a specified column if valid. It checks if the column is valid, the game is not over, and the bottom piece belongs to the current player. If valid, it creates a new board with the column's pieces shifted up, removes the bottom piece, and switches... | def pop(game_state: GameState, column_number: int) -> GameState:
'''
Given a game state and a column number, returns the game state that
results when the current player (whose turn it is) pops a piece from the
bottom of the given column. If the column number is invalid, a ValueError
is raised. If ... |
def write_tutorial(name, lang, comments, code, first):
"""
Given the parsed comments and code blocks this function will write out the
full reST page for the tutorial. It assumes that the code blocks and
comment blocks are interspersed, i.e. the original file went
code, comment, code, ...
or
... | The function `make_tutorials` converts source code files (Python, C++, CMake, etc.) from an input directory into reStructuredText (.rst) tutorial files, recursively processing subdirectories. It generates output files with title-cased names, replacing underscores with spaces, and saves them in the specified output dire... | def make_tutorials(input_dir, output_dir):
"""
Given a full path to a directory, this function will parse each source file
it finds. This process is repeated recursively for each subdirectory. For
each tutorial file, a .rst file with the same name will be created which
contains the contents of the s... |
def get_oid(name):
if name == '@':
name = 'HEAD'
refs_to_try = [
f'{name}',
f'refs/{name}',
f'refs/tags/{name}',
f'refs/heads/{name}',
]
for ref in refs_to_try:
if data.get_ref(ref, deref=False).value:
return data.get_ref(ref).value
# Nam... | This function checks out a branch by retrieving its commit's tree, updating the working directory, and setting the HEAD reference to point to the branch's commit or directly to the OID if not a branch. | def checkout(name):
"""checkout the branch with name
steps:
1. Get the oid of the branch
2. Read the tree with the oid
3. Write the tree to the index
Args:
name (str): The name of the branch to checkout
"""
oid = get_oid(name)
commit = get_commit(oid)
... |
def get_merge_base(oid1, oid2):
"""
Get the merge base of the two commits
Args:
oid1 (str): The oid of the first commit
oid2 (str): The oid of the second commit
steps:
1. Get the commit with the oid1
2. Get the commit with the oid2
3. Get the common ancestor of ... | The main task of the code is to merge the specified branch into the current branch by updating the index with merged content, handling fast-forward cases, and preparing for a commit. It retrieves branch information, resolves merge conflicts, updates the working directory, and sets references like MERGE_HEAD and HEAD, w... | def merge(other):
"""
Merge the other branch into the current branch
steps:
1. Get the oid of the other branch
2. Read the tree with the oid
3. Write the tree to the index
4. Write the index to the object store
5. Write the commit to the object store
6. Updat... |
def __current_node(self):
return self.input_nodes[self.current_node_index]
def __value(self, current_node: Node) -> str:
if current_node.value.isalnum():
if current_node.value in self.stored_variables:
return self.stored_variables[current_node.value][1]
else:
... | This code interprets a sequence of abstract syntax tree (AST) nodes by iterating through them. It processes each node: storing variable declarations in a dictionary and executing print statements by evaluating their values. The loop advances through the nodes to sequentially interpret the input program structure. | def interpret(self):
while self.current_node_index < len(self.input_nodes):
current_node = self.__current_node()
if isinstance(current_node, VarDecl):
self.stored_variables[current_node.var_name] = (current_node.type, current_node.value)
elif isinstance(curre... |
def __current_token(self) -> Token:
return self.input_tokens[self.current_token_index]
def __expect(self, expected_kind: TokenKind):
if self.__is_last_token():
self.__throw_err(f"Expected a(n) {expected_kind} after `{self.__current_token().value}`, but is end of the file")
i... | This code parses input tokens into variable declarations and print statements. It processes numeric annotations by expecting an identifier, value, and semicolon, creating VarDecl objects. For "print" keywords, it captures values and generates PrintStmts. Unrecognized tokens or keywords trigger errors, ensuring syntax c... | def parse(self):
while self.current_token_index < len(self.input_tokens):
match self.__current_token().kind:
# Numeric variables
case TokenKind.NUM_ANNOT:
var_name = ""
value = ""
self.__expect(TokenKind.EQU... |
def register_routes(self):
routes = []
for key, value in self.get_config('routes').items():
handlers = value.get('handlers', None)
if not handlers:
self.logger.info(f"No route handlers")
continue
for handler in handlers:
... | The code's main task is to initialize and run a web application by registering routes, WebSocket handlers, and plugins. It enables live reloading if configured, then starts the web server on a specified port. Any exceptions during execution are wrapped in an AioCinchException and raised. | def run(self, file):
try:
self.register_routes()
self.register_ws()
self.register_plugin()
if self.get_config('reload'):
self.logger.info("Enabled live reloading")
reload(file, self.logger)
web.run_app(self.app, port=sel... |
def getGraphMeanLine(teamPts):
# Funciton purpose is to create a Line of the Mean Team Points
# for the Analysis Graph
teamPtTracker = 0
teamPtsList = []
teamMeanLine = []
for tmPts in teamPts:
teamPtTracker += tmPts
teamPtsList.append(teamPtTracker)
tmGame = ... | The main task of the code is to generate a graph visualizing a team's points and their opponent's points across multiple games, including mean value lines, while displaying game statistics like win percentage. It plots data, sets axis labels, titles, and legends, then calls additional functions to show analysis results... | def displayGraph(teamName, gameNum, teamPts, oppPts):
# Function purpose is to display the matchup analysis graph
teamMeanLine = getGraphMeanLine(teamPts)
oppMeanLine = getGraphMeanLine(oppPts)
teamSym = teamAbbrev[teamName]
plt.plot(gameNum, teamPts, color='black', label=teamSym + ' ... |
def getTeamStatsDataFrame(team):
# Function creates a DataFrame for Team Name
# Convert Team Name to Symbol, build URL, and create DataFrame
teamSym = convertTeamNameToSym(team)
teamURL = buildTeamStatsURL(teamSym)
teamDF = buildTeamStatsDataFrame(teamURL)
return teamDF
... | The function `matchupAnalysisGraph` generates and displays performance graphs for both home and away teams by extracting their historical game statistics (points scored, opponent points, game numbers) from DataFrames. It also retrieves prior matchup data between the teams. However, a potential error exists in using `ge... | def matchupAnalysisGraph(homeTeam, awayTeam):
# Function purpose is to run the matchup analysis graph
# The DataFrames are used to display all prior games played of the season so far
homeDF = getTeamStatsDataFrame(homeTeam)
awayDF = getTeamStatsDataFrame(awayTeam)
home_gr... |
def getTodaySchedSearch():
# Function Purpose: To Build String to Search Basketball Reference DataFrame
# For Game's Being Played 'Today'
today = dt.date.today()
weekDay = today.strftime('%a')
month = today.strftime('%b')
day = today.strftime('%#d')
"""
day = day.lstrip('0... | The main task of the code is to provide a menu-driven interface for users to view or analyze NBA matchups. It allows users to select options for viewing today's matchups, analyzing all scheduled matchups, analyzing a custom matchup, or exiting. The code handles input validation, loops through matchup data, and calls an... | def main():
# Main Menu Loop
while True:
# User has Four Options within the program: View NBA matchups today,
# Analyze all of the matchups to be played today, Analyze an individual
# matchup or EXIT
print("*********************** MAIN MENU ********************... |
def in_between(self, key, lwb, upb, equals=True):
"""
Checks if key is between lwb and upb with modulus 2**bits
"""
if lwb == upb:
return equals
elif lwb < upb:
return lwb <= key and key < upb
else:
... | The function finds the predecessor node's ID for a given key in a DHT by iteratively using finger tables. It starts at the current node, checks if the key lies between the current node's ID+1 and its successor's ID+1. If not, it moves to the closest preceding finger node, repeating until the predecessor is found. The l... | def find_predecessor(self, key):
"""
Finds and returns the node's id for key predecessor
"""
current = self
while not (self.in_between(key, self.sum_id(current.id, 1), self.sum_id(current.successor, 1))):
current_id = current.closest_preceding_finger(key)
... |
def get_node_proxy(self, id:int):
"""
Returns a Chord Node proxy for the given id
"""
if id != self.id:
node = create_object_proxy(ChordNode.node_name(id), self.name_server_host, self.name_server_port)
else:
node = self
return node
def in_between(s... | This method checks if the provided node_id is a better predecessor than the current one. If the current predecessor is offline or node_id lies between the current predecessor and self, it updates the predecessor to node_id and transfers keys via the new predecessor's proxy. | def notify(self, node_id):
"""
Verifies if node_id is a better predecessor, if it is then the predecessor is updated.
"""
if self.predecessor != None:
try:
predecessor_node = self.get_node_proxy(self.predecessor)
predecessor_node.id
... |
def get_node_proxy(self, id:int):
"""
Returns a Chord Node proxy for the given id
"""
if id != self.id:
node = create_object_proxy(ChordNode.node_name(id), self.name_server_host, self.name_server_port)
else:
node = self
return node
def hash(self, v... | The code initializes a Chord DHT node by setting up a Pyro daemon, registering with a name server, retrieving the initial node from a coordinator, and joining the DHT to populate its finger table. If no initial node exists, it becomes the first node in the network. | def start(self, coordinator_address):
"""
Start the node taking initial_node as reference to fill the finger_table.
In case initial_node is None the the current node is the first in the DHT.
"""
self.running = True
self.executor.submit(self.cli_loop)
... |
def find_predecessor(self, key):
"""
Finds and returns the node's id for key predecessor
"""
current = self
while not (self.in_between(key, self.sum_id(current.id, 1), self.sum_id(current.successor, 1))):
current_id = current.closest_preceding_finger(key)
... | This method updates the finger tables of other nodes in a Chord network by iterating through bit positions. For each bit, it calculates a predecessor ID, retrieves the corresponding node, and instructs it to update its finger table with the current node's ID and the current bit index. This ensures accurate routing info... | def update_others(self):
"""
Update finger tables of nodes that should include this node
"""
for i in range(1, self.bits + 1):
# In the paper the +1 at the of 2**(i-1) doesn't exist but try example CHORD 3 then CHORD 5 and the FT of 3 doesn't update properly
pred_... |
def hash(self, value):
"""
Hash function used by ChordNode
"""
return hash(value) % (self.max_nodes)
def in_between(self, key, lwb, upb, equals=True):
"""
Checks if key is between lwb and upb with modulus 2**bits
"""
if lwb == upb:
return equal... | The main task of the code is to retrieve the value associated with a given key in a distributed hash table (DHT). It first hashes the key, checks if the key lies within the current node's responsible range, and returns the value if so. If not, it delegates the lookup to the appropriate successor node by finding the suc... | def lookup(self, key):
"""
Returns the value associated with the key
"""
key = self.hash(key)
if self.in_between(key, self.sum_id(self.predecessor, 1), self.sum_id(self.id, 1)):
return self.values[key]
successor_id = self.find_successor(key)
successor... |
def hash(self, value):
"""
Hash function used by ChordNode
"""
return hash(value) % (self.max_nodes)
def find_successor(self, key):
"""
Finds and returns the node's id for key successor
"""
pred_id = self.find_predecessor(key)
pred_node = self.get_... | This code inserts a value into a Distributed Hash Table (DHT), using a specified key or generating one via hashing. It identifies the appropriate successor node for the key and either stores the value locally if it matches the current node's ID or delegates insertion to the successor node for proper distribution in the... | def insert(self, value, key:int=None):
"""
Insert value into the DHT. If key is given then it will be inserted with it.
"""
if key == None:
key = self.hash(value)
successor_id = self.find_successor(key)
if successor_id == self.id:
self.values[key] ... |
def in_between(self, key, lwb, upb, equals=True):
"""
Checks if key is between lwb and upb with modulus 2**bits
"""
if lwb == upb:
return equals
elif lwb < upb:
return lwb <= key and key < upb
else:
... | This function updates the finger table entries of a node by replacing all instances of a leaving node's ID (node_id) with a new successor ID (new_successor_id). It iterates through each finger table entry, updating successors directly or recursively propagating the change to successor nodes when the leaving node's ID f... | def update_leaving_node(self, node_id, new_successor_id):
"""
Update finger table having node_id with successor_id
"""
for i in range(1, self.bits + 1):
finger_table_entry = self.finger_table[i]
if finger_table_entry.successor == node_id:
finger_ta... |
def find_successor(self, key):
"""
Finds and returns the node's id for key successor
"""
pred_id = self.find_predecessor(key)
pred_node = self.get_node_proxy(pred_id)
return pred_node.successor
def get_node_proxy(self, id:int):
"""
Returns a Chord Node pro... | This function transfers keys from the successor node to the current node by retrieving keys responsible for the predecessor's range plus one, updating the current node's values with these keys. | def transfer_keys(self):
"""
Brings the successor key values for what this node is responsible.
"""
successor_id = self.find_successor(self.successor)
successor_node = self.get_node_proxy(successor_id)
new_keys = successor_node.pop_keys(self.sum_id(self.predecessor, 1), s... |
def find_successor(self, key):
"""
Finds and returns the node's id for key successor
"""
pred_id = self.find_predecessor(key)
pred_node = self.get_node_proxy(pred_id)
return pred_node.successor
def get_node_proxy(self, id:int):
"""
Returns a Chord Node pro... | The code stabilizes a node in a distributed network by verifying its immediate successor, updating it if necessary due to failures or overlaps, and notifying the successor of its existence. It handles communication errors by searching for a new successor, transfers keys, and ensures correct node relationships in a ring... | def stabilize(self):
"""
Verifies current node's immediate successor and notifies it about current node's existence
"""
try:
old_successor_id = self.find_successor(self.successor)
old_successor_node = self.get_node_proxy(old_successor_id)
pred_old_succ... |
def populate_dates(soup, data_dict):
months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
paragraphs = soup.find_all('p', {'class': 'p'})
for loop in range(min(5, len(paragraphs))):
para = paragraphs[loop]... | The code processes HTML files by parsing their content to extract structured data (dates, participants, presentations, questionnaires) into nested JSON files and generating corresponding text corpora in .txt files, organizing outputs into two directories: 'ECTNestedDict' for structured data and 'ECTText' for textual co... | def build_ECTNestedDict():
if not os.path.exists('ECTNestedDict'):
os.makedirs('ECTNestedDict')
if not os.path.exists('ECTText'):
os.makedirs('ECTText')
file_num = 0
for file in files:
data_dict = {}
abs_path = os.path.abspath(os.path.join(DATA_PATH, file))
so... |
def loadData(file):
x, y = [], []
with open(file, encoding='utf-8') as f:
read_file = csv.reader(f, delimiter='\t')
for row in read_file:
label, feature = row[0], row[1:]
feature.append(1)
x.append(np.array(feature, dtype=float))
y.append(int(float... | The code implements logistic regression for binary classification. It trains a model using the training dataset, validates it, and evaluates performance on test data. It computes classification errors and saves predicted labels to files. Additionally, it compares training performance across different learning rates (0.... | def logisticRegression(trainFile, num, lr, trainout, testFile, testout, metric, valFile):
# load train and validation dataset
X, y = loadData(trainFile)
valX, valy = loadData(valFile)
# theta = train(np.zeros(301), X, y, num, lr)
theta, trainLoss, valLoss = trainLarge(np.zeros(301), X, y, valX, val... |
def cross_validation_gaussian_process(self):
fold_size = len(self.train_targets)/self.k_folds
mean_squared_errors = np.zeros(len(self.hyperparameters))
for id, hyperparam in enumerate(self.hyperparameters):
for fold in tqdm.tqdm(range(self.k_folds)):
time.sleep(0.0000... | The main task of the code is to train a Gaussian process model by selecting the optimal kernel width via cross-validation, evaluate its performance on test data using mean squared error, and return the trained posterior distribution, test error, and cross-validation errors for analysis. | def training_gaussian(self):
best_width, best_mean_squared_error, errors = self.cross_validation_gaussian_process()
posterior = self.train_gaussian_process(self.train_inputs, self.train_targets, best_width)
mse = self.eval_gaussian_process(self.test_inputs, posterior, self.test_targets)
... |
def _connect_to_server(self, action_result, first_try=True):
config = self.get_config()
is_oauth = self.auth_mechanism == "OAuth"
self._smtp_conn = None
server = config[phantom.APP_JSON_SERVER]
self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, server)
# defa... | The function handles authentication setup for an application, either using an existing access token for non-test actions or initiating interactive OAuth authentication for test connectivity. It retrieves credentials, validates the action type, attempts server connection, manages state persistence, and returns success/f... | def _set_interactive_auth(self, action_result):
config = self.get_config()
client_id = config.get("client_id")
client_secret = config.get("client_secret")
# Run the initial authentication flow only if current action is test connectivity
if self.get_action_identifier() != phanto... |
def _connect_to_server(self, action_result, first_try=True):
config = self.get_config()
is_oauth = self.auth_mechanism == "OAuth"
self._smtp_conn = None
server = config[phantom.APP_JSON_SERVER]
self.save_progress(phantom.APP_PROG_CONNECTING_TO_ELLIPSES, server)
# defa... | The main task of the code is to handle server connection based on the authentication type. For "Basic" auth, it directly connects and returns the status or error. For other auth types, it attempts to refresh tokens if needed, sets interactive authentication, and returns success or error statuses accordingly. | def _connect_to_server_helper(self, action_result):
"""Redirect the flow based on auth type"""
if self.auth_mechanism == "Basic":
try:
status_code = self._connect_to_server(action_result)
except Exception as e:
return self._parse_connection_error(... |
def _connect_to_server_helper(self, action_result):
"""Redirect the flow based on auth type"""
if self.auth_mechanism == "Basic":
try:
status_code = self._connect_to_server(action_result)
except Exception as e:
return self._parse_connection_error(... | This function handles sending an email by connecting to a server, executing the send operation, and managing errors. It initializes an action result, checks connectivity (except for test actions), sends the email, and returns the status code or error message if exceptions occur. | def _handle_send_email(self, param, action_result=None):
action_id = self.get_action_identifier()
if action_result is None:
action_result = self.add_action_result(ActionResult(dict(param)))
# Connect to the server
if action_id != phantom.ACTION_ID_TEST_ASSET_CONNECTIVITY:
... |
def _connect_to_server_helper(self, action_result):
"""Redirect the flow based on auth type"""
if self.auth_mechanism == "Basic":
try:
status_code = self._connect_to_server(action_result)
except Exception as e:
return self._parse_connection_error(... | This function sends an HTML email with attachments by parsing parameters, validating configurations, sanitizing content, constructing MIME messages, retrieving vault attachments, and handling SMTP delivery with error checks for encoding, recipients, and attachment integrity. | def _handle_send_htmlemail(self, param): # noqa: C901
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(param))
# Connect to the server
self.debug_print("Connecting to server")
if phantom.i... |
def getAllTapStates(self, state):
tapStates = []
for playerHand in range(0, 2):
if state[state[2]][playerHand]:
for oppHand in range(0, 2):
# Notice 1-state[2] returns the player whose turn it
# is NOT, aka the opponent
... | The main task of the code is to retrieve all child states of a given parent state by collecting "tap states" and, if switching is allowed, "switch states," then removing duplicates and returning the consolidated list of child states. | def getChildrenOfState(self, parentState):
childStates = []
tapStates = self.getAllTapStates(parentState)
for state in tapStates:
childStates.append(state)
if self.switchingAllowed:
switchStates = self.getAllSwitchStates(parentState)
for state in switc... |
def getChildrenOfState(self, parentState):
childStates = []
tapStates = self.getAllTapStates(parentState)
for state in tapStates:
childStates.append(state)
if self.switchingAllowed:
switchStates = self.getAllSwitchStates(parentState)
for state in switc... | This method initializes the graph's adjacency lists by iterating through each state, identifying its child states, and updating both the parent and child relationships in the graph structure. It populates the 'parents' and 'children' lists to represent directed edges between states, enabling traversal and analysis of t... | def initializeGraphEdges(self):
for stateIndex in range(0, self.stateCount):
childrenStates = self.getChildrenOfState(self.stateIndexToState(stateIndex))
for state in childrenStates:
childIndex = self.stateToStateIndex(state)
self.parents[childIndex].appen... |
def _get_compartments(input_file):
with open(input_file) as input_fp:
rucksacks = (line.strip() for line in input_fp.readlines())
rucksacks_compartments = (
(rucksack[0:(int(len(rucksack) / 2))], rucksack[(int(len(rucksack) / 2)):int(len(rucksack))])
for rucksack in rucksacks
)
... | The main task of the code is to calculate two sums: (1) the total priority of repeated items in rucksack compartments and (2) the total priority of badges in elves' groups, then return both values. It reads input from "day3/example.txt", processes compartments and elf groups, computes priorities, and combines results. | def solve_example():
input_file = "day3/example.txt"
rucksacks_compartments = _get_compartments(input_file)
repeated_items_priorities = _get_repeated_items_priorities(rucksacks_compartments)
sum_priorities = sum(repeated_items_priorities)
return sum_priorities, sum(_get_elves_groups_badges_prioritie... |
def run_agent(self, name):
""" Invoke an agent against the current population """
op, k = self.agents[name]
picks = self.get_random_solutions(k)
new_solution = op(picks)
self.add_solution(new_solution)
def remove_dominated(self):
nds = reduce(Evo._reduce_nds, self.pop.key... | The main task of the code is to evolve a population by running `n` random agents, periodically removing dominated solutions every `dom` iterations to maintain diversity, and printing population status every `status` iterations. It selects agents randomly, executes them, and ensures the population remains optimized by d... | def evolve(self, n=1, dom=100, status=100):
""" To run n random agents against the population
n - # of agent invocations
dom - # of iterations between discarding the dominated solutions """
agent_names = list(self.agents.keys())
for i in range(n):
pick = rnd.choice(... |
def _v(self, rating_list, RD_list):
""" The v function of the Glicko2 system.
_v(list[int], list[int]) -> float
"""
tempSum = 0
for i in range(len(rating_list)):
tempE = self._E(rating_list[i], RD_list[i])
tempSum += math.pow(self._g(RD_list[i]), 2) * te... | This code updates a player's rating and rating deviation (RD) based on game outcomes using a probabilistic model. It scales input ratings/RD, calculates variance (v), updates volatility (vol), adjusts pre-rating RD, computes a new RD using inverse square root formula, and adjusts the rating by summing weighted differen... | def update_player(self, rating_list, RD_list, outcome_list):
""" Calculates the new rating and rating deviation of the player.
update_player(list[int], list[int], list[bool]) -> None
"""
# Convert the rating and rating deviation values for internal use.
rating_list = [(x - 1500... |
def locate_gpus_and_config_if_found():
gpus = tf.config.experimental.list_physical_devices("GPU")
for gpu in gpus:
tf.config.experimental.set_memory_growth(gpu, True)
def check_for_anchor_and_positives():
print("\nChecking for 'anchor/' and 'positive/' directories...")
anc = os.getenv("ANCHOR_PA... | The main task of the code is to train and evaluate a machine learning model using TensorFlow/Keras. It preprocesses data, loads or creates a model with a custom L1Dist layer, configures GPU settings, trains the model with an Adam optimizer, saves checkpoints, evaluates performance on test data, and exports the trained ... | def main():
load_dotenv()
custom_objects = {"L1Dist": L1Dist}
locate_gpus_and_config_if_found()
check_for_anchor_and_positives()
donwload_negatives_if_needed()
preprocessed_data = preprocess_data()
data_to_train, data_for_tests = take_data_sample(preprocessed_data)
embedding = make_e... |
def check_platform_support():#this function checks if this program is compatible with the platform or not
global SUPPORTED_PLATFORMS , PLATFORM_IS_SUPPORTED
for p in SUPPORTED_PLATFORMS:
if p == platform.system() and 'ANDROID_ROOT' not in environ:
PLATFORM_IS_SUPPORTED = True
ret... | The main task of the code is to execute platform compatibility checks, process command-line arguments, and conditionally save data to a file or display help information based on user inputs. It exits with error messages for invalid syntax or completes tasks like saving data if the platform is supported and no help flag... | def main():
global OUTPUT_FILE_LOCATION,OUTPUT_FILE_NAME,help_exec
check_platform_support()
arg_exec()
if(('-h' in sys.argv) and len(sys.argv)>2):
exit_r("[-] Match option syntax. Use gwfp -h for help.")
elif(PLATFORM_IS_SUPPORTED and ('-h' not in sys.argv)):
save_all_data(OUTPUT_FIL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.