dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def handle_user_input(self, event):
# Stop simulation when user quits
if event.type == pygame.QUIT:
self.running = False
# Key presses
elif event.type == pygame.KEYDOWN:
# Spacebar pauses
if event.key == pygame.K_SPACE:
self.paused = no... | This function simulates a gravitational system of celestial bodies using Pygame. It initializes display settings, handles user input, updates planet interactions, and renders visualizations in real-time. The simulation loop processes physics calculations, tracks planetary motion, and displays trails, while allowing adj... | def simulate(self, width=1600, height=1000, speed=1e6, fps=33,
trail_length=1000, collisions=True,
track_all=False, run_while=(lambda x: True),
scale=1e-7, start_paused=False):
# Configure simulation
self.collisions = collisions
self.trail_le... |
def get_files(path):
files = []
try:
files = os.listdir(path)
except FileNotFoundError:
logger.error(f"Path not found: {path}")
return files
def sort_files(files, path, dict, basename):
for file in tqdm(files, desc=f'Sorting assets from \'{basename}\' directory', total=len(files), di... | The function gathers and processes media assets from specified paths, categorizing them into 'series', 'movies', and 'collections'. It handles override paths to prioritize or modify existing assets, normalizes titles, sorts files, and returns structured asset data with logging for debugging. | def get_assets_files(assets_path, override_paths):
asset_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']}
override_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']}
if assets_path:
files = get_files(assets_path)
basename = os.path.ba... |
def get_assets_files(assets_path, override_paths):
asset_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']}
override_files = {asset_type: [] for asset_type in ['series', 'movies', 'collections']}
if assets_path:
files = get_files(assets_path)
basename = os.path.ba... | The code processes media asset renaming based on configuration settings, logs runtime details, handles dry-run mode, retrieves asset files, processes instances (Plex/Radarr/Sonarr) to generate rename data, and sends Discord notifications. It checks config flags, constructs output tables, and executes renaming logic con... | def main():
if not config.run:
logger.info("Skipping renamer.py")
return
data = [
["Script Settings"],
]
create_table(data, log_level="debug", logger=logger)
logger.debug(f'*' * 40)
logger.debug(f'{"Dry_run:":<20}{config.dry_run if config.dry_run else "False"}')
lo... |
def helper_function(current, e, i, question_no):
a, b = bounding_phase_method(current, e, i, question_no)
a, b = interval_halving_method(a, b, current, e, question_no)
z = (a+b)/2
return z
def objective_function(x, question_no):
n = len(x)
ans = 0
match question_no:
case 1:
... | The code implements Powell's conjugate direction method for optimization, iteratively adjusting search directions to minimize an objective function. It updates positions using step sizes determined by a helper function, shifts directions, and converges when position changes fall below a threshold or max iterations are ... | def powells_conjugate_direction(starting_position, question_no, epsilon=1e-4, max_iterations=1000):
n = len(starting_position)
# e = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# directions=np.array(e)
directions = np.eye(n)
x = starting_position
x1 = starting_position + 2 * 10
... |
def helper_function(current, e, i, question_no,R,x_l,x_u):
a, b = bounding_phase_method(current, e, i, question_no,R,x_l,x_u)
a, b = interval_halving_method(a, b, current, e, question_no,R)
z = (a+b)/2
return z
def objective_function(x, question_no, R):
match question_no:
case 1: #question... | The code implements Powell's conjugate direction method for optimization, iteratively adjusting search directions to minimize an objective function. It updates directions based on current position changes, performs line searches via a helper function, and terminates when position changes fall below a threshold or max i... | def powells_conjugate_direction(starting_position, question_no, x_u, x_l, e1,e2, R, epsilon=1e-9, max_iterations=1000):
n = len(starting_position)
# e = [[1 if i == j else 0 for j in range(n)] for i in range(n)]
# directions=np.array(e)
directions = np.eye(n)
x = starting_position
x1 = starting... |
def json_to_xml(self, json_data):
xml_content = self.convert_dict(json_data)
self._logger.trace("xml_content: {}".format(xml_content))
return xml_content
def _get_endpoint(self, object_type):
for endpoint_class, endpoint_rest in endpoints.items():
if endpoint_class.lower().st... | This code modifies a system configuration by constructing an XML request with specified parameters, converting dictionary values to XML, and sending a PATCH request to a defined endpoint. It logs the operation, formats the data into an XML structure, and returns the response from the API call. | def set_system_configuration(self, modification_type, path, value):
self._logger.debug("set_system_configuration(modification_type={}, path={}, value={}", modification_type, path, value)
if isinstance(value, dict):
value = self.json_to_xml(value)
xml_data = """<objectModification
... |
def json_to_xml(self, json_data):
xml_content = self.convert_dict(json_data)
self._logger.trace("xml_content: {}".format(xml_content))
return xml_content
def get_object(self, object_type, object_oid):
endpoint = self._get_endpoint(object_type)
response = self._midpoint_call("GET"... | The code configures a notification handler by checking if a handler with the specified name already exists in the system configuration. If it exists, the function skips further processing; otherwise, it converts the provided JSON data to XML and updates the system configuration with the new handler settings. | def set_notification_configuration(self, modification_type, path, json):
notifier_name = json["name"]
self._logger.debug("notifier_name in user configuration file: {}".format(notifier_name))
xml_data = self.json_to_xml(json)
system_configuration_object = self.get_object("SystemConfigurat... |
def get_object(self, object_type, object_oid):
endpoint = self._get_endpoint(object_type)
response = self._midpoint_call("GET", endpoint, oid=object_oid, payload=None)
return response
def get_object_by_name(self, object_type, object_name):
endpoint = self._get_endpoint(object_type) + "/s... | This method adds an inducement (e.g., RoleType or ResourceType) to a target object in a system. It validates the existence of both the target and inducement objects using identifiers or names, checks for duplicate inducements, constructs XML for the modification, and applies the change via a PATCH request to the releva... | def _add_inducement(self, inducement_type, target_type, inducement_oid=None, inducement_name=None, target_oid=None, target_name=None):
self._logger.trace("_add_inducement(inducement_type={}, inducement_oid={}, inducement_name={}, target_type={}, target_oid={}, target_name={}", inducement_type, inducement_oid, i... |
def get_object(self, object_type, object_oid):
endpoint = self._get_endpoint(object_type)
response = self._midpoint_call("GET", endpoint, oid=object_oid, payload=None)
return response
def parse_class_logger(self, xml_content):
self._logger.trace("Parsing existing classLoggers.")
... | This function configures logging for a specified package by either updating an existing logger's level or adding a new logger if none exists. It retrieves system configuration, checks existing logger entries, and uses replace_class_logger or add_class_logger based on whether the package's logger already exists. | def set_class_logger(self, package, level):
system_configuration_object = self.get_object("SystemConfigurationType", "00000000-0000-0000-0000-000000000001")
existing_logger_id = None
logger_entries = self.parse_class_logger(system_configuration_object)
self._logger.trace("Existing logger... |
def wait_for_completed_task(self, iterations, interval, object_type="TaskType", object_oid=None, object_name=None):
self._logger.debug("Waiting task: {}".format(object_name))
self.wait_for_object(iterations=3, interval=30, object_type=object_type, object_oid=object_oid, object_name=object_name)
... | The main task of this code is to update the "requestable" status of a specified role in a system by sending a PATCH request to a midpoint API. It retrieves the role's unique identifier (OID), constructs a JSON payload with the provided value, and applies the modification to the role's configuration through an API call,... | def set_role_requestable(self, role_name, value):
self.wait_for_completed_task(iterations=2, interval=30, object_name="AD_GROUP_import")
self._logger.debug("role_name in user configuration file: {}".format(role_name))
role_object = self.get_object_by_name("RoleType", role_name)
object_oi... |
def add_resource_inducement_to_role(self, resource_oid=None, resource_name=None, role_oid=None, role_name=None):
response = self._add_inducement(inducement_type="ResourceType", inducement_oid=resource_oid, inducement_name=resource_name, target_type="RoleType", target_oid=role_oid, target_name=role_name)
... | The function `process_operation` handles operations based on the `operation_type` in `json_data` by invoking corresponding methods. It uses a match-case structure to route tasks like adding role/resource inducements, configuring system settings, logging levels, or notifications. Parameters are extracted from `json_data... | def process_operation(self, json_data):
self._logger.trace("Processing operation based on operation_type: {}".format(json_data.get('operation_type')))
match json_data["operation_type"]:
case "add_resource_inducement_to_role":
self.add_resource_inducement_to_role(resource_oid=... |
def load_pre_trained_nn(nn_name, gpu=None):
if type(gpu) == int:
map_location = torch.device("cuda:{}".format(gpu))
else:
map_location = torch.device("cpu")
num_c = get_num_classes(get_in_dataset_name(nn_name))
if "densenet" in nn_name:
model = DenseNetBC100(num_c)
if "sv... | The function generates and saves training logits and targets from a pre-trained neural network on a specified dataset. It creates directories, loads the model, processes data with a dataloader, computes predictions, saves tensors, and returns the saved logits for subsequent use. | def get_and_save_train_logits(nn_name, dataset_name, batch_size, gpu, *args, **kwargs):
os.makedirs(
"{}/tensors/{}/{}".format(ROOT, nn_name, dataset_name),
exist_ok=True,
)
model = load_pre_trained_nn(nn_name, gpu)
in_dataset_name = get_in_dataset_name(nn_name)
dataloader = train_da... |
def load_pre_trained_nn(nn_name, gpu=None):
if type(gpu) == int:
map_location = torch.device("cuda:{}".format(gpu))
else:
map_location = torch.device("cpu")
num_c = get_num_classes(get_in_dataset_name(nn_name))
if "densenet" in nn_name:
model = DenseNetBC100(num_c)
if "sv... | This function generates and saves test logits and targets from a pre-trained neural network on a specified dataset. It creates directories, loads the model, constructs a test dataloader, runs predictions, and stores results as tensors. Finally, it reloads and returns the saved logits for further use. | def get_and_save_test_logits(nn_name, dataset_name, batch_size, gpu, *args, **kwargs):
os.makedirs(
"{}/tensors/{}/{}".format(ROOT, nn_name, dataset_name),
exist_ok=True,
)
model = load_pre_trained_nn(nn_name, gpu)
in_dataset_name = get_in_dataset_name(nn_name)
dataloader = test_data... |
def initialize_objects(params):
# insert root object into the dict
seed_obj = Sphere()
base_color = params['base_color']
# color
seed_obj.R = base_color[0]
seed_obj.G = base_color[1]
seed_obj.B = base_color[2]
# seed_obj = Cube()
objects = {}
for g in range(params['generations'... | The code generates objects in successive generations by applying functions to parent objects, creating a directed graph (G) where each new object is linked to its parent. It iterates through generations, producing child objects from parents, assigns unique IDs, and updates the graph with nodes and edges. The process co... | def generate_objects(params):
objects_dict, G = initialize_objects(params)
for g, gen in enumerate(list(objects_dict.keys())[:-1]):
next_gen = list(objects_dict.keys())[g + 1]
print('generation:', gen)
new_objects = []
# apply functions to every object in previous gen and store ... |
def initialize_objects(generations=4):
seed_obj = Sphere()
# seed_obj = Cube()
objects = {}
for g in range(generations):
key_name = f"gen{g}"
objects[key_name] = []
objects['gen0'] = [seed_obj]
return objects
def generate_func_list(params, g):
dx, shrink_factor, col_delta, ... | The code generates objects across multiple generations by iteratively applying a set of functions to objects from the previous generation. It initializes objects, processes each generation to create new objects using stochastic functions, and compiles all generations into a final list. The process involves dynamic func... | def generate_objects(params):
objects_dict = initialize_objects(params['generations'])
for g, gen in enumerate(list(objects_dict.keys())[:-1]):
next_gen = list(objects_dict.keys())[g + 1]
print('generation:', gen)
new_objects = []
# apply functions to every object in previous ge... |
def preprocess_metadata():
# checking if summary pickle exists
if Path.exists(Path('./Processed_Data/summary.pickle')):
# load the pickle
pickle_file = open(Path('./Processed_Data/summary.pickle'), 'rb')
final_mapping = pickle.load(pickle_file)
pickle_file.close()
print("... | The code processes EEG data for epilepsy classification by splitting ictal and interictal segments into training/val sets using windowing. It excludes specific patients (chb12, chb24, chb16) based on window size, applies short Fourier transforms, and saves processed data in structured directories with batched files for... | def process_leave_out_one_data(window_size=1,size_threshold=None):
metadata = preprocess_metadata()
for patient in metadata:
# patient 12 and 24 should be omitted due to no valid interictal data
if 'chb12' in patient or 'chb24' in patient:
continue
# window size 12 comparison... |
def preprocess_metadata():
# checking if summary pickle exists
if Path.exists(Path('./Processed_Data/summary.pickle')):
# load the pickle
pickle_file = open(Path('./Processed_Data/summary.pickle'), 'rb')
final_mapping = pickle.load(pickle_file)
pickle_file.close()
print("... | The main task of the code is to process EEG data from patients into training and validation sets by splitting ictal and interictal segments into windowed time-frequency representations, saving them as NumPy files in a structured directory. It filters out specific patients, applies windowing, splits data into 75% traini... | def process_data(window_size=1,size_threshold=None):
metadata = preprocess_metadata()
for patient in metadata:
# patient 12 and 24 should be omitted due to no valid interictal data
if 'chb12' in patient or 'chb24' in patient:
continue
# window size 12 comparisons exclude pati... |
def MNI2XYZ3mm(mni):
"""
Converts the given MNI coordinates to X,Y,Z cartesian coordinates corresponding to the 2mm atlas
"""
x = math.floor((- mni[0] + 90)/3.0)
y = math.floor((mni[1] + 126)/3.0)
z = math.floor((mni[2] + 72)/3.0)
return [x,y,z]
def MNI2XYZ2mm(mn... | The function `getAtlasRegions` processes MNI coordinates to identify the most probable ROI (region of interest) across multiple brain atlases. It converts coordinates to atlas-specific spaces, filters out undesired regions (e.g., white matter, cortex), and selects the highest-probability ROI with minimal distance from ... | def getAtlasRegions(self, coordMni):
'''
Takes as input MNI coordinates and returns a tuple (ROI_number, Region_name, Atlas_index_used)
Algorithm:
Loops over multiple atlases
For each atlas get the maximum probability regions (2 here)
Select the max prob region w... |
def read_notebook(filename: str) -> nbformat.NotebookNode:
"""Reads in a Jupyter notebook as a Python dictionary."""
with open(filename, "r") as f:
notebook = nbformat.read(f, as_version=4)
return notebook
def notebook_to_script(notebook: nbformat.NotebookNode) -> str:
"""Converts a notebook to ... | The function `generate_pipeline_api` converts a pipeline notebook into a FastAPI application with REST routes. It reads the notebook, transforms it into a script, infers parameters, and renders a template with the script and pipeline path. The output includes a generated file header, code formatting (via Black), and li... | def generate_pipeline_api(
filename: str,
pipeline_family: Optional[str] = None,
semver: Optional[str] = None,
config_filename: Optional[str] = None,
flake8_opts: List[str] = lint.FLAKE8_DEFAULT_OPTS,
) -> str:
"""Given the filename for a pipeline notebooks, generates the a FastAPI
applicati... |
def notebook_file_to_script(
input_filename: str,
output_directory: str,
pipeline_family: Optional[str] = None,
semver: Optional[str] = None,
config_filename: Optional[str] = None,
flake8_opts: List[str] = lint.FLAKE8_DEFAULT_OPTS,
):
"""Converts a notebook file to a Python script and saves ... | This function converts Jupyter notebook files into Python FastAPI scripts, saving them as modular components in the specified output directory. It processes each notebook, generates appropriate module names, and aggregates them into a root FastAPI application module, supporting customization via parameters like pipelin... | def convert_notebook_files_to_api(
notebook_filenames: List[str],
input_directory: str,
output_directory: str,
pipeline_family: Optional[str] = None,
semver: Optional[str] = None,
config_filename: Optional[str] = None,
flake8_opts: List[str] = lint.FLAKE8_DEFAULT_OPTS,
):
"""Converts a l... |
def fill_train_test_dataframes(self, test_split=0.3, random_seed=None):
images_df = self.annotations_to_dataframe(self.dataset_path)
clear_df = images_df[images_df[COLUMN_INTENSITY] == 0]
fog_df = images_df[images_df[COLUMN_INTENSITY] != 0]
self.train_clear_df, self.test_clear_df = split... | The main task of the code is to prepare TensorFlow datasets for training and testing by generating image paths from dataframes, applying preprocessing, shuffling, batching, and splitting into train/test sets. It creates separate datasets for clear and fog images, with optional sample data for demonstration. The functio... | def prepare_dataset(self, batch_size, buffer_size=1000,
test_split=0.3,
autotune=tf.data.experimental.AUTOTUNE,
return_sample=True, sample_batch_size=1,
random_seed=None):
self.fill_train_test_dataframes(test_split, ... |
def deleteUI(ui) :
if mc.window(ui, exists = True) :
mc.deleteUI(ui)
deleteUI(ui)
def initFunctions(self) :
# set ui
self.ui.material_listWidget.setAlternatingRowColors(True)
self.ui.multiMatte_listWidget.setAlternatingRowColors(True)
# set default values
... | This code initializes a Qt GUI window by loading a pre-designed UI file ('multiMatteUI.ui'), deletes any existing UI with the same name, sets up the window with a specific title, and initializes functions and signals for interaction. It uses QtUiTools to load the UI, configures the working directory, and displays the i... | def __init__(self, parent=None):
self.count = 0
#Setup Window
super(MyForm, self).__init__(parent)
self.mayaUI = 'multiMatteWin'
deleteUI(self.mayaUI)
# read .ui directly
loader = QtUiTools.QUiLoader()
loader.setWorkingDirectory(moduleDir)
f = Q... |
def load_dicts():
"""Opens the 2 dictionaries in use, a smaller dictionary
of more common words, and a larger dictionary with
words that the user could guess.
TODO: Make this an API call to improve space constraints"""
common_words = []
all_words = []
with open('common-fives') as f:
... | The code implements a Wordle-style game where the user guesses a hidden 5-letter word within 6 attempts. It tracks guesses, updates keyboard/emoji feedback, checks validity, and displays results with celebratory messages for successful guesses or reveals the correct word on failure. The game also includes sharing funct... | def test2():
"""main game logic. initializes several variables, then jumps into the main loop:
1. compare a guess
2. print the new board
3. repeat."""
guess_history = []
index_map_history = []
common_words, all_words = load_dicts()
game_day = 0
shared_id, shared_word = ask_user_new_w... |
def raise_error(info):
logging.error(info)
exit(1)
def validate(config):
# Validate mandatory params.
server_config = config["config"]
keys = ["host", "username", "password"]
[check_field(k, server_config) for k in keys]
files = config["files"]
keys = ["path", "name"]
for f in files... | The code processes a configuration file by parsing command-line arguments, validating JSON content, creating a session, retrieving layers, and uploading them. It handles errors for missing/config issues and ensures proper file validation before proceeding with data operations. | def main():
parser = optparse.OptionParser()
parser.add_option("-c", "--config", dest="config")
options, _ = parser.parse_args()
if options.config is None:
raise_error("No configuration file provided")
# Open config file.
try:
with open(options.config) as f:
config ... |
def write_line(self, code: str = ""):
if code is None:
code = ""
self._write("{}\n".format(code))
def _push_indent(self) -> None:
self._indentation_level += 1
def write_code(self, statement: str = "") -> None:
for stmt in statement.split(";"):
stmt = stmt.strip()
... | This method creates a labeled section with indentation, capturing content written during the block. It writes the label, manages indentation, and ensures the block's output is inserted back into the buffer after execution, optionally appending an end string. | def _label(self, label: str, end: str = "") -> ContextManager:
self.write_line("{}:".format(label))
self._buffer.append(StringIO())
self._push_indent()
try:
yield
finally:
if end:
self.write_code(end)
text = self._buffer.pop(... |
def credit(customer,amount=None):
if not amount:
c,d = parse()
else:
c,d = amount
if not c and not d:
return
tmpd = customer.balance["d"]+d
tmpc = customer.balance["c"]+c
if tmpc < 0:
tmpd-=1
tmpc+=100
if tmpc>customer.balance["m"] or tmpd>customer.bal... | The code implements a simple banking system simulation where users can perform credit, debit, check balance, and transfer funds between accounts. It uses a list of user objects, processes menu-driven input, validates entries, and handles exceptions to ensure correct UID and transaction inputs. | def run():
bank =[user("John",1),user("Jane",2),user("Jack",3)]
while True:
try:
uid = int(input("$ Enter your uid: "))
u = bank[uid-1]
print("""
$ Select an option:
1. Credit
2. Debit
3. Check
4. Transfer
5. Exit
""")
choice = int(input("=>"))... |
def initVars(self, config):
global tilesize, width, height, num_keys, keys, keyimage, keyimage_dark, keyimage_maps, \
font, fontsize, fontcolor, backgroundcolor, displaymode, resetkey, pollingrate, cps_enable, \
cps_x, cps_y
v = config_parser.loadConfig(config)
tilesize, ... | This code initializes a main GUI application by setting up the main window, configuring variables, creating the user interface, fonts, keyboard handling, and optionally CPS features, then starts a timer to launch the application. | def __init__(self, config, app, *args, **kwargs):
print("[KVGUI] Initializing... (version v{version})".format(version=version))
super(MainGUI, self).__init__(*args, **kwargs)
print("[KVGUI] QMainWindow initialized.")
self.app = app
self.initVars(config)
self.initGUI()
... |
def getPopulation(self):
population = np.empty((0, self.chromosome_length))
for _ in range(self.population_num):
#constraints
while True:
rand_chromosome = np.random.randint(2, size=(self.chromosome_length))
# Parameter lists from result
... | This code implements a genetic algorithm to optimize a population of solutions over multiple generations. It iteratively selects parents, applies crossover and mutation, enforces constraints (placeholder for user-defined conditions), and tracks the best solutions found in each generation and overall. The algorithm retu... | def run(self):
count = 0
pool_of_generation = self.getPopulation()
best_of_generation = np.empty((0, 2))
best_of_all_stack = np.empty((0, 2))
best_of_all = np.empty((0, 2))
start_time = time.time()
stack_plot = []
print("First generation")
for ind... |
def get_ssm_parameter(ssm_key_name):
client = boto3.client('ssm')
response = client.get_parameter( Name=ssm_key_name,WithDecryption=False)
return eval(response['Parameter']['Value'])
def read_object(entity_name, last_processed_batch, prefix_value=staging_bukcet):
client = boto3.client('s3')
if last_... | The main task of the code is to process incremental data loads for specified tables (customers and sales) by retrieving configurations from AWS SSM, identifying new data paths since the last processed batch, and submitting Hudi jobs to EMR for processing. It checks for non-empty path lists and triggers jobs only when i... | def main():
list_tables = [tablename_customers, tablename_sales]
for table_name in list_tables:
ssm_key_name = base_ssm_key + table_name
table_config = get_ssm_parameter(ssm_key_name)
entity_name = table_config["table_name"]
last_processed_batch = table_config["processed_batch"]... |
def get_ssm_parameter():
client = boto3.client('ssm')
response = client.get_parameter( Name=ssm_key_name,WithDecryption=False)
return eval(response['Parameter']['Value'])
def read_object(entity_name, prefix_value = landing_bukcet):
client = boto3.client('s3')
response = client.list_objects_v2(
... | The code processes data from AWS S3 buckets by converting files to Parquet format. It retrieves table names and timestamps from SSM parameters, then iterates through each table. If a table's timestamp is "-1", all files in its landing bucket are converted. Otherwise, only files newer than the timestamp are processed. T... | def main():
tables_dict = get_ssm_parameter()
for (table_name, timestamp) in tables_dict.items():
if timestamp == '-1':
# Read every bucket from landing-data and go into folder named table_name and convert it into parquet file
print("{} has timestamp value {}".format(table_name, ... |
def reload(self):
''' Reloads the cache_store once module is loaded up '''
self.__cache_store = self.__retrieve()
def __revalidate(self, key):
if self.has(key):
expiry = self.__cache_store.get(key).get('expiry')
self.__cache_store.pop(key) if time() > expiry else None
def... | The code initializes an object by reloading data, revalidating all cache entries using `__revalidate`, and committing changes via `__commit`, ensuring cached data remains valid and up-to-date. | def __init__(self):
self.reload()
{self.__revalidate(key) for key, value in list(self.__cache_store.items())}
self.__commit() |
def create_widget(self):
#VARIABLES FOR DROP DOWN MENUS
self.var1 = tk.StringVar()
self.var2 = tk.StringVar()
self.var3 = tk.StringVar()
self.var4 = tk.StringVar()
self.var5 = tk.StringVar()
self.var6 = tk.StringVar()
#FORMATING ... | The code initializes a GUI window for a Covid data visualization interface by setting the title, background color, and icon, then creates UI components, a title section, and loads data for visualization. | def __init__(self, parent):
super().__init__(parent)
self.title("Covid Data Visulisation Interface")
self.configure(background = "grey22")
self.iconbitmap("coronavirus_orange_right_HPY_2.ico")
self.create_widget()
self.create_title()
self.load_da... |
def create_widget(self):
#OPTION MENU VARIABLES
self.var1 = tk.StringVar()
self.var2 = tk.StringVar()
self.var3 = tk.StringVar()
self.var4 = tk.StringVar()
self.var5 = tk.StringVar()
self.var6 = tk.StringVar()
#FORTMATTING
... | The code initializes a GUI application for visualizing COVID-19 data, setting up a window with a title, background color, and icon. It creates UI components, a title section, and loads data for visualization. The main task is to establish a graphical interface for displaying and analyzing coronavirus-related data. | def __init__(self, parent):
super().__init__(parent)
self.title("Covid Data Visulisation Interface")
self.configure(background = "grey22")
#self.attributes("-fullscreen", True)
self.iconbitmap("coronavirus_orange_right_HPY_2.ico")
self.create_widget()
se... |
def clear_box(self):
#FUNCTION TO EMPTY SECOND COUNTY VARIBLE WHEN BUTTON IS PRESSED
self.var7.set("")
def daily_figure(self):
#CHECKS TO SEE IF BOTH COUNTY OPTIONS ARE SELECTED TO DECIDE WHAT TYPE OF GRAPH
self.area_choice("Total_Cases", df_daily)
def cumalative_figure(self):
#... | This code creates a GUI widget using Tkinter, enabling users to select geographic areas, start/end dates via dropdown menus, and generate daily/cumulative graphs. It includes formatting, layout, and interactive elements like a "Remove Second Area" button and "QUIT" functionality. | def create_widget(self):
#MENU OPTION VARIABLES
self.var0 = tk.StringVar()
self.var1 = tk.StringVar()
self.var2 = tk.StringVar()
self.var3 = tk.StringVar()
self.var4 = tk.StringVar()
self.var5 = tk.StringVar()
self.var6 = tk.StringVar()
s... |
def create_widget(self):
#MENU OPTION VARIABLES
self.var0 = tk.StringVar()
self.var1 = tk.StringVar()
self.var2 = tk.StringVar()
self.var3 = tk.StringVar()
self.var4 = tk.StringVar()
self.var5 = tk.StringVar()
self.var6 = tk.StringVar()
s... | The main task of the code is to initialize a GUI application window with a specified title, background color, and icon, then create interface components, display a title, and load data. It sets up a coronavirus data visualization interface using Tkinter, configuring visual properties and triggering widget creation and ... | def __init__(self, parent):
super().__init__(parent)
self.title("Covid Data Visulisation Interface")
self.configure(background = "grey22")
self.iconbitmap("coronavirus_orange_right_HPY_2.ico")
self.create_widget()
self.create_title()
self.load_d... |
def get_token():
url = "https://api.hungermapdata.org/swe-notifications/token"
response = requests.post(url, auth=(username, password))
global token
token = response.json()["token"]
def get_population_dataframe():
url = "https://api.hungermapdata.org/swe-notifications/population.csv"
return pd.r... | The code calculates and compares the percentage of insecure populations in countries between past and current data, triggering email alerts if the current percentage exceeds the past by at least 5%. It retrieves population data, processes regional statistics, checks for valid numerical values, computes percentages, and... | def main():
print("Running---")
get_token()
population_df = get_population_dataframe()
get_countries_population_from_region(population_df)
global countries_dict
for country in countries_dict:
country_population = countries_dict.get(country, 0)
insecure_population_30 = countr... |
def conv(instate):
res = []
for i in instate:
res1 = []
for j in i:
res1.append(j)
res.append(res1)
return res
def makeVehicles(jinstate):
vehicleList = []
instate = [row[:] for row in jinstate]
for row in range(len(instate)):
#k = instate(row)
... | The code solves a Rush Hour puzzle using a breadth-first search (BFS) algorithm with a specified heuristic. It converts the start state into a Node, explores possible states, and returns the shortest path to the goal if a solution exists. If no solution is found, it outputs "No solution." The code also tracks and print... | def rushhour(heur, start):
startB = conv(start)
startNode = Node(startB, makeVehicles(startB),None,0)
path, expStates = bfsSearch(heur, [startNode], [])
if path == []:
print ("No solution ")
print("Total states Explored: ", expStates)
else:
toprint = ""
for i in path:... |
def parse_let_statement(self) -> ast.LetStatement:
"""
Parse 'self.cur_token' and turn it into a LetStatement.
Returns the LetStatement.
"""
statement = ast.LetStatement(token=self.cur_token)
if self.expect_peek(token.TokenTypes.IDENT) is False:
return None
... | This method parses the current token into a statement by selecting the appropriate parsing function based on the token's type. It logs the current token for debugging, then uses a match-case structure to determine whether to parse a 'let' statement, a 'return' statement, or an expression statement, returning the result... | def parse_statement(self) -> ast.Statement:
"""
Allows for 'self.cur_token' to be parsed as a statement by
selecting the proper parsing function for the current token Type.
Returns and executes the matched method, which in turns returns a statement.
"""
current_token = s... |
def get_strict_boolean(config, section, option):
"""Retrieve a strict boolean value from a configuration section."""
value = config.get(section, option)
if value.lower() not in {'true', 'false'}:
raise ValueError(f'Invalid boolean value for {option} in {section}.')
return config.getboolean(secti... | This function modifies a configuration option in a specified section, handling user input to either modify, toggle, or delete the value. It supports complex data types (dicts, tuples, lists), applies backups if requested, and writes changes to the config file. It also manages default values, encryption, and interactive... | def modify_option(config, section, option, config_path, backup_parameters=None,
can_back=False, can_insert_delete=False, initial_value=None,
prompts=None, items=None, all_values=None, limits=(),
is_encrypted=False):
"""Modify an option in a section of a configur... |
def get_arguments():
"""Parse and return command-line arguments."""
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
parser.add_argument(
'dates', nargs='*',
default=[pd.Timestamp.now().strftime(ISO_DATE_FORMAT)],
help='specify dates in the format... | The code processes trading journal data by parsing arguments, loading configurations, and reading Excel files. It iterates through specified dates, extracts trade details, applies configured styles, saves market data as CSV, and generates visualizations. Charts are stored in a directory, with a final check comparing ge... | def main():
"""Parse trade data, save market data, plot charts, and check charts."""
args = get_arguments()
config_path = file_utilities.get_config_path(__file__)
config = configure(config_path)
trading_path = args.f[0] if args.f else config['General']['trading_path']
trading_sheet = config['Gen... |
def modify_option(config, section, option, config_path, backup_parameters=None,
can_back=False, can_insert_delete=False, initial_value=None,
prompts=None, items=None, all_values=None, limits=(),
is_encrypted=False):
"""Modify an option in a section of a configur... | This function modifies a configuration section by allowing users to edit, insert, or delete options based on prompts. It supports backups, handles encrypted configs, and dynamically updates the configuration file with changes. The function returns True on success or False if the section doesn't exist. | def modify_section(config, section, config_path, backup_parameters=None,
option=None, can_back=True, can_insert_delete=False,
prompts=None, items=None, all_values=None, limits=(),
is_encrypted=False):
"""Modify a section of a configuration based on user input... |
def overlay_background_with_item(background, scaled_items, random_items_list):
position_of_boxes = np.zeros((len(scaled_items), 5))
crop_spots = np.zeros((len(scaled_items), 5))
result_image = np.zeros((background.shape[0], background.shape[1], 4))
result_image[:, :, :3] = copy.deepcopy(background)
... | The function generates a final composite image by overlaying scaled items onto a background, saves segmented item data, and records item positions in a text file. It then saves the resulting image as a JPEG in the specified directory with a designated filename. | def generate_result_photo(background, scaled_items, path_of_results, name_of_photo, random_items_list):
result_image, random_spots, crop_spots = overlay_background_with_item(background, scaled_items, random_items_list)
segmentation_items(result_image, random_items_list, path_of_results, name_of_photo)
posit... |
def load_background_and_item(items_list, backgrounds_list, items_name_list, no_of_result):
items = []
random_item_count = np.random.randint(1, len(items_name_list) // 2 + 1)
random_items_list = np.random.choice(len(items_name_list) // 2, random_item_count, replace=False)
for no_of_item in range(random_i... | The function generates a specified number of photos by combining items and backgrounds, starting from an existing count. It iterates to create new images, scales items to fit backgrounds, and saves them to a directory. If errors occur during generation, it skips the failed attempt, decrements the photo counter, and iss... | def generate_photos(items_list, backgrounds_list, path_of_results, items_name_list, results_count, exist_photos):
name_of_photo = exist_photos
for no_of_result in range(results_count - exist_photos):
try:
name_of_photo += 1
items, background, random_items_list = load_background_a... |
def results_to_path(path_of_data, delete):
path_of_results = path_of_data / "results"
path_of_segmentation = path_of_data / "segmentation"
if delete and path_of_data.is_dir():
shutil.rmtree(path_of_data)
if not path_of_data.is_dir():
path_of_data.mkdir()
if not path_of_results.is_dir... | The function generates a specified number of images by combining items and backgrounds, checking existing files in the results directory, and creating new ones as needed. It organizes items and backgrounds from provided paths, handles deletion of old results, and ensures the correct count of generated images. | def generate_data(path_of_item, path_of_backgrounds, path_of_data, categories, names_of_items, results_count, delete):
path_of_data = Path(path_of_data)
path_of_results = results_to_path(Path(path_of_data), delete)
exist_photos = len(list(path_of_results.glob("**/*.jpg")))
items_list, backgrounds_list, ... |
def tokenize(txt):
return word_tokenize(txt)
def n_unique_tokens(txt):
txt = tokenize(txt)
words = list(set(txt)) # set only stores unique values
return len(words)/len(txt)
def n_nonstop_words(txt):
txt = tokenize(txt)
nonstop_words = [i for i in txt if not i in stopwords]
n_nonstop_words = len(no... | The main task of the code is to extract and compute various text-based features and metadata from an article, including token counts, sentiment scores, keyword analysis, category flags, weekday information, and link/image/video statistics, organizing them into a structured dictionary for downstream analysis or machine ... | def processArticle(article):
content = {}
blob = TextBlob(article['text'])
title_blob = TextBlob(article['title'])
content['title'] = article['title']
content['n_tokens_title'] = len(tokenize(article['title']))
content['n_tokens_content'] = len(tokenize(article['text']))
content['n_unique_tokens'] = n_un... |
def monto_is_running():
return pid_file_path().is_file()
def kill_all_pids():
for pid in get_pids():
try:
if sys.platform == "win32":
os.kill(pid, signal.SIGBREAK)
else:
os.killpg(pid, signal.SIGTERM)
except ProcessLookupError:
... | The code defines a function `stop` that terminates the 'monto' service by checking if it's running, killing associated processes, removing the PID file, and printing a confirmation message if active; otherwise, it informs the user that 'monto' is not running. | def stop(config):
if monto_is_running():
kill_all_pids()
remove_pid_file()
print('monto has been stopped')
else:
print('monto is not running') |
def monto_is_running():
return pid_file_path().is_file()
def run_command(config, program, sets):
cwd = program.get('directory', '.')
if should_run(program, sets):
try:
process = subprocess.Popen(
args=program['command'],
cwd=cwd,
env=os.env... | The main task of the code is to start the "monto" application by checking if it's already running; if not, it retrieves a list of programs from the configuration, executes each program using the `run_command` function, and updates the application status. | def start(config, sets):
if monto_is_running():
print('monto is already running')
else:
programs = []
if 'programs' in config:
programs = config['programs']
for program in programs:
run_command(config, program, sets)
status(config) |
def error(msg):
print('send: {0!s}'.format(msg))
usage()
def usage():
print('usage: send [-c chnglang] [-s begin:end] file...')
def selargtoobj(selarg):
m = re.match(r'^(\d+):(\d+)$', selarg)
if m:
begin = int(m.group(1))
end = int(m.group(2))
if begin <= end:
ret... | The main task of the code is to parse command-line arguments using `getopt`, handle options like changing language (`-c`/`--chnglang`), displaying help (`-h`/`--help`), and selecting items (`-s`/`--selection`), then pass parsed arguments, language change value, and processed selections to the `send` function for furthe... | def main():
try:
opts, args = getopt.getopt(sys.argv[1:],
'c:hs:',
['chnglang', 'help', 'selection'])
except getopt.GetoptError as err:
error(err)
sys.exit(1)
chnglang = None
selections = []
for o, a in opt... |
def usage():
print('usage: monto [-h] [command]')
print(' commands: restart, start [set...] (default), status, stop')
def stop(config):
if monto_is_running():
kill_all_pids()
remove_pid_file()
print('monto has been stopped')
else:
print('monto is not running')
def start(... | The code parses command-line arguments to execute system commands (start, stop, restart, status) using a configuration file. It handles help options, validates commands, and delegates tasks to corresponding functions. If no arguments are provided, it defaults to 'start'. For 'restart', it stops then starts the service.... | def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])
except getopt.GetoptError as err:
montolib.error(err)
usage()
sys.exit(2)
for o, a in opts:
if o in ('-h', '--help'):
usage()
sys.exit()
else:
assert F... |
def error(msg):
print('wrap: {0!s}'.format(msg))
usage()
def usage():
print('usage: wrap [-m] [-v verslang] product prodlang command args...')
def wrap(verslang, message, product, prodlang, args, tmpfilepath):
montolib.server(
lambda c: run_command(product, message, prodlang, c, args, tmpfilepat... | The main task of the code is to parse command-line arguments, validate input parameters, create a temporary text file, and invoke the `wrap` function with specified arguments and the temporary file path. It handles options like `-m` (message), `-v` (verslang), and `-h` (help), checks for sufficient arguments, and ensur... | def main():
try:
opts, args = getopt.getopt(sys.argv[1:], 'mv:h', ['message', 'verslang', 'help'])
except getopt.GetoptError as err:
error(err)
sys.exit(2)
message = False
verslang = None
for o, a in opts:
if o in ('-m', '--message'):
message = True
... |
def maxSR(meanReturns, covMatrix, riskFreeRate=0, constraintSet=(0, 1)):
"Minimize the negative SR, by altering the weights of the portfolio"
numAssets = len(meanReturns)
args = (meanReturns, covMatrix, riskFreeRate)
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
bound = constraintSe... | The code calculates key portfolio optimization results: Max Sharpe Ratio portfolio, Min Volatility portfolio, and efficient frontier. It uses mean returns and covariance matrix inputs, applies optimization functions, and returns formatted outputs including portfolio returns, standard deviations, asset allocations (in p... | def calculatedResults(meanReturns, covMatrix, riskFreeRate=0, constraintSet=(0, 1)):
"""Read in mean, cov matrix, and other financial information
Output, Max SR , Min Volatility, efficient frontier """
# Max Sharpe Ratio Portfolio
maxSR_Portfolio = maxSR(meanReturns, covMatrix)
maxSR_returns, ma... |
def read_file_and_delete(filename:str) -> bytes:
if filename.endswith(".txt"):
with open(filename, "r", encoding=utils.ENCODING) as file:
data = file.read().encode(utils.ENCODING)
elif filename.endswith(".png"):
with open(filename, "rb") as file:
data = file.read()
os... | The main task of the code is to securely transmit multiple files to a server in encrypted chunks. It reads each file, splits it into predefined-size chunks, sends metadata (number of chunks, filename, remaining files) to the server, encrypts and sends each chunk sequentially with a 5ms delay between chunks to manage da... | def send_files_to_server(self, files: list):
chunk_size = utils.BUFFSIZE-96
number_of_files = len(files)
for index, file in enumerate(files):
data = read_file_and_delete(file)
chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)] # split data in chun... |
def _needs_update(repository_ctx):
target_name = repository_ctx.target_name
pod_root_dir = repository_ctx.GetPodRootDir()
_exec(repository_ctx, ["/bin/bash", "-c", "mkdir -p " + pod_root_dir])
_exec(repository_ctx, ["/bin/bash", "-c", "touch .pod-version"], pod_root_dir)
cached_version = _exec(repos... | This function updates a repository by executing a custom script with substitutions based on the repository context. It checks if an update is needed, prepares command substitutions for RepoTool, constructs a script to fetch podspecs and run installation logic, executes the script in the pod's root directory, and record... | def _update_repo_impl(repository_ctx):
if repository_ctx.GetTrace():
print("__RUN with repository_ctx", repository_ctx.__dict__)
global POD_PATHS
POD_PATHS.append(repository_ctx.GetPodRootDir())
if not _needs_update(repository_ctx):
return
print("Updating Pod " + repository_ctx.ta... |
def split_X_y(train, validate, test):
'''
Purpose:
---
To split the subsets further for modeling and testing
---
Parameters:
train: unscaled subset of dataframe for exploration and model training
validate: unscaled and unseen data for model testing
test: unscaled and... | The function `for_final_report` trains and evaluates machine learning models using train, validate, and test datasets alongside a feature bank. It splits data into features/labels, trains models, filters top-performing models (accuracy > 68%), validates them, selects the top 4 based on sensitivity and accuracy, tests t... | def for_final_report(train, validate, test, feature_bank):
'''
Purpose:
To create and train models for scoring on the train, validate, and test subsets
---
Parameters:
train: subset of data for model training purposes
validate: subset of data for model validation purposes
... |
def get_planes_from_miller_index(self, miller_index=(1,1,1)):
"""
miller_index : as an array with 3 integer numbers, positive or negative
100 or yz plane -> TUVS
010 or zx plane -> RSVQ
001 or xy plane -> PQVU
"""
self.planes = {'100': 'TUVS', '010': 'RSVQ', '001... | This code calculates the angle between two crystallographic planes defined by Miller indices. It draws both planes, computes their normal vectors, and visualizes these normals as arrows in 3D space. The function handles scaling, orientation, and rendering of planes, with miller2 defaulting to the xy-plane. | def draw_plane_calculate_angle(self, miller1, miller2=(0,0,1)):
"""
calculates angle between two planes.
miller1 : arbitray plane with 3 component miller index. draws this plane
miller2 : default is xy plane, with miller index (0,0,1). does not draw this plane
"""
... |
def pre_processing():
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
directory1 = "C:/Coding/Watermark-2.0/datasets/PIRM_Self-Val_set/LR"
directory2 = "C:/Coding/Watermark-2.0/datasets/PIRM_Self-Val_set/MR"
directory3 = "C:/Coding/Watermark-2.0/datasets/google"
num_lines_orig = 512
num_columns_orig = 768
... | The main task of the code is to preprocess data, train an autoencoder with a predefined filter configuration (32, 64, 128, 256, 8, 8), and evaluate its performance using training and validation loss, test data, and model parameters. The process involves data preparation, model training with specified filters, and post-... | def main():
y_train_data,y_test_data,input_shape = pre_processing()
n_filter= np.zeros((6))
n_filter[0] = 32
n_filter[1] = 64
n_filter[2] =128
n_filter[3] =256
n_filter[4] = 8
n_filter[5] = 8
loss,val_loss,y_test_data,x_test_data,epochs,sub_epochs,autoencoder = \
trai... |
def utilityclassProbsTailLipschitzGumbel(x, k, eps, rho=0.5):
assert (x[0] == -inf)
d = len(x)-1
A = probsCanonicalGamma1Gumbel(x,k,eps, rho)
return utilityclassProbs(A,k,d)
def utilityclassProbsCanonicalLipschitzGumbel(x, k, eps, rho=0.5):
assert (x[0] == -inf)
d = len(x)-1
A = probsCanonicalGumbel(x,... | The code initializes an object to compute and store probabilistic results based on input data (`x`), parameters (`k`, `eps`), and a string (`s`) specifying statistical models (e.g., Gumbel, logistic) and modes (e.g., fast/slow, tail/canonical). It processes `s` to determine the model type, sets parameters like `rho`, a... | def __init__(self, x, k, eps, s = None, reps = 100, verbose=False):
self.verbose = verbose
if x == None:
return
assert (s != None)
self.zipfs = -1
assert (x[0] == -inf)
d = len(x)-1
s = " "+s+" "
self.eps = eps
self.legend = s
self.style = ""
finv = None
finvMax = None
... |
def utilityclasses(k):
ret = dict()
ret[TOPK] = k,k
ret[GREATK] = int( ceil(k*0.1) ), int(k*1.1)
ret[GOODK] = int( ceil(k*0.01) ), int(k*1.5)
return ret
def getdatapoints(noneps, args,x, k, listeps, key, reps):
ret = [None for eps in listeps]
# all Pr < (1-0.999999)?
for i in between(len(listeps)-1, len(... | The code generates LaTeX plots comparing privacy-utility trade-offs of algorithms (e.g., canonical gumbel, oneshot exponential) for datasets like ZIPFIAN and MEDCOST. It processes input data, computes probability distributions over epsilon values, and writes TikZ/PGFplots code into `.tex` files. These files visualize h... | def run(experiment, args):
rootdir = args.r
subdir = args.u
algs = None
file = dict(m="MEDCOST.n4096",f="ZIPFIAN.n10000",h="HEPTH.n4096",i="INCOME.n4096",p="PATENT.n4096",s="SEARCHLOGS.n4096",n="NETFLIX.n17770", z="")[experiment]
oneshot_exp = r"""$\ONESHOT$ oneshot exponential red""" # oneshot_exp
canonica... |
def rotate270(data):
return rotate90(rotate180(data))
def move_east(data):
return [tilt(l) for l in data]
def rotate90(data):
return list((map(lambda l: ''.join(reversed(l)), zip(*data)))) | The main task of the code is to move data north by rotating it 90°, moving it east, then rotating 270°, effectively combining rotations and translation to achieve a net northward displacement. | def move_north(data):
return rotate270(move_east(rotate90(data))) |
def rotate90(data):
return list((map(lambda l: ''.join(reversed(l)), zip(*data))))
def move_east(data):
return [tilt(l) for l in data]
def rotate270(data):
return rotate90(rotate180(data)) | The code transforms the input data by first rotating it 270 degrees, then moving it east, and finally rotating the result 90 degrees. | def move_south(data):
return rotate90(move_east(rotate270(data))) |
def move_east(data):
return [tilt(l) for l in data]
def move_south(data):
return rotate90(move_east(rotate270(data)))
def move_west(data):
return rotate180(move_east(rotate180(data)))
def move_north(data):
return rotate270(move_east(rotate90(data))) | The main task of the code is to process input data by sequentially applying directional movement operations (north, west, south, east) to each line, stripping whitespace, and rejoining the transformed lines into a single string with newline separators. | def do_cycle(data):
data = list(map(lambda l: l.strip(), data.splitlines()))
data = move_east(move_south(move_west(move_north(data))))
return '\n'.join(data) |
def create_resources():
# Create nlb and grab ARN & dns name
lb = AmazonWebServices().create_network_lb(name=resource_prefix + "-nlb")
lbArn = lb["LoadBalancers"][0]["LoadBalancerArn"]
lbDns = lb["LoadBalancers"][0]["DNSName"]
# Upsert the route53 record -- if it exists, update, if not, insert
... | This function tests the installation of a high-availability Rancher setup using RKE. It checks certificate options, provisions infrastructure/resources if no kubeconfig is provided, installs Cert Manager (if enabled), deploys Rancher, validates cluster state, and creates a custom cluster. The process includes preparing... | def test_install_rancher_ha(precheck_certificate_options):
cm_install = True
if "byo-" in RANCHER_HA_CERT_OPTION:
cm_install = False
print("The hostname is: {}".format(RANCHER_HA_HOSTNAME))
# prepare an RKE cluster and other resources
# if no kubeconfig file is provided
if RANCHER_HA_KU... |
def write_kubeconfig():
file = open(kubeconfig_path, "w")
file.write(base64.b64decode(RANCHER_HA_KUBECONFIG).decode("utf-8"))
file.close()
def add_repo_create_namespace(repo=RANCHER_HELM_REPO):
helm_repo_cmd = \
export_cmd + " && helm_v3 repo add rancher-" + repo + \
" https://releases.r... | This code tests the upgrade process of a Rancher High Availability (HA) setup by writing Kubernetes configuration, adding repositories and creating namespaces, then performing an upgrade installation of Rancher. | def test_upgrade_rancher_ha(precheck_upgrade_options):
write_kubeconfig()
add_repo_create_namespace()
install_rancher(upgrade=True) |
def get_remote_tags_for_ref(remote, from_ref):
tag_ref_prefix = "refs/tags/"
tags = {}
for line in split_nonempty_lines(
check_output(["git", "ls-remote", "--tags", "--refs", remote])
):
h, tag = line.split(None, 1)
if not tag.startswith(tag_ref_prefix):
continue
... | This function retrieves version tags from a Git repository, prioritizing remote tags and falling back to local tags if remote fetching fails. It filters tags using a version pattern, returning a dictionary mapping tag hashes to version names that match the pattern. | def get_speedb_version_tags(remote, head_ref):
try:
tags = get_remote_tags_for_ref(remote, head_ref)
except subprocess.CalledProcessError:
warning("failed to fetch remote tags, falling back on local tags")
tags = get_local_tags_for_ref(head_ref)
version_tags = {h: n for h, n in tags... |
def _delete_all_simulation_points(self):
url = f"{self._url}{self._sensor}/delete_all/"
r = requests.get(url=url)
r.raise_for_status()
return r
def _simulate(self):
for v in self._data:
self._create_light_intensity_point(v)
def _get_light_intenstiy_points(self):
... | The main task of the code is to simulate sensor data, verify the number of generated intensity points matches expectations, check each point's value and sensor against original data, and clean up by deleting all simulation points to ensure correctness and consistency. | def simulate_and_check(self):
self._delete_all_simulation_points()
print("Delete all points previously stored with the same sensor")
self._simulate()
print("Data points simulated")
intensity_points = self._get_light_intenstiy_points()
assert len(intensity_points) == se... |
def angle_change_with_one_point(self):
return (self.SUNSET_ANGLE - self.SUNRISE_ANGLE) / self.total_number_of_points()
def total_number_of_points(self):
return self.points_difference(self.sunrise, self.sunset)
def target_total_illumination(self):
return self.target_average_illumination * self.to... | The code calculates a normalization factor by summing cosine values of angles derived from a sunset angle and incremental changes, then divides the target illumination by this sum to determine a normalized illumination value. | def calculate_f0(self):
angles = (
self.SUNSET_ANGLE + self.angle_change_with_one_point() * i
for i in range(self.total_number_of_points())
)
cosine_sum = sum(math.cos(math.radians(angle)) + 1 for angle in angles)
return self.target_total_illumination() / cosine_... |
def cramer_2x2(A, b):
# To do
subX = np.array([[b[0], A[0][1]],
[b[1], A[1][1]]])
subY = np.array([[A[0][0], b[0]],
[A[1][0], b[1]]])
x = np.array([det_2x2(subX)/det_2x2(A),
det_2x2(subY)/det_2x2(A)])
return x
def det_3x3(A):
detA... | The main task of the code is to test and compare Cramer's rule implementations for solving 2x2 and 3x3 linear systems using custom functions (`cramer_2x2`, `cramer_3x3`, `det_3x3`) against NumPy's `linalg.solve` for validation. It sets up matrices and vectors, computes solutions via Cramer's method, and prints results ... | def main():
# Set up a 2x2 array
A = np.array([[1., 2.],
[3., 4.]])
b = np.array([5., 6.])
A3 = np.array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 10.]])
b3 = np.array([10., 11., 12.])
print("Cramer's test:\n", cramer_2x2(A, b), '\n', sep='')
... |
def filelist(root):
"""Return a fully-qualified list of filenames under root directory"""
filenames = list()
for root_dir, sub_dirs, files in os.walk(root):
for file in files:
if file.endswith('.txt'):
filenames.append(os.path.join(root_dir, file))
return tuple(filen... | The main task of the code is to process articles from a specified root directory by retrieving their file paths, reading each article's text, tokenizing it through preprocessing, and compiling all tokenized articles into a list of lists. This function returns a structured collection of tokenized articles for further an... | def format_articles(root_dir):
# The root directory contains all articles for given party.
# Using the file path to an article text, load and read the article and process it.
# The processing step saves the article in a list of tokens. Append this list of tokens to a list.
# Returns a list containing a ... |
def calc_class_weights(data_dict, label_dict):
all_data = []
for data_name in ['train', 'validation', 'test']:
data = np.array(data_dict[data_name]).flatten()
label = np.array(label_dict[data_name]).flatten()
all_data.append(data)
all_data.append(label)
all_data = np.concaten... | This function trains a Seq2Seq model for sequence-to-sequence tasks using teacher forcing. It initializes the model, optimizer, and loss function with class weights. The training loop processes batches, computes loss, performs backpropagation with gradient clipping, and evaluates the model periodically. It saves traini... | def train(vocabs, batch_gen, train_params, model_params):
word2int, int2word = vocabs
num_epoch = train_params['num_epoch']
learn_rate = train_params['learn_rate']
clip = train_params['clip']
eval_every = train_params['eval_every']
train_tf_ratio = train_params['train_tf_ratio']
val_tf_ratio... |
def __load_from_csv(self):
# read all articles 1, 2 and 3
file_paths = os.listdir(self.raw_data_path)
file_paths = [os.path.join(self.raw_data_path, file_name) for file_name in file_paths]
df_list = []
for file in file_paths:
df = pd.read_csv(file, index_col=0)
... | This code initializes a dataset processor by either loading preprocessed data from pickle files or creating new data from CSV files. It sets parameters for data processing, constructs vocabulary and summary sets, and splits the data into training, validation, and test subsets for machine learning tasks. | def __init__(self, dataset_path, **data_params):
self.summary_path = os.path.join(dataset_path, 'summary_set.pkl')
self.vocab_path = os.path.join(dataset_path, 'vocab.pkl')
self.all_sum_save_path = os.path.join(dataset_path, 'all_sum_set.pkl')
self.raw_data_path = os.path.join(dataset_pa... |
def get_occupied_rooms(client: Any):
cursor = client.find(
collection=GUEST_COLLECTION,
search_query={},
projection_query={"keys": {"room_number": 1}},
)
occupied_rooms = []
for doc in cursor:
for key in doc["keys"]:
occupied_rooms.append(key["room_number"])
... | This code initializes a hotel database, seeds it with sample data, and provides a console interface for managing a fishing resort hotel. It allows users to view room/guest info, check room availability, calculate total booking prices via aggregation or MapReduce, and add new rooms/guests. The loop continues until the u... | def main():
# initialising DB
hotel_db = HotelMongoDBClient(CONNECTION_STRING, DB_NAME)
hotel_db.drop_db()
db_backfill_conf = {
ACCOMMODATION_COLLECTION: "src/data/accommodations_data.json",
GUEST_COLLECTION: "src/data/guest_data.json",
}
hotel_db.seed_db(db_backfill_conf)
... |
def check_input_gamemode(self):
if self.current_game_state == GameControl.GAME_OVER:
if pyxel.btn(pyxel.KEY_1):
self.start_new_game()
self.current_game_mode = GameMode.PLAYER_PLAYS
elif pyxel.btn(pyxel.KEY_2):
self.start_new_game()
... | The code updates the game state by calculating time intervals between frames, handling player or AI input based on the current game mode, and triggering snake movement and collision checks at intervals determined by speed. It accumulates time since the last move, resets counters when thresholds are met, and ensures app... | def update(self):
time_this_frame = time.time()
self.dt = time_this_frame - self.time_last_frame
self.time_last_frame = time_this_frame
self.time_since_last_move += self.dt
if self.current_game_mode == GameMode.NOBODY_PLAYS:
self.check_input_gamemode()
if self... |
def welcome(self, chatID, noWelcome=False):
welcome_string = ''
if(noWelcome==False):
welcome_string = "Hi , welcome to WhatsApp chatbot using Python\n"
else:
welcome_string = """wrong command
Please type one of these commands:
*hi* : Salut... | The function processes incoming messages by checking if `self.dict_messages` contains data. If so, it splits the message body into words, identifies the sender, and routes commands like 'hi', 'time', 'image', etc., to corresponding methods (e.g., `welcome`, `send_image`). If no command matches, it defaults to `welcome`... | def Processing_incoming_messages(self):
if self.dict_messages != []:
messages = self.dict_messages
text = message['body'].split()
if not message['fromMe']:
chatID = message['chat']['id']
if text[0] == 'hi':
return self.welco... |
def two_by_two_det(matrix: list) -> int:
"""
gets the determinant of a 2x2 matrix:
- matrix: 2x2 matrix
return determinant
"""
ad = matrix[0][0] * matrix[1][1]
bc = matrix[1][0] * matrix[0][1]
return ad - bc
def minor_matrix(matrix: list, row: int, col: int) -> list:
"""
Gets the... | The function `recursive_minor` computes the minor matrix of a square matrix recursively. For each element, it removes the corresponding row and column to form a submatrix, calculates its determinant (using a recursive method), multiplies it by the cofactor $(-1)^{i+j}$, and constructs the minor matrix. This process rep... | def recursive_minor(matrix: list) -> list:
"""
calculates the minor matrix of a square matrix with side bigger than 2
recursevely:
- matrix: list of lists whose minor matrix should be calculated
Returns: the minor matrix of matrix
"""
if len(matrix) == 2:
return two_by_two_det(matrix... |
def if_valid_password(username, password):
"""Check if the password is valid."""
# Get original password
connection = insta485.model.get_db()
cursor = connection.execute(
"SELECT password FROM users WHERE username = ?", (username,)
)
password_from_db = cursor.fetchone()
if password_f... | The function `show_accounts` handles account operations (login, logout, create, delete, edit, update password) by routing requests to corresponding functions. It validates credentials, manages user sessions, and redirects to a target URL after processing. | def show_accounts():
"""Intermediate page."""
connection = insta485.model.get_db()
operation = flask.request.form.get("operation")
target = flask.request.args.get("target", "/")
if operation == "login":
username = flask.request.form.get("username")
password = flask.request.form.get("... |
def load_and_parse_config(config_path: str) -> ConfigData:
"""
Load config JSON file and record information.
"""
try:
config_file = load_json(config_path)
return parse_config(config_file)
except Exception as err:
sys.exit(f'ERROR: {err}\nUnable to load or parse config. Exitin... | The main task of the code is to monitor cluster health by checking node/drive statuses, comparing current status to a previous state, and sending email alerts if unhealthy conditions are detected. It loads configuration, connects to the cluster, retrieves device statuses, checks for anomalies, and manages status persis... | def main(opts: argparse.Namespace) -> int:
config_data = load_and_parse_config(opts.config)
healthy = True
previous_file = 'cluster_status_previous.json'
if opts.print_config_data:
print(config_data)
return 0
check_cluster_connectivity(config_data)
# CHECK AND RECORD CLUSTER S... |
def getDiceDistribution(numdice, numsides):
single_die = getDieDistribution(numsides)
ret_die = single_die
for die in range(numdice-1):
ret_die = convolveDice(ret_die,single_die)
return ret_die
def getMaxDistribution(numdice, numsides):
probs = np.ones(numsides)
rolls = rolls = np.linspa... | This code initializes an object by parsing an expression to determine the probability distribution (PDF). It uses regex to identify formats like dice notation (e.g., '2d6'), advantage/disadvantage rolls ('adv', 'dis'), and max/min functions. Depending on the expression, it assigns the corresponding PDF using helper fun... | def __init__(self,expr: str = 'unknown',pdf = np.array([])) -> None:
self.expr = expr
if re.match('[0-9]+d[0-9]+', expr): # nds form
numdice = int(expr.split("d")[0])
numsides = int(expr.split("d")[1])
self.pdf = getDiceDistribution(numdice, numsides)
elif re... |
def expected_value(self):
ex = 0.0
for term in range(len(self.pdf[0])):
ex += self.pdf[0][term]*self.pdf[1][term]
return ex
def standard_dev(self):
return (self.variance()**0.5)
def minimum(self):
return self.pdf[1][0]
def maximum(self):
return self.pdf[1][-1] | The code prints statistical metrics including minimum, maximum, average, and standard deviation of a dataset. It formats the output to display the 66% confidence interval around the mean (average ± 1 standard deviation). This method is likely part of a class that analyzes numerical data, providing a summary of key desc... | def print_stats(self):
expected = self.expected_value()
stddev = self.standard_dev()
print("\tMinimum: {}".format(self.minimum()))
print("\tMaximum: {}".format(self.maximum()))
print("\tAverage: {:.2f}".format(expected))
print("\tStdDev: {:.2f} 66%[{:.2f},{:.2f}]".format... |
def get_data_from_api(url):
response = requests.get(url)
data = response.json()
return data
def fund_payload():
payload = {
"rta_fund_code": "scheme",
"name": "schdesc",
"fund_type": "category",
"fund_category": "category",
"fund_sub_type": "subcategory",
... | The code fetches data from a specified API endpoint, generates a payload using `fund_payload()`, and stores the retrieved fund data and scheme details into a database via `AMCFund.store_fund_data` and `store_fund_scheme_data` methods. The main task involves retrieving, processing, and persisting financial scheme data f... | def handle(self, *args, **options):
url = "https://clientwebsitesuat3.kfintech.com/bajaj/api/v1/masterData/getSchemes"
data = get_data_from_api(url)
payload_fund = fund_payload()
AMCFund.store_fund_data(payload_fund, data)
store_fund_scheme_data(data) |
def masks_as_image_resized(row, all_masks=None, resized_shape=(256, 256)):
"""
:param row:
:param all_masks:
:param resized_shape:
:return:
"""
if all_masks is None:
all_masks = np.zeros(resized_shape, dtype=np.uint8)
if isinstance(row['EncodedPixels'], str):
mask = rle... | The main task of the code is to process a DataFrame by resizing images and their corresponding masks to a specified target size. It initializes arrays for storing resized masks and RGB images, iterates through each row of the DataFrame to generate resized masks and images, and compiles them into a dictionary. If enable... | def process_dataframe_resized(data, target_size=(256, 256), print_log=True):
num_rows = len(data)
masks = np.zeros((num_rows, *target_size, 1), dtype=np.uint8)
images_rgb = np.zeros((num_rows, *target_size, 3), dtype=np.uint8)
for i in range(num_rows):
mask = masks_as_image_resized(data.iloc[i]... |
def driverIsAlive(self):
"""
Returns True if driver is alive, False otherwise"""
if(self.driver == None):
return False
try:
self.driver.current_url
return True
except:
return False
def setup(self):
""" Sets up driver and lo... | The main task of the code is to enter lotteries for all shows stored in the SHOWS_TO_ENTER_PATH. It ensures the driver is active, generates the list of shows to enter, and delegates the lottery entry process to the `enterLotteriesCustom` method, with an option to quit after completion. | def enterLotteries(self, quitAtEnd = True):
"""Enters lotteries for all shows saved in SHOWS_TO_ENTER_PATH"""
if(not self.driverIsAlive()):
self.setup()
self.createShowsToEnter()
self.enterLotteriesCustom(self.showsToEnter, quitAtEnd) |
def parse_toml(self, toml_file):
with open(toml_file) as file:
data = file.read()
parsed_toml = toml.loads(data)
return parsed_toml
def get_nutrition_plans_list(self,toml_file):
a = self.parse_toml(toml_file=toml_file)
dict1 = a.get('nutrition_plans')
return d... | The code parses a TOML file containing nutrition plans, creates each plan in the system, retrieves the generated plan ID, and adds associated meals to the plan using the ID. It processes each plan's 'meals' section recursively, ensuring structured data from the TOML is correctly integrated into the system's nutrition p... | def add_nutrition_plans_toml(self,toml_file_plans):
parsed_toml = self.parse_toml(toml_file=toml_file_plans)
if "nutrition_plans" in parsed_toml:
nutrition_plans_dict = self.get_nutrition_plans_list(toml_file_plans)
for nutrition_plan_key,nutrition_plan_value in nutrition_plans_d... |
def name_to_id(self, param1,param1_value ,param2, object):
req = self.get_req(object)
print(req[0].get('results', []))
for item in req[0].get('results', []):
if item.get(param1) == param1_value:
return item.get(param2), f"The id for {param1} was provided successfully"... | This code adds workout days and their associated exercises from a TOML configuration to a system. It maps a workout name to an ID, iterates through TOML day entries, creates day records with descriptions, and links exercises to each day using helper methods. | def add_days_for_workouts_toml(self,toml_days,workout):
workout_id_req = self.name_to_id(param1='name',param1_value=workout,param2='id',object='workout')
workout_id = workout_id_req[0]
for day_key,day_val in toml_days.items():
add_day1 = self.add_day(training=workout_id,description=d... |
def get_workouts(self,file):
a = self.parse_toml(toml_file=file)
dict = a.get('workouts',{})
return dict
def add_workout_day(self,name,description):
data = {
"name":name,
"description":description
}
return self.post_req('workout',data)
def add_d... | This function parses a TOML file containing workout data, extracts each workout's name and description, and adds them to the system. If the workout includes specific days, it further processes and adds those days associated with the workout using the provided key. The main task is to import and organize workout informa... | def add_workouts_toml_file(self,file):
toml_workouts = self.get_workouts(file=file)
for workout_key,workout_value in toml_workouts.items():
self.add_workout_day(workout_value.get('name'),
workout_value.get('description'))
if "days" ... |
def get_turn(self):
return self.pieces[self.turn]
def set_tile(self, coords, value, forced=False):
"""Set the value of the tile at coordinates to given piece."""
if forced or coords in self.allowed_moves:
if value in self.pieces:
self.subtiles[coords[0]][coords[1]] = ... | The function `make_a_move` places the current player's piece at specified coordinates, checks if the move is legal by attempting to set the tile, and updates the game state. It declares a win/draw if applicable, switches turns, and clears allowed moves upon game end. Returns `True` for a legal move or `False` if invali... | def make_a_move(self, coords, forced=False):
"""
Add piece of whoever's turn it is to the given coordinates.
Returns whether the move was legal
"""
piece = self.get_turn()
if self.set_tile(coords, piece, forced):
if len(self.find_winner(piece, coords)) > 1:
... |
def is_legal(self, action):
"""determine if the given action (x,y tuple) is a legal move
note: we only check ko, not superko at this point (TODO?)
"""
# passing is always legal
if action is PASS_MOVE:
return True
(x, y) = action
if not self._on_board(a... | The main task of the code is to determine if a given move results in a "ladder capture" in a board game (likely Go). It checks if the move captures an adjacent enemy group with exactly two liberties, ensuring no valid escape moves exist for the opponent. The function recursively explores potential escape paths, limited... | def is_ladder_capture(self, action, prey=None, remaining_attempts=80):
"""Check if moving at action results in a ladder capture, defined as being next
to an enemy group with two liberties, and with no ladder_escape move afterward
for the other player.
If prey is None, check all adjacent... |
def is_legal(self, action):
"""determine if the given action (x,y tuple) is a legal move
note: we only check ko, not superko at this point (TODO?)
"""
# passing is always legal
if action is PASS_MOVE:
return True
(x, y) = action
if not self._on_board(a... | The main task of the code is to determine if a move results in escaping a ladder by checking if the action increases a group's liberties to >=3 or provides two liberties that are not ladder-capturable. It evaluates adjacent groups (or a specific prey group) after the move, using recursion depth control to avoid infinit... | def is_ladder_escape(self, action, prey=None, remaining_attempts=80):
"""Check if moving at action results in a ladder escape, defined as being next
to a current player's group with one liberty, with no ladder captures
afterward. Going from 1 to >= 3 liberties is counted as escape, or a
... |
def is_legal(self, action):
"""determine if the given action (x,y tuple) is a legal move
note: we only check ko, not superko at this point (TODO?)
"""
# passing is always legal
if action is PASS_MOVE:
return True
(x, y) = action
if not self._on_board(a... | This function generates a list of legal moves on a game board, optionally including 'eyes' (potential self-atari moves). It uses caching for efficiency, checking each position's legality and whether it forms an eye. If no cache exists, it iterates through the board, classifying moves into legal moves or eyes, then recu... | def get_legal_moves(self, include_eyes=False):
if self.__legal_move_cache is not None:
if include_eyes:
return self.__legal_move_cache + self.__legal_eyes_cache
else:
return self.__legal_move_cache
self.__legal_move_cache = [PASS_MOVE]
self... |
def is_legal(self, action):
"""determine if the given action (x,y tuple) is a legal move
note: we only check ko, not superko at this point (TODO?)
"""
# passing is always legal
if action is PASS_MOVE:
return True
(x, y) = action
if not self._on_board(a... | The code's main task is to handle a player's move in a board game (likely Go), validate its legality, update the board state, manage captures, apply ko rules, track player turns, and check for game-ending conditions like consecutive passes or maximum moves. It switches players after a legal move, updates game history, ... | def do_move(self, action, color=None):
"""Play stone at action=(x,y). If color is not specified, current_player is used
If it is a legal move, current_player switches to the opposite color
If not, an IllegalMove exception is raised
"""
color = color or self.current_player
... |
def get_tile(self, position):
# returns the indices of the tile from current position
if position is None or not isinstance(position, tuple): return None
tile_x = int(math.floor(position[0]/self.tile_size))
tile_y = int(math.floor(position[1]/self.tile_size))
if not self.try_tile... | This function calculates the ideal heading angle for a Duckiebot at a given position on a map, considering the tile type (straight, curve, 3-way, 4-way). It returns the expected orientation in degrees for valid tiles, or None for complex intersections/asphalt tiles. The heading is determined based on lane positioning, ... | def pos_to_ideal_heading(self, position):
"""Method to calculate the "should-be" orientation of the duckiebot
at a given position
Note:
If lane following worked perfectly the heading of the duckiebot
should be equal to the output of this function
Args:
... |
def get_tile(self, position):
# returns the indices of the tile from current position
if position is None or not isinstance(position, tuple): return None
tile_x = int(math.floor(position[0]/self.tile_size))
tile_y = int(math.floor(position[1]/self.tile_size))
if not self.try_tile... | The function `pos_to_ideal_position` calculates the ideal localization position for a Duckiebot on a map, adjusting for lane alignment in straights, radial positioning in curves, and grid-search optimization on asphalt tiles. It returns the corrected (x,y) coordinates or `inf` for intersections, handling different tile... | def pos_to_ideal_position(self, position, heading=None):
"""Method to calculate the "should-be" position of the duckiebot
at a given (real) position
Notes:
- For straights, it only changes the lateral coordinate to be
in the middle between the white and the yellow line
... |
def _handle_settlements(self):
cur_date = dt.datetime.strptime(self.current_date, '%Y-%m-%d')
for t, asset in list(self.active_holdings.items()):
qty = asset.quantity
if asset.atype == 'FUTURES' and cur_date == asset.maturity_date and qty != 0:
self.trade(self.cur... | The main task of the code is to simulate advancing to the next day in a financial model by processing daily settlements, updating the net asset value (NAV), updating time series data, and incrementing the date index to reflect the next date from a predefined date list. | def next_day(self):
print(f"Current date: {self.current_date}")
self._handle_settlements()
self._update_nav()
print(f"Current NAV: {self.nav}")
print("")
self._update_series()
self.current_date_idx += 1
self.current_date = self.dates['date'][self.curren... |
def update_height(self, node):
if node is not None:
node.height = 1 + max(self.height(node.left),
self.height(node.right))
def balance_factor(self, node):
if node is None:
return 0
return self.height(node.left) - self.height(node.right)
d... | This function inserts a key into an AVL tree, maintaining balance through rotations. It recursively inserts the key into the appropriate subtree, updates node heights, calculates balance factors, and applies left/right rotations to correct imbalances caused by insertions, ensuring the tree remains height-balanced. | def insert(self, root, key):
if root is None:
return TreeNode(key)
if key < root.key:
root.left = self.insert(root.left, key)
elif key > root.key:
root.right = self.insert(root.right, key)
else:
return root
self.update_height(root... |
def pick_god_gender(sphere: str) -> str:
"""
Decides what gender the god will have based on the sphere of the god using the random.choice method and lists.
"""
if sphere == "good":
return random.choice(["male"] * 6 + ["female"] * 6 + ["nonb"] * 2)
if sphere == "neutral":
return rando... | The code generates a random non-pantheistic god with attributes like sphere, gender, name, domains, involvement, angel-like traits, and appearance, using helper functions and input fantasy level to customize the god's characteristics. | def generate_totally_random_god_non_pan(fant_lvl: int) -> God:
sph = random.choice(["good", "neutral", "evil", "force", "eldritch"])
gen = pick_god_gender(sph)
nm = pick_god_name(sph, gen)
g_of1 = pick_god_of1(sph, nm)
g_of2 = pick_god_of2(sph, nm, g_of1)
inv = pick_god_involvement(sph, fant_lvl... |
def pick_god_name(sphere: str, gender: str) -> str:
"""
Basically uses the sphere and gender of the god and assign it a name using the random.choice method and lists.
"""
if sphere == "good" and gender == "male":
return random.choice(RANDOM_GENERATOR["good male name"])
if sphere == "good" an... | This function generates a non-pantheistic god with attributes like name, domain, involvement, and appearance, tailored to a specified gender and fantasy level by randomly selecting traits and using helper functions to construct a detailed god profile. | def generate_gendered_god_non_pan(fant_lvl: int, gender: str) -> God:
sph = random.choice(["good", "neutral", "evil", "force", "eldritch"])
gen = gender
nm = pick_god_name(sph, gen)
g_of1 = pick_god_of1(sph, nm)
g_of2 = pick_god_of2(sph, nm, g_of1)
inv = pick_god_involvement(sph, fant_lvl)
a... |
def pick_god_gender(sphere: str) -> str:
"""
Decides what gender the god will have based on the sphere of the god using the random.choice method and lists.
"""
if sphere == "good":
return random.choice(["male"] * 6 + ["female"] * 6 + ["nonb"] * 2)
if sphere == "neutral":
return rando... | The function generates a non-pantheon god entity with attributes like gender, name, domains, involvement, angelic traits, and appearance, based on input parameters 'sphere' and 'fantasy level'. It combines multiple helper functions to construct a God object with unique characteristics, ensuring the 'pan' flag is set to... | def generate_sphered_god_non_pan(fant_lvl: int, sphere: str) -> God:
sph = sphere
gen = pick_god_gender(sph)
nm = pick_god_name(sph, gen)
g_of1 = pick_god_of1(sph, nm)
g_of2 = pick_god_of2(sph, nm, g_of1)
inv = pick_god_involvement(sph, fant_lvl)
ang = pick_god_angel_like(sph, inv, fant_lvl)... |
def pick_god_name(sphere: str, gender: str) -> str:
"""
Basically uses the sphere and gender of the god and assign it a name using the random.choice method and lists.
"""
if sphere == "good" and gender == "male":
return random.choice(RANDOM_GENERATOR["good male name"])
if sphere == "good" an... | The code generates a `God` object with attributes like name, sphere, gender, and relationships, using input parameters and helper functions. It sets `pan` to False, determines involvement, angel-like traits, and appearance, then returns the constructed `God` instance. | def generate_tooled_god_non_pan(fant_lvl: int, sphere: str, gender: str, g_of1: str) -> God:
sph = sphere
gen = gender
nm = pick_god_name(sph, gen)
g_of1 = g_of1
g_of2 = pick_god_of2(sph, nm, g_of1)
inv = pick_god_involvement(sph, fant_lvl)
ang = pick_god_angel_like(sph, inv, fant_lvl)
i... |
def pick_god_gender(sphere: str) -> str:
"""
Decides what gender the god will have based on the sphere of the god using the random.choice method and lists.
"""
if sphere == "good":
return random.choice(["male"] * 6 + ["female"] * 6 + ["nonb"] * 2)
if sphere == "neutral":
return rando... | The function generates a unique pantheon god with attributes like sphere, gender, name, domains, involvement, and appearance, ensuring the 'god_of1' domain is distinct from existing entries in the provided pan_list. It uses helper functions to randomly select properties while prioritizing uniqueness for the primary dom... | def generate_pan_god(fant_lvl: int, pan_list: dict):
unique = False
if pan_list[0].sphere == 'good' or pan_list[0].sphere == 'neutral' or pan_list[0].sphere == 'evil':
sph = random.choice(["good", "neutral", "evil"])
else:
sph = pan_list[0].sphere
gen = pick_god_gender(sph)
nm = pick... |
def hospital_picker(hospital):
"""Returns a lowercased hospital id and tag definitions.
Parameters:
hospital (str): The internal reference for the hospitals within the Serums system
Returns:
hospital_id (str): The hospital id is used throughout during... | The main task of the code is to generate a Smart Patient Health Record by validating JWT credentials, determining authorized data tags, querying patient data across specified hospitals, and compiling results into a structured format. It checks user permissions, filters tags, connects to hospital databases, retrieves pa... | def get_patient_data(body, jwt):
"""The main function for generating the Smart Patient Health Record
Parameters:
body (dict): The request body from the API call
Returns:
smart_patient_health_record (DataFrame): A DataFrame containing the selected patie... |
def is_train_test_file_exists(self)->bool:
try:
logging.info("Checking if training and test file is available")
is_train_file_exist = False
is_test_file_exist = False
train_file_path = self.data_ingestion_artifact.train_file_path
test_file_path = self... | The main task of the code is to validate data by checking the existence of training/test files, verifying dataset schema compliance, and detecting data drift. It then creates a `DataValidationArtifact` containing validation status, file paths, and a success message. If any step fails, it raises an exception. The functi... | def initiate_data_validation(self)->DataValidationArtifact :
try:
self.is_train_test_file_exists()
validation_status=self.validate_dataset_schema()
self.is_data_drift_found()
data_validation_artifact = DataValidationArtifact(
schema_file_path=self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.