dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def simple_update(self) -> bool:
for k, v in self._current_version.copy().items():
if k in self._new_version:
new_value = self.populate_new_values(v, self._new_version[k])
if new_value != self._current_version[k]:
self._current_version[k] = new_val... | The main task of the code is to perform a version update based on the specified mode (Simple, Brute, or default). It validates the presence of a new version, logs the update process, delegates execution to mode-specific methods, and returns the result of the update operation as a boolean. | def update_current_version(self) -> bool:
if not self._new_version:
raise Exception("new_version should not be empty")
self.logger.info(f"Starting {self._mode.name} Update")
if self._mode == UpdateMode.Simple:
return self.simple_update()
elif self._mode == UpdateM... |
def load(self, data) -> Dict:
try:
file = Path(data)
except TypeError as e:
if isinstance(data, dict):
self.logger.debug(f"Found input data: {data}")
return data
self.logger.error(e)
sys.exit(1)
if file.suffix != ".... | The main task of the code is to initialize a version updater that loads current and new version configurations from YAML files, sets an update mode, and attempts to update the current version to the new version. It logs progress and success/failure status, using a specified mode to determine the update process and pres... | def __init__(
self,
current_version: str,
new_version: str,
mode: str = "Default",
log=logger(),
) -> None:
self.logger = log
self._yaml = ruamel.yaml.YAML()
self._yaml.preserve_quotes = True
self.logger.info("Started Version Updater app")
... |
def _select_hosts(self, bench_parameters):
# Collocate all shards on the same machine.
if bench_parameters.collocate:
nodes = max(bench_parameters.nodes)
# Ensure there are enough hosts.
hosts = self.manager.hosts()
if sum(len(x) for x in hosts.values()) ... | The code executes distributed benchmarks on selected hosts by configuring nodes, running tests with varying input rates and node counts, handling errors, and logging results. It validates parameters, selects instances, updates nodes, and iterates through benchmark configurations, ensuring fault tolerance and reporting ... | def run(self, bench_parameters_dict, debug=False):
assert isinstance(debug, bool)
Print.heading('Starting remote benchmark')
try:
bench_parameters = BenchParameters(bench_parameters_dict)
except ConfigError as e:
raise BenchError('Invalid nodes or bench parameters... |
def cp_r(src, dst, *options):
return cp(src, dst, *['-r', *options])
def rm_d(*args):
return run_sync(None, os.execlp, 'rm', 'rm', *['-d', *args])[0][1]
def write_runcard(directory, seed, number):
path = os.path.join(directory, 'run_card.dat')
with open(path) as f:
card = f.read()
card, n = ... | This function initializes a working directory for a computational task by copying necessary files, writing configuration and script files, setting up logging, and redirecting standard input/output to specified files. It handles error cases during directory copying, configures the environment, and returns arguments alon... | def init_run(*args, **kwargs):
seed = kwargs['seed']
nwd = kwargs['nwd']
number = kwargs['number']
if cp_r(directory, nwd):
rm_d(nwd)
raise RuntimeError('cp_r error')
write_runcard(os.path.join(nwd, directory, 'Cards'), seed, number)
write_script(nwd)
os.chdir(nwd)
loggin... |
def submit_run():
seed, nwd = get_nwd(directory)
pend_job(init_run, os.execlp, 'mg5_aMC', 'mg5_aMC', 'event.dat', seed=seed, nwd=nwd, number=batch)
def finish_job(pid):
global count
pid, code = waitpid(pid)
args, kwargs = running.pop(pid)
(failed if code else success).append((args, kwargs))
... | The code manages a fixed-thread pool by repeatedly submitting, running, and finishing jobs. It ensures no more than 'thread' concurrent tasks, processes pending jobs, and dynamically submits new tasks when slots are available, looping until all 'number' tasks are completed. | def launch():
for i in range(thread):
submit_run()
while pending:
while pending:
while len(running) >= thread:
finish_job(-1)
if count < number:
submit_run()
run_job()
while running:
finish_job(-1)
... |
def create_deck():
"""
Generate a deck of cards by combining the predefined ranks and suits.
Each card is represented as a tuple (rank, suit).
Returns:
- deck: A shuffled deck of cards as a list of tuples.
"""
# Initialize an empty list to store the cards in the deck
de... | The main task of the code is to implement a Blackjack game where the player and dealer take turns drawing cards, check for busts, compare hands, and track wins, losses, and ties. The game allows multiple rounds with a "play again" option, updating global counters for outcomes and ending when the player chooses to stop. | def play_game():
global total_wins, total_losses, total_ties
print("Welcome to Blackjack!")
# Create a new shuffled deck
deck = create_deck()
while True:
# Clear the screen for a new round
clear_screen()
# Deal initial cards to the player and dealer
player_hand =... |
def create_deck():
"""
Generate a deck of cards by combining the predefined ranks and suits.
Each card is represented as a tuple (rank, suit).
Returns:
- deck: A shuffled deck of cards as a list of tuples.
"""
# Initialize an empty list to store the cards in the deck
de... | Your return The function simulates `n` rounds of a card game using basic strategies for both bot and dealer. It tracks total wins, losses, and ties, and calculates winrates after each iteration. Debug logs are printed if enabled. The results include cumulative outcomes and a list of winrates over iterations, providing ... | def run_complete_game_simulations_with_basic_strategies(n, debug_logs=False):
"""
Arguments:
- n: An integer representing the number of game simulations to run.
- debug_logs: A boolean indicating whether to print debug logs.
Returns:
- tuple<int, int, int, list[]> where:
... |
def flip(shape: int, direction: int) -> list:
if direction == 0: return [row[:] for row in shape] # No flip
if direction == 1: return [row[::-1] for row in shape] # Flip about y-axis
if direction ==-1: return rotate(flip(rotate(shape,1),1),-1)
def rotate(shape: list, n: int, r=0) -> list:
# Rotates sh... | The code generates a puzzle by randomly placing rotated and flipped shapes on a grid. It initializes a board, shuffles shape and color lists, then iteratively attempts to fit each shape into valid positions. If a shape fits, it's added to the puzzle. The loop continues until all pieces are placed or the board contains ... | def create_puzzle(self):
# -1 = empty square
# 0 = square not part of puzzle
# 1 = occupied square
while True:
self.board = [[0 for _ in range(BOARD_COLS)] for _ in range(BOARD_ROWS)]
self.pieces = []
shuffle(COLOURS)
shuffle(SHAPES)... |
def choose_hyper_params(models, params_ranges, eval_func, train, target='Vote', num_folds=3, wrapper=None,
random_state=None, n_iter=10, verbose=False):
"""
given a list of models and an evaluation function, find the best hyper parameters for each model to get the best score
:param m... | This function identifies the best-performing model for a given problem by either conducting a random hyperparameter search or loading pre-saved parameters. It evaluates estimators using a specified function, trains them on the training data, selects the top model based on validation performance, and returns it. | def find_problem_best_model(train, valid, estimators, params, problem, eval_func, wrapper, n_iter=10, seed=None,
search_hyper_params=True, verbose=False):
"""
:param train: train set
:param valid: validiation set
:param estimators: estimators that we should
:param params:... |
def _clean_data(self):
def _datagolf():
datagolf_query = "SELECT t.tournamentid, p.playerid, d.sg_app as approach, d.sg_arg as short_contest, d.sg_ott \
as driving, d.sg_putt as putting, d.sg_t2g as tee_to_green, d.sg_total FROM datagolf d \
... | The main task of the code is to simulate historical tournament data by connecting to a PostgreSQL database, retrieving tournament information, mapping tournament IDs to indices, and executing simulations. It cleans data, runs historical simulations, and optionally backtests contest results or prints outputs based on pa... | def simulate(self, verbose=False, tracking=False):
engine = create_engine(
'postgresql://username:password@pga-postgresql.cxmbk6ooy1lu.us-east-1.rds.amazonaws.com/pga')
conn = engine.connect()
self.tournaments = pd.read_sql("SELECT tournamentid FROM tournament", conn).values[::-1]
... |
def EnthalpyChange(Ti,Tf,vi,vf):
vinf=1000
DH1=quad(lambda v: dP_dV(Ti,v)*v+Ti*dP_dT(Ti,v), vi, vinf, limit=Maxintervals)
DH2=(quad(lambda T: IdealGasCv(T)+0.08314,Ti,Tf, limit=Maxintervals))
DH3=quad(lambda v: dP_dV(Tf,v)*v+Tf*dP_dT(Tf,v),vinf,vf,limit=Maxintervals)
DH=DH1[... | The function `H_TV` calculates specific enthalpy (H) from given temperature (T) and specific volume (V), handling single-phase (liquid/gas) and two-phase regions, and operating above/below the critical point. It computes enthalpy using `EnthalpyChange` and adjusts for saturation values (Hf, Hg) in two-phase regions via... | def H_TV(T,V):
"""
#calculates the enthalpy from the Temperature and volume
#Also handles the two phase region correctly, and works above and below critical
#point. Might fail very close to critical temperature.
#USE:
# [H,{state,Hf,Hg}] = H_TV(T,V)
# where:
... |
def SatDensityL(T):
"""
#Calculates the saturated density of liquid- consistent with MBWR equation of state
#USE:
#SatDensity= SatDensityL(T)
#WHERE:
# T = temperature (K)
# SatDensity = density of saturated liquid (kg/m^3)
"""
Tr=T / Tc
A=528.1464
B=755.1834
C=1028.676
D=- 949.1172
E=5... | The function `Hsat_T(T)` calculates the saturated enthalpies (Hf for liquid, Hg for gas) at a given temperature `T` (in K). If `T` exceeds the critical temperature (`Tc`), it issues a warning and returns `-1` for both enthalpies. Otherwise, it computes the specific volumes of liquid and vapor phases, determines the vap... | def Hsat_T(T):
#Calculates the saturated enthalpies.
#Displays a warning if the temperature is above the critical points and returns
#entropies of -1.
#USE:
#Hf,Hg = Hsat_T(T)
#Where;
# T = Temperature(K)
# Hf = Enthalpy of the liquid phase (kJ/kg/K)
# Hg = Enthalpy of the gas phase (kJ/kg/K)
if T > Tc:
p... |
def EntropyChange(Ti,Tf,vi,vf):
vinf=1000
DS1=quad(lambda v: dP_dT(Ti, v), vi , vinf, limit=Maxintervals)
DS2=quad(lambda T: IdealGasCv_T(T) , Ti, Tf, limit=Maxintervals)
DS3=quad(lambda v: dP_dT(Tf, v) , vinf,vf, limit=Maxintervals)
DS=DS1[0]+DS2[0]+DS3[0]
return D... | The function `S_TV(T, V)` calculates specific entropy (S) from given temperature (T) and specific volume (V), handling liquid, gas, and two-phase regions, including critical point conditions. It determines the state (fraction of gas), and returns saturation entropies (Sf, Sg) if in the two-phase region. The calculation... | def S_TV(T,V):
"""
#calculates the entropy from the Temperature and volume
#Also handles the two phase region correctly, and works above and below critical
#point. Might fail very close to critical temperature.
#USE:
# (S,{state,Sf,Sg}) = S_TV(T,V)
# where:
# V = specific volume(kJ/kg/K)
# T = pressure (KPa)
#... |
def SatDensityL(T):
"""
#Calculates the saturated density of liquid- consistent with MBWR equation of state
#USE:
#SatDensity= SatDensityL(T)
#WHERE:
# T = temperature (K)
# SatDensity = density of saturated liquid (kg/m^3)
"""
Tr=T / Tc
A=528.1464
B=755.1834
C=1028.676
D=- 949.1172
E=5... | The code calculates the saturated entropies (liquid and gas phases) at a given temperature T. If T exceeds the critical temperature, it returns -1 and issues a warning. Otherwise, it computes specific volumes using saturation density and vapor pressure, applies Newton-Raphson for gas-phase volume, and calculates entrop... | def Ssat_T(T):
#Calculates the saturated entropies
#Displays a warning if the temperature is above the critical points and returns
#entropies of -1.
#USE:
#sf,sg = Ssat_T(T)
#Where;
# T = Temperature(K)
# Sf= Entropy of the liquid phase (kJ/kg/K)
# Sg = Entropy of the gas phase (kJ/kg/K)
if T > Tc:
print(... |
def generateClg(self):
"""
Generate a contracted line graph (clg) out of the graph provided
as list of assertions in self.adjacency.
"""
clg = np.eye(self.numberOfPredicates, self.numberOfPredicates)
# resourceDict[resourceID] = [all facts that contain that reso... | The main task of the code is to compute cosine similarity between predicates by generating a contracted line graph, calculating TF-IDF values, and saving the resulting cosine similarity matrix. It also measures and prints the time taken for each step, storing intermediate results like the contracted line graph and fina... | def generate(self, experimentPath:str):
"""
Perform all steps to calculate the required
cosine similarity between predicates.
"""
start = time.time()
clg = self.generateClg()
end = time.time()
print("Generated contracted line graph in {} seconds".format(en... |
def _createActions(self):
self.homeAction = QAction('&Home', self)
self.homeAction.triggered.connect(lambda: self._createHomeWindow())
self.cameraAction = QAction('&Color', self)
self.cameraAction.triggered.connect(lambda: self._createCameraWindow())
self.depthCameraAction = QAct... | The code initializes a GUI application's main window by setting properties like title, size, and position, creating action handlers, initializing threads for color and depth processing, configuring a menu bar, and setting up a home window. It also defines flags and paths for camera toolbars, timers, and data saving. | def __init__(self, parent=None):
"""Initializer."""
super().__init__(parent)
self._createActions()
#Setup of Main Window
self.setWindowTitle("Home")
self.setFixedSize(800, 480)
self.move(0,0)
self.haveCameraToolBar = False
self.continueT... |
def _createActions(self):
self.homeAction = QAction('&Home', self)
self.homeAction.triggered.connect(lambda: self._createHomeWindow())
self.cameraAction = QAction('&Color', self)
self.cameraAction.triggered.connect(lambda: self._createCameraWindow())
self.depthCameraAction = QAct... | The code initializes a GUI application's main window, sets its properties (title, size, position), creates camera threads for color and depth data, initializes flags for UI elements, and sets up a menu bar and home window to manage camera functionality and user interface components. | def __init__(self, parent=None):
"""Initializer."""
super().__init__(parent)
self._createActions()
#Setup of Main Window
self.setWindowTitle("Home")
self.setFixedSize(800, 480)
self.move(0,0)
self.haveCameraToolBar = False
self.continueT... |
def getRawData(filename):
# Open the .txt file to read it
with open(filename, 'r') as file:
# Read each line
schedules = file.readlines() # --> ['RENE=MO10:00-..'02:00', 'ASTRID=MO10:00-...', 'ANDRES=MO10:00-...']
# Strip each element
schedules = list(map(lambda line: line.strip(... | The main task of the code is to identify and print overlapping schedule days between pairs of workers. It compares every unique worker pair using nested loops, checks for schedule conflicts with `checkDaysCoincidences`, and outputs conflicting worker names and overlapping days when conflicts are found. | def main():
schedules = getRawData(FILENAME)
appendSchedules(schedules)
# Nested loop to check first worker with every other-->second with every other except first and so on
for i in range(len(workers)):
j = i + 1
while(j < len(workers)):
flag, coincidences, names = checkDays... |
def get_expression_data():
x, aux = input().split()
x, y, z = map(int, [x] + aux.split('='))
return x, y, z
def get_answer_data():
name, exp_idx, operation = input().split()
return name, int(exp_idx), operation
def get_who_shall_not_pass(expressions: 'list[tuple]', answers: 'list[tuple]'):
shall_not_pass_list = [... | The main task of the code is to process multiple test cases by reading input lines, extracting iteration counts, generating corresponding expressions and answers, and printing results from a function that determines which expressions do not match the answers. | def main():
for line in stdin:
if line == '\n': break
iterations = int(line)
expressions = [get_expression_data() for _ in range(iterations)]
answers = [get_answer_data() for _ in range(iterations)]
print(get_who_shall_not_pass(expressions, answers)) |
def update_belief (self, belief_prob, action, observation, all_poss_actions, horizon):
new_belief_prob = []
for s_p in self.env.get_possible_next_states(belief_prob, action, all_poss_actions, horizon):
# print ("s:",self.env.get_state_tuple(s_p))
for o_p in self.env.simulate_observation(s_p,action):
# pri... | The function `compute_Q_one_action` calculates the expected reward of executing a specific action from a given belief state over a specified time horizon, considering immediate rewards, time steps, and future outcomes. It simulates action outcomes, aggregates rewards, checks for terminal states, and recursively compute... | def compute_Q_one_action (self, belief, action, horizon, max_horizon, one_action, gamma, tree_s=0, all_poss_actions=False, HPOMDP=False):
# print_status = True
tree_size = tree_s + 1
immediate_r = 0
immediate_time = 0
terminal = False
leaf_beliefs = []
for (prob,state) in belief.prob:
outcomes, step... |
def _publish_auto_data(self, relation: Relation):
if self._auto_data and self.unit.is_leader():
host, port = self._auto_data
self.provide_ingress_requirements(host=host, port=port)
def is_ready(self):
"""The Requirer is ready if the Provider has sent valid data."""
try:
... | The main task of the code is to handle relation events by publishing automatic data, updating the stored current URL when a new URL is detected, and emitting a "ready" event with the new URL if it differs from the stored one. It avoids redundant emissions by checking URL changes and ensures proper event handling for re... | def _handle_relation(self, event):
# created, joined or changed: if we have auto data: publish it
self._publish_auto_data(event.relation)
if self.is_ready():
# Avoid spurious events, emit only when there is a NEW URL available
new_url = (
None
... |
def create_team(self) :
"""Create a new team when the NEW TEAM QAction is pressed.
Show a popup asking for team name input.
Also, display all the players categorywise in the available players listwidget.
"""
## Give self.centralwidget as the 1st argument as it is the instance of... | This function handles team management actions by checking the text of a provided QAction. Depending on the action's label ("NEW Team," "OPEN Team," etc.), it triggers corresponding methods like create_team(), open_team(), save_team(), or evaluate_team(). The purpose is to execute specific team-related operations based ... | def manage_teams(self, action) :
"""Select one of the many QActions for the QMenu - menuManage_Teams.
"""
_txt = (action.text())
if _txt == "NEW Team" :
self.create_team()
elif _txt == "OPEN Team" :
self.open_team()
elif _txt == "SAVE Team" :
... |
def _set_action_space(self):
bounds = np.deg2rad(self.model.actuator_ctrlrange.copy())#; print(bounds)
# bounds = (self.model.actuator_ctrlrange.copy()/180.0); print(bounds)
low, high = bounds.T
# low, high = np.ones([2], dtype=np.float32)
self.action_space = spaces.Box(low=low, ... | This code initializes a MuJoCo simulation environment by loading a model from a specified path, setting up simulation parameters, defining action/observation spaces, and verifying the environment's functionality through a sample step. It handles path resolution, model validation, and initial state configuration for rei... | def __init__(self, model_path, frame_skip):
self.mCounter = 0
if model_path.startswith("/"):
fullpath = model_path
else:
fullpath = os.path.join(os.path.dirname(__file__), "assets", model_path)
if not path.exists(fullpath):
raise IOError("File %s does ... |
def clean(self):
'''
Returns cleaned transactions table.
'''
cleaned = self.orig_table.drop(['REG FEE', 'SHORT-TERM RDM FEE', 'FUND REDEMPTION FEE', ' DEFERRED SALES CHARGE'], axis=1)
cleaned.drop(cleaned.tail(1).index, inplace=True)
mapper = {'COMMISSION': 'Commission'... | The code initializes a class by loading an Excel file from a given path, cleans the data, and retrieves open and closed positions from the cleaned dataset. | def __init__(self, path):
self.path = path
self.orig_table = pd.read_excel(self.path)
self.table = self.clean()
self.open_positions = self.open_positions()
self.closed_positions = self.closed_positions() |
def table_of_contents_recycling_factory(screen):
text = " Hello! I am Paul, the chef worker here.\n In the box to the left, you have the " \
" amount of\nrecycled materials of each kind so far and how much\nmaterial we need to recreate something else." \
"\n We will create new products a... | The main task of the code is to display an interactive recycling factory interface in a Pygame application. It renders product options (e.g., biofuel, compost, reusable items) with waste requirements, handles user clicks to show product details, animates a worker sprite, and manages navigation arrows. The loop processe... | def visit_recycling_factory(screen):
# MAIN WINDOW FOR THE PRODUCTS
font3 = pygame.font.SysFont('arialblack', 12)
running = True
x = 1000
while running:
recycling_factory_music.play(-1)
screen.blit(recycling_factory, (0, 0))
if x > 700:
x -= 3
else:
... |
def read_nodes_from_file(file):
"""
Supported extensions: obj, txt
"""
nodes = []
connectivity = []
n_rods = 0
if file.endswith('.obj'):
with open(file, 'r') as f:
for i, line in enumerate(f):
if line.startswith('v'):
pt = []
... | This function processes a dataframe to generate a grid of periodic rods. It reads 3D point cloud data from .obj files, aligns each to axes, creates periodic rods with specified material, and arranges them in a regular grid using parameters like row/column counts and spacing factors. | def load_rods_from_dataframe(df, data_path, material, n_rows=None, n_cols=None, step_factor=1, grid_step_x=None, grid_step_y=None):
knot_types = df['knot_type']
eq_ids = df['eq_id']
rods = []
for knot_type, eq_id in zip(knot_types, eq_ids):
file = data_path + knot_type + '/' + str(eq_id).zf... |
def handle_client_cmd(self, conn, request, con):
cmd, msg = protocol_library.disassemble_message(request)
cmd_send, msg_send = "", ""
if cmd == client_commands["join_my_player_cmd"]:
if not self.is_full and self.current == "waiting" and msg not in [player.player_name for player in
... | The main task of this code is to handle a player's connection to a server, process incoming client commands, manage game state transitions (e.g., updating turns), and gracefully handle disconnections or errors by closing sockets, updating player information, and shutting down the server if necessary. It maintains a dat... | def handle_player_conn(self, conn):
try:
con = sql.connect("Data_Bases/accounts_database.db")
while True:
request = conn.recv(1024).decode()
if request is None or request == "":
raise ConnectionError
print(f"\n[Client {c... |
def registerNewSlave():
workers=int(master.get("Workers")) # Gets the number of currently registered slaves on the system. At least 0
master.set("Workers", workers+1)
def subscribeToMaster():
pubsubS.subscribe("Board")
def listenToBoard(): # Method to retrieve the information fro... | The code defines a function `slave()` that initializes a slave node in a distributed system. It registers the slave, subscribes to a master node for communication, and listens to a board for incoming tasks or data, enabling coordination within the system. | def slave():
registerNewSlave()
subscribeToMaster()
listenToBoard() |
def Error(self,peso,matrizX,matrizY):
yc = self.Yc(peso,matrizX)
y = matrizY
resta = yc - y
error = np.array(resta)
return error
def Norma(self,peso,matrizX,matrizY):
error = self.Error(peso,matrizX,matrizY)
norma = np.linalg.norm(error... | This function performs gradient descent to adjust a neural network's weights (w) by iteratively minimizing the error between predicted and actual outputs (matrizX, matrizY). It updates weights using the learning rate (tasa) until the error norm (norma) falls below a threshold (umbral). The process tracks convergence fo... | def NeuronaStart(self,tasa,umbral,peso,matrizX,matrizY,id):
ward = []
w = peso
bandera = False
while bandera == False:
error = self.Error(w,matrizX,matrizY)
norma = self.Norma(w,matrizX,matrizY)
x = matrizX
... |
def checkIfElementIsLoadedByXpath(self, elementXpath):
try:
element = WebDriverWait(self.driver, 120).until(EC.presence_of_element_located((By.XPATH, elementXpath)))
if element:
self.logger.info("element is loaded in the page")
time.sleep(3)
... | The main task of the code is to retrieve user information by verifying the presence of a user's name and phone number, locating a contact element via XPath, and collecting data if successful. It returns True if user info is collected successfully, otherwise False, while logging errors for missing elements or invalid da... | def getAlluserInfo(self):
if self.person.name and self.person.phoneNumber:
contactDiv = self.checkIfElementIsLoadedByXpath(self.Xpath.contactDivXpath)
if contactDiv:
self.openContact()
self.checkIfBussinessProfile()
result = self.collectUse... |
def sameAboutBio(self):
'''
this method to check if the new about deffers from the last one
Returns:
bool: True if the about status bio has changed, False otherwise.
'''
try:
if not self.persondb:
self.logger.... | The main task of the code is to monitor changes in a user's "about" bio. If the bio has changed, it fetches new data if missing, updates the local data, and attempts to change the user's about bio, returning True on success or False otherwise. If no change is detected, it logs that the bio remains unchanged. | def monitorAbout(self):
sameAbout = self.sameAboutBio()
if sameAbout == False:
if not self.data.get('about'):
self.getAlluserInfo() # if no about data fetch new ones from the servers
self.data['newAbout'] = self.data.get('about')
resul... |
def downloaImage(self, imgUrl, tempImage=False):
try:
if imgUrl and self.person.name and SharedMethods.BaseClass.checkIfDir(f"Files/{self.person.name}"): # ensure that the person has dir profile
ImgName = f"Files/{self.person.name}/whatsApp/TempSmallImage" if tempImage else f'Files/{... | The function monitors a user's profile picture by downloading and storing new images if they differ from existing ones. It retrieves image URLs, downloads the small image, checks for changes using `sameProfilePic()`. If different, it fetches missing URLs, downloads the big image, stores both in the database, and return... | def monitorProfilePic(self):
bigImageUrl, smallImageUrl = self.data.get('bigImageUrl'), self.data.get('smallImageUrl')
self.newSmallImage = self.downloaImage(smallImageUrl, tempImage=True)
samePic = self.sameProfilePic()
if samePic == False:
if not (bigImageUrl and smallImage... |
def setup_globals():
global input_maf, annotated_maf, scripts_dir, oncokb_scripts, gl_input, gf_map_input, dbscSNV_data, cv5, cv6, myVariant_merged, ONCOKB_API_TOKEN, debug
#create argument parser
parser = argparse.ArgumentParser()
parser.add_argument('--input_maf', type=str, help='The input maf f... | The main task of the code is to process and annotate a MAF file by renaming columns, filtering blacklisted variants, calculating MAF values, filtering rare variants (ExAC2_AF < 2%), removing duplicates, merging gene-level annotations (oncogenes, tumor suppressors), and performing downstream analyses. The output include... | def main():
# parse arguments from command line and then initialize necessary directories
setup_globals()
# load the input data into dataframe
input_maf_data = pd.read_csv(input_maf, sep = '\t', low_memory = False)
if 'Tumor_Seq_Allele2' in input_maf_data:
input_maf_data.rename(columns={'Tu... |
def exec_tsm(*args):
# # Create a subprocess, and execute the given command
log(level="Info", message=f"Running the following tsm command: {' '.join(args)}")
tsm_output = check_output(args).decode('UTF-8')
# # Log, then return the output of the TSM command
log(message=tsm_output, level="In... | The function performs a backup of TSM (Tivoli Storage Manager) configurations and data by generating dated filenames, cleaning the server, exporting settings to a JSON file, creating a `.tsbak` backup, uploading both files to an S3 bucket with a specified prefix, and deleting local backups. It returns `True` on success... | def backup(tsm, bucket_name, s3_prefix):
# Generate a filename for the tsbak
today = datetime.now().strftime('%Y-%m-%d')
# cleanup the server first
exec_tsm(tsm, "maintenance", "cleanup", "--all")
# export the tsm settings
settings_filename = f"{today}-settings.json"
settings_fullpa... |
def setup_logging(log_file_path, additional_modules):
# Define how to handle logging within this script
logging.basicConfig(
format='%(message)s',
level=logging.INFO,
handlers=[
logging.FileHandler(log_file_path),
logging.StreamHandler()
]
)
... | The main task of the code is to perform Tableau backup/restore operations using TSM (Tableau Server Management) and AWS S3. It parses command-line arguments for 'backup' or 'restore' actions, configures logging, interacts with AWS S3 via specified parameters, and executes the respective operation: backing up Tableau da... | def main():
# Setup logging
setup_logging(log_file_path="tableau-backup-restore-s3.log",additional_modules=["boto3","botocore"])
# Parse parameters
parser = argparse.ArgumentParser()
parser.add_argument("--command", help="Options are 'backup' or 'restore'", type=str, required=True)
parser... |
def __deep_update_and_copy(source, target, typing = True):
obj = __update({}, source);
_obj = target;
for key, value in _obj.items():
if key in obj.keys():
if(typing and (type(obj[key]) != type(value))): # and (type(obj[key]) != dict and type(value) != dict)):
raise TypeE... | The main task of the code is to test deep copy and update functionalities for nested/circular data structures. It verifies that __deep_copy creates independent copies (modifications to copies do not affect originals), while __deep_update_and_copy merges dictionaries hierarchically without overwriting. Tests include nes... | def __test__():
foo = 'foo';
a1 = {foo: {1: '2', 4: 4, 5: 5, 6: {7: {9: 9}}}, 'a': 5};
a2 = {foo: {1: '1', 2: '2', 6: {7: {8: {}}}}, 'a': int(6)};
# __deep_update(a1, a2); # not overwriting all the objects
# a1.update(a2); # overwriting all the objects
a3 = __deep_update_and_copy(a1, a2);
p... |
def check_for_template(screenshot, template):
points = template_matching(screenshot, template, threshold=0.8)
points = non_maximum_suppression_points(points, ITEM_SLOT_PIXEL_SIZE)
if len(points) == 0:
return False, None
if len(points) > 1:
print(f"WARNING: there is multiple locations fo... | The code detects game states (main menu/raid) via template matching, identifies active CAPTCHA windows, extracts CAPTCHA item names using OCR, locates item slots in the game window, and overlays visual indicators on detected items. It adjusts update intervals based on game context and dynamically updates the UI to high... | def update():
global captcha_was_active, menu_was_active, update_period_in_ms
# locate captcha window and item name
screenshot = screenshot_taker.take_screenshot()
# check if in main menu
menu_is_active, point = check_for_template(screenshot, tarkov_menu_image)
if menu_was_active != menu_is_ac... |
def million(n):
num_word.append((number(n[:n.index(",")]) + " million, ").capitalize())
n = n[n.index(",") + 1:]
thousand(n)
def thousand(n):
num_word.append((number(n[:n.index(",")]) + " thousand, ").capitalize())
n = n[n.index(",") + 1:]
num_word.append(number(n).lower())
def number(n):
if... | The code converts a number to words by analyzing commas in its string representation. It counts commas to determine the scale (thousands/millions) and uses helper functions (`thousand`, `million`, `number`) to convert segments of the number into words, appending results to `num_word` for final output. | def turn_num_to_word(n):
comma_count = 0
working_num = f"{n:,}"
for i in working_num:
if "," == i:
comma_count += 1
match comma_count:
case 2:
million(working_num)
case 1:
thousand(working_num)
working_num = working_num[working_nu... |
def inorder(self):
"""calls recursive inorder_helper()"""
output = []
self.inorder_helper(self.root, output)
return output
def remove(self, data):
"""removes value from BST"""
return self.remove_helper(self.root, data)
def re_balance_helper(self, lyst, bst):
'''re... | The main task of the code is to rebalance a Binary Search Tree (BST) by first extracting its elements via inorder traversal, removing all existing nodes, deduplicating the extracted elements, and then reconstructing a balanced BST from the deduplicated sorted list using a helper function. | def rebalance_tree(self):
'''rebalances BST'''
unbalanced_tree_list = self.inorder()
for i in unbalanced_tree_list:
self.remove(i)
res = []
for num in unbalanced_tree_list:
if num in res:
continue
else:
res.appe... |
def calc_water_X(self):
self.water_X = 0
self.calc_water_X1()
while abs(self.water_X - self.water_X1) >= 1e-4:
if self.charge_density > 0:
self.water_X += 1e-4
self.calc_water_X1()
elif self.charge_density < 0:
self.water_X ... | The main task of the code is to calculate the value of `big_gamma` using the formula involving `water_a`, `water_dipolar_moment`, `sinh(-water_X)`, `theta_free`, and `water_mole_thicknes`. It first computes intermediate values `water_X` and `theta_free` before applying the formula, then returns the computed `big_gamma`... | def calc_big_gamma_water(self):
self.calc_water_X()
self.calc_theta_free_water()
self.big_gamma = self.water_a * self.water_dipolar_moment * sinh(-self.water_X) * self.theta_free \
/ (self.water_mole_thicknes ** 2)
return self.big_gamma |
def move(self, particle, direction):
old_position = particle.sub_particles.keys()
o, p, q = direction
x, y, z = particle.position
new_position = (x+o, y+p, z+q)
new_pos = self.grid.get(new_position)
if new_pos is None:
particle.move(direction)
for ... | This function processes particle events based on the event code. It executes actions like diffusion, charging, discharging, or dimer formation, updates counters (e.g., del_q, n_mv_d), and sets event types (e.g., 'Diffusion', 'MV_Charge'). For eventcode 11, it handles dimer degradation, increments dimer counters, and ca... | def execute_event(self, particle, eventcode):
if isinstance(event_decode[eventcode], tuple):
self.move(particle, event_decode[eventcode])
self.del_q = 0
self.event_type = 'Diffusion'
elif eventcode == 8:
self.discharge(particle)
self.del_q = -... |
def add_particles(self, particles):
self.grid.update(particles)
def calc_electrode_surface_concentration(self):
self.n_mv_nd_ef = 0
self.n_mv_d_ef = 0
for particle in self.particles:
if particle.z >= self.Z - 1 and particle.particle_charge == 1:
self.n_mv_nd_e... | The code initializes particles of three types (mv_nd, mv_d, cl_ion) by randomly generating positions, ensuring no overlaps with existing grid particles. It appends valid particles to lists, updates the grid, and triggers post-initialization calculations for electrode concentration, reaction rates, and field solving to ... | def initialize_particles(self):
self.mv_nd_init = []
self.mv_d_init = []
self.cl_ion_init = []
for i in range(self.n_mv_nd):
while True:
x = randint(1, self.X)
y = randint(1, self.Y)
z = randint(1, self.Z)
tmp_p ... |
def compile_rate_list(self):
rate_list = []
events = []
for particle in self.particles:
# Reaction event
if particle.z > self.tunneling_limit and particle.particle_charge == 1:
pass
# reaction_rate = self.get_reaction_rate(particle.z, part... | This method performs a kinetic Monte Carlo (KMC) simulation step by selecting events based on their rates, updating system time and charge density, and recalculating physical properties. It compiles event rates, normalizes them into probabilities, randomly selects an event, executes it, computes a time increment (dt) u... | def vssm_sonar(self):
self.compile_rate_list()
rates = np.array(self.kmc_rates, dtype=float)
self.K_total = rates.sum()
probabilities = rates / self.K_total
n_events = len(rates)
if not n_events:
print('no more event available')
raise ValueError("e... |
def simu_condiiton_setting(self, name, **kwargs):
self.file_xyz = name + '.xyz'
self.file_pot = name + '.out'
self.file_psd = name + '.txt'
self.iteration = kwargs['max_iterations']
self.frequency = kwargs['frequency']
self.cut_off_time = kwargs['time']
def set_board_inf... | This code initializes a simulation object by configuring conditions, board settings, electrolyte properties, electrochemistry parameters, and other operational data. It sets up the simulation environment, initializes particles in a grid, and resets the simulation time to zero, preparing the system for computational mod... | def __init__(self, run_info, board_info, operation_conditions, electrolyte_info,
electrochemistry_info, MV_info, *args, **kwargs):
self.simu_condiiton_setting(**run_info)
self.set_board_info(board_info, operation_conditions, electrolyte_info)
self.set_operation_conditions(opera... |
def upload(source_path, destination_path):
print(f"upload: {source_path} -> {destination_path}")
des_dir = os.path.dirname(destination_path)
if des_dir != "":
ssh(f"mkdir -p {des_dir}")
run_cmd(
f"rsync -av --rsh='ssh -o StrictHostKeyChecking=no -p {DEPLOY_PORT}' "
f" {source_pat... | This function executes SSH commands, either uploading and running a local script file on a remote server or directly executing a command from remaining arguments. It handles file uploads, sets execute permissions, and uses SSH with optional root privileges. | def ssh_action(args: argparse.Namespace, remaining_args: list[str]):
if args.file:
file = args.file
name = splitext(basename(file))[0]
suffix = splitext(basename(file))[1]
timestamp = int(time.time())
# dest_file = f"/tmp/{name}_{timestamp}{suffix}"
dest_file = f"/tmp... |
def muse_readfile_from_line(filename, start_line = 1): # LINE INDEX STARTS AT ONE
data = [[],[],[],[],[]]
current_line = 1
with open(filename) as csvfile:
dataset = csv.reader(csvfile)
header = (start_line == 1)
while(current_line < start_line): # skip ahead in the file until current_line == start_line
curr... | This function performs real-time EEG analysis on an updating CSV file, calculating power metrics (band averages or ratios) for multiple electrodes. It monitors file updates, appends new data, computes spectral power in specified frequency ranges (theta, alpha, beta), and logs results in different modes (raw power, abso... | def eeg_live_analysis_from_updating_file(filename="current_stream_data.csv", mode = 1, duration=1800, mean_time_interval=5, print_power=True):
# run for duration (seconds)
# checks for updated data file every check_for_update_interval (seconds)
# if data file has no update, check again after check_for_update_interva... |
def muse_readfile(fn):
# file vars
file = [[],[],[],[],[]] # no shorthand, memory assignment issue
filename = fn
# store file data in 2d list file[tag_index][n] where n is the data point
with open(filename) as csvfile:
dataset = csv.reader(csvfile)
hold = True
for row in dataset:
if(hold):
for i ... | The code processes raw EEG data from a Muse file, segmenting it into time windows (default 10s) to compute relative band power averages for four electrodes across specified frequency ranges (FN_lower-FN_upper and FD_lower-FD_upper). It saves results as a CSV file with timestamps and bandpower values for each segment, r... | def convert_raw_to_rel_bandpower(filename, FN_lower, FN_upper,FD_lower, FD_upper,frames_per_seg=2560, advancement = 2560, write=True): #default 10s with 256 hz
dataset = muse_readfile(filename)
output = [[],[],[],[],[]]
# add headers
for i in range(5):
output[i].append(dataset[i][0])
current_win_end = frames_per... |
def muse_readfile(fn):
# file vars
file = [[],[],[],[],[]] # no shorthand, memory assignment issue
filename = fn
# store file data in 2d list file[tag_index][n] where n is the data point
with open(filename) as csvfile:
dataset = csv.reader(csvfile)
hold = True
for row in dataset:
if(hold):
for i ... | This code converts raw EEG data into three frequency band power ratios (alpha/theta, alpha/beta, theta/beta) for each electrode over time segments. It processes non-overlapping 10-second windows (2560 frames at 256Hz), calculates relative band power averages, and stores results in a structured CSV format with timestamp... | def convert_raw_to_3ratio_bandpower(filename,frames_per_seg=2560, advancement = 2560, write=True): #default 10s with 256 hz
dataset = muse_readfile(filename)
freq_ranges = [[4,8],[8,12],[12,30]]
output = [[],[],[],[],[],[],[],[],[],[],[],[],[]]
# add headers
output[0].append(dataset[0][0])
for i in range(1,5):
... |
def __set_foldername(self, folder):
'''
Set a valid folder name, either the one saved
in this instance or the provided one.
'''
if folder == 'default':
if not self.hasSaved:
raise ValueError('Name of the folder to read from must be specified unless... | This function plots the time evolution of the average value of a specified quantity from simulation data. It validates inputs, runs simulations, collects time-series data, computes averages, and generates a plot with optional trendlines and relative scaling. The plot displays average values over time, labeled with unit... | def plot_avg(self, quantity, folder='default', measure_time='auto', title='', showTrendline=False, relative=False, units={}):
'Plots the time evolution of the average of a given quantity.'
# *** Make sure that the inputted values are valid ***
quantity = str(quantity)
folder = str(fol... |
def __set_foldername(self, folder):
'''
Set a valid folder name, either the one saved
in this instance or the provided one.
'''
if folder == 'default':
if not self.hasSaved:
raise ValueError('Name of the folder to read from must be specified unless... | The main task of the code is to read the last data arrays from files in a specified folder and convert simulation parameters into a dictionary, returning both the arrays and the processed parameters. It involves setting up the folder, initializing data, reading the final arrays, closing files, and using an adaptive con... | def get_last_data(self, folder):
'''
Reads the last arrays in the files of the given folder
and returns them in a dictionary.
'''
# Set valid folder name
self.__set_foldername(folder)
# Set attributes required for reading the data
self.__get_init_data()... |
def __set_foldername(self, folder):
'''
Set a valid folder name, either the one saved
in this instance or the provided one.
'''
if folder == 'default':
if not self.hasSaved:
raise ValueError('Name of the folder to read from must be specified unless... | This function generates an animation visualizing the time evolution of a 1D fluid simulation, plotting a specified quantity across spatial extent. It validates inputs, prepares figures with labeled axes and units, and defines an update function to render dynamic data. Options include saving snapshots, generating videos... | def animate_1D(self, quantity, folder='default', extent=[0, 1], anim_fps='auto', showDeviations=True, showParams=True, height=6, aspect=1.3, title='', save=False, anim_time='auto', video_fps=30, video_name='auto', snapshots=None, units={}):
'Creates an animation of the time evolution of a 1D simulation.'
... |
def __set_foldername(self, folder):
'''
Set a valid folder name, either the one saved
in this instance or the provided one.
'''
if folder == 'default':
if not self.hasSaved:
raise ValueError('Name of the folder to read from must be specified unless... | This function generates an animation visualizing the time evolution of a 2D fluid simulation quantity (e.g., density, velocity). It creates interactive plots with color-mapped fields, vector quiver plots, dynamic text displays (time, deviations, parameters), and configurable output options (snapshots/videos). The anima... | def animate_2D(self, quantity, matrixLike=True, folder='default', extent=[0, 1, 0, 1], anim_fps='auto', showDeviations=True, showParams=True, showQuiver=True, quiverscale=1, N_arrows=20, interpolation='none', cmap='jet', height=6, aspect='equal', cbar_aspect=0.02, title='', save=False, anim_time='auto', video_fps=30, v... |
def __set_foldername(self, folder):
'''
Set a valid folder name, either the one saved
in this instance or the provided one.
'''
if folder == 'default':
if not self.hasSaved:
raise ValueError('Name of the folder to read from must be specified unless... | This function generates an animation visualizing the horizontally averaged vertical energy flux over time. It validates inputs, prepares a matplotlib figure, sets axis limits/labels, and defines an update function to animate the flux data. The animation can save snapshots or a video, displaying time, simulation steps, ... | def animate_energyflux(self, folder='default', extent=[0, 1, 0, 1], anim_fps='auto', showParams=True, height=7, aspect=1.1, title='', save=False, anim_time='auto', video_fps=30, video_name='auto', snapshots=None, units={}):
'Creates an animation of the horizontally averaged vertical energy flux.'
# **... |
def tenant_information(sdk, idname, global_vars):
print_array = []
print_array.append({ style: P1, data: "TENANT Information"})
resp = sdk.get.tenants()
if resp.cgx_status:
tenant_name = resp.cgx_content.get("name", None)
print_array.append({ style: B0, data: pBold("Tenant Name") + ": " ... | The main task of the code is to perform a series of network health checks using a provided SDK and API, gather tenant and site information, apply threshold-based metrics (jitter, loss, latency), and report results via Slack. It updates global variables for data sharing, triggers health-check functions for disconnected ... | def dashboard_health_check(raw_api, sdk, idname):
global global_vars
global passed_raw_api
passed_raw_api = raw_api
print_array = []
constructed_raw_message = {
"channel": passed_raw_api.channel_id,
"as_user": passed_raw_api.self_id,
"blocks": gl... |
def random_grid() -> np.array:
""" Generate a random grid for training. """
# sample parameters --- between 50 to 100 pixels, 45 degree rotations
# dist = randrange(500, 910)
dist = randrange(HEIGHT*25/64, HEIGHT*25/32)
angle = tuple(randrange(-pi/4, pi/4) for i in range(3))
# generate grid and ... | The function generates a training pair (X, y) by modifying a grid. It randomly removes points from the original grid (y) based on parameter `f`, then adds `n` new random points to create X. Both X and y are converted to images for training, combining data augmentation with original grid data. | def train_pair(f: float=1/2, n: int=100) -> tuple:
""" Return the training pair (X, y). """
y = random_grid()
# remove points from the original grid
X = rng.permutation(y)
X = X[:round((1 - randrange(0, f))*len(y))]
# add new random points
m = rng.integers(n)
px, py = rng.integers(HEIGHT... |
def init(K: int, points: list, weight: dict) -> list:
""" Returns a list of K initial points with the k-means++ strategy. """
# start with an arbitrary point
l = [points[sample(norm([weight[p] for p in points]))]]
for k in range(K - 1):
i = sample(norm([dist(q, closest(l, q))*weight[q] for q in ... | The code implements the k-means clustering algorithm to group data points into K clusters. It initializes centroids, assigns each point to the nearest centroid, updates centroids as the average of their assigned points, and repeats until convergence. The process reduces redundant points by frequency weighting, ensuring... | def k_means(K: int, points: list) -> tuple:
""" Applies the k-means clustering algorithm on the data. """
# weight points to remove redundant points while keeping centroids the same
freq = {}
for point in points:
freq[point] = freq.get(point, 0) + 1
centers = init(K, list(freq.keys()), freq)... |
def load_yaml(file_path):
"""
Load yaml file
:param file_path: path of the yaml file ready to load
:return: content of the file
"""
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = yaml.load(f.read(), Loader=yaml.Loader)
return content
except y... | The function validates a SIG's metadata by checking the existence and structure of its 'sig-info.yaml' file, verifying required fields, maintaining consistency between repository data and directory structure, and ensuring valid maintainers, committers, and contributors. It accumulates and returns error counts from each... | def check_sig_info(sig, access_token):
print('\nStarting to check sig info of sig {}'.format(sig))
sig_info_errors = 0
# 1. Get sig-info.yaml
sig_info_path = os.path.join("community", 'sig', sig, 'sig-info.yaml')
sig_dir_path = os.path.join("community", 'sig', sig)
if not os.path.exists(sig_inf... |
def get_branches(self, pkg):
"""
get history branches and change_branches of a package
:param pkg: a dict of the package
:return: a tuple of history branches and change_branches
"""
pkg_name = pkg['name']
branches = pkg['branches']
history_branches = []
... | The code checks for errors and warnings in a PR by comparing history and changed branches for each package. It iterates through `self.change_msg`, retrieves branch lists, runs `history_check` and `differences_check` if branches exist, logs results, and exits with an error if any issues are found. | def check(self):
for pkg in self.change_msg:
history_branches, changed_branches = self.get_branches(pkg)
if history_branches:
self.history_check(history_branches, pkg)
if changed_branches:
self.differences_check(changed_branches, pkg)
p... |
def parse_arguments():
parser = argparse.ArgumentParser(
description='A tool for checking the consistency between multiple SIG information'
' and sigs.yaml, and validation of fields for every SIG information.')
parser.add_argument('-o', '--owner', help='owner of Pull Request', requir... | The main task of the code is to check if modified SIGs (Special Interest Groups) in a GitHub Pull Request have valid information and no existing OWNERS files. It parses arguments, retrieves PR diff files, identifies changed SIGs, skips checks for 'sig-template', verifies each SIG's info, counts errors, and exits with f... | def main():
args = parse_arguments()
owner = args.owner
repo = args.repo
number = args.number
access_token = args.token
# get diff files of the Pull Request
diff_files = check_diff_files(owner, repo, number)
# get all sigs have changed
change_sigs = []
for diff_file in diff_files... |
def expand_attribute(self, attribute):
"""Expand attribute to get more info about itself."""
parent_name = []
while attribute.__class__ is ast.Attribute:
parent_name.append(attribute.attr)
attribute = attribute.value
name, attr_id = '.'.join(reversed(parent_name))... | This code parses a class definition from an AST symbol, extracting attributes, methods, decorators, docstring, and line number, then returns them in a structured dictionary format. | def parse_class(self, symbol):
"""Parse class and get info from itself."""
docstring, attr, func, decora, name = "", {}, {}, [], symbol.name + '('
name += ', '.join(self.expand_attribute(_) for _ in symbol.bases) + ')'
for sym in symbol.body:
if sym.__class__ is ast.Assign:
... |
def parse_assign(self, symbol):
"""Parse assign and get info from itself."""
assigns, attributes = {}, {}
for var in symbol.targets:
if var.__class__ == ast.Attribute:
attributes[var.attr] = var.lineno
elif var.__class__ == ast.Name:
assign... | This code parses Python source code to extract and organize information about classes, functions, assignments, imports, and docstrings into a structured dictionary. It uses AST parsing to identify symbols, categorizes them into attributes, functions, and classes, and returns a comprehensive symbol table for analysis or... | def get_symbols(self, source, filename=''):
"""Parse module code to get Classes, Functions and Assigns."""
symbols, globalAttributes, globalFunctions, classes = {}, {}, {}, {}
try:
module = ast.parse(source)
except:
log.warning("Python file has syntax errors: {0}!... |
def _get_logger():
if "LOGGING_LEVEL" in env:
level = logging.getLevelName(env["LOGGING_LEVEL"])
else:
level = logging.INFO
logging.basicConfig(
level=level, format="%(levelname)-7s %(name)-22s %(message)s", style="%"
)
return logging.getLogge... | This code initializes a Tuya API client by setting up authentication parameters, restoring previous authorization details from a file, validating required credentials, and handling token authentication or refresh. It configures headers for API requests and ensures a valid access token is available for subsequent API in... | def __init__(
self,
region: str,
client_id: str,
client_secret: str,
):
self.region = region
self.client_id = client_id
self.client_secret = client_secret
self.token = None
self.refresh_token = None
self.token_expire = 0
self.a... |
def build_model_conv1d(x_train, num_classes: int):
model = Sequential()
model.add(Convolution1D(32, 3, activation='relu',
input_shape=(x_train.shape[1], 1)))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(MaxPooling1D(2))
model.add(Flatten())
model.add(Dense(... | (Conv1D function trains a 1D Convolutional Neural Network (CNN) on provided training data, evaluates it on test data, and appends classification metrics to a result list. It converts labels to categorical format, trains the model with early stopping callbacks, predicts test class probabilities, extracts predicted label... | def Conv1D(X_train, X_test, Y_train, Y_test, num_classes, result: list):
model_conv1d = build_model_conv1d(X_train, num_classes)
Y_train = to_categorical(Y_train, num_classes)
callback1, callback2, callback3 = make_callback_earlystop()
history = model_conv1d.fit(X_train, Y_train, validation_split=0.15, ... |
def hasItLanded(self):
row = (len(self.currentShape) - 1)
for col in range(len(self.currentShape[0])):
if self.yPos + len(self.currentShape) >= self.length:
self.landed = True
elif self.currentShape[row][col] != 0 and self.gameBoard[self.yPos + len(self.currentSh... | The main task of this code is to manage the game loop for a Tetris-like game, handling block movement, line clearing, score updates, and difficulty adjustment. It moves the falling piece down at intervals, checks for landings, clears completed lines when triggered, increases the score and multiplier, and adjusts fallin... | def gameLoop(self):
if not self.isItBeingCleared:
# Moves the block down slowly buy allows to move sideways or rotate faster
if self.loopCounter > self.fallingSpeed:
self.hasItLanded()
self.movePieceDown()
self.loopCounter = 0
else:... |
def _off_to_on_fade(self, travel_fraction, is_first_step, is_last_step):
if is_first_step:
self._current_state.color_temp_kelvin = self._target_state.color_temp_kelvin
self._current_state.hue = self._target_state.hue
self._current_state.saturation = self._target_state.saturat... | This function calculates the progress fraction (travel_fraction) of a state transition based on elapsed time, then applies the appropriate fade method (e.g., on/off transitions, saturation changes, hue shifts) to update the system state, using the specified fade type and step context (first/last step) to determine the ... | def _compute_new_state(
self, change_time_secs: float, is_first_step: bool, is_last_step: bool
):
travel_fraction = (change_time_secs - self._last_state_change_time_secs) / (
self._end_time_secs - self._last_state_change_time_secs
)
travel_fraction = min(1, travel_fractio... |
def url_to_image(self, url):
options = Options()
options.add_argument("--headless")
options.add_argument("--window-size={},{}".format(*default_options.resolution))
options.add_argument("--hide-scrollbars")
options.add_argument(f"--force-device-scale-factor={2.0}")
driver ... | The code initializes an object to convert HTML content from a URL, file, or string into an image, sets a default output video file name ("html_page.mp4"), and configures properties like duration and static mode. It prioritizes loading HTML via a URL, then a file, then a string, using specific methods for each source. | def __init__(self, html_str=None, html_url=None, html_file=None, duration=5,
actions=[]):
self.duration = duration
if html_url is not None:
self.img = self.url_to_image(html_url)
if html_file is not None:
self.img = self.file_to_image(html_file)
e... |
def mem_help():
print("mem r [address] [size] - Hexdumps memory, size has to be >= 4")
print("mem d [address] [size] [filePath] - Dumps memory into a file, size has to be >= 4")
print("mem rb [address] - Reads a single byte")
print("mem rs [address] - Reads a string")
print("mem w [filePath] [addres... | This function handles memory operations based on command-line arguments: reading/writing memory regions, dumping data, or writing files/bytes. It supports commands like 'r' (read hex dump), 'w' (write file), 'wd'/'wb' (write dword/byte), 'rb' (read byte), 'rs' (read string), and 'd' (dump memory). It validates input ar... | def mem_command(args):
if len(args) == 0:
mem_help()
return
if len(args) > 1:
if len(args) == 3:
if args[0] == "r":
hexdump(mem_read(int(args[1], 16), int(args[2], 16)))
elif args[0] == "w":
filePath = args[1]
addr ... |
def mem_write_dword(addr, dword):
runUnderware(f"photo_hw.write {hex(addr)} 4 {hex(dword)}")
def runUnderware(s):
return runShellCommand(f"udws \"{s}\"")
def build_rop(name, directory):
chainPath = os.path.join(directory, name)
if not os.path.exists(chainPath):
print(f"{chainPath} does not exist... | This code sets up a Return-Oriented Programming (ROP) exploit chain by adjusting thread priorities, disabling watchdogs, and writing a custom ROP payload into memory. It configures a fake export table to redirect execution flow, then triggers the exploit via a network command to exploit a vulnerability in the target sy... | def rop_run(name, path):
print("Setting tGGW priorities and thresholds so our RopChain doesn't preempt...")
ggwThread = tasks["tGGW"]
mem_write_dword(ggwThread + 0x38, 0) # priority
mem_write_dword(ggwThread + 0x48, 0) # preempt_threshold
mem_write_dword(ggwThread + 0xC0, 0) # user_priority
m... |
def task_help():
print("task parse - Parses the threads of all tasks in memory")
print("task list - Lists parsed tasks")
print("task save [fileName] - Saves the parsed threads to a file")
print("task load [fileName] - Loads the parsed threads from a file")
print("task dump [taskName] - Dumps all fie... | This code parses and manages task information from memory, allowing users to list tasks, save/load task data, and dump task details or stack memory. It reads memory structures, extracts task names and addresses, and provides commands for inspecting or exporting task-related data. | def task_command(args):
global tasks
if len(args) == 0:
task_help()
return
if len(args) == 1:
if args[0] == "parse":
tasks = {}
print("Reading sm_ModuleTaskThreads...")
taskThreadList = struct.unpack(">" + ("I" * 256), mem_read(sm_ModuleTaskThrea... |
def struct_help():
print("struct dump [structName] [address] - Reads a struct at the specified address and dumps its fields")
print(
"struct stackdump [structName] [taskName] [offset] - Reads a struct from the stack of the specified task and dumps its fields")
print("struct list - Lists all availabl... | The main task of the code is to process commands for reading and dumping memory structures. It handles "dump" (reading a struct from a memory address), "stackdump" (reading a struct from a task's stack), and "list" (displaying available structs). It validates inputs, checks struct/task existence, and uses helper functi... | def struct_command(args):
if len(args) == 0:
struct_help()
return
if len(args) > 1:
if len(args) == 3 and args[0] == "dump":
structName = args[1]
structAddress = int(args[2], 16)
if structName not in structs:
print(f"{structName} doesn... |
def rop_help():
print("rop list - Lists available RopChains")
print("rop build [chainName] - Builds a RopChain and hexdumps it")
print("rop run [chainName] - Builds a RopChain and runs it")
def build_rop(name, directory):
chainPath = os.path.join(directory, name)
if not os.path.exists(chainPath):
... | This function processes ROP chain commands: lists available chains, builds ROP payloads as hex dumps, or runs specified chains while printing serial output until completion. It handles "list", "build", and "run" subcommands with appropriate arguments, using ROP_PATH for file operations and serial communication for exec... | def rop_command(args):
if len(args) == 0:
rop_help()
return
if len(args) == 1 and args[0] == "list":
chains = [f for f in os.listdir(ROP_PATH) if os.path.isfile(os.path.join(ROP_PATH, f))]
print("Available chains:")
for chain in chains:
print(chain)
elif ... |
def code_help():
print(f"code list - Lists projects in \"{CODE_PATH}\"")
print("code run [name] - Builds and runs the specified project")
def rop_run(name, path):
print("Setting tGGW priorities and thresholds so our RopChain doesn't preempt...")
ggwThread = tasks["tGGW"]
mem_write_dword(ggwThread + ... | The code's main task is to handle commands for listing available code projects and running selected projects. When running a project, it compiles the code, generates ROP chains with memory addresses, writes binaries to device memory, and executes them via serial communication. It manages memory allocation, template rep... | def code_command(args):
global scratchAddress
global dataAddress
if len(args) == 0:
code_help()
return
if len(args) == 1 and args[0] == "list":
print("Available projects:")
codeList = [dir for dir in os.listdir(CODE_PATH) if os.path.isdir(os.path.join(CODE_PATH, dir))]
... |
def load_config(self):
self.auto_adjust_scan_ip_thread_num = config.CONFIG.getint("google_ip", "auto_adjust_scan_ip_thread_num")
self.max_scan_ip_thread_num = config.CONFIG.getint("google_ip", "max_scan_ip_thread_num") #50
self.scan_ip_thread_num = self.max_scan_ip_thread_num
self.max_go... | The code's main task is to initialize an object by loading configuration settings, retrieving IP addresses, and searching for additional Google IPs during object creation. The `__init__` method sequentially calls three methods: `load_config()` to fetch configurations, `load_ip()` to retrieve IP data, and `search_more_g... | def __init__(self):
self.load_config()
self.load_ip()
self.search_more_google_ip() |
def is_bad_ip(self, ip_str):
if ip_str in self.bad_ip_pool:
return True
return False
def add_ip(self, ip_str, handshake_time, domain=None, server=None):
if not isinstance(ip_str, basestring):
xlog.error("add_ip input")
handshake_time = int(handshake_time)
... | This function scans IP addresses by retrieving them from a range, validating, testing connectivity, and managing a list of valid IPs. It runs in a loop controlled by thread limits and connection status, logs results, handles errors like honeypots, and maintains the IP list by removing slow entries and saving updates. | def scan_ip_worker(self):
while self.searching_thread_count <= self.scan_ip_thread_num and connect_control.keep_running:
if not connect_control.allow_scan():
time.sleep(10)
continue
try:
time.sleep(1)
ip_int = ip_range.get_... |
def conn_sql(self):
#connect to db
try:
cnxn = pymssql.connect(self.server, self.user_login, self.password, self.database)
cursor = cnxn.cursor()
return cnxn,cursor
except Exception as e:
self.alert_slack("Danger! cannot connect sql server")
... | (The main task of the code is to insert log data into a SQL Server database table. It connects to the database, executes an INSERT query with timestamp, status, file name, process, message, and error fields from the `result` dictionary, then commits the transaction. If an error occurs during insertion, it sends a Slack... | def log_to_db(self,result):
#connect to db
cnxn,cursor=self.conn_sql()
try:
cursor.execute(f"""
INSERT INTO [{self.database}].[dbo].[{self.table_log}]
values(
getdate(),
'{result["status"]}',
... |
def alert_slack(self,msg):
value = alert.slack_notify(self.slack_notify_token,msg)
if value == constant.STATUS_OK:
self.info_msg(self.alert_slack.__name__,'send msg to slack notify')
else:
self.info_msg(self.alert_slack.__name__,value)
def alert_error_msg(self,result):
... | The main task of the code is to generate an error response dictionary, send an alert via Slack, log the error to a database, and exit the program. If any step fails, it logs the exception and exits. It handles errors by centralizing error reporting, ensuring alerts are sent, data is logged, and the process terminates g... | def error_msg(self,process,msg,e):
result = {"status":constant.STATUS_ERROR,"file_name":self.path_now,"process":process,"message":msg,"error":e}
try:
self.alert_slack(self.alert_error_msg(result))
self.log_to_db(result)
sys.exit()
except Exception as e:... |
def conn_sql(self):
#connect to db
try:
cnxn = pymssql.connect(self.server, self.user_login, self.password, self.database)
cursor = cnxn.cursor()
return cnxn,cursor
except Exception as e:
self.alert_slack("Danger! cannot connect sql server")
... | The main task of the code is to create a database table if it doesn't exist. It connects to a SQL database, attempts to create a table using predefined name and columns, and handles exceptions: logging success if created, detecting existing tables, or reporting column definition errors and unknown creation failures. | def check_table(self):
#connect to db
cnxn,cursor=self.conn_sql()
# create table
try:
cursor.execute('''
CREATE TABLE '''+self.table+''' (
'''+self.table_columns+'''
)
''')
cnxn.commit()
curso... |
def conn_sql(self):
#connect to db
try:
cnxn = pymssql.connect(self.server, self.user_login, self.password, self.database)
cursor = cnxn.cursor()
return cnxn,cursor
except Exception as e:
self.alert_slack("Danger! cannot connect sql server")
... | The main task of the code is to create a database table named `self.table_log` with specified columns if it doesn't exist. It connects to the database, attempts table creation, and handles exceptions: logging success if created, notifying if the table already exists, or reporting column-definition errors. The function ... | def check_table_log(self):
#connect to db
cnxn,cursor=self.conn_sql()
# create table
try:
cursor.execute('''
CREATE TABLE '''+self.table_log+''' (
'''+self.table_columns_log+'''
)
''')
cnxn.commit()
... |
def calc_average_dist():
"""
calculates the average distance between 1% of all students
"""
sum_dist = 0
no_connection = 0
for n in range(int(number_of_students/100)):
student1 = random.choice(list_of_all_students)
student2 = random.choice(list_of_all_students)
dist = bre... | This function appends a row of calculated metrics to a CSV file, including average distances for different nationalities (Dutch, German, Other), faculties (FSE, FA, etc.), and connection statistics. It uses helper functions to compute values like average distances, connection counts, and association-based averages, the... | def write_results():
""" Function to write results to csv file. Decomment lines in first run, for having headers"""
with open(output_file, mode='a') as results_file:
results_writer = csv.writer(results_file, delimiter=',')
# results_writer.writerow(['Attempt_name', 'Avg dist', 'Avg dist Dutch', ... |
def choose_game_mode():
"""Function asks user about game mode and returns it
Returns:
game_mode (str)
"""
possible_modes = {'1': 'PvP', '2': 'PvC', '3': 'CvC'}
menu = '''
1. PvP
2. PvC
3. CvC
'''
print(menu)
game_mode = ''
while game_mode not in possible_modes... | The main task of the code is to initialize a game by configuring game mode, player names, AI difficulty, and ship placement. It creates a game instance, assigns starting players, randomizes turn order, and prepares the game state for play, returning essential components like the game object, players, AI, and game mode ... | def setup_game():
game_mode = choose_game_mode()
ai_level = 'easy'
if game_mode != 'PvP':
ai_level = choose_ai_level()
game = Game()
set_players_names(game, game_mode)
difficulty_level = DifficultyLevel(ai_level)
artificial_intelligence = ArtificialIntelligence(difficulty_level, ... |
def print_highscore():
"""
Print 10 lines of hall of fame file
"""
os.system('clear')
print('HALL OF FAME')
print(' ' + '_' * 61)
print('|{:>30}|{:>30}|'.format('winner', 'unhited squares').replace(' ', '_'))
highscores = read_highscore_file()
for highscore in highscores[:10]:
... | The code runs a turn-based game, managing player turns, attack coordinates, and game state updates. It initializes game components, processes hits on opponent grids, switches turns, and determines the winner. The loop continues until one player's ocean ends the game, then updates high scores and displays the result. | def main():
print_highscore()
intro('additional_files/intro_art.txt')
game, current_player, waiting_player, artificial_intelligence, game_mode = setup_game()
while not current_player.ocean.end_game():
# game main loop
current_player.ocean.is_owner_looking = True
waiting_player... |
def get_available_pieces(self, board) -> list[int]:
"""Return the list of available pieces"""
available_pieces = []
for piece in range(16):
if piece not in board:
available_pieces.append(piece)
return available_pieces
def get_available_positions(self, board) -... | The main task of the code is to determine the optimal position to place a selected piece on a board using a minimax algorithm with alpha-beta pruning. It prioritizes random selection when many pieces are available to save computation time, but employs deeper minimax analysis with adjustable search depth when fewer piec... | def place_piece(self) -> tuple[int, int]:
'''This function is used to choose the best position to place the selected piece'''
# Initialize alpha and beta to negative infinity and positive infinity respectively
alpha = float('-inf')
beta = float('inf')
# Get the board status
... |
def makeKey(self, state, action, piece = None):
# choose q-table
if action == "CHOOSE":
possible_actions = self.free_pieces(state)
for i in possible_actions:
if (tuple(state.flatten()), i) not in self.choose_q:
self.choose_q[(tuple(state.flatt... | The function updates Q-table entries for "CHOOSE" and "PLACE" actions in a Quarto game using Q-learning. It calculates rewards based on terminal states, applies the Bellman equation with learning rate and discount factor, and adjusts Q-values for both choosing pieces and placing them on the board to optimize future dec... | def update_q2(self, state, action, piece = None):
'''update the Q-table'''
if action == "CHOOSE":
self.makeKey(state, action)
current_choose = self.choose_piece_train(state)
if self.previous_choose is not None:
reward = 0 # the reward is 0... |
def makeKey(self, state, action, piece = None):
# choose q-table
if action == "CHOOSE":
possible_actions = self.free_pieces(state)
for i in possible_actions:
if (tuple(state.flatten()), i) not in self.choose_q:
self.choose_q[(tuple(state.flatt... | The code updates Q-tables for a reinforcement learning agent in a game, handling "CHOOSE" and "PLACE" actions. It adjusts Q-values using the learning rate, discount factor, and reward signals, distinguishing between choosing pieces (non-terminal, zero reward) and placing pieces (terminal reward if a win). It tracks pre... | def update_q(self, state, action, piece = None):
'''update the Q-table'''
if action == "CHOOSE":
self.makeKey(state, action)
current_choose = self.choose_piece_train(state)
if self.previous_choose is not None:
reward = 0 # the reward is 0 ... |
def _get_corner_coords(self, corners_list_len):
"""
corner_coords(N,1,W*H,3): 3D coordinate the origin is on the top right corner
"""
corner_coord = np.mgrid[:self.pattern_shape[0], :self.pattern_shape[1]].T.reshape(-1, 2)
corner_coord = np.hstack((corner_coord, np.zeros((corner_... | This code performs camera calibration by iteratively optimizing intrinsic parameters (camera matrix and distortion coefficients) using detected corner coordinates from multiple images. It computes homographies, refines parameters via multithreaded optimization, filters results with reprojection error, and saves the cal... | def calibrate(self, corners_list, img_names, img_shape):
success= False
corners_coords = self._get_corner_coords(len(corners_list))
homographies = compute_homographies(corners_coords, corners_list)
corners = [corners_coords, corners_list]
print ("\nstart to calibrate camera ... |
def vectorCreator(query):
keywords = keywordsLoader()
vector = []
for i in query.split():
if i in keywords:
vector.append(1)
else:
vector.append(0)
return vector
def brains(vector):
# Solving for neurons neuron layer_value
neuron1_1 = ReLU(neuronSolver(0, ... | The main task of the code is to process user input by converting it into a vector, generating a list of actions via the 'brains' function, and executing those actions using the 'executer' function. The 'main' function handles input retrieval, vector creation, action generation, and execution, forming a pipeline for tas... | def main(query=""):
query = input("What would you like to do? ")
inputVector = vectorCreator(query)
outputList = brains(inputVector)
executer(outputList, query) |
def _set_parent(self, child: 'Node', parent: 'Node') -> None:
"""Sets the child's parent to node "parent".
:return:
"""
if child:
child.parent = parent
def _count_size(self, node: 'Node') -> int:
"""Finds count of the nodes in the subtree rooted "node".
:param... | The code initializes a splay tree from an input string, constructing each node by inserting characters sequentially. It balances the tree for efficient operations like string printing and rearrangement (new_order). The root node is built iteratively, with each new character added to the left, and parent-child relations... | def __init__(self, init_str: str):
"""Tree is represented by its root node, initially None.
The following methods are implemented:
Create a new splay tree.
The string init_str is used to populate the tree.
Each node of the tree contains one letter:
... |
def _split(self, node: 'Node', id: int) -> ('Node', 'Node'):
"""Divides the tree into two.
In one tree, all values are to the left of the node with the identifier id,
and in the other, all values are to the right.
:param node: The tree identified by the root "node" to be split.
:... | The function `new_order` cuts a substring from index `i` to `j` in a string and inserts it after the `k`-th character of the remaining string (or at the beginning if `k=0`). It achieves this by splitting the data structure (likely a balanced tree) at specified positions, removing the substring, and reinserting it at th... | def new_order(self, i, j, k) -> None:
"""User interface for cut a piece of string and rearrange it to another place.
Cut the substring S[i..j] (where i and j are indexed from 0)
and insert it after the k-th character of the remaining string
(where k is indexed from 1).
If k = 0, ... |
def welcome_message():
print("\nWelcome to Cinemate!")
print()
cowsay.tux("Hello! I'm here to help you discover awesome movies!")
print()
def load_data(file_path):
df = pd.read_csv(file_path)
return df
def menu(pivot_table, cosine_sim_df, df):
while True:
print("\n1. Get movie recomm... | The main task of the code is to compute user similarity based on movie ratings data. It loads a dataset, creates a user-movie rating matrix, fills missing values with zeros, calculates pairwise cosine similarity between users, and stores the results in a DataFrame. The output is passed to a menu function for further an... | def main():
welcome_message()
df = load_data(file_path)
pivot_table = df.pivot_table(index='userId', columns='movieId', values='rating')
pivot_table = pivot_table.fillna(0)
cosine_sim = cosine_similarity(pivot_table)
cosine_sim_df = pd.DataFrame(cosine_sim, index=pivot_table.index, columns=pivot... |
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if not self.game_over:
if event.key == pygame.K_UP:
... | The code runs a game loop that continuously handles user input, updates the game state, draws the game scene, and maintains a consistent frame rate using a clock. | def run(self):
running = True
while running:
self.handle_events() # Handle user input
self.update() # Update game state
self.draw() # Draw game scene
self.clock.tick(self.fps) |
def _train(self, train_data):
x, y = train_data[self.label_columns], train_data[self.target_column]
if self.model_type == 'Decision Tree':
model = _train_decision_tree(x, y)
elif self.model_type == 'Linear Regression':
model = _train_sgd_classifier(x, y)
elif self... | The code trains a machine learning model by splitting data into training and test sets, trains the model using `_train()`, evaluates it (with AutoML-specific metrics or accuracy), stores the model and its performance metric, and returns the model ID, metric type, and value. | def train(self, test_size=0.15):
train_data, test_data = train_test_split(
self.df,
test_size=test_size,
random_state=42
)
model = self._train(train_data)
if self.model_type == 'AutoML':
self.metric_key, metric = self.evaluate_automl_mode... |
def urlrequest(url: str, timeout: int = 10):
"""
complete a url-request to the specified url
"""
headers = {'User-Agent': user_agent}
req = urllib.request.Request(url, headers=headers)
return urllib.request.urlopen(req, timeout=timeout)
def convert_content(path: str, data: bytes) -> bytes:
"... | The function fetches HTML content from a given URL, extracts title and content using specified XPaths, and generates a Chapter object. It uses the URL to download data, processes the HTML, and constructs the chapter with optional title and XPath parameters for customization. | def create_chapter_from_url(
url: str,
title: Optional[str] = None,
title_xpath: Optional[str] = None,
content_xpath: Optional[str] = None,
) -> Chapter:
"""
generate a chapter object from the given file
:param url: url being downloaded for html content
:pa... |
def run_setup():
create_cells() # Create the game board cells
find_neighbouring_bombs()
def event_handler(event):
if event.type == pygame.QUIT: # Check if the quit event is triggered
terminate_program()
elif event.type == pygame.MOUSEBUTTONDOWN: # Check if a mouse button is pressed down
... | The main task of the code is to initialize a game, run an infinite loop to process events, update the game state, and render graphics on the screen using Pygame, continuously refreshing the display until the program is terminated. | def main():
run_setup() # Run the initial setup for the game
while True: # Main game loop
for event in pygame.event.get(): # Process events
event_handler(event)
draw() # Draw the game state on the screen
pygame.display.flip() # Update the display
terminate_prog... |
def generate_round_keys(key):
round_keys = []
key_permuted = [key[pc - 1] for pc in permuted_choice_1]
left_half = key_permuted[:28]
right_half = key_permuted[28:]
for i in range(16):
left_half = left_half[shift_amount[i]:] + left_half[:shift_amount[i]]
right_half = right_half[shi... | The code implements the DES encryption and decryption process using a given hexadecimal key and plaintext. It converts inputs to binary, generates round keys, encrypts the plaintext, decrypts the ciphertext, and returns the original plaintext, encrypted ciphertext, and decrypted plaintext in hexadecimal format for vali... | def des_algorithm(key_hex = "e3b98d45a5b38a7f", plaintext_hex = "1f05d3c2872a59b6", ciphertext_hex = "3pgzk8pmzna2kbuqq0m89wte7finc38w"):
key_binary = bin(int(key_hex, 16))[2:].zfill(64)
plaintext_binary = bin(int(plaintext_hex, 16))[2:].zfill(64)
round_keys = generate_round_keys(key_binary)
encrypted_... |
def dd_selected(self):
"""This method is called whenever a value is selected in a given drop-down menu.
For example, if a map scale is selected, the possible values of the primary
state drop-down are updated to only show states for which maps were produced
at the given scale, the prima... | This code initializes a class with tkinter widgets (label, dropdown menu, navigation buttons) and associated data. It binds the dropdown selection event to a method, links button clicks to navigation functions, and stores hierarchy index and possible values. The setup prepares the UI for dynamic dropdown menu interacti... | def __init__(self, label: tk.Label, menu: AutocompleteCombobox, prev: tk.Button,
next: tk.Button, index: int, next_vals: dict):
"""Initialize the tkinter widgets (label, menu, prev, next) and associated
data like index (the position of this drop-down menu in the hierarchy) and
... |
def crossover(tree1, tree2):
original_tree1 = deepcopy(tree1)
original_tree2 = deepcopy(tree2)
node1 = get_random_node(original_tree1)
node2 = get_random_node(original_tree2)
if node1.value in function_set and node2.value in function_set:
node1.left, node2.left = node2.left, node1.left
... | This function implements a modified genetic algorithm operator combining tournament selection, crossover, and mutation. It selects the two fittest individuals, then iteratively generates new offspring through tournament-based selection of parents, performs crossover on their solutions, applies mutation, and adds unique... | def modified_tournament_selection_and_crossover(
population, points, mutation_rate, fitnesses, k
):
population_size = len(population)
ran = population_size - 1
enumerated_solutions = list(enumerate(fitnesses))
sorted_solutions = sorted(enumerated_solutions, key=lambda x: x[1], reverse=False)
h... |
def create_response_object_error(oid: str, size: int,
error_code: Optional[int] = None,
error_message: Optional[str] = None):
''' Create an object error for the response['objects'] list.
:oid: The Git LFS object id
:size: ... | This code processes object upload/download requests by validating hash algorithms, checking object existence in a bucket, and generating responses with action instructions. It handles errors for invalid hashes and missing objects, constructs response objects with operation details, and returns a structured output indic... | def handler(event, context):
print(json.dumps(event))
bucket = event['bucket']
project = event['project']
repo = event['repo']
operation = event['request']['operation']
objects = event['request']['objects']
hash_algo = event['request'].get('hash_algo', 'sha256')
response = {
'tr... |
def _handle_close(self):
status = 1000
reason = u''
length = len(self.data)
if length == 0:
pass
elif length >= 2:
status = struct.unpack_from('!H', self.data[:2])[0]
reason = self.data[2:]
if status not in _VA... | The code handles incoming packets by checking the opcode value. It validates control frames (PING/PONG) for data length, raises errors for invalid opcodes or oversized control frames, and routes packets to specific handlers like _handle_close, _handle_no_fin, or _handle_other based on the opcode and fin flag. | def _handle_packet(self):
if self.opcode == BINARY:
pass
elif self.opcode == CLOSE:
pass
elif self.opcode == STREAM:
pass
elif self.opcode == TEXT:
pass
elif self.opcode == PONG or self.opcode == PING:
if len(self.data) ... |
def _header_b1(self, byte):
self.fin = byte & 0x80
self.opcode = byte & 0x0F
self.state = HEADERB2
self.index = 0
self.length = 0
self.lengtharray = bytearray()
self.data = bytearray()
rsv = byte & 0x70
if rsv != 0:
... | The function processes incoming bytes according to the current state, handling different stages of message parsing including header, length, mask, and payload using a state machine approach. | def _parse_message(self, byte):
#======================================================================
# Read in the header.
#======================================================================
if self.state == HEADERB1:
self._header_b1(byte)
elif self.state == HE... |
def get_prediction(model, device, data_folder, loss, input_size, num_labels):
test_loader = loader(data_folder, input_size, split='test')
test_feats, test_labels = get_output(model, device, test_loader)
if loss.name == 'CrossEntropy':
test_preds = test_feats.argmax(axis=1)
elif loss.name == 'Tri... | The code evaluates a pre-trained deep learning model on a classification task using specified weights and loss function. It loads the model architecture, configures device settings, initializes the loss, loads weights if provided, and computes evaluation metrics like accuracy, balanced accuracy, and confusion matrices ... | def main(args):
model_name = args.model
weights = args.weights
data_folder = args.dataset
labels = os.listdir(os.path.join(data_folder, 'test'))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
feature_size = get_feature_size(model_name, device)
loss = Losses.from_string... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.