dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def peak_detector_basic(data, wfun, max_level, window_size, window_size_for_threshold, search_radius):
#
peak_loc_ensemble = np.array([])
features = np.zeros_like(data)
for ch in np.arange(data.shape[0]):
data_const = wavelet_filtering(data[ch, :], wfun, max_level)
#
feature = lo... | This function detects ECG peaks using a wavelet-based method, then refines results by: 1) identifying missing peaks via interval thresholds (initial 750, then 1.7×median interval), and 2) removing false peaks (0.33×median interval). It returns refined peak positions and features for ECG signal analysis. | def peak_detector_with_refinement(file_name, wfun='sym8', max_level=8, window_size=50, window_size_for_threshold=1000,
search_radius=50):
#
data = sio.loadmat(file_name)['ECG'][0][0][2]
#
peaks, features = peak_detector_basic(data, wfun, max_level, window_size, window_s... |
def peak_detector_basic(data, wfun, max_level, window_size, window_size_for_threshold, search_radius):
#
peak_loc_ensemble = np.array([])
features = np.zeros_like(data)
for ch in np.arange(data.shape[0]):
data_const = wavelet_filtering(data[ch, :], wfun, max_level)
#
feature = lo... | The code refines peak detection by first identifying initial peaks, then retrieving missing peaks using a fixed threshold and an adaptive threshold based on peak spacing, followed by removing false peaks using a spacing-based threshold, ultimately returning refined peak locations and associated features. | def peak_detector_with_refinement_v2(data, wfun='sym8', max_level=8, window_size=50, window_size_for_threshold=1000,
search_radius=50):
peaks, features = peak_detector_basic(data, wfun, max_level, window_size, window_size_for_threshold, search_radius)
missing_peak_thres = 750
... |
def get_current_date_widget():
current_date = datetime.now()
if 10 <= current_date.day <= 20:
suffix = 'th'
else:
suffix = {1: 'st', 2: 'nd', 3: 'rd'}.get(current_date.day % 10, 'th')
formatted_date = current_date.strftime(f"%A, %B {str(current_date.day) + suffix}")
return html.S... | The code generates a weather dashboard UI by fetching weather data, conditionally displaying date/time widgets, and arranging current weather, hourly forecasts, and daily forecasts in a styled HTML layout with flexbox structure. | def get_weather_widget(run_lite):
weather_data = weather_api_call()
if run_lite:
datetime_widget_child = get_current_date_widget()
else:
datetime_widget_child = get_current_time_widget()
daily_forecast_list = pull_daily_forecast(weather_data)
hourly_forecast_list = pull_ho... |
def get_user_list_resource_name(client, customer_id, list_name):
"""Gets the User List using the name provided.
Args:
client: The Google Ads client instance.
customer_id: The customer ID for which to add the user list.
list_name: The name of the user list to search.
Returns:
The User List resour... | The main task of the code is to upload processed customer data to a Google Ads user list, creating the list if it doesn't exist. It uses the provided client, customer ID, list name, type, and data to either retrieve an existing list or create a new one, then uploads the data while optionally skipping API polling for co... | def upload_data(client,
customer_id,
list_name,
list_type,
customer_data,
skip_polling,
app_id=None):
"""Uploads processed data to the specified list and creates it if necessary.
Args:
client: The Google Ads client.... |
def uniform(n=1):
""" This function simulates a uniform distribution on [0, 1] """
return np.random.uniform(0, 1, n)
def uniform_1(n=1):
""" This function simulates a uniform distribution on [-1, 1] """
return uniform(n=n) * 2 - 1
def uniform_pi(n=1):
""" This function simulates a uniform distributi... | This function generates samples from a von Mises distribution using rejection sampling with a wrapped Cauchy proposal. It computes parameters (tau, rho, r), generates candidate samples, and applies an acceptance criterion. For non-zero kappa, it iteratively samples until reaching the desired size, adjusting outputs to ... | def von_mises_cauchy(mu=0., kappa=1., n=1):
"""
This function simulates a von Mises distribution using the
rejection sampler based on a wrapped Cauchy distribution :
https://www.researchgate.net/publication/246035131_Efficient_Simulation_of_the_von_Mises_Distribution
:param float mu: mu
:param ... |
def uniform(n=1):
""" This function simulates a uniform distribution on [0, 1] """
return np.random.uniform(0, 1, n)
def uniform_1(n=1):
""" This function simulates a uniform distribution on [-1, 1] """
return uniform(n=n) * 2 - 1
def uniform_pi(n=1):
""" This function simulates a uniform distributi... | The function estimates the acceptance rate of generating von Mises distributed samples using a wrapped Cauchy distribution as the proposal distribution. It simulates n samples, applies an acceptance criterion based on logarithmic comparisons, and returns the percentage of accepted samples relative to n. | def von_mises_cauchy_acceptance(kappa=1., n=100_000):
"""
This function estimates the acceptance rate according to a wrapped cauchy distribution
as proposal distribution.
https://www.researchgate.net/publication/246035131_Efficient_Simulation_of_the_von_Mises_Distribution
:param float mu: mu
:p... |
def config_dist_env_and_opt(opt):
opt = copy.copy(opt)
# set world_size, gpu, global rank
if opt.dist_mode == 'cpu':
opt.gpu = None
opt.world_size = 1
opt.rank = 0
elif opt.dist_mode == 'single':
if opt.gpu is None:
opt.gpu = 0
opt.world_size = 1
... | The main task of the code is to train and validate an image classification model with distributed training support. It loads datasets, initializes a model, configures loss functions and optimizers, handles mixed precision, and performs training or evaluation based on flags. The code supports checkpointing, resuming tra... | def main(opt, argv):
assert opt.save_dir is not None
job_done_fn = os.path.join(opt.save_dir, 'train_image_classification.done')
if os.path.isfile(job_done_fn):
print('skip ' + job_done_fn)
return
opt = config_dist_env_and_opt(opt)
# create log
if opt.rank == 0:
log_fi... |
def initialize_grid(self):
#Create the grid of checkboxes
for row in range(GRID_SIZE): #Repeat 5 times as the GRID_SIZE constant = 5
for col in range(GRID_SIZE): #Used to create columns for the grid of checkboxes in the game
var = tk.BooleanVar() #Create a BooleanVar for eac... | This code initializes a GUI-based Colour Match Game using Tkinter. It sets up the game window, creates UI elements like instructions, target color display, timer, grid of color boxes, control buttons, and event handlers. The constructor configures the game's structure, binds keyboard inputs, and prepares the game envir... | def __init__(self, master): #Constructor used to create the attributes of the ColourMatchGame class
self.master = master
self.master.title("Colour Match Game") #Name of the window
self.master.geometry("550x750") #Size of the game window
self.master.resizable(False, False) #Game window ca... |
def load_high_scores(self):
#Load the high scores from the file
try:
with open(HIGH_SCORE_FILE, "r") as file:
high_scores = [line.strip().split(",") for line in file]
return high_scores
except FileNotFoundError:
return []
def is_high_score(self... | The code ends the game by calculating the total playtime, resetting the timer, loading high scores, checking if the current score is a high score, and either prompting the player for their name to record the high score or displaying the end screen. | def end_game(self):
#End the game and check for high scores
self.total_time = round(time.time() - self.start_time, 2)
self.start_time = None
#Check if the current time is a high score
high_scores = self.load_high_scores()
if self.is_high_score(high_scores):
s... |
def initialize_grid(self):
#Create the grid of checkboxes
for row in range(GRID_SIZE): #Repeat 5 times as the GRID_SIZE constant = 5
for col in range(GRID_SIZE): #Used to create columns for the grid of checkboxes in the game
var = tk.BooleanVar() #Create a BooleanVar for eac... | The code initializes a GUI for a colour-matching game, setting up a window with a black background, instructions, a target colour display, a timer, and a grid of interactive boxes. It creates controls for checking answers, restarting, and exiting, binds keyboard shortcuts, and initializes game mechanics like levels and... | def __init__(self, master): #Constructor used to create the attributes of the ColourMatchGame class
self.master = master
self.master.title("Colour Match Game") #Name of the window
self.master.geometry("550x750") #Size of the game window
self.master.resizable(False, False) #Game window ca... |
def clear_window(self):
for widget in self.master.winfo_children(): #Loop through all widgets that are in the wiindow
widget.destroy()
def get_attribute(self):
return "instagram followers" if self.current_topic == "Celebrities" else "net worth"
def load_data(self):
file_path = celebr... | The code creates a game screen where users guess which celebrity or company has a higher value of a specific attribute. It clears the window, displays a question label, loads two random entries from external data, and presents them as clickable buttons. The buttons trigger a check_answer method to evaluate the user's c... | def create_game_screen(self):
self.clear_window() #Clear the current window by destroying all widgets
topic_word = "celebrity" if self.current_topic == "Celebrities" else "company" #Decide the word 'celebrity' or 'company' based on the selected topic
label = tk.Label(self.master, text=f"Guess wh... |
def initialize_grid(self):
#Create the grid of checkboxes
for row in range(GRID_SIZE): #Repeat 5 times as the GRID_SIZE constant = 5
for col in range(GRID_SIZE): #Used to create columns for the grid of checkboxes in the game
var = tk.BooleanVar() #Create a BooleanVar for eac... | This code initializes the ColourMatchGame GUI, setting up the window, UI elements (instructions, target color display, timer, grid of checkbuttons), buttons (Check, Restart, Menu, Exit), and keyboard bindings. It prepares the game environment and starts the game, enabling players to interact by matching colors within a... | def __init__(self, master): #Construct the parts that make up ColourMatchGame class
self.master = master
self.master.title("Colour Match Game") #Name of the window
self.master.geometry("550x775") #Size of the game window
self.master.resizable(False, False) #Game window cannot be resized ... |
def clear_window(self): #Clear the current window by destroying all widgets
for widget in self.master.winfo_children(): #Check if there are widgets in the window
widget.destroy()
def get_attribute(self): #Get the attribute based on the selected topic
if self.current_topic == "Celebrities":
... | The main task of the code is to create a game screen where users guess which celebrity or company has a higher attribute. It clears the window, displays a question label, loads random data entries, creates two buttons for the choices, and links them to the check_answer method for user interaction. | def create_game_screen(self): #Create the game screen
self.clear_window() #Clear the current window
topic_word = "celebrity" if self.current_topic == "Celebrities" else "company" #For the labels to use the correct wording and proper grammar later
label = tk.Label(self.master, text=f"Guess which... |
def update_level_label(self):
#Update the level label with the current level
self.level_label.config(text = "Level {}".format(self.level))
def randomize_grid_colours(self):
#Randomize the colours of the grid checkboxes
target_colour = random.choice(list(COLORS.keys()))
self.targe... | The code checks selected checkboxes against target colors, counts correct/incorrect selections, and advances the game level if all correct checkboxes are selected without errors, otherwise displaying a warning message. | def check_boxes(self):
#Check if the selected checkboxes are correct
correct_count = 0
incorrect_count = 0
for checkbutton, var in self.grid_checkbuttons:
if var.get() and checkbutton.target_colour:
correct_count += 1
elif not var.get() and checkbu... |
def initialize_grid(self):
#Create the grid of checkboxes
for row in range(GRID_SIZE):
for col in range(GRID_SIZE):
var = tk.BooleanVar()
checkbutton = tk.Checkbutton(self.grid_frame, width = 10, height = 5, variable = var, anchor = tk.CENTER)
... | (The code initializes a "Colour Match Game" GUI, setting up a window with instructions, a target color display, a timer, a grid of interactive boxes, level tracking, and buttons for checking answers, restarting, and accessing a menu. It binds the spacebar to the check action and prepares the game grid for gameplay.) | def __init__(self, master):
self.master = master
self.master.title("Colour Match Game")
self.master.resizable(False, False)
self.level = 1
self.start_time = None
self.total_time = None
#Create the top frame for instructions and target colour
self.top_fram... |
def end_screen(self):
'''Ends the game and displays score / reset info'''
while True:
#If ship2 not alive
if not self.ship2.alive():
#Fill the screen red
self.screen.fill((200, 100, 100))
#Use special font
#Kam Summe... | The code defines a main game loop that continuously checks if either ship has been destroyed to trigger an end screen, processes events, and updates the game screen in real-time to maintain gameplay flow. | def run_game(self):
"""Main Loop"""
while True:
#End Screen if ship2 wins
if not self.ship1.alive():
self.end_screen()
#End screen if ship1 wins
if not self.ship2.alive():
self.end_screen()
#Constantly check for ... |
def normal_f_v(self, v):
"""Normal vector at v
Normal vector at v
Args:
v:
Returns:
normal_vec:
"""
gv = self.grad_f_v(v)
gvn = np.linalg.norm(gv, axis=1)
return (gv / gvn[:, np.newaxis])
def f_v(self, v):
"""Metaball ... | This function moves a point onto the surface of a metaball by iteratively adjusting its position along the normal direction, using gradient information. It computes the normal vector at the initial point, then updates the position in each iteration until the change falls below a threshold or the maximum iterations are ... | def stick_to_mb(self, vs0, max_ite=10, eps=1.0e-10):
"""Move a point onto the surface of metaball
Move a point onto the surface of metaball
Args:
vs0:
max_ite:
eps:
Returns:
vs:
"""
n = len(vs0)
normal_vs0 = se... |
def sendTilde(self, serialObject, timer):
# Define command strings to send
# Tilde is sent to interrupt boot sequence
command = '~\n'
# 'version' is sent as it gives an output to read
# 'version' was chosen as the command as it does not return anything in linux, only in UBoot
... | (The main task of the code is to update a device's kernel via TFTP by validating prerequisites, configuring network settings, initiating a TFTP server, rebooting the device, sending U-Boot commands to trigger the update, and restoring network configurations. It checks required kernel files, handles SSH/serial communica... | def runUpdate(self, serialObject, conIP, PCIP, kernelPath):
# Check if IP addresses are valid
test = ipaddress.IPv4Address(conIP)
test = ipaddress.IPv4Address(PCIP)
# Replace slashes in kernel path
# The TFTP server didn't like the standard way
newpath = kernelPath.repl... |
def load(filepath):
df = pd.read_csv(filepath)
return df
def run_prompts(model: HookedTransformer, *prompts, **kwargs):
device = get_device()
_, cache = model.run_with_cache(list(prompts), **kwargs)
cache.prompts = list(prompts)
cache.device = device
return cache
def generate(cache):
ret... | The main task of the code is to load existing data from a CSV file if it exists, or generate new data by running prompts through a model, converting the results to a DataFrame, and saving it as a CSV file when the file is not found or if forced to create new data. | def load_or_create_data(filename, model, *prompts, force_create=False):
try:
if force_create:
raise FileNotFoundError
df = load(filename)
except FileNotFoundError as e:
cache = run_prompts(model, *prompts)
print(f'Creating new file {filename}')
data = generate... |
def create_output(pin):
gpio_out = digitalio.DigitalInOut(pin)
gpio_out.direction = digitalio.Direction.OUTPUT
return gpio_out
def create_input(pin):
gpio_in = digitalio.DigitalInOut(pin)
gpio_in.direction = digitalio.Direction.INPUT
gpio_in.pull = digitalio.Pull.DOWN
return gpio_in
def crea... | The code initializes and monitors button and potentiometer peripherals. It sets up buttons as inputs/outputs, tracks their states, and prints changes. It also reads potentiometer values, detecting and printing changes. The loop continuously scans for input changes, logging updates to the console. | def test_peripherals():
buttons_select = []
buttons_data = []
buttons_state = {}
for pin in BUTTON_SELECT:
buttons_select.append(create_output(pin))
buttons_select[-1].value = False
for pin in BUTTON_DATA:
buttons_data.append(create_input(pin))
for select_index, select in... |
def __decode_units(string):
word_num = ''
if '1' in string:
word_num = 'one'
elif '2' in string:
word_num = 'two'
elif '3' in string:
word_num = 'three'
elif '4' in string:
word_num = 'four'
elif '5' in string:
w... | The code calculates the total character count (excluding spaces) of the English word representations of numbers from 1 to 1000 by iterating through each number, converting it to words using private decoding methods, and summing the lengths of these word strings. | def result(self):
result = 0
for i in range(1, 1000 + 1):
s = str(i)
number_string = ''
if len(s) == 1:
word_unit = self.__decode_units(s)
number_string = word_unit
elif len(s) == 2:
word_dozens = self.__deco... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def normalize_string(self, input_string):
result = self.remove_accents(input_string)
result = result.lower()
result = result.replace(" ", "_")
return result
def discovery_create_control(self, type, name, config):
sel... | This code generates MQTT discovery configurations for an HVAC system in Home Assistant, creating entities like climate control, switches, selectors, sensors, and a refresh button. Each component is configured with topics, parameters, and device info, then registered using `discovery_create_control` to enable integratio... | def discovery_config(self):
self.log_debug(f"set_discovery_config()")
unique_name = self.normalize_string(f"{self.room_name}-hvac")
# Climate device
config = {
"name": self.room_name,
"unique_id": unique_name,
"device": {
"name": f"{self.room_name} HVAC",
"identifiers":... |
def log_hvac(self, message):
if (self.hvac_log):
self.log_main("HVAC: " + message)
def decstr_to_hexstr(self, input):
result = str(hex(int(input))).replace('0x', '').upper()
if (len(result) < 2):
result = "0" + result # missing leading zero
return result
def hvac_checksum(self, input_command... | This function queries an HVAC system to retrieve specific data (e.g., temperature) by sending a formatted command with a checksum, parsing the response, handling retries on invalid responses, and converting hex values to human-readable results like temperature. It manages communication with the HVAC device, error recov... | def hvac_query(self, input_function, num_retries = 4, retry_counter = 0, response_only = False):
self.log_hvac(f"hvac_query('{input_function}')")
query_command_prefix = '020003100000060130010001'
query_result_variable = 'Var2'
if (not response_only):
# prepare query
query_command = query_com... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def hvac_query(self, input_function, num_retries = 4, retry_counter = 0, response_only = False):
self.log_hvac(f"hvac_query('{input_function}')")
query_command_prefix = '020003100000060130010001'
query_result_variable = 'Var... | This function queries an HVAC system's state (e.g., mode, temperature) via `hvac_query`, handles edge cases like power-off states, formats results for MQTT, and publishes them. It returns the state as a string, logs errors for failed queries, and adjusts values (e.g., lowercasing) for compatibility with Home Assistant.... | def get_state(self, state):
self.log_debug(f"get_state('{state}')")
topic = self.topic_prefix + "/" + state + "/state"
# GET HVAC STATE
# handle HA unit mode on powered off unit (do not query real unit mode when power is off)
if (state == "UNIT_MODE" and self.get_state('POWER_STATE') == 'OFF'):
... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def get_callback_lock(self):
self.log_debug(f"get_callback_lock()")
if (self.callback_lock):
self.log_debug(f"Callback lock is SET (on {self.callback_lock_time} by {self.callback_lock_source})")
else:
self.log_de... | The main task of the code is to retrieve all device states while preventing callback conflicts. It checks for a connection error by verifying each state's value; if any state returns "false", it aborts and returns False. Upon success, it updates an MQTT topic with the current timestamp and returns True. The function us... | def get_all_states(self, kwargs = None):
self.log_debug(f"get_all_states()")
if (self.get_callback_lock()):
self.log_debug("Skipping get_all_states() run")
return False # avoid callback conflicts
self.set_callback_lock(True)
power_state = self.get_state('POWER_STATE')
if (power_state.lo... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def get_callback_lock(self):
self.log_debug(f"get_callback_lock()")
if (self.callback_lock):
self.log_debug(f"Callback lock is SET (on {self.callback_lock_time} by {self.callback_lock_source})")
else:
self.log_de... | The main task of the code is to retrieve indoor and outdoor temperature data while managing a callback lock to prevent concurrent execution. It checks if a lock is active, skips execution if true, otherwise acquires the lock, fetches temperature states, releases the lock, and returns success status. Debug logs track ex... | def get_temps(self, kwargs = None):
self.log_debug(f"get_temps()")
if (self.get_callback_lock()):
self.log_debug("Skipping get_temps() run")
return False # avoid callback conflicts
self.set_callback_lock(True)
self.get_state('TEMP_INDOOR')
self.get_state('TEMP_OUTDOOR')
self.set_call... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def get_callback_lock(self):
self.log_debug(f"get_callback_lock()")
if (self.callback_lock):
self.log_debug(f"Callback lock is SET (on {self.callback_lock_time} by {self.callback_lock_source})")
else:
self.log_de... | The main task of the code is to check if either the "TIMER_OFF" or "TIMER_ON" state is active. It ensures thread safety by using a callback lock to prevent conflicts, returns True if either timer is on, and False otherwise while managing the lock properly. | def get_timers(self, kwargs = None):
self.log_debug(f"get_timers()")
if (self.get_callback_lock()):
self.log_debug("Skipping get_timers() run")
return False # avoid callback conflicts
# off timer is more common
self.set_callback_lock(True)
if (self.get_state('TIMER_OFF') == 'ON'):
... |
def log_hvac(self, message):
if (self.hvac_log):
self.log_main("HVAC: " + message)
def get_state(self, state):
self.log_debug(f"get_state('{state}')")
topic = self.topic_prefix + "/" + state + "/state"
# GET HVAC STATE
# handle HA unit mode on powered off unit (do not query real unit mode when... | This function sends HVAC commands to a device by constructing a control command with a prefix, function code, and value, then verifying the response. It handles retries, validates inputs, and includes special logic for 'SPECIAL_MODE'. The function returns True on success or False if errors occur or retries are exhauste... | def hvac_command(self, input_function, input_value, num_retries = 4, retry_counter = 0, response_only = False):
self.log_hvac(f"hvac_command('{input_function}', '{input_value}')")
original_input_value = input_value
control_command_prefix = '020003100000070130010002'
command_result_variable = 'Var3'
... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def log_set(self, message):
if (self.set_log):
self.log_main("SET: " + message)
def get_all_states(self, kwargs = None):
self.log_debug(f"get_all_states()")
if (self.get_callback_lock()):
self.log_debug("Skippin... | The main task of the code is to handle a "refresh request" for system states. When the payload value is "-", it triggers a states refresh by calling `get_all_states()`, logging success or failure. If the payload is not "-", it logs that the refresh was omitted. The function debugs inputs and reports refresh status via ... | def refresh_request(self, event_name, data, kwargs):
value = data['payload']
self.log_debug(f"refresh_request('{value}')")
if (value == "-"):
self.log_set("States refresh requested...")
if (self.get_all_states()):
self.log_main("States refresh done")
else:
self.log_main("ER... |
def normalize_string(self, input_string):
result = self.remove_accents(input_string)
result = result.lower()
result = result.replace(" ", "_")
return result
def log_main(self, message):
self.log(message)
topic = self.topic_prefix + "/log_message"
self.mqtt_publish(topic, message, qos=1, name... | The main task of the code is to initialize a Toshiba HVAC control system by configuring logging, MQTT topics, and device parameters, then scheduling periodic state polling to monitor or control the HVAC device. It sets up configuration variables, initializes discovery and listeners, reads initial device states, and sch... | def initialize(self):
self.log("=== TOSHIBA HVAC CONTROL ===")
# config variables
self.set_log = self.args['set_log']
self.debug_log = self.args['debug_log']
self.hvac_log = self.args['hvac_log']
self.tasmota_log = self.args['tasmota_log']
self.tasmota_host = self.args['tasmota_host']
se... |
def log_debug(self, message):
if (self.debug_log):
self.log_main(message)
def get_state(self, state):
self.log_debug(f"get_state('{state}')")
topic = self.topic_prefix + "/" + state + "/state"
# GET HVAC STATE
# handle HA unit mode on powered off unit (do not query real unit mode when power is... | This function sets a device state via MQTT, handling interactions between UNIT_MODE and POWER_STATE. It adjusts power state when UNIT_MODE changes, converts numeric values, executes HVAC commands, verifies state updates, and logs results. It ensures correct state synchronization and handles timers affecting power state... | def set_state(self, state, value):
self.log_debug(f"set_state('{state}', '{value}')")
topic = self.topic_prefix + "/" + state + "/state" # this MQTT topic
# UNIT_MODE handling
if (state == "UNIT_MODE"):
power_state = self.get_state('POWER_STATE')
if (value == "off"):
# HA setting UNI... |
def get_month_due(actual_amount_due):
return total_due * (
(interest_rate_per_month * get_month_rate_installment()) / (get_month_rate_installment() - 1)) \
+ get_fee_insurance_cost(actual_amount_due)
def get_month_interest_due(actual_amount_due):
return actual_amount_due *... | The function calculates monthly payment details for a loan or financial plan, incorporating extraordinary payments, updating due dates, tracking principal and interest dues, insurance fees, and detecting inflection points where principal exceeds interest. It structures and returns these calculations in a Due object whi... | def get_due(actual_amount_due, principal_payment=0):
writer.write_line(f'----- month plan {result.total_months} [{state.due_date}] ------')
principal_fixed_payment = principal_payment
if state.due_date.isoformat() in principal_dict:
extraordinary_payment = principal_dict[state.due_da... |
def __poll_events(self):
# Did the user click the window close button?
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
# Clear the screen if the user clicks right button
if pygame.mouse.get_pressed()[2]:
... | The code defines a `render` method that runs a game loop while `self.running` is True. It continuously polls for events, updates game state, and draws frames. Upon exiting the loop, it calls `pygame.quit()` to terminate the Pygame instance. The primary task is to manage the game's main loop for event handling, state up... | def render(self):
while(self.running):
self.__poll_events()
self.__update()
self.__draw()
# Done! Time to quit.
pygame.quit() |
def welcome(s):
if s:
s.display()
def buy_option():
print("1) Buy a large pizza:")
print("2) Buy a large pasta:")
c=input("Please choose option: ")
if c=='1':
buy_pizza()
elif c=='2':
buy_pasta()
else:
buy_option() | The main task of the code is to manage a purchase process where users can buy pizzas and pastas, accumulating their prices into `pizza_price` and `pasta_price` by iterating through global lists. It prints item details, updates totals, and recursively restarts the purchase loop if the user chooses to continue. The funct... | def main(pizza_price,pasta_price):
global pizza_list ,pasta_list
pizza_list=[]
pasta_list=[]
sess = Session()
welcome(sess)
buy_option()
print(pizza_price,pasta_price)
for pasta in pasta_list:
pasta_price += pasta.price
print(pasta.item_name ,pasta.quantity,pasta.price)
for pizza in pizza_list:
pizza... |
def get_growth_rates_df(dataframe: pd.DataFrame) -> pd.DataFrame:
"""
:param df: the original data frame, with missing values
:return: initial dataset growth rates (nan: infinite or unavailable)
"""
growth_rates = dataframe.pct_change(fill_method=None)
# --- change inf values to na (will be drop... | The main task of the code is to impute missing values in a dataframe by leveraging correlations between variables and growth rates. It calculates growth rates and correlations, applies a user-defined activation function to weight correlations, then fills missing data using these weighted correlations. The result is a d... | def impute_df_with_correlations(
dataframe: pd.DataFrame, corr_activation_f: Callable[[float], float]
) -> pd.DataFrame:
"""
:param dataframe: the original data frame, with missing values
:param corr_activation_f: calculates weights from correlations
:return: the original dataframe, imputed using co... |
def preprocess_image_test(img_name, resolution=480):
img = Image.open(img_name)
tfms = transforms.Compose(
[
transforms.ToTensor(),
transforms.Resize((resolution, resolution)),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
... | The function reranks a list of image similarity scores using spatial feature matching. It loads a pre-trained neural network model to extract feature maps from images, computes feature similarities between a target image and others, then reorders the original similarity scores based on these feature-level comparisons. ... | def rerank_spatial(uid, sims, uid2path, similarities=False):
model = ReplicaNet('resnext-101', 'cpu')
replica_dir = '/mnt/project_replica/datasets/cini/'
A = preprocess_image_test(replica_dir + catch(uid, uid2path), 320)
pool_A = model.predict_non_pooled(A)
pool_A = np.moveaxis(pool_A.squeeze(0).cpu... |
def sanity_check():
argParser = argparse.ArgumentParser()
argParser.add_argument("-c","--conf", required=True, help="Path to json configuration file")
argParser.add_argument("-f","--fps", required=False, help="Overwrite the video capture framerate")
argParser.add_argument("-v","--verbose",required=False... | The code initializes a PiCamera for motion detection or streaming, connects to Dropbox if enabled, and starts a Flask server for streaming when motion detection is disabled. It handles configuration checks, error logging, and gracefully exits on user interruption. | def main():
config = sanity_check()
utils.print_title("SPiCam")
client = None
if config["dbx_enabled"]:
try:
client = dropbox.Dropbox(config["dbx_access_token"])
sw_print("Dropbox client connected","INFO",config)
except Exception as e:
sw_print(f"Dropb... |
def reorder_method_CR(data_BxF):
res = reorder_by_MBTree(data_BxF, get_method_COS_REAL_MBTree_idxs_N_ck2idxs, idxs=None)
return res
def reorder_method_CV(data_BxF):
res = reorder_by_MBTree(data_BxF, get_method_COS_VIRT_MBTree_idxs_N_ck2idxs, idxs=None)
return res
def reorder_method_RAND(data_BxF):
r... | The function combines rankings from three methods (CR, CV, RAND) by summing their individual ranks for each index, then sorts indices based on the aggregated rank scores, returning the reordered indices list. | def reorder_method_CR_CV_RAND(data_BxF):
idxs_CR = reorder_method_CR(data_BxF)
idxs_CV = reorder_method_CV(data_BxF)
idxs_RAND = reorder_method_RAND(data_BxF)
ridxs = np.arange(len(data_BxF)).tolist()
ridx2rank = {ridx: 0 for ridx in ridxs}
for idxs_M in [idxs_CV, idxs_CR, idxs_RAND]:
... |
def reorder_method_CV(data_BxF):
res = reorder_by_MBTree(data_BxF, get_method_COS_VIRT_MBTree_idxs_N_ck2idxs, idxs=None)
return res
def reorder_method_EV(data_BxF):
res = reorder_by_MBTree(data_BxF, get_method_EUC_VIRT_MBTree_idxs_N_ck2idxs, idxs=None)
return res
def reorder_method_RAND(data_BxF):
r... | The code combines rankings from three reordering methods (CV, EV, RAND) by summing their individual ranks for each index, then sorts indices based on the aggregated rank to produce a combined reordered list. | def reorder_method_CV_EV_RAND(data_BxF):
idxs_CV = reorder_method_CV(data_BxF)
idxs_EV = reorder_method_EV(data_BxF)
idxs_RAND = reorder_method_RAND(data_BxF)
ridxs = np.arange(len(data_BxF)).tolist()
ridx2rank = {ridx: 0 for ridx in ridxs}
for idxs_M in [idxs_CV, idxs_EV, idxs_RAND]:
... |
def boss_fight():
global T,I
global player_score
health = 100
n = random.randint(1, 10)
if n % 2 == 0:
boss = "Minotaur"
else:
boss = "Goblin King"
if boss == "Minotaur":
boss_health = 200
boss_damage = 40
boss_loss = 40
else:
boss_health =... | The function `player_movement` handles player navigation in a grid-based game, updating coordinates based on input directions (Up, Down, Left, Right) while checking for walls at specific positions. It triggers a boss fight at coordinates (2,5) or (5,2), displays messages for obstacles, and allows actions like checking ... | def player_movement(player_input):
global map_row
global map_column
global coordinates
global T,I
coordinates = map_row, map_column
if player_input == "Up":
if coordinates not in [(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 5), (5, 2)]:
map_row = map_row - 1
elif coor... |
def accept_choice(lst_of_choices):
choice = ""
while choice not in lst_of_choices:
print("Select one of the following:")
for count, option in enumerate(lst_of_choices):
print(f"{count + 1}:{option}")
count = len(lst_of_choices)
while True:
try:
... | The main task of the code is to allow a player to choose between exploring a room for random gold coins or moving in a game. If they choose "Yes," they receive a random amount of gold coins added to their total. If "No," they select from movement or status options. Invalid inputs prompt retries, ensuring valid choices ... | def room():
import random
global gold_coins
player_input2 = ["Yes", "No"]
input2 = accept_choice(player_input2)
if input2 == "Yes":
t = random.randrange(0, 201)
print(f"You have found a sack containing {t} gold coins!")
gold_coins = gold_coins ... |
def accept_choice(lst_of_choices):
choice = ""
global T,I, INPUT
while choice not in lst_of_choices:
T.insert(END,"Select one of the following:")
for count, option in enumerate(lst_of_choices):
T.insert(END,(f"{count + 1}:{option}"))
count = len(lst_of_choices)
wh... | The function handles a game scenario where the player can choose to collect random gold coins (0-200) or move. If "Yes", coins are added to the global count and displayed. If "No", movement options are presented. It updates a text widget with game events and manages player input through predefined choices. | def room():
import random
global gold_coins
global T,I
player_input2 = ["Yes", "No"]
input2 = accept_choice(player_input2)
if input2 == "Yes":
t = random.randrange(0, 201)
T.insert(END,f"You have found a sack containing {t} gold coins!")
... |
def select_column(col):
global _right_bit, _left_bit, _DELAY, _row, _col, _defer
_col=col
if _defer: return
if col < 20:
_left_bit = 1
_right_bit = 0
else:
_left_bit = 0
_right_bit = 1
col = col % 20
col_arr=_byte_to_arr(col)
GPIO.output(_A, _zeroes)
G... | This function renders a string `s` at screen coordinates `(x, y)` using a 5x7 dot matrix font. It calculates column positions, retrieves character patterns from `dotmat5x7`, shifts and combines bits with existing screen data, and writes updated bytes to display the text. The code handles proportional spacing, descender... | def print_at_proportional(x, y, s, _width=None):
for i in range(0, len(s)):
col = int(x / 8)
shift = x % 8
if col >= 40: break
select_column(col)
c = ord(s[i:i+1])-32
dots = dotmat5x7.dots[c]
width = dotmat5x7.widths[c] if _width==0 else _width
for j i... |
def print_at_proportional(x, y, s, _width=None):
for i in range(0, len(s)):
col = int(x / 8)
shift = x % 8
if col >= 40: break
select_column(col)
c = ord(s[i:i+1])-32
dots = dotmat5x7.dots[c]
width = dotmat5x7.widths[c] if _width==0 else _width
for j i... | This function prints a string `s` at position `(x, y)` using a 5x7 dot matrix. If `width` is provided, it uses proportional spacing. Otherwise, it calculates the starting column and row, iterates through each character, selects the corresponding dot pattern, and writes each byte to the appropriate memory address for di... | def print_at(x, y, s, width=None):
if width != None: return print_at_proportional(x, y, s, width)
r = int (y / 8) * 8
c = int (x / 8)
for i in range(0, len(s)):
col = c + i
if col >= 40: break
select_column(col)
dots = dotmat5x7.dots[ord(s[i:i+1])-32]
for j in ran... |
def generate_source_path(self, seq_num, episode_num, flow_type):
gen_path = self._tree["basic_path"] + self._slash
gen_path += self._tree["video_list"][seq_num]["av_number"] + self._slash
gen_path += str(self._tree["video_list"][seq_num]["episode_offset"] + episode_num) + self._slash
gen... | The main task of the code is to process media files by renaming .m4s audio/video files to .mp3/.mp4 formats, validate their existence, and combine them into a final MP4 file using moviepy. It generates output paths, checks for required files, and exports the merged video with specified audio to a designated location wh... | def handle_m4(self, seq_num, episode_num, flow_type):
filepath = self.generate_source_path(seq_num, episode_num, flow_type)
stg_log(f"m4 focusing on {filepath}")
# from moviepy import *
default_audio_path = filepath + self._slash + "audio.m4s"
useable_audio_path = filepath + self... |
def generate_source_path(self, seq_num, episode_num, flow_type):
gen_path = self._tree["basic_path"] + self._slash
gen_path += self._tree["video_list"][seq_num]["av_number"] + self._slash
gen_path += str(self._tree["video_list"][seq_num]["episode_offset"] + episode_num) + self._slash
gen... | The code processes FLV files by renaming .blv files to .flv, converting them to MP4 using ffmpeg, and concatenating sequential clips into a final video. It validates file sequences, handles conversions, and exports the result as a unified MP4 file. | def handle_flv(self, seq_num, episode_num, flow_type):
from operator import itemgetter
filepath = self.generate_source_path(seq_num, episode_num, flow_type)
stg_log(f"flv focusing on {filepath}")
default_video_path = ""
useable_video_path = ""
export_video_path = ""
... |
def stg_log(msg = "test log", level="info", filename = "./vc.log", do_print = 1):
"""
msg: info message to be printed
level: info or warning or error
"""
from datetime import datetime
std_log_msg = f"vc: {datetime.now().isoformat(timespec='seconds')}: [{level}]: {msg}"
if (do_print):
... | This function processes all video episodes by iterating through video and episode indices, constructing file paths, detecting flow types, identifying video formats (FLV/M4), applying specific handling methods, and moving configuration files. It logs progress and warnings for invalid paths or formats. | def deal_all(self):
stg_log(f"start to deal with all...")
for video_index in range(0, len(self._tree["video_list"])):
for epi_index in range(
self._tree["video_list"][video_index]["episode_offset"] + 1,
self._tree["video_list"][video_index]["episode_offset"] +... |
def _normalize(self):
if "projects" not in self.values:
raise ValueError("No project list defined")
projects = self.values["projects"]
if type(projects) != list:
raise ValueError("projects must be a list")
if len(projects) < 1:
raise ValueError("at le... | The code generates and cleans configuration components (containers, cirrus, gitlab) based on their enabled status in `self.values`, using a dryrun flag to simulate actions without changes. It normalizes input first, then processes each enabled component, raising a ManifestError on failures. | def generate(self, dryrun=False):
try:
self._normalize()
if self.values["containers"]["enabled"]:
generated = self._generate_containers(dryrun)
self._clean_containers(generated, dryrun)
if self.values["cirrus"]["enabled"]:
gen... |
def convert_mentions_to_conll(json_file):
""" Convert the mentions from Redcoat (which are in JSON format) to
CONLL-format, i.e. single-class Named Entity Recognition.
Args:
json_file (string): The filename of the json file.
Returns:
list: output_data: The output data
dict: label_counts: A dicti... | The function processes training, development, and test datasets by converting mentions to CoNLL format, shuffling data, saving processed files to an output folder, and printing label distributions. It iterates over each dataset, applies conversion, randomizes order, stores results, and outputs statistics, with an optio... | def build_data(train_filename, dev_filename, test_filename, output_folder):
filenames = {
"train": train_filename,
"dev": dev_filename,
"test": test_filename
}
# Run the script on each train, dev and test dataset.
for dataset_name in ['train', 'dev', 'test']:
json_file = filenames[dataset_name]
print(... |
def sync_setup():
global courses
courses = []
console.print(Panel("You have not yet defined the courses from which materials should be downloaded. Time to add the first one!"))
add_course()
def modify_courses():
global courses
console.print(Panel("[bold]Would you like to add or remove a course?[... | The main task of the code is to load course data from "courses.json", set up a download directory, and iterate through courses to download materials using `get_course()`. If `go_to_download` is "false", it presents a menu for modifying courses or exiting. It ensures the download folder is cleaned and recreated before p... | def main(go_to_download = "true"):
global driver, courses
if os.path.isfile("courses.json"):
with open('courses.json') as json_file:
courses = json.load(json_file)
else:
sync_setup()
with open('courses.json') as json_file:
courses = json.load(json_file)
... |
def _experimental_feature_selection(X: list[np.ndarray], d: int, no_samples: int):
"""(Experimental) feature selection heuristic"""
# Sample random data points
sampled_points = []
for data_class in X:
np.random.seed(42)
sampled_indices = np.random.choice(data_class.shape[1], size=no_samples, replace=Fal... | The code fits a tropical polynomial model for classification by transforming input data into a tropical subspace, selecting monomials via simplex lattice or heuristic, computing the model's apex (decision boundary), and determining sector assignments based on data distribution. It handles log-linear dequantization, fea... | def fit(self, data_classes: list[np.ndarray], poly_degree: int = 1, native_tropical_data: bool = False, log_linear_beta: bool = None, feature_selection: int = None) -> None:
"""Fit the model according to the given training data.
data_classes: list of classes (2D NumPy arrays whose columns are the data points)
... |
def create_connection(database_file):
connection = None
try:
connection = sqlite3.connect(database_file)
connection.row_factory = dict_factory
except Error as e:
print(e)
return connection
def get_training(connection, training_id):
sql = '''
SELECT
cns.I... | The code retrieves training data from a database using the provided training ID, iterates through each combination in the training set, and processes each combination using the `speak_combination` function. The main task is to train a model or system by handling combinations from a database, likely for speech generatio... | def train(training_id):
connection = create_connection(os.path.join(DB_FOLDER, DB_FILE))
with connection:
training = get_training(connection, training_id)
for combination in training:
#combination["__Generate"] = True
speak_combination(combination) |
def new_game(self):
self.lives = 3
self.score = 0
self.gameOver = False
self.level = 0
self.gameDone = False
self.restart = False
self.next_level()
def event_listener(self):
ev = pg.event.poll()
if ev.type == pg.QUIT:
self.gameDone = ... | The main task of the code is to run a game loop that initializes the game, processes events, updates game state, renders graphics, maintains a target frame rate, tracks FPS, and returns the final score once the game ends. | def main_loop(self):
self.new_game()
while not self.gameDone:
self.event_listener()
self.update(self.dt)
self.draw()
self.clock.tick(DEFAULT_FPS)
self.fps = self.clock.get_fps()
self.destroy_game()
return self.score |
def _take_action(self, position):
if position != self._position:
self._trade(position)
def _take_action_order_limit(self):
if len(self._limit_orders) > 0:
ticker = self._get_ticker()
for position, params in self._limit_orders.items():
if position != se... | The code defines a `step` method in an RL agent that executes an action (position change), updates portfolio metrics (value, interest, distribution), tracks historical data, checks termination conditions (portfolio value <=0, episode duration), calculates rewards, and returns observations, reward, and episode status fo... | def step(self, position_index = None):
if position_index is not None: self._take_action(self.positions[position_index])
self._idx += 1
self._step += 1
self._take_action_order_limit()
price = self._get_price()
self._portfolio.update_interest(borrow_interest_rate= self.bor... |
def load_session(self):
if os.path.isfile(self.session_path):
with open(self.session_path, 'r') as f:
pickled = f.read()
return pickle.loads(codecs.decode(pickled.encode(), "base64"))
return None
def check(self):
try:
r = self.post(self.url... | The main task of the code is to attempt to log in by either reusing a valid existing session or sending login credentials via a POST request. It first checks if a previously loaded session is valid; if so, it returns True. If not, it submits the login data and verifies the session's validity again before returning the ... | def log_in(self):
old_session = self.load_session()
if not old_session is None:
self.session = old_session
if self.check():
return True
self.post(self.url, data = {'team' : self.login, 'password' : self.password, 'op' : 'login'})
return self.check(... |
def log_in(self):
old_session = self.load_session()
if not old_session is None:
self.session = old_session
if self.check():
return True
self.post(self.url, data = {'team' : self.login, 'password' : self.password, 'op' : 'login'})
return self.check(... | This function submits a coding task solution to a specific contest on a programming competition platform. It logs in, selects the contest, constructs a file path, and uploads the solution file with the given task ID and language code (6) to the submission endpoint, returning the server's response text. | def submit_task_bp(self, contest_id, task, path):
self.log_in()
self.change_contest(contest_id)
path = self.path + '/' + contest_id + '/' + path
url = 'https://acm.math.spbu.ru/tsweb/submit'
with open(path, 'rb') as file:
r = self.post(url, data = {'prob' : task, 'la... |
def exists_contest(self, contest_id):
return os.path.isdir(self.path + '/' + contest_id)
def change_contest(self, contest_id):
self.post(self.url, data = {'newcontestid' : contest_id, 'op' : 'changecontest'})
def get_problems(self, relogin = False):
if relogin: self.log_in()
res = self.p... | The main task of the code is to add a new contest by creating a directory for it and generating individual `.cpp` files for each problem in the contest. It checks if the contest already exists, creates the directory, writes template code into each problem file, and outputs the number of problems added. | def add_contest(self, contest_id):
if self.exists_contest(contest_id):
return
self.change_contest(contest_id)
problems = self.get_problems()
pth = self.path + '/' + contest_id + '/'
os.mkdir(pth[:-1])
for problem in problems:
with open(pt... |
def all_contests(self):
self.log_in()
res = self.post('https://acm.math.spbu.ru/tsweb/contests?mask=-1')
data = []
s = 'index?op=changecontest&newcontestid='
for i in res.text.split('\n'):
if s in i:
try:
mem = i.split('\"')[1]
... | The function `update_contests` checks for contests not already present in the system by iterating through a list of contest IDs. For each missing contest, it adds the contest and increments a counter. Finally, it returns a formatted message indicating the number of contests successfully added. | def update_contests(self):
contests = self.all_contests()
count = 0
for contest_id in contests:
if not self.exists_contest(contest_id):
print('Adding contest with id {}'.format(contest_id))
self.add_contest(contest_id)
count += 1
... |
def generate_pop():
return np.random.randint(-10, 10, size = 3)
def avaliation(points):
a = points[0]
b = points[1]
c = points[2]
error_rate = 0
for x, expected in default_values:
result = a * (x*x) + (b*x) + c
error_rate += abs(expected - result)
return error_rate
def cross(pop):
first_point = ... | This code implements a genetic algorithm (GA) to evolve a population over generations. It initializes a population, evaluates individuals, selects the best, applies crossover and mutation to generate new offspring, and iterates through generations to optimize solutions. The process tracks results and returns the final ... | def ga(pop_size, generation):
pop = [ generate_pop() for _ in range(pop_size)]
print("First pop ", pop)
final = []
for x in range(generation):
results = []
validateds = [ avaliation(point) for point in pop ]
index = validateds.index(min(validateds))
results.append(pop[index])
if validateds[i... |
def generate_pop(size):
return np.random.randint(-10, 10, size = size)
def get_zero_value(pop):
results = {}
for i in pop:
result = (i*i) - (3*i) + 4
results[i] = abs(result)
zero = min(results.values())
print("results ", results)
index = list(results.values()).index(zero)
return list(result... | The code implements a genetic algorithm (GA) to evolve a population over multiple generations. It initializes a population, then iteratively applies selection (get_zero_value), crossover (cross_times), and mutation operations to generate new populations. The process repeats for a specified number of generations, storin... | def ga(pop_size, generation, cross, mutations):
pop = generate_pop(pop_size)
print("First pop ", pop)
final = []
for x in range(generation):
results = []
results.append(get_zero_value(pop))
results += cross_times(pop, cross)
results += mutation(pop, mutations)
pop = results
final.a... |
def load_pack_meta(self):
print("Loading Metadata.")
pack_meta_url = "http://dl.stickershop.line.naver.jp/products/0/0/1/{pack_id}/android/productInfo.meta".format(pack_id=self.pack_data.id)
response = requests.get(pack_meta_url)
assert (response.status_code == 200), "Sticker pack not ... | The code initializes a class instance for a sticker pack by validating the provided `pack_id` as an integer, loading metadata, icon, and stickers using the `StickerPack` class, and setting up internal data structures for the pack. | def __init__(self, pack_id):
print("Pack Id: {}".format(pack_id))
assert (isinstance(pack_id, int)), "Pack Id must be a number."
self.pack_data = StickerPack(pack_id)
self.load_pack_meta()
self.load_icon()
self.load_stickers() |
def add_word(self, w):
self.written.append(w)
self.add_line(
", ".join(
[
f"0x{b:02x}"
for b in [
(w >> 24) & 0xFF,
(w >> 16) & 0xFF,
(w >> 8) & 0xFF,
... | This code writes block data with headers, payloads, and CRC checksums into a binary format, then inserts the generated content into a specified section of an existing code file. It processes memory blocks, calculates sizes, generates headers, encodes payloads, computes CRC32 checksums, and replaces the "SWITCH CONFIG" ... | def write(self, code_path, blocks: dict[int, list[Mem]]):
self.add_word(self.device_id)
for block_id, records in blocks.items():
size = 0
for item in records:
if isinstance(item, Mem):
size += len(item.to_bytes())
else:
... |
def space_exist():
return board.count('X') + board.count('O') != 9
def print_board():
x = 1
for i in board:
end2 = ' | '
if x % 3 == 0:
end2 = ' \n'
if i != 1:
end2 += '---------\n'
char = ' '
if i in ('X', 'O'):
char = i... | This code handles a tic-tac-toe game by taking player input, updating the game state with player name and score, and managing game logic. It checks for valid moves, determines win/loss conditions, updates the leaderboard upon a player's win, and displays the game board and results. The function returns the updated lead... | def main_code(leaderboard_obj,gamestate_object):
name=input("Enter your name : ")
gamestate_object['name']=name
gamestate_object['game_name']='tic tac toe'
gamestate_object['duration']='5mins'
print('Player is [%s] and computer is [%s]' % (player, Ai))
result = '%%% Game tied ! %%%'
while space_exist():
p... |
def print_info(self, msg):
print("[%s] \t%s" % (self.server_name,msg))
if self.logger:
self.logger.info(msg)
def accept_new_connection(self, select_key):
# TODO: Implement the above functionality
conn, addr = select_key.fileobj.accept()
conn.setblocking(False)
... | This function monitors IO devices for incoming connections or events. It uses a selector to listen on a specified port, processes ready IO devices by accepting new connections or handling events, and terminates gracefully when requested. The loop ensures the server can be stopped by setting self.request_terminate to Tr... | def check_IO_devices_for_messages(self):
self.print_info("Listening for new connections on port " + str(self.port))
# All calls to select() MUST be inside of this loop. Select is a blocking call, and we need to terminate the
# server in order to test its functionality. We will accomplish this b... |
def print_info(self, msg):
print("[%s] \t%s" % (self.server_name,msg))
if self.logger:
self.logger.info(msg)
def setup_server_socket(self):
self.print_info("Configuring the server socket...")
self.my_sock = socket(AF_INET, SOCK_STREAM)
self.my_sock.bind((self.connect_... | The code's main task is to launch a server by initializing a server socket, connecting to a specified remote server if configured, and then listening for incoming connections or messages via I/O devices. It performs setup, potential remote connection, and starts monitoring for network activity to handle client interact... | def run(self):
self.print_info("Launching server %s..." % self.server_name)
# Set up the server socket that will listen for new connections
self.setup_server_socket()
# If we are supposed to connect to another server on startup, then do so now
if self.connect_to_host and self.c... |
def rollDiceWithStrategy(strategy, scoringEngine, cumulativeGameScore, otherPlayerScores):
"""
Roll Dice with Strategy
Simulates a turn using the specified strategy, scoring engine, and other miscellaneous exogneous variables (cumulativeGameScore,
otherPlayerScores), which may affect strategy decision-... | This function simulates multiple turns of a game using a specified strategy and threshold, tracks scores and rolls per turn, computes statistical metrics, generates histograms, and returns results in JSON format. It evaluates strategy performance by analyzing score distribution, roll counts, and the number of turns nee... | def simulateTurnsWithStrategyAndCalculateStats(strategyName, threshold, scoringEngine, maxNumTurns, saveImages):
"""
Simulate Turns with Strategy and Calculate Stats
Simulates a desired number of turns with the specified strategy and threshold (where relevant).
:param strategyName: The name of ... |
def simulateSinglePlayerGame(strategyName, threshold, scoringEngine):
"""
Simulate Game
Simulates one game of the dice game for a single player with the specified strategy and threshold (if relevant)
:param strategyName: The name of the strategy for the player involved
:param threshold: ... | The function simulates multiple games using a specified strategy and threshold, collecting statistics on turns to win and final scores. It generates histograms and statistical summaries for these metrics, returning a JSON payload with results. Parameters include strategy name, threshold, scoring engine, number of games... | def simulateGames(strategyName, threshold, scoringEngine, numGames, saveImages):
"""
Simulate Games
Simulates the specified number of games for a single player with the specified strategy and threshold (where relevant)
:param strategyName: The name of the strategy for the player involved
:p... |
def _configureLogger(logLevel):
format = '%(message)s'
if logLevel != 'INFO':
format = '%(levelname)s: %(message)s'
logging.basicConfig(format=format, level=logLevel.upper())
def simulateTurnsWithStrategyAndCalculateStats(strategyName, threshold, scoringEngine, maxNumTurns, saveImages):
"""
... | (The main task of the code is to execute simulations based on the specified mode ("simulateTurns" or "simulateGames"), using a given strategy, threshold, and number of simulations. It configures logging, initializes a scoring engine, and runs either turn-based or game-based simulations, returning statistical results or... | def main(args):
_configureLogger(args.logLevel.upper())
random.seed()
threshold = max(int(args.threshold), 0) if args.threshold is not None else None
traditionalScoringEngine = TraditionalScoringEngine()
numSimulations = max(int(args.numSimulations), 0) if args.threshold is not None else 1000
m... |
def revenue_from_tariff(self):
return ((self.production() * self.tariff_rate_total())/100).round(0)
def market_revenue(self):
if self.tariff_duration < self.proj_project_useful_life:
l = np.array([self.forecasted_voe])
for i in range(1, self.proj_project_useful_life):
... | The code calculates total royalties by summing revenue from tariff, market, and federal/state incentives, multiplying by a percentage rate, then rounding to the nearest integer and applying a negative sign, likely representing a cost or deduction. | def royalties(self):
return -(self.om_royalties_pc * (self.revenue_from_tariff() + self.market_revenue() + self.federal_cash_incentive() + self.state_cash_incentive())).round(0) |
def revenue_from_tariff(self):
return ((self.production() * self.tariff_rate_total())/100).round(0)
def market_revenue(self):
if self.tariff_duration < self.proj_project_useful_life:
l = np.array([self.forecasted_voe])
for i in range(1, self.proj_project_useful_life):
... | The method `project_revenue_all` calculates and returns the total projected revenue by summing individual revenue components: tariff revenue, market revenue, interest from reserves, and federal and state cash incentives. | def project_revenue_all(self):
return self.revenue_from_tariff() + self.market_revenue() + self.interest_on_reserves() + self.federal_cash_incentive() + self.state_cash_incentive() |
def fixed_om_expense(self):
l = self.operating_expense_inflation_factor()
return -(l * self.om_fixed_om_expense_yr_one * self.proj_nameplate_capacity).round(0)
def var_om_expense(self):
l = self.operating_expense_inflation_factor()
p = self.production()
return -(l * p * self.om_v... | The code calculates total operating expenses by summing fixed operational expenses, variable operational expenses, insurance, project management costs, property taxes, land lease fees, and royalties. The function aggregates these individual components into a single total value for operational costs. | def total_operating_expenses(self):
return self.fixed_om_expense() \
+ self.var_om_expense() \
+ self.insurance() \
+ self.project_management() \
+ self.property_taxes() \
+ self.land_lease() \
+ self.royalties() |
def is_need_intention(self, *args, **kwargs):
return True
def infer_intention(self, prev_mask, clicks_list):
input_image = self.original_image
if prev_mask is None:
prev_mask = self.prev_prediction
if hasattr(self.int_net, 'with_prev_mask') and self.int_net.with_prev_mask:
... | This function generates a segmentation prediction using click inputs and previous masks in 'cascade' evaluation mode. It infers intention when needed, combines image data, applies transformations, processes through a network, and returns the final prediction after inverse transformations, updating the previous predicti... | def get_prediction(self, clicker, prev_mask=None, step=-1):
clicks_list = clicker.get_clicks()
if step == 0:
need_intention = True
else:
need_intention = self.is_need_intention()
# > Last prediction as previous mask
if self.eval_mode == 'normal':
... |
def reply(url, report_id,api_key):
try:
# url for getting report reply
reply_url=url+'/bulk-report-reply'
headers={'User-Agent':'tns_marker{"tns_id":2040,"type": "user", "name":"jwyang"}'} # FIXME
# construct a dictionary of api key data and report id
reply_data={'api_key... | The function sends a reply to a report using an API, checks the response, and if successful, processes and prints structured feedback from the JSON response. It handles nested feedback data, extracts relevant messages, and formats them with separators for readability. If the reply fails, it indicates whether the report... | def print_reply(url,report_id, api_key):
# sending reply using report id and checking response
print ("Sending reply for the report id "+report_id+" ...")
reply_res=reply(url, report_id, api_key)
reply_res_check=check_response(reply_res)
# if reply is sent
if reply_res_check==True:
print... |
def send_json_report(url,json_file_path,api_key):
try:
json_url=url+'/bulk-report'
headers={'User-Agent':'tns_marker{"tns_id":2040,"type": "user", "name":"jwyang"}'} # FIXME
# read json data from file
json_read=format_to_json(open(json_file_path).read())
# construct a dic... | This function sends a report (TSV or JSON) to a TNS server using an API key, checks the response, retrieves a report ID if successful, and then polls the server periodically to check for a reply using that ID. It prints status updates and handles success/failure scenarios, with a loop that terminates after a set number... | def send_report(url, report, type_of_report,api_key):
# sending report and checking response
print ("Sending "+report+" to the TNS...")
# choose which function to call
if type_of_report=="tsv":
response=send_tsv_report(url,report)
else:
response=send_json_report(url,report,api_key)
... |
def _apply_builtin(builtin_symbol, arity, args):
return builtin_microcode[builtin_symbol](args)
def _lookup(x, e):
res = _lookup_(x, e, 0)
return res[0]
def _extend(xs, vs, e):
vi = iter(vs)
result = {}
for x in xs:
result[x] = next(vi)
return (result, e) | This function executes a function call in a custom interpreter by handling argument spreading, rest parameters, and updating the environment and control stack. It processes built-in or closure functions, validates argument counts, and extends the environment with parameters and arguments for execution. | def cse_microcode_app_i(cmd):
arity = cmd['arity']
args = []
for _ in range(arity):
args.append(S.pop())
sf = S.pop()
if sf['tag'] == 'builtin':
S.append(_apply_builtin(sf['sym'], arity, args))
elif sf['tag'] == 'closure':
global E
if not C or C[0]['tag'] == 'rese... |
def is_string(x):
return type(x) is str
def _reduce(f, iterable, init):
# Reimplement reduce because functools not in Micropython
res = init
for x in iterable:
res = f(res, x)
return res
def _is_closure(x):
# more pythonic would be isinstance(v, Dict),
# but package typing not availa... | Your return
The function `value_to_string` converts various data types (e.g., booleans, null, strings, floats, closures, built-ins) into string representations. It handles special cases: `Undefined`, `True`, `False`, `Null` return fixed strings; strings are quoted with escaped double quotes; closures and built-ins re... | def value_to_string(x):
# Printing not speed-critical, so nested conditionals are fine
if x is Undefined:
return 'undefined'
elif x is True:
return 'true'
elif x is False:
return 'false'
elif x is Null:
return 'null'
elif is_string(x):
# surround character... |
def __ensure_sql_table_presence(self):
self.__db.execute('''
CREATE TABLE IF NOT EXISTS quiz_progresses (
chat_id INTEGER,
completed_steps INTEGER
)
''')
def __get_progress(self, chat_id):
return QuizChatProgress(chat_id=chat_id, db=self.__... | The main task of the code is to greet a user based on their progress. It checks if the user's progress exists: if so, it returns a "welcome again" message with their current state; if not, it initializes progress and returns a standard welcome message with the current state. The function ensures database readiness, ret... | def greet(self, chat_id: int):
self.__ensure_sql_table_presence()
progress = self.__get_progress(chat_id)
current_state_message = self.__current_state_message(progress)
if progress.exists():
return self.__scenario['welcome_again_message'] + '\n\n' + current_state_message
... |
def __ensure_sql_table_presence(self):
self.__db.execute('''
CREATE TABLE IF NOT EXISTS quiz_progresses (
chat_id INTEGER,
completed_steps INTEGER
)
''')
def __get_progress(self, chat_id):
return QuizChatProgress(chat_id=chat_id, db=self.__... | This function handles a step-by-step interaction by checking if a user's message matches the expected answer for the current step. If correct, it advances the progress and provides feedback; if incorrect, it returns an error message. It ensures SQL table existence, retrieves progress, and manages state transitions for ... | def say(self, chat_id: int, message: str):
self.__ensure_sql_table_presence()
progress = self.__get_progress(chat_id)
if not progress.exists():
return self.greet(chat_id)
if self.__is_completed(progress):
return self.__current_state_message(progress)
cu... |
def get_faces(self, img):
face_detector = self.detector
img_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
result = face_detector.detect_faces(img_RGB)
bboxes, fimages = [], []
for face_info in result:
[fx,fy,fw,fh] = face_info['box']
if fw<self.required_shap... | This function uses a KNN classifier to recognize faces in an image by comparing normalized embeddings against a pre-trained model. It processes detected faces, filters predictions based on a threshold, and returns matched labels, confidence scores, and bounding boxes. The function also maintains a history of recent rec... | def recognize_knn(self, db_path, img, threshold, onlyone=True):
clf = load(os.path.join(db_path, 'knn_faces.joblib'))
face_encoder = self.face_encoder
faces_data = self.get_faces(img=img)
#if onlyone is True and len(faces_data)>1:
# return []
boxes = []
preds ... |
def get_log_prior(samples, prior):
"""Return log prior of sampled Gaussians.
Args:
samples: A `Tensor` with shape `[num_samples, :, :]`.
prior: String representing prior distribution.
Returns:
log_prior: A `Tensor` with shape `[num_samples]`, with the log priors
summed across lat... | The main task of the code is to approximate the variational Evidence Lower Bound (ELBO) for a probabilistic model involving document-topic, ideological-topic, and ideal point distributions. It computes log-priors, entropies, and Poisson log-likelihoods of word counts, combines them with task-specific losses (classifica... | def get_elbo(counts,
document_indices,
brand_indices,
brand_weights,
document_distribution,
objective_topic_distribution,
ideological_topic_distribution,
ideal_point_distribution,
num_documents,
batch_si... |
def get_log_prior(samples, prior):
"""Return log prior of sampled Gaussians.
Args:
samples: A `Tensor` with shape `[num_samples, :, :]`.
prior: String representing prior distribution.
Returns:
log_prior: A `Tensor` with shape `[num_samples]`, with the log priors
summed across lat... | The code approximates the variational Lognormal Evidence Lower Bound (ELBO) using Monte Carlo sampling, combining log-priors, entropies, and Poisson likelihoods of word counts. It samples from document, topic, and ideal-point distributions, computes classification loss via cross-entropy with labeled and reversed scores... | def get_elbo(counts,
document_indices,
author_indices,
author_weights,
document_distribution,
objective_topic_distribution,
ideological_topic_distribution,
ideal_point_distribution,
num_documents,
batch_... |
def build_input_pipeline(source_dir,
batch_size,
random_state,
time_slice,
dev_ratio,
counts_transformation="nothing",
test=True):
"""Load data and build iterator for... | The code trains a probabilistic model using variational inference across time slices, optimizing parameters via ELBO with Adam. It processes data from specified directories, evaluates model performance using Spearman correlation for ranking, and saves results. GPU resources are configured, and training includes stages ... | def main(argv):
del argv
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
print("Num GPUs Available: ", len(
tf.config.experimental.list_physical_devices('GPU')))
tf.debugging.set_log_device_placement(True)
config = tf.ConfigProto(allow_soft_placement=True,
log_device_pla... |
def build_input_pipeline(source_dir,
batch_size,
random_state,
time_slice,
dev_ratio,
counts_transformation="nothing",
test=True):
"""Load data and build iterator for... | The main task of the code is to train a probabilistic topic model with adversarial components on time-sliced text data. It initializes distributions for documents, topics, and ideal points, optimizes the ELBO objective using variational inference, and incorporates adversarial training to refine model parameters. The co... | def main(argv):
del argv
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
print("Num GPUs Available: ", len(
tf.config.experimental.list_physical_devices('GPU')))
tf.debugging.set_log_device_placement(True)
config = tf.ConfigProto(allow_soft_placement=True,
log_device_pla... |
def __get_tables_of_schema(self, schema: str) -> Dict[str, Table]:
tables = self.__get_table_meta_data(schema)
return {t.name: self.__map_table(t) for t in tables}
def __get_views_of_schema(self, schema: str) -> Dict[str, View]:
with self.__connection.cursor() as cursor:
query = """
... | The main task of the code is to map schema metadata into a Schema object by retrieving its tables, views, and routines from the database, then constructing and returning a new Schema instance with these components. | def __map_schema(self, meta_data: SchemaMetaData) -> Schema:
tables = self.__get_tables_of_schema(meta_data.name)
views = self.__get_views_of_schema(meta_data.name)
routines = self.__get_routines_of_schema(meta_data.name)
return Schema(meta_data, tables, views, routines) |
def schema_name(schema: Schema) -> str: return schema.meta_data.name
def __check_meta_data_diff(self, asset_type: str, asset_name: str, left: Dict[str, Any], right: Dict[str, Any],
field_exclusions: List[FieldExclusion]):
if left != right:
exclusions = map_excluded_fie... | The main task of the code is to compare two schema objects (left and right) by checking metadata differences and structural discrepancies in tables, views, and routines. It uses exclusion rules for metadata fields and delegates asset-specific comparisons to helper methods like __process_table, __process_view, and __pro... | def __process_schema(self, left: Schema, right: Schema):
asset_name = schema_name(left)
self.__check_meta_data_diff(ASSET_TYPE_SCHEMA, asset_name, left.meta_data.to_dict(), right.meta_data.to_dict(),
self.exclusions.schema_fields)
self.__check_diff_of_assets(... |
def table_name(table: Table) -> str:
return "{} - {}".format(table.meta_data.schema, table.meta_data.name)
def __check_meta_data_diff(self, asset_type: str, asset_name: str, left: Dict[str, Any], right: Dict[str, Any],
field_exclusions: List[FieldExclusion]):
if left != right:... | The main task of the code is to compare two database tables (left and right) by checking differences in their metadata, columns, key column usages, referential constraints, and indices. It uses exclusion lists to ignore specified fields during comparisons, ensuring structural consistency while allowing controlled devia... | def __process_table(self, left: Table, right: Table):
asset_name = table_name(left)
self.__check_meta_data_diff(ASSET_TYPE_TABLE, asset_name, left.meta_data.to_dict(), right.meta_data.to_dict(),
self.exclusions.table_fields)
self.__check_diff_of_leaf_assets(A... |
def routine_name(routine: Routine) -> str:
return "{} - {}".format(routine.meta_data.schema, routine.meta_data.name)
def __check_meta_data_diff(self, asset_type: str, asset_name: str, left: Dict[str, Any], right: Dict[str, Any],
field_exclusions: List[FieldExclusion]):
if left... | The main task of the code is to compare two routines' metadata and parameters, checking for differences while excluding specified fields. It retrieves the routine's asset name, validates metadata consistency between inputs, and compares leaf assets (parameters) against exclusion rules to identify discrepancies. | def __process_routine(self, left: Routine, right: Routine):
asset_name = routine_name(left)
self.__check_meta_data_diff(ASSET_TYPE_ROUTINE, asset_name, left.meta_data.to_dict(), right.meta_data.to_dict(),
self.exclusions.routine_fields)
self.__check_diff_of_l... |
def get_theme(pkg):
settings = get_settings(pkg)
if pkg is SUBLIME_LINTER:
items = settings.get('user', '')
if items != '':
return items.get('gutter_theme', '')
if pkg in (PLAIN_TASKS, PLAIN_NOTES):
return settings.get('color_scheme', '')
def revert_theme(pkg, path):
... | The function `on_done` executes specific commands based on the provided index. If index is 0 or 1, it triggers 'boxy_plain_notes' or 'boxy_plain_tasks' commands. For index 2, it checks the current theme, reverting to a default theme if the current one matches 'boxy'; otherwise, it activates the 'boxy' theme. The task i... | def on_done(self, index):
if index is NO_SELECTION:
return
if index is 0:
self.window.run_command('boxy_plain_notes')
if index is 1:
self.window.run_command('boxy_plain_tasks')
if index is 2:
current = get_theme(SUBLIME_LINTER)
... |
def revert_theme(pkg, path):
if path is '':
get_settings(pkg).erase('color_scheme')
else:
set_theme(pkg, path)
return save_settings(pkg)
def activate_theme(pkg, path):
set_theme(pkg, path)
return save_settings(pkg)
def _quick_list_to_theme(self, index):
return ('Packages/Box... | The function `on_done` handles task selection by reverting to the initial theme if no selection is made (`NO_SELECTION`), otherwise activating a theme based on the selected task index. It uses `revert_theme` and `activate_theme` to manage UI states, ensuring the interface updates correctly according to user input. | def on_done(self, index):
if index is NO_SELECTION:
revert_theme(PLAIN_TASKS, self.initial_theme)
return
activate_theme(PLAIN_TASKS, self._quick_list_to_theme(index)) |
def revert_theme(pkg, path):
if path is '':
get_settings(pkg).erase('color_scheme')
else:
set_theme(pkg, path)
return save_settings(pkg)
def activate_theme(pkg, path):
set_theme(pkg, path)
return save_settings(pkg)
def _quick_list_to_theme(self, index):
return ('Packages/Box... | This method handles theme activation based on user selection. If no selection is made (index is NO_SELECTION), it reverts to the initial theme. Otherwise, it applies a theme derived from the selected index in a quick list, updating the UI accordingly. | def on_done(self, index):
if index is NO_SELECTION:
revert_theme(PLAIN_NOTES, self.initial_theme)
return
activate_theme(PLAIN_NOTES, self._quick_list_to_theme(index)) |
def ReadGeneratorConfig(filename, globalData):
lineNumber = 0
for line in open(filename, 'r'):
lineNumber += 1
line = line.strip()
# Skip empty lines and comment lines
if not line or line[0] == '#': continue
try:
key, value = line.split(':', 1)
ke... | The main task of the code is to generate static HTML content from articles using a configuration file and cache system. It scans articles, validates them, caches data, and outputs HTML files along with index pages for the main site and labels. The `forceGenerate` parameter allows overriding cache behavior to force rege... | def Generate(forceGenerate):
globalData = GlobalData()
ReadGeneratorConfig("generator.conf", globalData)
CheckConfig(globalData)
if forceGenerate:
globalData.config["ForceRefresh"] = True
# TODO: configurable cache file
globalData.SetCache(Cache(SqlBackend("pycache.db")))
ScanArti... |
def get_csv_data(self):
# CSV file & Data modification
with open(self.file_mod_file()) as f_csv:
data = read_csv(f_csv, usecols=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]).tail(2)
# Find the null value present in the row and if present the remove it
if data.i... | The main task of the code is to extract data from a barcode, validate electrical parameters (voltages and frequencies) against specified ranges, compile test results, and store them in a SQLite database. It retrieves PO numbers, part numbers, timestamps, and operator names, then logs measurement statuses and values int... | def data_entry(self):
# Get the PO number from barcode
main_data = self.get_csv_data().to_dict()
po = ('po', main_data["Barcode"][-11:-4]) # PO number from barcode
po = ''.join(po)
print(po)
p_n = main_data["Barcode"].split('#') # Get Part Number from barcode
p... |
def _file_ext(fname):
return os.path.splitext(fname)[1].lower()
def _get_zipfile(self):
assert self._type == 'zip'
if self._zipfile is None:
self._zipfile = zipfile.ZipFile(self._path)
return self._zipfile
def _load_raw_image(self, raw_idx):
fname = self._image_fnames... | This code initializes a dataset by loading image files from a directory, zip archive, or CSV metadata file. It handles resolution normalization, sun azimuth alignment, and exposure multipliers. The dataset processes file paths, validates image formats, and prepares metadata for subsequent use, ensuring compatibility wi... | def __init__(self,
path, # Path to directory or zip or csv.
resolution = None, # Ensure specific resolution, None = highest available, setting a resolution forces resizing (one-time preprocessing)
normalize_azimuth=False,# Rotate the image so that the sun azimuth is 180 de... |
def setup_snapshot_image_grid(training_set, random_seed=0):
rnd = np.random.RandomState(random_seed)
gw = np.clip(7680 // training_set.image_shape[2], 7, 32)
gh = np.clip(4320 // training_set.image_shape[1], 4, 32)
# No labels => show random subset of training samples.
if not training_set.has_label... | This code implements a training loop for a GAN (generator G, discriminator D, and encoder E) to generate images resembling a training dataset. It handles distributed GPU training, data augmentation, EMA smoothing, regularization, and metrics tracking. The loop iteratively updates networks using specified optimizers, ap... | def training_loop(
run_dir = '.', # Output directory.
training_set_kwargs = {}, # Options for training set.
clear_training_set_kwargs = {}, # Options for training set.
data_loader_kwargs = {}, # Options for torch.utils.data.DataLoader.
E_kwargs ... |
def draw_nextcard(np_random):
return int(np_random.choice(deck_nextcard))
def is_bust(hand): # Is this hand a bust?
if sum_hand(hand)>21:
return True
elif sum_hand(hand) < 0:
return True
else:
return False
def sum_hand(hand): # Return current hand total
#if usable_ace(hand)... | This code implements a step function for a Blackjack game environment. It processes the player's action (hit or stick), updates the player's hand, checks for bust conditions, and calculates rewards. If the player sticks, the dealer plays out their hand. The function returns the new observation, reward (based on game ou... | def step(self, action):
assert self.action_space.contains(action)
if action: # hit: add a card to players hand and return
self.player.append(draw_nextcard(self.np_random))
if is_bust(self.player):
done = True
reward = -1
else:
... |
def Y(my_user: User, D: int):
"""
Reward function
:param my_user: User; The agent who receives reward
:param D: int; Agent choice
:return: int; Reward
"""
# U = random noise
U = np.random.binomial(m, 1 / 2) - int(m / 2)
U = int(U / 2)
# gp = group label
gp = int(my_user.tru_... | The code implements BIC sampling for arm selection, balancing exploration-exploitation by recommending arms based on ranked rewards, collecting historical data (psi), and saving results. It iteratively samples agents, adjusts parameters (q_t, E_happen), resamples data, and stores estimated rewards and records in CSV fi... | def sample(k: int, gp: int, c_t):
"""
BIC sampling stage
:param k: int, 5/10 low_D, 50/100 high_D ; Sampling size
:param gp: int; Cluster label
:param c_t: float; Parameter in BIC sampling
:return: None
"""
gp_cluster_id = cluster_list[gp]
gp_p_i = p_i[gp]
gp_theta = theta[gp]
... |
def Y(my_user: User, D: int):
"""
Reward function
:param my_user: User; The agent who receives reward
:param D: int; Agent choice
:return: int; Reward
"""
# U = random noise
U = np.random.binomial(m, 1 / 2) - int(m / 2)
U = int(U / 2)
# gp = group label
gp = int(my_user.tru_... | The code implements the BIC racing algorithm to identify the optimal arm within a cluster by iteratively eliminating suboptimal arms. It uses DML estimators, historical data sampling, and statistical trimming (via `trim_c`) to compare arms, retaining only those close to the maximum estimated value (`theta_hat_star`). T... | def race(k: int, gp: int, tau):
"""
BIC racing stage
:param k: int; Racing size (= sampling size)
:param gp: int; Cluster label
:param tau: float; Paramter in BIC racing
:return: None
"""
# initialize
gp_cluster_id = cluster_list[gp]
rang = len(gp_cluster_id)
gp_p_i = p_i[gp]... |
def update_text_label(self, word):
self._word = word
self._text_label["text"] = self._word
def set_timer(self, count):
# Update the timer in the game
self._clock["text"] = str(int((count / (1000 * 60)) % 60)) + ":" + str(int((count / 1000) % 60))
if count == 30000:
... | The main task of the code is to initialize and start a game by setting the game state to active, hiding the start button, clearing text labels, setting a 3-minute timer, and updating button text to reflect the game's start. | def start_game(self):
self.game_is_on = True
self._start_button.pack_forget()
self.update_text_label("")
self.set_timer(180000)
self.set_button_text() |
def fill_form(self, web_id, client_input):
"""
Fills a form field on the web page with the provided input.
Args:
web_id (str): The ID of the form field to fill.
client_input (str): The input to fill the form field with.
"""
try:
# Locate the i... | The code automates scraping flight data from a specified URL by navigating to the site, filling a search form with departure/arrival details and dates, submitting the form, extracting flight data from the resulting page, and exporting it to a CSV file named based on the locations. It returns the CSV filename for use in... | def run(self):
"""
Runs the entire process of scraping flight data from the specified URL and exporting it to a CSV file.
Returns:
str: The name of the generated CSV file. (for flask in app.py)
"""
# Navigate to the URL
url = "https://www.aa.com/homePage... |
def drivers_prices_from_csv(driver_prices_csv: Path) -> list[DriverPriceModel]:
with driver_prices_csv.open() as f:
reader = csv.DictReader(f)
return [DriverPriceModel.model_validate(row) for row in reader]
def constructors_prices_from_csv(constructor_prices_csv: Path) -> list[ConstructorPriceModel]... | The main task of the code is to calculate and output teams' maximum scores based on driver/constructor prices, race positions, special points, and ignore lists. It processes input CSV files, computes scores via a `calculations` function, and writes results—including team details and input data—to a specified output fil... | def main(
chips_path: Path,
finishing_positions_qualifying_path: Path,
finishing_positions_race_path: Path,
ignore_constructors_path: Path,
ignore_drivers_path: Path,
price_constructors_path: Path,
price_drivers_path: Path,
special_points_path: Path,
output_file_path: Path,
curre... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.