dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def __produce_z_f_gate(self):
'''
Produce matrix and gate for Z_f
using the mapping between the input and output.
'''
z_f = np.identity(2**n)
bit_strings = self.__generate_bit_strings(self.n)
for bit_string in bit_strings:
output = f(bit_string)
... | This code constructs the quantum circuit for Grover's algorithm. It initializes necessary gates, builds the Grover diffusion operator (G) with oracle and reflection components, and assembles the main circuit by applying Hadamard gates and repeating the diffusion operator $k$ times to amplify solution probabilities. | def __build_circuit(self):
'''
Build the circuit for Grover's algorithm
'''
self.__produce_z_f_gate()
self.__produce_z_0_gate()
self.__produce_negative_gate()
#The part of the Grover's algorithm circuit
#which might repeated to obtain the correct solution... |
def __produce_z_f_gate(self):
'''
Produce matrix and gate for Z_f
using the mapping between the input and output.
'''
z_f = np.identity(2**n)
bit_strings = self.__generate_bit_strings(self.n)
for bit_string in bit_strings:
output = f(bit_string)
... | The main task of the code is to construct a quantum circuit implementing Grover's algorithm. It builds a Grover operator (G) comprising an oracle (z_f), diffusion operator (z_0), and reflection gate, then applies it iteratively (k times) to an initial Hadamard state. The circuit initializes qubits with Hadamards, appli... | def __build_circuit(self):
'''
Build the circuit for Grover's algorithm
'''
self.__produce_z_f_gate()
self.__produce_z_0_gate()
self.__produce_negative_gate()
G = QuantumCircuit(self.n, self.n)
#The part of the Grover's algorithm circuit
#which ... |
def Sbox_differential(sbox):
differential = dict()
for i in range(64):
for j in range(16):
differential[(i,j)] = []
for input1 in range(64):
output1 = sbox_map(sbox, input1)
for input2 in range(64):
output2 = sbox_map(sbox, input2)
input_xor = in... | The code performs differential cryptanalysis on a DES-like cipher by analyzing chosen plaintext-ciphertext pairs to narrow down possible subkeys. It uses S-box differentials to filter key candidates iteratively, reduces possibilities through set intersections, and eventually brute-forces remaining unknown bits to recon... | def break_cipher(chosen_pairs):
differentials = list()
differentials.append(Sbox_differential(s1))
differentials.append(Sbox_differential(s2))
differentials.append(Sbox_differential(s3))
differentials.append(Sbox_differential(s4))
differentials.append(Sbox_differential(s5))
differentials.app... |
def encode_to_BV(str):
bv_list = []
for i in range(0, len(str), 2):
first_part = ord(str[i]) - ord('f')
second_part = ord(str[i+1]) - ord('f')
number = (first_part << 4) + second_part
bv_list.append(bv(number))
return bv_list
def query_server(string):
fhand = open("requi... | The code breaks a cipher by querying a server with specific bit vectors, analyzing responses, and solving for secret matrix A and exponent vector E through exponentiation and multiplication checks. It iteratively determines A’s diagonal entries, cross entries, and validates guesses using cryptographic operations, ultim... | def break_cipher():
e_a = [[] for i in range(8)]
for i in [7, 6, 5, 4, 3, 2, 1, 0]:
ciphertext_one = encode_to_BV(query_server(list_to_str([0]*i + [1] + [0]*(7-i))))
ciphertext_two = encode_to_BV(query_server(list_to_str([0]*i + [2] + [0]*(7-i))))
#Get diagonal element
for m ... |
def encode_to_BV(str):
bv_list = []
for i in range(0, len(str), 2):
first_part = ord(str[i]) - ord('f')
second_part = ord(str[i+1]) - ord('f')
number = (first_part << 4) + second_part
bv_list.append(bv(number))
return bv_list
def invert_exponentiation(vec):
result = []
... | The code decrypts an encoded string by applying inverse transformations: converting the string to a BV structure, then repeatedly inverting exponentiation and matrix operations (invert_A), finally converting the result to integers to retrieve the original data. | def decrypt(string):
vec = encode_to_BV(string)
vec = invert_exponentiation(vec)
vec = invert_A(vec)
vec = invert_exponentiation(vec)
vec = invert_A(vec)
vec = invert_exponentiation(vec)
return [get_int_from_BV(i) for i in vec] |
def register(url):
# Send a POST request to the specified URL to register an admin user
post(url, json={'email': "wbwek@example.com",'password': "admin","passwordConfirmation": "admin","name": "admin","role":"ADMIN","groupName": "","groupId": ""})
# Register additional users with different roles and gr... | The main task of the code is to automate interactions with a car-related API by registering a user, logging in to obtain a token, and using that token to manage tire, motor, car model, and car data through admin endpoints. It sequentially calls functions to handle registration, authentication, and administrative operat... | def main():
# **Post**
register('http://localhost:8080/api/register')
token = login("http://localhost:8080/login")
tires("http://localhost:8080/admin/tires", token)
motors("http://localhost:8080/admin/motor", token)
car_model("http://localhost:8080/admin/carModel", token)
car("http://localho... |
def get_new_name(name_to_check):
obj_names = [obj.name for obj in bpy.data.objects]
new_name = ""
# if there's no obj with the name, keep name as is
if name_to_check not in obj_names:
new_name = name_to_check
else:
for i in range(1, 40):
i = f"{i:003}"
new_nam... | This code creates a custom armature with predefined bones, constraints, and materials in Blender. It generates bone shapes, sets up a bone group with specified color, links objects to collections, and ensures proper hierarchy. It also handles error checks for active collections and applies transformations, modifiers, a... | def bounding_box_set_up(self, name, color):
if bpy.context.mode != "OBJECT":
bpy.ops.object.mode_set(mode="OBJECT")
# get active collection
target_collection = bpy.context.view_layer.active_layer_collection.collection
if target_collection.get("class_id") != None:
name = get_new_name(na... |
def filter_data(data_choices, skip=[]):
"""Filters the data to only show pokes "Left" or "Right" events, which are pokes that did not occur
during time out, or during pellet dispensing.
Parameters
----------
data_choices : pandas.DataFrame
The fed3 data file
Returns
--------
... | The main task of the code is to calculate the "pokes per pellets" ratio from a fed3 bandit dataset. It filters the input data, counts pokes and pellets, and returns their ratio (pokes/pellets) as an integer or NaN if either count is zero to avoid division by zero errors. | def pokes_per_pellet(data_choices):
"""Calculates pokes per pellets from fed3 bandit file
Parameters
----------
data_choices : pandas.DataFrame
The fed3 data file
Returns
--------
ppp : int
pokes per pellets
"""
f_data_choices = filter_data(data_choices)
pe... |
def profile_with_pseudocounts(motifs):
"""
Finds the profile matrix of list of motifs
Parameters:
motifs (list of strings): DNA sequences
Returns:
profile (dict): dictionary of nucleotides profile/proportion
"""
profile = {}
counts = ... | (The function performs a greedy motif search to identify the best set of k-mers (motifs) from t DNA sequences. It initializes best motifs as the first k-mer of each sequence, then iterates through all possible k-mers in the first DNA string. For each, it constructs a profile matrix, uses it to find the most probable k-... | def greedy_motif_search(dna, k, t):
"""
Finds the most probable kmer
Parameters:
dna (list of string): DNA sequences
k (int): length of motif/k-mer
t (int): number of dna sequences
Returns:
list (string) : b... |
def random_motifs(dna, k, t):
"""
Generates random motifs from dna strings provided
Parameters:
dna (list of string): DNA sequences
k (int): length of motif/k-mer
t (int): number of dna sequences
Returns:
li... | The function performs randomized motif search to identify the best k-mer motifs across t DNA sequences. It initializes random motifs, iteratively updates them using a profile with pseudocounts, and improves the motifs until the score no longer decreases, returning the optimal motif set. | def randomized_motif_search(dna, k, t):
"""
Finds best motif by utilizing profile of a randomized initial motifs
Parameters:
dna (list of string): DNA sequences
k (int): length of motif/k-mer
t (int): number of dna sequences
Re... |
def get_all_findings_with_scan(client, org_id, app_name, version, ratings):
"""Method to retrieve all findings"""
findings_list = []
version_suffix = f"&version={version}" if version else ""
findings_url = f"https://{config.SHIFTLEFT_API_HOST}/api/v4/orgs/{org_id}/apps/{app_name}/findings?per_page=249&t... | (The function `export_report` generates a security findings report for specified apps in an organization, identifying optimal fixes and optionally troubleshooting issues. It processes each app to retrieve scan data, analyzes findings, and exports results to a CSV file. If troubleshooting is enabled, it attempts to reso... | def export_report(
org_id,
app_list,
report_file,
rformat,
source_dir,
version=None,
ratings=["critical", "high"],
troubleshoot=False,
):
if not app_list:
app_list = get_all_apps(org_id)
if not app_list:
return
with Progress(
transient=True,
... |
def update_comparison_trial_time(self):
if hasattr(self, 'comparison_start_time'):
self.comparison_trial_time = (datetime.now() - self.comparison_start_time).total_seconds()
else:
self.comparison_trial_time = "NA"
def write_data(self, event, outcome):
# This function writ... | This function handles an incorrect choice state in a trial by updating the timer, logging the event, incrementing incorrect key press counter, and transitioning to the next phase (ITI or comparison phase) based on whether the key press count meets a threshold. It maintains a resting state dependent on a key press, othe... | def incorrect_choice(self, event):
# This is one half of the RR loop. It can be thought of as the resting
# "return state" that is dependent upon a key press (on the O key).
# Otherwise, it will stay in this state forever.
self.update_comparison_trial_time() # Update the timer
... |
def clear_canvas(self):
# This is by far the most called function across the program. It
# deletes all the objects currently on the Canvas. A finer point to
# note here is that objects still exist onscreen if they are covered
# up (rendering them invisible and inaccessible); if too ... | This code handles the reinforcement phase of an experiment by updating the trial stage, incrementing the reinforcement counter, clearing the display, logging the event, providing visual/text feedback for testing, and controlling hardware (e.g., lights, servo) to deliver reinforcement. It also schedules the next phase (... | def reinforcement_phase(self):
self.trial_stage = 2
# We first need to add one to the reinforcement counter
self.reinforced_trial_counter += 1
# In this part of a trial, reinforcement is provided
self.clear_canvas()
self.write_data(None, "reinforcement_provided")
# Pr... |
def update_comparison_trial_time(self):
if hasattr(self, 'comparison_start_time'):
self.comparison_trial_time = (datetime.now() - self.comparison_start_time).total_seconds()
else:
self.comparison_trial_time = "NA"
def write_data(self, event, outcome):
# This function writ... | This method processes a key press event (likely for the 'O' key) in a trial, updating timing data, logging the event, and incrementing a counter. If the counter meets a predefined threshold (comparison_FR), it transitions to a reinforcement phase; otherwise, it re-enters the comparison phase. The function acts as a sta... | def comp_key_press(self, event):
# This is one half of the RR loop. It can be thought of as the resting
# "return state" that is dependent upon a key press (on the O key).
# Otherwise, it will stay in this state forever.
self.update_comparison_trial_time() # Update the timer
se... |
def update_comparison_trial_time(self):
if hasattr(self, 'comparison_start_time'):
self.comparison_trial_time = (datetime.now() - self.comparison_start_time).total_seconds()
else:
self.comparison_trial_time = "NA"
def write_data(self, event, outcome):
# This function writ... | The main task of the code is to handle a correct key press event in a state machine. It updates timing data, logs the event, increments a counter for correct key presses, and transitions to either the reinforcement phase (if the counter meets a threshold) or continues the comparison phase. This function acts as a "retu... | def correct_choice(self, event):
# This is one half of the RR loop. It can be thought of as the resting
# "return state" that is dependent upon a key press (on the O key).
# Otherwise, it will stay in this state forever.
self.update_comparison_trial_time() # Update the timer
se... |
def cz(m,a,b,z_str,p_e):
m[a][b] = flip(m[a][b])
m[b][a] = m[a][b]
add_error(m,[a,b],z_str,p_e)
def lc(m,v,z_str,p_e):
nbs = get_nbs(m,v)
for i in range(len(nbs)):
for j in range(i+1,len(nbs)):
m[nbs[i]][nbs[j]] = flip(m[nbs[i]][nbs[j]])
m[nbs[j]][nbs[i]] = m[nbs[i]][... | The function `cn_build_ghz` constructs a Greenberger-Horne-Zeilinger (GHZ) entangled state for `n` qubits using quantum gates (controlled-Z and local operations) and simulates error detection. It initializes a graph state with Bell pairs, applies corrections, performs measurements, and checks if the resulting error str... | def cn_build_ghz(n,p_e):
m = [[0 for i in range(3*n)] for j in range(3*n)]
err_str = [0 for i in m]
for i in range(n):
cz(m,i+n,i+2*n,err_str,p_e) #initialize graph state with Bell pairs
for i in range(1,n):
cz(m,0,i,err_str,p_e)
lc(m,0,err_str,p_e)
for i in range(n):
... |
def par_ghz(m,bit_str,err_str,p_e):
n = len(bit_str)
cz(m,bit_str[0],bit_str[1],err_str,p_e)
k=1
while 2*k<n:
for i in range(1,k+1):
cz(m,bit_str[i],bit_str[k+i],err_str,p_e)
lc(m,bit_str[i],err_str,p_e)
cz(m,bit_str[i],bit_str[k+i],err_str,p_e)
k*=2
... | The function `sc` implements a quantum error correction protocol using GHZ states and local corrections. It creates an entangled GHZ state, applies syndrome-checking and error correction steps (via `sc_ghz_par` and `lc` operations), performs Z-basis measurements for syndrome extraction, and optionally resets qubits. If... | def sc(m,n,k,bit_str,err_str,p_e,last = False, reset = True): #m is a matrix of size (n+k)
assert(k<=n+1 and k>=2)
#create inner ghz state
m = par_ghz(m,[i for i in range(k)],err_str,p_e)
sc_ghz_par(m,n,k,bit_str,err_str,p_e)
for i in range(k,n+k):
lc(m,bit_str[i],err_str,p_e)
sc... |
def get_optim(self, model):
if self.optimizer == 'SGD':
optim = SGD(model.parameters(), lr=self.lr)
elif self.optimizer == 'RMSprop':
optim = RMSprop(model.parameters(), lr=self.lr, alpha=0.99, eps=1e-08)
elif self.optimizer == 'Adam':
optim = Adam(model.param... | The code trains a neural network model using mean squared error (MSE) loss, iterating over training batches and performing backpropagation. It incorporates early stopping based on validation loss, tracks training/validation losses, and supports device placement (e.g., GPU). The function returns stopping status and loss... | def fit(
self,
model,
train_batches:Iterator[Tuple[torch.Tensor, torch.Tensor]],
val_batches=None,
verbose:bool=True,
):
model.to(self.device)
optim = self.get_optim(model)
if self.criterion in eb_criteria:
model... |
def getTileBoardRelativeCenter(self):
return ((self.screenSize[0] / 2) - (self.tileBoard.get_width() / 2), (self.screenSize[1] / 2) - (self.tileBoard.get_height() / 2))
def getTileBoard(self):
return self.tileBoard
def getTileSize(self):
return self.tileSize
def fillBoard(self, startPos):
... | This code processes mouse clicks on a game board, adjusting coordinates relative to the board's center, checking if the click is within the board's area, and handling left/right clicks to uncover tiles or toggle flags, depending on the game state and tile status. | def processClick(self, event):
pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
x,y = event.pos
bcw, bch = self.getTileBoardRelativeCenter()
x = int(x - bcw)
y = int(y - bch)
boardRect = self.getTileBoard().get_rect()
if boardRect.collidepoint((x, y)):
... |
def _create_gen_folder(self):
folder_name = self._make_gen_filename('')
if not exists(folder_name):
mkdir(folder_name)
def _delete_file(self, filename: str):
gen_filename = self._make_gen_filename(filename)
if self._verbose:
print(f'deleting file {gen_filename}')... | The main task of the code is to generate and manage header/source files by creating a generation folder, deleting existing header files, saving source text, preprocessing and generating header content from source if needed, updating header filenames, and preprocessing headers for further processing. It ensures files ar... | def _generate(self) -> bool:
self._create_gen_folder()
self._delete_file(self._generated_header_filename)
self._save_file(self._generated_source_filename,
self._source_text + '\n')
if 0 != len(self._source_text):
if 0 == len(self._header_text):
... |
def _delete_file(self, filename: str):
gen_filename = self._make_gen_filename(filename)
if self._verbose:
print(f'deleting file {gen_filename}')
try:
remove(gen_filename)
except:
pass
def _generate(self) -> bool:
self._create_gen_folder()
... | The main task of the code is to build a C extension module using Cython's FFI. It validates input sources/headers, generates code, compiles the module with specified arguments, handles errors during generation/compilation, and returns success/failure status. The process includes cleaning existing files, checking depend... | def _build(self) -> bool:
self._delete_file(self._module_name)
if self._verbose:
print(f'header_text: {self._header_text}')
print(f'source_text: {self._source_text}')
if 0 == (len(self._source_filenames) + len(self._source_text)):
print(f'{self._name}: No so... |
def playing_events(self):
# listening for quit event
for event in pg.event.get():
if event.type == pg.QUIT:
self.running = False
# listening for left click event
if event.type == pg.MOUSEBUTTONDOWN:
# find cell selected
... | This code defines a game loop that runs while 'self.running' is True. When the game state is "playing", it processes events, updates game logic, and renders the display. The loop exits when 'self.running' becomes False, then quits Pygame and exits the application. | def run(self):
while self.running:
if self.game_state == "playing":
self.playing_events()
self.playing_update()
self.playing_display()
pg.quit()
sys.exit() |
def get_range_month_actual(self, num):
"""output range actual month and range month num+=1 """
range_month = CalendarEvent(self.get_date_add_month(0), num).range_months()
return range_month
def get_list_TrueOrFalse_Event(self, **kwargs):
"""output list Event. If event is in db return Tru... | The main task of the code is to generate a context dictionary for a specific month and year, including event existence checks and reserved hours data. It converts the month name to a numeric value, prepares a range of months, and compiles relevant parameters into a dictionary for rendering templates, likely in a web ap... | def get_context(self, request, *args, **kwargs):
"""get kwargs from page where user been """
"""convert name month to number of month"""
num = strptime(kwargs['month'][0:3], '%b').tm_mon
context = {
'month': kwargs['month'],
'year': kwargs['year'],
'... |
def mcts_iter(self):
node = self.select(self.root)
reward = self.rollout(node.state)
self.backpropogate(node, reward)
def best_action(self, node, explore_val):
r = random.Random(500)
best_val = float("-inf")
best_nodes = []
for child in node.children.values():
... | The code performs Monte Carlo Tree Search (MCTS) to determine the optimal action in a given state. It runs either a time-limited or iteration-limited search, repeatedly executing `mcts_iter()` to build the search tree. After completing the search, it selects the best child node from the root using `best_action()` and r... | def search(self,state):
if self.limit_type == 'time':
time_limit = time() + self.time_limit / 1000
while time() < time_limit:
self.mcts_iter()
else:
for i in range(self.search_limit):
self.mcts_iter()
best_child = self.best_ac... |
def build_parser():
"""Build a parser for all the arguments"""
parser = argparse.ArgumentParser(description='Compute the size benchmark')
parser.add_argument(
'--builddir',
type=str,
default='bd',
help='Directory holding all the binaries',
)
parser.add_argument(
... | The main task of the code is to measure the size of benchmarks by parsing arguments, setting up logging, locating benchmarks, collecting size data, and generating statistics. It ensures proper validation, logs results, and handles errors by exiting if no data is collected. The process includes two data passes for stati... | def main():
"""Main program driving measurement of benchmark size"""
# Establish the root directory of the repository, since we know this file is
# in that directory.
gp['rootdir'] = os.path.abspath(os.path.dirname(__file__))
# Parse arguments using standard technology
parser = build_parser()
... |
def build_parser():
"""Build a parser for all the arguments"""
parser = argparse.ArgumentParser(description='Build all the benchmarks')
parser.add_argument(
'--builddir',
default='bd',
help='Directory in which to build benchmarks and support code',
)
parser.add_argument(
... | The main task of the code is to compile and link benchmark programs using command-line arguments for configuration. It sets up logging, validates input, locates benchmarks, configures parameters, and iterates through each benchmark to compile, link, and log success/failure. The process ensures all benchmarks are built ... | def main():
"""Main program to drive building of benchmarks."""
# Establish the root directory of the repository, since we know this file is
# in that directory.
gp['rootdir'] = os.path.abspath(os.path.dirname(__file__))
# Parse arguments using standard technology
parser = build_parser()
ar... |
def get_blog_categories():
"""Get the current blog categories and convert it to an id-based dictionary"""
categories = {}
pages = get_category_page_count()
for page_idx in range(1, pages + 1):
url, params = url_obj.categories_url(page_idx)
r = requests.get(url, params=params)
if... | The main task of the code is to download blog categories and posts, then save them as JSON files. It retrieves categories using get_blog_categories(), stores them in CATEGORIES_FILE, and fetches posts via get_posts_threaded() (replacing the older get_posts() method), saving them to POSTS_FILE. This function likely serv... | def legacy_download():
categories = get_blog_categories()
save_json(CATEGORIES_FILE, categories)
# Was posts = get_posts()
posts = get_posts_threaded()
save_json(POSTS_FILE, posts) |
def beginning_lines_nosn(self, stock_summary_line, sc):
# date = "date < (select date + INTERVAL '1 day' \
# from stock_move as m where location_dest_id = %s \
# and date between '%s 00:00:00' \
# and '%s 00:00:00' and state = 'done' \
# order by date asc limit 1)" % (
# ... | The main task of the code is to calculate stock summaries by clearing existing records, retrieving stock moves within a date range, calculating in/out quantities based on location changes, updating balance (starting balance + in - out), and storing results in the stock_summary_line model for a given stock summary. | def action_calculate(self):
# kosongkan stock_summary_line
# cari list produk yang ada stocknya di location id
# cari stock move product_id dan location_id, start_date to end_date
# insert into stock_summary_line
# jika keluar dari location (source_id) maka isi ke qty_out
... |
def is_train_test_file_exist(self) -> bool:
try:
logging.info("Checking if training and test file is available")
is_train_file_exist = False
is_test_file_exist = False
train_file_path = self.data_ingestion_artifact.train_file_path
test_file_path = sel... | The main task of the code is to validate data by checking the existence of train/test files, verifying dataset schema against a predefined schema file, and detecting data drift. If successful, it generates a `DataValidationArtifact` with validation status, paths, and a success message. On failure, it raises an exceptio... | def initiate_data_validation(self) -> DataValidationArtifact:
try:
self.is_train_test_file_exist()
self.validate_dataset_schema(SCHEMA_FILE_PATH)
self.is_data_drift_found()
data_validation_artifact = DataValidationArtifact(
schema_fil... |
def shuffle(self):
self.cards = list(range(66))
#print(self.cards)
random.shuffle(self.cards)
def winning_Card(self,card_list):
winning_card = card_list[0]
color = -1
if 64 in card_list:
for card in card_list:
if card == 4*13+5 or card == 4*13+... | This function simulates a game round where players take turns playing cards, determine the winning card, and track wins. It initializes player hands, collects predictions, executes multiple turns, identifies winners using winning_Card(), updates win counts, and prints results including predictions, win totals, and card... | def game_round(self,num=0):
self.shuffle()
prediction = []
result = [0 for i in range(len(self.players))]
for player in self.players:
player.set_hand(self.cards[:num+1])
self.cards = self.cards[num+1:]
prediction.append(player.get_prediction())
... |
def get_uploaded_files():
children = make_tree(uploads_dir)["children"]
files = []
for child in children:
files.append(child["name"].split('/')[-1])
return files
def play_generated_frames(args, func):
g = Generator(num_lights, num_colors, screen_height)
e = Encoder(num_lights, num_colors)
frames = None
if fu... | The code handles video frame processing via HTTP requests. It uploads files (POST) by reading binary data and storing them in a board with specified FPS, then renders 'play.html' with uploaded files. For GET requests, it triggers frame generation using a specified function and renders the same template, enabling intera... | def play():
files = get_uploaded_files()
if request.method == 'POST':
f = request.form["file"]
fps = int(request.form["fps"])
with open(os.path.join(uploads_dir, f), "rb") as frames:
board.put(frames.read(), fps)
return render_template('play.html', data=files)
elif request.method == 'GET':
if "func" in ... |
def calculateHours(self):
matrix = calendar.monthcalendar(self.year,self.month)
num_sun = sum(1 for x in matrix if x[calendar.SUNDAY] != 0)
num_sat = sum(1 for x in matrix if x[calendar.SATURDAY] != 0)
self.logger.info("ScheduleTab: calculateHours: calculated SUNDAYS: " + str(num_sun))
... | The code schedules nurses for duties by iterating through each day's requirements, assigning valid nurses until three are allocated per duty. If insufficient nurses are found, it logs warnings and handles unassigned duties by planning remaining hours and setting contractors. The primary task is to allocate nurses to da... | def schedule(self):
self.calculateHours()
#self.setContractors()
j = 0
notFinished = []
for i in range(len(self.duties)):
self.logPreviousWeek(i)
self.logger.info("\nSchedulling day " + str(self.duties[i].day) + " " + self.duties[i].type)
times... |
def createMonth(self, month=None):
self.year = int(datetime.datetime.now().strftime('%Y'))
if month == None:
self.month = int(datetime.datetime.now().strftime('%m')) + 1
if self.month == 13:
self.month = 1
self.year += 1
self.numberOfDa... | The code's main task is to initialize a monthly schedule by creating a month-specific structure, retrieving nurse data via a function call, generating a schedule, and creating a list control for display or management. It orchestrates setup steps for a scheduling system, likely in a GUI application, to prepare and organ... | def OnNew(self, month):
self.createMonth(month=month)
self.nurses = self.NIF("GET_NURSES")
self.schedule()
self.createListCTRL() |
def new_game():
start_game = game()
session["game"] = start_game
session["game"].legal_move = True
if session["new_game_options"][0][0] == 1:
session["game"].computer = True
elif session["new_game_options"][0][1] == 1:
session["game"].computer = False
if session["new_gam... | The code manages a game session by initializing or resuming a game, handling "NEW GAME" requests, making player and computer moves, updating game state (score, move status), and rendering the game board template with dynamic parameters like game state, sound effects, and move status. | def index():
if "new_game_options" in session:
new_game()
if "game" not in session:
no_game = game()
session["game"] = no_game
return render_template("board.html", game = session["game"])
if request.method == "POST":
if request.form.get("NEW GAME") == "NEW... |
def calculate_mean_activations(self, activations, predictions, labels):
self.mean_activations, self.eucos_dist = compute_mav_distances(activations, predictions, labels)
def weibull_tailfitting(eucos_dist, mean_activations, taillength=8):
"""
Fits a Weibull model of the logit vectors farthest from the MA... | The function evaluates optimal tail lengths for anomaly detection by fitting Weibull models to activation data, computing anomaly scores for inlier/outlier sets, calculating AUROC scores for each tail length, and returning sorted tail lengths by performance. It identifies the best tail lengths that maximize detection a... | def find_tail_length(self, outputs, predictions, labels, inlier_set, outlier_set):
from utils.metrics import MetricPlots
self.calculate_mean_activations(outputs, predictions, labels)
tail_test_lengths = np.arange(10, 100, 1)
auc_scores = np.zeros(len(tail_test_lengths))
for i, ... |
def plot_risk_vs_coverage_curve(self, save_name=None, fancy=True):
sns.set()
self.__plot_function(
self.coverage, self.risk, xlabel='coverage', ylabel='risk',
title=None, save_name=save_name, xlim=(0, 1), ylim=(0, 1), fancy=fancy
)
def plot_anomaly_distributions(self, bins=30, save_name=None):
if not self... | The main task of the code is to generate and save four types of visualizations (risk-coverage curve, anomaly distributions, ROC curve, and PR curve) using the provided `save_file` prefix to define output filenames. If `save_file` is None, plots are not saved. The method delegates plotting to separate functions, handlin... | def plot_all(self, save_file=None):
if save_file is not None:
risk_cov = save_file + '_risk_coverage.pdf'
distr = save_file + '_anomaly_distributions.pdf'
roc_curve = save_file + '_roc_curve.pdf'
pr_curve = save_file + '_pr_curve.pdf'
else:
risk_cov = None
distr = None
roc_curve = None
pr_cu... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __get_from_memory(self, address: int) -> bytearray:
if address < MODULO_BASE:
return self.__memory.get(address)
elif address <= REGISTER_MAX:
... | The method `__execute_rmem` reads two memory addresses (`a` and `b`), retrieves the value stored at address `b`, and writes that value to address `a`, effectively copying data from one memory location to another. This operation is part of a larger system (e.g., emulator or interpreter), where `rmem` is a command to tra... | def __execute_rmem(self):
"""
rmem: 15 a b
read memory at address <b> and write it to <a>
"""
a = self.__read_next_address_in_memory()
b = self.__read_next_address_in_memory()
self.__logger.debug(" ", a, b)
value = self.__get_from_memory(b)
sel... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __input(self) -> str:
return self.__io.input()
def __set(self, address: int, value: int, in_memory=False):
return self.__set_raw(address, Converter.IntToBytes... | The main task of the code is to read a single character from terminal input, convert it to its ASCII code, and store that value at a memory address specified by the program. The function retrieves the target memory address, logs it, captures the input, extracts the first character's ASCII value, and writes it to the de... | def __execute_in(self):
"""
in: 20 a
read a character from the terminal and write its ascii code to <a>; it can be assumed that once input starts, it will continue until a newline is encountered; this means that you can safely read whole lines from the keyboard and trust that they will be fully ... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The main task of the code is to compare two values (`b` and `c`) and store the result (1 if equal, 0 otherwise) in a specified memory address (`a`). It retrieves the address and literals from memory, evaluates their equality using an ALU method, and writes the outcome to the address. This operation is part of a low-lev... | def __execute_eq(self):
"""
eq: 4 a b c
set <a> to 1 if <b> is equal to <c>; set it to 0 otherwise
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The code executes a "greater than" operation: it reads a memory address `a`, evaluates two literals `b` and `c`, compares them using an ALU function, and stores `1` in memory at `a` if `b > c`, otherwise `0`. This implements conditional logic based on numeric comparison, typical in low-level interpreters or virtual mac... | def __execute_gt(self):
"""
gt: 5 a b c
set <a> to 1 if <b> is greater than <c>; set it to 0 otherwise
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debu... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The main task of the code is to execute an addition operation: read memory address 'a', evaluate two literals 'b' and 'c', compute their sum modulo 32768 using ALU.add(), then store the result in memory address 'a'. It logs the operands and performs modular arithmetic for overflow handling in a 16-bit signed integer co... | def __execute_add(self):
"""
add: 9 a b c
assign into <a> the sum of <b> and <c> (modulo 32768)
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The main task of the code is to execute a multiplication operation by reading a memory address (a), evaluating two literals (b and c), computing their product modulo 32768 using an ALU, and storing the result back into the memory location specified by address a. The operation is logged for debugging purposes. | def __execute_mult(self):
"""
mult: 10 a b c
store into <a> the product of <b> and <c> (modulo 32768)
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debug... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The main task of the code is to perform a modulo operation: read a memory address 'a', evaluate two literals 'b' and 'c', compute the remainder of 'b' divided by 'c' using ALU.mod, then store the result in the memory location specified by 'a'. It logs the operands and result for debugging. | def __execute_mod(self):
"""
mod: 11 a b c
store into <a> the remainder of <b> divided by <c>
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ",... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The method `__execute_and` performs a bitwise AND operation. It reads a memory address `a`, then retrieves two literals `b` and `c` from memory. It computes the bitwise AND of `b` and `c` using `ALU.bitwise_and`, then stores the result in the memory location specified by `a`. The operation logs the values of `a`, `b`, ... | def __execute_and(self):
"""
and: 12 a b c
stores into <a> the bitwise and of <b> and <c>
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ", a, ... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The code executes a bitwise OR operation by reading memory addresses and literals, performing the operation using an ALU, and storing the result in a specified memory location. It retrieves addresses and values from memory, logs them, computes the OR of two literals, and writes the result to the memory address indicate... | def __execute_or(self):
"""
or: 13 a b c
stores into <a> the bitwise or of <b> and <c>
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
c = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ", a, b, ... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | This method computes the 15-bit bitwise inverse of a literal value <b> using the ALU, then stores the result in the memory address specified by <a>. It reads <a> from memory, evaluates <b> as a literal, logs both values, applies the inverse operation, and writes the result back to <a> using the ALU. | def __execute_not(self):
"""
not: 14 a b
stores 15-bit bitwise inverse of <b> in <a>
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ", a, b)
result = ALU.bitwise_inverse(b)
self._... |
def __read_next_address_in_memory(self) -> int:
result = Converter.BytesToInt(self.__read_next_raw_in_memory())
return result
def __evaluate_next_literal_in_memory(self) -> int:
value = self.__read_next_address_in_memory()
if value < MODULO_BASE:
return value
elif val... | The method `__execute_wmem` writes a value into a specified memory address. It reads the target memory address (`a`) and the value (`b`) from the instruction stream, logs them, and then stores `b` at memory location `a` using `self.__set(a, b, in_memory=True)`. This operation implements the "wmem" command, which direct... | def __execute_wmem(self):
"""
wmem: 16 a b
write the value from <b> into memory at address <a>
"""
a = self.__read_next_address_in_memory()
b = self.__evaluate_next_literal_in_memory()
self.__logger.debug(" ", a, b)
self.__set(a, b, in_memory=True) |
def t1_t7_u1_parser(packets: list):
res = {"U1": {}}
for pkt in packets:
for snd, rcv in pkt:
if str(snd.sport)[-1] == "8":
res["U1"] = u1_parser(snd, rcv)
else:
key = f'T{str(snd.sport)[-1]}'
res[key] = {}
if rcv is... | This function aggregates parsed network response data from various protocols (TCP, ICMP, etc.) into a consolidated fingerprint dictionary, combining TCP sequence analysis, window scaling, ECN flags, and ICMP responses. The merged fingerprint is structured to match nmap's OS detection database format for comparison, ena... | def parse_pkt_res_2_fp(tcp_ans, seq_ans, icmp_ans, tcp_cport_ans, ecn_ans):
"""
A function that parses all the probes responses into a single fingerprint,
in order to compare it to the nmap os db.
"""
t1_t7_u1 = t1_t7_u1_parser(tcp_ans)
ops_win = tcp_ops_win_parser(seq_ans)
seq = seq_parser... |
def dSdt(self) -> float:
"""
:return: dS/dt
"""
return (-self.alpha * self.symptomatic * self.calc_total_attendants() - self.alpha *
((1 - self.quarantine_percent) * self.symptomatic + self.asymptomatic) * self.susceptible) * self.timeStep
def dIAdt(self) -> float:
... | This method updates the state variables of a compartmental model by calculating derivatives for susceptible, asymptomatic, symptomatic, recovered, and dead populations, then incrementing each compartment's value based on these rates. It also computes total infected individuals and advances the simulation time by one ti... | def step(self):
dSdt = self.dSdt()
dIAdt = self.dIAdt()
dISdt = self.dISdt()
dRdt = self.dRdt()
dTdt = self.dTdt()
self.susceptible += dSdt
self.asymptomatic += dIAdt
self.symptomatic += dISdt
self.infected = self.asymptomatic + self.symptomatic
... |
def dSdt(self) -> float:
"""
:return: dS/dt
"""
return (-self.alpha * self.infected * self.calc_total_attendants() - self.alpha *
(1-self.quarantine_percent) * self.infected * self.susceptible) * self.timeStep
def dIdt(self) -> float:
"""
:return: dI/dt
... | This code updates the model's state variables (susceptible, infected, recovered, dead) by adding their respective time derivatives calculated in methods dSdt(), dIdt(), dRdt(), and dTdt(). It then increments the simulation time by the predefined time step, advancing the model's temporal progression in a discrete-step m... | def step(self):
dSdt = self.dSdt()
dIdt = self.dIdt()
dRdt = self.dRdt()
dTdt = self.dTdt()
self.susceptible += dSdt
self.infected += dIdt
self.recovered += dRdt
self.dead += dTdt
self.time += self.timeStep |
def ellipse_check_channel(configuration, system_params):
# returns True if configuration (= [x, y, theta]), lies within the allowed configuration space, returns False if not
y, theta = configuration[1], configuration[2]
boundary = ellipse_boundary(theta, system_params)
if y < boundary[1] and y > bound... | The function generates a reflected configuration by identifying the boundary exit point between a valid and failed configuration in an elliptical domain. It calculates a normal vector at this boundary, then reflects the failed configuration across this boundary using geometric projection, returning a new valid configur... | def generate_reflected_configuration_channel(configuration, failed_configuration, system_params, M = 32):
x0, y0, theta0 = configuration[0], configuration[1], configuration[2]
x1, y1, theta1 = failed_configuration[0], failed_configuration[1], failed_configuration[2]
# if ellipse_check_channel(configuratio... |
def has_uids(uids):
for clazz in CLASSES:
for gender in GENDERS:
if len(uids[clazz][gender]) == 0:
return False
return True
def generate_fold(
uids,
input_dir,
input_ext,
output_dir,
group,
fold_index,
input_shape,
... | The code generates cross-validation folds by splitting input files into groups, writing them to specified output directories. It handles two scenarios: creating folds dynamically (if `num_folds < 2`) or dividing files into a fixed number of folds. Files are grouped by unique identifiers, processed, and saved with fold-... | def generate_folds(
input_dir,
input_ext,
output_dir,
group,
input_shape,
output_shape,
num_folds=0):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
files = glob(os.path.join(input_dir, '*' + input_ext))
uids = common.group_uids(f... |
def gini(self, y_data, sample_weight):
return self.gini_entropy_common(y_data, sample_weight, is_gini=True)
def entropy(self, y_data, sample_weight):
return self.gini_entropy_common(y_data, sample_weight, is_gini=False)
def impurity(self, y, sample_w):
if self.criterion == 'gini':
re... | This function recursively constructs a decision tree by selecting the optimal feature and threshold to split the data, minimizing impurity (Gini or entropy). It creates nodes with class labels when stopping conditions are met (single class or max depth reached) and recursively builds left/right subtrees for splits, ens... | def tree_generate(self, X, y, depth, sample_w):
unique_classes, counts = np.unique(y, return_counts=True)
if len(unique_classes) == 1 or (self.max_depth is not None and depth == self.max_depth):
return Node(class_index=unique_classes[counts.argmax()])
num_features = X.shape[1]
... |
def load_valid_colors(file_path: str) -> set:
"""Load valid colors from a text file."""
try:
with open(file_path, 'r') as file:
return {line.strip().lower() for line in file}
except FileNotFoundError:
print(f"Error: File {file_path} not found.")
return set()
def get_input... | The main task of the code is to repeatedly prompt the user to draw a tree using turtle graphics, validate color inputs from a file, and render trees with specified parameters until the user chooses to exit. | def main() -> None:
valid_colors = load_valid_colors('turtle_colors.txt')
dan = turtle.Turtle()
dan.speed(10)
while True:
answer = input("Would you like to draw a tree (y/n)? ").strip().lower()
while answer not in ["y", "n", "q"]:
print("Invalid input. Enter 'y', 'n', or '... |
def is_hana_running(system_id, userstore_key, verbose):
GET_HANA_STATUS = "SELECT ACTIVE_STATUS FROM SYS.M_DATABASES"
output = run_command(HDBSQL + [userstore_key] + [GET_HANA_STATUS],
verbose, True, True, system_id=system_id)
if output == HANA_NOT_RUNNING:
return False
output = output.... | The code's main task is to restore a database snapshot by first verifying the HANA database is stopped, retrieving the appropriate mount point for the cloud volume, and then executing the internal restore process with the specified snapshot and verbosity settings. | def restore(self, cloud_volume, snapshot, system_id, userstore_key, auth,
project_number, verbose):
if is_hana_running(system_id, userstore_key, verbose):
print("Error - database must be stopped before it can be restored")
sys.exit(2)
mount_point = self.get_mount_point(... |
def validate_cloud_volumes(self, cloud_volumes, project_number, auth,
snapshot_name, verbose):
volumes = {}
for cloud_volume in cloud_volumes:
vol = self.get_volume(cloud_volume, project_number, auth, verbose)
if not vol:
print("Error - volume '" + cloud_v... | The main task of the code is to perform a HANA database backup by validating input parameters, creating a snapshot of specified cloud volumes, and managing the backup process. It checks for required inputs like project number, system ID, and cloud volumes, generates a snapshot name if unspecified, validates volumes, op... | def hana_backup(self, cloud_volumes, snapshot_name, system_id,
userstore_key, auth, project_number, verbose):
# validate arguments
if not project_number:
print("Error - \"project_number\" unknown, specify in " + \
"configuration file")
sys.exit(2)
... |
def is_hana_running(system_id, userstore_key, verbose):
GET_HANA_STATUS = "SELECT ACTIVE_STATUS FROM SYS.M_DATABASES"
output = run_command(HDBSQL + [userstore_key] + [GET_HANA_STATUS],
verbose, True, True, system_id=system_id)
if output == HANA_NOT_RUNNING:
return False
output = output.... | The main task of the code is to restore a database snapshot by first verifying the database is stopped, obtaining the appropriate mount point using provided credentials and subscription ID, and then executing the restoration process internally with the specified snapshot and verbosity settings. | def restore(self, cloud_volume, snapshot, system_id, userstore_key, auth,
client_id, verbose):
credentials = auth
subscription_id = client_id
if is_hana_running(system_id, userstore_key, verbose):
print("Error - database must be stopped before it can be restored")
... |
def create_snapshot_name():
# snapshot names may not contain ":" or "." characters, so remove
date = datetime.datetime.now().isoformat()
snapshot_name = date.replace(":","-").replace(".","-")
return snapshot_name
def validate_cloud_volumes(self, cloud_volumes, subscription_id,
credentials, snap... | The main task of the code is to create a snapshot of specified cloud volumes by validating input parameters, generating default values where necessary, and delegating the snapshot creation process to an internal method. It checks for required arguments like subscription ID and cloud volumes, handles verbose output, and... | def create_snapshot(self, cloud_volumes, snapshot_name, system_id,
credentials, client_id, verbose):
subscription_id = client_id
# validate arguments
if not subscription_id:
print("Error - \"subscription_id\" unknown, specify in " + \
"configuration file")
... |
def create_snapshot_name():
# snapshot names may not contain ":" or "." characters, so remove
date = datetime.datetime.now().isoformat()
snapshot_name = date.replace(":","-").replace(".","-")
return snapshot_name
def validate_cloud_volumes(self, cloud_volumes, subscription_id,
credentials, snap... | This function creates a snapshot backup for HANA databases by validating inputs, preparing the environment, opening the backup, creating the snapshot, and closing it. It checks required parameters like subscription ID, system ID, and cloud volumes, generates a snapshot name if unspecified, and handles errors during the... | def hana_backup(self, cloud_volumes, snapshot_name, system_id,
userstore_key, auth, client_id, verbose):
credentials = auth
subscription_id = client_id
# validate arguments
if not subscription_id:
print("Error - \"subscription_id\" unknown, specify in " + \
... |
def productotensor(m1,m2):
res = []
control = 0
pj = 0
for pi in range((len(m1)-1)*2):
f1 = m1[pi]
f2 = m2[pj]
f = []
for i in f1:
for j in f2:
f.append(multicomplex(i,j))
pj += 1
f2 = m2[pj]
res.append(f... | The code simulates tensor product operations and matrix multiplication on defined structures (H, X, O), generating intermediate results like HH, HX, OO, and a final vector |y> by applying HHHX to OO. It demonstrates quantum state transformations using custom tensor and matrix operations, printing each step's output. | def simulacion_OO_HH_HX():
H=[[(0.707,0),(0.707,0)],[(0.707,0),(-0.707,0)]]
X=[[(0,0),(1,0)],[(0,0),(1,0)]]
O=[(1,0),(0,0)]
print("HH")
HH=productotensor(H,H)
for i in HH:
print(i)
print()
print("HX")
HX=productotensor(H,X)
for i in HX:
print(i)
print()
p... |
def choose_element(d):
element = rand.choice(d)
return element
def basic_game_run(op_a, op_b):
clear()
print(main_logo)
print(f"Compare A: {op_a['name']}, a {op_a['description']}, from {op_a['country']}.")
print(vs_logo)
print(f"Against B: {op_b['name']}, a {op_b['description']}, from {op... | The main task of the code is to initialize a game round by selecting two options, running the game logic, comparing their follower counts, checking the user's answer, updating the score if correct, and proceeding to the next sequence. It handles the first round's setup, user input validation, score tracking, and debug ... | def initial_load():
global FINAL_SCORE
option_a = choose_element(data)
option_b = choose_element(data)
basic_game_run(option_a, option_b)
# Debug line
print(
f"Option A Follower Count: {option_a['follower_count']}, Option B Follower Count: {option_b['follower_count']}")
user_choi... |
def get_valid_moves(board, player, i, j):
moves = []
#board = [row[:] for row in board_ref] deep cloning not needed here
dirx = ( 1 if (player == "Bb") else -1)
#forward right check
if(i + dirx >= 0 and i + dirx < 8 and j + 1 >= 0 and j + 1 < 8):
if(board[i+dirx][j+1] == None):
... | The function `fill_tree` recursively generates a game state tree up to a specified depth. It starts from a root node, identifies all valid moves for the current player, creates child nodes for each move, and recursively builds the tree by repeating this process for each child node, decrementing the depth each time. The... | def fill_tree(root, depth):
if(depth == 0):
return
moves = []
enemy = ("Rr" if (root.player == "Bb") else "Bb")
#enumerate through board looking for valid pieces to move
for (i, row) in enumerate(root.board):
for (j, value) in enumerate(row):
if(str(value) in root.pla... |
def get_pawn_score(board, player, w):
score = 0
enemy = ("Rr" if (player == "Bb") else "Bb")
for (i, row) in enumerate(board):
for (j, value) in enumerate(row):
##square is empty
if(value == None):
continue
#square has a piece
if(value ... | The main task of the code is to calculate a fitness score for a player's board position in a game (likely checkers) by summing weighted evaluations of various game elements. It combines scores from pawn/kings' value, safety, mobility, distance, and defensive positions, using weights from the "brain" object. The score a... | def get_fitness(board, brain, player = "Bb"):
enemy = ("Rr" if (player == "Bb") else "Bb")
score = float()
score += get_pawn_score(board, player, brain.weights[0])
score += get_king_score(board, player, brain.weights[1])
score += get_safe_pawn(board, player, brain.weights[2])
score += get_safe_k... |
def fill_tree(root, depth):
if(depth == 0):
return
moves = []
enemy = ("Rr" if (root.player == "Bb") else "Bb")
#enumerate through board looking for valid pieces to move
for (i, row) in enumerate(root.board):
for (j, value) in enumerate(row):
if(str(value) in root.pla... | The code simulates a turn-based game between two AI players using a minimax algorithm with a given depth. It initializes a 2D board, alternates turns, evaluates moves with the provided 'brain' models, executes the best move, and checks for a winner or draw after 100 turns. | def play_game(brain1, brain2):
board = "b,null,b,null,b,null,b,null"
board += ",null,b,null,b,null,b,null,b"
board += ",b,null,b,null,b,null,b,null"
board += ",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null"
board += ",null,r,null,r,null,r,null,r"
board += ",r,nu... |
def load_documents(self, train_docs_path: str) -> None:
tmp_path = RESOURCES_DIR / 'tmp' / 'documents.pkl'
if os.path.exists(tmp_path):
with open(tmp_path, 'rb') as f:
self.documents = pickle.load(f)
return
with open(train_docs_path, 'r') as f:
... | This code initializes a document retrieval system using LSI and a LightGBM ranker. It loads or trains models for querying Wikipedia documents, processes text with a preprocessor, and prepares datasets for ranking. The system handles training data, validation queries, and relevance judgments, building a model to rank do... | def __init__(self) -> None:
from gensim.corpora import Dictionary
self.documents = {}
self.queries = {}
self.val_queries = {}
self.q_docs_rel = {}
self.val_q_docs_rel = {}
self.group_qid_count = []
self.val_group_qid_count = []
self.dataset = [... |
def rbp(self, ranking, p=0.8):
""" menghitung search effectiveness metric score dengan
Rank Biased Precision (RBP)
Parameters
----------
ranking: List[int]
vektor biner seperti [1, 0, 1, 1, 1, 0]
gold standard relevansi dari dokumen di ra... | The code evaluates retrieval models (TF-IDF, BM25, and Letor variants) on a query set by retrieving top-100 documents per query, checking relevance against qrels, and computing average RBP, DCG, NDCG, and AP scores across 150 queries to compare model performance. | def eval_retrieval(self, qrels, query_file="queries.txt", k=100):
"""
loop ke semua query, hitung score di setiap query,
lalu hitung MEAN SCORE-nya.
untuk setiap query, kembalikan top-100 documents
"""
BSBI_instance = BSBIIndex(
data_dir=(RESOURCES_DIR / 'col... |
def WaitForMutexLock(self, sftp):
start_time = time.time()
while True:
pid = -1
user = 'none'
if exists_remote(sftp,self.MUTEX_FILE):
file = sftp.file(self.MUTEX_FILE, "r", -1)
pid = int(file.readline().strip())
user = f... | The code executes a benchmark on a BeagleBoard by acquiring a mutex lock, preparing execution parameters, running the specified project, capturing CSV output, verifying results, and managing resources. It handles DSP power cycling, error checking, and result logging, ensuring proper cleanup and connection management. | def Run(self, file):
if not self.build_server or not self.beagle_board:
raise NotConnectedError('Please make sure the class made a successfull connection to the build server and the development board.')
try:
sftp_build = self.build_server.open_sftp()
print("... |
def create_dicts(self,args_list):
dict1 = {
'Model': 'ELM',
'Number of neurons': args_list[0],
'tag': args_list[1],
'Total number of test samples': args_list[2],
"Total number of test samples in tagged_set": args_list[3],
"Total number of t... | The code trains and evaluates Extreme Learning Machine (ELM) classifiers for image classification using embeddings from different tags, varying neuron counts, and saving results. It handles GPU/CPU setup, data loading, model training, evaluation metrics (accuracy, Brier score), and visualization, while iterating over t... | def train_test_classifier(self):
import matplotlib.pyplot as plt
global class_names,best_neuron_count,device,iteration_models
n_neurons=50 #default
class_names = []
accuracies = []
precisions = []
recalls = []
f1_scores = [... |
def get_max_column_lengths(self,file_path):
max_lengths = {column: 0 for column in ["Share", "Server", "Username", "Password", "MountPoint", "AutoMount","FSTYPE"]}
with open(file_path, "r") as file:
for line in file:
values = line.strip().split(",")
for colu... | The main task of the code is to create a GUI interface for managing network mount configurations. It sets up a Treeview table to display mount details (Share, Server, Username, etc.), input fields for editing parameters, and buttons to perform actions like adding, editing, deleting, mounting, and saving mounts. The int... | def create_widgets(self):
self.treeview = ttk.Treeview(self )
# self.treeview.grid(row=0,columnspan=1, padx=5, pady=3, sticky="ew")
max_lengths = self.get_max_column_lengths(file_path)
self.treeview.grid(row=0, column=0, padx=5, pady=3, sticky="nsew")
self.treeview['show']='head... |
def find_chain_IDs(model_name, receptor_chain=receptor_chain_global,
glycine_linkers='auto', min_linker_length=10):
"""
Find out the receptor chain ID and a list of peptide chain ID.
model_name(string): name of the model.
receptor_chain(string): can be 'last' or 'A', 'B', 'C' etc.. If 'last', then... | The code quantifies peptide-receptor binding interactions in a PDB file by calculating geometric metrics (distances, angles), contact atom counts, and pLDDT-weighted parameters. It processes chains, identifies peptide-receptor interfaces, and compares binding affinity in pairwise mode. Results, including structural fea... | def quantify_peptide_binding_in_pdb(pairwise_mode=True, \
receptor_chain=receptor_chain_global, glycine_linkers='auto'):
"""
The main function to measure different metrics for quantifying
peptide-receptor binding within a single pdb file.
pairwise_mode: (boolean) if true, the first and last peptide... |
def read_variants_ht(path: str) -> hl.Table:
variants_ht = hl.read_table(path)
# Make sure that types match
assert (
isinstance(variants_ht.key[0], hl.expr.LocusExpression) &
(variants_ht.key[1].dtype == hl.tarray(hl.tstr)) &
isinstance(variants_ht.key[2], hl.expr.LocusE... | The main task of the code is to process genetic variant data by loading it from a file or text input, compute phased haplotype information using specified parameters (least_consequence, max_freq), and export the results in either a Hail table format (".ht") or a flattened format based on the output file extension. The ... | def main(args):
# Load data
variants_ht = read_variants_ht(args.ht) if args.ht else variants_ht_from_text(args.variants)
# Add phase
phased_ht = compute_phase(variants_ht, args.least_consequence, args.max_freq)
# Write results
if args.out.endswith(".ht"):
phased_ht.write(args.out, over... |
def load_data_coco(batch_size, pic_width, num_train_samples, num_test_samples):
train_images_path = 'C:/Users/user/Desktop/Projects/DattNet/data/coco-2017/small_batch/train'
test_images_path = 'C:/Users/user/Desktop/Projects/DattNet/data/coco-2017/small_batch/test'
transform = transforms.Compose([transform... | The function either generates or loads pre-saved training/test data loaders based on the 'generate' flag, using parameters like batch size, image width, and pattern configurations. It measures and returns the time taken for generation/loading, along with data loaders and pattern information. | def get_data(generate, log_path, batch_size, pic_width, prc_patterns, m_patterns, num_train_samples, num_test_samples):
train_set_file_name = f"train_loader_bs{batch_size}_pw{pic_width}_mp{prc_patterns}.pickle"
test_set_file_name = f"test_loader_bs{batch_size}_pw{pic_width}_mp{prc_patterns}.pickle"
if gene... |
def define_m_random_patterns(pic_width, m):
""" define the light patterns"""
patterns = [np.random.rand(pic_width, pic_width) for i in range(m)]
return patterns
def generate_data(train_data, test_data, pic_width, m_patterns, batch_size, patterns):
""" Get set of images and return simulated detector data... | The function generates or loads mock image data for training and testing, based on the 'generate' flag. It creates synthetic image tensors, constructs data loaders, and saves/load them as pickle files. The task includes timing data generation/loading, returning loaders, time message, and patterns. Parameters define fil... | def get_mock_data(generate, log_path, batch_size, pic_width, prc_patterns, m_patterns):
train_set_file_name = f"mock_train_loader_bs{batch_size}_pw{pic_width}_mp{prc_patterns}.pickle"
test_set_file_name = f"mock_test_loader_bs{batch_size}_pw{pic_width}_mp{prc_patterns}.pickle"
if generate:
start = t... |
def parameters_initialization(input_unit, hidden_unit, output_unit):
W1 = np.random.randn(hidden_unit, input_unit)*((2/hidden_unit)**0.5)
b1 = np.zeros((hidden_unit, 1))
W2 = np.random.randn(output_unit, hidden_unit)*((2/hidden_unit)**0.5)
b2 = np.zeros((output_unit, 1))
parameters = {"W1": W1,
... | This function trains a simple neural network with one hidden layer to minimize the mean squared error (MSE) between predicted and actual outputs. It initializes parameters, iteratively performs forward and backward propagation, updates weights using gradient descent, and optionally prints training and validation costs ... | def neural_network_model(X, Y, hidden_unit, num_iterations = 1000, verbose=True):
input_unit = 1
output_unit = 1
parameters = parameters_initialization(input_unit, hidden_unit, output_unit)
W1 = parameters['W1']
b1 = parameters['b1']
W2 = parameters['W2']
b2 = parameters['b2']
... |
def get_selected_shots_and_colours(self):
# get the ticked shots
ticked_shots = {}
for i in range(self.shot_model.rowCount()):
item = self.shot_model.item(i, SHOT_MODEL__CHECKBOX_INDEX)
colour_item = self.shot_model.item(i, SHOT_MODEL__COLOUR_INDEX)
shutter_it... | This function updates plots based on selected shots by adjusting the x-axis range, managing plot visibility, adding/removing data items and shutter markers, and creating new plots for enabled channels. It ensures plots reflect current selections, scales axes appropriately, and handles resampling triggers. | def update_plots(self):
# get list of selected shots
ticked_shots = self.get_selected_shots_and_colours()
# SHould we rescale the x-axis?
# if self._hidden_plot[0].getViewBox.getState()['autoRange'][0]:
# self._hidden_plot[0].enableAutoRange(axis=pg.ViewBox.XAxis)
# e... |
def _update_non_linear_time(self, changed_shot=False):
old_scalerhandler = self.scalehandler
marker_index = self.ui.markers_comboBox.currentIndex()
shot = self.ui.markers_comboBox.itemData(marker_index)
if shot is not None and self.scale_time:
self.scalehandler = shot.scaleha... | The main task of the code is to update visual markers on two plots by removing existing lines, retrieving selected markers from a combo box, and adding new dashed lines with colors, labels, and time deltas. It sorts markers by time, applies scaling if enabled, formats labels, and updates plots for accurate visualizatio... | def _update_markers(self, index):
for line, plot in self.all_marker_items.items():
plot.removeItem(line)
self.all_marker_items = {}
marker_index = self.ui.markers_comboBox.currentIndex()
shot = self.ui.markers_comboBox.itemData(marker_index)
self.all_markers = shot.m... |
def int_to_enum(enum_list, value):
"""stupid hack to work around the fact that PySide screws with the type of a variable when it goes into a model. Enums are converted to ints, which then
can't be interpreted by QColor correctly (for example)
unfortunately Qt doesn't provide a python list structure of enu... | This method handles user interactions with a shot model's checkbox, color, and shutter columns. When a shot's checkbox is toggled, it updates the color display, enables/disables combo box entries, and adjusts shutter settings. If the color column changes, it updates plot visuals. If the shutter column changes, it trigg... | def on_shot_selection_changed(self, item):
if self.shot_model.indexFromItem(item).column() == SHOT_MODEL__CHECKBOX_INDEX:
# add or remove a colour for this shot
checked = item.checkState()
row = self.shot_model.indexFromItem(item).row()
colour_item = self.shot_mo... |
def is_valid_file(parser, arg, var):
if not os.path.exists(arg):
parser.error("argument %s: The file %s does not exist!" % (var, arg))
else:
return arg
def check_values(val, minval, maxval, parser, var):
value = float(val)
if value < minval or value > maxval:
parser.error(
... | The code defines a function to parse command-line arguments for a tool tracking duplicates in taxonomic/functional references. It uses argparse to handle required inputs like duplicate files and optional parameters for BAM/BLAST/LCA files, ANI thresholds, memory sorting, threads, and output files. The function validate... | def get_arguments(argv=None):
parser = argparse.ArgumentParser(
description="A simple tool to track duplicates on taxonomic and functional references.",
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
# parent_parser = argparse.ArgumentParser(add_help=False)
required = parser.a... |
def parse_args(argv):
if len(argv) == 1: # running with no arguments
return (1*RES, 1*RES, 0), (9*RES, 9*RES, 0), 5, 10, 0.1, True
elif len(argv) > 9: # Input from launch file
argv = [float(i) for i in argv[:8]]
start = (argv[0]*RES, argv[1]*RES, argv[2])
goal = (argv[3]*RES, ar... | The code sets up a motion planning environment by parsing input parameters, configuring obstacle maps, validating start/goal positions, and initializing visualization. It prepares for pathfinding using a motion model and grid-based exploration, with optional plotting of obstacles and execution of the application logic ... | def main(argv=[]):
global width, height, obs, conf, ax, mm
global RES, STEP_SIZE, ROBOT_RADIUS, CLEARANCE, GOAL_RADIUS, PLOT
RES = 20 # parts per meter
start, goal, rpm1, rpm2, clearance, PLOT = parse_args(argv)
GOAL_RADIUS = round(0.25 *RES)
ROBOT_RADIUS = round(0.2 *RES)
CLEARANCE =... |
def _get_path(self, image_name: str, subdirectory: str = "") -> str:
"""
Checks if file with name exists at directory. Returns path to file.
"""
# Builds directory from subdirectory
directory = f"assets/{subdirectory}"
# Appends filetype to image name
image_file =... | This code initializes a Pygame window for displaying a piano. It loads the piano image to determine dimensions, calculates the window width based on the number of octaves, sets up the display with the computed size, adds a title and icon, and clears the window to prepare for drawing the piano. | def __init__(self) -> None:
# Acquires sizes from image
with image_data.open(self._get_path("piano")) as image:
self.piano_width, self.window_height = image.size
# Creates window width from number of octaves
self.window_width = self.piano_width * NUM_OCTAVES
# Sets a ... |
def ExtractUnnecessaryWords(setOfWords, printToWindow = False):
# This method extracts unnecessary words from an input set and returns the remaining words as a TextBlob object
if printToWindow:
print("Parts of speach for each word: " + str(setOfWords.tags))
extraWords = [word for word, tag in setOf... | The code defines a chatbot function that processes user input by removing unnecessary words, calculates similarity between the input and predefined questions using TextBlob, applies a threshold to determine relevance, and returns the best-matching answer from a list based on similarity scores. | def SentenceSimilarityChatBot(msg, answerList, questionList, wordTupList, uniqueWordSums, thresholdLearner ):
printToWindow = True
response = ''
newMsg = TextBlob(msg) #convert the input string to TextBlob
newMsg = ExtractUnnecessaryWords(newMsg) # remove unnecessary words from the message
similar... |
def pullData(FTP_HOST, FTP_USER, FTP_PASS, SERVER_NUM):
my_tz = pytz.timezone("US/Pacific")
now = datetime.now(my_tz)
Fdate = now.strftime("%Y%m%d")
logging.info(
"[DOWNLOAD_INFO] Attempting to download from server:"
+ str(SERVER_NUM)
+ " at "
+ str(now)
)
print(... | The main task of the code is to pull data from three FTP servers using environment variables, clean the data, validate its consistency, and upload the processed data. If validation fails, it logs an error and exits; if corrections are needed, it logs a warning. The validated data is then combined and processed into a m... | def main():
load_dotenv()
# Get the environment variables
df_server1 = pullData(
os.getenv("FTP_HOST_1"),
os.getenv("FTP_USER_1"),
os.getenv("FTP_PASS_1"),
1,
)
df_server2 = pullData(
os.getenv("FTP_HOST_2"),
os.getenv("FTP_USER_2"),
os.geten... |
def clearSelection(self):
self.selectedFeatures.clear()
self.rubberBands.clear()
self.selectionRubberBand.reset(True)
def selectFeaturesInRect(self):
vlayer = self.currentVectorLayer()
pt1 = self.toMapCoordinates(self.selectionRect.topLeft())
pt2 = self.toMapCoordinates(s... | This method handles mouse release events to select vector features on a map canvas. It distinguishes between right-click (clear selection) and left-click/drag operations. For dragging, it defines a rectangular selection area, while single clicks select individual features. It updates visual rubber bands for selected fe... | def canvasReleaseEvent(self, e):
if e.buttons() == Qt.RightButton:
self.clearSelection()
return
vlayer = self.currentVectorLayer()
if e.button() != Qt.LeftButton or not vlayer:
return
self.selectionRubberBand.reset(True)
if self.isDra... |
def __TT_comb(self,vars_list):
coloumns = len(vars_list)
rows = 2**coloumns
TT = []
ones_zeros_no = 1
for i in range(coloumns):
col = []
for j in range(int(rows/(2*ones_zeros_no))):
for k in range(ones_zeros_no):
col.append('F')
... | The main task of the code is to generate a truth table for a logical expression by substituting variables, solving each boolean function result, and formatting outputs as 'T'/'F' with reversed variable order. It processes input variables and a string expression, computes truth values, and returns modified variables and... | def Parser_Output(self,string,vars):
TT = self.__TT_comb(vars)
sub_TT = self.__TT_Substitute(string,TT,vars)
TT_OUT = []
for v in sub_TT:
TT_OUT.append(self.__Boolean_Function_Solve(v))
vars.reverse()
for i in range(0,len(TT_OUT)):
if TT_OUT[i]:
TT_OUT[i... |
def __vars_list(self,string):
open_bracket = 0
close_bracket = 0
vars = []
for i in string:
if i == '(':
open_bracket = open_bracket + 1
elif i == ')':
close_bracket = close_bracket + 1
if open_bracket == close_bracket:
flag_brackets = 1
... | This function checks the validity of variables and boolean expressions in a given string. It verifies bracket correctness, variable naming rules, and expression syntax. Returns flags for validation success/failure, error messages, variable lists, and the original string for GUI feedback. | def GUI_check(self,string):
vars,flag_barckets = self.__vars_list(string)
Correct_flag = 0
error_list_names = []
error_list_names_cuz = []
expr_flag = 0
if flag_barckets:
Correct_flag,error_list_names = self.__vars_names_checks(vars)
if Correct_flag:
try... |
def checkMonitor():
time.sleep(0.5)
print('\nHARDWARE MONITOR:')
ser.timeout = 1
sendRequestStatus()
time.sleep(0.5)
readSerial(11)
print()
def outOfBoundsRun():
global ser
global oobDetected
global oobMessageSentTime
cycle = 0;
success = True
while cycle < 6:
... | The main task of the code is to execute and verify test cases (outOfBoundsRun, pingRun) by running them, checking their results, and printing "SUCCESS" or "FAIL" accordingly. The code also calls checkMonitor() before and after each test to monitor system status, ensuring tests are run in a controlled environment and ou... | def main():
print('Referee started')
checkMonitor()
print()
print('OUT OF BOUNDS RUN')
print('SUCCESS' if outOfBoundsRun() else 'FAIL')
print()
checkMonitor()
print()
print('PING RUN')
print('SUCCESS' if pingRun() else 'FAIL')
print()
checkMonitor()
print()
... |
def calc_ym(xi, demand):
ym = []
for i in range(len(xi)):
ym[i] = xi[i] - demand[i]
return ym
def calculate_objective_function(p: list, z_x: list, z_d: list, alpha: float,
c: np.ndarray, k: np.ndarray, ym: np.ndarray,
m_penalty: np.nd... | The code implements a simulated annealing algorithm to optimize a solution (xi, kn) by iteratively generating new solutions, evaluating their objective function (costs, penalties), and updating the best solution (incXi, incKn) based on temperature (T) cooling. The process initializes with an initial solution, reduces T... | def simulatedAnnealing(xi, kn, m, k, alpha, T, beta, volume, demand, p, kioskVolume, kioskCost, penalty, f):
ym = calc_ym(xi, demand)
print("Initial Solution")
print("xi: ", xi, "kn: ", kn, "z = ", calculate_objective_function(p, xi, demand, beta, kioskCost, kn, ym, penalty))
#initialize incum... |
def get_temp_email():
return get_email()
def get_random_user_cred():
username=getRandomUserName(10)
return [username,getRandomPassword()]
def email_activation(email):
try:
link=get_activation_link(email)
return link
except Exception as e:
print(e) | The main task of the code is to automate user registration on a website by generating temporary credentials, filling out a sign-up form with random data, handling email activation via a temporary email service, and returning the created username and password for later use. | def sign_up(browser):
email=get_temp_email()
[username,password]=get_random_user_cred()
print(username,email,password)
sleep(2)
browser.get("https://www.eporner.com/")
browser.find_element(By.CSS_SELECTOR, "#headmenu > a:nth-child(2)").click()
time.sleep(4)
browser.find_element(By... |
def insert_token(mutation_path, token_w2i, gen, logger):
logger.info('inserting ...')
name = os.path.split(mutation_path)[1].split('.sol')[0]
addr = name.split('__')[0]
repair_dir = 'dataset_vul/newALLBUGS/validation/genetic/{}/{}/'.format(addr, gen)
preceding, following, _ = finds(mutation_path)
... | The function `mutation_token` orchestrates multiple code mutation strategies by invoking sub-functions to insert, replace, and move tokens/lines within a given codebase. It utilizes word-to-index (`code_w2i`) and index-to-word (`code_i2w`) mappings for token manipulation, alongside a generator (`gen`) and logger (`logg... | def mutation_token(mutation_path, code_w2i, code_i2w, gen, logger):
insert_token(mutation_path, code_w2i, gen, logger)
replace_token(mutation_path, code_w2i, gen, logger)
move_line(mutation_path, gen, logger)
insert_move_token(mutation_path, code_w2i, gen, logger)
replace_move_token(mutation_path, c... |
def diplomacy_read(s):
"""
read a list of string
in a list
return every input line has three elements separated by spaces: an army, a location, and an action.
return a list of all inputs, representing all of the inputs
"""
s = s.read()
a = s.split("\n")
return a
def diplomacy_eval(i... | This code processes input by reading data from a reader, evaluating it, and writing the result to a writer. The main task is to perform a diplomacy-related computation, where input is read, evaluated, and output is generated for a diplomatic scenario or simulation. | def diplomacy_solve(r, w):
"""
r a reader
w a writer
"""
i = diplomacy_read(r)
v = diplomacy_eval(i)
diplomacy_print(w, v) |
def isValid(move, board):
try:
if board[move] != OUTER:
return True
except:
if type(move) != 'int':
print('Please input an integer value')
else:
print('Out of bounds selection')
return False
def isLegal(move, player, board):
#Create a list ... | The function `getMove` handles human input for selecting a valid game move. It prompts the player to enter a tile number, validates the input, checks if the move is legal, and recursively re-prompts on errors. For non-human strategies (bots), it returns `None`. The core task is to ensure human players input a valid, le... | def getMove(strategy, player, board):
if player == WHITE:
playerS = 'WHITE'
else:
playerS = 'BLACK'
if strategy == 'human':
try:
move = int(input('Please input a number for a tile, '+playerS+'\n>>'))
except KeyboardInterrupt:
sys.exit(0)
except... |
def minimaxLegalMoves(self, player, board):
valids = []
for i in range(len(self.SQUARE_WEIGHTS)):
if i < 11 or i > 88:
valids+=[False]
else:
if isLegal(i, player, board):
valids+=[True]
else:
... | This function implements the Minimax algorithm to determine the optimal move for a player in a board game. It recursively evaluates possible moves up to a specified depth, considering opponent responses. The algorithm selects the move with the highest evaluation value, using randomness to break ties. It returns the bes... | def minimax(self, player, board, depth=0, evaluate=None, moves=None): #Def
if depth == self.MAX_DEPTH: #Limits searching to avoid spending too much time calculating game states
#print('DOA')
return evaluate
else:
copy = list(board)
num = 0
if ... |
def get_device_id():
return app.config["DEVICE_ID"]
def get_config():
ret = parse_current_config()
return Response(dumps(ret), mimetype="application/json") | The function `connect()` initializes and connects a device source if not already configured. It checks if `DEVICE_SOURCE` is absent in `app.config`, then creates it using `get_source()` with parameters like `device_id`, `DATA_SOURCE`, and `MODE`. It updates the device source's configuration and establishes a connection... | def connect():
if app.config.get("DEVICE_SOURCE", None) is None:
app.config["DEVICE_SOURCE"] = get_source(
app.config,
device_id=get_device_id(),
data_source=app.config["DATA_SOURCE"],
source_type=app.config["MODE"],
)
app.config["DEVICE_SOU... |
def disconnect():
if app.config.get("DEVICE_SOURCE", None) is not None:
app.config["DEVICE_SOURCE"].disconnect()
app.config["DEVICE_SOURCE"] = None
print("Disconnected from device.")
return get_config()
def cache_config(config):
tmp = {
"CONFIG_SAMPLE_RATE": config["CONFI... | The main task of the code is to handle a POST request for configuring device settings. It updates the application's configuration with baud rate, source type, and mode from a form, connects to the specified device, caches the configuration, and returns the current configuration as a JSON response. The function manages ... | def config():
form = DeviceConfigureForm()
if request.method == "POST":
disconnect()
if (
form.data.get("baud_rate", None) is not None
and form.data["source"].upper() == "SERIAL"
):
app.config["BAUD_RATE"] = form.data["baud_rate"]
source = g... |
def parse_asn(data: bytes, offset=0, limit=-1):
items = []
if len(data) == 0 or limit >= 0 and offset >= limit:
return items
current_limit = limit
if current_limit < 0:
current_limit = len(data)
current_offset = offset
while current_offset < current_limit:
(tag, constr... | The code exports a symmetric key using TR-34 standards, verifies its authenticity via ASN.1 structure parsing, decrypts the key block with an ephemeral RSA key, and validates integrity checks (nonce, digest, certificate IDs). It handles AWS KMS key management, generates cryptographic certificates, and returns the key’s... | def exportKey(keyArn, region):
apc_client = boto3.client('payment-cryptography', region_name=region)
OID_MGF1 = bytes.fromhex('2A864886F70D010108')
OID_SHA256 = bytes.fromhex('608648016503040201')
OID_PKCS7_DATA = bytes.fromhex('2A864886F70D010701')
OID_RSAES_OEAP = bytes.fromhex('2A864886F70D010... |
def course_len(course_start, course_end):
'''
Return the duration of a course, in number of whole weeks.
Note: Final week may be less than 7 days, depending on course start and end dates.
:param course_start: datetime object for first day of course (generated from user input)
:param course_end: da... | The function `extract_all_clickstream_features` processes a Coursera clickstream file to extract three user activity metrics—forum views, active days, and quiz interactions—in a single pass. It initializes data structures to track weekly activity per user, processes each clickstream line to categorize events (using reg... | def extract_all_clickstream_features(coursera_clickstream_file, users, course_start, course_end):
"""
Extract active days, forum views, and quiz views in a single pass.
:return:
"""
# initialize all data structures
n_weeks = course_len(course_start, course_end)
forum_output = {user: {n: [] ... |
def fetch_start_end_date(course_name, run, date_csv = "coursera_course_dates.csv"):
"""
Fetch course start end end date (so user doesn't have to specify them directly).
:param course_name: Short name of course.
:param run: run number
:param date_csv: Path to csv of course start/end dates.
:retu... | The main task of the code is to process clickstream data from a course session to extract user features and dropout patterns. It identifies the relevant clickstream file, fetches course dates, extracts user activity data, generates features, and outputs weekly CSV files and a user dropout summary to the '/output' direc... | def main(course_name, run_number):
session_dir = '/input/{0}/{1}/'.format(course_name, run_number)
clickstream_file = [x for x in os.listdir(session_dir) if x.endswith('clickstream_export.gz')][0]
clickstream_fp = os.path.join(session_dir, clickstream_file)
OUTPUT_DIRECTORY = '/output'
course_start,... |
def get_computer_choice():
rps_input = ['Rock', 'Paper', 'Scissors']
computer_choice = random.choice(rps_input)
print(computer_choice)
return computer_choice
def get_user_choice():
user_choice = get_prediction()
print ("User Choice ", user_choice)
return user_choice
def get_winner (computer_... | The main task of the code is to simulate a game where the computer and user play rounds until one reaches 3 wins. The loop continues until either computer_wins or user_wins reaches 3, then it prints the winner. The function orchestrates rounds by getting choices, determining winners, and declaring the final result. | def play():
while computer_wins < 3 and user_wins < 3:
computer_choice = get_computer_choice()
user_choice = get_user_choice()
get_winner(computer_choice,user_choice)
if computer_wins == 3:
print('computer wins')
else:
print('User wins') |
def loadConfig(self, path):
self.config = Config(path)
def initializeDatabaseThread(self):
self.t_db = DatabaseThread(self.config.get('database'))
self.t_db._MASTER = self
self.t_db.start()
def initializeIOThread(self):
self.t_io = IOThread()
self.t_io._MASTER = self
... | The code initializes and runs a Radio Logger application by loading configuration, starting database, I/O, station, and watchdog threads, then entering a main loop. It handles graceful shutdown on user interruption, logging status and operating in daemon mode if enabled. | def run(self):
try:
self.info('Radio Logger v{} starting...'.format(self._VERSION))
if self.IS_DAEMON:
self.info('Running in daemon mode.')
self.loadConfig(path.join(self.BASE_DIR, 'config.json'))
self.initializeDatabaseThread()
self.... |
def configure_namenode_hadoop(Type):
# if Type == 1:
# ip = '192.168.43.194'
#else:
ip = '0.0.0.0'
sleep(1)
os.system('tput setaf 3')
sb.call("echo '[Namenode]'", shell=True)
sb.call("echo 'Configuring hdfs-site.xml file...'", shell=True)
file_handeling('/etc/hadoop/hdfs-site.xml', '0.0.0.0', True)
sleep(1)... | The main task of the code is to provide a menu-driven interface for configuring Hadoop components (Namenode, Datanode, cluster) and managing operations like generating reports. It repeatedly displays options, accepts user input, and executes corresponding Hadoop setup or diagnostic commands, with an exit option to retu... | def hadoop():
while True:
os.system('tput setaf 10')
print("""
-----------------------------------------------------
Hadoop:
-----------------------------------------------------
1. Configure Hadoop Namenode
2. Configure Hadoop Datanode
3. Configure the Whole Cluster
4. Show Report
5... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.