dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def generateLargePrime(keysize = 1024):
while True:
num = random.randrange(2**(keysize-1), 2**(keysize))
if isPrime(num):
return num
def gcd(a, b):
while a != 0:
a, b = b % a, a
return b
def findModInverse(a, m):
if gcd(a, m) != 1:
raise ValueError
u1, u2, u3 ... | The function generates RSA public and private keys. It creates two large primes (p, q), computes n = p*q, selects an exponent e coprime to φ(n) = (p-1)(q-1), calculates the modular inverse d of e, and returns keys as hex-encoded tuples (n, e) and (n, d). | def rsaGenerateKey(keySize):
keySize = keySize/2
# Step 1: Create two prime numbers, p and q. Calculate n = p * q.
p = generateLargePrime(keySize)
q = generateLargePrime(keySize)
n = p * q
# Step 2: Create a number e that is relatively prime to (p-1)*(q-1).
while True:
e = random.ran... |
def promptWithSingleKeyResponse(promptStr, validKeyListStr):
while True:
if sys.version_info.major == 2:
key = raw_input(promptStr)
else:
key = input(promptStr)
key = key.upper()
if key and validKeyListStr.upper().find(key) != -1:
return key
def ge... | This function checks if a file exists at the specified path. If it does, it handles the situation based on the 'ifexists' argument (skip/overwrite/uniquename/exit/prompt). It may prompt the user for action, generate a unique filename, skip processing, or exit the application, returning the adjusted path/filename or Non... | def checkIfFileExistsAndHandle(pathAndFilename):
if g.args['ifexists'] != 'overwrite' and os.path.exists(pathAndFilename):
if g.args['ifexists'] == 'prompt':
g.applog.info("\"{:s}\" exists".format(pathAndFilename))
#
# note that if the user takes too long to respond the M... |
def splitPath(pathWithFilename, fConvertToAbsolutePathBeforeSplit=True):
if fConvertToAbsolutePathBeforeSplit:
pathWithFilename = os.path.abspath(pathWithFilename)
(path, filenameWithExt) = os.path.split(pathWithFilename)
(root, extension) = os.path.splitext(filenameWithExt)
return (path, root, ... | This code generates output filenames and paths for video processing based on user-defined settings, handling cases for combining clips or individual outputs. It constructs filenames using specified formats, selects appropriate directories (scratch/output), replaces container extensions if specified, checks for file con... | def __init__(self, videoSourceFile, outputNameSpecDict):
#
# first split the source filename into its path, filename, and extension
#
(path, root, extension) = splitPath(videoSourceFile.filename)
if extension and extension[0] == '.': # remove leading period in extension
... |
def splitPath(pathWithFilename, fConvertToAbsolutePathBeforeSplit=True):
if fConvertToAbsolutePathBeforeSplit:
pathWithFilename = os.path.abspath(pathWithFilename)
(path, filenameWithExt) = os.path.split(pathWithFilename)
(root, extension) = os.path.splitext(filenameWithExt)
return (path, root, ... | The main task of the code is to combine multiple video clips into a single output file using FFmpeg. It determines the output filename, directory, and container format, checks for existing files, generates a FFmpeg input list, executes the concatenation, and handles cleanup. It also logs results and manages temporary f... | def combineOutputClips(outputClipFileList, group, outputNameSpecDict, groupSourceDirectory):
(firstFilePath, firstFileRoot, firstFileExtension) = splitPath(outputClipFileList[0].filename)
outputNameSpec = g.args['outputnamespec']
if not outputNameSpec:
# no user-specified outname name spec. use de... |
def displayAppBanner():
g.applog.minimal("\n{:s} v{:s} - Cuts videos from edits in Premiere -> FCP7 Export [GPL v3]".format(APP_NAME, APP_VERSION))
g.applog.minimal("Copyright (c) TestCams.com - Time: {:s}, Py: {:d}.{:d}.{:d}, OS: {:s}\n".format(getDateTimeStr(fMilitaryTime=True),\
sys.version_info.majo... | The main task of the code is to parse and process command-line arguments for a video editing application, handling options like input/output paths, clip combination settings, FFmpeg configurations, and logging. It validates arguments, applies defaults, and configures logging levels, ensuring proper handling of user-spe... | def processCmdLine():
#
# note: if you add additional filter options/logic, go to realTimeCapture() to see if those options
# need to be overriden when we enter the realtime capture phase
#
parser = ArgumentParserWithException(fromfile_prefix_chars='!',\
formatter_class=argparse.RawDescript... |
def display_grid():
for i in board:
for j in i:
print('|',j,'|', end = " ")
print()
print(' \n')
def turn():
player_move()
if check_win():raise Exception()
ai_move()
if check_win():raise Exception()
print('-' * 65,' \n')
d... | The code defines a game function that initializes a grid, alternates turns between players, checks for a win condition, and declares a tie if no winner is found. It uses `display_grid()` to show the board, `turn()` for player moves, and `check_win()` to determine victory, raising an exception if a win occurs. If the ga... | def game():
print('Play Grid : \n')
display_grid()
print('-' * 65,' \n')
turn()
turn()
turn()
turn()
player_move()
if check_win():raise Exception()
print('***Tie***')
print('-' * 65,' \n') |
def generate_tile_coordinates(self):
last_y = 0
for i in range(len(self.tile_coordinates) - 1, -1, -1):
if self.tile_coordinates[i][1] < self.current_y_loop:
del self.tile_coordinates[i]
if len(self.tile_coordinates) > 0:
last_y = self.tile_coordinates[-1... | This code updates the vertical and horizontal scrolling of a game or simulation by adjusting the offset based on time delta (dt) and speed. It manages looping tiles by resetting the offset when it exceeds line spacing, regenerating tile coordinates, and updating visual elements like lines and tiles to reflect the new p... | def update(self, dt):
time_factor = dt * self.FPS
self.current_offset_y += self.SPEED * time_factor
spacing_y = self.H_LINES_SPACING * self.height
if self.current_offset_y > spacing_y:
self.current_offset_y -= spacing_y
self.current_y_loop += 1
self.g... |
def start_climate(vin):
global assumed_climate_state, climate_timer, engine_status
# Start the api call in another thread for HA performance
Thread(target=volvo.api_call, args=(CLIMATE_START_URL, "POST", vin)).start()
# Start door check thread to turn off climate if driver door is opened
check_engi... | The code processes incoming MQTT messages to execute vehicle control commands. It extracts a VIN from the topic, then triggers actions like climate control (ON/OFF), locking/unlocking, data updates, and scheduling based on the message payload. It also validates and applies update intervals, logging errors for invalid i... | def on_message(client, userdata, msg):
try:
vin = msg.topic.split('/')[2].split('_')[0]
except IndexError:
logging.error("Error - Cannot get vin from MQTT topic!")
return None
payload = msg.payload.decode("UTF-8")
if "climate_status" in msg.topic:
if payload == "ON":
... |
def refresh_auth():
logging.info("Refreshing credentials")
global refresh_token
headers = {
"authorization": "Basic aDRZZjBiOlU4WWtTYlZsNnh3c2c1WVFxWmZyZ1ZtSWFEcGhPc3kxUENhVXNpY1F0bzNUUjVrd2FKc2U0QVpkZ2ZJZmNMeXc=",
"content-type": "application/x-www-form-urlencoded",
"accept": "appli... | This function handles API calls to Volvo endpoints, refreshing authentication tokens when needed. It uses caching for specific URLs to reduce requests, makes GET/POST calls with session management, processes JSON responses, and handles errors like 403/503 status codes. It returns parsed data on success or None on failu... | def api_call(url, method, vin, sensor_id=None, force_update=False, key_change=False):
if datetime.now(util.TZ) >= token_expires_at:
refresh_auth()
if url in [RECHARGE_STATE_URL, WINDOWS_STATE_URL, LOCK_STATE_URL, TYRE_STATE_URL,
STATISTICS_URL, ENGINE_DIAGNOSTICS_URL, VEHICLE_DIAGNOSTICS... |
def current_events(service, calander_id):
"""
Grabs and returns the current events from the 'code-clinics' calendar.
returns it as an event.
"""
event = service.events().get(calendarId='qphjd@example.com', eventId=calander_id).execute()
return event
def user_pre_slotted(cc_events, user_name):
... | The function inserts a user into a calendar event by checking for existing bookings, ensuring the slot isn't full, adding the user to attendees, verifying no conflicting meetings, and updating the event. If successful, it confirms joining; otherwise, it reports errors like full booking or missing events. | def insert_patient(service, command_params, user_name, cc_events):
"""
Creates all variables that will be used, for the params, and the date/time.
Checks if the user already has slots. If false return.
Checks if the slot is already fully booked. if False return.
Adds the user to the event.
check... |
def validate_params(command_params):
"""
Checks if the it is valid or not.
seperates the date and time into variabels.
runs if they are valid or not, if both are true returns the date and time
else returns false
"""
if command_params == []:
print("invalid request, plese try again")
... | The function validates and inserts a user-scheduled event into a calendar by checking: 1) valid time slot format, 2) user hasn't already booked that slot, 3) no overlapping meetings exist. If all checks pass, it creates the event with parsed parameters. The core task is ensuring valid, non-conflicting event scheduling ... | def insert_event(command_params, service, user_name, table_data, full_time_list, cc_events, us_events):
"""
Seperates the command params into the slots they need if valid.
1. checks if they are valid slot. if False return.
2. checks if they user already has this slot. if False return.
3. checks if t... |
def evolutution_TSP(distances, n_survivors, n_parents, n_generations,
parent_selection, recombination, survivor_selection,
hybrid=None):
max_dist = np.sum(np.max(distances, axis=1))
n_children = n_parents
n_alleles = len(distances)
children = np.empty((n_children,... | This code evaluates and compares the performance of three genetic algorithm recombination methods (PMX, Cycle Crossover, Order Crossover) for solving the Traveling Salesman Problem. It runs 20 simulations for each method over 250 generations, tracking the average shortest travel distance. Results are plotted to visuali... | def test_GA_recobination():
n_generations = 250
n_runs = 20
fig, ax = plt.subplots()
b = np.empty((3, n_runs, n_generations))
x = np.arange(n_generations)
recombinations = [pmx_pair, cycle_crossover_pair, order_crossover_pair]
names = ["Partially Mapped Crossover", "Cycle Crossover", "Order ... |
def createModel(self, bodyType: CogBody, department: Department = None, skelecog=False, lose=False) -> None:
"""
Creates the appropriate model and all subparts for the given Body. Also cleans up the previous model if necessary.
:param bodyType: The CogBody that stores the wanted models
:... | The main task of the code is to transition a cog actor into its "lose" state for a defeated explosion animation. It checks if the cog is already in the lose state, then sets internal flags, nullifies health and medallion references, and applies the lose model with updated textures and visual elements. This ensures the ... | def becomeLoseActor(self) -> None:
"""
Switches the cog to its lose model, which is a special model used for the defeated explosion animation.
:return:
"""
if self._isLose:
print("CogActor: becomeLoseActor() called, but already in the lose state")
return
... |
def createModel(self, bodyType: CogBody, department: Department = None, skelecog=False, lose=False) -> None:
"""
Creates the appropriate model and all subparts for the given Body. Also cleans up the previous model if necessary.
:param bodyType: The CogBody that stores the wanted models
:... | The method `becomeNormalActor` switches a cog from its "lose" state back to its normal state by updating its model, textures, and visual elements. It first checks if the cog is already normal, then resets the `_isLose` flag, recreates the model with the original parameters (excluding the lose state), reapplies textures... | def becomeNormalActor(self) -> None:
"""
Switches the cog back to its normal model from its lose model.
:return:
"""
if not self._isLose:
print("CogActor: becomeNormal() called but already normal")
return
self._isLose = False
self.createMo... |
def createModel(self, bodyType: CogBody, department: Department = None, skelecog=False, lose=False) -> None:
"""
Creates the appropriate model and all subparts for the given Body. Also cleans up the previous model if necessary.
:param bodyType: The CogBody that stores the wanted models
:... | This method sets whether the cog is a skelecog, regenerating its model and updating visual elements like textures, heads, and attachments. It checks if the state has changed, updates internal flags, and triggers model recreation with new parameters, then adjusts the medallion and health meter positioning if applicable. | def setSkelecog(self, skelecog: bool) -> None:
"""
Sets whether the cog is a skelecog. This will regenerate the model.
:param skelecog:
:return:
"""
if self._isSkelecog == skelecog:
return
self._isSkelecog = skelecog
self.createModel(self._bod... |
def createModel(self, bodyType: CogBody, department: Department = None, skelecog=False, lose=False) -> None:
"""
Creates the appropriate model and all subparts for the given Body. Also cleans up the previous model if necessary.
:param bodyType: The CogBody that stores the wanted models
:... | The main task of the code is to apply a template's data to an actor's attributes and visual properties. It loads a template (either by object or name), initializes the actor's model with the template's body, department, and scaling parameters, sets textures, colors, and head models based on the template's specification... | def loadTemplate(self, template: TemplateCog | str) -> None:
"""
Applies all the data from a template onto the actor.
:param template: Either the template, or the string name of the template
:return:
"""
if isinstance(template, str):
try:
templ... |
def loadDepartments(departments: dict[str, Any]):
"""
Loads department definitions from a ToontownJSON formatted departments dictionary and adds them to the Departments
dictionary
:param departments: ToontownJSON formatted departments object
:return:
"""
for name, data in departments.items(... | The function loads definitions from a ToontownJSON file by parsing its "departments," "bodies," and "cogs" sections, delegating each to respective loader functions if present. It extracts these nested dictionaries from the input and processes them to populate data structures, likely for game or simulation context. | def loadFromJson(contents: dict[str, dict]):
"""
Loads definitions from a ToontownJSON file
:param contents: ToontownJSON cog file root object
:return:
"""
departments: dict = contents.get("departments")
if departments is not None:
loadDepartments(departments)
bodies: dict = co... |
def loadTemplate(self, template: TemplateCog | str) -> None:
"""
Applies all the data from a template onto the actor.
:param template: Either the template, or the string name of the template
:return:
"""
if isinstance(template, str):
try:
templ... | Your returnThe code initializes a `CogActor` object, either by copying a template (`cogType`) or constructing from a `bodyType` and departmental attributes. It sets up visual properties (textures, head models) and behavioral flags (skelecog, waiter, lose). If `cogType` is provided, it overrides other parameters; otherw... | def __init__(self, cogType: TemplateCog | str = None,
bodyType: CogBody = None, dept: Department = None, head: str = None,
skelecog=False, waiter=False, lose=False) -> None:
"""
CogActor constructor.
If cogType is specified, bodyType, dept and head are ignored.
... |
def read_audio_file(self, file_name):
'''
file_name: string, name of file including extension, e.g. "audio1.wav"
'''
# Get the path to the file
audio_folder = os.path.join(file_name)
# Read the amplitudes and sample rate
audio_amps, audio_sample_... | The code creates a dataset for machine learning by processing annotated audio files (.svl) and corresponding .wav files. It applies a low-pass filter, downsamples audio, extracts annotated segments, converts them into spectrograms, and generates labeled input-output pairs (X_calls, Y_calls) for training. The dataset in... | def create_dataset(self, verbose):
'''
Create X and Y values which are inputs to a ML algorithm.
Annotated files (.svl) are read and the corresponding audio file (.wav)
is read. A low pass filter is applied, followed by downsampling. A
number of segments are extracted and augmen... |
def board_info(player_names, stones_list):
"""
This function places the players names and number of stones in each cup to send to draw_board
:param player_names: A list with the two names
:param stones_list: A list with the number of stones in each cup
:return: does not return anything
"""
... | The function `take_turn` manages a player's move in a game (likely Mancala). It displays the board, identifies the current player, prompts for a cup selection, validates the input, and executes the move. It loops until a valid cup is chosen, converts the choice to an integer, and calls `make_move` to update the game st... | def take_turn(players, who, cups):
"""
This function displays the board and asks for new moves
:param players: list of strings with player names
:param who: integer who's turn it is
:param cups: list of cups with number of stones
:return: returns a list with new stone locations and whether last ... |
def get_player():
"""
This function gets the names of player 1 and player 2
:return: a list of the two names
"""
player_list = []
# adds player names to a list
for i in range(NUM_PLAYERS):
name = input("Player {} please enter your name: ".format(i + 1))
player_list.append(... | The `run_game()` function manages a two-player game involving moving stones between positions, checking for game-ending conditions, and determining winners. It initializes player names, tracks turns, updates positions after each move, and checks if the game has ended. If a player lands a stone in a mancala, they get an... | def run_game():
"""
This function runs the game
:return: does not return anything
"""
# calls get_player() to get names
player_list = get_player()
player_turn = PLAYER_ONE
current_positions = START_POSITIONS
game_over_check = game_over(current_positions)
# game_over_check[0]... |
def partition_to_vector(label):
x = np.ones(N)
for i in range(N):
x[i] = G.nodes[i][label]
x[x == 0] = -1
return x
def houdayer_step():
potential_nodes = []
for node in range(N):
local_overlap = G.nodes[node]['estimate1'] * G.nodes[node]['estimate2']
G.nodes[node]['local... | The code performs multiple runs of a Markov Chain Monte Carlo (MCMC) algorithm to approximate a true partition (x_true) using two estimates (x1, x2). It initializes random states, updates them via Houdayer and Metropolis steps, tracks overlaps with the true partition (if not in fast mode), and returns results containin... | def houdayer(max_run, max_iter, n, fast_run=True):
results = [] # list containing the results of MCMC results
x_true = partition_to_vector('block')
for run in range(max_run):
#initialize result object
result = Result(run)
#initial state
x1 = np.random.choice((-1,1... |
def material_param(material_mode = 0):
# Return material parameters for the non-wetting phase which can be substituted
if material_mode == 0:
# Non-wetting phase: air
Kg = 1.01E5
rhoGR0 = 1.2
piG = 1.82E5
if material_mode == 1:
# Non-wetting phase: oil
Kg = 5.... | This function calculates geomechanical parameters for wave analysis, returning Lame's first constant (lambS), partial densities (rhoS0, rhoF0, rhoG0), compressibility factors (kappaF, kappaG), and resistance parameters (piFS, piGS) derived from input saturation (S0) and material mode. It combines material properties, c... | def derived_param(S0, material_mode=0):
# Derive remaining parameters for wave analysis
# Return [Lame constant], [partial densities], [compressibility], [resistance]
piG = material_param(material_mode)[2]
pc, dpcdS = capillary(S0, 1)
bulkMod, rhoF0kappaF, rhoG0kappaG = albers_param(S0, pc, dpcdS, m... |
def get_output_regions(my_file):
root = etree.fromstring(my_file['model']['serialized_config'][0])
outputs = {}
for son in root:
if son.tag.endswith('OutputScheme'):
for grandson in son:
outputs[grandson.get("filename")] = grandson.get("region")
return outputs
def get... | This function processes simulation data to compute calcium concentration (Ca_conc), RyR channel open probabilities (open_ryr3), and average open/closed times (mean_o_t, mean_c_t) across trials. It aggregates population data, calculates species-specific metrics, and handles different RyR variants. The output includes st... | def get_numbers(my_file, output="all"):
output_dict = get_output_regions(my_file)
Ca_conc = []
open_ryr3 = []
mean_c_t = []
mean_o_t = []
no = 0
sum_o = 0
nc = 0
sum_c = 0
for trial in my_file.keys():
if trial == "model":
continue
times = get_times... |
def get_2d_stack(images: List[Image.Image], gap: int, orientation: ImageOrientation) -> Image.Image:
"""Stack a sequence of images into a single image.
Args:
images (List[Image.Image]): A list of images to stack.
gap (int): The gap between images in the generated stack of images.
orient... | This function generates a visualization displaying dominant colors of an analyzed image as color chips, alongside the original image and optionally a remapped version. It arranges these elements horizontally or vertically based on the image's orientation, applies padding, and saves the composite image to a specified pa... | def save_dominant_color_visualization(
analyzed_image: AnalyzedImage,
dominant_color_chip_size: int,
dest_path: str,
include_remapped_image: bool,
display: bool,
):
"""Save a visualization of the provided analyzed image's dominant colors.
Saves the dominant colors as chips alongside a repre... |
def pad_concat_horizontal(
visualization_components: List[Image.Image], outer_border: int, inner_border: int
) -> Image.Image:
"""Pad and concatenate asequence of images horizontally into a single image.
Applies padding to ensure that
- all images have the same height before concatenating
- `outer_... | This function generates a collage of analyzed images, adjusting layout dimensions to maintain a square aspect ratio when using "sqrt" for width. It arranges images in rows/columns, adds spacing, combines them into a single image, and saves it to the specified path, optionally displaying it. | def save_image_collage(analyzed_images: List[AnalyzedImage], width: Union[int, str], dest_path: str, display: bool):
"""Generate a collage of the sorted images.
Tries to keep aspect ratio of generated graphic as square as possible.
Args:
analyzed_images (List[AnalyzedImage]): Sequence of analyzed ... |
def BacktoNormal(self):
#gets rid of power Ups
self.Xspeed = Player.MAX_movX
self.counter = 0
def Xcollsion(self, level):
collsion = False
#if self.x += self.movX = collsion collsion = True
xPosL = self.x + self.movX
xPosR = xPosL + (self.PlayerWalkingWidth-5)
... | This code updates a game character's movement and animation. It handles X/Y collision detection, adjusts velocity for falling/jumping, cycles through sprites based on tick intervals, and manages power-up states. The character's position is updated with collision checks, velocity adjustments, and sprite changes dependin... | def update(self, level, tick):
if(self.velocity < 0):
#Y collsion + Jump***********
self.falling=True
#*
#Sprite animation
if tick == 60:
#PowerUp
if self.counter < 5 and self.Xspeed == Player.SSMAX_movX:
#Speed
... |
def get_index(self, ts: int, from_idx=0, to_idx=None, valid_read_index=False):
# Empty list:
if len(self.sorted_list) <= 0:
return 0
# Clamp indexes, default: whole list
from_idx = min(max(from_idx, 0), len(self.sorted_list)-1)
if to_idx is None:
to_idx... | This code inserts a timestamp-value pair into a sorted list while maintaining order. If the timestamp already exists and overwrite is True, it updates the existing entry; otherwise, it inserts the new entry at the correct position. After insertion, it automatically trims the list and saves the data. | def insert_sorted(self, ts: int, value, overwrite=True):
vt = [ts, value] # Use list as a tuple to make it yaml-comp
idx = self.get_index(ts)
if overwrite and \
len(self.sorted_list) > 0 and \
idx < len(self.sorted_list) and \
idx >= 0 and \
... |
def _retrieve_svhn_training():
url = "http://ufldl.stanford.edu/housenumbers/train_32x32.mat"
return _retrieve_svhn("train.npz", url)
def _preprocess_svhn(raw, withlabel, scale, image_dtype, label_dtype):
images = raw["x"].transpose(3, 2, 0, 1)
images = images.astype(image_dtype)
images *= scale / 2... | (The function retrieves and preprocesses the SVHN dataset, returning the 'extras' and 'test' subsets. It loads raw data, scales pixel values, converts data types, and optionally includes labels, similar to MNIST but without the ndim parameter. SciPy is required for data retrieval.) | def get_svhn(withlabel=True, scale=1., dtype=numpy.float32,
label_dtype=numpy.int32):
"""Gets the SVHN dataset.
`The Street View House Numbers (SVHN) dataset <http://ufldl.stanford.edu/housenumbers/>`_
is a dataset similar to MNIST but composed of cropped images of house
numbers.
The fu... |
def poly_param_search(
x: np.ndarray, y: np.ndarray, num_folds: int
) -> Tuple[float, int]:
"""
Parameter search for Poly kernel.
There are two possible approaches:
- Grid Search - Fix possible values for lambdas and ds.
Have nested loop over all possibilities and record value with ... | The main task of the code is to optimize hyperparameters (lambda, gamma, d) for polynomial and RBF kernels using `x_30`, `y_30`, then train models with these optimal parameters to predict on a fine grid (0–1). It plots predictions alongside the true function, applying `plt.ylim(-6, 6)` to ensure visibility. The code ca... | def main():
"""
Main function of the problem
It should:
A. Using x_30, y_30, rbf_param_search and poly_param_search report optimal values for lambda (for rbf), gamma, lambda (for poly) and d.
Note that x_30, y_30 has been loaded in for you. You do not need to use (x_300, y_300) or (x_10... |
def init_distributed():
dist_url = "env://"
rank = int(os.environ["RANK"])
world_size = int(os.environ['WORLD_SIZE'])
local_rank = int(os.environ['LOCAL_RANK'])
dist.init_process_group(
backend="nccl",
init_method=dist_url,
world_size=world_size,
... | The code trains a sequence-to-sequence model (likely for translation) using distributed GPU training, mixed precision (FP16), gradient accumulation, and validation. It loads a pre-trained Vietnamese-English ViT5 model, fine-tunes it on a dataset, and saves checkpoints based on BLEU scores from test/validation sets. The... | def train(config):
init_distributed()
print("###Init model and tokenizer")
tokenizer = AutoTokenizer.from_pretrained(
"VietAI/envit5-translation", cache_dir="pretrained")
model = AutoModelForSeq2SeqLM.from_pretrained(
"VietAI/envit5-translation", cache_dir="pretrained").cuda()
opt... |
def connection_to_client():
global event_stop
t1 = threading.Thread(target=create_socket)
event_stop = threading.Event()
t1.start()
def start_new_game():
global shot_number, game_on, balls, root, racket2_id, score1, score2
score1 = 0
score2 = 0
root.config(cursor='none')
balls = {}
... | The main task of the code is to initialize a GUI-based game using Tkinter, setting up a yellow canvas, game elements like a score label, and connecting to a client. It starts a new game, initializes game variables, and enters a loop to handle game updates and rendering via `tick()` and `mainloop()` for continuous inter... | def main():
global interval, rand, root, canvas, label_score, conn
interval = 0
rand = randint(5, 30)
root = tk.Tk()
root.iconbitmap('racket.ico')
root.geometry(str(WIDTH) + 'x' + str(HEIGHT))
canvas = tk.Canvas(root, bg='yellow')
canvas.pack(expand=1, fill='both')
GameMenu()
lab... |
def get_positions(self, stone_color):
x = set()
for i in range(9):
for j in range(9):
if self.state[i][j] == stone_color:
x.add((i, j))
return x
def point_neighbours(self, position):
neighbour_class = {0: set(), 1: set(), 2: set()}
... | The code evaluates a game state by calculating the difference in stone counts, eye spaces, and liberties between two players, combining these factors with weighted coefficients to determine an overall score or advantage. | def evaluate(self):
player_1 = np.count_nonzero(self.state == self.player)
player_2 = np.count_nonzero(self.state == self.opp_player)
stone_pieces = player_1 - player_2
my_eyes = 0
opp_eyes = 0
points = self.get_positions(0)
for i in points:
n = self... |
def get_positions(self, stone_color):
x = set()
for i in range(9):
for j in range(9):
if self.state[i][j] == stone_color:
x.add((i, j))
return x
def eval(self):
player_1 = np.count_nonzero(self.state == 1)
player_2 = 2.5 + np.count_... | The function generates valid game states (moves) using a priority queue, considering captures, liberties, and board position. It adds "PASS" when applicable, prioritizes moves based on liberties, opponent neighbors, and position weights, returning a queue of valid actions for the current player. | def valid_states(self, order):
valid_states = self.get_positions(0)
valid_queue = PriorityQueue()
if np.count_nonzero(self.previous_board) == 0 and np.count_nonzero(self.state) == 0:
valid_queue.put((0, (2, 2)))
return valid_queue
if (self.previous_board == self... |
def convert_to_wav(self, filename):
if filename.lower().endswith(".wav"):
# Already a WAV file, no need to convert
self.filename = filename
self.sample_rate, self.audio_data = wavfile.read(filename)
return
try:
audio = AudioSegment.from_file(f... | The code loads an audio file, converts it to WAV format, calculates its duration, computes RT60 (reverberation time), retrieves frequency data, and generates a length array for acoustic analysis. | def load_audio_file(self, filename):
self.convert_to_wav(filename)
self.duration = len(self.audio_data) / self.sample_rate
self.calculate_rt60()
self.getEntireFrequency()
self.getLengthArray() |
def addLog(self, log: str) -> None:
if self._verbose:
self._logs.append(log)
def normalizeString(self, text: str, fromDict: bool = False) -> str:
# normalize the text to NFD form
text = unicodedata.normalize('NFD', text)
# remove diacritics
text = re.sub(r'[\u0300-\u036f]', '', text)
# r... | The main task of the code is to process text by tokenizing input into words, applying case normalization, removing stopwords, and performing stemming on remaining words. It logs each step and returns stemmed words as a space-separated string, or an empty string if no valid words remain after filtering. | def stemWords(self) -> str:
self._fullLogs = []
self._words = re.findall(r'\b[\w-]+\b', self._input)
self.addLog(f'✔ Tokenisasi input: "{self._input}" menjadi: [{", ".join(self._words)}]')
self._results = [self.normalizeString(word) for word in self._words]
self.addLog(f'✔ Proses casefolding m... |
def getM(self, word):
form = self.wordForm(word)
m = form.count('VC')
return m
def doubleCons(self, stem):
if len(stem) >= 2:
if self.isConsonant(stem, -1) and self.isConsonant(stem, -2):
return True
else:
return False
else:... | This function modifies a word by removing its last character if it ends with 'l', has two consecutive consonants before it, and has a vowel measure greater than one, aiding in word stemming by simplifying suffixes like double consonant + 'l' | def step5b(self, word):
if self.getM(word) > 1 and self.doubleCons(word) and self.endsWith(word, 'l'):
word = word[:-1] #remove the last one
return word |
def replaceM0(self, word, removePart, replacePart):
position = word.rfind(removePart)
base = word[:position]
if self.getM(base) > 0:
replaced = base + replacePart
return replaced
else:
return word
def containsVowel(self, stem):
for letter in st... | This function performs step 1b of a stemming algorithm, handling suffixes like 'eed', 'ed', and 'ing'. It truncates these suffixes when appropriate, then applies optional transformations: adding 'e' for specific endings, removing double consonants, or appending 'e' based on vowel and consonant patterns to derive the wo... | def step1b(self, word):
optionalStep = False
if word.endswith('eed'):
position = word.rfind('eed')
base = word[:position]
word = self.replaceM0(base, 'eed', 'ee')
elif word.endswith('ed'):
position = word.rfind('ed')
base = word[:positi... |
def replaceM1(self, word, removePart, replacePart):
position = word.rfind(removePart)
base = word[:position]
if self.getM(base) > 1:
replaced = base + replacePart
return replaced
else:
return word
def getM(self, word):
form = self.wordForm(word... | This code performs suffix removal in a stemming process. It checks if a word ends with specific suffixes (e.g., 'al', 'ance', 'er', 'ion') and removes them using the `replaceM1` method. For 'ion', it applies additional conditions based on the base word's structure. The goal is to reduce words to their root forms by str... | def step4(self, word):
if word.endswith('al'):
word = self.replaceM1(word, 'al', '')
elif word.endswith('ance'):
word = self.replaceM1(word, 'ance', '')
elif word.endswith('ence'):
word = self.replaceM1(word, 'ence', '')
elif word.endswith('er'):
... |
def step1a(self, word):
if word.endswith('sses'):
word = self.replace(word, 'sses', 'ss')
elif word.endswith('ies'):
word = self.replace(word, 'ies', 'i')
elif word.endswith('ss'):
word = self.replace(word, 'ss', 'ss')
elif word.endswith('s'):
... | This code applies the Porter stemming algorithm to reduce a word to its stem by sequentially processing it through multiple steps (step1a to step5b), each handling specific suffixes and transformations to normalize the word form. | def getStem(self, word):
word = self.step1a(word)
word = self.step1b(word)
word = self.step1c(word)
word = self.step2(word)
word = self.step3(word)
word = self.step4(word)
word = self.step5a(word)
word = self.step5b(word)
return word |
def prepareForReCodeSign(ipaPath, provisionPath):
resigningIPAPath = validateParam(ipaPath, '.ipa')
provisionFilePath = validateParam(provisionPath, '.mobileprovision')
os.system("security cms -D -i " + provisionFilePath + " > pendingProvision.plist")
os.system("/usr/libexec/PlistBuddy -x -c \'Print:\'E... | The code's main task is to re-sign an iOS app (IPA) with a specified certificate and provisioning profile, modifying its bundle identifier, updating the Info.plist, and repackaging it with an optional new name. It unzips the IPA, re-signs frameworks, replaces provisioning files, and compresses the result into a new IPA... | def reCodeSignApp(resigningIPAPath, certificationName, provisionFilePath, bundleIdentifier, newName = ''):
prepareForReCodeSign(resigningIPAPath, provisionFilePath)
unzipIPA(resigningIPAPath)
reCodeSignFrameworks(certificationName)
replaceProvisionFile(provisionFilePath)
mofidyInfoPlist(bundleIdenti... |
def prepareForReCodeSign(ipaPath, provisionPath):
resigningIPAPath = validateParam(ipaPath, '.ipa')
provisionFilePath = validateParam(provisionPath, '.mobileprovision')
os.system("security cms -D -i " + provisionFilePath + " > pendingProvision.plist")
os.system("/usr/libexec/PlistBuddy -x -c \'Print:\'E... | The code's main task is to re-sign an iOS app (IPA) with a specified certificate and provisioning profile, modifying its Info.plist, injecting files if needed, and renaming the output. It unzips the IPA, replaces the provisioning file, re-signs frameworks and the app, then re-zips it with an optional new name, ensuring... | def reCodeSignApp(resigningIPAPath, certificationName, provisionFilePath, bundleIdentifier, newName = '', injectionDir = None):
prepareForReCodeSign(resigningIPAPath, provisionFilePath)
unzipIPA(resigningIPAPath)
doInjection(injectionDir)
reCodeSignFrameworks(certificationName)
replaceProvisionFile(... |
def add_airport_vertex(self, latitude: float, longitude: float):
# search for the airport node in the airports list
airport = self.search_airport_in_list(latitude, longitude)
if airport is not None:
# check if the airport is not already in the graph
if airport not in self... | The main task of the code is to initialize and compute all-pairs shortest paths between airports using the Floyd-Warshall algorithm. It first adds all airports as vertices, creates complete connections between them, computes shortest paths, stores these paths in a dictionary, and then clears temporary graph data. This ... | def initialize_shortest_paths(self):
# add all the vertex to the graph
for i in range(len(self.airports_list)):
self.add_airport_vertex(
self.airports_list[i].latitude, self.airports_list[i].longitude)
# add all the possible connections to the graph
... |
def conv_fw_def_(self):
conv_def = ''
conv_def += self.add_def_("v_g", self.group)
# Input image batch offset
conv_def += self.add_def_("v_B_off", self.fmaps_in * self.prod_(self.im_in_shape))
# Output image batch offset
conv_def += self.add_def_("v_C_off", self.fm... | This function generates LIBDNN code for convolutional or deconvolutional layers. If `is_deconv` is False, it combines forward definitions and kernels for standard convolution. If True, it generates equivalent code for deconvolution. The output is a concatenation of definition and kernel implementation strings, specific... | def generate_libdnn_code(self):
if not self.is_deconv:
return self.conv_fw_def_() + self.conv_fw_kernel_(self.name)
else:
return self.deconv_fw_def_() + self.deconv_fw_kernel_(self.name) |
def create_initial_population(self):
"""Create the first population randomly.
"""
if self.njobs > 1:
pool = Pool(self.njobs)
jobs = self.jobMaker(self.population_size, self.njobs)
outputs = pool.map(self.create_initial_population_njobs, jobs)
poo... | The code initializes a Genetic Algorithm (GA) to optimize a fitness function using configurable parameters like population size, generations, and recombination/mutation probabilities. It sets up the initial population, iteratively evolves it through selection, recombination, and mutation, and tracks the best solution's... | def __init__(self,
data,
label,
fitness,
population_size=20,
children_size=20,
generations=15,
recombination_probability=0.8,
mutation_probability=0.2,
tournament_size... |
def getState(self):
return self._state
def update_state_inactive(self):
"""STATE_INACTIVE: This is the state at the beginning, and is the state
so long as the player never presses a key. In addition, the application
switches to this state if the previous state was STATE_ACTIVE and the
... | The code manages game states (e.g., inactive, new game, countdown, active, paused) by updating the current state and delegating gameplay mechanics to the Play class. It transitions between states based on conditions like user input, time intervals, and game events, ensuring proper animation and flow control. The update... | def update(self,dt):
"""Animates a single frame in the game.
It is the method that does most of the work. It is NOT in charge of
playing the game. That is the purpose of the class Play. The primary
purpose of this game is to determine the current state, and -- if the
g... |
def getAlphaWeight(unet2out):
alpha0 = F.sigmoid(unet2out[:, 4:5, :, :])
alpha1 = 1 - alpha0
return alpha0,alpha1
def validate(curEpoch):
totalLoss = 0
totalDice = 0
totalDiceNp = torch.zeros(4)
with torch.no_grad():
for valIndex, (valSliceList, validationSliceIndex) in enumerate(va... | The code trains a neural network model with two UNet architectures to predict image slices by combining deformation fields (DFs) and fusion weights. It uses L1 and Dice losses for optimization, tracks the best Dice coefficient during validation, and saves model weights periodically. The training loop includes forward p... | def main():
bestDice = -1
bestDiceEpoch = -1
# train loop, for every epoch
for epoch in range( args.epochs):
log.info("exp_name={} Epoch: {}, bestDice(epoch) ={:.4f}\t{}".format(exp_name, epoch, bestDice, bestDiceEpoch ))
curEpoch = epoch
lossList = []
l1LossList = []
... |
def draw_text(self, text, size, color, x, y):
'''Function which draws NORMAL text on the screen with a specific font, size and colour'''
font = pygame.font.Font("./Fonts/GamePlayed.ttf", size)
text_surface = font.render(text, True, color)
text_rect = text_surface.get_rect()
text_... | The code's main task is to initialize and manage the game loop, resetting game elements, handling movement and collision detection, updating scores, and managing game over states, including high score checks and restart logic. | def play(self):
'''Function which starts the game'''
# Local function variables
running = True
play_collision = False
# Reset rocket to original position
self.rocket.reset(self.width / 2, self.height / 2)
for asteroid in self.asteroids:
asteroid.rese... |
def settings(self):
'''Function which shows the settings screen'''
# Local function variables
running = True
self.click = False
while running:
# Get the mouse position
mx, my = pygame.mouse.get_pos()
# Draw Background and text to the setting... | This function renders the game's home screen by displaying a background image, a rotated rocket, and three interactive buttons (Settings, Tutorial, Quit). It handles mouse input to trigger actions like opening settings, tutorials, or exiting. It also displays the game title, high score, and instructions, adjusting text... | def show_home_screen(self):
'''Function which displays the home screen of the game'''
# Show static background image on home screen
self.screen.blit(self.background, (0, 0))
rotated_rocket = pygame.transform.rotate(self.rocket_image, 25)
self.screen.blit(rotated_rocket, (self.wi... |
def show_home_screen(self):
'''Function which displays the home screen of the game'''
# Show static background image on home screen
self.screen.blit(self.background, (0, 0))
rotated_rocket = pygame.transform.rotate(self.rocket_image, 25)
self.screen.blit(rotated_rocket, (self.wi... | The main task of the code is to run the game loop, handle user inputs (mouse clicks, spacebar, window resizing), and manage transitions between the home screen and play screen. It polls events, updates the game state, maintains FPS, and exits gracefully when the user quits. | def run(self):
'''Function which is the main game loop'''
while not self.quit:
# Show home screen by default
self.show_home_screen()
# Clock for home screen
self.clock.tick(FPS)
# Event handling - MOUSEBUTTON click, 'X' button click, SPACE ... |
def _load(self):
rospy.loginfo("[Blimp Environment Node] Load and Initialize Parameters...")
self.cnt = 0
self.RATE = rospy.Rate(100)
self.GRAVITY = 9.81
# actuator
self.stick_angle = 0
self.elv1_angle = 0
self.elv2_angle = 0
self.rud1_angle = ... | The code initializes a ROS node for a blimp environment, loads configurations, sets up publishers/subscribers, and starts a control loop to manage the blimp's operations in simulation or real-world scenarios. | def __init__(self):
rospy.init_node('blimp_node', anonymous=False)
rospy.loginfo("[Blimp Environment Node] Initializing...")
self._load()
self._create_pubs_subs()
# self.gaz = GazeboConnection(True, "WORLD")
# self.gaz.unpauseSim()
rospy.loginfo("[Blimp Environme... |
def swap(instruction: str, s: str) -> str:
pattern = r'swap (position|letter) (\d+|.) with.*(\d+|.)'
matches = re.match(pattern, instruction)
if matches:
if matches.group(1) == 'position':
index1 = int(matches.group(2))
index2 = int(matches.group(3))
temp = lis... | The main task of the code is to process a list of scrambling instructions (swap, rotate, reverse, move) sequentially on a string `s`, modifying it step-by-step according to each operation, and returning the final transformed string. | def scramble(instructions: list[str], s: str) -> str:
for instruction in instructions:
if 'swap' in instruction:
s = swap(instruction, s)
elif 'rotate' in instruction:
s = rotate(instruction, s)
elif 'reverse' in instruction:
s = reverse(instruction, s)
... |
def _get_ips_iqns_luns(self, connection_properties, discover=True):
"""Build a list of ips, iqns, and luns.
Used only when doing multipath, we have 3 cases:
- All information is in the connection properties
- We have to do an iSCSI discovery to get the information
- We don't wa... | This function generates a map of devices associated with TCP sessions based on connection properties. It categorizes devices into 'belong' (from the current connection) and 'others' (from different connections) per (ip, iqn) session. If ips_iqns_luns is provided, it bypasses connection properties. For multipath scenari... | def _get_connection_devices(self, connection_properties,
ips_iqns_luns=None):
"""Get map of devices by sessions from our connection.
For each of the TCP sessions that correspond to our connection
properties we generate a map of (ip, iqn) to (belong, other) where
... |
def _run_iscsiadm(self, connection_properties, iscsi_command, **kwargs):
check_exit_code = kwargs.pop('check_exit_code', 0)
attempts = kwargs.pop('attempts', 1)
delay_on_retry = kwargs.pop('delay_on_retry', True)
(out, err) = self._execute('iscsiadm', '-m', 'node', '-T',
... | The main task of the code is to connect to an iSCSI portal using provided properties, handle authentication if required, check for existing sessions, and return the session ID upon successful connection. It ensures the target is discovered, configures manual scan mode, and retries login if necessary, logging errors and... | def _connect_to_iscsi_portal(self, connection_properties):
"""Connect to an iSCSI portal-target an return the session id."""
portal = connection_properties['target_portal'].split(",")[0]
target_iqn = connection_properties['target_iqn']
# NOTE(vish): If we are on the same host as nova vo... |
def _connect_vol(self, rescans, props, data):
"""Make a connection to a volume, send scans and wait for the device.
This method is specifically designed to support multithreading and
share the results via a shared dictionary with fixed keys, which is
thread safe.
Since the heav... | This function attempts to connect to a storage volume using a single path by iterating over target configurations, performing connection attempts, checking for discovered devices, retrieving WWN identifiers, and handling cleanup or errors. If successful, it returns a connection result; otherwise, it raises an exception... | def _connect_single_volume(self, connection_properties):
"""Connect to a volume using a single path."""
data = {'stop_connecting': False, 'num_logins': 0, 'failed_logins': 0,
'stopped_threads': 0, 'found_devices': [],
'just_added_devices': []}
for props in self._... |
def _connect_multipath_volume(self, connection_properties):
"""Connect to a multipathed volume launching parallel login requests.
We will be doing parallel login requests, which will considerably speed
up the process when we have flaky connections.
We'll always try to return a multipat... | The function `connect_volume` attaches a storage volume to an instance using iSCSI, handling potential conflicts caused by concurrent operations on the same node. It uses multipath or single-path connection methods based on the `use_multipath` flag. If failures occur (e.g., due to network issues), it retries up to thre... | def connect_volume(self, connection_properties):
"""Attach the volume to instance_name.
NOTE: Will retry up to three times to handle the case where c-vol
and n-cpu are both using os-brick to manage iSCSI sessions but they
are on the same node and using different locking directories. In ... |
def on_event(self, event):
keys = pygame.key.get_pressed()
if event.type == pygame.QUIT:
self.__running = False
elif keys[pygame.K_ESCAPE]:
self.__pause = not self.__pause
if keys[pygame.K_1]:
self.my_sprite.set_index(0)
if keys[pygame.K_2]:
... | This code defines a game loop that handles events, updates game state, renders graphics, and maintains a frame rate. It initializes a clock, processes user input/events, checks for game events, renders the game, updates the display, and cleans up resources upon exit. The loop runs while `self.__running` is True, contro... | def game(self):
self.clock = pygame.time.Clock()
# self.on_init()
while self.__running:
pygame.time.delay(100)
self.clock.tick(200)
for event in pygame.event.get():
self.on_event(event)
temp = self.event.get_event()
se... |
def load_snips_data(data_dir):
domain2data = {}
for domain in snips_domains:
file_path = os.path.join(data_dir, 'snips', domain, f'{domain}.txt')
domain2data[domain] = load_file(file_path, domain)
return domain2data
def load_atis_data(data_dir):
file_path = os.path.join(data_dir, 'atis',... | The function generates training, validation, and test text data for a specified target domain by combining SNIPS and ATIS datasets. It excludes the target domain and ATIS from training data, then includes a subset of the target domain's data (controlled by `shot_num`). Validation and test sets are slices of the target ... | def generate_text_data(data_dir, target_domain, shot_num=0):
snips_data = load_snips_data(data_dir)
atis_data = load_atis_data(data_dir)
all_data = {**snips_data, **atis_data}
train_data = []
valid_data = []
test_data = []
for domain_name, domain_data in all_data.items():
if domain_... |
def _seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
def _get_all_obs(self):
return {agent: self._get_obs(agent) for agent in self.agents}
def _get_all_infos(self):
return {agent: self._get_info(agent) for agent in self.agents} | This code resets the environment by initializing robot positions in a circular pattern with random angles and radius, setting initial orientations, and returning observations and info. It uses a seed for reproducibility, calculates positions using polar coordinates, and resets each robot's position/orientation in a phy... | def reset(self, seed=None, options=None):
if seed is not None:
self._seed(seed)
self.current_time = 0
self.agents = self.possible_agents[:]
polarAngle = self.np_random.uniform(low=np.deg2rad(0), high=np.deg2rad(360), size=(1))[0]
yawAngleOffset = self.np_random.unif... |
def flesch_reading_ease(self) -> float:
"""
The Flesch Reading Ease Formula is a simple approach to assess the
grade-level of the reader. It’s also one of the few accurate measures
around that we can rely on without too much scrutiny. This formula is best
used on school text. It ... | The code defines a method `indexes` that computes and returns a dictionary containing three readability metrics: Flesch Reading Ease, Flesch-Kincaid Reading Age, and Automated Readability Index, each calculated by corresponding instance methods. The purpose is to aggregate these text analysis scores for readability eva... | def indexes(self) -> Dict[str, Any]:
return {
"flesch reading ease": self.flesch_reading_ease(),
"flesch kincaid reading age": self.flesch_kincaid_reading_age(),
"automated readability index": self.automated_readablitity_index(),
} |
def start_time(self):
self.timer = time.time()
def forward(self, x):
# lapisan pertama
self.z_in=self.Funcz_in(x, self.W1, self.b1)
self.z=self.sigmoid(self.z_in)
# lapisan output
self.y_in=self.Funcz_in(self.z, self.W2, self.b2)
self.y=self.sigmoid(self.y_in)
def bac... | This code trains a neural network using batch gradient descent. It initializes weights and biases, iterates over epochs, processes data in batches of 32 samples, performs forward and backward propagation for each data point, computes mean squared error (MSE), tracks error per epoch, and stops early if MSE meets a thres... | def fit(self, X, Y):
self.Xtrain, self.Ytrain = X, Y
self.W1correction, self.b1correction, self.W2correction, self.b2correction = np.array([]), np.array([]), np.array([]), np.array([])
data, epoch, msenow, mseepoch=0, 0, 0, 0
self.arrayError=np.array([]) #menghitung error per epoch
... |
def processFile(self, path):
if "mp4" in path:
return self.handleVideo(path)
else:
# cv2.waitKey(1)
return self.handleImage(path)
def getFilesFromDir(self, path):
files = os.listdir(path)
files.sort()
return files | This code recursively processes files and directories. It iterates through each file path, checks if it's a file, processes it with `processFile`, or recursively processes subdirectories by calling itself. The results are stored in `self.info`, which is returned. | def processFiles(self, files, cwd = ''):
for path in files:
path = os.path.join(cwd, path)
if os.path.isfile(path):
self.pf = self.processFile(path)
else:
self.processFiles(self.getFilesFromDir(path), cwd = path)
return self.info |
def print_header(self):
print("----------------------------------------------------")
print("Collecting informations...")
print("----------------------------------------------------")
def confirm_reservoir(self):
while True:
is_reservoir = input("\nIs your... | This function collects and validates user inputs for various reservoir and fluid properties, storing them in a data structure. It handles different property types (numeric, string) with specific validations, including range checks, length limits, and ensuring logical consistency (e.g., diameters, time sequences). User ... | def collect_data(self):
self.print_header()
data_names = self.confirm_reservoir()
if data_names == None:
return data_names
for prop_name in data_names:
print(f"\n{prop_name.upper()}----------------")
stay_on_cu... |
def compare_all_methods(self, tolerance=0.001, to_print=False):
all_methods_info_dict = {}
# Get refined runge-kutta as the exact values and store the time
# required to do that.
# time_before_refined = time.time()
refined_details = self.get_exact_from_(self.runge_kutta_label)
# ... | This method generates HTML reports comparing numerical methods for pipe and reservoir systems. It creates tables, plots graphs, and saves results with timestamps. It handles pipe and reservoir data, constructs HTML content with dynamic labels, units, and images, then writes and opens the report in a web browser. | def get_all_numerical_values(self, to_print=False, dimen_unit="m",
fluid_type="Water", time_unit="s"):
self.dimen_unit = dimen_unit
self.time_unit = time_unit
all_numerical_method_dict = self.compare_all_methods(self.err_tolerance,
... |
def getF(self, V):
# Returns a dictionary that contains friction factor and Reynolds number.
ff = friction_factor.FrictionFactor(V, self.v, self.e, self.D)
return ff.getF_and_R()
def k(self, t, z, V):
return self.fn(t, z, V)
def m(self, t, z, V):
return self.gn1(t, z, V) | This function implements the 4th-order Runge-Kutta method to numerically solve a system of differential equations, updating state variables zn (position) and Vn (velocity) using intermediate steps k1-k4 and m1-m4. It also calculates and stores friction factors and Reynolds numbers for fluid dynamics analysis, with resu... | def runge_kutta_4th(self, tn, zn, Vn):
if (not self.A1) or (not self.A2):
ff = self.getF(Vn)
f = ff["f"] # get friction factor
R = ff["R"] # get Reynold's number
self.results[tn] = (tn, zn, Vn, f, R) # track all the required values
h = self.h
... |
def collect_data(self):
self.print_header()
data_names = self.confirm_reservoir()
if data_names == None:
return data_names
for prop_name in data_names:
print(f"\n{prop_name.upper()}----------------")
stay_on_cu... | The main task of the code is to process input data for fluid flow simulation, configure parameters for oscillation modeling, compute numerical results, and display outcomes in a browser. It initializes a FlowOscillation object, sets reservoir parameters if applicable, runs calculations with specified tolerances, and ou... | def design_flow(self):
data = self.collect_data()
if data != None: # if we have data
table = self.table_data(data)
print(table)
print("-----------------------------------------------------------")
print("\nKindly wait w... |
def _db_to_amp(x):
return np.power(10.0, x * 0.05)
def _denormalize(D):
return (((np.clip(D, -hparams['max_abs_value'], hparams['max_abs_value'])
+ hparams['max_abs_value']) * -hparams['min_level_db'] /
(2 * hparams['max_abs_value'])) + hparams['min_level_db'])
def _inv_preemphasis(x)... | The code converts a normalized spectrogram back to an audio signal by reversing normalization, applying Griffin-Lim for phase reconstruction, and inverting preemphasis, using parameters from `hparams` for power and reference level adjustments. | def inv_spectrogram(spectrogram):
S = _db_to_amp(_denormalize(spectrogram) + hparams['ref_level_db']) # Convert back to linear
return _inv_preemphasis(_griffin_lim(S ** hparams['power'])) |
def _db_to_amp(x):
return np.power(10.0, x * 0.05)
def _denormalize(D):
return (((np.clip(D, -hparams['max_abs_value'], hparams['max_abs_value'])
+ hparams['max_abs_value']) * -hparams['min_level_db'] /
(2 * hparams['max_abs_value'])) + hparams['min_level_db'])
def _inv_preemphasis(x)... | This function reconstructs an audio signal from a CQT spectrogram by converting the input from dB scale to linear amplitude, applying inverse preemphasis, and using the Griffin-Lim algorithm to invert the CQT transform and recover the original waveform. | def inv_cqt_spectrogram(cqt_spectrogram):
S = _db_to_amp(_denormalize(cqt_spectrogram) + hparams['ref_level_db']) # Convert back to linear
return _inv_preemphasis(_cqt_griffin_lim(S)) |
def reset(self):
self.power_on() #It has to be powered on before resetting
self._set_mode(self.RESET)
def _set_mode(self, mode):
self.mode = mode
self.bus.write_byte(self.addr, self.mode)
def wait_for_result(self, additional=0):
basetime = 0.018 if (self.mode & 0x03) == 0x03 else... | The code performs a complete measurement by resetting the device, setting the specified mode, waiting for the result with an optional additional delay, and returning the output value in Lx (lux). | def do_measurement(self, mode, additional_delay=0):
"""
Perform complete measurement using command
specified by parameter mode with additional
delay specified in parameter additional_delay.
Return output value in Lx.
"""
self.reset()
self._set_mode(mode)
... |
def set_icon(filepath='entropy.ppm'):
thismanager = plt.get_current_fig_manager()
img = PhotoImage(file=my_path(filepath))
thismanager.window.tk.call('wm', 'iconphoto', thismanager.window._w, img)
def read_data_to_y(c):
y = []
file_in = open(c.data_file_name, 'r')
for line in file_in.readlines()... | The code creates an interactive matplotlib plot with sliders, buttons, and radio buttons to adjust compartment size, subcompartment number, and line visibility. It visualizes entropy and data lines, updating dynamically based on user inputs, key presses, and hover actions, while maintaining specified styles and layout ... | def plotting_logic(c, data_size, restart_flag):
mpl_style_use(c.matplotlib_style)
fig, ax = plt.subplots(figsize=(c.default_width / c.screen_dpi, c.default_height / c.screen_dpi), dpi=c.screen_dpi)
set_icon()
plt.subplots_adjust(left=0.15, bottom=0.25, right=0.95)
fig.canvas.set_window_title('Entrop... |
def text_window(title, text, iconpath):
# build a rectangle in axes coords
left, width = .25, .5
bottom, height = .25, .5
right = left + width
top = bottom + height
fig = plt.figure(figsize=(8, 3))
fig.canvas.set_window_title(title)
set_icon(iconpath)
ax = fig.add_axes([0, 0, 1, 1])... | The main task of the code is to repeatedly check for the existence of configuration and data files, restore settings if needed, read data with validation, configure decimal separators, and execute plotting logic. If the data file is invalid or reading fails, it exits with an error. The loop terminates when the 'restart... | def main():
restart = Flag(False)
while True:
if not os_path.isfile('settings.ini'):
text_window('WARNING', "Settings file does not exist - creating", 'warning.ppm')
restore_settings()
c = Config()
if not os_path.isfile(c.data_file_name):
text_wind... |
def query_all_record_fields(self, recordNum): # Query the db for all the record fields associated with a particular LetterID, then store that info in a dictionary for future use
fields = self.list_all_fields()
FieldNames = fields[0]
FieldNameList = fields[1]
SQLrecord = self.executeQuer... | The main task of the code is to load all database field values for a specified record into the UI form, disable auto-save to prevent recursion, adjust navigation buttons based on record position, and update relevant widgets (QTextEdit, QTextBrowser, QComboBox) with retrieved data, then re-enable auto-save. | def load_all_fields(self, recordNum): # Queries the values for all fields from the database and inserts the values into the fields for the letter form
self.ui.AutoSaveActive = False # so we don't recursively call save_field on textChanged() forever
self.ui.LatestValueDict = self.query_all_record_fie... |
def get_newestORoldest_LetterID(self, indicator): # Finds and loads the oldest or most recent record
if indicator == "newest":
return self.executeQuery("SELECT max(LetterID) FROM {0}".format(self.DBDataSource))[0][0]
elif indicator == "oldest":
return self.executeQuery("SELECT m... | This function checks if database changes have occurred since a record was last loaded. If changes are detected, it updates the UI fields with the latest database values and adjusts the "Next" button text to prevent creating new records from non-newest entries. It compares stored UI values against freshly queried databa... | def check_if_refresh_needed(self): # Check if changes to a record have occured in the database since the record was last loaded. If a change has occured, reload the record.
letterID = str(self.ui.LetterID.toPlainText())
NewestLetterID = str(self.get_newestORoldest_LetterID("newest"))
LatestVals ... |
def get_newestORoldest_LetterID(self, indicator): # Finds and loads the oldest or most recent record
if indicator == "newest":
return self.executeQuery("SELECT max(LetterID) FROM {0}".format(self.DBDataSource))[0][0]
elif indicator == "oldest":
return self.executeQuery("SELECT m... | This function navigates to the previous database record based on a given ID. It calculates the prior record ID, checks validity, and recursively adjusts if the record is missing. If at the oldest record, it halts. Finally, it loads the fields of the found record. | def goToPreviousRecord(self, recurseLetterId): #
OldestLetterID = int(self.get_newestORoldest_LetterID("oldest"))
if recurseLetterId > OldestLetterID: # Normal case - go to the next oldest record
prevLetterID = recurseLetterId - 1
elif recurseLetterId == OldestLett... |
def get_newestORoldest_LetterID(self, indicator): # Finds and loads the oldest or most recent record
if indicator == "newest":
return self.executeQuery("SELECT max(LetterID) FROM {0}".format(self.DBDataSource))[0][0]
elif indicator == "oldest":
return self.executeQuery("SELECT m... | The main task of the code is to navigate to the next newest record in a database. If the current record is the newest, it creates a new record with an incremented LetterID and loads its fields. Otherwise, it retrieves the next record's data, recursively checking if it exists, and loads the fields once found. The functi... | def goToNextRecord(self, letterID): # Go to the next newest record. If currently at the newest record, create a new record with a higher LetterID
NewestLetterID = int(self.get_newestORoldest_LetterID("newest"))
nextLetterID = letterID + 1
if letterID == NewestLetterID:
... |
def executeQuery(self, queryString, htmlarg = ""): #function for communicating with the sqlite3 db. It executes a given query string, using a special format if the query includes a html string from a field.
try:
sqliteConnection = sqlite3.connect('Night Letter 2.0 data.db')
cursor = sqli... | This function updates attachment links in a database during migration by converting them into HTML links pointing to new file locations. It retrieves attachment data from a SQL table, processes each file name, generates formatted HTML links, and updates corresponding UI fields. The function ensures no existing HTML for... | def updateAttachmentLinks(self):
#Used during migration to reformat all links from an Access dump to refer to the new Attachment file locations
#Caution! No attachment links can have HTML formatting, or this function will mess them up.
#In order to run this function, I had to map it to a button... |
def attach_document(self, docPath):
letterID = self.ui.LetterID.toPlainText()
#If the dialog is closed by the user, the docPath is None and we end here
if docPath is None:
return
fileName = self.getFileName(docPath)
#If no name is entered by... | The code initializes a GUI application by setting up the main window, configuring database and attachment paths, and connecting UI elements like buttons and links to specific functions for handling document attachments, record navigation, and date selection. | def __init__(self, parent=None):
super(NightLetterMain, self).__init__(parent)
self.ui = Ui_MainWindow()
self.DBDataSource = "NightLetterData" #Important: This tells the application which table to query in the DB.
self.AttachmentFolderPath = "W:\\CLTBODY\\Kotter\\Projects\\Night Lette... |
def get_last_legionella_date():
influx_db = "test1"
influx_query = {'q': "select last(temp) from boiler where temp >= 60"}
r = requests.get(url=influx_url1 + influx_db, params=influx_query).json()
if len(str(r)) <= 40:
date_last_legionella = "1999-01-01 01:01:01T0000"
else:
date_last... | The function determines whether to start or stop heating based on conditions like legionella safety, PV power levels, room temperature, and water temperature states. It evaluates sensor data, categorizes system states (1-5), and triggers heating actions if criteria like low water temp, sufficient PV power, or room cond... | def decide_what_2_do():
days_since_last_legionella = datetime.datetime.strptime(str(datetime.datetime.now()).split(" ", 1)[0],'%Y-%m-%d') \
- datetime.datetime.strptime(str(get_last_legionella_date().split(" ", 1)[0]).replace("T", " ").split(" ", 1)[0], '%Y-%m-%d')
pv_last_peak_... |
def setup():
squares = [y + x for x in "12345678" for y in "abcdefgh"]
start = "RNBQKBNR" + "P" * 8 + " " * 32 + "p" * 8 + "rnbqkbnr"
board_view = dict(zip(squares, start))
piece_view = {_:[] for _ in start}
for sq in board_view:
piece = board_view[sq]
if piece != " ":
... | This function converts a list of chess moves into a sequence of FEN (Forsyth–Edwards Notation) strings representing the board state after each move. It processes castling, piece movement, and captures, updating the board and turn information iteratively. The output includes all intermediate FENs, the final board view, ... | def pgn_to_fen(moves: [(str, str)]) -> [str]:
whose_move = WHITE
board_view, piece_view = setup()
all_fen = ["rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w"]
for each in moves:
for move in each:
if move in all_castling:
if whose_move =... |
def process_arguments(args):
parser = argparse.ArgumentParser(description='generate video')
parser.add_argument('--video', action='store', help='path to directory of input video')
parser.add_argument('--dir', action='store', help='path to directory of directories of input videos')
parser.add_argument('-... | The code processes command-line arguments to generate videos. It sets parameters (sa, co, sh) from input, defaults to 1.0. If a 'video' path is provided, it generates a single video; if a 'dir' path is given, it processes all files in the directory, overwriting existing outputs. The 'sacosh' argument allows custom para... | def main():
params = process_arguments(sys.argv[1:])
sa, co, sh = 1.0, 1.0, 1.0
if params['sacosh'] is not None:
sacosh = params['sacosh'].split(',')
sa, co, sh = float(sacosh[0]), float(sacosh[1]), float(sacosh[2])
if params['video'] is not None:
gen_video(params['video'], sa, c... |
def generate_spacetime_coloc_rand(space, time, n_coll_dim, tensor=False):
"""
Given N-dimensional array of space begin and end coordinates (e.g. [x0,x1])
and 1D array of time begin and end ([t0,t1])
return tensorflow tensor of n_coll_dim**2 randomly sampled points (x,t)
with shape (n_coll_dim**N, N+... | The code trains a neural network to approximate physical systems using data and physics-informed losses. It iteratively computes predictions, calculates data and physics losses, and updates weights via gradient descent. Collocation points are randomized periodically, and the network's complexity increases via an anneal... | def train(self, space_vec, data_vec, n_coll_dim, space_range, time_range, epochs=80000, randomize_ep=1, lr_decay=0.75, warmup_eps=0, nc_prog=None, anneal_eps = 8500):
"""
space_vec: input location tensor; shape (n_pts, 2); for bounding positions in spacetime
data_vec : input data tensor; shape (... |
def validasi(cekapa,inputnya,rangemin = None,rangemax = None) :
if cekapa == 1 : # CEK SESUAI RANGE
if inputnya < rangemin or inputnya > rangemax :
showMessages(2)
return False
else :
return True
elif cekapa == 2 : # CEK INPUT Y / N / 0
if inputnya == ... | The function prompts the user to view employee or position lists based on the 'what' parameter, validates input (Y/N/0), and returns the choice. It loops until valid input is received, allowing navigation to submenus or returning to the previous menu. Error handling ensures correct selections, with '0' exiting the subm... | def promptToSee(what) :
if what == 'empl' :
while True :
subMenuInput = input('Apakah anda mau melihat daftar karyawan terlebih dahulu?\n(Y/N) atau 0 untuk kembali ke menu sebelumnya :').upper()
if validasi(2,subMenuInput) :
break
if subMenuInput == 'Y' :
... |
def draw_menu(self): # draw the menu screen
new_background_color = (0, 0, 0)
pygame.draw.rect(self.screen, new_background_color,
(0, 0, self.width, self.height))
menu_color = self.WHITE
menu_width = self.width * 0.9 # Adjust menu width to be 90% of the screen ... | The code implements a game loop for a Tic-Tac-Toe-like game using Pygame, handling user input for grid clicks, game over states, score display, and AI vs. human gameplay. It checks for mouse events to reset the game, switch settings, or exit, updates the board state, and alternates between human and AI turns via the `p... | def play_game(self): # play the game function
done = False
clock = pygame.time.Clock()
self.draw_menu()
while not done:
for event in pygame.event.get(): # checks if user clicked on grid or quit
"""
YOUR CODE HERE TO CHECK IF THE USER CLICKE... |
def connect():
global conn
if not conn:
conn = sqlite3.connect("session_db.sqlite")
conn.row_factory = sqlite3.Row
def create_session():
query = '''CREATE TABLE IF NOT EXISTS Session (sessionID INTEGER PRIMARY KEY,
startTime TEXT, startMoney REAL, stopTime TEXT, stopMoney REAL);'''
... | The main task of the code is to connect to a system, create a session, retrieve the last session's data, print the session's stopMoney value, and then close the connection. It performs basic session management and data retrieval operations. | def main():
connect()
create_session()
session = get_last_session()
print("Money:", session.stopMoney)
close() |
def align_with_bboxes(
latents_all_list, mask_tensor_list, bboxes, horizontal_shift_only=False
):
"""
Each offset in `offset_list` is `(x_offset, y_offset)` (normalized).
"""
new_latents_all_list, new_mask_tensor_list, offset_list = [], [], []
for latents_all, mask_tensor, bbox in zip(
l... | The function `compose_latents_with_alignment` integrates latent representations of background, moved, and changed objects into a unified latent space. It aligns object latents with specified bounding boxes, handles spatial transformations for moving objects, combines foreground and background masks, and composes the fi... | def compose_latents_with_alignment(
model_dict,
latents_bg_lists,
latents_all_list,
mask_tensor_list,
original_remove,
change_objects,
move_objects,
num_inference_steps,
overall_batch_size,
height,
width,
align_with_overall_bboxes=True,
overall_bboxes=None,
horizo... |
def getTile(self, coordinates):
return self.Pieces[coordinates[0]][coordinates[1]]
def Algo_Pawn(self, x, y):
foundTiles = []
curruntTile = self.getTile([x, y])
toUp = 1
if curruntTile.hasMoved:
toUp = 1
else:
toUp = 2
foundTiles.extend... | This method determines valid moves for a chess piece by identifying its type (e.g., Pawn, Bishop) and invoking corresponding algorithms. It retrieves the piece's position, checks its identity, and calculates potential moves using specialized functions like Algo_Pawn or FindAngle45. The result is a list of valid positio... | def getMovables(self,toMovePiece,curruntSide):
self.toMovePiece = toMovePiece
self.curruntSide = curruntSide
toMovePiece = self.getTile(self.toMovePiece)
Movables = []
if toMovePiece.pid == CONSTANTS.PIECE_IDS["Pawn"]:
Movables = self.Algo_Pawn(
self.... |
def set_key_input(self):
player=self.player.sprite
player.game_status=self.edit_mode
key_input=pygame.key.get_pressed()
if key_input[pygame.K_e] and self.edit_mode=='playing':
self.edit_mode='edit'
pygame.time.delay(100)
elif key_input[pygame.K_e] and self... | This code handles game state updates and rendering based on the 'edit_mode' setting. In 'playing' mode, it updates game elements (tiles, enemies, player), applies scrolling, checks collisions, and draws the scene. In 'edit' mode, it manages map editing, draws the background/grid, updates tiles, and renders UI elements.... | def run(self):
self.set_key_input()
# print(self.minus_scroll_x_edit)
if self.edit_mode=='playing':
self.screen.fill('#aff9f0')
self.collide_horizon()
self.collide_vertical()
self.tiles.update(self.player.sprite.scroll_x_speed,self.player.sprite.sc... |
def ROI_center(mask):
roi_coord = ROI_coord(mask)
x_center = int(roi_coord[0] + (roi_coord[1] - roi_coord[0]) / 2)
y_center = int(roi_coord[2] + (roi_coord[3] - roi_coord[2]) / 2)
return [x_center, y_center]
def color_black(img, mask, binary, ROI_center_coord, side):
dist = []
if side == 'right'... | The code preprocesses medical images (e.g., mammograms) by flipping images to standardize breast orientation, binarizing pixel values, applying ROI-based masking, removing artifacts, cropping backgrounds, enhancing contrast with CLAHE, and saving processed images/masks. It handles dataset-specific naming, processes pai... | def preprocessing(df, path_img, path_mask, path_img_out, path_mask_out, name_complete_csv, name_mask_csv, dataset_name,
save):
for (image_name, mask_name) in zip(list(df[name_complete_csv]), list(df[name_mask_csv])):
if dataset_name == 1:
image_name = str(image_name) + '.png'
... |
def animText(message):
color = ['red', 'yellow', 'blue', 'green', 'cyan', 'Purple']
for character in message:
random.shuffle(color)
console.print(character, end='', style=f'{color[0]} bold')
time.sleep(0.05)
def predict(message):
bow = wordBag(message)
res = model.predict(np.arr... | The code defines an interactive AI assistant that processes user inputs, performs actions like date/time display and basic math operations (add, subtract, multiply, divide) based on keyword detection, and provides responses using a prediction model and dataset. It features animated text and a styled logo for engagement... | def helloAI():
logo = render("Hello AI", align='left', font='chrome', colors=['red', 'blue', 'yellow'], background='transparent',
transition=True, space=False)
print(logo)
animText("Hey!, I am here. \n")
animText("Yeess!!! we are online now \n")
tDate = datetime.datetime.now()
... |
def loadLocalData(self):
try:
with open("data.txt","r") as f:
self.data = json.load(f)
print("Loaded Local")
if len(self.data["data"]) <1:
self.loadApiData()
else:
pass
except FileNotFoundError:
self.loadApiData()
def LoadLocalCoins(self):
t... | The code initializes a class instance by setting attributes like `data`, `coins`, and `myTotal`, loads local data and coin information using `loadLocalData()` and `LoadLocalCoins()`, populates name lists, and triggers a `process()` method to handle further logic. | def __init__(self):
self.data = None
self.coins = None
self.myTotal = 0
self.globalNameList = []
self.loadLocalData()
self.LoadLocalCoins()
self.nameList = []
self.process() |
def saveCoins(self):
with open("coins.txt","w") as f:
json.dump(self.coins,f)
def process(self):
a = self.data["data"]
self.nameList = []
self.globalNameList = []
self.symbolNameConverter = {}
for k in self.coins.keys():
self.nameList.append(k)
cleandata = []
f... | The main task of the code is to update the `coins` dictionary by either adding or removing a value `v` associated with a key `k`. It first converts `k` using a symbol converter and standardizes its format. If "remove", it subtracts `v` from the coin's value; if "add", it adds `v` (or initializes the key if absent). Aft... | def updateCoins1(self,k,v,addremove):
if k.lower() in self.symbolNameConverter:
k = self.symbolNameConverter[k.lower()]
k = k.lower().capitalize()
if addremove == "remove":
self.coins[k] = self.coins[k] - v
self.saveCoins()
self.process()
self.loadLocalData()
elif addremove... |
def check_collisions(self, bubble, bubbles):
distance = self.outline_distance(bubble, bubbles)
return len(distance[distance < 0])
def center_of_mass(self):
return np.average(
self.bubbles[:, :2], axis=0, weights=self.bubbles[:, 3]
)
def collides_with(self, bubble, bubbles):
... | This function iteratively moves bubbles toward their center of mass (COM) over `n_iterations`, adjusting positions to avoid collisions. For each bubble, it calculates a direction vector toward the COM, attempts a move, and checks for collisions. If collisions occur, it tries orthogonal adjustments to navigate around ob... | def collapse(self, n_iterations=50):
"""
Move bubbles to the center of mass.
Parameters
----------
n_iterations : int, default: 50
Number of moves to perform.
"""
for _i in range(n_iterations):
moves = 0
for i in range(len(self... |
def obj_size(self, obj):
ww, wh = self.paras["size"]
wider = wh/ww < h/w
w_size = wh if wider else ww*h/w
size = [s*w_size for s in obj.size]
return(size)
def obj_pos(self, obj):
ww, wh = self.paras["size"]
wider = wh/ww < h/w
w_size = wh if wider else ww*... | This code renders a game object on a screen by adjusting its size, alpha transparency, and position, then blits the scaled image and associated text box. It handles both the main object graphic and its text elements, ensuring proper display with calculated scaling and positioning. | def render(self, obj):
size = self.obj_size(obj) ; pos = self.obj_pos(obj)
obj.color = obj.color[:3] + (int(obj.alpha),)
obj.obj.set_alpha(obj.alpha)
OBJ = pygame.transform.scale(obj.obj, size)
self.screen.blit(OBJ, pos)
obj.show_text()
if(obj.text_box != None):
... |
def remove_object(self, ID):
pop_these = []
for i, obj in enumerate(self.objects):
if obj.ID == ID:
pop_these.append(i)
for i in reversed(pop_these): self.objects.pop(i)
def render(self, obj):
size = self.obj_size(obj) ; pos = self.obj_pos(obj)
obj.col... | This code runs a Pygame game loop, handling user input (mouse/keyboard), updating object states (fading, dragging), rendering objects, and managing interactions (clicks, text input). It processes events, updates display, and maintains object behaviors like dragging, fading, and typing, ensuring real-time interaction an... | def run(self):
running = True ; frames = 0
old_pos = pygame.mouse.get_pos()
while running:
frames += 1 ; pos = pygame.mouse.get_pos()
for obj in reversed(self.objects):
if(obj.constant != None):
obj.constant()
if(obj.fad... |
def get_piece_from_action(self, action):
return (action // 9) + 1
def get_index_from_action(self, action):
pos = self.get_pos_from_action(action) # [0-8]
piece_size = self.get_piece_size_from_action(action) # [1-3]
return pos + 9 * (piece_size - 1)
def is_legal(self, action, agent_index... | The code handles a player's turn in a game by validating a move, updating the game board with the player's piece at the specified index, and removing the piece from its previous position if it was already placed. It adjusts the piece's value for the second player (agent_index=1) and ensures only legal moves are execute... | def play_turn(self, agent_index, action):
piece = self.get_piece_from_action(action)
if agent_index == 1:
piece = piece * -1
index = self.get_index_from_action(action)
# First: check if a move is legal or not
if not self.is_legal(action, agent_index):
ret... |
def get_args() -> argparse.Namespace:
parser = get_parser()
return parser.parse_known_args()[0]
def get_env(render_mode=None, args=None):
return PettingZooEnv(gobblet_v1.env(render_mode=render_mode, args=args))
def get_agents(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] ... | The code simulates and observes trained agents in a PettingZoo environment, collecting rewards and rendering gameplay. It initializes policies, configures evaluation modes, and uses a Collector to gather step data. If enabled, it records frames as a GIF. The loop runs until the environment terminates, printing final re... | def watch(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] = None,
agent_opponent: Optional[BasePolicy] = None,
) -> None:
env = DummyVectorEnv([lambda: get_env(render_mode=args.render_mode, args=args)])
policy, optim, agents = get_agents(
args, agent_learn=agent_lea... |
def get_args() -> argparse.Namespace:
parser = get_parser()
return parser.parse_known_args()[0]
def get_env(render_mode=None, args=None):
return PettingZooEnv(gobblet_v1.env(render_mode=render_mode, args=args))
def get_agents(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] ... | This code runs a human vs AI gameplay loop in a PettingZoo environment, using a trained policy for the AI agent and manual keyboard input for the human player. It initializes the environment, configures exploration parameters, collects observations, executes actions, and displays final rewards. The loop alternates betw... | def play(
args: argparse.Namespace = get_args(),
agent_learn: Optional[BasePolicy] = None,
agent_opponent: Optional[BasePolicy] = None,
) -> None:
env = DummyVectorEnv([lambda: get_env(render_mode=args.render_mode, args=args)])
# env = get_env(render_mode=args.render_mode, args=args) # T... |
def get_report(logs):
if logs:
# Output options
if args.csv:
try:
keys = logs[0].keys()
except KeyError:
keys = logs.keys()
with open(args.csv, 'w') as outfile:
dict_writer = csv.DictWriter(
outf... | The main task of the code is to generate a report based on user-specified inputs (file, IP, CIDR block, or country code) over a defined number of days. It validates CIDR blocks using regex, defaults to 30 days if unspecified, and exits with errors for invalid inputs or missing required arguments. The script uses argpar... | def main():
if args.days:
days = args.days
else:
days = 30
if args.file:
get_report(check_file(args.file, days))
elif args.ip:
get_report(check_ip(args.ip, days))
elif args.block:
regex = r'^([0-9]{1,3}\.){3}[0-9]{1,3}(\/([2][4-9]|3[0-2]))?$'
valid_bl... |
def log_failed_download(link):
if any(pattern in link for pattern in dropbox.url_patterns):
filename = "dropbox.txt"
elif any(pattern in link for pattern in googledrive.url_patterns):
filename = "gdrive.txt"
elif any(pattern in link for pattern in mega.url_patterns):
filename = "mega... | The code downloads a file from a given URL, corrects potential URL formatting issues, handles download errors, saves the content to a file with a generated name, and unpacks the file while removing the original download. | def download(url, fname=None):
try:
url = str(url).replace('http://https://', 'https://', 1) # http://https:// sometimes seems to happen?
url = str(url).replace('http://https//', 'https://', 1) # http://https// sometimes seems to happen?
response = requests.get(url, allow_redirects=True)
... |
def initSigGen(self):
self.ui.pushButton_sg_connect.clicked.connect(lambda: sigGen.connect())
self.ui.pushButton_sg_disconnect.clicked.connect(lambda: sigGen.disconnect())
self.ui.pushButton_sg_set.clicked.connect(lambda: self.setSigGenParam())
self.ui.pushButton_sa_run.clicked.connect(l... | This code initializes a GUI application by setting up the main window's UI components, connecting them to respective functions for signal generation, oscilloscope, and spectrum analyzer. It also initializes state variables to control graph display for the oscilloscope and spectrum analyzer. | def __init__(self):
super(App, self).__init__()
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
# connect ui to functions
self.initSigGen() # Signal Generator UI
self.initOScope() # Oscilloscope UI
self.initSpecAn() # Spectrum Analyzer UI
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.