dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def peer_manipulate(self, peer, method):
'''
Add or remove peers.
'''
if (method == 'remove' and peer not in self.connections):
self.cli.log(f'Invalid command: not connected to {peer}')
# The peer coming in could be a temporary peer to attempt look up the real Peer
... | This function handles CLI commands for managing peers and tracking data. It processes 'help', 'exit', 'peer add/remove', and 'track list/get' commands, validating inputs, logging responses, and executing actions like adding peers, listing tracks, or downloading tracks based on user input. | def handle_commands(self, command):
if (command in ['help', '?', '/?', 'h']):
self.cli.log('\nAvailable commands:')
self.cli.log(' peer add HOST:PORT')
self.cli.log(' peer remove HOST:PORT')
self.cli.log(' track list')
self.cli.log(' track get S... |
def send(self, data, is_str=True, is_json=False):
'''
Send data.
'''
if (is_json):
data = json.dumps(data)
if (is_str or is_json):
data = data.encode()
try:
self.tcp_conn.sendall(data)
self.tcp_conn.sendall('\r\n\r\n'.enc... | The main task of the code is to check if a peer is still connected by sending a 'ping' message and verifying a 'pong' response. If no response is received within 1 second, it logs the disconnection, updates the connection status to False, and returns the updated status. | def ping(self):
'''
Check if the peer is alive.
'''
if (not self.connected):
return False
self.send('ping')
resp = self.recv(timeout=1)
self.connected = (resp == 'pong')
if (not self.connected):
self.cli.log(f'Connection to {sel... |
def __ensure_cf(self, retry: int = 3) -> None:
'''
Ensure Cloudflare cookies are set\n
:param retry: Number of retries
'''
self.logger.debug('Opening new tab...')
original_window = self.driver.current_window_handle
self.driver.switch_to.new_window('tab')
... | The code sends a message to ChatGPT using Selenium, simulates user input, handles streaming responses, extracts the generated content, checks for errors, and returns a dictionary containing the response text and conversation ID. It ensures cookies are set, waits for elements, and manages session state. | def send_message(self, message: str, stream: bool = False) -> dict:
'''
Send a message to ChatGPT\n
:param message: Message to send
:return: Dictionary with keys `message` and `conversation_id`
'''
self.logger.debug('Ensuring Cloudflare cookies...')
self.__ensure_... |
def get_neighbours_index(L):
"""
:return: (dict) containing as keys the index of the site on the lattice and as values a list containing the indexes
of its neighbours
"""
neighbours_dict = {} # Index of site -> indexes of neighbours of that site (key -> value)
N = L**2
for i in range(N):
... | The code simulates a lattice model (e.g., Ising model) using the Metropolis algorithm, varying parameters like lattice size (L_list) and coupling constants (l_list). It initializes random spin configurations, performs Monte Carlo sweeps to calculate system action, discards initial thermalization data, and writes final ... | def simulate():
L_list = [6, 8, 10, 12, 14]
m_squared = -4
l_list = [6.975, 6.008, 5.550, 5.276, 5.113]
N_list = np.array(L_list)**2
n_sweep = list([i for i in range(nsweeps)])
with open('phi4.txt', 'w') as file:
for i in range(len(L_list)):
N = N_list[i]
l = ... |
def flatten(self, page_pic, corners, imgsize=(1000,1000)):
'''
page_pic is the original full-page image taken by the user
corners is a 2D nparray, lists pixel coordinates of the crossgrid's 4 corners
First row is top left corner, proceed counterclockwise
imgsize is the side ... | This code processes a crossword puzzle image by loading and converting it to grayscale, detecting grid corners, flattening the grid, identifying black squares, generating a clue grid, extracting small boxes, performing OCR on across/down clues, and initializing a charge grid for puzzle solving. | def __init__(self, page_path, corner_path):
self.page_pic = cv2.cvtColor(cv2.imread(page_path), cv2.COLOR_BGR2GRAY)
#self.corners = np.array([[240,2120], [1840,2115], [1890,3800], [150,3830]])
self.corners = np.loadtxt(corner_path, delimiter=',', dtype=int)
self.flatgrid = self.flatten(s... |
def zoom(self, target, amount=1.0):
# Given a target area rect, ensure the area is not too small.
area = self.locate(target)
if area[3] == area[1]:
area[3] += 1
high = float(area[3]-area[1])
wide = float(area[2]-area[0])
ratio = wide / high
if high < s... | The main task of the code is to smoothly transition a camera's view from its current area to a target area using eased motion along a direct path. It calculates intermediate frames via Bezier curves, avoiding abrupt linear interpolation, and animates the movement by updating the camera position step-by-step while rende... | def pan(self, svg, target, ts=0, margin=1.0):
# Shoot the intervening frames from the current camera area toward
# a target camera area. The camera speed eases into the motion and
# eases to a stop, rather than lurching with a simple linear
# interpolation, but the motion is in a direct... |
def __pre_process(self):
# Obtaining all setting files.
self.__settings = [name for name in os.listdir(self.__folder_path)
if os.path.isfile('/'.join([self.__folder_path, name]))]
def _backup_preferences(self, setting_file, msg_callback):
with open(os.path.join(self.__... | This method performs backup or restore of application preferences based on the 'is_backup' flag. It iterates through settings (excluding ignored ones), uses msg_callback to log progress, and calls either _backup_preferences or _restore_preferences for each setting. After processing all settings, it notifies via msg_cal... | def backup_restore_process(self, msg_callback, is_backup=True):
self.__pre_process()
self.__is_backup = is_backup
self.__msg_callback = msg_callback
# Parsing each of setting files' content.
for stg in list(set(self.__settings) - set(self.__ignore_settings)):
msg_cal... |
def read_calib_file(self, index):
""" Read in a calibration file and parse into a dictionary.
Ref: https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
"""
data = {}
calib_filename = os.path.join(self.calib_dir, "%06d.txt" % (index))
# print("calib_filename"... | This code initializes a dataset loader for a specific split (e.g., training/validation) and index by constructing paths to calibration, image, LiDAR, and label directories. It loads corresponding data files (calibration, image, point cloud, and labels) and generates ground truth labels. The image dimensions are extract... | def __init__(self,dataset_dir,split,index) -> None:
self.calib_dir = os.path.join(dataset_dir,split,"calib")
self.image_dir = os.path.join(dataset_dir,split,"image_2")
self.lidar_dir = os.path.join(dataset_dir,split,"velodyne")
self.label_dir = os.path.join(dataset_dir,split,"label_2")
... |
def check_image_processing_params(form_dict):
"""
Return parameter values related to image processing based on
website input
"""
image_type = form_dict["ImageType"]
hole_fill_area_str = form_dict["HoleFillArea"]
cell_intensity_num = int(form_dict["CellIntensityNum"])
if hole_fill_area_s... | The main task of the code is to handle image upload and analysis for colony recognition. It processes user-submitted image files, applies specified analysis parameters, generates colony detection results, uploads processed data to cloud storage, and renders a visualization template with analysis outcomes, including col... | def upload_image_cr():
# set default values
save_extra_info=True
if request.method != "POST":
return render_template("public/colony_recognition.html")
result = request.form
site_output_dict = dict(result.items())
# get image analysis parameters
image_type, hole_fill_area, cleanup... |
def check_image_processing_params(form_dict):
"""
Return parameter values related to image processing based on
website input
"""
image_type = form_dict["ImageType"]
hole_fill_area_str = form_dict["HoleFillArea"]
cell_intensity_num = int(form_dict["CellIntensityNum"])
if hole_fill_area_s... | The main task of the code is to handle image upload and growth rate analysis. It processes form data, validates parameters, uploads and renames image files, executes analysis using predefined functions, uploads results to Google Cloud, and renders a result template with analysis outcomes, colony counts, and processing ... | def upload_image_gr():
# set default values
timepoint_spacing = 3600
growth_window_timepoints = 0
user_email = ""
review_permission = False
if request.method != "POST":
return render_template("public/growth_rate.html")
result = request.form
site_output_dict = dict(result.... |
def filter_reload_data(dataset_name, table_name):
trips_data = load_data_from_gbq(dataset_name, table_name)
new_schema_data = get_destination_schema()
load_data_to_gbq(trips_data, utils.get_table_full_name(dataset_name, table_name), new_schema_data)
def get_popular_hexs(full_table_name, field_name, report_... | The code performs ETL tasks by filtering and reloading data, retrieving popular pickup/dropoff locations and routes, combining results, defining a BigQuery schema, and loading aggregated data into a destination table for reporting. | def start_etl():
filter_reload_data(ds_id, destination_table_name)
table_full_name = utils.get_table_full_name(ds_id, destination_table_name)
popular_pickups = get_popular_hexs(table_full_name, 'pickup_hex', 'pickup',popular_results_count)
popular_dropoff = get_popular_hexs(table_full_name, 'dropoff_h... |
def rent_game(username):
print ("\nRENT A GAME")
while True:
try:
available_games()
game = input ("\nEnter the game you want to rent (Press ENTER to go back): ")
if not game:
return
elif game not in game_library:
print ("\nG... | This function displays an admin menu with options for managing user actions like renting/returning games, top-ups, inventory checks, and points. It loops until the user selects "Exit," calling corresponding functions based on their choice. | def admin_menu(username):
print("\nADMIN MENU")
while True:
print("\nPlease select an option:")
print("1. Rent a Game")
print("2. Return a Game")
print("3. Top Up")
print("4. Game Inventory")
print("5. Redeem Free Game")
print("6. Check Points")
p... |
def algo_fix(self):
"""Solve BIP under median scenario and evaluate the obtained solution under its worst-case scenario
"""
# Generate median scenario
c = {j: float(self.c_upp[j] + self.c_low[j])/2 for j in self.c_upp}
# Solve BIP under median scenario
res = self.solve_bi... | The main task of the code is to solve a problem using a specified algorithm (e.g., 'fix', 'bc', 'ds', etc.) within a given time limit. It validates the algorithm type, initializes parameters, and executes the corresponding method (e.g., `algo_fix`, `algo_ds`). For specialized algorithms like 'ids' or 'bcds', it extract... | def solve(self, algorithm: str = 'fix', timelimit: int = 30):
"""Solve the problem
Args:
algorithm (str): algorithm name. Defaults fix.
timelimit (int, optional): time limit. Defaults 30.
"""
if algorithm not in {'fix', 'bc', 'bd', 'ds', 'ids-h', 'ids-b', 'bcds-h... |
def get_domain_name(url):
return urlparse(url).netloc
def fetch_url(url):
'''
Request package 1 time
'''
response = requests.Response()
try:
response = requests.get(url)
#print(dir(response)) # python
#print(response.__class__) # python
except requests.exceptions.Conn... | The code parses a blog post by fetching content from a URL constructed using the provided path and domain, extracting text, splitting it into words, cleaning the words, and returning the cleaned list of words. | def parse_blog_post(path, url):
domain_name = get_domain_name(url)
lookup_url = f"http://{domain_name}{path}"
lookup_response = fetch_url(lookup_url)
if lookup_response.status_code in range(200, 299):
lookup_soup = soupify(lookup_response.text)
lookup_html_soup = get_content_data(lookup... |
def fetch_url(url):
'''
Request package 1 time
'''
response = requests.Response()
try:
response = requests.get(url)
#print(dir(response)) # python
#print(response.__class__) # python
except requests.exceptions.ConnectionError:
print("Could not connect to the url. ... | The function scrapes a webpage to extract internal links and text. It processes HTML to identify local paths, constructs absolute URLs, extracts text content, splits it into words, cleans the words, and returns a set of URLs to scrape along with the cleaned word list. | def fetch_links_words(url):
print(url, "scraping..")
response = fetch_url(url)
soup = soupify(response.text)
html_soup = get_content_data(soup, url)
local_paths = get_regex_local_paths(html_soup, url) # /this/is/some/path
domain_name = get_doma... |
def get_input():
url = input("What is your url? ")
if url == 'q':
return end_program()
url = append_http(url)
try:
validate_url(url)
except ValueError as err:
print(err)
print("Type 'q' to quit lookup")
return get_input()
return url
def fetch_url(url):
... | The main task of the code is to fetch a webpage, parse its HTML content, extract local paths, gather words from blog posts at those paths, and output the 100 most common words using a counter. It validates the HTTP response, processes text with BeautifulSoup, and analyzes word frequency in scraped content. | def main():
url = get_input()
response = fetch_url(url)
if response.status_code not in range(200, 299): # Http Status Codes
print(f"Invalid request, you cannot view this. {response.status_code}")
return None
response_html = response.text # html
soup = soupify(response_html)
html_... |
def addTaskToSeqByNum(self, t_num:int):
idx = 0
while idx < len(self.queue):
if self.queue[idx].num == t_num:
self.sequence.append(self.queue[idx])
idx+=1
self.queue = deque(task for task in self.queue if task.num != t_num)
def checkIncompleteSchedule(sel... | This code processes a sequence of transactions, handling read (R), write (W), and commit (C) operations with lock management. It checks for available locks, executes tasks, tracks incomplete schedules, and prints the transaction flow. If a task cannot acquire a lock, it's marked incomplete. The loop continues until all... | def start(self):
while self.sequence or self.queue:
if len(self.queue) > 0:
if self.queue[0].item not in self.lock_table.keys():
self.sequence.appendleft(self.queue.popleft())
self.incomplete_schedule[self.sequence[0].num] = False
... |
def basic_FTP_comp_vs_comm(data_size_config: Dict, processing_time_config: Dict, bytes_per_second: float, device_count: int, core_per_device: int) -> Dict:
computation_time: td = td()
communication_time: td = td()
conv_blocks = list(data_size_config.keys())
conv_blocks.append(None)
list_a = [[con... | The main task of the code is to compute network and processing performance metrics for different models under various configurations. It calculates bytes_per_second from given bit rates, loads model-specific data, and evaluates metrics like FTP transfer, offloading strategies, and partitioning methods using predefined ... | def data_main():
bits_ps = 55947313.60676045
jitter = 11301312.582474127
bytes_per_second = ((bits_ps - jitter) / 8)
models = [model for model in os.listdir(
model_folder) if model != ".DS_store"]
cores_per_device = 4
devices_in_network = 4
results_dict = {key: {"ftp": {}, "ftp_no_... |
def forward(self, X):
""" Forward pass through full network"""
z, mu, logvar = self.encode(X)
X_rec = self.decode(z)
return X_rec, mu, logvar
def vae_loss(self, y_pred, y_true, mu, logvar):
""" Custom loss for VAE """
kld = -0.5 * torch.sum(1. + logvar - mu.pow(2) - logva... | This code trains a Variational Autoencoder (VAE) using a training dataset, optimizing parameters via Adam with weight decay. It implements early stopping for both training and validation phases, computes reconstruction loss, and optionally evaluates on a test set. The model's training loss and validation loss are recor... | def train_model(self, train_loader, learning_rate, n_epochs, train_patience, test_patience, test_loader=False, save_model=True):
""" Train VAE """
epoch_hist = {}
epoch_hist['train_loss'] = []
epoch_hist['valid_loss'] = []
optimizer = optim.Adam(self.parameters(), lr=learning_rat... |
def delete_tree_nodes(self):
for child in self.tree.get_children():
self.tree.delete(child)
def insert_tree_node(self, field: str, value: object, node: str = '') -> None:
"""Inserts a tree node (consisting of field name and value) at the node (tree position).
If value is a (JSON-able... | The main task of the code is to allow users to select a JSON file via a file picker, load its contents, and dynamically update a tree structure with the parsed JSON data while handling errors and clearing existing nodes before insertion. | def load_json_file(self) -> None:
"""Launches a filepicker to select a file, that will be read as json and inserted into the tree.
"""
fp = filedialog.askopenfilename(initialdir=self.path, filetypes=[("JSON files", "*.json"), ("All Files", "*.*")])
if not fp:
return
... |
def delete_tree_nodes(self):
for child in self.tree.get_children():
self.tree.delete(child)
def insert_tree_node(self, field: str, value: object, node: str = '') -> None:
"""Inserts a tree node (consisting of field name and value) at the node (tree position).
If value is a (JSON-able... | This method opens a file dialog to select a JSON file, loads its content, clears existing tree nodes, inserts the JSON data into a tree structure, expands the tree, and sets focus on the first item for user interaction. | def load_json_file(self) -> None:
"""Launches a filepicker to select a file, that will be read as json and inserted into the tree.
"""
fp = filedialog.askopenfilename(initialdir=self.path, filetypes=[("JSON files", "*.json"), ("All Files", "*.*")])
if not fp:
return
... |
def reconstruct_element_list(grid):
# grid comes from ids%grid_ggd(grid_ind)
elm_list_imas = np.array( grid.space[0].objects_per_dimension[2].object.array )
elm_list = element_list_class()
elm_list.n_elm = len(elm_list_imas)
for elm in elm_list_imas:
elm_tmp = element_class()
... | The function `value_at_RZphi` computes interpolated values at specified $(R, Z)$ points with associated $\phi$ coefficients using a grid-based mesh. It reconstructs node and element lists from the grid, validates input consistency, precomputes element centers for efficiency, and evaluates values via parallel processing... | def value_at_RZphi(grid, val_coeff, Rp, Zp, phi):
print( ' Reconstruct node/element list')
elm_list = reconstruct_element_list( grid )
node_list = reconstruct_node_list( grid )
# Sanity check
if ( (len(Rp) != len(Zp)) or (len(Rp) != len(phi)) or (len(Zp) != len(phi)) ):
print( " The... |
def delete_past_messages(
bot: tb.TeleBot,
call: tb.types.CallbackQuery,
quantity: int = 10) -> None:
"""Deletes past messages.
Args:
bot (tb.TeleBot): Bot instance.
call (tb.types.CallbackQuery): CallbackQuery instance.
quantity (int, optional): Quantity of me... | This function processes a Telegram bot callback query by managing news categories, pagination, settings, and cleaning up past messages to handle user interactions effectively. | def handle_callback_query(call: tb.types.CallbackQuery) -> None:
"""Handles callback query.
Args:
call (tb.types.CallbackQuery): Callback query instance.
Returns: None
"""
news = {
'pln': ['today', 'accidents', 'automir', 'culture', 'society'],
'cdi': ['news'... |
def align_peaks(self):
"""
align all waveforms so that merger occurs at t=0
we define merger at the point where 22 mode amplitude is the largest
"""
tpeak_cir = get_peak(self.t_cir, abs(self.h_cir_dict['h_l2m2']))[0]
tpeak_ecc = get_peak(self.t_ecc, abs(self.h_ecc_dict['h... | The code initializes a class to process gravitational waveform data from both eccentric and circular orbital models. It aligns these waveforms on a common time grid, validates input parameters, identifies mode key formats, computes amplitude and orbital frequency modulations, and generates updated eccentric multimodal ... | def __init__(self, t_ecc=None, h_ecc_dict=None, t_cir=None, h_cir_dict=None,
get_orbfreq_mod_from_amp_mod=False, recompute_tpeak=True):
"""
t_ecc: time array for the eccentric 22 mode waveform
h_ecc_dict: dictionary of eccentric wavefform modes. Should only contain 22 mode
... |
def load_settings(workspace: Workspace, document_path: str) -> PluginSettings:
"""
Load settings from pyproject.toml file in the project path.
Parameters
----------
workspace : pylsp.workspace.Workspace
Current workspace.
document_path : str
Path to the document to apply ruff on... | This function generates code actions using Ruff for a Python document, handling diagnostics to provide fixes, disable options, and organize imports. It processes Ruff's checks, applies unsafe fixes if allowed, and adds 'fix all' actions when applicable, returning structured code action dictionaries for the language ser... | def pylsp_code_actions(
config: Config,
workspace: Workspace,
document: Document,
range: Dict,
context: Dict,
) -> List[Dict]:
"""
Provide code actions through ruff.
Parameters
----------
config : pylsp.config.config.Config
Current workspace.
workspace : pylsp.worksp... |
def initial_pheromone(self):
for p_list in self.distances:
temp_list=[]
#print(p_list)
for i in p_list:
if i == np.inf:
temp_list.append(0)
else:
temp_list.append(1/len(self.distances))
#print... | This code implements Ant Colony Optimization (ACO) to find the shortest path between a start and destination node. It initializes pheromones, iteratively updates trails based on path lengths, and applies 'shaking' perturbations at specific iterations (i=2,5) by modifying distance matrices and pheromone values. The shak... | def get_route(self, start, dest, shaking):
self.start = start
self.dest = dest
self.shaking = shaking
shortest_path = None
allRoutes = None
all_time_shortest_path = ("placeholder", np.inf)
self.initial_pheromone()
for i in range(self.n_iterations):
... |
def sample_mushroom_data(file_name,
num_contexts,
shuffle_rows=True,
r_noeat=0,
r_eat_safe=5,
r_eat_poison_bad=-35,
r_eat_poison_good=5,
prob_po... | This code initializes a dataset for reinforcement learning or policy evaluation by either loading precomputed data or generating new data based on the specified dataset name (e.g., mushroom, stock). It processes features, normalizes them, and stores rewards, optimal actions, and offline policies. The main task is to pr... | def __init__(self,
trial,
T,
name,
behavior_pi = 'eps-greedy',
behavior_epsilon=0.1,
num_test = 1000
): # Create or load on trial basis. If saved, be consistent with T
"""
datasets: (n, d)
opt_vals[0]: opt... |
def AsteroidScreenWrap(self, asteroid: GameObject.Asteroid):
if asteroid.sprite.x > self.data.game_res[0]:
asteroid.sprite.x = -asteroid.sprite.width
elif asteroid.sprite.x < -asteroid.sprite.width:
asteroid.sprite.x = self.data.game_res[0]
if asteroid.sprite.y > self.... | This method updates the game state by handling player movement, collision detection between projectiles and asteroids, updating scores, managing asteroid spawning and removal, and triggering game over logic when the player's lives reach zero. It processes input, moves game objects, checks for collisions, updates UI ele... | def update(self, game_time: pyasge.GameTime) -> None:
self.asteroids_to_add = []
self.asteroids_to_remove = []
self.score_text.string = f"Score: {self.score}"
if self.menu:
pass
elif self.game_over:
return
else:
x_dir = 0
... |
def display_welcome_menu(self):
# Display welcome menu: tell them the rules of the game
# ask for their name
welcome_message = '''
Welcome to Mastermind game. A random number has been generated
It is your job to guess what this hidden number is...
To make it to the lead... | The code defines a gameplay method that initializes and runs a number guessing game. It displays a welcome menu, lets the user select a mode, generates a random target number, executes the game loop for guessing, and finally prints the total number of guesses required to win. | def gameplay(self):
self.display_welcome_menu()
self.mode_select()
self.random_number()
self.gameloop()
print("You needed {game_count} guesses to get it right...".format(game_count = self.game_count)) |
def draw_line(self, dot_1, dot_2):
dot_1.connect_dots(dot_2)
dot_2.connect_dots(dot_1)
self.canvas.create_line(dot_1.get_pos(self.spacer, self.offset)[0] + self.offset,
dot_1.get_pos(self.spacer, self.offset)[1] + self.offset,
dot_2... | This method handles drawing lines between adjacent, unconnected dots in a game. When a mouse event occurs, it identifies the clicked dot, checks adjacency and connection status, draws a line if valid, claims the connecting box, and checks for game completion. If the game ends, it retrieves the winner and restarts the g... | def is_line(self, event=None): # Draws lines between dots ; Called by Event
if event: # Event is a class within Tkinter
dot = self.game.get_dot_by_posXY(event.x, event.y, self.spacer, self.offset)
if dot == self.selectedDot: # Prevents making a line for just itself
return... |
def update_current_player_title(self):
self.root.title("{0} - Turn : {1}".format(type(self.game).__name__,
self.game.get_current_player().get_initial()))
def select_dot(self, event=None): # On Event we select a dot
if event:
self.selectedDot ... | This code initializes a graphical user interface (GUI) for a game, setting up a window with specified dimensions, background color, and icon. It creates a canvas for rendering game elements like dots and lines, binds mouse events for user interaction (dot selection and line drawing), and initializes game-specific attri... | def __init__(self, root, window_size, game):
self.root = root
self.game = game
self.fire_icon_path = r"src/games/dotgame/FireIcon32x32.ico"
self.dot_color = "black"
self.text_color = "white"
self.font_style = "TimeNewRoman 20"
self.window_size = window_size
... |
def perform_refinement(self, model, sample, encoder_out):
assert "random_refine_step" in sample
random_refine_step = sample["random_refine_step"]
was_training = model.training
model.eval()
y_input = sample["net_input"]["prev_output_tokens"]
y_mask = (y_input != 1)
... | The code computes the loss for a given sample during training, incorporating conditional refinement strategies (exposure1, progressive) and different loss computation paths (pnet2 vs standard). It returns the computed loss, sample size, and logging metrics including reward values, while handling gradient contexts and t... | def forward(self, model, sample, reduce=True):
"""Compute the loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
"""
net_in... |
def accumulate_expool(self, sample, pool):
y_input = sample["net_input"]["prev_output_tokens"]
src_tokens = sample["net_input"]["src_tokens"]
src_lengths = sample["net_input"]["src_lengths"]
y_mask = (y_input != 1)
cmlm_mask = (y_input == 4)
true_target = sample["true_tar... | The code computes the loss for a given sample during training or evaluation, managing a pool of examples and generating logging outputs. It adjusts the model's decoder based on progressive refinement steps, samples from the pool, and calculates loss, reward, and sample reward. The function returns the loss, sample size... | def forward(self, model, sample, reduce=True):
"""Compute the loss for the given sample.
Returns a tuple with three elements:
1) the loss
2) the sample size, which is used as the denominator for the gradient
3) logging outputs to display while training
"""
assert... |
def read_csv():
with open(csvfile, 'r', encoding="ISO-8859-1") as csv_grid_f:
csv_grid_r = csv.reader(csv_grid_f, )
P = []
next(csv_grid_r)
for row in csv_grid_r:
row[1] = row[1].replace(" ","")
P.append(row[1:14]+row[15:17])
P = np.vstack(P)
return P
def set_params(params):
grid = G... | The main task of the code is to process volcanic data from a CSV file, extract parameters for each volcano, and generate a grid for the specific volcano with ID '284160' by setting its spatial coordinates and other attributes. The code loops through all entries, applies parameters, and triggers grid creation only for t... | def main():
'''
params[_] = [name_no_spaces, id_number, min_easting, max_easting, min_northing, max_northing, NW_zone, NE_zone, SW_zone, SE_zone, vent_zone, resolution, mean_elevation, zone_crossing, equator_crossing]
'''
params = read_csv()
for i in range(len(params)):
grid = set_params(params[i]) # add ... |
def get_start_date(self):
"""
Finds the start date of the prime rates schedule
equivalent to when the morgage loan was created
"""
return self.convert_string_to_date(constants.LOAN_DATE)
def get_end_date(self, start_date, number_of_years):
return start_date + relativedelt... | The code generates a mortgage amortization schedule by calculating a date range, creating a prime rates schedule, and returning the generated rates. It determines start/end dates, constructs a date range, and produces a schedule of prime rates for the specified period. | def handle(self):
"""
Get mortgage amoritization schedule
"""
start_date = self.get_start_date()
end_date = self.get_end_date(start_date, constants.NUMBER_OF_YEARS)
dates = self.get_date_range(
start_date, end_date, constants.PRIME_RATES_SCHEDULE
)
... |
def generate_search_url(donor):
'''
Generates the search url
'''
url = 'https://www.vpap.org/search/?q='
donor = donor.replace(' ', '+')
url += donor + '&facet=donors'
return url
def make_soup(link):
'''
Creates a soup object
'''
page = urllib.request.urlopen(link)
soup = BeautifulSoup(page, 'html.parser')
... | The code scrapes donation data for a specified donor by first generating a search URL, parsing results, extracting recipient links, and then retrieving and processing donation details from each recipient's page. | def scrape_data(donor):
search_page = generate_search_url(donor)
search_soup = make_soup(search_page)
results = search_soup.find_all('a', attrs = {'class': 'list-group-item'})
for result in results:
donor_page = generate_recipients_link(result, donor)
donor_soup = make_soup(donor_page)
scrape_donations(dono... |
def get_search_page(donor):
'''
Gets the search results for the donor.
Needed to find the correct URL
'''
search_page = generate_search_url(donor)
print(search_page)
return search_page
def soup_page(link):
'''
Creates a soup object
'''
page = urllib.request.urlopen(link)
soup = BeautifulSoup(page, 'html.p... | The code scrapes donation data for a specified donor by first searching a webpage for a matching link, retrieving the donor's specific page, and then extracting donation details from that page. It handles case-insensitive donor name matches, skips empty searches, and processes the final page to gather relevant donation... | def scrape(donor):
search_page = get_search_page(donor)
search_soup = soup_page(search_page)
#Search by class list-group-item to find the link for the search result
results = search_soup.find_all('a', attrs = {'class': 'list-group-item'})
element = None
for result in results:
if donor.lower() in result.get_text... |
def retrieve(self, course, assignment, submission):
"""
Connects to Google Drive and downloads files for submissions that have been turned in.
Submission number supplied to this method will determine which submission is retrieved eg. '1' for first submission
'2' for second submission an... | The code deploys a grading process by retrieving submission files, grading them, submitting results, and saving grading information. It downloads files, evaluates them, submits outcomes, and stores errors or success data, conditional on submission success. | def deploy(self, course, assignment, submission, return_grade=False):
# Download and store files
self.retrieve(course, assignment, submission)
# Results of grading. Stored in results.json also
results = self.grade_files(course, assignment, submission)
# Submit results
... |
def bids_read_json(fname):
'''
Safely read JSON sidecar file into a dictionary
:param fname: JSON filename
:return: dictionary structure
'''
try:
fd = open(fname, 'r')
json_dict = json.load(fd)
fd.close()
except:
print('*** JSON sidecar not found - returning ... | The function handles BIDS image processing based on purpose (func, fmap, anat) by modifying metadata, renaming files, and organizing outputs. It detects sequence types (e.g., EPI, GRE), adjusts JSON sidecar fields (e.g., TaskName, EchoTime), creates event templates, and moves NIfTI/JSON files to BIDS directories. Speci... | def bids_purpose_handling(bids_purpose, seq_name, src_nii_fname, src_json_fname, bids_nii_fname, bids_json_fname,bids_bval_fname,bids_bvec_fname):
"""
bids_purpose_handling(bids_purpose, seq_name, src_nii_fname, src_json_fname, bids_nii_fname, bids_json_fname)
Special handling for each image purpose
... |
def parse_dcm2niix_fname(fname):
"""
Parse dcm2niix filename into values
Filename format is '%n--%d--%q--%s' ie '<name>--<description>--<sequence>--<series #>'
:param fname: BIDS-style image or sidecar filename
:return subj_name, ser_desc, seq_name, ser_no:
"""
# Ignore containing directory... | This function converts NIfTI files from a directory into BIDS-compliant format by parsing filenames, applying protocol rules, generating structured output paths, and handling special cases like diffusion data. It skips excluded protocols, creates BIDS directories, and optionally cleans up temporary files after processi... | def bids_run_conversion(conv_dir, first_pass, prot_dict, sid_dir, SID, SES, use_run):
"""
bids_run_conversion(bids_conv_dir, first_pass, prot_dict, bids_ses_dir, SID, SES, use_run)
conv_dir=bids_conv_dir
sid_dir=bids_ses_dir
:param conv_dir:
:param first_pass:
:param prot_dict:
:param si... |
def bids_load_prot_dict(prot_dict_json):
"""
Read protocol translations from JSON file in DICOM directory
:param prot_dict_json:
:return:
"""
if os.path.isfile(prot_dict_json):
# Read JSON protocol translator
json_fd = open(prot_dict_json, 'r')
prot_dict = json.load(jso... | The main task of the code is to convert DICOM medical images into BIDS-compliant NIfTI format, organizing them into a structured directory hierarchy. It processes DICOM files from input directories, maps protocols using a JSON template, runs dcm2niix for conversion, and generates metadata files like participants.tsv. T... | def main():
# Parse command line arguments
parser = argparse.ArgumentParser(description='Convert DICOM files to BIDS-compliant Nifty structure')
parser.add_argument('-i','--indir', default='dicom', help='DICOM input directory with Subject/Session/Image organization [dicom]')
parser.add_argument('-o','-... |
def read_output_value(file_in):
file_handler = open(file_in,'r').readlines()
size = int(file_handler[0].strip())
time = int(file_handler[1].strip())
value_tab = []
new_string = ''
for i_line in range(0, len(file_handler)-2):
for i_b in range(0, len(file_handler[i_line+2].strip())):
... | This function solves a SAT problem to determine the origin of a grid-based system (like Conway's Game of Life) by generating a CNF encoding from input data, applying constraints (including cyclic ones if enabled), running a solver, and visualizing the solution if found. It reads input values, constructs logical constra... | def find_origin_of_gol(inputfile, cycle, solver, trans, show):
value_tab, size, time = read_output_value(file_in = inputfile)
nr_of_variables, nr_of_clauses, encoding = grid_over_time(size = size,
time = time,
... |
def train(model, optimizer, graph, features, labels, train_mask, val_mask, test_mask, n_epochs, inductive):
full_graph, full_features, full_labels = graph, features, labels
if inductive:
graph = graph.subgraph(torch.nonzero(torch.logical_or(train_mask, val_mask)).flatten())
features = featu... | This function trains a GraphSAGE model for inductive node classification on a graph dataset. It loads training/test data, splits into train/validation/test sets, constructs a graph from node relationships, prepares features/labels, initializes a GNN model, trains it with Adam optimizer, and saves the trained model and ... | def inductive_entry_train(training_dir,
model_dir,
output_dir,
features_train,
features_test,
target_column,
source_destination_node_index,
... |
def frobenius_norm_squared(A):
A2 = np.multiply(A,A)
return np.real(np.sum(A2))
def fitness(inputs, outputs, A):
return frobenius_norm_squared(np.dot(inputs, A) - outputs)
def tracenorm(A):
U, s, V = np.linalg.svd(A)
return sum(s)
def next_tracenorm_guess(inputs, outputs, lmbd, mu, current_A):
#... | The code implements gradient descent with trace norm regularization to optimize matrix A, minimizing a fitness function while preventing overfitting. It computes a Lipschitz constant for stability, iteratively updates A using a custom `next_tracenorm_guess` function, and tracks costs combining fitness and regularizatio... | def gradient_tracenorm(inputs, outputs, lmbd, iterations):
# Epsilon is here to ensure that the Lipschitz constant is big enough
# (because the expression of L is tight)
epsilon = 0.05
L = (1+epsilon)*2*math.sqrt(frobenius_norm_squared(np.dot(inputs.transpose(), inputs)))
print("Computed L: "+str(L)... |
def frobenius_norm_squared(A):
A2 = np.multiply(A,A)
return np.real(np.sum(A2))
def fitness(inputs, outputs, A):
return frobenius_norm_squared(np.dot(inputs, A) - outputs)
def tracenorm(A):
U, s, V = np.linalg.svd(A)
return sum(s)
def next_tracenorm_guess(inputs, outputs, lmbd, mu, current_A):
#... | The code implements an optimization algorithm to find a low-rank matrix $ A $ that minimizes a cost function combining data fitting (via `fitness`) and trace norm regularization (controlled by $ \lambda $). It iteratively updates $ A $ using gradient-like steps, adjusting the Lipschitz constant $ L $ dynamically to ens... | def extended_gradient_tracenorm(inputs, outputs, lmbd, iterations, initial=0):
# Epsilon is here to ensure that the Lipschitz constant is big enough
# (because the expression of L is tight)
epsilon = 0.05
L_bound = (1+epsilon)*2*math.sqrt(frobenius_norm_squared(np.dot(inputs.transpose(), inputs)))
L... |
def frobenius_norm_squared(A):
A2 = np.multiply(A,A)
return np.real(np.sum(A2))
def fitness(inputs, outputs, A):
return frobenius_norm_squared(np.dot(inputs, A) - outputs)
def tracenorm(A):
U, s, V = np.linalg.svd(A)
return sum(s)
def next_tracenorm_guess(inputs, outputs, lmbd, mu, current_A):
#... | This code implements an accelerated gradient descent algorithm with trace norm regularization to optimize a weight matrix $ W $. It minimizes a loss function (fitness) combined with a trace norm penalty, using adaptive step size control (via $ L $) and momentum-like updates (via $ Z $). The algorithm iteratively adjust... | def accelerated_gradient_tracenorm(inputs, outputs, lmbd, iterations, initial=0):
L = 1
gamma = 1.5
alpha = 1
epsilon = 0.1
L_bound = (1+epsilon)*2*math.sqrt(frobenius_norm_squared(np.dot(inputs.transpose(), inputs)))
p = np.shape(inputs)[0]
q = np.shape(inputs)[1]
r = np.shape(outputs... |
def read_file_builds(self):
data = read_file_yaml(self.builds_filepath)
builds = {}
for build in data['builds']:
builds[build['name']] = build['tasks']
return builds
def read_file_tasks(self):
data = read_file_yaml(self.tasks_filepath)
tasks = {}
fo... | The code updates data by reading build and task files, then constructing task queues for each build. If reading files or building queues fails, it logs errors and rolls back to old data to maintain consistency. | def update_data(self):
try:
builds = self.read_file_builds()
tasks = self.read_file_tasks()
except Exception as exc:
logging.error(exc)
logging.error(
msg="Error reading input data. Stopping data updates! Rollback to old data.")
els... |
def drawBoard(self):
"""
Draw a chessboard with the starting position and then redraw
it for every new move.
"""
board = self.board
lastmove = board.peek() if board.move_stack else None
check = board.king(board.turn) if board.is_check() else None
self.rend... | This code initializes a chess GUI application by setting up an SVG chessboard, configuring window properties, creating UI elements like labels and buttons for move prediction and image loading, and preparing the board for game interactions. It calculates board dimensions, positions pieces, and launches prediction threa... | def __init__(self, board):
"""
Initialize the chessboard..
"""
super().__init__()
self.setWindowTitle("Chess Cheaters")
self.setGeometry(300, 300, 800, 800)
self.widgetSvg = QSvgWidget(parent=self)
self.widgetSvg.setGeometry(10, 10, 600, 600)
se... |
def drawBoard(self):
"""
Draw a chessboard with the starting position and then redraw
it for every new move.
"""
board = self.board
lastmove = board.peek() if board.move_stack else None
check = board.king(board.turn) if board.is_check() else None
self.rend... | This method retrieves an image path from user input, processes it into a matrix using 'do_magic', converts the matrix to a FEN string via FEN_convertor, updates the chess board, and initiates prediction threads if position validation fails. It handles exceptions with error dialogs. | def get_image_path(self):
text, okPressed = QInputDialog.getText(self, "", "Path_to_image:", QLineEdit.Normal, "")
if okPressed and text != '':
try:
matrix = do_magic(text)
# matrix = [
# ['.', '.', '.', '.', '.', '.', '.', '.'],
... |
def check_promotion(self, coordinates):
P = self.pieceToMove[0].symbol()
if P == 'P' and self.board.turn:
return coordinates[-1] == '8'
elif P == 'p' and not self.board.turn:
return coordinates[-1] == '1'
return False
def choose_promotion(self):
items = {"... | This code handles left mouse clicks to enable chess piece movement by selecting a piece and a target square. It validates moves against chess rules, suppresses illegal moves, manages pawn promotion, updates the board state, and initiates threaded position checks. Legal moves trigger board updates, arrow resets, and par... | def mousePressEvent(self, event):
"""
Handle left mouse clicks and enable moving chess pieces by
clicking on a chess piece and then the target square.
Moves must be made according to the rules of chess because
illegal moves are suppressed.
"""
if event.x() <= sel... |
def preprocess(text):
data = tokenize(text)
data = removeStopwords(data)
data = stem(data)
return data
def processSimpleQuery(tokens):
global offset
global vocabFile
global indexFolder
fields = ["t", "b", "i", "c", "l", "r"]
docFreq = {}
docList = defaultdict(dict)
for tok... | This code processes search queries by analyzing field-specific weights. It handles simple queries and field-based queries (e.g., "t:term"), tokenizes input, ranks results using field-dependent scoring factors, and returns top K results with titles. Field weights vary (e.g., title "t" has higher priority than "r"), infl... | def parse(K, query):
global titleOffset
global defaultFieldFactor
fieldFactor = defaultdict(dict)
query = query.lower().strip()
isFieldQuery = False
if (":" in query):
isFieldQuery = True
if (not isFieldQuery):
tokens = preprocess(query)
results, docFreq = processS... |
def processTitle(text):
data = preprocess(text)
return data
def processBody(text):
data = re.sub(r'\{\{.*\}\}', r' ', text)
data = preprocess(data)
return data
def processInfobox(text):
data = text.split("\n")
flag = 0
lines = []
numLines = len(data)
for i in range(numLines):
... | The code processes input text by splitting it into sections based on "references" markers, extracts and processes title, body, infobox, categories, links, and references, converting everything to lowercase. It returns these parsed components for further use. | def processText(title, text):
title = title.lower()
text = text.lower()
categories = []
links = []
references = []
data = text.split("==references==")
if (len(data) == 1):
data = text.split("== references ==")
if (len(data) == 1):
data = text.split("== references==")
... |
def hold_old_lvl_stats(character: Character) -> Tuple[int, int, int, int, int, int, int]:
"""
Save the character's old values before leveling up.
:param character: The character whose old values need to be saved.
:return: A tuple containing the old level, old dexterity, old intelligence, old strength, ... | The main task of the code is to level up a character by incrementing their level, updating attributes, recalculating derived stats (max health, mana, stamina), restoring current vitals to new maximums, and printing the updated statistics compared to previous values. | def level_up(character: Character) -> Character:
"""
Level up the character, increasing their level, attributes, and other properties.
:param character: The character to level up.
:return: The updated character.
"""
# Save the character's old values
old_level, old_level_dexterity, old_leve... |
def use_ability(character: Character, enemy: Character, decision_data) -> None:
"""
Allows a character to use an ability against an enemy.
:param character: The Character object representing the character using the ability.
:param enemy: The Character object representing the enemy being tar... | This function processes a character's decision during a game encounter, executing actions like attacking, using abilities, items, or fleeing. It checks the decision type, retrieves relevant ability/item data, and triggers corresponding game mechanics, ensuring valid actions are performed and handling errors for invalid... | def perform_decision(character: Character, enemy: Character, decision: tuple) -> None:
"""
Perform an action based on the character's decision.
:param character: The character object.
:param enemy: The enemy character object.
:param decision: A tuple with the decision type ('attack', 'ability', 'it... |
def add_exp(character: Character, experience_points: int) -> None:
character.experience += experience_points
def print_gained_exp(character: Character, experience_points: int) -> None:
print(f"{character.name} gained {experience_points} experience points!")
def check_exp_for_lvl_up(character: Character) -> Char... | The function awards 100 experience points to a character, prints the gain, checks if the character levels up based on the new experience, and returns the updated character with potential level progression. | def award_experience(character: Character) -> Character:
"""
Award experience points to the character and level up the character if necessary.
:param character: The character to receive the experience points.
:return: The updated character.
"""
# The amount of experience points to award to the ... |
def round_init() -> int:
"""
Initialize the round number for a battle.
:return: The initial round number.
"""
round_number = 1
return round_number
def print_rounds(round_number: int):
"""
Print the current round number with a separator before it.
:param round_number... | The code simulates a turn-based battle between two characters, repeatedly attacking and printing health status until one dies. It returns the winner or None if both survive, awarding experience to the victor. | def battle(character1: Character, character2: Character) -> Union[Character, None]:
"""
Simulates a battle between two characters and prints the results of each round.
The battle continues until one of the characters is no longer alive.
:param character1: The first character participating i... |
def pause_game(self):
pygame.display.set_caption("Paused")
self.timer.tick(self.snake.speed)
paused = True
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
... | This code runs a game loop for a Snake-like game, handling user input, updating game state (snake movement, collision detection), drawing game elements (level, food), managing snake growth/reduction, level progression, and maintaining frame rate using Pygame. | def run(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
s... |
def button(bot, update, chat_data, job_queue):
update.callback_query.answer()
arg_one = update.callback_query.data.split(" ")[0] if not 'new' in chat_data else chat_data['cur']
if arg_one == "sday" or arg_one == "gday":
chat_data[arg_one] = update.callback_query.data.split(" ")[1]
month = st... | This function handles a button interaction in a bot, executing the 'button' function with error handling. If a KeyError occurs, it cleans up chat_data, detects the user's language, and triggers a send function to respond appropriately. The debug flag bypasses error handling for testing. | def try_button(bot, update, chat_data, job_queue):
if cfg['agecalculator']['debug']:
button(bot, update, chat_data, job_queue)
else:
try:
button(bot, update, chat_data, job_queue)
except KeyError:
chat_data.pop("new", None)
if not "lang" in chat_data:
... |
def get_dates(chat_data):
time = chat_data["bhour"] + ":" + chat_data["bmin"] if "bhour" in chat_data else "00:00"
bday = datetime.strptime(
chat_data["sday"] + "." + chat_data["smonth"] + "." + chat_data["syear"] + " " + time, "%d.%m.%Y %H:%M")
tday = datetime.strptime(
chat_data["gday"] + ... | The function generates a list of special dates based on age calculations from birth to current date, using helper functions to compute variations with added days, seconds, and repdigit patterns for months, days, hours, minutes, and seconds. | def __calulate_date_list(chat_data):
bday, tday = get_dates(chat_data)
d_age = (tday - bday).days
s_age = (tday - bday).total_seconds()
date_list = []
date_list.append(__special_month(bday, d_age, chat_data, add=1))
date_list.append(__special_month(bday, d_age, chat_data, add=2))
date_list.... |
def print_to_file(data):
with open(log_path, "a") as f:
f.write("{} - {} \n".format(time.ctime(), data))
def get_status(pi_ip):
get_string = 'http://{}:3000/event/'.format(pi_ip)
r = requests.get(get_string, timeout=10)
return r
def alert(data):
print_to_file(data)
# set webhook url... | The code's main task is to monitor Raspberry Pi devices by periodically sending HTTP-GET requests to each host IP listed in a CSV file. It handles timeout and request errors, processes JSON responses, checks status, logs statistics, and prints results. The loop repeats at intervals defined by a timeout configuration, e... | def _main():
timeout = int(monitor_config['DEFAULT']['timeout'])
hostips = []
with open("../hosts.csv", "r") as hostfile:
hosts = hostfile.readlines()
for line in hosts:
hostips.append(line.split(';')[1])
# Main loop, polls the 9 pis then waits
while True:
for ip ... |
def moveStraight(self): # moves robot forward/backward 10 cm
global x1
global y1
#Set directon to moving forward or backward
if (self.isForward == True):
dest = 1
else:
dest = -1
print(self.rX, self.rY)
x1 = self.rX+dest*10
y1 = se... | The code determines a robot's path based on obstacle count, using different strategies (straight, pathA, pathB) and visualizing the route with the `draw` method, incorporating obstacle coordinates when present. It handles 0, 1, or 2 obstacles, ignoring extra ones, to plan and display the next three navigation points. | def pathFinder(self, numObstacle): # Returns a path of the next 3 points
print("Start Pathfinding")
if(numObstacle == 0):
self.moveStraight()
#x2 = y2 = x3 = y3 = self.obstacle[0][0]]= [0][1]= [1][0] = [1][1] = None
self.draw(self.rX, self.rY,x1,y1, None,None,None,No... |
def deposit():
input_text = ""
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN and input_text.isdigit():
... | The code implements a Pygame-based slot machine game loop. It initializes a balance via deposit(), handles user input (Enter to spin, Q to quit), updates the balance based on spin results, and continuously renders the current balance on-screen. The loop processes events, maintains a 60 FPS frame rate, and exits gracefu... | def main():
balance = deposit()
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print(f"You left with €{balance}")
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOW... |
def display_slot_machine(self, columns):
"""
Display the slot machine spin on the GUI.
Parameters:
- columns (list): 2D list representing the slot machine spin.
"""
for i, column in enumerate(columns):
for j, symbol in enumerate(column):
self.... | This code simulates a slot machine spin with visual and audio effects. It plays a spin sound, displays animated slot results for 2 seconds, then stops the sound, calculates the spin outcome based on lines/bet, and updates the player's balance. The core tasks are: 1) Visual spin animation 2) Audio feedback 3) Result cal... | def spin_with_effect(self, lines, bet):
spin_duration = 2
# Play the spin sound
spin_sound.play()
start_time = time.time()
while time.time() - start_time < spin_duration:
slots = SlotMachineLogic.get_slot_machine_spin(ROWS, COLS, symbol_count)
self.disp... |
def _connect_to_collection(self):
"""Internal method that connects to the mongo database using The path,
database name, and collection name the instance of Analyze was
initialized with.
This method doesn't do anything if there is already a connection
to the database.
"""... | The main task of the code is to retrieve a list of ISO-formatted dates containing active and reactive power readings from a MongoDB collection. It connects to the database, identifies the date range (first and last dates), filters out dates without power data, and returns the filtered list of dates. | def get_isodate_list(self):
"""Get the list of dates in isodate format that contain active and
reactive power readings.
:return: list of isodates that contain power readings.
"""
self._connect_to_collection() # Will error out if can't connect.
# Will error out is can't ... |
def foreground(self):
"""Foreground the window."""
hwnd = self.hwnd
try:
win32gui.SetForegroundWindow(hwnd)
except pywintypes.error:
raise RuntimeError(f"Failed to foreground window {hwnd}.")
def open_console(self):
# Open the console -- press tilde until console status is True.
while not self.get_sta... | The code restarts a specific Farming Simulator 22 savegame by interacting with its console. It checks if the game window exists, brings it to focus, opens the console, inputs the `cpRestartSaveGame` command with a savegame ID, and presses Enter. It then waits for the game window to close and reopen, ensuring the game r... | def restartSavegame(self):
# Find the open Farming Simulator 22 window, and send it first the tilde/grave key n times, then "restartMySavegame", then enter.
if not self.window_exists:
print("No Farming Simulator 22 window found.")
else:
# Foreground the window.
self.foreground()
self.open_console... |
def normalizeEquations(self):
for equation in self.equations:
equation.normalize()
def simplifyEquationsUntilNoneAreLeft(self):
while len(self.equations) > 0:
self.simplifyEquations()
def makeBackSubstitution(self):
solutionForVariables = {}
for variable, algebrai... | The code solves a system of equations by normalizing the equations, simplifying them iteratively until no further simplification is possible, and then performing back substitution to find the solution without checking for satisfiability. | def solveWithoutSatisfiabilityCheck(self):
self.normalizeEquations()
self.simplifyEquationsUntilNoneAreLeft()
return self.makeBackSubstitution() |
def clicker(self, button):
if self.counter % 2 == 0:
mark = "X"
self.label.setText("O's Turn")
else:
mark = "O"
self.label.setText("X's Turn")
button.setText(mark)
button.setEnabled(False)
# Increment the counter
self.coun... | The main task of the code is to initialize a UI for a turn-based game (likely Tic-Tac-Toe) by setting up buttons, disabling them initially, tracking turns with counters, and connecting each button to a click handler. It also links restart/start buttons to their respective functions, preparing the interface for gameplay... | def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setupUi(self)
# Create a list of all the buttons in order to iterate many times later
self.button_list = [
self.Button_1,
self.Button_2,
self.Button_3,
self.Button_... |
def popFiller(pop, direction):
"""
Takes in population and direction lists and fills them with random values within the range.
"""
for i in range(POPULATIONSIZE):
# Generate a random path and add it to the population list
pop.append([(randint(1, ROWS), j) for j in range(1, COLS + 1)])
... | The code implements a genetic algorithm to solve a maze by evolving paths through generations. It initializes a population, evaluates fitness, selects parents, applies crossover and mutation, and checks for solutions. If found, it traces the optimal path using an agent; if not, it restarts or exits. Fitness metrics are... | def main():
# Initialize population, direction, and solution lists
pop, direc, sol = [], [], []
# Set the generation count and the maximum number of generations
gen, maxGen = 0, 2000
# Set the number of solutions to be found
sol_count = 1
# Set the number of solutions to be found
pop, d... |
def validate_new_length(name_op):
validate_hash_length(name_op["hash"])
def validate_firstupdate_length(name_op):
validate_rand_length(name_op["rand"])
validate_anyupdate_length(name_op)
def validate_update_length(name_op):
validate_anyupdate_length(name_op) | This function generates a Bitcoin script string based on the operation type in `name_op`. It appends hex codes for specific operations (e.g., `OP_NAME_NEW`, `OP_NAME_FIRSTUPDATE`) and data fields (hash, name, value) using `push_script`. Validations ensure correct data lengths, and unknown operations trigger exceptions.... | def name_op_to_script(name_op) -> str:
if name_op is None:
script = ''
elif name_op["op"] == OP_NAME_NEW:
validate_new_length(name_op)
script = '51' # OP_NAME_NEW
script += push_script(bh2u(name_op["hash"]))
script += '6d' ... |
def get_wallet_name_delta(wallet, tx, domain=None):
# get domain
if domain is None:
domain = wallet.get_addresses()
domain = set(domain)
name_input_is_mine = False
name_output_is_mine = False
name_input_value = None
name_output_value = None
def nameop_is_mine(inout):
i... | The function determines the appropriate label for a name-related transaction based on its type (e.g., Transfer, Registration, Update) and wallet ownership, returning labels like "Transfer (Outgoing)", "Registration", or "Pre-Registration" while handling edge cases like queued transactions and name operation deltas. | def get_default_name_tx_label(wallet, tx) -> Optional[str]:
for idx, o in enumerate(tx.outputs()):
name_op = o.name_op
if name_op is not None:
# TODO: Handle multiple atomic name ops.
name_input_is_mine, name_output_is_mine, name_value_is_unchanged = get_wallet_name_delta(wal... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--baseline', action="store_true", help="run the experiment using the baseline")
parser.add_argument("--train", action="store_true", help="train the model on the whole datasetand store it")
parser.add_argument("--no-holdout", actio... | The code performs training, cross-validation, and testing of machine learning models. It loads datasets, creates models (baseline or tuned with hyperparameters), trains them, saves models, and evaluates performance using metrics. Cross-validation tests multiple hyperparameter combinations, while testing evaluates the b... | def main():
args = parse_args()
validate_args(args)
if args.train:
sample_size = get_sample_experiment_size()
if args.no_holdout:
split = load_experiment(args.sample)
dataset= split.training
path_model = get_path_model_training("model")
else:
... |
def transpuestaMatriz(a):
return [[a[j][i] for j in range(len(a))] for i in range(len(a[0]))]
def conjugadoMatriz(a):
return [conjugadoVector(a[i]) for i in range(len(a))]
def multiplicacionMatriz(a, b):
if len(a[0]) == len(b):
filas = len(a)
columnas = len(b[0])
res = [[(0, 0) for i... | The code checks if a given matrix is unitary by verifying if the product of the matrix with its conjugate transpose equals the product of the conjugate transpose with the matrix. It first ensures the matrix is square, computes the transpose and conjugate, multiplies the matrix with its conjugate transpose, and compares... | def matrizUnitaria(a):
if len(a) == len(a[0]):
temp = transpuestaMatriz(a)
temp = conjugadoMatriz(temp)
c = multiplicacionMatriz(a,temp)
d= multiplicacionMatriz(temp,a)
if c == d: return True
else: return False
else:
print("no es una matriz cuadrada")
... |
def selectSquare(self):
mousePos = pg.mouse.get_pos()
for y in self.squareArray:
for x in y:
x.color = (150, 150, 150)
x.borderWidth = 1
if x.rect.collidepoint(mousePos):
self.selectedSquare = x
self.sele... | This code runs a game loop handling user input and rendering a board. It processes events like quitting, mouse clicks (to select squares or exit), and key presses (to input numbers or trigger a solver). The loop maintains a 15 FPS clock, updates the display with the board and return button, and exits when the return bu... | def run(self):
while self.running:
self.clock.tick(15)
for event in pg.event.get():
if event.type == pg.QUIT:
sys.exit()
if event.type == pg.MOUSEBUTTONDOWN:
if self.return_button_rect.collidepoint(pg.mouse.get_pos(... |
def get_best_action(self, parent):
# calculate UCB1 heuristic for each node in parent's children
ucb1_values = [self.ucb1(child) for child in parent.children]
# determine best action from index of maximum UCB1 value
best_action = parent.children[ucb1_values.index(max(ucb1_values))]
... | The code traverses a tree structure, alternating between state and action nodes. It selects the best action from state nodes, expands action nodes when branching is required, or randomly plunges into child states. The traversal continues until reaching a terminal node with no children, returning its state for evaluatio... | def traverse(self):
curr_node = self.root
# print("Traversing tree...")
# print("At root node...")
# print("Action for root node: ", self.root.children[0].action)
# While the current node has children or is an action node
while curr_node.children or (curr_node.depth % 2) ... |
def events(events_queue):
""" Events pass. """
for event in events_queue:
# close
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
return False
# set destination
elif event.type == MOUSEBUTTONDOWN:
G.world.create_mark(event.__dic... | The main task of the code is to run a game loop using Pygame, controlling frame rate via MAX_FPS, updating game state with time deltas, and rendering frames. It initializes a clock, processes events, tracks time intervals, calls update() for state changes, and draw() for rendering, ensuring consistent timing and respon... | def main():
""" Main loop. """
frame_min_t = 1 / MAX_FPS
t = 0.0
t_last = 0.0
time.clock() # init clock
while events(pygame.event.get()):
t_last = t
t = time.clock()
update(t - t_last)
draw() |
def process_wiki_text(text, src_lang='en'):
parsed_text = []
for elem in text.split('\n'):
if elem == '== See also ==':
break
if len(elem) > 0 and elem[0] != '=':
parsed_text.append(elem)
parsed_text = ' '.join(parsed_text)
if src_lang == 'ru':
return nltk... | The code processes claims and Wikipedia documents to generate BERT training data. It loads documents, extracts text and links, saves processed text, and uses coreference resolution if enabled. It then formats claim-text pairs into a TSV file, handling translations and coreference adjustments, for BERT model input. Your... | def create_bert_file(task_type, claims, mode=1, total=None, top=20, use_coreference_bert=False,
use_coreference_search=False, ann_type='Stanford', directory='tmp/', source_lang='en'):
with open(os.path.join(directory, 'documents_{}.pickle'.format(task_type)), 'rb') as f:
documents = pi... |
def silence():
pg.press("Enter")
pg.write("/silence Incorrect version, try to reload the game.")
pg.press("Enter")
time.sleep(2)
def get_data():
room_list = ["vanilla2", "vanilla1", "1", "5", "survivor787", "survivor esek", "survivor", "racing1", "racing96846468"]
arr = change_room(room_list)
... | The main task of the code is to execute a sequence of operations: suppress logging, retrieve data, and process it using the `inviter` function with provided `luadata` as input. The `main` function orchestrates these steps to handle data processing or initialization, likely within a script or application framework that ... | def main(luadata):
#log()
silence()
get_data()
inviter(luadata=luadata) |
def moveToCenter(points):
center = center_of_gravity(points)
points -= center
return points, center
def correctRotation(points, axes=None):
p0 = np.copy(points)
if not axes:
axis_max, axis_min = getPrincipleAxis(points)
else:
axes = np.copy(axes)
axis_max, axis_min ... | The main task of the code is to rectify a set of points by translating, rotating, and scaling them to align with a standard coordinate system. If no parameters are provided, it automatically centers the points, corrects their rotation based on given axes, and adjusts their size. If parameters are provided, it applies t... | def rectify(points, parameters=None, axes=None):
if not parameters:
points, T = moveToCenter(points)
points, R = correctRotation(points, axes)
points, S = correctSize(points)
else:
R, T, S = parameters
points -= T
points = np.dot(R, points.T).T
points, S =... |
def getPrincipleAxis(points):
center = center_of_gravity(points)
covariance = np.cov(points.T)
eigenvalues, eigenvectors = np.linalg.eig(covariance)
largest_eigenvalue_index = np.argmax(eigenvalues)
smallest_eigenvalue_index = np.argmin(eigenvalues)
axis_max = eigenvectors[:, largest_eigenvalue_... | The function `rectifySeries` aligns a series of 3D points by rectifying their orientations using principal axes derived from the input data. If `enable_movement` is True, it computes a reference frame (either the midpoint or a specified frame), determines primary and secondary axes, and applies consistent rectification... | def rectifySeries(pointss, ref_frame=-1, enable_movement = True):
print('Rectifying series...')
if enable_movement:
i = pointss.shape[0]//2 if ref_frame <0 else ref_frame
#max_axis = getFloorAxes(pointss)[:3]
max_axis, _ = getPrincipleAxis(pointss[i])
max_axis = getPrincipleAxisM... |
def rectifySeries(pointss, ref_frame=-1, enable_movement = True):
print('Rectifying series...')
if enable_movement:
i = pointss.shape[0]//2 if ref_frame <0 else ref_frame
#max_axis = getFloorAxes(pointss)[:3]
max_axis, _ = getPrincipleAxis(pointss[i])
max_axis = getPrincipleAxisM... | The main task of the code is to preprocess a series of points by rectifying their coordinates, applying fixes, and adding computed speed and acceleration data. It copies the input array, rectifies the series (with optional movement correction), applies fixes, calculates speed and acceleration, then returns the modified... | def preprocess(pointss, enable_movement=True):
pointss = np.copy(pointss)
pointss = rectifySeries(pointss, enable_movement=enable_movement)
pointss = fix(pointss)
pointss = addSpeedSeries(pointss)
pointss = addAccSeries(pointss)
return pointss |
def cut_box(self, p, centerSnap = False):
p1 = self.selectedObjBox.p1
p2 = self.selectedObjBox.p2
w = self.selectedObjBox.width()
h = self.selectedObjBox.height()
c = self.selectedObjBox.center()
p = c if centerSnap else p
xbound = p.x... | This code handles mouse click events to modify selected shapes by cutting them with defined boxes, inserting the result into the cell, and updating the view. If buttons 16/32 are pressed, it changes the cut direction and triggers movement logic. The operation is prioritized when 'prio' is true, ensuring transactional u... | def mouse_click_event(self, p, buttons, prio):
if prio:
if buttons in [8]:
self.view.transaction("slice Shape")
try:
for o in [o.dup() for o in self.selectedObjs]:
shape = o.shape
out_reg = pya.Re... |
def set_config(self, global_config):
if hasattr(global_config, 'seed'):
self.seed = global_config.seed
else:
self.seed = random.getrandbits(32)
def convert_qobj_circuit_to_qasm(self, experiment):
instructions = experiment.instructions
qubit_num = len(experiment.he... | The code executes a quantum experiment by converting the input circuit to QASM, running it, and returning structured results. It records execution time, parses output data, and compiles metadata (e.g., experiment name, memory slots, success status) into a dictionary. The primary task is to run a quantum circuit simulat... | def run_experiment(self, config, experiment):
self.set_config(config)
# do this before running so we can output warning to the user as soon as possible if needed
self.start_time = time.time()
qasm = self.convert_qobj_circuit_to_qasm(experiment)
run_output = self.run(qasm)
... |
def offset_fuzzer(command):
crash = ''
buffer = ''
rough_fuzzing = True
fine_fuzzing = True
while rough_fuzzing:
try:
crash = crash + 'A'*300
payload = ''.join([command, crash])
s,connection = connection_init()
send_message(s, payload)
... | This code provides a command-line interface for selecting tools related to overflow exploitation, such as fuzzing, manual testing, EIP checks, bad character identification, and shellcode execution. It loops until the 'shell' command is entered, offering options to run specific functions or display available tools. | def overflow_tools():
toolbox = ('fuzzer','manual','shell','check','test eip','badchars','test module','help','send shellcode')
while True:
tool = input('tools> ')
if tool == toolbox[0]:
command = input('Enter the command to fuzz: ')
offset_fuzzer(command)
elif to... |
def temp_grab():
DHT_SENSOR = Adafruit_DHT.DHT11
DHT_PIN = 4
humidity, temperature = Adafruit_DHT.read(DHT_SENSOR, DHT_PIN)
return temperature, humidity
def temp_set(temperature, humidity):
if humidity is not None and temperature is not None:
# print(temperature, humidity, sep=',')
LE... | The code's main task is to retrieve temperature and humidity data using `temp_grab()`, pass them to `temp_set()`, and attempt to update a database via `sql_update()` after validating the temperature as an integer. If the temperature conversion fails, it recursively restarts the `main()` function, potentially creating a... | def main():
temperature, humidity = temp_grab()
# print(temperature, humidity, sep='|')
temp_set(temperature, humidity)
try:
int(temperature)
sql_update(temperature, humidity)
except:
# print('Exits successful')
main() |
def numpy_to_dict(weight, feature_dict):
for i,k in enumerate(feature_dict.keys()):
feature_dict[k] = weight[i]
return feature_dict
def loss_fn(x_data, y_data, feature_dict, y_vocab, eta=0):
loss = 0
for x_instance, y_instance in zip(x_data, y_data):
loss += loss_fn_instance(x_instance, ... | This function computes the loss and gradients for a model using given weights and data. It converts weights to a dictionary format, calculates the loss with a specified function, computes gradients, and converts them back to numpy arrays. The result is a tuple containing the loss value and gradients for optimization. | def get_loss_grad(weight, *args):
x_data, y_data, feature_dict, y_vocab = args
feature_dict = numpy_to_dict(weight, feature_dict)
loss = loss_fn(x_data, y_data, feature_dict, y_vocab, eta=0.1)
grads = gradient_fn(x_data, y_data, feature_dict, y_vocab, eta=0.1)
grads = dict_to_numpy(grads, feature_di... |
def numpy_to_dict(weight, feature_dict):
for i,k in enumerate(feature_dict.keys()):
feature_dict[k] = weight[i]
return feature_dict
def loss_fn(x_data, y_data, feature_dict, y_vocab, f_ls, eta=0):
loss = 0
for x_instance, y_instance in zip(x_data, y_data):
loss += loss_fn_instance(x_inst... | This function computes the loss and gradients for a model given input data and parameters. It converts weights to a dictionary, calculates the loss using a specified function, prints the loss value, computes gradients via another function, converts gradients back to numpy format, and returns both the loss and gradients... | def get_loss_grad(weight, *args):
X, Y_NER, W, Y_NER_set, tf_ls, sf_ls = args
feature_dict = numpy_to_dict(weight, W)
loss = loss_fn(X, Y_NER, W, Y_NER_set, [*tf_ls, *sf_ls], eta=0.1)
print(loss)
grads = gradient_fn(X, Y_NER, W, Y_NER_set, tf_ls, sf_ls, eta=0.1)
grads = dict_to_numpy(grads, W)
... |
def _init(self):
print("INITIALIZING")
ospath = os.getenv('LOCALAPPDATA')
if ospath == None:
ospath = Path.home()
self.storage_directory = os.path.join(ospath, '.DCN/WebScraping/')
self.storage_stats_directory = os.path.join(ospath, '.DCN/WebScraping/Data/')
... | The code's main task is to initialize a process, load articles, and save statistics. It starts by printing "STARTING," then calls `_init()` to set up initial states, `_loadArticles()` to retrieve or process article data, and `_saveStats()` to store computed statistics. This sequence likely prepares data for analysis, u... | def handle(self, *args, **options):
print("STARTING")
self._init()
self._loadArticles()
self._saveStats() |
def _loadRSSArticleSet(self, filePath):
print("LOADING ARTICLE FILE")
with open(filePath, 'rb') as f:
self.rssArticleSet = pickle.load(f)
def _parseArticle(self, url):
print("Loading webpage");
self._loadWebPage(url)
time.sleep(1);
print("Beginning to expand c... | The code's main task is to initialize a Chrome WebDriver, parse a specific RSS article URL, measure execution time, and save statistics. It loads RSS articles into a set, comments out a loop for parsing multiple articles, and instead directly parses one article URL. The script then calculates and prints the total runti... | def start(self):
print("Running")
startTime = time.perf_counter()
try:
self.driver = webdriver.Chrome()
except:
self.driver = webdriver.Chrome(executable_path='D:\\Documents\\chromedriver_win32\\chromedriver.exe')
self.rssArticleSet = set... |
def determine_number_of_shots(
weapon: dict,
target_unit_size: int,
half_range: bool = False
):
number_of_weapons = weapon["Number"]
type = weapon["Type"]
shots_per_weapon = weapon["Shots"]
blast = weapon.get("Blast", False)
if isinstance(shots_per_weapon, int):
shots = numbe... | This function simulates a weapon attack in a tabletop wargame, calculating damage based on attacker stats, weapon properties, defender attributes, and modifiers like range, special rules (e.g., Leontus, regimental standard), and overcharged weapons. It determines shots, hits, wounds, saves, and final damage, returning ... | def shoot_weapon(
attacker_bs: int,
weapon: dict,
defender: dict,
half_range: bool = False,
Leontus: bool = False,
Leontus_balls: bool = False,
regimental_standard: bool = False,
castellan: bool = False,
overcharged_las: bool = False,
born_soldiers_trigger: Optional[int] = None,
... |
def read():
with open("input.in") as f:
content = f.read().splitlines()
new_content = []
for c in content:
c = list(c)
temp = []
for i in c:
temp.append(int(i))
new_content.append(temp)
return new_content
def part1(content):
ans = 0
for i in ra... | The main task of the code is to read input content, process it using two functions (part1 and part2), and print the results of these processes. The code executes the `read()` function to obtain data, applies `part1()` and `part2()` to analyze or transform the content, and outputs the outcomes sequentially. This structu... | def main():
content = read()
print(part1(content))
print(part2(content)) |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def capture_int_response():
response = input("Hint: type your answer as an integer (e.g: 1 or 2 or 3) here: ")
return int(response) if response.isdigit() else None
def add_relic(num_relics):
global players_relics
players_relics... | This function presents the player with three room choices (Kitchen, Bedroom, Bathroom) in a text-based game. Depending on the selected room, the player encounters different scenarios: gaining a relic or life, facing demonic threats, or escaping. It captures input, processes the choice via a match statement, updates gam... | def level_one_room_choice():
print_and_pause("Where will you go now?. You can choose ONE room...", 1)
print_and_pause("1 for the Kithchen", 1)
print_and_pause("2 for the Bedroom", 1)
print_and_pause("3 for the Bathroom", 1)
room = capture_int_response()
match room:
case 1: # Kitchen
... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def capture_int_response():
response = input("Hint: type your answer as an integer (e.g: 1 or 2 or 3) here: ")
return int(response) if response.isdigit() else None
def add_relic(num_relics):
global players_relics
players_relics... | This function presents three path choices (Dead Ahead, Left, Right) in a text-based game, processes player input, and triggers different narrative outcomes. Choosing Left grants a relic and partial safety, Right leads to immediate death, and Dead Ahead offers a safer escape with relics. The function loops until valid i... | def level_two_path_choice():
print_and_pause("Your only options were to go Dead Ahead, Left or Right", 1)
print_and_pause("1 for Dead Ahead", 1)
print_and_pause("2 for Left", 1)
print_and_pause("3 for Right", 1)
path = capture_int_response()
match path:
case 1: # Dead ahead
... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def add_relic(num_relics):
global players_relics
players_relics = players_relics + num_relics
return
def subtract_lives(num_lives):
global players_lives
players_lives = players_lives - num_lives
return
def check_if_game... | This function handles a player's decision to take or leave a relic, affecting their inventory or lives. It processes input, updates game state via add_relic() or subtract_lives(), and checks for game over conditions, looping until valid input is given. | def find_relic_level_one():
print_and_pause("Do you want to take the relic?", 1)
response = input("Hint: type either 'yes' or 'no' here: ")
response = response.lower()
match response:
case "yes":
print_and_pause(
"\nYou picked up the relic from the dirt and brushed... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def capture_int_response():
response = input("Hint: type your answer as an integer (e.g: 1 or 2 or 3) here: ")
return int(response) if response.isdigit() else None
def subtract_lives(num_lives):
global players_lives
players_liv... | The function presents a multiplication math challenge where the user must solve a randomly generated problem within two attempts. Correct answers reward progression, while incorrect answers deduct lives, leading to a game-over scenario on the second failure. The task combines arithmetic verification with game mechanics... | def blue_book_maths_challenge():
#
num1 = random.randint(6, 12)
num2 = random.randint(6, 12)
correct_answer = num1 * num2
print_and_pause("\nYou opened the blue book, your homework was a math problem:", 1)
print_and_pause(f"\n'What is {num1} * {num2}?'", 1)
attempts = 0
while attempt... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def subtract_lives(num_lives):
global players_lives
players_lives = players_lives - num_lives
return
def check_if_game_over():
if players_lives == 0:
game_over()
else:
print_and_stop(
f"\nYou hav... | The code presents a history quiz challenge where the user must correctly identify the German leader in WWII (Hitler) within two attempts. Incorrect answers result in life deductions or a game-over scenario with a dramatic death message, emphasizing the consequences of failure in a game context. | def red_book_history_challenge():
print_and_pause("\nYou opened the red book, your homework is a history problem:", 1)
print_and_pause(f"\n'Who was the German leader in the Second World War?'", 1)
correctAnswers = ["hitler", "adolf hitler", "adolf"]
attempts = 0
while attempts < 2:
answer... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def subtract_lives(num_lives):
global players_lives
players_lives = players_lives - num_lives
return
def check_if_game_over():
if players_lives == 0:
game_over()
else:
print_and_stop(
f"\nYou hav... | This code presents a biology quiz where the player must identify the "powerhouse of the cell" (mitochondria) from a list of intentionally misspelled options. The player has two attempts; incorrect answers trigger escalating penalties, including life subtraction and a game-over scenario if failed. The function integrate... | def green_book_biology_challenge():
print_and_pause(
"\nYou opened the green book, your homework is a biology problem:", 1
)
print_and_pause(f"\nWhat is the powerhouse of a cell?", 1)
correctAnswers = [
"mitochondria",
"nitochondria",
"jitochondria",
"mutochondr... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def subtract_lives(num_lives):
global players_lives
players_lives = players_lives - num_lives
return
def check_if_game_over():
if players_lives == 0:
game_over()
else:
print_and_stop(
f"\nYou hav... | The code presents a riddle asking for something uniquely personal yet shared by others, allowing two attempts to answer correctly. If solved, the player proceeds; if not, lives are lost, and the game ends with a failure message. It enforces a game mechanic where incorrect answers trigger penalties, integrating narrativ... | def riddle_challenge_one():
print_and_pause("Here is a riddle to solve:", 1)
print_and_pause(
"\nTroll: 'Tidings to you, mortal one. In order to pass, partake in my class : What belongs to only you, but those around you use it, too?'",
1,
)
correctAnswers = ["your name", "name", "my nam... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def subtract_lives(num_lives):
global players_lives
players_lives = players_lives - num_lives
return
def check_if_game_over():
if players_lives == 0:
game_over()
else:
print_and_stop(
f"\nYou hav... | This code presents a riddle challenge where the player must answer "What room do ghosts hate going in?" with two attempts. Correct answers ("living room" or "the living room") grant victory, while incorrect answers trigger life deductions or a game-over scenario involving a shadow demon. The function manages input vali... | def riddle_challenge_two():
print_and_pause("Here is a riddle to solve:", 1)
print_and_pause(
"\nGirl: 'Hey, Mister! Play a game with me! I tell you a widdle, and you figure out the answer, okay? Here we go! What room do ghosts hate going in?'",
1,
)
correctAnswers = ["living room", "th... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def find_relic_level_one():
print_and_pause("Do you want to take the relic?", 1)
response = input("Hint: type either 'yes' or 'no' here: ")
response = response.lower()
match response:
case "yes":
print_an... | The code defines the first level of a text-based adventure game, guiding the player through a narrative where protagonist Harvey Staker discovers an ancient relic, navigates a haunted house, confronts a demon, and escapes into the forest. It includes story progression, player choices (room selection), and transitions t... | def level_one():
# story start
print_and_pause(
"\nYour name is Harvey Staker - an experienced hunter who fended for himself in the middle of nowhere. It was late, and you were tired from a hard day of poaching.\n",
5,
)
print_and_pause(
"On your usual route home, a heavy storm ... |
def print_and_pause(message, seconds):
print(message)
pause(seconds)
def capture_int_response():
response = input("Hint: type your answer as an integer (e.g: 1 or 2 or 3) here: ")
return int(response) if response.isdigit() else None
def blue_book_maths_challenge():
#
num1 = random.randint(6, 12)... | The function `level_three_book_choice` prompts the user to select one of three books (Blue, Red, or Green), each triggering a specific challenge (maths, history, or biology). Based on the choice, it executes the corresponding challenge function and awards relics (2 for the Blue Book, 1 for others). Invalid inputs trigg... | def level_three_book_choice():
print_and_pause("Which book do you choose?. You can choose ONE book...", 1)
print_and_pause("1 for the Blue Book", 1)
print_and_pause("2 for the Red Book", 1)
print_and_pause("3 for the Green Book", 1)
book = capture_int_response()
match book:
case 1: #... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.