dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def _show(self, message):
self.io.write(message + "\n")
def _ships_unplaced_message(self):
ship_lengths = [str(ship.length) for ship in self.game.unplaced_ships]
return ", ".join(ship_lengths)
def _prompt_for_ship_placement(self):
ship_length = self._prompt("Which do you wish to place?")... | The code runs a ship placement and shooting game. It first guides the user to place all ships on the board, displaying remaining ships and updating the board after each placement. Once setup is complete, it starts the game loop, prompting the user to take shots and updating the game board until all ships are destroyed,... | def run(self):
self._show("Welcome to the game!")
self._show("Set up your ships first.")
while self._ships_unplaced_message():
self._show("You have these ships remaining: {}".format(
self._ships_unplaced_message()))
self._prompt_for_ship_placement()
... |
def run_arg_parser(self):
# argument parse
parser = argparse.ArgumentParser(
prog='SNPfilter',
)
subparsers = parser.add_subparsers(
title='subcommands', dest="subcommand_name")
# argparse for prepare
parser_a = subparsers.add_parser('prepare',
... | The code's main task is to parse command-line arguments and execute corresponding subcommand functions. It checks the `subcommand_name` from parsed arguments and invokes `prepare_main`, `qcfilter_main`, or `codefilter_main` accordingly. If no valid subcommand is found, it prints usage help. The method handles argument ... | def run(self):
self.run_arg_parser()
# self.args = self.arg_parser.parse_args()
# if hasattr(self, "subcommand_name"):
# self.args.func(self.args)
# else:
# self.arg_parser.print_help()
args_dict = vars(self.args)
if args_dict["subcommand_name"] ... |
def find_pixel(x, y):
"""
Finds the top-left corner of the pixel that contains a given dot
:param x: x coordinate of the dot
:param y: y coordinate of the dot
:return: x,y coordinates of the top-left corner of the pixel
"""
while x % 5 != 0:
x -= 1
while y % 5 != 0:
y -= ... | The code initializes a graphical drawing application with a canvas, color selection, and various tools (pen, eraser, shapes). It handles user interactions for drawing, shape creation, color changes, and actions like save/load/undo. The main task is to create an interactive drawing interface with multiple modes and func... | def main():
###################################
# SETTING BASE SCREEN:
###################################
screen.fill(GRAY)
canvas = pygame.draw.rect(screen, WHITE, (150, 20, 830, 560))
###################################
# SETTING CURRENT COLOR:
###################################
... |
def calc_safe_hit(dealer, num):
safe = 0
if num == 10:
safe = dealer.full_deck_total
elif num == 9:
safe = dealer.nines + dealer.eights + dealer.sevens + dealer.sixes + dealer.fives\
+ dealer.fours + dealer.threes + dealer.twos + dealer.aces
elif num == 8:
safe = ... | The function determines whether a player should "Hit" or "Double Down" in a card game based on calculated probabilities. It evaluates hand values (`hand_alt`) against a `true_assumption`, computes a `beat_prediction` probability using `calc_safe_hit`, and triggers "Double Down" (DD) if the probability exceeds 50%, othe... | def hit_or_dd(hand, hand_alt, true_assumption, cards_in_hand, dealer, player):
decision = " "
lowest_beat = 0.0
beat_prediction = 0.0
if hand_alt == 11 or hand_alt == 10 or hand_alt == 9:
lowest_beat = true_assumption - hand_alt + 1
beat_prediction = calc_safe_hit(dealer, lowest_beat) /... |
def k_array(k1 = 2.19e-4 , k2 = 6.12e-5 , k3 = .997148 , k4 = 6.79e-2) :
return np.array([k1 , k2 , k3 , k4])
def hs_func(os , alpha_s) :
diff = (2*os) - alpha_s
k3 = k_array()[2]
diff_coeff = diff * alpha_s * k3
os2 = os * os
return (os-sqrt(os2-diff_coeff))/k3
def cs_func(os , alpha_s) :
... | The main task of the code is to compute a value by multiplying the fourth element of `k_array()` with the squared result of `hs_func(os, alpha_s)` divided by `cs_func(os, alpha_s)`, returning the final calculated value. | def ps_func(os , alpha_s) :
return k_array()[3] * (((hs_func(os , alpha_s))**2) / cs_func(os , alpha_s)) |
def hs_func(os , alpha_s) :
diff = (2*os) - alpha_s
k3 = k_array()[2]
diff_coeff = diff * alpha_s * k3
os2 = os * os
return (os-sqrt(os2-diff_coeff))/k3
def cs_func(os , alpha_s) :
return (alpha_s - hs_func(os , alpha_s)) / 2
def ps_func(os , alpha_s) :
return k_array()[3] * (((hs_func(os ,... | The code initializes an 8xN NumPy array with specified parameters and computed values. It sets the first column to input parameters (p, os, od, alpha_s, ad) and calculates three function outputs (hs_func, cs_func, ps_func) using os and alpha_s, then returns the populated array. | def init_array(yf , yi , p = 1.00 , os = 2.01 , od = 2.23 , alpha_s = 2.26 , ad = 2.26) :
output_space = np.zeros((8,yf - yi))
output_space[0 , 0] = p
output_space[1 , 0] = os
output_space[2 , 0] = od
output_space[3 , 0] = alpha_s
output_space[4 , 0] = ad
output_space[5 , 0] = hs_func(os,al... |
def vs_comp(vs = 0.12) :
return 1 / vs
def wo_diff_comp(od , os , w = 0.001) :
return w * (od - os)
def k_array(k1 = 2.19e-4 , k2 = 6.12e-5 , k3 = .997148 , k4 = 6.79e-2) :
return np.array([k1 , k2 , k3 , k4])
def u_array(u1 = 4.95e2, u2=4.95e-2) :
return np.array([u1 , u2])
def p_diff_comp(p , os , alp... | The function `os_dt` computes a value by multiplying the result of `vs_comp()` with the difference between `wo_diff_comp(od, os)` and terms involving `k_array()[0]` and `u_array()[1]` scaled by `p_diff_comp(p, os, alpha_s)`. It combines these components to calculate an adjusted metric, likely for modeling or analysis p... | def os_dt(od , os , p , alpha_s) :
return vs_comp() * (wo_diff_comp(od , os) - k_array()[0] - (u_array()[1] * p_diff_comp(p ,os, alpha_s))) |
def p_diff_comp(p , os , alpha_s , d = 8.64) :
return (ps_func(os , alpha_s) - p) / d
def f_CO(t) :
exp1 = 2.0 * np.exp(-((t - 1988) / 21) ** 2)
exp2 = 10.5 * np.exp(-((t - 2100) / 96) ** 2)
exp3 = 2.7 * np.exp(-((t - 2265) / 57) ** 2)
return exp1 + exp2 + exp3
def u_array(u1 = 4.95e2, u2=4.95e-2) :... | The function `dp_dt` computes the time derivative of a variable `p` by combining two terms: a component from `p_diff_comp` and a scaled version of `f_CO(t)`, where the scaling factor is the reciprocal of the first element in `u_array`. This integrates dynamic behavior from `p_diff_comp` with a time-dependent adjustment... | def dp_dt(alpha_s , os , p , t) :
return p_diff_comp(alpha_s , os , p) + (f_CO(t) / u_array()[0]) |
def dp_dt(alpha_s , os , p , t) :
return p_diff_comp(alpha_s , os , p) + (f_CO(t) / u_array()[0])
def os_dt(od , os , p , alpha_s) :
return vs_comp() * (wo_diff_comp(od , os) - k_array()[0] - (u_array()[1] * p_diff_comp(p ,os, alpha_s)))
def od_dt(od , os) :
return vd_comp() * (k_array()[0] - wo_diff_comp(o... | This function computes the derivatives of state variables using a Runge-Kutta method. It takes current state values and time, calculates time derivatives for eight variables (p, os, od, alpha_s, ad, etc.), and returns them in an array for numerical integration of differential equations. | def runge_katta_iterator(current_row,current_time) :
output_space = np.zeros((8))
p = current_row[0]
os = current_row[1]
od = current_row[2]
alpha_s = current_row[3]
ad = current_row[4]
output_space[0] = dp_dt(alpha_s,os,p,current_time)
output_space[1] = os_dt(od,os,p,alpha_s)
outpu... |
def load_model_epoch(self, model, epoch):
assert os.path.exists(
self.path+'models/'+self.model_params['model_name']+'/epo%d_code.h5' % epoch), 'Weights at epoch %d not found' % epoch
assert os.path.exists(
self.path+'models/'+self.model_params['model_name']+'/epo%d_desc.... | This code trains a machine learning model using data chunks, with options to reload previous models, pad input data, and validate/savemodels periodically. It iterates over epochs, loads and processes data, trains the model, tracks the best validation loss, and performs validation and saving based on specified intervals... | def train(self, model):
if self.train_params['reload']>0:
self.load_model_epoch(model, self.train_params['reload'])
valid_every = self.train_params.get('valid_every', None)
save_every = self.train_params.get('save_every', None)
batch_size = self.train_params.get('batch_size',... |
def move_east(self):
"""
function moves the snake south by 20 px
"""
if self.snake[0].heading() != 180:
prev_position = self.snake[0].position()
self.snake[0].seth(0)
self.move_forward(prev_position)
def move_north(self):
"""
function m... | The function `keep_moving_forward` continuously moves the snake in its current direction by checking the heading (0°, 90°, 180°, or others) and calling corresponding movement methods: `move_east`, `move_north`, `move_west`, or `move_south`. This ensures the snake progresses forward without changing direction unless exp... | def keep_moving_forward(self):
"""function is called continuously to keep snake moving
in the direction it is already facing"""
direction = self.snake[0].heading()
if direction == 0:
self.move_east()
elif direction == 90:
self.move_north()
elif dir... |
def getAllImagePaths(self):
paths = []
dirs = [dir for dir in os.listdir(self.imageFolder) if os.path.isdir(f"{self.imageFolder}\\{dir}")]
for dir in dirs:
curDirPath = f"{self.imageFolder}\\{dir}\\"
files = os.listdir(curDirPath)
for file in files:
... | The code either trains a machine learning model using image data (splitting into training/test sets) and saves it, or loads a pre-saved model. If prediction is enabled, it processes each specified image using the model for inference. | def run(self):
if not self.useSavedModel:
paths = self.getAllImagePaths()
self.getTrainingData(paths)
df_train, df_test = self.splitData(self.dataFrame)
self.trainModel(df_train, df_test)
if self.shouldSave:
self.saveModel()
... |
def unpause_sim(self):
rospy.wait_for_service('/gazebo/unpause_physics')
try:
self.unpause()
except rospy.ServiceException as e:
print ("/gazebo/unpause_physics service call failed")
def _set_action(self, action):
prev_pose = self.get_gt_pose()
if action == 0:
rospy.loginfo("> FORWARDS")
# Move f... | The main task of the code is to execute a given action in a simulation environment by unpausing the simulation, applying the action, and pausing again. It then retrieves the observation, checks if the episode is done, computes the reward, updates the cumulative reward, and returns the observation, reward, done status, ... | def step(self, action):
self.unpause_sim()
self._set_action(action)
self.pause_sim()
obs = self._get_obs()
done = self._is_done(obs)
info = {}
reward = self._compute_reward(obs, done)
self.cumulated_episode_reward += reward
return obs, reward, done, info |
def unpause_sim(self):
rospy.wait_for_service('/gazebo/unpause_physics')
try:
self.unpause()
except rospy.ServiceException as e:
print ("/gazebo/unpause_physics service call failed")
def pause_sim(self):
rospy.wait_for_service('/gazebo/pause_physics')
try:
self.pause()
except rospy.ServiceException... | The code's main task is to reset a drone simulation by arming the drone (if unarmored), moving it to a predefined start position via multiple intermediate steps, initiating takeoff, initializing environment variables, updating the episode state, and returning observations for a reinforcement learning environment. | def reset(self):
rospy.logwarn('start reset')
#First call of reset, arm drone (no need to move to start point as already there):
if (self.drone.is_armed() == False):
rospy.loginfo("Arm drone")
self.unpause_sim()
self.drone.arm()
self.drone.wait_for_status(self.drone.is_armed, True, 2)
self.pause_s... |
def denavit_transformation(theta, index):
"""
Computes the homogeneous transformation according to the Denavit-Hatenberg convention
Parameters
----------
theta : Rotation in z-axis [radians].
Internal variables
------------------
d : Distance between x-axes in meters.
alpha : Angle... | The code computes the analytic Jacobian matrix for a robotic manipulator by combining the geometric Jacobian with a kinematic operator derived from end-effector orientation. It calculates Denavit-Hartenberg transformations, exponential maps, spatial Jacobian, end-effector position, and constructs the analytic Jacobian ... | def compute_jacobian(theta, screw, dof=6 ):
# Compute DH transformations
# Compute exponential maps too
G_local = []
expMap_local = []
for i in range(dof):
G_local.append(denavit_transformation(theta[i], i))
expMap_local.append(G_local[i] @ exponential_map(screw[i], theta[i]))
... |
def ur5_params():
"""
Returns
-------
home_position : Home position of the UR5 with DH parameters
screw : Screw matrix for UR5 with DH parameters
"""
# UR5 link parameters (in meters)
l1 = 0.425
l2 = 0.392
h1 = 0.160
h2 = 0.09475
w1 = 0.134
w2 = 0.0815
home_posit... | The code computes the forward kinematics of a UR5 robot arm, solves for joint angles to reach a desired position using root-finding, simulates the motion in CoppeliaSim, and compares the calculated end-effector transformation matrix with the simulated result. It retrieves robot parameters, calculates transformations, i... | def main():
np.set_printoptions(precision=3, suppress=True) # Restrict decimals in console output
dof = 6
home_position, screw = ur5_params() # Get UR5 parameters
theta_0 = np.array([0, 0, 0, 0, 0, 0]) # Initial position
theta_d = np.array([0,-m.pi/2, 0, 0, m.pi/2, 0]) # Desired position, converte... |
def get_pokemon_details(pokemon_name):
api_url = f'https://pokeapi.co/api/v2/pokemon/{pokemon_name}'
response = requests.get(api_url)
return response.json()
def update_pokemon_details(cursor, *args):
current_pokemon_name = args[0]
new_pokemon_details = args[1]
sql = f"UPDATE pokemon SET height =... | The main task of the code is to evolve a Pokémon by updating its details and types in a database. It retrieves the Pokémon name, attempts evolution, fetches evolved details, and updates the database using a cursor. If evolution fails, it returns an error. | def evolve_pokemon(cursor, args):
pokemon_name = args[0]
try:
evolved_pokemon = evolve(pokemon_name)
except Exception as e:
return {'error': 400, 'details': 'This pokemon can not be evolved ' + str(e)}
evolved_details = get_pokemon_details(evolved_pokemon)
update_pokemon_details(curs... |
def parse_plate_name(plate_folder):
return os.path.split(plate_folder)[1]
def add_image_data(input_files, plate_name):
tmp_root = f'./tmp_{plate_name}'
os.makedirs(tmp_root, exist_ok=True)
file_format = "ome.zarr"
print("Add dapi / nuclei")
tmp_folder = os.path.join(tmp_root, "ims_nuclei")
... | The function processes a plate's data by adding images and segmentations, creating site/well tables, configuring 2D views (all or default based on input), and validating the dataset structure for a microscopy project. | def add_plate(plate_folder, all_views):
plate_name = parse_plate_name(plate_folder)
ds_folder = f"./data/{plate_name}"
print("Adding plate", plate_name)
input_files = glob(os.path.join(plate_folder, "*.h5"))
input_files.sort()
print("with", len(input_files), "images")
# add images and segm... |
def saveImage(event=None):
inducers.append(rgb(r, g, b)) # inducer
predictions.append(crgb(colorPredictedAfterImage)) # predicted after image color
experiments.append(crgb(colorsys.hsv_to_rgb(hPredicted, sPredicted, vPredicted))) # actual after image color seen by the subject
hInducers.append(colorsys.... | The function `newCircle` performs three main tasks: saves the current image, updates the color, and refreshes the grid. It then schedules the `drawFirstCircle` function to execute after a 1-second delay using `root.after()`, likely to introduce a pause before rendering the first circle in a graphical application. | def newCircle(event=None):
saveImage()
newColor()
grid()
# delay 1 sec
root.after(1000, drawFirstCircle) |
def conv(x, nf, sz, wd, stride=1):
return tf.layers.conv2d(inputs=x, filters=nf, kernel_size=sz, strides=(stride,stride),
padding='same', data_format='channels_first',
kernel_initializer= tfk.initializers.he_uniform(),
bias_initiali... | This function constructs a Tiramisu neural network for image segmentation, combining dense blocks with skip connections. It processes input images through convolutional layers, a downsampling path (encoder), upsampling path (decoder), and outputs class probabilities via softmax. Key parameters include growth rate, bloc... | def create_tiramisu(nb_classes, img_input, height, width, nc, loss_weights, nb_dense_block=6,
growth_rate=16, nb_filter=48, nb_layers_per_block=5, p=None, wd=0., training=True, batchnorm=False, dtype=tf.float16, filter_sz=3, comm_rank=-1):
create_tiramisu_timer_logger = logger(comm_rank, "Creat... |
def init_timeline_configs(enable_tf_timeline, trace_level, min_timeline_step, max_timeline_step):
options = None
run_metadata = None
many_runs_timeline = None
if enable_tf_timeline:
options = tf.RunOptions(trace_level=trace_level)
run_metadata = tf.RunMetadata()
many_runs_timeli... | The code trains a deep learning model (Tiramisu architecture) using distributed computing with Horovod, handling data loading, model setup, loss computation, optimization, and validation. It includes checkpointing, timeline profiling for performance analysis, and distributed synchronization across multiple GPUs. The ma... | def main(input_path, blocks, weights, image_dir, checkpoint_dir, trn_sz, learning_rate, loss_type, fs_type, opt_type, batch, batchnorm, num_epochs, dtype, chkpt, filter_sz, growth, disable_training, enable_tf_timeline):
options = None
run_metadata = None
many_runs_timeline = None
timeline_trace_fp = op... |
def mean(data):
"""Return the sample arithmetic mean of data."""
n = len(data)
if n < 1:
raise ValueError('mean requires at least one data point')
return sum(data)/n
def pstdev(data):
"""Calculates the population standard deviation."""
n = len(data)
if n < 2:
raise ValueError... | The function computes basic statistical measures (mean, min, max, standard deviation, median, mode) of a dataset, rounding values to three decimal places. It returns NaN for all metrics if the input list is empty. For mode, it identifies the most frequent value, rounded to three decimals. | def findStatistics(dataObj):
dataObjMean = round(mean(dataObj),3) if len(dataObj) > 0 else float('nan')
dataObjMin = round(min(dataObj),3) if len(dataObj) > 0 else float('nan')
dataObjMax = round(max(dataObj),3) if len(dataObj) > 0 else float('nan')
dataObjStdev = round(pstdev(dataObj),3) if len(dataObj... |
def getTraininingTier(self, fish):
if (fish.fishType == "training" and not self.trainingTierCaptured):
self.trainingTierCaptured = fish.getTier()
def getSteps(self, fish, targetLoc, nFrames = 3):
hashableID = id(fish)
prevLoc = self.fishPrevLocDict.get(hashableID)
# if just ... | This code simulates an evolutionary algorithm for fish behavior in an aquarium. It runs multiple generations, each with training fish and NPCs, evaluating their scores based on survival time. User controls allow adjusting simulation speed or skipping to optimal generations. After each generation, the best-performing fi... | def displayMain(self):
generation = 0
self.speedUp = 1
wait = int(1000/self.fps/(1+self.speedUp))
# aquarium demonstration variables (Note: can pres -> or <- to slow/speed up a generation)
# user can also press up arrow to skip to generation with best attributes
generatio... |
def check_dependency(self):
return (self.password_hash and self.key)
def request_keychain(self, salt):
challenge = self._kdf(password=self.password_hash, salt=salt)
return self.call("open", challenge=HexEncoder.encode(challenge).decode("utf-8"))
def authenticate(self, password, challenge):
... | The code's main task is to authenticate a user by either retrieving a keychain based on a challenge's password hash salt (if dependencies are met) or directly authenticating with the provided password. It returns the derived key and keychain, handling two authentication paths depending on dependency checks. | def open(self, challenge, password):
if self.check_dependency():
self.keychain = self.request_keychain(challenge.password_hash_salt)
else:
self.authenticate(password, challenge)
return self.key, self.keychain |
def _open_block(self, block_type: str):
"""
Pushes given block to the open block stack and updates the current block
pointer.
"""
self._open_block_stack.append(DOM(block_type))
def _write_to_current_open_block(self, *items: Union["DOM", str]):
"""
Writes the provi... | This function parses a paragraph by collecting consecutive TEXT_LINE and INDENT tokens, stripping their content, and appending them to a paragraph DOM block. It starts with a TEXT_LINE, then loops to add continuation lines, ensuring paragraphs end when non-TEXT_LINE/INDENT tokens are encountered. The result is a DOM el... | def _paragraph(self) -> DOM:
# paragraph should end if it is followed by anything other than
# TEXT_LINE, INDENT_LINE, but it can have multiple of them.
# I'm not sure the best way to write this but here is a stab
# at it
"""
Paragraph
: TEXT_LINE Paragraph
... |
def _eat(self, expected_type: str) -> dict[str, str]:
"""
Consume the lookahead and set the lookahead to the next token
"""
if self._lookahead["type"] == expected_type:
old_token = self._lookahead
self._lookahead = self._tokenizer.get_next_token()
retu... | The main task of the code is to parse and return the appropriate DOM element (AtxHeader, CodeBlock, or Paragraph) based on the current token type, while skipping blank lines. It checks the lookahead token and delegates parsing to specific methods for each element type, defaulting to Paragraph if none match. | def _element(self) -> DOM | None:
"""
Element
: AtxHeader
| Paragraph
| CodeBlock
;
"""
if self._lookahead["type"] == "BLANK_LINE":
# if there is a blank line here then skip it
self._eat("BLANK_LINE")
... |
def _open_block(self, block_type: str):
"""
Pushes given block to the open block stack and updates the current block
pointer.
"""
self._open_block_stack.append(DOM(block_type))
def _write_to_current_open_block(self, *items: Union["DOM", str]):
"""
Writes the provi... | This method constructs a DOM 'body' block by opening a block, populating it with an element list, and returning the closed block as a structured DOM node. | def _body(self) -> DOM:
"""
Body
: ElementList
;
"""
self._open_block("body")
self._write_to_current_open_block(*self._element_list())
return self._close_block() |
def get_next_token(self):
while self.current_char is not None:
if self.current_char.isspace():
self.advance()
continue
if self.current_char.isdigit():
val = self.get_int()
return Token(INTEGER, val)
... | This code evaluates an arithmetic expression involving addition and subtraction. It initializes the result with the first term, then iteratively applies operators (+/-) to combine subsequent terms, updating the result accordingly. The loop continues until all operators are processed, ultimately returning the computed v... | def expr(self):
self.current_token = self.get_next_token()
result = self.term()
while(self.current_token.__get_type__() == OPERATOR):
token = self.syntax_eat(OPERATOR)
if token == '+':
result += self.term()
elif token == '-':
... |
def get_region(transcript):
""" Return the region for an Ensembl transcript"""
url = f"https://rest.ensembl.org/lookup/id/{transcript}?content-type=application/json"
js = fetch(url)
if js["assembly_name"] != "GRCh38":
msg = f"Unsupported reference {js['assembly_name']}"
raise NotImpleme... | The code retrieves genomic and UniProt data for a specified transcript by fetching UCSC Genome Browser data, parsing transcript details, collecting related tracks, and exporting results in the requested format. It first locates the transcript's genomic region, extracts UniProt annotations, compiles the data, and output... | def main(transcript, format, export):
# Get the location for the specified transcript
chrom, start, end, version = get_region(transcript)
# Add the version to the transcript name
transcript = f"{transcript}.{version}"
url = f"https://api.genome.ucsc.edu/getData/track?genome=hg38;track=knownGene;chrom=... |
def find_pins(self, contours: list[np.ndarray]):
"""
### Find potential pins
---------------
Function that finds the pins and adds them to their bounding squares.
The pins are found by finding the square structures in the image.
#### Args:
* contours: list of con... | The function identifies grid blocks by analyzing contours to detect potential pins, assigning them to squares if they reside in square corners, and designating a square as a block if it contains a predefined number of pins. | def find_blocks(self, contours: list[np.ndarray]):
"""
### Find blocks
---------------
Function that determines which squares are blocks in the grid.
It does this by finding the potential pins (p_pins)
then checking if the pin is in the corners of the square and adding i... |
def check_if_target_visible(self):
if self.color_visible()[0] == self.color_index:
return True
return False
def turn_to_angle_360_system(self, angle, lin_speed = None, ang_speed = None, ignore_color = False):
self.publish_velocity.publish_velocity()
difference_cloc... | The main task of the code is to navigate a robot to locate and approach a target using odometry and lidar data. It continuously checks for target visibility, adjusts movement based on environmental data, avoids obstacles by rotating and reversing, and takes a picture once the target is detected. The loop handles both e... | def main_loop(self):
while not self.ctrl_c:
if self.odom_data.initial_data_loaded and self.lidar_data.initial_data_loaded:
self.map_saver.save_map()
if not self.target_found:
if not self.check_if_target_visible() or self.picture_taken:
... |
def __update_expected_landing_point_x(self, ball: Ball):
"""
Calculate the actual landing point of current ball x
"""
copyBall = Ball(False)
copyBall.x, copyBall.y, copyBall.x_velocity, copyBall.y_velocity = ball.x, ball.y, ball.x_velocity, ball.y_velocity
loopCounter = ... | This function updates the environment state based on player actions (P1_act, P2_act), computes a reward, next state, and termination flag (done). It adjusts speed, handles mode-specific updates (train/play/validate), calculates rewards with external logic, logs losses, and returns the reward, next state, and terminatio... | def update(self, P1_act, P2_act):
"""
This function will return `reward, next_state, done`.
"""
# Update landing point
self.__update_expected_landing_point_x(self.env.engine.ball)
self.speed = 1 / (time.perf_counter() - self.last_time)
if self.mode == "Train":
... |
def prepare_bifurcation_end(self, tree_segment, tree, start_num):
jump_reference = []
bifurcation_list = []
end_list = []
for idx, vessel_segment in enumerate(tree_segment):
if idx == 0:
jump_reference.append(vessel_segment[self.start_idx])
... | The code evaluates a model's performance on a validation dataset by processing each sample to trace vessel structures, calculate metrics (e.g., TPR, TPM, FN, FP), and record time consumption. It iterates through validation regions, computes instance-level parameters, aggregates results, and optionally visualizes trajec... | def evaluate(self):
print('Start Validation')
all_point_val_result = []
all_point_rate_result = []
all_time_list = []
for _, sample in enumerate(self.val_loader):
tpr, tpm, fn, fp, ai_gt, ai_infer, tpr_of, tpm_of, fn_of, fp_of = 0, 0, 0, 0, 0, 0, 0, 0, ... |
def fire_bullet(ai_settings, screen, ship, bullets):
"""Fire a bullet if limit not reached yet."""
#Create a new bullet and add it to the group 'bullets' using the add() method
#Confirm the number of existing bullet is below the allowed number before creating a new bullet
if len(bullets) < ai_settings.bullets_allow... | This function handles keypress events in a Pygame game, controlling ship movement, bullet firing, game state transitions, and exit actions by evaluating specific keyboard inputs and triggering corresponding game mechanics like movement, shooting, and play initialization. | def check_keydown_events(event, ai_settings, screen, stats, sb, play_button, ship,
aliens, bullets, mouse_x, mouse_y, alien_bullets, long_bullets,
health, shield):
"""Respond to keypresses"""
if event.key == pygame.K_RIGHT:
ship.moving_right = True
elif event.key == pygame.K_LEFT:
ship.moving_left = True
... |
def save_high_score(stats):
filename = 'high_score.txt'
with open(filename, 'w') as file_object:
file_object.write (str(stats.high_score))
def check_keydown_events(event, ai_settings, screen, stats, sb, play_button, ship,
aliens, bullets, mouse_x, mouse_y, alien_bullets, long_bullets,
health, shield):
"""Res... | The function `check_events` processes keyboard and mouse inputs in a Pygame game. It handles quitting the game, key presses (invoking `check_keydown_events` for actions like movement/shooting), key releases (`check_keyup_events`), and mouse clicks (triggering `check_play_button` to start gameplay). It updates game stat... | def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens,
bullets, alien_bullets, long_bullets, health, shield):
# Watch for keyboard and mouse events.
for event in pygame.event.get():
if event.type == pygame.QUIT:
save_high_score(stats)
sys.exit()
elif event.type == pygame.KEYDOWN:
... |
def create_long_bullet(ai_settings, screen, stats, long_bullets):
"""Reload a long bullet for a certain amount of alien kills."""
if (stats.alien_kills % ai_settings.long_bullet_reload_point == 0):
if ai_settings.long_bullet_count < ai_settings.long_bullet_limit:
ai_settings.long_bullet_count += 1
#to pre... | The main task of the code is to manage long bullets in a game by creating, firing, updating their positions, removing off-screen bullets, and checking collisions with aliens. It handles the lifecycle of long bullets, ensuring they are properly generated, moved, cleaned up, and interact with game elements like aliens. | def update_long_bullets(ai_settings, screen, stats, sb, ship, aliens,
bullets, long_bullets):
#Create long bullet for standby
create_long_bullet(ai_settings, screen, stats, long_bullets)
#Fire long bullet on trigger
fire_long_bullet(ai_settings, screen, stats, ship, long_bullets)
#Update long bullet positio... |
def check_fleet_edges(ai_settings, aliens):
"""Respond appropriately if any aliens have reached an edge"""
for alien in aliens.sprites():
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break
def check_high_score(stats, sb):
"""Check to see if there's a new high score"""
if stats.score >... | This function updates alien positions, checks for collisions with the player's ship, manages shield interactions, updates scores, triggers level progression when aliens are eliminated, and handles shield depletion by restarting the ship if the shield limit is exceeded. | def update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets):
"""
Check if the fleet is at an edge,
and update the positions of all aliens in the fleet
"""
check_fleet_edges(ai_settings, aliens)
aliens.update()
#Look for alien-ship collisions
if pygame.sprite.spritecollideany(ship, aliens):
if ... |
def exitIfRunTooFrequently():
lastRun = readSecret('lastRun', 0, False, '')
now = time.time()
if now - float(lastRun) < 86400: # less than a day
print('Script already ran today, use the "-f" option to force the script to run.')
exit()
writeSecret('lastRun', str(now))
def getPlayListId(u... | The code transfers music playlists between specified destinations by authenticating, clearing target playlists, and moving content from source to destination playlists, avoiding redundant transfers. It checks for the '-f' flag to bypass frequency limits and processes configurations to extract playlist IDs for transfer. | def start(config):
if not (len(sys.argv) > 1 and sys.argv[1] == '-f'):
exitIfRunTooFrequently()
paths = []
for path in config:
newPath = {'from': getPlayListId(path['from']), 'to': getPlayListId(path['to'])}
paths.append(newPath)
authenticate()
destinationsSeen = []
co... |
def create_control_dict(iterations, pressure, cofr, rho):
return FoamFile(
make_header(location="system", object="controlDict"),
{
"application": "simpleFoam",
"startTime": 0,
"endTime": iterations,
"deltaT": 1,
"startFrom": "startTime",
... | The function creates an OpenFOAM simulation case by generating essential configuration files, including control parameters, solver settings, boundary conditions, and parallel processing configurations, based on input parameters like iterations, pressure, velocity, and fluid properties. | def create_openfoam_case(iterations: int, pressure: float, velocity: Sequence[float], parallel: int = 1, cofr=[0, 0, 0], rho=1.2041):
case = OpenFoamCase()
case.add_file(create_control_dict(iterations, pressure=pressure, cofr=cofr, rho=rho))
case.add_file(fvSolution)
case.add_file(fvSchemes)
case.a... |
def find_split(data, columns):
best_split = Split() #create new Split object
best_info = -1.0 #pick the split with most information gain
for column_index in range(columns):
col_values = data[:, column_index] #fetch entries in a column
unique_values = np.unique(col_values) #possibly saves ti... | The main task of the code is to recursively build a decision tree by splitting data based on information gain. It creates internal nodes for splits (if information gain is positive) and leaf nodes for terminal classifications, tracking node creation depth and limiting tree growth to a specified maximum depth. | def create_class_tree(data, depth, max_depth):
global node_count
node_count += 1
print("Generating node: #{}".format(node_count)) #handy output to keep user aware that the program is functioning
classes = data[:, -1]
_, columns = np.shape(data[:, :-1]) #get column size info
if depth <= max_dep... |
def get_year_id_from_filename(filename: str):
_filename, extension = filename.split(".")
words = _filename.split("_")
return words[-1]
def get_df_sofifa_ids(match: pd.Series, team: Literal["away", "home"]):
"""
Returns a variant of
```python
L LR CL C CR ... | The main task of the code is to generate PCSP (player configuration strategy plan) files for football matches using predefined model templates and dataset ratings/matches data. It processes each model template, iterates through match CSV files, extracts player positions and statistics, dynamically populates template li... | def main():
# allow for modification of global variables
global RATINGS
global MATCHES
# list of model templates
models = [f for f in os.listdir(model_folders) if f.endswith('.pcsp')]
# create models folder
if not os.path.exists("./models"):
os.makedirs("./models")
# iterate ... |
def initialize_pop(inst, pop_size, using_grasp, alpha, grasp_iterations):
pop = []
ns = TourReversal() # since we used this ns for GRASP in the first assignment
for _ in range(pop_size):
if using_grasp:
pop.append(grasp(inst, ns, alpha, max_iterations=grasp_iterations))
else:
pop.append(construct_random_gr... | This function implements a genetic algorithm (GA) to solve an optimization problem defined by an instance. It initializes a population using GRASP or greedy heuristics, then iterates through generations, selecting individuals via tournament selection, applying crossover and mutation, and replacing the population. The a... | def ga(inst, num_generations=100, pop_size=300, using_grasp=False, grasp_iterations=10, alpha=1.0, selec_ratio=0.5, tour_size=3, repl_ratio=1.0, crossover_prob=0.7, mutation_prob=0.3, hof_size=3, max_time=math.inf, return_gen_data=False):
'''
inst: instance
num_generations = number of generations the algorithm per... |
def is_disc_other_player(self, node):
return node.is_on_board() and self.board.nodes[node] not in [self.player.color, self.EMPTY]
def is_disc_current_player(self, node):
return node.is_on_board() and self.board.nodes[node] == self.player.color
def change_current_player(self):
if self.player == s... | This code processes a player's move in a board game (like Reversi/Othello). It checks valid directions from a given node, identifies opponent discs to flip, updates the board with the current player's color, switches players, and updates game state and scores by counting each player's discs. | def play(self, node):
new_colors = []
for d in self.DIRECTIONS:
current_node = node + d
while self.is_disc_other_player(current_node):
current_node += d
if self.is_disc_current_player(current_node):
new_colors += node.check(current_nod... |
def is_internet_available():
try:
socket.create_connection(("www.google.com", 80), timeout=5)
return True
except OSError:
return False
def scan_ip(ip):
try:
nm = nmap.PortScanner()
nm._nmap_opt = '-Pn'
common_ports = [21, 22, 80, 443, 8080]
common_scan... | The main task of the code is to continuously monitor internet connectivity, retrieve an IP address from a server, scan it, and submit the results in a loop. It retries every 10 seconds if the internet is unavailable, logs the IP address upon successful retrieval, executes a scan, and submits results, repeating the proc... | def main():
while True:
while not is_internet_available():
logging.warning("No internet connection. Retrying in 10 seconds...")
time.sleep(10)
data = requests.get(f'{BASE_URL}/get_ip').json()
if data.get("ip"):
logging.info(data.get("ip"))
res... |
def read_mails(file_path):
em = []
la = []
em, la = read(file_path[0], em, la, 0)
em, la = read(file_path[1], em, la, 1)
em = clean_text(em)
return em, la
def get_label_index(la):
''' Label the index
label is of the list
return dict object
'''
from collections impor... | The code processes incoming email data by classifying it as spam or ham using a trained Naive Bayes model. It unpickles input data, extracts features, tests against a pre-trained model, stores classification results in Redis using keywords and hash values, and retrieves stored data for verification. The task involves r... | def callback(ch, method, properties, body):
print("Callback function is called!")
obj1, obj2, obj3 = pickle.loads(body)
text = obj1
hashval = obj2
first_Word = text.split(' ', 1)[0]
#print("First Word",first_Word)
print("#"*50)
print("Processing the mail.....")
file_path_legit = os.... |
def data_loader(data_path, split):
FB = pd.read_csv(f'{data_path}/{split}/FB.csv', delimiter=',')
AAPL = pd.read_csv(f'{data_path}/{split}/AAPL.csv', delimiter=',')
TSLA = pd.read_csv(f'{data_path}/{split}/TSLA.csv', delimiter=',')
data = pd.concat((FB, AAPL, TSLA))
data = data.dropna()
# cons... | The main task of the code is to load training and test datasets, train either a logistic regression or perceptron model based on the specified algorithm, and evaluate their performance by calculating and printing training and test set accuracies. | def main(args):
X_train, Y_train = data_loader(args.data, 'Train')
X_test, Y_test = data_loader(args.data, 'Test')
print("number of training data instances: ", X_train.shape)
print("number of test data instances: ", X_test.shape)
print("number of training data labels: ", Y_train.shape)
print("n... |
def deal_hand(n):
"""
Returns a random hand containing n lowercase letters.
ceil(n/3) letters in the hand should be VOWELS (note,
ceil(n/3) means the smallest integer not less than n/3).
"""
hand = {}
num_vowels = int(math.ceil(n / 3))
for i in range(num_vowels - 1):
x = random.... | The main task of the code is to enable a user to play a series of hands in a word game. It prompts for the total number of hands, repeatedly deals a hand, allows the user to modify letters or replay the hand, plays each hand using the play_hand function, accumulates individual hand scores into a total, and finally retu... | def play_game(word_list):
"""
Allow the user to play a series of hands
* Asks the user to input a total number of hands
* Accumulates the score for each hand into a total score for the
entire series
* Call functions play_hand, it returns a score of hand
* Returns the total score for th... |
def print_classic_warning(warnings_point, guesses_point, secret_word, letters_guessed):
'''
If user is playing in classic game, but inputted '*', firstly programme output information
that user is playing in classic game, next time if user will input '*' he/she will lose
one warnings point
'secret_wo... | The function `check_letter` validates user input, updating game state variables. It checks if the input letter is valid (single ASCII character, not previously guessed) or a hint symbol. If invalid, it issues warnings; if valid, it updates guesses and tracked letters. It returns updated warning and guess counts, handli... | def check_letter(letter, warnings_point, guesses_point, secret_word, letters_guessed):
'''
This function check if letter is correct. So letter is correct, if it is acsii_letters, len(letter) is 1 and
letter not in letters_guessed. Additionally, it check that letter is or is not a HINTS_SYMBOL("*")
'secr... |
def is_word_guessed(secret_word, letters_guessed):
'''
secret_word: string, the word the user is guessing; assumes all letters are
lowercase
letters_guessed: list (of letters), which letters have been guessed so far;
assumes that all letters are lowercase
returns: boolean, True if all the le... | The code implements a Hangman game where the user guesses letters of a secret word. It supports two modes: classic Hangman and a version with hints. The game tracks guesses and warnings, checks valid inputs, updates the guessed letters, and displays progress. If hints are enabled, users can request possible matching wo... | def hangman(secret_word, with_hints):
'''
Game Hangman. "request" show hangman(classic) or hangman with hints.
Print information for user, start loop, check user choose hangman or hangman with hints,
Check input letter and call letter_in_word, check if user guessed word.
'secret_word' is random word... |
def gen_batched_data(batch_size, iter, dataset, PAD_IDX = 1):
st = iter * batch_size
ed = min([(iter+1) * batch_size, len(dataset)])
batched_data = dataset[st:ed]
max_input_len = max([len(data[0]) for data in batched_data])
max_output_len = max([len(data[1]) for data in batched_data])
batched_input_id = [... | The code trains a sequence-to-sequence model using gradient accumulation, evaluating periodically on a test set and saving the best model based on perplexity. It processes batches from the training dataset, computes loss with masked NLL, updates parameters, and logs metrics. The model is saved when test perplexity impr... | def train(model,dataset,optimizer,log_path,best_model_pth,batch_size = 64, num_accumulation = 2, steps = 50000, epoch_num = 10):
train_dataset = dataset["train"]
test_dataset = dataset["test"]
iter_num = len(train_dataset) // batch_size
best_ppl = 10000000
best_score = 0
step_count = 0
tota... |
def gen_batched_data(batch_size, iter, dataset, PAD_IDX = 1):
st = iter * batch_size
ed = min([(iter+1) * batch_size, len(dataset)])
batched_data = dataset[st:ed]
max_input_len = max([len(data[0]) for data in batched_data])
max_output_len = max([len(data[1]) for data in batched_data])
batched_input_id = [... | The code trains a language model using neural architecture search (NAS) with unrolled gradient updates, accumulating gradients over multiple batches, and periodically evaluates the model on validation data. It optimizes both model weights and architecture parameters, saving the best model based on perplexity. The train... | def train(model,dataset,test_data,train_data,optimizer,log_path,gen_path,best_model_pth,batch_size = 64, num_accumulation = 2, steps = 50000, epoch_num = 10):
train_dataset = dataset["train"]
test_dataset = dataset["test"]
dev_dataset = dataset["dev"]
iter_num = len(train_dataset) // batch_size
bes... |
def get_instances(self):
"""
gets the sagemaker studio details
Returns:
A dictionary of the domain instances details
Raise:
ClientError of botocore.exceptions
"""
instances_list = self.sagemaker.list_domains()
instances = []... | This code schedules the deletion or stopping of AWS SageMaker domains based on tags and event parameters. It retrieves instances, checks tags to trigger deletion/stop actions, empties domains before deletion, applies retention policies (Delete/Retain), and handles forced deletions if domains aren't empty. It also stops... | def run(self, event):
"""
runs the schedulation
Args:
event (dictionary): aws details
'force' (list): list of services identifier that they have to be forced for deleting
"""
instances = self.get_instances()
for instance in instance... |
def costFunction(self, paraRange, arr, numOfDes):
arr = self.scaling(paraRange, arr)
sf = 0
for i in range(arr.shape[0]):
sf = sf + self.inverse_euclidean_distance(arr[i,:], arr)
nc = self.noncollapsing(paraRange, arr, numOfDes)
return (sf + nc)
def initialSamples(sel... | The main task of the code is to implement a modified Jaya optimization algorithm for multi-parameter optimization. It initializes a population of random solutions within specified ranges, iteratively refines them using the JayaAlgorithm, tracks the best and worst designs, and visualizes the optimal solutions. The proce... | def PerformSJAYA(self, NumOfParameters, ParaRange, save_path=None):
lower_limits = ParaRange[0]
upper_limits = ParaRange[1]
population = np.zeros((self.NumOfDesigns, self.SizeofPopulation,NumOfParameters))
for i in range(self.NumOfDesigns):
SubPopulations = np.zeros((self.Siz... |
def simulate():
# Numerically Solve CURRENT SETUP Using RK4
Y01 = [0, V01, Patm, theta_0]
Y1, t1 = RK4(dY1, Y01, 0, t_end, dt)
w1, _, _, theta1 = Y1
# Re-Compute Burning Surface Area at Every Point in Time
surface1 = angleBurn1(w1, theta1)
# Calculate Thrust at Every Point in Time
F1 = ... | The function `toleranceSensitivity` simulates and compares pressure profiles for three geometric configurations (minimal, nominal, maximal) of a propellant system. It updates global geometry parameters, runs simulations, plots pressure curves (in MPa vs. time), and prints performance characteristics. Config flags deter... | def toleranceSensitivity(geometry_min, geometry_max, config1 = True, config2 = True):
"""Geometry = (Dout, Dport, Lgrain, Lhalf)\n"""
global Dout, Dport, Lgrain, Lhalf
# Nominal Geometry
geometry_nom = data[1]
geometries = [geometry_min, geometry_nom, geometry_max]
labels = ["Minimal", "Nominal... |
def sensV(factors, config1, config2):
global Vadd, data
# Determine Different Vadd's
Vs = np.array(factors)*Vadd
# Store Original Data!
original = data
# For Each, Simulate and Plot Pressure Profile
plt.figure()
ax = plt.axes()
for V in Vs:
# Update Chamber Volume
... | The code defines a sensitivity analysis function that routes input parameters to specific analysis functions (e.g., sensV, sensR) based on the given parameter. It accepts factors, configuration flags (config1/config2), and dispatches to the appropriate sensitivity calculation. If the parameter is unrecognized, it retur... | def sensitivity(parameter, factors, config1 = True, config2 = True):
"""Parameter Options are: Vadd, r0, n, Tc, theta_end, eta_c, Patm, Tatm\n"""
# Determine Which Parameter to Tweak
if parameter == "Vadd":
return sensV(factors, config1, config2)
elif parameter == "r0":
return sens... |
def state_at_waypoint(self):
rospy.loginfo("At waypoint")
#Save time at waypoint
time_at_waypoint = time.time() - self.start_time
data = ["waypoint_" + str(self.goal_cnt+1),time_at_waypoint]
self.save_to_csv(self.time_csv_path,data)
ts = Tag_scan(self.start_time,self.r... | The main task of the code is to handle action server status updates. When status 3 is detected, it transitions to a waypoint state and stops tracking. For status 4, it aborts navigation, logs skipped waypoints, records timestamps in a CSV file, and resumes patrol. The function manages navigation state transitions and d... | def status_cb(self, msg): #
status = self.client.get_state()
#rospy.loginfo(status)
if status == 3:
print("Action_Server_Status: " + str(status))
# rospy.loginfo(" status tree ")
self.client.stop_tracking_goal()
rospy.loginfo("GOING TO WAYPOINT STA... |
def ckeck_params_loaded(self):
if not self.param_fed:
if self.ot_type == "unsupervised":
print("Please feed the unsupervised OT parameters by function 'feed_unsupervised_OT_params'.")
elif self.ot_type == "semi-supervised":
print("Please feed the unsupervi... | The code trains neural networks `u_net` and `v_net` for optimal transport (OT) using source and target datasets, with optional paired data for semi-supervised learning. It initializes data loaders, sets up an Adam optimizer, and iteratively computes OT losses (`dual_semi_supervised_OT_loss` or `dual_unsupervised_OT_los... | def train(self,source_dataset,target_dataset,paired_dataset = None, batch_size=64,num_workers=0,
lr=1e-6,num_train_steps=100000,save_interval=10000,save_dir = "exp/OT/models"):
'''
Training the potentials u_net, v_net.
'''
self.ckeck_params_loaded()
###### building ... |
def pausePlayShow(self):
# print(Function - pausePlayShow(self)')
# variable playingStatus in paused mode is == False.
if self.playingStatus:
self.mStrCmd = 's'
self.playingStatus = False
# Setting widgets to let user the app is paused.
self.setBtnsImgsDirection()
def playShowDriver(self):
# prin... | The main task of the code is to handle directory selection for image display, pause/resume functionality, and UI updates. It pauses the app, prompts for a directory, cancels or processes the selection, updates image data, sets display direction, swaps images, and adjusts button styles and widget states accordingly. | def setDirectorio(self):
# print('Function - setDirectorio()')
# Setting the app in paused mode.
self.pausePlayShow()
# Getting the directory path.
self.strPath = dirName = tk.filedialog.askdirectory()
# if block to handle the cancelation of directory selection.
if dirName == '':
if self.playingStat... |
def nextPicture(self):
# print('Function - nextPicture(self)')
# if statement to set the application movement forward.
if self.imgNamesSize >= 1:
# Changing the play text only if app mode is not in pause mode.
if self.nextBackMode == False:
self.nextBackMode = True
self.forWardBtn["style"] = "gre... | The main task of the code is to delete an image file when the app is paused, handling error cases such as invalid indices, missing files, or OS errors. It updates the UI by displaying warnings, adjusting the image list, and navigating to the next/previous image if deletion succeeds. The function ensures deletion only o... | def deletePicture(self):
# print('Funcion - deletePicture()')
if self.playingStatus == True:
# Talvez poner un warnig al user.
print("To delete a picture set the app on Paused Mode.")
# else block to actually delete the image file.
else:
# Getting the image list size from the control class.
self.... |
def get_moves(self):
"Returns the number of moves left"
return self.moves
def get_player(self):
"Returns the player instance"
return self.player
def print_help(self, additional=False):
"""
Prints help for main game loop
Uses additional parameter for printing more ... | This function handles a move in the main game loop by updating the player's status, managing energy boosts when halfway to the treasure, processing player input (status, look, help), and controlling game progression. It checks moves remaining, triggers energy restoration at 5 moves, processes user choices, and either a... | def handle_move(self):
"Handles a move in the main game loop"
if self.get_moves() > 1:
print(f'According to your map, you are {self.get_moves()} moves away from the treasure.')
else:
print('According to your map, you are only 1 move away from the treasure!')
# In... |
def print_header(self):
"Prints header for a game instance"
print('\n' + ('-'*29))
print('Welcome to my Adventure Game!')
print('-'*29)
def set_up_player(self):
"Sets up the player instance for a game"
while True:
name = input('\nWhat is your name (<enter> to ... | This code runs an Adventure Game instance by initializing the game, handling player moves, managing game state, and ending the game when conditions are met. It processes player actions in a loop, decrements moves, handles treasures when moves are exhausted, and manages game-over states. | def run(self):
"Runs an instance of the Adventure Game"
self.print_header()
self.set_up_player()
self.print_intro()
while not self.is_game_over():
if self.get_moves() >= 1:
self.handle_move()
self.decrement_moves()
else:
... |
def read_config():
config_path = "config.ini"
config = configparser.ConfigParser()
try:
config.read(config_path)
except FileNotFoundError:
logging.exception("There is no config file named config.ini")
else:
RADIUS_FACTOR = config.getfloat("Parameters", "RADIUS_FACTOR")
... | The main task of the code is to process asteroid observation data based on user inputs (asteroid list, date, location), filter visibility during nighttime, calculate celestial positions, and return a structured JSON response with details like status, observation times, and positional data for each asteroid. It uses ast... | def main():
(
RADIUS_FACTOR,
MAX_STARS,
MAX_DISTANCE,
QUERY_STARS_LIMIT,
MIN_DEG,
STEP_SIZE,
) = read_config()
status = 200
Gaia.ROW_LIMIT = int(QUERY_STARS_LIMIT)
data = request.get_json()
asteroid_names = data.get("asteroid_list").split(", ")
... |
def _5_and_3_in(self, number: int) -> bool:
return self._5_in(number) and self._3_in(number=number)
def _is_divisible_by_5(self, number: int) -> bool:
return number % 5 == 0
def _is_fizz_buzz(self, number: int):
return self._5_and_3_in(number) or self._is_divisible_by_5_and_3(number=number)
def ... | The code converts an integer into a string representation based on divisibility rules. It checks if the number is divisible by 3, 5, both, or neither, returning 'Fizz', 'Buzz', 'FizzBuzz', or the number itself as a string, with additional logic for specific combined conditions. | def convert(self, number: int) -> NumberString | Fizz | Buzz | FizzBuzz | FizzBuzzBuzz:
if self._5_and_3_in(number) and self._is_divisible_by_5(number=number):
return FizzBuzzBuzz()
if self._is_fizz_buzz(number=number):
return FizzBuzz()
if self._is_fizz(number=number):
... |
def on_session_started(session_started_request, session):
""" Called when the session starts.
One possible use of this function is to initialize specific
variables from a previous state stored in an external database
"""
pass
def on_launch(launch_request, session):
""" Called when the u... | This code defines an AWS Lambda handler for an Alexa skill, routing incoming requests (LaunchRequest, IntentRequest, SessionEndedRequest) to appropriate functions. It initializes new sessions, processes launch requests, handles user intents, and manages session endings, acting as a dispatcher for Alexa interaction even... | def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
if event['session']['new']:
on_session_started({'requestId': event['request']['requestId']},event['session']... |
def strToVector(str):
out = tuple(map(float, str.split(',')))
return out
def MR_kCenterOutliers(points, k, z, L):
#------------- ROUND 1 ---------------------------
# Partition into L coresets
round_1_start = time.time() # default_timer()
coreset = points.mapPartitions(lambda iterator: extrac... | The code implements a MapReduce solution for the k-center clustering problem with outliers using Apache Spark. It reads input points from a file, initializes Spark configuration, partitions data, and applies the MR_kCenterOutliers algorithm to find k centers while allowing z outliers. It then calculates the objective f... | def main(argv):
# Checking number of cmd line parameters
assert len(argv) == 5, "Usage: python Homework3.py filepath k z L"
# Initialize variables
filename = argv[1]
k = int(argv[2])
z = int(argv[3])
L = int(argv[4])
start = 0
end = 0
# Set Spark Configuration
conf = Spark... |
def add_availability(self, cmd: CreateAvailabilityCommand):
availability = self.find_availability(cmd.available_at)
if availability:
raise AvailabilityExistsException(f"Availability {cmd.available_at} for user {self.user_id} exists already")
availability = Availability(available_at=cmd.available_at, ... | The `replay_events` method processes a list of events to reconstruct system state by applying each event's command. It extracts common data (correlation_id, user_id, available_at) and dispatches events to specific handlers: creating/deleting availability or appointments via corresponding commands. After processing all ... | def replay_events(self):
for event in self.events:
self.user_id = event.user_id
self.version = event.version
data = event.event_payload
common = {"correlation_id": event.correlation_id, "user_id": event.user_id, "available_at": data["available_at"]}
if event.event_type == AvailabilityC... |
def peek(tokens):
return tokens[0]
def parse_number(context):
tokens = context.tokens
nr = int(peek(tokens).tok, context.base)
if nr >= -0x80000000 and nr <= 0xffffffff:
token = tokens.pop(0)
return Nr(token.tok, [token], nr)
else:
raise CompileError("number isn't within rang... | This code compiles a definition from tokens, handling control structures (if, while, etc.) by parsing tokens into labels, branches, and instructions. It processes tokens sequentially, managing nested branches and loops via stacks, and constructs a 'Word' object representing the compiled definition, which is added to th... | def colon_compile(context):
words = []
tokens = context.tokens
definition = [tokens.pop(0), tokens.pop(0)]
name = definition[1].tok
branch_stack = []
if_stack = []
next = peek(tokens).tok
while next != ";":
try:
words.append(parse_number(context))
next = ... |
def peek(tokens):
return tokens[0]
def parse_number(context):
tokens = context.tokens
nr = int(peek(tokens).tok, context.base)
if nr >= -0x80000000 and nr <= 0xffffffff:
token = tokens.pop(0)
return Nr(token.tok, [token], nr)
else:
raise CompileError("number isn't within rang... | This function parses tokens from a context, attempting to interpret them as numbers or dispatching to specific handlers based on token type (e.g., 'hex', ':', '(', 'constant', etc.), with error handling for number parsing failures and conditional execution of parsing operations. | def parse_token(context):
tokens = context.tokens
next = peek(tokens)
token = next.tok
try:
context.stack.append(parse_number(context))
return
except ValueError:
pass
if token == 'hex':
tokens.pop(0)
context.base = 16
elif token == ':':
colon... |
def tokenize(file):
tokens = []
with open(file) as fp:
line = fp.readline()
count = 1
while line:
things = line.split()
[tokens.append(Token(x, count)) for x in things]
line = fp.readline()
count += 1
return tokens
def parse(tokens):
... | This code compiles a high-level Forth-like language into assembly. It parses command-line arguments for input file and output path, tokenizes the input, parses tokens into a context, then converts this context to assembly code and writes it to the specified output file. The output defaults to the input filename with a ... | def main():
parser = argparse.ArgumentParser(description='high-level Forth word compiler')
parser.add_argument('file', help='The file that needs to be compiled')
parser.add_argument('-o', default="",
help='the output file')
args = parser.parse_args()
out = os.path.splitext(os... |
def get_coords(elem, options, ret):
lon = elem.longitude
lat = elem.latitude
if options['fix_coord_chars'] == True:
lon = fix_coord_chars(lon)
lat = fix_coord_chars(lat)
ret["coordinates"] = check_coord_format(lon, lat, options)
def get_address(elem, required_lang):
ret = []
street_lang = False
... | The function `get_locations` processes institutional locations from input data, generating structured dictionaries with attributes like `locationid`, coordinates, names (with language tags), address, SSID, encryption level, AP number, and tags (e.g., port restrictions, IPv6). It organizes data into a list, applying def... | def get_locations(root, options, inst_name):
ret = []
idx = 1
for i in root.institution.location:
loc_id = inst_name + str(idx).zfill(3)
loc = { "locationid" : loc_id }
idx += 1
# coords
get_coords(i, options, loc)
loc['stage'] = config.default_stage
loc['type'] = config.default_loc... |
def get_inst_type(elem):
if elem == 1:
return "IdP"
elif elem == 2:
return "SP"
return "IdP+SP"
def get_inst_realm(root, inst_type, data):
if inst_type == "SP": # SP
if hasattr(root.institution, 'inst_realm'): # this part does not strictly follow the spec: "for type SP no realm... | This function extracts and structures data from an institution's XML (or similar) data into a dictionary. It populates fields like institution ID, type, name, address, contact details, policies, and timestamps, using default values where needed. It handles optional fields, processes location data, and converts timestam... | def get_data(root, filename, options):
ret = {}
required_lang = "en" # language required for some fields
ret["instid"] = ".".join(filename.split(".")[:-1]) # instid
ret["ROid"] = config.ROid # ROid
ret["type"] = get_inst_type(root.institu... |
def read_xml(filename):
data = lxml.objectify.parse(filename)
return data
def to_json(data, filename):
with open(filename.replace(".xml", ".json"), 'w') as f:
f.write(json.dumps(data, default=to_serializable))
def get_data(root, filename, options):
ret = {}
required_lang = "en" ... | The code converts an XML file into a JSON format. It reads the XML from the input directory, processes its root element with custom options, extracts relevant data, and writes the resulting JSON to the specified output directory with the same filename. | def convert(input_dir, filename, output_dir, options):
contents = read_xml(input_dir + filename) # read xml with objectify
root = contents.getroot() # get root element
to_json(get_data(root, filename, options), output_dir + filename) |
def reconcile_sequences(self, line_type, index):
"""Called during initialization of each of the nonogram's sequences. If the cell that marks the intersection between two sequences is known in one sequence and unknown in the other, updates the sequence in which the cell is unknown."""
opp_line_type = "ro... | The code initializes a puzzle solver by processing row and column clues, setting up sequences for possible solutions, tracking known solution sets, and identifying unsolved elements. It processes each clue into a Sequence object, reconciles sequences, filters those with limited solutions (1–50), and updates unsolved el... | def __init__(self, clues):
self.max_solutions_to_find = 50
self.width = len(clues[0])
self.height = len(clues[1])
self.sequences = {"row":dict(), "col":dict()}
self.known_solution_sets = list()
self.unsolved = set()
for i, line_type in enumerate(("col", "row")):
... |
def fit_slices(histo, x_range, x_bin_step):
x_start = histo.GetXaxis().FindBin(x_range[0])
x_stop = histo.GetXaxis().FindBin(x_range[1])
x_values = array('d')
slices = []
fits = []
for i, x_bin in enumerate(range(x_start, x_stop + 1, x_bin_step)):
projec = histo.ProjectionY(histo.GetT... | The code generates a multi-subplot figure comparing fitted data from two configurations (config1 and config2) across six sectors. It plots error bars for mean values (mu) with standard deviations (sig), removes outliers, adds reference lines, grids, and legends, then saves the visualization as a PDF. The function proce... | def plot_fits_mpl(histos1, histos2, config1, config2,
x_range, x_bin_step, title_formatter,
save_name, y_range=None, title=None,
xtitle=None, ytitle=None, max_errorbar=0.5):
fig = plt.figure(figsize=(12,16))
# Plot options for each type.
opts1 = {... |
def draw_click_area_blank(self):
self.screen.fill(self.backgroundcolor, self.rect)
def approachX1ToCenter_x7(self):
#increment x param if needed
if self.centerx1_adj > self.centerx \
and abs(self.centerx1_adj - self.centerx) > int(self.slope1CorrectionParam * 100):
se... | This function adjusts coordinates in stages to align with a center. It checks if adjusted coordinates differ from target values, triggering recalculations and updates if thresholds are exceeded. Stage 1 aligns positions, while Stage 2 verifies slope adjustments. Once both stages complete, it transitions to state 'x' an... | def drawing_click_area_x7(self):
if not self.stage1_x_done:
if abs(self.centerx1_adj - self.centerx) > (self.slope1CorrectionParam * 100) \
or abs(self.centery1_adj - self.centery) > (self.slope1CorrectionParam * 100) \
or abs(self.centerx2_adj - self.centerx)... |
def createClickAreas(game_screen, g_set, g_stats):
areasList = []
for horizontal in range(3):
for vertical in range(3):
#creating 9 ClickAreas based on RELATIVE coordinates (corelated to the whole board)
areasList.append(ClickArea((horizontal * g_set.x1, vertical * g_set.y1), gam... | The code initializes a Pygame game, sets up game settings, screen, and components like a message board and clickable areas. It runs a loop handling game states: waiting for input, drawing areas, or checking for a win. It updates the screen, processes events, switches turns when needed, and ensures game flow by toggling... | def run_game():
pygame.init()
clock = pygame.time.Clock()
g_set = Settings(boardwidth=300, boardheight=600, message_board_height=50)
g_stats = Stats(g_set)
game_screen = pygame.display.set_mode((g_set.game_screen_width,
g_set.game_screen_height + g_set.mess... |
def __parse_time_signature(self):
length = self.__parse_variable_length_int()
nn = self.__readbyte()
dd = self.__readbyte()
cc = self.__readbyte()
bb = self.__readbyte()
data = {"numerator": nn, "denominator": 2**dd, "cc": cc,
"bb": bb}
return Meta... | This method parses MIDI meta events by identifying the event type from the file and delegating to specific parsing functions for time signatures, key signatures, tempo settings, or a default handler for other meta events. | def __parse_meta_event(self):
type = self.midi_file[self.offset]
self.offset += 1
if type == TIME_SIGNATURE_CODE:
return self.__parse_time_signature()
elif type == KEY_SIGNATURE_CODE:
return self.__parse_key_signature()
elif type == SET_TEMPO_CODE:
... |
def __parse_sysex_event(self):
length = self.__parse_variable_length_int()
data = self.midi_file[self.offset:self.offset + length]
self.offset += length
return SysexEvent(data=data)
def __parse_meta_event(self):
type = self.midi_file[self.offset]
self.offset += 1
... | This function parses MIDI events by checking the status byte at the current offset. If the status byte is 0xF0/0xF7, it parses a SysEx event; if 0xFF, a meta event; otherwise, a standard MIDI event. It increments the offset and delegates parsing to respective methods based on event type. | def __parse_event(self):
statusbyte = self.midi_file[self.offset]
if (statusbyte == 0xF0 or statusbyte == 0xF7):
self.offset += 1
return self.__parse_sysex_event()
elif (statusbyte == 0xFF):
self.offset += 1
return self.__parse_meta_event()
... |
def on_init(self):
pygame.init()
self.GIFmode = GIFMode()
self.GIFmode.isActive = True
self.GradientMode = GradientMode()
self.GradientMode.isActive = False
self.on_setScreenSize()
pygame.mouse.set_visible(False)
def on_event(self, event):
if event.type ==... | The code defines a game loop that initializes the game, processes events, updates game logic, renders graphics, and cleans up resources. It first checks if initialization succeeds; if not, it exits. While running, it handles events, calls update/logic methods, renders frames, and continues until `running` is set to Fal... | def on_execute(self):
if self.on_init() is False:
self.running = False
while(self.running):
for event in pygame.event.get():
self.on_event(event)
self.on_loop()
self.on_render()
self.on_cleanup() |
def read_gis_data(self, fname):
''' Load GIS data on residential buidlings from a file '''
with open(fname, 'r') as fin:
# Skip the header
next(fin)
for line in fin:
temp = {}
line = line.strip().split()
# Common infor... | This code initializes a class to generate individual households from census and GIS data. It processes input files (residential data, type mappings, and multiunit statistics) to create household structures, distinguishing between single-unit and multiunit buildings. The class stores household data, building information... | def __init__(self, n_tot, fres, res_map=None, funit=None):
''' Generate individual households from input data '''
#
# Household is defined as a single living unit
# fr_vacant will not be occupied but will be stored and reported
#
# n_tot - total number of households accor... |
def create_channel(i):
name = f"channel{i}"
viewers = random.randint(500, 2000000)
viewing_time = random.randint(30, 80)
return TVchannel(name, viewers, viewing_time)
def rate_channel(channel):
if channel.viewers >= 1500000:
return "Rank 1-Excellent"
elif channel.viewers >= 1000000:
... | The code defines a menu-driven TV channel application allowing users to create 10 channels, rate them, visualize sorting algorithms, or exit. It maintains a channel list, generates channels with unique IDs, rates each channel, and plots sorting algorithms when selected. The loop handles user choices until exit is selec... | def app_menu():
Channels = []
while True:
print("\nTV Channel App")
print("1. Create 10 Channels")
print("2. Rate Channels")
print("3. Plot Sorting Algorithms")
print("4. Exit")
choice = input("Enter Your choice: ")
if choice == "1":
for i in ... |
def get_work_dir():
# Get the current subfolder you will be working in
loc = input("Folder to create subfolders in: ")
working = path + '/' + loc
if not os.path.exists(working):
os.makedirs(working)
return working
def create_folders(working):
# Create specified number of folders in previ... | The main task of the code is to set up a directory structure by creating folders, optionally copying example files and replacing placeholder text in HTML files, then asking if the folders should be zipped. It interacts with the user to determine actions like copying files, replacing text, and zipping, executing corresp... | def main():
working = get_work_dir()
folders = create_folders(working)
if input("Copy files from examples? [y/n] ") == 'y':
copy_files(folders, working)
# There's only text to replace if we're using examples
if input("Replace all placeholder text in files? [y/n] ") == 'y':
... |
def make_path(self, phase, type):
name = phase+'_'+type
return os.path.join(config.DATA_PATH, name)
def clean_data(self, df):
cols = ['Headline', 'articleBody']
print('Cleaning Data...')
for col in cols:
col_name = 'tokenized_'+col
df[col_name] = df[col].a... | The main task of the code is to generate word2vec features for headlines and article bodies from a DataFrame. It checks if precomputed features exist; if not, it cleans data, loads a word2vec model, and constructs features as vectors (for MLP) or matrices (for LSTM). Features are saved as a pickle file and returned as ... | def extract_word2vect_features(self, df, name):
feature_path = self.make_path(name, self.network+'_w2v_feature_matrix')
if not os.path.exists(feature_path):
df = self.clean_data(df)
headlines = df['tokenized_Headline'].values.tolist()
articles = df['tokenized_articleB... |
def extract_bert_features(self, df, phase):
bert_feature_path = self.make_path(phase, 'lstm_bert_feats')
if os.path.exists(bert_feature_path):
df = pd.read_pickle(bert_feature_path)
bert_feats = df[['Headline_sentences', 'article_sentences']]
else:
model = Sen... | The code extracts text features from a DataFrame using BERT or word2vec, concatenates them with optional cosine similarity features, retrieves stance labels (mapped from 'Stance' column), and returns both as numpy arrays for model input. | def extract_features(self, df, name):
if self.use_transformers:
text_feats = self.extract_bert_features(df, name)
if self.network == 'mlp':
headlines = [x.mean(axis=0) for x in text_feats[:, 0]]
articles = [x.mean(axis=0) for x in text_feats[:, 1]]
... |
def get_quantity():
quantities = [1,2]
quantity = random.choice(quantities)
return quantity
def get_tense():
tenses = ["past","present","future"]
tense = random.choice(tenses)
return tense
def get_random_sentence(quantity, tense):
random_sentences = [1,2]
random_sentence = random.choice(... | This program generates sentences based on user input. It offers random sentences or lets users specify sentence length (short/long), quantity (singular/plural), and tense (past/present/future). The loop continues until the user declines, providing tailored sentences using predefined functions for determiners, nouns, ve... | def main():
follow = ""
print("I am a program that generates sentences.")
print()
while follow.lower() != "no":
print()
quantity = get_quantity()
tense = get_tense()
random_sentence = get_random_sentence(quantity, tense)
random_or_not = input ("Would you like a ra... |
def bearish_patterns_for_index_zero(cur_cand, idx: int) -> int:
if shooting_star(cur_cand) == -1:
# print(f"shooting star: {idx}")
return -1
elif black_marubozu(cur_cand) == -1:
# print(f"black marubozu: {idx}")
return -1
def bullish_patterns_for_index_zero(cur_cand, idx: int) ->... | This function identifies and labels each candlestick pattern in a DataFrame as bearish (-1) or bullish (1). It checks the first row using specialized zero-index pattern functions, then compares each subsequent row with its predecessor using different pattern detection logic. The results are stored in a new 'candle_patt... | def mark_candle_pattern_column(df):
for idx, row in df.iterrows():
cur_cand = df.iloc[idx]
if idx == 0:
if bearish_patterns_for_index_zero(cur_cand, idx) == -1:
df.at[df.index[idx], "candle_pattern"] = -1
elif bullish_patterns_for_index_zero(cur_cand, idx) == ... |
def init_scale():
scale_ok = scale_up();
if (scale_ok == 1):
print("##### Autoscaler initialized #####");
else:
print("Could not meet requirements");
def infaas_select_model():
global slo_latency, slo_accuracy,latency_margin
candidate_models = []
for itr in range(len(model_lat_list)):
if model_lat_list... | This code performs autoscaling to meet Service Level Objectives (SLOs) for accuracy, latency, and cost while evaluating model prediction accuracy through majority voting and weighted voting strategies. It dynamically scales instances up/down based on global accuracy metrics, tests model ensembles against a baseline, tr... | def main():
global inst_list, current_latency, current_cost, infaas, matched, BLmatch, not_matched, step_matching_pred,weights
print('main invoked',slo_accuracy,slo_latency,slo_cost)
if scheme == "infaas":
infaas = True
signal(SIGINT, handler)
time_Scale = 1
init_scale();
if infaas:
return infaas_select_mo... |
def graph_reverse(adj):
adj_r = [[] for _ in range(n)]
for i in range(len(adj)):
for v in adj[i]:
adj_r[v].append(i)
return adj_r
def dfs(adj):
pre = [[0, i] for i in range(len(adj))]
post = [[0, i] for i in range(len(adj))]
visited = [False for _ in range(len(adj))]
cloc... | This code counts the number of strongly connected components (SCCs) in a directed graph using Kosaraju's algorithm. It first reverses the graph, performs a DFS to determine node finishing times, then processes nodes in reverse finishing order on the original graph, incrementing the component count each time a new unvis... | def number_of_strongly_connected_components(adj):
result = 0
adj_rev = graph_reverse(adj)
pre, post = dfs(adj_rev)
post = sorted(post, key=lambda x: x[0], reverse=True)
visited = [False for _ in range(len(adj))]
for vertex in post:
if not visited[vertex[1]]:
explore(adj, visi... |
def GetQ(self):
return self.q
def sift_up(self, i: int):
q = self.GetQ()
parent = PriorityQueue.GetParent(i)
while i > 0 and q[i][0] < q[parent][0]:
q[i], q[parent] = q[parent], q[i]
self.map[q[i][1]] = i
self.map[q[parent][1]] = parent
i =... | The main task of the code is to remove the element at index `i` from a priority queue by setting its priority to negative infinity, then restoring the heap property via `sift_up`, and finally extracting the minimum element to effectively delete the target element. | def remove(self, i):
q = self.GetQ()
q[i][0] = -math.inf
self.sift_up(i)
return self.extract_min() |
def validate_workflow_path(self, workflow_path):
"""Validate existence of files and directories in workflow path."""
workflow_path = Path(workflow_path)
if not workflow_path.exists():
raise FileNotFoundError(
f"workflow path, {self.workflow_path}, does not exist"
... | This code initializes a workflow test environment by validating input paths, loading configuration parameters from a YAML file, setting up working directories, and generating environment matrices and neurodocker specifications for testing. It prepares the infrastructure to execute and evaluate workflow tests with speci... | def __init__(self, workflow_path, working_dir=None, tmp_working_dir=False):
if WorkflowRegtest._etelemetry_version_data is None:
WorkflowRegtest._etelemetry_version_data = check_latest_version()
self.workflow_path = self.validate_workflow_path(workflow_path)
self.working_dir = self.... |
def parse(*args):
parser = argparse.ArgumentParser(description="Data fetcher from Gharchive")
parser.add_argument('--year', type=int, required=True)
parser.add_argument('--month', type=int, required=True)
parser.add_argument('--day', type=int)
parser.add_argument('--directory', help='Place to put d... | The main task of the code is to parse command-line arguments for downloading data based on specified dates (year, month, day) and a target directory. It sets up logging for debugging, creates the directory if it doesn't exist, and triggers either `download_day` (for specific day data) or `download_month` (for monthly d... | def main():
logging.getLogger().setLevel(logging.DEBUG)
args = parse(sys.argv[1:])
year = args.year
month = args.month
day = args.day
directory = args.directory
logging.debug("Download started")
if directory is not None and not os.path.exists(directory):
os.makedirs(directory... |
def get_today_file():
try:
file_name = f'./../database/{date_to_number()}.csv'
if not os.path.exists(p(file_name)):
with open(p(file_name), 'w') as f:
f.write('S.No.,Test No.,Yellow,Dark Green,Medium Green,Light Green,Brown\n')
return file_name
except OSError ... | The function `add_new_entry` appends a formatted data entry to a daily log file. It retrieves an index, generates a test number, converts data to a string, and writes the result to the file. It updates the index afterward and returns `True` on success or an `OSError` if writing fails. | def add_new_entry(data):
try:
file_name = get_today_file()
index = get_index()
response = f'{index},{get_test_number(index)},{",".join(mapToStr(data))}\n'
with open(p(file_name), 'a') as f:
f.write(response)
update_index()
return True
except OSError as... |
def parse_data(data):
digits_list = []
display_list = []
for line in data.split("\n"):
digits, display = line.split("|")
digits = [d for d in digits.split()]
display = [d for d in display.split()]
digits_list.append(digits)
display_list.append(display)
return digi... | The code processes input data to count occurrences of digits 1, 4, 7, and 8 in output values (Part 1) and calculates the sum of all decoded output numbers (Part 2). It reads input text, parses digit-display mappings, and applies two distinct analytical tasks to derive and print the results. | def main():
data = data_folder.joinpath("input.txt").read_text()
digits_list, display_list = parse_data(data)
print("Part 1")
n_digit_appearances = count_digit_appearances(digits_list, display_list)
print(f"In the output values, the digits 1, 4, 7, or 8 appear {n_digit_appearances} times.")
pri... |
def parse_data(data):
height_map = [[int(d) for d in line] for line in data.split("\n")]
height_map = np.array(height_map, dtype=int)
return height_map
def compute_risk_level_sum(height_map):
rows, cols = find_low_points(height_map)
low_points = height_map[rows, cols]
return np.sum(low_points + ... | The code reads a heightmap from a file, computes the sum of risk levels for all low points (Part 1), and calculates the product of the three largest basin sizes (Part 2). It processes input data, parses it into a 2D grid, and applies algorithms to identify low points and basins, then outputs the results. | def main():
data = data_folder.joinpath("input.txt").read_text()
height_map = parse_data(data)
print("Part 1")
risk_level_sum = compute_risk_level_sum(height_map)
print(f"The sum of the risk levels of all low points on the heightmap is {risk_level_sum}")
print()
print("Part 2")
basin_p... |
def get_fit_step(img_shape, frame_shape, min_box):
fit_h, inter_h = calcule_fit_step(img_shape[0], frame_shape[0], min_box[0])
fit_w, inter_w = calcule_fit_step(img_shape[1], frame_shape[1], min_box[1])
return (fit_h, fit_w), (inter_h, inter_w)
def cope_with_labels(img_crop, label, x0, y0, shape, need_... | The code crops an image into smaller regions based on a grid defined by `frame` and `min_box`, adjusts labels within each crop, applies blurring if specified, and returns a list of cropped image-label pairs. | def crop_function(img, label, frame, min_box, need_blur, threshold):
fit, inter = get_fit_step(img.shape, frame, min_box)
frames = []
for i in range(fit[1] + 1):
for j in range(fit[0] + 1):
x0 = i*frame[1] - inter[1]*i
x1 = (i+1)*frame[1] - inter[1]*i
y0 = j*fra... |
def process(self):
self.centroids = [self.data[i] for i in random.sample(range(0, self.dataset_size), self.clusters_number)]
self.mews = numpy.zeros([self.dataset_size, self.clusters_number])
for i in range(100):
for data_number in range(self.dataset_size):
for cluste... | The main task of the code is to iterate through cluster numbers 1 to 10, calculate clustering costs for each configuration, store the results in a list, and visualize the cost trends. It progresses by updating cluster counts, processing data, recording costs, and finally plotting the accumulated cost values. | def run(self):
for cn in range(1, 11):
print(f"progress: {cn}")
self.clusters_number = cn
self.process()
# for data_number in range(self.dataset_size):
# print(self.mews[data_number])
# self.plot_data()
self.costs.append(sel... |
def initial_patients(self):
peeps = []
append = peeps.append
cuminitials = np.cumsum(np.round(self.ninitialPatients))
for i in range(cuminitials[2]):
# assign properties according to category of initial patients
if i < cuminitials[0]: # ECMO patients
... | The code simulates healthcare resource usage over time, tracking available resources, medication consumption, and consultations. It initializes patients, processes arrivals, updates resource states (with special handling for non-depletable resources like ECMO/ventilators), and records data for each time step. The simul... | def run_sim(self):
# Initialize time vector of consultations
consultations = []
# Set up available resources
resources = defaultdict(list)
medication = defaultdict(list)
for r in Resources:
resources[r.name] = [self.availableResources[r.name]]
for m i... |
def get_location_hours_dict(self):
"""
Queries Redshift for each location's current regular hours and returns a map
from (branch_code, weekday) to (regular_open, regular_close)
"""
self.redshift_client.connect()
raw_hours = self.redshift_client.execute_query(
... | The code's main task is to execute a data pipeline by retrieving location hours from Redshift, fetching and processing all sites' data between specified dates, recovering previously unhealthy data from a prior date range, and managing client connections (S3/Kinesis) based on configuration flags. It logs progress and en... | def run(self):
"""Main method for the class -- runs the pipeline"""
self.logger.info("Getting regular branch hours from Redshift")
self.shoppertrak_api_client.location_hours_dict = self.get_location_hours_dict()
all_sites_start_date = self._get_poll_date(0) + timedelta(days=1)
a... |
def contains(self, name: str):
return name in self.__parameters.keys()
def set(self, name: str, value, type = None):
if re.match(self.__PARAMETER_EXPRESSION, name) and self.contains(name):
self.__validate_value(name, value)
self.__parameters[name] = value
return value
raise Exception('nam... | This code either updates an existing key-value pair or adds a new one to a data structure. If the key 'name' exists, it calls 'set' to update the value; otherwise, it uses 'add' to insert the new key-value pair. The method ensures data consistency by checking existence before modifying or inserting data. | def setadd(self, name: str, value):
if self.contains(name):
return self.set(name, value)
else:
return self.add(name, value) |
def load_dataset_UI():
button_status = False
dataset_dict = {}
emp_st= st.empty()
dataset_name = st.radio("Datasets on which analysis can be done",('Compas(ProPublica recidivism)', 'German credit scoring', 'Adult census income'))
if(dataset_name == "Adult census income"):
st.write("Classifie... | This code creates a Streamlit web app for a data bias mitigation workflow. It provides a sidebar menu to navigate between loading datasets, visualizing bias, selecting debiasing algorithms, and viewing results. The app uses a global dataset dictionary to pass data between steps, allowing users to analyze bias in datase... | def load_data_pipeline():
st.title("Data Bias Mitigation Demo")
a = st.sidebar.empty()
options = ['Datasets for Analysis', 'Visualise Data Bias','Debias Algorithm', 'Debias Results']
My_Page = a.radio('De-biasing work Flow', options)
global Dataset_Dict1
Dataset_Dict1 = {}
if My_Page == 'Da... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.