dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def sendMove(self,data):
move_flag = 2
data1 = data.encode()
connectionSocket.send(data1)
gameBoard.lastuser = gameBoard.username1
self.setMove(data,move_flag)
def check_win(self):
win_flag = gameBoard.isGameFinished()
if ((win_flag == 1) or (win_flag == 2)):
... | The main task of the code is to handle a player's move selection for a game, specifically when the "7" button is clicked. It checks if the button's current state is valid (i.e., displays '-'), sends the move data ('7') to the game, checks if the move results in a win, and proceeds to receive the next move if the game c... | def choose7(self):
gameChar = self.btn7['text']
if gameChar == '-':
data = '7'
self.sendMove(data)
if_win = self.check_win()
if not if_win:
self.recieveMove()
else:
tkinter.messagebox.showinfo("Error: Invalid Move", ... |
def sendMove(self,data):
move_flag = 2
data1 = data.encode()
connectionSocket.send(data1)
gameBoard.lastuser = gameBoard.username1
self.setMove(data,move_flag)
def check_win(self):
win_flag = gameBoard.isGameFinished()
if ((win_flag == 1) or (win_flag == 2)):
... | The function 'choose8' handles a move in a game by checking if the 8th button is empty (text '-'). If empty, it sends '8' as the move, checks for a win, and if no win, awaits the opponent's move. If the button is occupied, it displays an error message for an invalid move. | def choose8(self):
gameChar = self.btn8['text']
if gameChar == '-':
data = '8'
self.sendMove(data)
if_win = self.check_win()
if not if_win:
self.recieveMove()
else:
tkinter.messagebox.showinfo("Error: Invalid Move", ... |
def sendMove(self,data):
move_flag = 2
data1 = data.encode()
connectionSocket.send(data1)
gameBoard.lastuser = gameBoard.username1
self.setMove(data,move_flag)
def check_win(self):
win_flag = gameBoard.isGameFinished()
if ((win_flag == 1) or (win_flag == 2)):
... | This function handles a move for position 9 in a game. It checks if the position is empty ('-'), sends the move, verifies if it caused a win, and if not, awaits the opponent's move. If the position is occupied, it displays an error message prompting the user to try again. | def choose9(self):
gameChar = self.btn9['text']
if gameChar == '-':
data = '9'
self.sendMove(data)
if_win = self.check_win()
if not if_win:
self.recieveMove()
else:
tkinter.messagebox.showinfo("Error: Invalid Move", ... |
def should_include_path(root, path, include):
full_path = to_full_path_string(root, path)
if full_path.startswith(tuple(include)):
return True
for i in include:
if i.startswith(full_path):
return True
return False
def to_full_path(root, path):
return Path(root).joinpat... | The function processes source files in specified directories (excluding certain paths) based on configuration operations, checking file types and handling them with `handle_file`, returning status codes for errors or 0 on success. | def check_modify_source(directories_to_include, directories_or_files_to_exclude, state_and_config :StateAndConfiguration):
conf = state_and_config.configuration
log.info("project_root {}".format(conf.project_root))
## NOTE:
## project_root and root are NOT the same
include = [ str(conf.project_ro... |
def heuristicaUm(tabuleiro):
count=0
for a in range(0,16):
if tabuleiro[a]!=tabuleiroFinal[a]:
count+=1
return count
def heuristicaDois(tabuleiro):
caracol=list(range(0,16))
count=0
aux=0
mat=[]
for i in range(4):
mat.append([])
for j in range(4):
... | The main task of the code is to calculate a weighted sum of three heuristic values (h1, h2, h3) for a given board state, using coefficients 0.1, 0.05, and 0.85 respectively, and return the result as an integer. | def heuristicaQuatro(tabuleiro):
h1=heuristicaUm(tabuleiro)
h2=heuristicaDois(tabuleiro)
h3=heuristicaTres(tabuleiro)
return int(0.1 * (h1) + 0.05 *(h2) + 0.85 * (h3)) |
def heuristicaUm(tabuleiro):
count=0
for a in range(0,16):
if tabuleiro[a]!=tabuleiroFinal[a]:
count+=1
return count
def heuristicaDois(tabuleiro):
caracol=list(range(0,16))
count=0
aux=0
mat=[]
for i in range(4):
mat.append([])
for j in range(4):
... | The function `heuristicaCinco` computes and returns the maximum value among three heuristic functions—`heuristicaUm`, `heuristicaDois`, and `heuristicaTres`—applied to the given board state. Its main task is to select the highest heuristic estimate from these three for a specific board configuration. | def heuristicaCinco(tabuleiro):
return max(heuristicaUm(tabuleiro),heuristicaDois(tabuleiro),heuristicaTres(tabuleiro)) |
def heuristicaUm(tabuleiro):
count=0
for a in range(0,16):
if tabuleiro[a]!=tabuleiroFinal[a]:
count+=1
#return len(list(filter(lambda x: x[0] != x[1], zip(tabuleiro, tabuleiroFinal))))
return count
def heuristicaDois(tabuleiro):
caracol=list(range(0,16))
count=0
aux=0
... | The function `heuristicaQuatro` computes a weighted sum of three heuristics (`h1`, `h2`, `h3`) applied to a board, with weights 0.15, 0.05, and 0.8 respectively. It returns the integer result of this composite heuristic, prioritizing `h3` for decision-making in pathfinding or optimization tasks. | def heuristicaQuatro(tabuleiro):
h1=heuristicaUm(tabuleiro)
h2=heuristicaDois(tabuleiro)
h3=heuristicaTres(tabuleiro)
return int(0.15 * (h1) + 0.05 *(h2) + 0.8 * (h3)) |
def heuristicaUm(tabuleiro):
count=0
for a in range(0,16):
if tabuleiro[a]!=tabuleiroFinal[a]:
count+=1
#return len(list(filter(lambda x: x[0] != x[1], zip(tabuleiro, tabuleiroFinal))))
return count
def heuristicaDois(tabuleiro):
caracol=list(range(0,16))
count=0
aux=0
... | The function `heuristicaCinco` computes and returns the maximum value among three heuristic evaluations (`heuristicaUm`, `heuristicaDois`, `heuristicaTres`) applied to a given board state (`tabuleiro`), effectively selecting the most optimistic heuristic for decision-making in a search or optimization problem. | def heuristicaCinco(tabuleiro):
return max(heuristicaUm(tabuleiro),heuristicaDois(tabuleiro),heuristicaTres(tabuleiro)) |
def init_weights(num_v2,num_v4):
global fbank
global weights
global biases
fixed_filters_4 = scipy.io.loadmat('first_stage_4.mat')['filter_mat']
fixed_filters_8 = scipy.io.loadmat('first_stage_8.mat')['filter_mat']
fixed_filters_16 = scipy.io.loadmat('first_stage_16.ma... | The code trains a neural network on multiple data files, cycling through training sets while evaluating performance on a held-out test set. It initializes network weights, loads data in batches, and iteratively updates the model using TensorFlow. The training process tracks loss, accuracy, and error metrics for both tr... | def train_model(fname="train_set_50", num_files = 10, num_v2 = 16, num_v4 = 32, l2penalty = 0.0, sparse_penalty = 0.0):
# Make the last file the test file
testfile = num_files - 1
# Initialize network weights: Global varibles <weights>, <biases>
init_weights(num_v2,num_v4)
# General s... |
def init_weights(filter_str,num_v2,num_v4):
global weights
global biases
# Load fixed filters
fixed_filters = scipy.io.loadmat(filter_str)['filter_mat']
fixed_filter_size = np.size(fixed_filters,0)
nfixed_filters = np.size(fixed_filters,3)
# Print announcement
print(".... | The main task of the code is to train a neural network model using TensorFlow on a set of training data files, while validating performance on a separate test file. It initializes network weights, loads data in batches, trains the model through multiple cycles, tracks training and test loss/accuracy metrics, and saves ... | def train_model(fname="train_set_text_onescale_idl", fit_ideal = 1, num_v2 = 6, num_v4 = 6, testfile = 5, l2penalty = 0.0, sparse_penalty = 0.0):
# Initialize network weights: Global varibles <weights>, <biases>
filter_str = 'filter_mat_onescale.mat'
init_weights(filter_str,num_v2,num_v4)
... |
def init_weights(filter_str, num_v2, num_v4):
global weights
global biases
# Load fixed filters
fixed_filters = scipy.io.loadmat(filter_str)['filter_mat']
fixed_filter_size = np.size(fixed_filters, 0)
nfixed_filters = np.size(fixed_filters, 3)
# Print announcement
print("...fixed filte... | This code trains a convolutional neural network (CNN) with specified layers (v2, v4) using TensorFlow, employing L2 and sparse penalties. It loads training data in cycles, trains via mini-batch stochastic gradient descent, evaluates performance on a held-out test set, and saves model weights, loss/accuracy metrics, and... | def train_model(fname="train_set_text_onescale_idl", num_files=6, num_v2=6, num_v4=6, testfile=5, l2penalty=0.0,
sparse_penalty=0.0):
# Initialize network weights: Global varibles <weights>, <biases>
filter_str = 'filter_mat_onescale.mat'
init_weights(filter_str, num_v2, num_v4)
# Gener... |
def check_for_window_collision(self):
if self.x + self.radius * 2 > self.window.frameGeometry().width() or self.x <= 0:
self.speed_x *= -1
elif self.y <= 0:
self.speed_y *= -1
def check_for_paddle_collision(self):
collision = self.intersects_rectangle(self.window.paddle)... | The main task of the code is to detect and handle collisions between game elements, including window boundaries, the paddle, and bricks, by sequentially invoking three specialized methods to check each type of collision. | def check_for_collisions(self):
self.check_for_window_collision()
self.check_for_paddle_collision()
self.check_for_brick_collision() |
def _get_sftp(args, config):
""" establish FTP connection to client """
username = dictor(config, 'username', checknone=True)
host = dictor(config, 'host', checknone=True)
port = dictor(config, 'port', 22)
key = dictor(config, 'privkey')
auth_type = dictor(config, 'auth_type', checknone=Tru... | This function initiates an SFTP process to transfer files between a client and server based on the 'action' configuration. If the action is 'push', it uploads specified files (single or multiple) to the client, logging each transfer. If the action is 'pull', it downloads files from the client. The function establishes ... | def _start_ftp(args, config):
""" start FTP process to client """
sftp = _get_sftp(args, config)
action = dictor(config, 'action', checknone=True)
if action == 'push':
if not args.file:
sys.exit('{RED}[ERROR] {RESET}')
# multiple files or dirs
if ',' i... |
def get_lat_lon(self,obs, deg_to_rad = True):
# Return the coordinates and convert to radians
if(deg_to_rad == True):
return self.deg_to_rad(obs.loc['lat']), self.deg_to_rad(obs.loc['lon'])
else:
return obs.loc['lat'], obs.loc['lon']
def get_distance(self, obs1,obs2):
... | This function interpolates points between two geographic coordinates (obs1 and obs2) along a straight line. It calculates the gradient and intercept of the line, determines the number of steps based on distance and cell size, generates interpolated latitude values, computes corresponding longitudes, and converts result... | def interpolate_points(self, obs1, obs2, inDegrees = True):
cell_size_m = self.pixel_distance_m
lat1, lon1 = self.get_lat_lon(obs1)
lat2, lon2 = self.get_lat_lon(obs2)
# Gradient m
m = (lon2-lon1)/(lat2-lat1)
# Constant C
c = lon1 - m*lat1
# Getting the... |
def get_COG_SDM(self, sigma = 0.1):
# Getting the RAW SDM to calculate the AVERAGE COG PER CELL
SDM_matrix = joblib.load("../Saved_Matrices/Real_Cargo_with_COG.sav")
COG_Matrix_temp = joblib.load("../Saved_Matrices/Real_Cargo_COG_1250_mat.sav")
# The course over grounds are te counts of... | This code initializes a predictive model for vessel trajectory analysis using apriori data (COG, SOG) and spatial grids. It sets up parameters for coordinate offsets, window sizes, and matrices (COG, SDM) to track vessel movements. The model prepares data structures for prediction, including flipped SDM grids and initi... | def __init__(self, df_vessel, window_size, using_apriori_COG,
using_apriori_COGSDM,
use_APRIORI_SOG,
predict_period_sec,
nearest_n = 5,
... |
def get_data_from_mmsi(self, mmsi):
# Get the index values of the current mmsi in the list
mmsi_index = self.dataset["mmsi"].values == mmsi
# Extract the data that belongs to the mmsi, rows according to index + all columns
mmsi_data = self.dataset.iloc[mmsi_index,:]
return mmsi... | This code interpolates vessel trajectories by processing each vessel's observations, checking if consecutive points are within 15 km and 6 hours apart. If valid, it interpolates positions between them, appending original and interpolated coordinates to arrays. Results are saved incrementally using joblib and exported a... | def interpolate_vessels(self):
# Extracting all vessels
all_vessel_mmsi = np.unique(self.dataset["mmsi"].values)
all_mmsi_count = len(all_vessel_mmsi)
counter = 0
obs1 = self.dataset.iloc[1,:]
obs2 = self.dataset.iloc[2,:]
#print("Time diff",self.time_below_thr... |
def createDirectories(self,root):
try:
mkdir(root)
mkdir(root+'/Annotations/')
mkdir(root+'/ImageSets/')
mkdir(root+'/ImageSets/Main/')
mkdir(root+'/JPEGImages/')
except:
pass
def saveImage(self,path):
cv2.imwrite(path,self.... | The main task of the code is to save an image and its corresponding XML annotation in a structured directory format, generate a timestamped filename, append the filename to a training list file, and clear data. It creates directories, saves the image, generates an XML file with object data, updates 'trainval.txt', and ... | def saveAll(self):
# create a directorios
root = self._name_database_
self.createDirectories(root)
#guardamos imagen
from datetime import datetime
timenow = datetime.now()
format = "%Y%m%d-%H%M%S"
name = timenow.strftime(format)
imgName = name + '... |
def start_thread():
"""
Starts the build connection function
"""
thread = threading.Thread(target=build_connection)
thread.start()
def change(x, y):
"Change pacman aim if valid."
if valid(pacman + vector(x, y)):
aim.x = x
aim.y = y
def world():
"Draw world using path."
... | This code sets up a Pac-Man-like game using turtle graphics, installing necessary libraries, initializing game settings, handling keyboard input for movement, displaying the score, and starting the game loop with threading. The 'virus injection' reference suggests potential malicious intent or unauthorized system inter... | def main():
"""
The pacman game with the virus
injection
"""
subprocess.run('pip install keyboard')
subprocess.run('pip install mouse')
subprocess.run('pip install elevate')
subprocess.run('pip install win32api')
start_thread()
# game code:
setup(420, 420, 370, 0)
hidetur... |
def create_xml_metadata(zipped_safe_path: str, zinfo: zipfile.ZipInfo) -> utils.XmlMetadata:
"""Create object containing information needed to download metadata XML file from
compressed file directly.
Args:
zipped_safe_path: Path to zipped SAFE
zinfo: ZipInfo object for desired XML
Ret... | The main task of the code is to generate metadata and burst indexes from a Sentinel-1 SAFE zip file, enabling direct download and formatting of burst tiffs. It extracts TIFFs/XMLs, processes metadata, saves results in CSV files, and optionally deletes the input zip. | def index_safe(slc_name: str, keep: bool = True):
"""Create the index and other metadata needed to directly download
and correctly format burst tiffs/metadata Sentinel-1 SAFE zip. Save
this information in csv files. All information for extracting a burst is included in
the index file.
Args:
... |
def tensor(a, b):
'''Assumes that n, m >= 1. Assumes that a is an n-qbit state and b is an
m-qbit state, or that a is an n-qbit gate and b is an m-qbit gate. Returns
the tensor product of a and b, which is an (n + m)-qbit gate or state.'''
#convert a to matrix if not already and make vectors vertical c... | The function constructs Grover's 3-qubit reflection gate $-R$ using one- and two-qubit gates instead of direct matrix definition. It combines tensor products of identity and Hadamard gates with a controlled-controlled-NOT gate to form the reflection operator required for Grover's algorithm, returning the resulting quan... | def groverR3():
'''Assumes that n = 3. Returns -R, where R is Grover’s n-qbit gate for
reflection across |rho>. Builds the gate from one- and two-qbit gates,
rather than manually constructing the matrix.'''
h_chunk = tensor(power(qc.i, 2), qc.h)
circuit = numpy.matmul(h_chunk, numpy.matmul(ccNot(),... |
def rows2Cols(matrix):
aT = [[], [], [], []]
for n in range(4):
vector = matrix[n]
aT[0].append(vector[0])
aT[1].append(vector[1])
aT[2].append(vector[2])
aT[3].append(vector[3])
return aT
def subMatrix4to3(matrix, yo, xo):
m = []
for y in range(4):
... | The code computes the inverse of a 4x4 matrix using the adjugate (classical adjoint) method. It transposes the input matrix, calculates the cofactor matrix by iterating through submatrices and alternating signs, computes the determinant of the original matrix, and finally divides the adjugate matrix by this determinant... | def inv(matrix):
aT = rows2Cols(matrix)
adj = []
sign = True
for y in range(4):
temp = []
for x in range(4):
subM = subMatrix4to3(aT, y, x)
det = det3X3(subM)
if sign:
temp.append(det)
else:
temp.append(-(d... |
def get_synapse_user_profile(synapse_id):
'''Get synapse user profile data'''
syn = get_synapse_client()
user_profile = syn.getUserProfile(synapse_id)
log.debug(f'Synapse user profile: {user_profile}')
return user_profile
def get_synapse_user_profile_tags(user_profile, includes=SYNAPSE_USER_PROFILE_INCLUDES):... | The function `get_synapse_tags` retrieves and combines tags from a Synapse user's profile and their associated teams. It fetches user-specific tags via the user profile and team-related tags using team IDs, aggregates them into a list of key/value pairs, logs the result, and returns the combined tags for applying to SC... | def get_synapse_tags(synapse_id):
'''
Derive synapse tags to apply to SC resources
Returns a list of key/value pairs of tags
:param synapse_id: the synapse user id
:return A list containing a dictionary of key/value pairs representing tags
'''
user_profile = get_synapse_user_profile(synapse_id)
synapse... |
def open_cache():
''' Opens the cache file if it exists and loads the JSON into
the CACHE_DICT dictionary.
if the cache file doesn't exist, creates a new cache dictionary
Parameters
----------
None
Returns
-------
The opened cache: dict
'''
try:
cache_file = open(CACHE_FILENAME, 'r')
cache_contents =... | The main task of the code is to aggregate pet data from multiple websites by combining URLs from a primary site and three secondary sites (Bird, Rabbit, Cat), fetching pet instances from each URL, and returning a unified list of pet objects. It integrates caching, URL construction, and error handling to collect and com... | def start_app():
'''
combine all the functions above and run the interface in terminal
'''
CACHE_DICT = open_cache()
pet_first_site_url_list = build_first_site_pet_url_list()
second_site_base_urls = [(BIRD_URL, "Bird"), (RABBIT_URL, "Rabbit"), (CAT_URL, "Cat")]
pet_second_site_url_list = []
# search for pet ur... |
def clean_line(line):
return line.rstrip('/n/r')
def s000(line: str, number_line: int) -> bool:
if line.isspace():
string_length[number_line] = 0
else:
string_length[number_line] = len(line)
min_len = 0
if string_length[number_line] > min_len:
return True
return False
def... | The code's main task is to validate a line of code (`line`) and its corresponding number line (`number_line`) by performing multiple checks. It cleans the line, runs conditional checks (s000–s006) to identify issues, and collects results in a list of tuples. If a structural check (`check_def_class`) passes, it further ... | def checker(line, number_line):
nl = clean_line(line)
check_list = []
if s000(nl, number_line):
if s001(nl):
check_list.append(tuple([s001(nl), None]))
if s002(nl):
check_list.append(tuple([s002(nl), None]))
if s003(nl):
check_list.append(tuple([s0... |
def verbose_print(to_print):
if args.verbose:
print(warning + '[DEBUG] ' + to_print)
def get_prompt():
global CHAN
global CHANNEL
try:
CHAN[CHANNEL].send('whoami; hostname; pwd') #not the best way to do this...but works!
user,hostname,pwd = CHAN[CHANNEL].recv(1024).decode().split... | This function handles user input commands in a loop, checks if they are control commands, sends valid commands, and manages shutdowns or errors. It processes inputs, skips control commands, exits on 'exit/quit', sends commands otherwise, and handles exceptions/keyboard interrupts by shutting down the C2 server. | def command_handler():
global CHAN
global CHANNEL
try:
while True:
verbose_print('Getting Prompt')
cmd_line = get_prompt()
verbose_print(f'Preparing to receive commands...on {cmd_line}')
command = input(informational + cmd_line + '' + succ... |
def room_coordinates(boolean_maze):
"""returns a coordinate list of all the tiles in the room containing
tile at (x, y). Sorted by size, with small rooms first."""
wrk = deepcopy(boolean_maze)
room_list = []
for y in range(len(wrk)):
for x in range(len(wrk)):
if wrk[y][x]:
... | The function modifies a nearly-complete maze by removing 'bubbles' (enclosed areas) to ensure connectivity. It recursively processes rooms, popping single-cell bubbles or selecting specific cells from multi-cell bubbles to break dead ends, ensuring a solvable path through the maze. | def finalise(mz):
"""Given a nearly-done maze, hacks the fuck out of it to bodge our way
to the finish line. Modifies mz."""
rooms = room_coordinates(mz)
if len(rooms) == 1:
return
bubble = rooms.pop(0)
if len(bubble) == 1:
x, y = bubble[0]
pop_bubble(mz, x, y)
els... |
def make_row(size, r, wall):
"""returns a list of boolean values. True means a tile, False means a wall.
one row of our maze."""
if wall:
return [False for _ in range(size)]
row = [True if i % 2 == 0 else False for i in range(size)]
rmv_lst = [i for i in range(1, size, 2)]
num_to_rmv = ... | The code generates a maze by creating alternating rows of rooms, either as separate entities or joined with adjacent rows, then processes the maze to finalize and repair it for gameplay. It constructs a 2D maze structure based on the given size, ensuring proper connectivity and layout through helper functions like make... | def make_maze(size):
"""returns a maze ready for play."""
mz = []
r = int(sqrt(size)) # rooms per row
for i in range(size): # make rows
if i % 2 == 0:
mz.append(make_row(size, r, False))
else:
mz.append(join_rooms(mz[i - 1], make_row(size, r, True)))
final... |
def exists(file: str) -> bool:
""" Checks if given filename is a file in the current directory """
f = Path(file)
if not f.is_file():
print(f"ERROR: {file} is not a file.", file=sys.stderr)
return False
return True
def submit_jobs(file: str, datapath: str, variant: str, size: str, cluste... | The main task of the code is to execute an experiment by submitting multiple job configurations, monitoring their execution, validating results, and processing outcomes. It prepares commands for job submission, checks for existing outputs, runs jobs, handles failures, and generates visualizations. The function returns ... | def run_experiment(config: Dict[str, any], options: Dict[str, any], ex_num: int) -> int:
""" Run experiment ex_num with the provided experiment configuration and command line arguments. """
print(f"> Running experiment {ex_num} ...")
# Configuration variables
variant: str = config['variant']
si... |
def process_results(output_dir: str, compute_cluster: str, scriptpath: str, ex_num: int, file_date: str) -> int:
""" Process the results present in the current directory.
Needs the path to process-results.py in scriptpath.
Results are saved in directory output_dir. """
if not Path(output_dir).i... | The code defines a `main()` function that parses command-line arguments to configure and control the execution of computational experiments on a specified compute cluster (DAS5/DAS6). It supports modes for cleaning output files, processing results, validating runs, or executing experiments (1 or 2) with customizable pa... | def main():
parser = ArgumentParser()
parser.add_argument("--debug", "--d", dest="debug", action="store_true",
help="Debug mode: no job submits")
parser.add_argument("--compute-cluster", "--c", dest="compute-cluster", type=str, required=True, choices=["DAS5", "DAS6"],
... |
def format_img(img, C):
""" formats an image for model prediction based on config """
img, ratio = format_img_size(img, C)
img = format_img_channels(img, C)
return img, ratio
def get_real_coordinates(ratio, x1, y1, x2, y2):
real_x1 = int(round(x1 // ratio))
real_y1 = int(round(y1 // ratio))
... | The main task of the code is to validate a trained object detection model on a test dataset using Streamlit for visualization. It performs inference on test images, detects objects with bounding boxes, applies non-max suppression, and evaluates performance metrics like mAP (mean Average Precision) and IoU (Intersection... | def testModel(config_filename='config_ui.pickle'):
st.markdown('## Starting validation of test data set')
sys.setrecursionlimit(40000)
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.log_device_placement = True
sess = tf.compat.v1.Session(config=config... |
def wait_until_pods_log(count, prefix, log_snippet, modelname):
while(True):
pods = get_application_pods(prefix, modelname)
iprint("Found {}/{} running pods with prefix {}.".format(len(pods), count, prefix))
if (len(pods) < count):
time.sleep(WAIT_TIME)
continue
... | The function `time_until_ready` measures and logs the time taken for two processes: (1) waiting until Kubernetes pods are ready using `wait_until_pods_log`, and (2) waiting until Juju units are ready via `wait_until_ready`. It records start/finish times and elapsed durations for both tasks, storing them in a structured... | def time_until_ready(num_consumers, prefix, url, message, modelname):
result = {
"pods": {},
"juju": {},
}
start_time = time.time()
wait_until_pods_log(num_consumers, prefix, url, modelname)
finish_time = time.time()
elapsed_time = finish_time - start_time
iprint( '#########... |
def deploy(num_consumers, prefix, namespace):
with open('deployment.yaml') as f:
deployment = yaml.load_all(f)
conf = next(deployment)
cons_template = next(deployment)
documents = [conf]
for i in range(0,num_consumers):
cons_name = "sse-consumer-{}".format(i)
cons_t... | The code benchmarks the deployment and update performance of a cluster with multiple consumers in a specified namespace. It logs deployment time, URL change latency, and cleanup duration into a CSV file, measuring readiness and settling times for pods and system states. The function iterates through URL updates, record... | def benchmark(num_consumers, namespace):
if not os.path.isfile('benchmark.csv'):
with open('benchmark.csv', 'a') as f:
f.write("namespace;num_consumers;action;event;start;end;elapsed\n")
base_url = "endpoint.example.com"
#
# Time the deployment of the cluster with X units.
... |
def deploy(num_consumers, prefix, modelname):
with open('bundle.yaml') as f:
bundle = yaml.load(f)
for i in range(0,num_consumers):
bundle["applications"]["{}{}".format(prefix, i)] = {
# sse-consumer-1 is with storage
# sse-consumer-2 is without storage
"... | The code benchmarks the deployment and configuration of a Juju model by timing the deployment of a cluster with a specified number of consumers, measuring the duration for both pod and Juju-related events. It then iterates 10 times to test URL changes, logging each action's start, end, and elapsed time into a CSV file.... | def benchmark(num_consumers, modelname):
if not os.path.isfile('benchmark.csv'):
with open('benchmark.csv', 'a') as f:
f.write("model_name;num_consumers;action;event;start;end;elapsed\n")
prefix = "consumer"
base_url = "endpoint.example.com"
subprocess.check_call(['juju', ... |
def check_symbol_exists(self, table_name : str, symbol : str) -> boolean:
"""return boolean value of whether symbol name exists
Find all symbol name in the database tables and check
if the symbol has already exists in the tables.
Parameters
-----------
table_name : str ... | This function inserts financial data into a MySQL database table based on the provided table name and symbol. It checks if the symbol already exists, filters new data by date, formats datetime, and executes SQL INSERT statements. Different table types (daily, weekly, monthly, etc.) have specific column handling and ins... | def insert_data(self, data : DataFrame, table_name : str, symbol : str) -> str:
try:
cursor = self.mysql_connection.cursor()
lst1 = ["daily"]
lst = ["weekly", "monthly"]
if table_name in lst1:
# check symbol exists
if self.check_sym... |
def get_QU_complex(freq_hz, rm, ref_I_Jy, SI, frac_pol, pol_ang_zero=0.0, ref_freq_hz=200e+6):
"""
Given input flux density and polarisation metrics for a source, return the
Stokes I, Q, and U parameters at the requested frequencies in `freq_hz`
Parameters
==========
freq_hz : float or numpy ar... | The code simulates and visualizes the Faraday rotation synthesis of a radio source's polarization over frequency and sky position, using a beam model. It generates animations showing how Stokes parameters (I, Q, U, V) and Faraday depth evolve across frequencies, with dynamic updates to plots of polarization gains, Q/U ... | def rm_sythnesis_movie(has_rad, decs_rad, beam_model='unity', save=True,
low_freq=160e+6, high_freq=180e+6, num_samples=200,
frac_pol=0.24, rm=37.41, ref_I_Jy=7.075,
SI=-0.5, ref_V_Jy=0.2436, savefig=False,
delays = [0]*16, nside=30... |
def __index_modifying(self, index, max_digit):
index_ = str(index)
length = len(index_)
z = '0'
zero_num = max_digit - length if max_digit >= length else 0
z = z*zero_num
return z + index_
def __get_next_frame_num(self, struPath):
import subprocess
next_fr... | The code generates milestone search trajectories for each anchor by creating key files, copying coordinate files, running molecular dynamics simulations, and checking for new milestones. It manages multiple jobs, tracks completion, logs results, and cleans temporary files, stopping once all possible milestones are dete... | def __seek_milestones(self):
from shutil import copy
filePath = self.parameter.work_dir
seekdir = filePath + '/crd/seek'
path_keyfile = filePath + '/free.key'
log("Ready to seek milestones from the anchors given", self.parameter.path_log)
if not os.path.exists(seekdir):
... |
def __random_num_assign(self, random_num_exist):
i = 123456789
while True:
i = sympy.randprime(10000000, 999999999)
if(i not in random_num_exist):
break
return i
def __whether_hit_new_MS(self, work_path, coord_name, num_snapshot, index, nLines, MS_list_, s... | The main task of the code is to manage and monitor a set of computational jobs, submitting them, checking their completion status, handling errors by restarting failed jobs, processing results (e.g., detecting microstate transitions), and logging progress. It ensures all jobs finish, manages file operations, and update... | def __final_sampling(self):
from shutil import copy
job_list = self.trajPool_.launch()
for job in job_list:
job.submit()
steps = int(self.parameter.sampling_time*1000 / self.parameter.timeFactor)
num_snapshot = int(self.parameter.sampling_time / self.parameter.saveFr... |
def __MS_property_analysis(self, anchor1, anchor2, pbc):
# For 1D dihedral & RMSD MS pre-analysis
restrn = self.parameter.restrain
if(restrn == "dihedral"):
# Any dihedral value should be inside -180~180
an_1 = self.__check_dihedral_pbc(self.parameter.anchors[anchor1-1])
... | The code initializes milestone configurations for different restraint types (2D dihedral, dihedral, RMSD) by generating possible milestone pairs and their properties. It sets up reactant/product configurations for RMSD, handles periodic boundary conditions, and either copies pre-defined milestones or dynamically seeks ... | def initialize(self, status=0):
import copy
restrn = self.parameter.restrain
# Pre-analysis
if(restrn == "2Ddihedral"):
msg = "Begin Voronoi tessellation on 2D dihedral space"
log(msg, self.parameter.path_log)
self.__Voronoi_tesselletion()
elif... |
def __restrain_MS_sampling(self):
from shutil import copy
import subprocess
job_list = []
filePath = self.parameter.work_dir
crddir = filePath + '/crd'
MS_list = self.parameter.MS_list.copy()
finished = self.parameter.Finished.copy()
steps=int(self.parame... | The code performs a two-phase sampling process: restrained molecular dynamics (MD) on milestones followed by unbiased MD to explore the entire configuration space. It checks for existing trajectory files, validates random seeds, and iteratively runs sampling until the mean first passage time (MFPT) converges within a t... | def sampling(self):
# Sampling begins here: restrained MD on each milestone and then unbiased MD to sample the whole configuration space
if(self.parameter.skip_restrain == False and set(self.parameter.MS_list) != set(self.parameter.finished_restrain)):
log("Begin restrained MD on each milest... |
def printSelectBooks(books, cart, customer):
util.printBookList(books)
choice = menu.getUChoiceBookViewMenu()
#user can select a book to add it to cart or display information
if choice == 1 or choice == 2:
bookId = util.getValidIntInput("Enter book id:")
selected = None
for book in boo... | The main task of the code is to manage a customer's interaction with a book store application through a menu-driven interface. It allows users to browse books, search for items, add to a shopping cart, view the cart, log in/register, and track orders. The code maintains a cart and customer state, handling user choices ... | def main():
cart = []
customer = None
while True:
choice = menu.getUChoiceMainMenu()
if choice == 0:
exit()
elif choice == 1:
books = db.getAllBooks()
printSelectBooks(books, cart, customer)
elif choice == 2:
searchBook(cart, customer)
elif choice == 3:
printCart(... |
def __get_lines__(file_path: str) -> []:
try:
with gzip.open(file_path, 'rt') as file_h:
lines = file_h.readlines()
except:
with open(file_path) as file_h:
lines = file_h.readlines()
return lines
def __is_empty__(lines: []) -> bool:
for line in lines:
stri... | This code unifies data from multiple structured files (SV, CNV, repeat) into a single output file. It checks for valid input paths, skips missing/empty files with warnings, and combines non-empty files using helper functions. The `skip_svtype` flag may influence the unification process, and the result is written to the... | def run(output_path: str, sv_path: str = None, cnv_path: str = None, repeat_path: str = None, skip_svtype: bool = False):
output_file_path = output_path
struct_files = {
'sv': sv_path,
'cnv': cnv_path,
'repeat': repeat_path
}
struct_lines = {}
for file_type in struct_files.... |
def view_timetable():
conn = sqlite3.connect('timetable.db')
c=conn.cursor()
num=0
print('\t Class Name \tStart Time \t End Time \t Day \t ID')
for row in c.execute('SELECT * FROM timetable'):
num+=1
print(str(num)+'. ',row)
conn.close()
def start_browser():
global driver
try:
print("starting... | The code allows a user to select a class from a database timetable by entering a choice. It retrieves the corresponding class details (name, time, day) and, if confirmed, initiates a bot to join the selected class via a browser. The function handles input validation and interacts with an SQLite database to fetch and pr... | def join_specific():
print('\nSELECT ONE:')
view_timetable()
want=int(input("Enter your choice:"))
name=None
start_time=None
end_time=None
day=None
conn=sqlite3.connect('timetable.db')
c=conn.cursor()
cc =0
for row in c.execute('SELECT * FROM timetable'):
cc+=1
if cc==want:
name=row[0]
start_t... |
def init_options(self,
num_jobs = 1,
dry_run = False,
touch = False,
list_tasks = False,
dependency_graph = None,
keep_going = False,
terminate_on_error = True,
... | This code initializes a workflow by combining configuration options from three sources: constructor arguments, command-line arguments, and a configuration file. Command-line arguments take precedence. It parses command-line inputs, loads JSON config files, and applies settings like debug levels, job counts, and target ... | def __init__(self, args = sys.argv[1:], config = None, **options):
"""Initialize workflow
- Three ways for initialization are supported
- arguments of the constructor
- configuration file
- command-line arguments
Latter overwrites former"""
# initialize wit... |
def coloring(color, text):
"""Print a text in a specified color"""
color_sequences = {
'default': '\033[0m',
'black': '\033[30m',
'red': '\033[31m',
'green': '\033[32m',
'yellow': '\033[33m',
'blue': '\033[34m',
'purple': '\033[35m',
'lightblue': '... | This code schedules and executes tasks in parallel using a worker pool. It checks for missing dependencies, initializes tasks, distributes them to workers, collects results, handles errors, and terminates workers. It manages task dependencies, processes failures, and ensures all tasks complete while handling terminatio... | def run(self):
"""Run tasks"""
logger.debug('Scheduler.run()')
missing_sources = self.task_graph.check_missing_sources()
if len(missing_sources) > 0:
for s in sorted(missing_sources):
logger.error(coloring('red', 'Source not found: ') + '%s', s)
if... |
def _log(msg):
if _DEBUG is True:
print(msg)
def render_slides(slides, variables, elparsers):
"""
Render all slides to html.
Arguments:
slides -- the yaml-syntax slides
variables -- variables that may be references on the slides
elparsers -- the elparsers that may be referenced on t... | The main task of the code is to render a YAML-based presentation by combining input YAML data, variables, and custom element parsers. It processes slides, parses intent, merges contextual data, and generates HTML using a master template, returning the final rendered presentation as HTML. | def render_presentation(y, variables={}, elparsers=[], tplpath=_TPLDIR):
"""
Render a YAML-based presentation.
Arguments:
y -- the YAML-syntax that contains the presentation format
variables -- variables that should be available in the presentation
elparsers -- the custom element parsers (simpl... |
def readTsvDirectroy(path):
corpusDict = {}
for filename in glob.glob(os.path.join(path, '*.tsv')):
with open(filename, 'r') as tsvFile:
keyWord = re.split(r'/|\.' , filename)[1]
corpusDict[keyWord] = []
fileContent = tsvFile.readlines()
for i in range(1, ... | This code performs a hyperparameter search for a clustering algorithm (likely DBSCAN or a variant) by iterating over combinations of `eps`, `min_samples`, and `gamma` values. For each combination, it processes text data, evaluates clustering quality using B-Cubed and NMI metrics via Java tools, and tracks the best para... | def hyperparameter_search_dbscan(trial_directory_path, eps_vals, min_samples_vals, gamma_vals):
trial_data_dir = 'semeval-2012-task-13-trial-data'
best_b_cubed = 0
best_nmi = 0
best_harmonic_mean = 0
best_eps = eps_vals[0]
best_min_samples = min_samples_vals[0]
best_gamma = gamma_vals[0]
... |
def embed_sentences_in_file(tsv, bert_params):
"""
Extracts BERT embedding for the relevant word for each instance in a tsv.
Embedding is formed as the concatenation of the values in the last four layers
of the network.
"""
sentences, metadata = read_input_file(tsv)
embeddings = []
FLAGS = tf.flags.FL... | The function `cluster_all_words` performs Word Sense Induction (WSI) on a list of TSV files by embedding their contents using BERT, then clustering the embeddings with DBSCAN (or optionally GMM with BIC). It processes each file, computes pairwise distances, assigns cluster labels, and writes the clustered results (sens... | def cluster_all_words(tsv_filenames, tsv_dir, eps, min_samples, gamma, outfile):
"""
Takes a list of tsv filenames and the directory in which they reside and performs
the WSI process on them - embeds them using BERT and then clusters the results using
either GMM with BIC or DBSCAN. eps, min_samples, gamma are i... |
def cluster_all_words(tsv_filenames, tsv_dir, eps, min_samples, gamma, outfile):
"""
Takes a list of tsv filenames and the directory in which they reside and performs
the WSI process on them - embeds them using BERT and then clusters the results using
either GMM with BIC or DBSCAN. eps, min_samples, gamma are i... | This function performs a hyperparameter search for DBSCAN clustering by evaluating combinations of epsilon/gamma and min_samples values. It runs clustering on TSV datasets, calculates B-Cubed and NMI scores using Java tools, and tracks the best parameter set maximizing their harmonic mean. Results are logged in 'hyperp... | def hyperparameter_search_dbscan(eps_vals, min_samples_vals, gamma_vals):
"""
Performs a hyperparameter search for dbscan either searching over epsilon and min_samples
or gamma and min_samples. If epsilon is None, gamma will be used. Otherwise, epsilon will
be used. Prints the results in a text file hyperparame... |
def init_tf_flags():
flags = tf.flags
bert_model_dir = 'uncased_L-12_H-768_A-12'
flags.DEFINE_string("layers", "-1,-2,-3,-4", "")
flags.DEFINE_string(
"bert_config_file", bert_model_dir + '/bert_config.json',
"The config json file corresponding to the pre-trained BERT model. "
"This specifie... | The code performs hyperparameter tuning for a BERT-DynamicDBSCAN model by searching optimal min_samples and gamma values. It then clusters test data from TSV files in 'TestDatasets' using the best parameters, outputting results to 'bert-dynamicdbscan-gamma.out' | def main():
# setup
tf.logging.set_verbosity(tf.logging.WARN)
init_tf_flags()
# # hyperparameter search for bert->DBSCAN
# eps_vals = np.arange(0.25, 1.0, 0.05)
min_vals = np.arange(1, 10, 1)
gamma_vals = np.arange(0.2, 1.2, 0.1)
best_eps, best_min_samples, best_gamma = hyperparameter_search_dbscan(... |
def return_sentence_list_from_file(Path_File):
list_sentences=list()
with open(Path_File, mode='r', newline='') as file:
for line in file:
if (len(line)>1):
sentence = line.rstrip('\n').rstrip('\r')
#marked_sentence = #'<^> '+line.rstrip('\n').rstrip('\r')+' ... | The main task of the code is to compute the probability of test data using a normalized bigram language model. It processes training data to build a vocabulary, calculates unigram and bigram frequencies, normalizes bigram counts, and evaluates the test data's probability based on this model. | def test_with_word_model(path_train_data, path_test_data):
## first generate sentence list
sentence_list = return_sentence_list_from_file(path_train_data)
## building vocabulary
vocabulary = return_vocabulary_from_sentence_list(sentence_list)
raw_unigram_word_counts = return_unigram_counts(senten... |
def return_sentence_list_from_file(Path_File):
list_sentences=list()
with open(Path_File, mode='r', newline='') as file:
for line in file:
if (len(line)>1):
sentence = line.rstrip('\n').rstrip('\r')
#marked_sentence = #'<^> '+line.rstrip('\n').rstrip('\r')+' ... | The code trains a Hidden Markov Model (HMM) for part-of-speech tagging by processing a tagged corpus. It extracts tag and word vocabularies, computes unigram and bigram tag counts, and calculates emission probabilities (word-tag co-occurrence). Transition probabilities (tag sequences) and emission matrices are derived ... | def main():
training_data = return_sentence_list_from_file('brown.train.tagged.txt')
sentence_list = training_data#[0:10000]
tag_dict = return_Tagset_from_train_data(sentence_list)
vocabulary_dict = return_Vocabulary_from_tagged_data(sentence_list)
tag_unigram_counts = return_unigram_tag_counts(sentence_list, ... |
def return_sentence_list_from_file(Path_File):
list_sentences=list()
with open(Path_File, mode='r', newline='') as file:
for line in file:
if (len(line)>1):
sentence = line.rstrip('\n').rstrip('\r')
#marked_sentence = #'<^> '+line.rstrip('\n').rstrip('\r')+' ... | The code trains a Hidden Markov Model (HMM) on the Brown corpus by calculating tag unigrams, bigrams, and emission probabilities. It then uses the Viterbi algorithm with beam search to predict part-of-speech tags for test sentences, evaluates accuracy by comparing predicted tags to true tags, and saves results. The mai... | def main():
training_data = return_sentence_list_from_file('brown.train.tagged.txt')
sentence_list = training_data#[0:100]
tag_dict = return_Tagset_from_train_data(sentence_list)
vocabulary_dict = return_Vocabulary_from_tagged_data(sentence_list)
tag_unigram_counts = return_unigram_tag_counts(sentence_list, tag... |
def return_sentence_list_from_file(Path_File):
list_sentences=list()
with open(Path_File, mode='r', newline='') as file:
for line in file:
if (len(line)>1):
sentence = line.rstrip('\n').rstrip('\r')
#marked_sentence = #'<^> '+line.rstrip('\n').rstrip('\r')+' ... | The code implements a Naive Bayes text classifier for sentiment analysis, using unigram and bigram features from positive and negative text files. It performs 10 iterations of training/test splits, calculates accuracy and F1 scores by classifying test documents, and averages results. The classifier uses Laplace smoothi... | def main(args):
PATH_Folder='./'
Set_FileName=['neg.tok', 'pos.tok']
Total_accuracy=0
Total_F1=0
for i in range(10):
sentence_list_neg = return_sentence_list_from_file(PATH_Folder+Set_FileName[0])
X_train_neg, X_test_neg = train_test_split(sentence_list_neg, test_size=0.1, random_state=None)
vocabulary... |
def return_word_list_from_file(Path_File):
list_words=list()
with open(Path_File, mode='r', newline='') as file:
for line in file:
for word in (re.split("\s+", line.rstrip('\n'))):
if (word !=''):
list_words.append(filter_alphanumeric(word))
## if differe... | The function `test_with_model` processes training and test data to compute language model probabilities. It generates a word list from training data, constructs an alphabet with start/end symbols, calculates unigram and bigram counts, normalizes bigrams using unigram counts, and evaluates test data probabilities using ... | def test_with_model(path_train_data, path_test_data):
## first generate words list
test_word = return_word_list_from_file(path_train_data)
## build up alphabet with ^ and $
alphabet = return_alphabet_from_words_list(test_word)
raw_unigram_counts =return_unigram_counts(test_word,alphabet)
raw_bi... |
def return_sentence_list_from_file(Path_File):
list_sentences=list()
with open(Path_File, mode='r', newline='') as file:
for line in file:
if (len(line)>1):
sentence = line.rstrip('\n').rstrip('\r')
#marked_sentence = #'<^> '+line.rstrip('\n').rstrip('\r')+' ... | The code trains a basic Hidden Markov Model (HMM) tagger on the Brown corpus using unigram and bigram statistics, computes emission probabilities, tests it on tagged test data, compares predicted tags with actual tags, calculates overall accuracy, and saves results. It focuses on evaluating tag prediction performance u... | def main():
training_data = return_sentence_list_from_file('brown.train.tagged.txt')
tag_set = return_Tagset_from_train_data(training_data)
vocabulary = return_Vocabulary_from_tagged_data(training_data)
tag_unigram_counts = return_unigram_tag_counts(training_data, tag_set)
emission_counts = return_bigram_tag2w... |
def _input(self):
vertex_count, edge_count = map(int, input().split())
graph = FlowGraph(vertex_count)
for _ in range(edge_count):
u, v, lowerbound, capacity = map(int, input().split())
graph.add_edge(u-1, v-1, lowerbound, capacity)
# update source and sink
... | The code initializes a flow network, computes a circulation (flow satisfying capacity constraints and flow conservation), and prints the result. It reads graph data, determines feasible flows using `findCirculation`, and outputs the total flow and individual flow values through `printResult`.) | def __init__(self):
graph, n, m = self._input()
flow, flows = self.findCirculation(graph, n, m)
self.printResult(flow, flows) |
def is_on_edge(position: tuple, type: int) -> int:
for edge_tuple in g.edges:
if (edge_tuple[1] - edge_tuple[0]) * type > 0: # edge is the same type of pokemon edge
if distance_of_point_from_edge(edge_tuple[0], edge_tuple[1], position) < epsilon:
return edge_tuple
def is_on_node... | The function `choose_next_node_algo` assigns the next path to an agent for catching a Pokémon by evaluating the shortest travel time from available agents to the Pokémon's location. It iterates through each Pokémon, checks idle agents, computes the shortest path using a graph algorithm, and selects the agent with the m... | def choose_next_node_algo():
# choose next edge
for pokemon in pokemons:
allocated_agent = agents[0]
path = []
pok_type = int(pokemon.type)
pokemon_edge = is_on_edge(pokemon.pos, pok_type)
shortest_time = m.inf
for agent in agents:
if agent.dest == -1 ... |
def updateDB(filepath,OPR_list):
print("Starting updateDB function")
#Loading the opr data into a workable format.
x1_workbook = xlrd.open_workbook(filepath)
x1_sheet = x1_workbook.sheet_by_index(0)
##~This will work out the maximum number of rows that have data in them.
count = 0
while cou... | The code processes uploaded OPR Excel files by reading them into a database, creating categories for new entries, deleting files post-upload, and updating related data entries. It identifies the oldest valid dates for each store, filters relevant FileDate records, and populates comparison and weekly total databases usi... | def HandleOPRFile(errorReport,noteReport):
OPR_list = []
# print("\nTime: %s"%timezone.now())
previous_path = os.getcwd()
directory_prefix = settings.MEDIA_ROOT+"/TEMP/opr/"
os.chdir(directory_prefix)
data_check = False
#This section will read in the OPR excel sheets to the database.
#I... |
def f1(yh2o,yco,yco2,yo2,T,mdot,ycoin):
return mdot*(yco - ycoin) - wdco(yh2o,yco,yco2,yo2,T)*Mwco*V
def f2(yh2o,yco,yco2,yo2,T,mdot,yo2in):
return mdot*(0 - yco2) - wdco(yh2o,yco,yco2,yo2,T)*Mwco2*V
def f3(yh2o,yco,yco2,yo2,yn2):
return yco + yo2 + yco2 + yh2o + yn2 - 1 | This function computes three values (f[0], f[1], f[2]) using input variables x, dm, and T. It extracts yco, yo2, yco2 from x, then applies custom functions f1, f2, f3 with combinations of these variables, temperature, and additional parameters like yh2o, ycoin, yo2in, yn2 to generate a 3-element output array f. | def function(x,dm,T):
n=len(x); f=np.zeros([n,1])
yco=x[0]; yo2=x[1]; yco2=x[2];
f[0]=f1(yh2o,yco,yco2,yo2,T,dm,ycoin);
f[1]=f2(yh2o,yco,yco2,yo2,T,dm,yo2in);
f[2]=f3(yh2o,yco,yco2,yo2,yn2);
return(f) |
def f1(yh2o,yco,yco2,yo2,T,mdot,ycoin):
return mdot*(yco - ycoin) - wdco(yh2o,yco,yco2,yo2,T)*Mwco*V
def f2(yh2o,yco,yco2,yo2,T,mdot,yo2in):
return mdot*(0 - yco2) - wdco(yh2o,yco,yco2,yo2,T)*Mwco2*V
def f3(yh2o,yco,yco2,yo2,yn2):
return yco + yo2 + yco2 + yh2o + yn2 - 1 | The function computes three values f[0], f[1], f[2] using helper functions f1, f2, f3. It takes input x (a 3-element list), parameters dm and T, and calculates outputs based on components of x and additional variables like yh2o, ycoin, yo2in, yn2. The result is an array f containing these computed values. | def function(x,dm,T):
n=len(x); f=np.zeros(n)
yco=x[0]; yo2=x[1]; yco2=x[2];
f[0]=f1(yh2o,yco,yco2,yo2,T,dm,ycoin);
f[1]=f2(yh2o,yco,yco2,yo2,T,dm,yo2in);
f[2]=f3(yh2o,yco,yco2,yo2,yn2);
return f |
def net_usage(self, inf="eth0"): # change the inf variable according to the interface
try:
net_stat = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
net_in_1 = net_stat.bytes_recv
net_out_1 = net_stat.bytes_sent
net_in = round((net_in_1 - self.in_net_data... | The main task of the code is to collect system health metrics, including CPU usage, memory availability, and network data (in/out) for 'eth0', along with a timestamp. It packages these metrics into a dictionary, writes them to a file, and logs the data. Exceptions during execution are caught and logged. The function is... | def get_health_data(self):
try:
net_in,net_out = self.net_usage("eth0")
date_time = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
#cpu_utilization = psutil.cpu_percent(interval = 1, percpu = False)
cpu_utilization = psutil.cpu_percent(percpu = False)
... |
def __define_layout_objects(self):
# Report heading data
self.select_plan = Select(title='Plan:')
self.button_refresh_plans = Button(label='Scan DICOM Inbox', button_type='primary')
self.select_protocol = Select(title='Protocol:', options=self.protocols.protocol_names, value='TG101')
... | This code initializes a class by setting up data structures for dose-volume histograms (DVH), ROI (region of interest) information, and UI components. It prepares data sources, binds UI elements, and configures layouts for a medical application, likely for radiation therapy planning, by initializing protocol data, stru... | def __init__(self):
# Initialize Data Objects
self.dvh = None
self.dvh_counts = []
self.bin_count = 0
self.bin_counts = None
self.roi_keys = None
self.roi_names = None
self.roi_key_map = None
self.plans = None
self.structures = None
... |
def _w(self):
return hk.get_parameter(
"w", [self.n_ssm, self.n // 2], dtype=jnp.complex64, init=self._w_init
)
def _C(self):
B = self._B()
B = repeat(B, "t n -> (v t) n", v=self.n_ssm // B.shape[-2])
C = hk.get_parameter(
"C",
(self.channels, ... | The code defines an RNN method that instantiates an S4DCell object using parameters like weights, state matrices, and time-scale adjusted delta-t values, returning the configured cell for sequence processing. | def rnn(self, timescale=1.0):
return S4DCell(self._w(), self._C(), self.D, self._dt(timescale)) |
def _w(self):
return hk.get_parameter(
"w", [self.n_ssm, self.n // 2], dtype=jnp.complex64, init=self._w_init
)
def _C(self):
B = self._B()
B = repeat(B, "t n -> (v t) n", v=self.n_ssm // B.shape[-2])
C = hk.get_parameter(
"C",
(self.channels, ... | The code defines a method `cnn` that constructs and returns an instance of the `S4DConv` class, initializing a convolutional layer with parameters such as weights (`self._w()`), channel dimensions (`self._C()`), dilation (`self.D`), time-scale adjustment (`self._dt(timescale)`), number of channels (`self.channels`), an... | def cnn(self, timescale=1.0):
return S4DConv(
self._w(),
self._C(),
self.D,
self._dt(timescale),
self.channels,
bidirectional=self.bidirectional,
) |
def save_url_to_s3_and_return_html(self):
s3 = create_s3_connection()
r = requests.get(self.url, verify=True)
s3.Object(s3_bucket_name, f"{'__'.join(self.url.split('/')[2:])}.html").put(Body=r.text)
print(f"Saved {self.url} to S3..")
return r.text
def get_website_storage_url(self... | The code's main task is to save website data by extracting the company name, storage URL, and keyword frequency analysis from raw HTML, then passing these to the parent class's save method for further processing. | def save(self, **kwargs):
raw_html = self.save_url_to_s3_and_return_html()
storage_location_url = self.get_website_storage_url()
website_name = self.get_company_name_from_url()
keyword_frequency_count_json = self.get_website_keyword_frequency_json(raw_html)
self.keywords = keyw... |
def new_round(self):
self._reset()
pool = list(self.DOMINOS)
random.shuffle(pool)
for i in range(len(self.players)):
self.players[i].give_dominos(pool[i::4])
if self.first_game_round_step:
for p in self.players:
if p.has_double_six():
... | The main task of the code is to manage a game round by initializing it, repeatedly updating and displaying the game state step-by-step until completion, then finalizing the round with a score update. It uses a loop to execute game steps, renders the game state after each step, and ensures the final state and score are ... | def play_round(self):
self.new_round()
while self.step():
self._display_wrapper.display_game(self.to_game_data())
self._display_wrapper.display_game(self.to_game_data())
self.update_score() |
def startup():
update_viewport(None, 400, 400)
glClearColor(0.0, 0.0, 0.0, 1.0)
glEnable(GL_DEPTH_TEST)
def render(time):
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
spin(time * 180 / math.pi)
axes()
# print_egg_points()
# print_egg_lines()
# print_egg_tr... | This code initializes a GLFW window, sets up rendering context, and performs real-time rendering in a loop until the window is closed. It handles framebuffer size changes, enables vertical sync, and manages the rendering pipeline with startup/shutdown functions. | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(400, 400, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSwapInterval(1)
startup()
... |
def startup():
update_viewport(None, 400, 400)
glClearColor(0.5, 0.5, 0.5, 1.0)
def render(time):
glClear(GL_COLOR_BUFFER_BIT)
# print_rectangle(0.0, 1.0, 30, 30, [0, 0, 0.5])
# print_funny_rectangle(0.0, 0.0, 30, 30, 0.1)
print_carpet(0, 0, 100, 100, 4)
glFlush()
def shutdown():
pass | The code initializes a GLFW window for OpenGL rendering, sets up a rendering loop with vsync, and manages the OpenGL context lifecycle. It creates a 400x400 window, registers a viewport update callback, and continuously renders frames using `render()` until the window is closed, handling input and cleanup through `star... | def main():
if not glfwInit():
sys.exit(-1)
window = glfwCreateWindow(400, 400, __file__, None, None)
if not window:
glfwTerminate()
sys.exit(-1)
glfwMakeContextCurrent(window)
glfwSetFramebufferSizeCallback(window, update_viewport)
glfwSwapInterval(1)
startup()
... |
def mergeSort_MC(self) -> list: # insertion sort based on market cap
changedList = self.arr
# for elem in changedList:
# if elem.marketCap == 'N/A':
# changedList.remove(elem)
return self.mergeSort_MC_r(changedList)
def mergeSort_PE(self) -> list: # insertion sort b... | This method routes sorting operations by dispatching to specific merge sort implementations based on the input parameter 'val', which specifies the financial metric to sort by (e.g., market cap, PE ratio, EPS, volume, or beta). It acts as a switch-case to select the appropriate sorting function and returns the sorted r... | def mergeSort(self, val) -> list: # calls insertion sort based on input
if val == "market cap":
return self.mergeSort_MC()
elif val == "pe":
return self.mergeSort_PE()
elif val == "eps":
return self.mergeSort_EPS()
elif val == "volume":
re... |
def insert_MC(self, node) -> None: # inserts node into tree based on market cap
self.size += 1
if self.root is None:
self.root = node
return
else:
self.insert_MC_r(self.root, node)
def insert_PE(self, node) -> None: # inserts node into tree based on price to... | This method inserts a node into a data structure using different strategies based on the 'val' parameter, which specifies the financial metric type. It routes insertion to specialized methods like insert_MC (market cap), insert_PE (price-to-earnings), insert_EPS (earnings per share), insert_beta (beta coefficient), or ... | def insert(self, node, val) -> None: # default insert by market cap
if val == "market cap":
self.insert_MC(node)
elif val == "pe":
self.insert_PE(node)
elif val == "eps":
self.insert_EPS(node)
elif val == "beta":
self.insert_beta(node)
... |
def construct_features(self, X: ndarray, window_len: int): # TODO remove forward-looking params and slice X accordingly
df = pd.DataFrame(X)
df['Left local mean'] = df.rolling(window_len).mean()
df['Left local std'] = df[0].rolling(window_len).std(ddof=1)
df['Right local mean'] = df[0... | The code trains a Hidden Markov Model (HMM) by iteratively optimizing parameters (theta) and state sequences through multiple epochs and iterations. It constructs features if enabled, initializes parameters, and alternates between fitting theta and state sequences. Convergence is checked via state sequence stability an... | def fit(self, X, auto_construct_features=True, get_hmm_params=True, verbose=0):
self.is_fitted = False
old_objective_score = best_objective_score = np.inf
if auto_construct_features is True:
X = self.construct_features(X, window_len=self.window_len)
# Each epoch independent... |
def fit(self, X):
"""
fit model to data. Defined in respective child classes
"""
pass
def decode(self, X):
"""
Function to output the most likely sequence of states given an observation sequence.
Parameters
----------
X : ndarray of shape (n_sampl... | The main task of the code is to fit a model to input data, decode the most likely state sequence, and generate posterior probabilities for future states. It combines fitting, decoding, and prediction into one method. If initial fitting fails, it doubles the iteration limit and retries. The function returns the decoded ... | def fit_predict(self, X, n_preds=15, verbose=False):
"""
Fit model, then decode states and make n predictions.
Wraps .fit(), .decode() and .predict_proba() into one method.
Parameters
----------
X : ndarray of shape (n_samples,)
Data to be fitted.
n_p... |
def force_gravity(self):
return np.array([0.0, 0.0, -GRAVITY])
def force_pressure(self, others):
force = np.array([0.0, 0.0, 0.0])
p_i = self.pressure(others)
for other in others:
distance = self.distance(other)
if distance >= DISTANCE_LIMIT:
con... | The code calculates the total force acting on an object by summing four components: gravitational force, pressure force from interactions with other objects, viscous force due to fluid dynamics, and surface tension force. This aggregated force likely represents the net physical force influencing the object's motion or ... | def force(self, others):
return (
self.force_gravity()
+ self.force_pressure(others)
+ self.force_viscosity(others)
+ self.force_surface_tension(others)
) |
def get_bank(pages):
'''Identify the bank referenced in the statement by associating it with the most common URL'''
bank_frequency = {}
for page in pages:
lines = page.extract_text().split('\n')
for line in lines:
result = re.search("www\.([a-zA-Z]+)\.com", line.lower())
... | The main task of the code is to extract transaction data from a PDF document. It identifies the bank, parses transaction lines, and structures them into dictionaries containing date, price, vendor, and account details. The function processes each page, detects table headers/footers, and collects valid transactions into... | def parse_pdf(filename):
# Create array of dictionaries to track all transactions in PDF
transactions_info = []
pdf_path = sys.argv[1]
pdf_obj = pdfplumber.open(pdf_path)
bank = get_bank(pdf_obj.pages)
end_digits = get_end_digits(pdf_obj.pages[0])
is_table = False
for page in pdf_obj... |
def mouseOnGrid(self):
if self.mousePos[0] < gridPos[0] or self.mousePos[1] < gridPos[1]:
return False
if self.mousePos[0] >gridPos[0]+gridSize or self.mousePos[1] > gridPos[1]+gridSize:
return False
x = (self.mousePos[0]-gridPos[0])//cellSize
y = (self.mousePos[1... | This method handles user input events in a Pygame application. It processes mouse clicks to select grid cells, navigates selections via arrow keys, and records 'X'/'O' inputs to update the game grid. It enables computer mode after a player's move, tracks used cells, and checks game state. | def events(self):
for event in pygame.event.get():
self.mousePos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
self.running = False
if event.type == pygame.MOUSEBUTTONDOWN:
selected = self.mouseOnGrid()
if selected:
... |
def events(self):
for event in pygame.event.get():
self.mousePos = pygame.mouse.get_pos()
if event.type == pygame.QUIT:
self.running = False
if event.type == pygame.MOUSEBUTTONDOWN:
selected = self.mouseOnGrid()
if selected:
... | The code defines a `run` method that executes a game loop, repeatedly calling `self.events()` to handle user inputs and `self.draw()` to update the display while `self.running` is True. Upon exiting the loop, it quits Pygame and invokes the `main()` function, likely to restart or initialize the application. The primary... | def run(self):
while self.running:
self.events()
self.draw()
pygame.quit()
main() |
def fileIsDownloaded(self, run):
dateString = self.createDateFolder()
datefolder = DOWNLOADS_PATH + dateString + '/' + str(run) + '/'
if os.path.exists(os.path.dirname(datefolder)):
path, dirs, files = next(os.walk(os.path.dirname(datefolder)))
if len(files) == 9:
... | The main task of the code is to check if files for a specific time range are already downloaded. If not, it constructs a server URL, verifies the existence of 9 files in increments of 3 within a 25-unit range, and downloads them if all exist. It avoids redundant downloads by checking file existence before initiating th... | def check_and_download(self, hour, time, detail):
print(f'hour >={hour} and hour < {hour + 6}', end="\n")
if self.fileIsDownloaded(hour):
print('files already downloaded', end="\n")
return
SERVER_URL = self.createServerByTime(time, detail)
counter = 0
for ... |
def moveFlames():
global moveFlamesFlag
dmoves = [(1, 0), (0, 1), (-1, 0), (0, -1)]
moveFlamesFlag = 0
for g in range(len(flames)):
dirs = gamemaps.getPossibleDirection(flames[g])
if inTheCentre(flames[g]):
flames[g].dir = 3
else:
if g == 0: followPlayer(g... | This code handles player interactions in a Pygame Zero game, managing flame collisions to update scores/lives, animating game elements, and processing input to control player movement, pauses, and restarts. It checks collision events, adjusts game states, plays sounds, and triggers animations based on player actions an... | def update(): # Pygame Zero update function
global player, moveFlamesFlag, flames
if player.status == 0:
if moveFlamesFlag == 4: moveFlames()
for g in range(len(flames)):
if flames[g].status > 0: flames[g].status -= 1
if flames[g].collidepoint((player.x, player.y)):
... |
def __event_pktarrival(self, evnt):
# if packts arrive at the sender side
self.t = evnt.time
# Get the current maximum packet number
self.max_pkt_no = self.accumu_packets[evnt.frm_id]
# Schedule next arrival event
self.ind += 1
if self.ind < self.num_frms:
... | The code processes simulation events in a loop. It retrieves events from a queue, handles them based on their type (packet arrival, loss, delivery, or acknowledgment), and terminates when no more events remain. | def sim_run(self):
while True:
# logger.debug(str(event_list.queue))
# Get imminent event
try:
evnt = self.event_list.get_nowait()
except queue.Empty:
logging.debug("No events any more")
break
else:
... |
def selectOpt(price):
el = driver.find_element(By.XPATH, "//select[@id='PageContent_ddPB']")
for option in el.find_elements(By.TAG_NAME, "option"):
if option.text == price:
option.click()
def addBondNum(list):
for i in list:
print(i)
driver.find_element(By.XPATH, "//input... | The function `get100()` sets a price variable to "Rs. 100/-", invokes `selectOpt()` with this price, adds a bond number using `addBondNum(bond100)`, and calls `dynamicTable()` to generate or update a dynamic table. The commented `getResult()` suggests potential future integration for output retrieval. Its primary task ... | def get100():
price = "Rs. 100/-"
selectOpt(price)
addBondNum(bond100)
# getResult()
dynamicTalbe() |
def selectOpt(price):
el = driver.find_element(By.XPATH, "//select[@id='PageContent_ddPB']")
for option in el.find_elements(By.TAG_NAME, "option"):
if option.text == price:
option.click()
def addBondNum(list):
for i in list:
print(i)
driver.find_element(By.XPATH, "//input... | The function `get200()` sets a price of "Rs. 200/-", selects an option using this price, adds a bond number (`bond200`), and initializes a dynamic table (commented out). Its primary task is to configure and initialize bond-related data for a 200-unit transaction, likely for a financial or inventory system. | def get200():
price = "Rs. 200/-"
selectOpt(price)
addBondNum(bond200)
# getResult()
dynamicTalbe() |
def selectOpt(price):
el = driver.find_element(By.XPATH, "//select[@id='PageContent_ddPB']")
for option in el.find_elements(By.TAG_NAME, "option"):
if option.text == price:
option.click()
def addBondNum(list):
for i in list:
print(i)
driver.find_element(By.XPATH, "//input... | The function `get750()` sets a price variable to "Rs. 750/-", invokes `selectOpt()` with this price, adds a bond number using `addBondNum(bond750)`, and generates a dynamic table via `dynamicTable()`. The commented-out `getResult()` suggests a potential future step for retrieving outcomes. The primary tasks involve con... | def get750():
price = "Rs. 750/-"
selectOpt(price)
addBondNum(bond750)
# getResult()
dynamicTalbe() |
def _set_channel(self, channel_name):
return self._cmd(f':WAV:SOUR {channel_name}', DS4024_SCPI.RET_NONE)
def _fetch_preamble(self):
'''Run :WAV:PRE" to get the current channel's settings'''
preamble_s = self._cmd(':WAV:PRE?', DS4024_SCPI.RET_LINE)
return self._parse_preamble(preamble_s)... | The main task of the code is to fetch a single waveform from an oscilloscope for a specified channel (default: "CHAN1"), optionally using provided trigger settings. It retrieves waveform data, channel settings, and instrument metadata, constructs a Waveform object, and returns it. The function avoids redundant trigger ... | def fetch_waveform(self, channel="CHAN1", trigger_settings=None):
'''Fetch a single waveform, with optional pre-captured trigger settings
This returns a Waveform object. That said, you probably want
to use fetch_waveforms() to get multiple channels all in one
go.
The trigger_s... |
def scan_link(link):
api_key = "YOUR_VIRUSTOTAL_API_KEY"
url = f"https://www.virustotal.com/vtapi/v2/url/scan"
params = {"apikey": api_key, "url": link}
try:
response = requests.post(url, data=params)
response.raise_for_status()
return response.json()
except requests.excepti... | The main task of the code is to scan a provided link using VirusTotal, retrieve the scan results, analyze them with GPT, extract the server IP address, and log details like the link, email, timestamp, and scan outcome. It handles API errors and updates the GUI with real-time status messages. | def main_process():
link = entry_link.get()
email = entry_email.get()
date_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
output_entry.insert(tk.END, "Scanning in VirusTotal...\n")
scan_result = scan_link(link)
if scan_result:
scan_id = scan_result.get("scan_id")
if scan_i... |
def scan_link(link):
api_key = "VIRUSTOTAL API_KEYS" # Replace with your Virustotal API key
url = f"https://www.virustotal.com/vtapi/v2/url/scan"
params = {"apikey": api_key, "url": link}
try:
response = requests.post(url, data=params)
response.raise_for_status()
return respons... | The main task of the code is to scan a provided link using the VirusTotal API, retrieve the scan results, and process them by logging the outcome along with metadata like the link, email, and timestamp. If the scan fails or returns an invalid response, it logs an error. The function integrates with a GUI to display rea... | def main_process():
link = entry_link.get()
email = entry_email.get()
date_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
output_entry.insert(tk.END, "Scanning in VirusTotal...\n")
scan_result = scan_link(link)
if scan_result:
scan_id = scan_result.get("scan_id")
if scan_i... |
def _get_instrucitons(self) -> list:
"""
Exract parsing instriction from attribute self.parsing_isctructions.
Return:
instructions (list): List of parsing instructions.s
"""
with open(self.parsing_isctructions, 'r') as f:
instrucitons = [
l... | This method extracts and organizes data from a JSON dictionary by processing instructions. It iterates through instructions, splits them into table names and parsing rules, updates target tables (like CHART_INFO/GENRE_INFO), parses content accordingly, and appends structured data to tables. Special handling ensures pro... | def extract_all(self, relevant_content: dict) -> None:
"""
Main method for extraction that calls other "sub methods".
Parameter:
relevant_content (dict): json-dict with all information.
"""
for instruction in self._get_instrucitons():
instruction... |
def create_dummy_db_person(cls, user):
person = Person.objects.create(
user=user,
birth_date = "1977-01-01",
address = "fake address"
)
return person
def create_dummy_db_user(cls, username):
user = User.objects.create_user(username=username, email="",
password=username)
... | The main task of the code is to create a dummy Doctor object with predefined attributes. It uses helper methods to generate a person (via user and staff creation) and assigns a fake speciality. The function returns the constructed Doctor instance for testing or mock data purposes. | def create_dummy_db_doctor(cls, name):
doctor = Doctor.objects.create(
person=create_dummy_db_person(cls, create_dummy_db_user(cls, name)),
staff = create_dummy_db_staff(cls, "staff1", "department1"),
speciality = "fake speciality"
)
return doctor |
def create_dummy_db_hospital(obj, name, address):
hospital = Hospital.objects.create(name=name, address=address)
return hospital
def create_dummy_db_department(obj, name, hospital):
department = Department.objects.create(
name=name,
hospital=create_dummy_db_hospital(obj, hospital, "hospital1... | The code defines a class method `setUpTestData` to initialize test data by creating dummy database entries for a hospital, its department, and a staff member. It uses helper functions to set up hierarchical relationships: a hospital, an associated department, and a staff member linked to that department. This prepares ... | def setUpTestData(cls):
cls.hospital = create_dummy_db_hospital(cls, "hospital1", "hospital1 address")
cls.department = create_dummy_db_department(cls, "department1", cls.hospital)
cls.staff = create_dummy_db_staff(cls, "staff1", department = "department1") |
def parse_config(filename):
config = ConfigParser()
config.read(filename)
init = config.get('Terrain', 'InitPosLimit')
sheep = config.get('Movement', 'SheepMoveDist')
wolf = config.get('Movement', 'WolfMoveDist')
if float(init) < 0 or float(sheep) < 0 or float(wolf) < 0:
logging.error("N... | This code sets up and runs a simulation with configurable parameters, including number of rounds, sheep, movement distances, logging, and output directory. It parses command-line arguments to override default values, processes a config file if provided, initializes logging, and launches the simulation with specified se... | def main():
rounds = 50
sheep_number = 15
init_pos_limit = 10.0
sheep_move_dist = 0.5
wolf_move_dist = 1.0
directory = None
wait = False
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', help="set config file", action='store', dest='conf_file', metavar='FILE')
... |
def get_build_ids():
"""Return filterd list of builds for a given config.id.
Also store auth info in cookies.
"""
global SESSION
if not ARGS.buildtype_id:
print("[error] missing --buildtype-id argument")
sys.exit(1)
# if --build-id is not set, get the latest one.
if ARGS.b... | The main task of the code is to retrieve changes from TeamCity using specified build IDs, identify modified DLC file paths, extract their base names, and process these DLCs. It exits if no changes are found or if a build type ID is missing, ensuring only relevant DLCs are handled based on version control differences. | def process_teamcity():
"""Get changes from teamcity and process dlc according to those changes."""
if not ARGS.buildtype_id:
print("[error] need to specify at least --buildtype-id")
sys.exit(1)
build_ids = get_build_ids()
changed_paths = get_changed_paths(build_ids)
if not changed_... |
def __pox_alpha(temp_array: __array) -> None:
aleph = (temp_array[0] ^ temp_array[1]) & __MASK_WORD_ZZFF
daal = (temp_array[2] ^ temp_array[3]) & __MASK_WORD_FFZZ
theh = (aleph | daal) % __POX_8B_PRIMES[0]
gaaf = (aleph ^ daal) % __POX_8B_PRIMES[1]
temp_array[0] >>= theh
temp_array[1] >>= ((the... | The main task of the code is to apply four sequential transformations—alpha, delta, theta, and gamma—to a given array (`temp_array`) as part of a cryptographic or hashing algorithm's round process, modifying the array in-place through these operations. | def __pox_round_apply_alphabet(temp_array: __array) -> None:
__pox_alpha(temp_array)
__pox_delta(temp_array)
__pox_theta(temp_array)
__pox_gamma(temp_array) |
def assert_file(arg: str) -> bool:
return len(arg) > FILE_PREFIX_LEN and arg.startswith(FILE_PREFIX)
def assert_int(arg: str) -> bool:
return len(arg) > INT_PREFIX_LEN and arg.startswith(INT_PREFIX)
def to_ubyte_array(arg: str) -> any:
from array import array
return array('B', arg)
def to_int(numbers: s... | This function processes an input argument which could be a file path, an integer with a prefix, or a regular string. It converts the input into a byte array, integer, or file content based on its type, using helper functions to determine the input format and perform the conversion. | def process_arg(arg: str) -> any:
if not assert_file(arg) and not assert_int(arg):
return to_ubyte_array(arg.encode())
elif assert_int(arg):
return to_int(arg[INT_PREFIX_LEN:])
return to_ubyte_array(read_given_file(arg[FILE_PREFIX_LEN:]).encode()) |
def __pox_round_apply_alphabet(temp_array: __array) -> None:
__pox_alpha(temp_array)
__pox_delta(temp_array)
__pox_theta(temp_array)
__pox_gamma(temp_array)
def __pox_round_apply_prime(temp_array: __array) -> None:
for i in range(__POX_ROUND_PRIME_NUM):
curr_pnum = __POX_ROUND_PRIMES[i]
... | The function `__pox_round` processes an input array by converting it into a temporary array, then sequentially applying three transformations: alphabet-based modification, prime-related adjustments, and shuffling. Finally, it merges the transformed temporary array back into the original array, likely for data manipulat... | def __pox_round(factor_array: __array) -> None:
temporary_array = __array('H', factor_array.tolist())
__pox_round_apply_alphabet(temporary_array)
__pox_round_apply_prime(temporary_array)
__pox_round_apply_shuffle(temporary_array)
__pox_round_add_tmp_to_facts(factor_array, temporary_array) |
def validate_flags(exec: str, argv: list[str]) -> None:
len_argv = len(argv)
flags_arg = argv[0]
len_flags = len(flags_arg)
script_name = get_script_and_exec_name(exec)
if len_argv < MIN_ARG_NUM:
error_out("No flags passed")
if len_flags < MIN_FLAG_SIZE or len_flags > MAX_FLAG_SIZE:
... | The main task of the code is to compute cryptographic hashes of input arguments using the `pox_hash` function, with optional flags for echoing input, joining arguments, and measuring execution time. It validates flags, processes each argument into byte arrays, calculates hashes, and prints results with timing informati... | def main(exec_name: str, argv: list[str]) -> None:
validate_flags(exec_name, argv)
flags_arg = argv[0]
if not arg_has_flag(flags_arg, FLAG_NHEADER):
printf(
"\033[1;30;47m PoxHashRunner | Python | March 2023 - Chubak Bidpaa | MIT \033[0m\n"
)
echo_arg = arg_has... |
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def training(model, train_data, val_data, log, config):
optimizer = torch.optim.AdamW(
params=model.parameters(),
lr=config['lr'],
weight_decay=config['weight_decay']
)
num_train_st... | The function trains a base model over multiple iterations, evaluates it on a validation set, logs metrics (loss, accuracy, F1, precision, recall), and saves the final model. It initializes the model from a config, trains using specified datasets, aggregates training history, and stores the model state in a structured f... | def train_base(log, tokenized_dataset, val_dataloader, config, device):
base_model = config['init_base_func'](config).to(device)
log.info(f'Number of parameters: {count_parameters(base_model)}')
total_iterations = 0
full_history = dict()
# TODO: fix this, we are using this only to make sure exper... |
def count_parameters(model):
return sum(p.numel() for p in model.parameters() if p.requires_grad)
def training(model, train_data, val_data, log, config):
optimizer = torch.optim.AdamW(
params=model.parameters(),
lr=config['lr'],
weight_decay=config['weight_decay']
)
num_train_st... | The code trains a concept space model for classification tasks, optimizing inter-space and intra-space losses. It iteratively trains the model, evaluates validation metrics (accuracy, F1, precision, recall), tracks the best performance, and saves the model. The process involves embedding generation, loss computation, a... | def train_space(log, tokenized_dataset, val_dataloader, config, device):
space_model = config['init_space_func'](config).to(device)
log.info(f'Number of space model parameters: {count_parameters(space_model)}')
# estimation losses
ids = tokenized_dataset['test'][0]['input_ids'].unsqueeze(0).to(device... |
def seed_everything(seed=42):
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
def train_base(log, tokenized_dataset, val_dataloader, config, device):
base_model = co... | The code executes a machine learning experiment by training and evaluating models (base and/or space) based on configuration parameters. It initializes logging, loads a dataset, trains models if specified, and evaluates their performance on a test set. Results are logged, visualized, and saved, with error handling for ... | def run(config):
base_name = f'{config["dataset_name"]}_{config["model_name"].replace("/", "_")}_{"space" if config["train_space"] else ""}_({config["n_latent"]})_{config["num_epochs"] * config["iterations"]}_{config["device_id"]}'
log = get_logger(f'logs/{config["experiment_name"]}/', f'{base_name}.log')
... |
def _validate_integer(self, action_result, parameter, key):
"""
Validate an integer.
:param action_result: Action result or BaseConnector object
:param parameter: input parameter
:param key: input parameter message key
:return: status phantom.APP_ERROR/phantom.APP_SUCCES... | The code polls LogRhythm for alarms using REST API calls, processes each alarm into Phantom containers with associated artifacts, and manages state to track the last processed time. It handles both immediate and scheduled polling, validates configuration parameters, and ensures data is structured for ingestion into Pha... | def _handle_on_poll(self, param):
self.save_progress("In action handler for: {0}".format(self.get_action_identifier()))
action_result = self.add_action_result(ActionResult(dict(param)))
config = self.get_config()
params = {
"orderBy": "dateInserted"
}
# Use... |
def _handle_test_connectivity(self, param):
action_result = self.add_action_result(ActionResult(dict(param)))
self.save_progress("Connecting to endpoint")
# make rest call
ret_val, response = self._make_rest_call(LOGRHYTHM_ALARMS_API, action_result, params=None)
if phantom.is_f... | The code defines a method `handle_action` that determines and executes the appropriate action based on the `action_id` retrieved from the instance. It delegates tasks to specific handler methods like `_handle_test_connectivity` or `_handle_on_poll`, updating `ret_val` with the result of each action. Finally, it returns... | def handle_action(self, param):
ret_val = phantom.APP_SUCCESS
# Get the action that we are supposed to execute for this App Run
action_id = self.get_action_identifier()
self.debug_print("action_id", self.get_action_identifier())
if action_id == 'test_connectivity':
... |
def can_attain_level(self):
# Determine whether or not this project is enough
# to qualify to meet the level
description = ""
for i in range(len(self.__readme_list)):
row = self.__readme_list[i]
if "### HTML Level" in row:
# set description to next... | The main task of the code is to validate HTML compliance with required standards by checking essential elements, HTML5 requirements, inline styles, and overall criteria through a series of validation methods. | def analyze_results(self):
self.can_attain_level()
self.validate_html()
self.set_html5_required_elements_found()
self.set_required_elements_found()
self.meets_required_elements()
self.meets_html5_essential_requirements()
self.check_for_inline_styles()
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.