dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def self_tuning(self, tau=0.5, standardize=True):
'''
A Simulation-based Approach for Choosing the Penalty Level (Lambda)
Reference
---------
l1-Penalized Quantile Regression in High-dimensinoal Sparse Models (2011)
by Alexandre Belloni and Victor Chernozhukov
... | This function performs model selection using the Bayesian Information Criterion (BIC) for quantile regression with penalized methods like L1, SCAD, or MCP. It computes BIC values across a sequence of lambda regularization parameters, selects the model with the minimum BIC (or constrained by max_size), and returns the c... | def bic(self, tau=0.5, h=None, lambda_seq=np.array([]), nlambda=100,
kernel="Laplacian", order='ascend', max_size=False, Cn=None,
penalty="SCAD", a=3.7, nstep=5, standardize=True, adjust=True):
'''
Model Selection via Bayesian Information Criterion
Reference
... |
def top10recommended(self):
top10recommended = []
recommended_movies = self.main()
for movie in recommended_movies :
if len(movie.title) < 10:
top10recommended.append(movie)
if len(top10recommended)> 10:
return top10recommended[:10]
return... | This method populates a context dictionary with movie recommendations and mood-related data for a web template. It retrieves top 10 recommended movies, maps a mood to a genre, adds movies to the context if available, sets an empty mood string, and fetches mood-based recommendations using the genre. The context is then ... | def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
movies = self.top10recommended()
genre = self.mood_to_genre()
if movies:
context["movies"] = movies
context["mood"] = ""
context["mood_movies"] = self.get_mood_based_recommendat... |
def load_data(portfolio_path, profile_path, transcript_path):
"""
It loads the datasets
:param profile_path
:param portfolio_path
:param transcript_path
:return the dataframes content
"""
portfolio = pd.read_json(portfolio_path, orient='records', lines=True)
profile = pd.read_json(p... | The main task of the code is to train a linear regression model using data from portfolio, profile, and transcript files. It loads, cleans, and splits the data into training/test sets, trains the model, evaluates performance with R² scores, and saves feature relevance coefficients to an Excel file. The script requires ... | def main():
if len(sys.argv) == 4:
portfolio_path, profile_path, transcript_path = sys.argv[1:]
print('Loading data...\n PORTFOLIO: {}\n PROFILE: {}\n TRANSCRIPT: {}'
.format(portfolio_path, profile_path, transcript_path))
portfolio, profile, transcript = load_data(port... |
def choose_character():
starting_location = village
player_name = input("What's your name?: ")
print("\n--- Class ---")
print("1. Knight \t Health: 100 \t Attack Power: 10")
print("2. Mage \t Health: 80 \t Attack Power: 15")
print("3. Archer \t Health: 90 \t Attack Power: 12")
choice = i... | The main task of the code is to present a text adventure game's main menu, allowing users to start a new game, load a saved game, or quit. It handles user input to trigger character creation, game loading, or exit, and directs gameplay flow by calling respective functions like `choose_character()`, `save_game()`, `intr... | def main_menu():
print("Welcome to your Text adventure!")
print("1. Start New Game")
print("2. Load a save. ")
print("3. Quit. ")
mainMenu = int(input("\nChoice: "))
if mainMenu == 1:
player = choose_character()
save_game(player)
intro(player)
elif mainMenu == 2:
... |
def tgear(thtl):
'tgear function'
if thtl <= .77:
tg = 64.94 * thtl
else:
tg = 217.38 * thtl - 117.38
return tg
def conf16(x, u, const):
'apply constraints to x'
radgam, singam, rr, pr, tr, phi, cphi, sphi, thetadot, coord, stab, orient = const
gamm = asin(singam)
#
... | This function computes an objective cost for optimization to determine trim conditions in flight dynamics. It modifies input variables x (state) and u (controls) in-place, calculates derivatives using a model (e.g., 'stevens'), and computes a weighted cost 'r' based on flight orientation (level flight, climb, turn, pit... | def clf16(s, x, u, const, model='stevens', adjust_cy=True):
'''
objective function of the optimization to find the trim conditions
x and u get modified in-place
returns the cost
'''
_, singam, _, _, tr, _, _, _, thetadot, _, _, orient = const
gamm = asin(singam)
if len(s) == 3:
... |
def train_test_index_split(data_idx, k=5, CV=False):
'''
Shuffles data indices and splits into k bins, where the testing data takes 1 bin, and the training data takes k-1.
INPUT:
data_indices: a 1D array of indices to be shuffled
OUTPUT:
if CV=False:
train_idx, test_idx
if ... | The main task of the code is to find the optimal candidate model (v_star) from a list of candidates by evaluating their performance via cross-validation on training data. It then trains this selected model on the full training set and evaluates its performance on the test set, returning the best model along with its tr... | def find_best_val(data_idx, kernel_mat, candidates, epochs=3, k=5, calc_conf=True, keep_mistakes=True):
train_idx, test_idx = train_test_index_split(data_idx)
scores = np.array([cross_val(train_idx, kernel_mat, candidates[i], epochs) for i in range(len(candidates))])
v_star = candidates[np.argmin(scores)... |
def train_test_index_split(data_idx, k=5, CV=False):
'''
Shuffles data indices and splits into k bins, where the testing data takes 1 bin, and the training data takes k-1.
INPUT:
data_indices: a 1D array of indices to be shuffled
OUTPUT:
if CV=False:
train_idx, test_idx
if ... | The function `find_best_val_ovo` identifies the optimal candidate parameter (`v_star`) by evaluating each candidate's performance via cross-validation on training data. It then trains a perceptron using the best candidate on the training set and evaluates it on the test set, returning `v_star` along with training and t... | def find_best_val_ovo(data_idx, kernel_mat, candidates, epochs=3, k=5, keep_mistakes=True):
'''
Implements the method in question 2.
'''
train_idx, test_idx = train_test_index_split(data_idx)
scores = np.array([cross_val_ovo(train_idx, kernel_mat, candidates[i], epochs) for i in range(len(cand... |
def train_test_index_split(data_idx, k=5, CV=False):
'''
Shuffles data indices and splits into k bins, where the testing data takes 1 bin, and the training data takes k-1.
INPUT:
data_indices: a 1D array of indices to be shuffled
OUTPUT:
if CV=False:
train_idx, test_idx
if ... | The function `find_best_val` identifies the optimal candidate model (`v_star`) by minimizing cross-validation scores across given candidates. It splits data into training/test sets, evaluates each candidate's performance using cross-validation, selects the candidate with the lowest score, and then trains a perceptron m... | def find_best_val(data_idx, kernel_mat, candidates, epochs=3, k=5, calc_conf=True, keep_mistakes=True):
'''
Implements the method in question 2.
'''
train_idx, test_idx = train_test_index_split(data_idx)
scores = np.array([cross_val(train_idx, kernel_mat, candidates[i], epochs) for i in range(... |
def paymentCost(cart_items, pinCode):
print(pinCode, "pinCode")
amountPayable = {}
discount_percentage = list(cart_items.values_list("coupon_code__discount_percentage", flat=True))
mrpTotal, discount, totalPayable, withOutDiscount, couponDiscount, mumbaiCharge, india, east, shippingAmount = 0, 0, 0, 0, ... | This function processes a user's cart checkout by handling COD and UPI payments. It filters cart items, validates inventory, calculates charges, creates orders, updates quantities, sends confirmation/failure emails, and redirects post-payment. It also cleans up cart data after successful transactions. | def overview(request):
cart_items = Cart.objects.filter(user=request.user)
cart_items.filter(book__quantity__lte=0).delete()
merchantId = PHONEPAY_MERCHANT_ID
deliveryAddress=DeliveryAddress.objects.get(id=list(cart_items.values_list("deliveryAddress", flat=True))[0])
print("deliveryAddress",deliver... |
def load_pickle(filename):
with open(filename, 'rb') as f:
data = pickle.load(f)
return data
def check_makedirs(dir_name):
if not os.path.exists(dir_name):
os.makedirs(dir_name)
def proc_pert(points, gt, pred, folder,
names, part=False, ignore_label=255):
"""Process and sav... | The function `save_vis` processes and saves visualizations for 3D point cloud data from either S3DIS or ScanNet datasets. It loads ground truth and predicted labels, validates data consistency, creates directories, and applies `proc_pert` to generate output files. For S3DIS, it handles Area5 data; for ScanNet, it proce... | def save_vis(pred_root, save_root, data_root):
from config import CLASS_NAMES
if 'S3DIS' in data_root: # save Area5 data
names = CLASS_NAMES['S3DIS']['other']
gt_save = load_pickle(
os.path.join(pred_root, 'gt_5.pickle'))['gt']
pred_save = load_pickle(
os.path.jo... |
def plant(self): #Plant mines
iter = 0
while iter < self.mine :
temp = self.randTuple()
if(self.board[temp[0]][temp[1]] != "X"):
self.board[temp[0]][temp[1]] = "X"
iter += 1
def populate(self): #Populate the numbers
print(" ")
#Iter... | The main task of the code is to run a game loop that plants and populates game elements, repeatedly displays the current state, processes user input, checks for a win condition, and terminates when the game ends, finally printing the game state and a "You won!" message. | def main(self):
self.plant()
self.populate()
while(not self.gameOver):
print(self.showShown())
self.ask()
self.checkWin() #Win is outside, Loss terminates program
print(self)
print("You won!") |
def get_game_info(game_name: str):
"""
returns the game info of the specified name
"""
collection = connect_to_db()
if collection is None:
return None
# find the game with the specified game_name in the database
game_info = collection.find_one({"name": game_name})
if game_info ... | This function adds a player to a specified game if they are not already participating. It updates the game's player list, marks the player as alive, saves the changes, and shuffles the game's targets. The process ensures no duplicates and maintains game state consistency. | def add_player_to_game(game_name: str, netid: str):
"""
adds player to game and shuffles the targets
"""
game_info = get_game_info(game_name)
if game_info == None:
return
# Check if player is already in game
if netid in game_info["players"]:
return
# add player to game
... |
def get_game_info(game_name: str):
"""
returns the game info of the specified name
"""
collection = connect_to_db()
if collection is None:
return None
# find the game with the specified game_name in the database
game_info = collection.find_one({"name": game_name})
if game_info ... | This function processes a player killing their target in a game by removing the target from the alive list, adding them to the dead list, sending notifications, transferring the target's assignment to the killer, incrementing the killer's kill count, and updating the game state in the database. | def killed_target(game_name: str, netid: str):
"""
The netid of the player that killed their target.
Removes target from alive list and increases player's kill count
"""
game_info = get_game_info(game_name)
if game_info is None:
return None
# Ensure the killer is alive
if ne... |
def process_csv_and_create_game(file_path, game_name):
player_netids = []
with open(file_path, newline='', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# Extract player information
netid = row['netID']
full_name = row['Full... | This code tests the setup of an "Ivy Assassin" game by creating a game instance from a CSV file, retrieving game data, and simulating the distribution of target assignments to alive players via email. It verifies the game initialization process and email notification functionality for player targets. | def test_ivy_assassin():
with app.app_context():
# Create new game
game_name = "ivy"
process_csv_and_create_game('ivy_assassin_signup.csv', 'ivy')
game_info = get_game_info(game_name)
print("alive:", game_info["alive_players"])
targets = game_info["targets"]... |
def new_player(netid: str, name: str, nickname = None, email = None):
"""
creates a new player and adds it to the players collection in db
"""
players_collection = connect_to_db(collection_name="players")
if players_collection is None:
return None
# clean netid
netid = netid.low... | This test function verifies the functionality of an assassin game system by creating a game with three players, checking initial game/player data, simulating a kill, and validating state changes (dead players, kill counts). It also prompts manual verification of email notifications for game events. | def test_assassin_game():
with app.app_context():
# Create new game
game_name = "Test Game 2"
players_list = ["piercemaloney1", "pmaloney", "kmaloney"]
new_player('piercemaloney1', 'Pierce Maloney 1', nickname='Slaya', email='friyn@example.com')
new_player('pmaloney', 'Pierce... |
def parse_fasta(file_name, database):
"""
COMPLETE
"""
with open(file_name) as fp:
while True:
# strips > symbols change this?
identifier = (fp.readline()).strip()
no_arrow = identifier[1:]
sequence = (fp.readline()).strip()
if not seq... | The code constructs a phylogenetic tree using the UPGMA algorithm. It reads FASTA files into a database, calculates pairwise distances between sequences, builds a distance matrix, and generates a hierarchical clustering tree. The resulting tree is saved in Newick format. | def main():
# BUILD DATABASE
database = dict()
id_list = []
#data_base = "database_test.txt"
data_base = "database-sequences.fasta"
parse_fasta(data_base, database)
sus_file = "query-sequence.fasta"
parse_fasta(sus_file, database)
size = len(database)
d_matrix = [[0 for x in... |
def _refreshOptions(self):
self._ui.identifier_label.setText('Identifier: ' + self._model.getIdentifier())
self._ui.displayDataPoints_checkBox.setChecked(self._segmentation_data_model.isDisplayDataPoints())
self._ui.displayDataContours_checkBox.setChecked(self._segmentation_data_model.isDisplay... | This method initializes the graphics scene in a SceneviewerWidget upon its creation. It loads model settings, refreshes UI options, sets the scene from the model, configures camera parameters, enables slow transparency mode, and triggers automatic line adjustments and a simulated view-all button action to finalize scen... | def _graphicsInitialized(self):
"""
Callback for when SceneviewerWidget is initialised
Set custom scene from model
"""
sceneviewer = self._ui.sceneviewer_widget.getSceneviewer()
if sceneviewer is not None:
self._model.loadSettings()
self._refreshOp... |
def extract_img_tags(self):
""" Extracts all image src links from the html document """
if self.doc:
img_tags = self.doc.find_all('img')
return img_tags
def get_img_url_from_tag(self, img_tag):
return img_tag.get('src') if img_tag and img_tag.get('src') else None
def refi... | The main task of the code is to extract the latest image URL from a webpage, prioritizing images with a title matching the page's title, and falling back to the largest image if no title match is found. It handles edge cases like single-image pages and ensures robustness by refining URLs and using fallback logic when i... | def extract_latest_img_url(self):
"""
Extracts latest image url from the page
Assumptions:
1. If there is only one image on the page, return that
2. Image url with the title is the most accurate if there are multiple image urls
3. If the previous step fails, the image ur... |
def find_endpoint(service_type, production=True, monitored=True, site=None):
"""
Searching GOCDB for endpoints according to service types and status
:param service_type:
:param production:
:param monitored:
:param site: list of sites, None for searching all sites
:return: list of endpoints... | The function retrieves projects from OpenStack Nova endpoints for a given site using an access token. It iterates over endpoints, obtains unscoped tokens, fetches project details (ID, name, status), and compiles them with endpoint information into a list, which is returned. | def get_projects_from_sites(access_token, site):
"""
Get all projects from sites using access token
"""
project_list = []
for ep in find_endpoint("org.openstack.nova", site=site):
os_auth_url = ep[2]
unscoped_token, _ = get_unscoped_token(os_auth_url, access_token)
project_li... |
def __to_json(self, obj) -> Dict[str, any]:
return json.dumps(obj, indent=4, allow_nan=True)
def __create_file_path(self, metadata: bool = False) -> str:
path = Config.GCS_DUMP_DIR
base_name = Config.RAW_DATA_FILE_NAME
file_ext = ".json"
current_datetime = datetime.now(timezone... | The main task of the code is to serialize a file object into JSON format, generate a GCS file path using metadata (if enabled), and upload the JSON data to a Google Cloud Storage bucket with a specified timeout. The function handles conversion, path creation, and GCS upload operations to store structured data in cloud ... | def dump_to_gcs_bucket(
self, file_object, metadata: bool = False, timeout: int = 60
) -> None:
file_object = self.__to_json(file_object)
gcs_dump_path = self.__create_file_path(metadata)
self.__dump_to_gcs(file_object, gcs_dump_path, timeout) |
def __table_exists(self, dataset: str, table_name: str) -> bool:
if not self.__dataset_exists(dataset):
return False
dataset_table = self.bq_client.dataset(dataset).table(table_name)
return self.__exist(self.bq_client.get_table, dataset_table)
def __create_table(
self,
... | (The function inserts a pandas DataFrame into a specified BigQuery table, creating the table with the given schema if it does not already exist.) | def insert_df(
self,
df: pd.DataFrame,
dataset_name: str,
table_name: str,
schema: Dict[str, any]
) -> None:
if not self.__table_exists(dataset_name, table_name):
self.__create_table(dataset_name, table_name, schema)
self.__insert_df_to_bq_table(d... |
def handle_circle_event(self):
"""Handle circle events and remove arcs that disappear."""
event = self.event.pop()
if event.valid:
edge = Edge(event.p)
self.output.append(edge)
arc = event.a
if arc.pprev is not None:
arc.pprev.pnex... | The main task of the code is to construct a Voronoi diagram by processing site and circle events in a priority queue. It alternates between handling site events (adding new points) and circle events (forming vertices where three circles intersect), ensuring proper edge connections. After exhausting all points, remainin... | def run_diagram(self):
"""Run the Voronoi diagram algorithm."""
while not self.points.empty():
if not self.event.empty() and (self.event.top().x <= self.points.top().x):
self.handle_circle_event()
else:
self.handle_site_event()
while not s... |
def parse_args():
global frame_count_between_updates
global frame_no_display
global frame_min_size_areas
global frame_write_addon_count
global frame_idle_count
global frame_reset_count
global frame_one_file_only
global frame_write_jpgs
global frame_jpgs_min
global frame_jpgs_capt... | The main task of the code is to monitor a camera feed for motion detection, capture and save video or JPG files when motion is detected, manage video file segmentation during idle periods, and send processed file paths to a queue for further handling. It uses frame differencing and contour analysis to detect moving obj... | def camera_monitor(queue):
parse_args()
send_args(queue)
# create a VideoCapture object
cap = cv2.VideoCapture(camera_number)
# check if camera opened successfully
if (cap.isOpened() == False):
print("VideoCapture cannot open the camera: " + str(camera_number))
exit(0)
# ... |
def fuse2(points, d):
ret_exp = []
d2 = d * d
len_l = [len(points)]
check = 0
while check == 0:
ret = []
n = len(points)
taken = [False] * n
for i in range(n):
if not taken[i]:
count = 1
point = [points[i][0], points[i][1]]
... | The function detects and analyzes protein spots in images by thresholding, clustering local maxima, filtering coordinates, and visualizing results. It processes grayscale and color images, normalizes coordinates, checks linear arrangements, and generates plots for analysis, returning ordered coordinates, linearity scor... | def prot_det (test, SPR, processing_dir, img_gs, img_color_file, int_thr, d_thr_site_nm, d_thr_str_nm, index, site_d, site_n_limit, pix_nm_SPR):
# Open png files in dir
from skimage.feature import peak_local_max
import cv2
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import... |
def Dist(p1, p2):
import numpy as np
return np.sqrt(Dist2(p1, p2))
def rot_angle_calc(p1,p2):
#import packages used
import numpy as np
#Define reference point (p3) to define axis to rotate to
x1,y1 = p1
x2,y2 = p2
p3 = [x1, y2]
#Calculate distances between point for calculating ang... | This function aligns and quantifies protein spot positions in images by translating, rotating, and cropping based on reference coordinates. It detects peaks in defined regions to determine spot occupancy, maps localizations to sites, and returns processed data including cropped images, coordinates, and occupancy counts... | def align_and_quant(img_clr, img_gs, ord_coor, loc_array, loc_frames, SPR, pix_gap, crop_w_w, crop_w_h, spot_d, sweep_w_perc, site_n, min_peak_prom,
test, str_index):
# import packages used
import numpy as np
import copy
from scipy.signal import find_peaks
#
str_index = str_... |
def fuse2(points, d):
ret_exp = []
d2 = d * d
len_l = [len(points)]
check = 0
while check == 0:
ret = []
n = len(points)
taken = [False] * n
for i in range(n):
if not taken[i]:
count = 1
point = [points[i][0], points[i][1]]
... | The code detects protein spots in an image by thresholding a grayscale image, identifying local maxima, clustering peaks based on distance thresholds, normalizing coordinates, and visualizing results. It returns clustered coordinates, linear scores, and total distances for analysis. | def prot_det (test, red, SPR, processing_dir, img_gs, img_color_file, site_n_thr, int_thr, d_thr_site_nm, d_thr_str_nm, index, site_d, pix_nm_SPR):
# Open png files in dir
from skimage.feature import peak_local_max
import cv2
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
impo... |
def partition_match(match):
points = match['dtw']
if (len(points) > 0 and stats.linregress(points)[2] < MIN_R):
parts = partition(split_segments2(points))
print(match['file'], 'split into', [len(p) for p in parts])
return parts
return [[sorted(points)]]
def fill_gaps(tracks, lengths)... | The main task of the code is to generate timeline visualizations from input matches by processing partitions, filling gaps, and plotting segmented and partitioned timelines into PDF files. It extracts partition data, adjusts for gaps, and creates three distinct timeline plots: segment limits, partition limits (twice), ... | def construct_timeline(matches):
pairs = [[(partition_match(m), m['length']) for m in ms] for ms in matches]
partitions = [[p[0] for p in ps] for ps in pairs]
gapless = [[fill_gaps(p[0], p[1]) for p in ps] for ps in pairs]
plot_timelines([[seglimits(p) for p in ps] for ps in partitions], 'seglines.pdf')... |
def get_ref_tracks():
lengths = list(json.load(open(ref_lengths)).values())
ref_starts = [sum(lengths[:i]) for i in range(len(lengths))]
return [[[ref_starts[i], ref_starts[i]+lengths[i]]] for i in range(len(lengths))]
def partition_match(match):
points = match['dtw']
if (len(points) > 0 and stats.l... | The code processes audio match data to generate segment timelines. It retrieves reference tracks, partitions matches into segments, calculates segment limits, combines them with reference tracks, and plots the results as a timeline in 'seglines5.pdf', labeling tracks with specific filenames and directory paths. | def plot_seglines(matches):
ref_tracks = get_ref_tracks()
partitions = [[partition_match(m) for m in ms] for ms in matches]
limits = [[seglimits(p) for p in ps] for ps in partitions]
limits.insert(0, ref_tracks)
names = ['gd1982-10-10.nak700.anon-poris.LMPP.95682.flac16']+[d.replace(base_dir, '') fo... |
def get_ref_tracks():
lengths = list(json.load(open(ref_lengths)).values())
ref_starts = [sum(lengths[:i]) for i in range(len(lengths))]
return [[[ref_starts[i], ref_starts[i]+lengths[i]]] for i in range(len(lengths))]
def partition_match(match):
points = match['dtw']
if (len(points) > 0 and stats.l... | The code constructs a timeline by processing audio matches, resolving overlaps by adjusting track timings, applying tunings, and exporting results to JSON and PDF. It handles reference tracks, fills gaps, detects overlaps, shifts subsequent tracks, and generates visual timelines with tuning ratios for output. | def construct_timeline_forreal(matches):
ref_tracks = get_ref_tracks()
#print(ref_tracks)
partitions = [[partition_match(m) for m in ms] for ms in matches]
lengths = [[m['length'] for m in ms] for ms in matches]
tunings = [[m['tuning'] if 'tuning' in m else 0 for m in ms] for ms in matches]
... |
def sort_subgraphs(subs, lengths, ids_by_length):
flatsub = lambda l: list(set([list(l.keys())[0]] + [x for sublist in list(l.values())[0] for x in sublist]))
# file_lists sorted by list length
file_list = []
for i in ids_by_length:
file_list.append([i+'_'+t[0] for t in lengths[i]])
sorted_... | The main task of the code is to process subgraph data by identifying duplicate entries, then generating partitions based on relationships within each subgraph. It prepares data, sorts subgraphs, detects duplicates, and creates partitions by mapping track tuples to JSON IDs, using these keys to split data via the `parti... | def main():
subgraphs, ids_by_length, ids_by_number_of_matched_files, lengths, jsons = prepare_data(DATE)
subgraphs = sort_subgraphs(subgraphs, lengths, ids_by_length)
#json.dump(subgraphs, open('subgraphs.json', 'w'))
#json.dump(jsons, open('jsons.json', 'w'))
dupes = find_dupes(subgraphs)
ppri... |
def collision(obj, points, life, decay, music):
respawnX = random.randint(40, 381)
respawnY = random.randint(-450, 0)
player_loc = canvas.bbox(player_image)
food_loc = canvas.bbox(obj)
if (player_loc[1] < food_loc[3] < player_loc[3]) and (food_loc[2] > player_loc[0] > food_loc[0]... | This function moves a food item down the screen, checks for collisions, respawns it if it goes off-screen, adjusts game difficulty based on score, updates visuals (country/food images) at score thresholds, and schedules repeated execution to animate movement. | def food1_movement():
global velocity
global score
respawnX = random.randint(40, 381)
respawnY = random.randint(-450, 0)
canvas.move(drawFood1, 0, velocity)
food_coords = canvas.bbox(drawFood1)
collision(drawFood1, random.randint(50, 100), 0, 0, munch)
if... |
def collision(obj, points, life, decay, music):
respawnX = random.randint(40, 381)
respawnY = random.randint(-450, 0)
player_loc = canvas.bbox(player_image)
food_loc = canvas.bbox(obj)
if (player_loc[1] < food_loc[3] < player_loc[3]) and (food_loc[2] > player_loc[0] > food_loc[0]... | This function moves a food item down the screen, checks for collisions, respawns it if it goes off-screen, updates score/velocity, changes food images based on score thresholds, and schedules the next movement. | def food2_movement():
global velocity
global score
respawnX = random.randint(40, 381)
respawnY = random.randint(-450, 0)
canvas.move(drawFood2, 0, velocity)
food_coords = canvas.bbox(drawFood2)
collision(drawFood2, random.randint(50, 100), 0, 0, munch)
if ... |
def draw_ray(self):
win = self.window
pos = self.player_pos
ang = self.angle
x = pos[0] + (m.cos(m.radians(ang)) * ray_length)
y = pos[1] + (m.sin(m.radians(ang)) * ray_length)
#pg.draw.aaline(win, ray_color, pos, (x, y))
self.cast_multiple_rays()
def controls(se... | This method handles rendering and game logic updates, including drawing rays, player collision detection, control input when alive, intersection checks, enemy vision, power input validation, click events, menu return, and direction updates in a game environment. | def draw(self):
#self.ws = self.body.win_size
self.draw_ray()
self.player_rect_collision = pg.Rect(self.player_pos[0] - 10, self.player_pos[1] - 10, 20, 20)
#pg.draw.rect(self.window, rect_collision_color, self.player_rect_collision)
#self.player_circle = pg.draw.circle(win, 'w... |
def check_if_see_player(self):
self.see_player = self.body.player.seen_by_enemy
if self.see_player:
self.go_to_seen_pos = True
def draw_render_box(self):
self.render_box = [(self.enemy_coordinate[0] - 10, self.enemy_coordinate[1] - 10), (self.enemy_coordinate[0] + 10, self.enemy_coo... | The code defines a `draw` method that updates an object's chase speed, checks if the player is alive, and triggers actions like visibility checks, rendering, distance calculations, and movement when the player is alive. It prints speed values for debugging and orchestrates the object's behavior in response to the playe... | def draw(self):
self.chase_speed = self.speed * 2
print(self.speed, self.chase_speed)
if self.body.player.alive:
self.check_if_see_player()
self.draw_render_box()
self.distance_to_player_checker()
self.movement() |
def check_purity(data):
rating_column = data[:, -1]
unique_classes = np.unique(rating_column)
if len(unique_classes) == 1:
return True
else:
return False
def classify_data(data):
rating_column = data[:, -1]
unique_classes, counts_unique_classes = np.unique(rating_column, retur... | This function recursively constructs a decision tree by splitting data based on the best feature-value pair, stopping when data is pure, sample count is insufficient, or maximum depth is reached. It returns a nested dictionary structure representing the tree, where each node contains a decision question and branches to... | def decision_tree_algorithm(df, counter=0, min_samples=2, max_depth=5):
# data preparations
if counter == 0:
global COLUMN_HEADERS
COLUMN_HEADERS = df.columns
data = df.values
else:
data = df
# base cases
if (check_purity(data)) or (len(data) < min_samples) or (cou... |
def Is_pure(data):
rating_column = data[:, -1]
unique_classes = np.unique(rating_column)
if len(unique_classes) == 1:
return True
else:
return False
def Data_classification(data):
rating_column = data[:, -1]
unique_classes, counts_unique_classes = np.unique(rating_column, retu... | This function recursively constructs a decision tree by splitting data based on the best feature-value pair, handling base cases (pure data, insufficient samples, max depth), and building tree nodes with left/right children for subsequent splits. | def decision_tree_algorithm(df, counter=0, min_samples=2, max_depth=5):
# data preparations
if counter == 0:
global COLUMN_HEADERS
COLUMN_HEADERS = df.columns
data = df.values
else:
data = df
# base cases
if (Is_pure(data)) or (len(data) < min_samples) or (counter ... |
def resnet101(**kwargs):
return _resnet([3, 4, 23, 3], model_urls['resnet101'], **kwargs)
def resnet50(**kwargs):
return _resnet([3, 4, 6, 3], model_urls['resnet50'], **kwargs)
def wrap_lr_pad(net):
for name, m in net.named_modules():
if not isinstance(m, nn.Conv2d):
continue
if ... | The code initializes a ResNet-based Feature Pyramid Network (FPN) with configurable backbones (resnet50/101), input channels, and optional features (u/v). It modifies the backbone's first convolution layer to accommodate extra input channels if specified, sets up lateral connections via 1x1 convolutions for multi-scale... | def __init__(self, backbone='resnet101', channel=256, lr_pad=True,
add_u=False, add_v=False, no_p0p1=False):
super(ResnetFPN, self).__init__()
if backbone == 'resnet101':
self.backbone = resnet101()
elif backbone == 'resnet50':
self.backbone = resnet50()... |
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
def super_l2(pipe_img2img, X, prompt, step_size, iters, eps, clamp_min, clamp_max, grad_reps = 5, target_image = 0, **kwargs):
X_adv = X.clone()
last_image = None
iterator = tqdm(r... | This code performs adversarial attacks on a sequence of input images using a Stable Diffusion model, generating both original and adversarial edited images. It evaluates the quality of these images using metrics like LPIPS, PSNR, SSIM, VIF, and FSIM, then saves the results in a CSV file for analysis. The attack type (L... | def perform_attack():
# make sure you're logged in with `huggingface-cli login` - check https://github.com/huggingface/diffusers for more details
device = torch.device("cuda:{}".format(FLAGS.GPU_ID))
model_id_or_path = "CompVis/stable-diffusion-v1-4"
pipe_img2img = MyStableDiffusionImg2ImgPipeline.from_... |
def config_window(self):
self.config(padx=20, pady=20)
self.resizable(False, False)
self.title("Typing Speed Test")
def create_widgets(self):
# ---------------------------- LABELS ------------------------------- #
self.correct_label = Label(text=f'Correct words: {self.game.correc... | The code initializes a game window by setting up GUI components, selecting the first word from a list, determining its position, highlighting it, starting a countdown timer, and entering the main event loop to run the application. | def __init__(self, game):
super().__init__()
self.game = game
self.config_window()
self.create_widgets()
self.setup_widgets_layout()
self.bind_functions()
# Initialize game : Pick a word, highlight it and enter the countdown event
self.active_word = self.g... |
def binaryToInt(binary,signed=0):
sum=0
if not signed:
for i in range(0,len(binary)):
sum+=2**(len(binary)-i-1)*int(binary[i])
else:
for i in range(0,len(binary)):
if i==0:
sum-=2**(len(binary)-i-1)*int(binary[i])
else:
sum+... | The code implements a signed less-than immediate comparison. It compares the value in register rs with the sign-extended immediate im, sets register rt to 1 if rs is less than im, otherwise to 0, then increments the program counter (PC) by 4. | def MIPS_sltiu(rt,rs,im):
global PC
reg_1=binaryToInt(rt)
reg_2=binaryToInt(rs)
binary2=register_list[reg_2]
int2=binaryToInt(binary2,0)
int_im=binaryToInt(extend(im,32,1),0)
if int2<int_im:
register_list[reg_1]=intToBinary(1,32)
else:
register_list[reg_1]=intToBinary(0,3... |
def binaryToInt(binary,signed=0):
sum=0
if not signed:
for i in range(0,len(binary)):
sum+=2**(len(binary)-i-1)*int(binary[i])
else:
for i in range(0,len(binary)):
if i==0:
sum-=2**(len(binary)-i-1)*int(binary[i])
else:
sum+... | This function performs a MIPS subtraction operation by subtracting the value in register rt (subtrahend) from the value in register rs (minuend), storing the result in register rd. It converts binary register identifiers to integers, retrieves their values, computes the subtraction using two's complement addition, upda... | def MIPS_sub(rd,rs,rt):
global PC
reg_1=binaryToInt(rd)
reg_2=binaryToInt(rs)
reg_3=binaryToInt(rt)
minuend=register_list[reg_2]
subtrahend=register_list[reg_3]
register_list[reg_1]=binary_add(minuend,twos_complement(subtrahend),1)
PC+=4 |
def binaryToInt(binary,signed=0):
sum=0
if not signed:
for i in range(0,len(binary)):
sum+=2**(len(binary)-i-1)*int(binary[i])
else:
for i in range(0,len(binary)):
if i==0:
sum-=2**(len(binary)-i-1)*int(binary[i])
else:
sum+... | The function performs an unsigned subtraction operation (MIPS 'subu' instruction) by subtracting the value in register 'rt' from 'rs', storing the result in 'rd', and incrementing the program counter (PC) by 4. It converts binary register identifiers to integers, retrieves their values, computes the result using two's ... | def MIPS_subu(rd,rs,rt):
global PC
reg_1=binaryToInt(rd)
reg_2=binaryToInt(rs)
reg_3=binaryToInt(rt)
minuend=register_list[reg_2]
subtrahend=register_list[reg_3]
register_list[reg_1]=binary_add(minuend,twos_complement(subtrahend),0)
PC+=4 |
def binaryToInt(binary,signed=0):
sum=0
if not signed:
for i in range(0,len(binary)):
sum+=2**(len(binary)-i-1)*int(binary[i])
else:
for i in range(0,len(binary)):
if i==0:
sum-=2**(len(binary)-i-1)*int(binary[i])
else:
sum+... | This function simulates the MIPS ADDI (Add Immediate) instruction. It adds the value in register rs to an immediate value (im), stores the result in register rt, and increments the program counter (PC) by 4. The immediate is sign-extended to 32 bits before addition. The operation follows MIPS's instruction execution mo... | def MIPS_addi(rt,rs,im):
global PC
reg_1=binaryToInt(rt)
reg_2=binaryToInt(rs)
binary_im=extend(im,32,1)
binary2=register_list[reg_2]
register_list[reg_1]=binary_add(binary2,binary_im,1)
PC+=4 |
def binaryToInt(binary,signed=0):
sum=0
if not signed:
for i in range(0,len(binary)):
sum+=2**(len(binary)-i-1)*int(binary[i])
else:
for i in range(0,len(binary)):
if i==0:
sum-=2**(len(binary)-i-1)*int(binary[i])
else:
sum+... | This function performs the MIPS 'addiu' instruction: it adds a sign-extended 16-bit immediate value to the value in register rs, stores the result in register rt, and increments the program counter (PC) by 4. It converts binary register identifiers to integers, extends the immediate value to 32 bits, performs the addit... | def MIPS_addiu(rt,rs,im):
global PC
reg_1=binaryToInt(rt)
reg_2=binaryToInt(rs)
binary_im=extend(im,32,1)
binary2=register_list[reg_2]
register_list[reg_1]=binary_add(binary2,binary_im,0)
PC+=4 |
def adjacent_up(p, target, mid):
"""Performs linear search to find adjacent pair right side
Args:
p: integer indicating the index of player in list of players
looking for matches
target: integer indicating height of player to look for
mid: index of match found, to search in a... | The main task of the code is to search for pairs of players in a list whose heights sum to a specific target value. It iterates through players, calculates complementary heights, and uses linear or binary search to find matches. If pairs are found, they are stored and printed. The function checks height ranges, skips i... | def search(size):
"""search for pairs in list
Args:
size:is an integer with the number of players in the list
players: is the list of dictionaries containing the players info
"""
for p in range(size):
plyr1 = int(players[p].get('h_in')) # store first player height
pl... |
def extract_int_request(request, param_name) -> Optional[int]:
"""Returns an integer, or None if the parameter doesn't exist or is 'null'"""
val = extract_string_request(request, param_name)
if val is None:
return None
else:
return int(val)
def extract_date_request(request, param_name, d... | The function extracts parameters from an HTTP request, including dataset ID, species ID, date ranges, records type, and area IDs, to apply filtering criteria. It returns these values as a tuple for further processing, enabling data retrieval or analysis based on specified constraints. | def filters_from_request(request):
dataset_id = extract_int_request(request, "datasetId")
species_id = extract_int_request(request, "speciesId")
start_date = extract_date_request(request, "startDate")
end_date = extract_date_request(request, "endDate")
records_type = extract_string_request(request, ... |
def set_seed(self, seed=None):
self.seed = seed
if self.seed is None:
self.seed = np.frombuffer(os.urandom(4), dtype=np.uint32)[0]
self.rng = np.random.RandomState(self.seed)
def init_worlds(self):
self.world_files = [
pkg_resources.resource_filename("RatSi... | This code initializes a 2D robotic rat simulation environment, setting up joint parameters, touch sensors, action/observation spaces (including joint positions, touch data, oscillator state, and object positions), rendering configurations, and reward functions. It prepares the environment for reinforcement learning by ... | def __init__(self):
super(Box2DSimRatEnv, self).__init__()
self.set_seed()
self.init_worlds()
self.init_worlds()
self.num_joints = 7
self.num_move_degrees = 2
self.num_touch_sensors = 6
self.random_mean = np.array([0, 0])
self.random_std = 5
... |
def initialise(self):
try:
pygame.init()
self.font = pygame.font.Font('freesansbold.ttf', 35)
self.topText = "Welcome, Player 1's Move"
self._display_surface = pygame.display.set_mode(SIZE, pygame.DOUBLEBUF | pygame.HWSURFACE)
pygame.display.set_captio... | This code initializes a game loop, checking if initialization succeeded. If so, it repeatedly renders the screen, processes events via pygame's event system, and updates game logic until the loop is stopped by setting self._running to False. | def start(self):
if self.initialise() == False:
self._running = False
while self._running:
self.render()
for event in pygame.event.get():
self.eventHandler(event)
self.loop() |
def search_linguee(self, german: str):
response = requests.get(self.linguee_url(german))
if response.status_code >= 500:
error = \
'Linguee server error - probably from sending too many ' \
'requests. Either wait an hour or so, or change your IP ' \
... | The code translates German text using Linguee first, returning cleaned results if available; otherwise, it falls back to DeepL. It logs translation attempts and handles errors by returning None while recording exceptions. | def translate(self, german: str, new_log_entry=True):
try:
log(f'Translating {german}...', new_log_entry)
# At first, try to translate with Linguee.
translations = self.search_linguee(german)
# If we get a None back, Linguee server rejected us - don't
... |
def initQ(self, s, a, types="ones"):
if types == "ones":
return np.ones((s, a))
elif types == "random":
return np.random.random((s, a))
elif types == "zeros":
return np.zeros((s, a))
def epsilon_greedy(self, Q, s, train=False):
if train or np.random.ra... | This code implements a Q-learning agent for a reinforcement learning task. It initializes a Q-table, trains the agent over multiple episodes using epsilon-greedy exploration, updates Q-values via the Bellman equation, tracks cumulative rewards and regret, and visualizes reward trends. The agent is tested post-training ... | def run(self):
Q = self.initQ(self.n_states, self.n_actions, types="random")
timestep_reward = []
# statistics
reward_log = []
regret_log = []
for episode in range(self.episodes):
print(f"Episode: {episode}")
s, _ = self.... |
def print_time(self, description: str = ""):
if self.do_timeing:
elapsed = timeit.default_timer() - self.start_time
print(f"{description} TIME: {elapsed}")
self.start_time = timeit.default_timer()
def _gradient_penalty(self, real_data, generated_data, gp_weight):
b_si... | This code evaluates a generative model's performance by computing Wasserstein errors, gradient norms, and Chen errors using test data. It compares results against stored minima, updates best results, calculates model scores, and optionally saves models. The function switches networks to evaluation mode, runs forward pa... | def do_tests(self, comp_joint_err=False, comp_grad_norm=False, comp_loss_d=False, comp_chen_error=False, save_models=False, save_best_results=True):
self.netG.eval()
self.netD.eval()
chen_errors = []
if comp_chen_error or comp_grad_norm:
unfixed_data = self.samples_torch[:se... |
def print_time(self, description: str = ""):
if self.do_timeing:
elapsed = timeit.default_timer() - self.start_time
print(f"{description} TIME: {elapsed}")
self.start_time = timeit.default_timer()
def _gradient_penalty(self, real_data, generated_data, gp_weight):
b_si... | The main task of the code is to train a generative adversarial network (GAN) using classical training methods. It configures optimizers (Adam/RMSProp), applies Lipschitz constraints (weight clipping/gradient penalty), and iteratively trains the generator (netG) and discriminator (netD). The function handles hyperparame... | def classic_train(self, tr_conf_in: dict = None, save_models=True):
self.print_time("START TRAIN")
if tr_conf_in is None:
importlib.reload(configs)
tr_conf = configs.training_config
else:
tr_conf = tr_conf_in
# Number of training epochs using classica... |
def print_time(self, description: str = ""):
if self.do_timeing:
elapsed = timeit.default_timer() - self.start_time
print(f"{description} TIME: {elapsed}")
self.start_time = timeit.default_timer()
def _gradient_penalty(self, real_data, generated_data, gp_weight):
b_si... | The main task of the code is to train a generative adversarial network (GAN) using a custom configuration, including optimizer selection (Adam/RMSProp), learning rates, and Lipschitz constraints (weight clipping or gradient penalty). It performs iterative training of the generator and discriminator, applies gradient pe... | def chen_train(self, tr_conf_in: dict = None, save_models=True):
self.print_time("START CHEN TRAIN")
if tr_conf_in is None:
importlib.reload(configs)
tr_conf = configs.training_config
else:
tr_conf = tr_conf_in
# Number of training epochs using classi... |
def config(self):
cf = {
'device': self.device,
'ngpu': self.ngpu,
'w dim': self.w_dim,
'a dim': self.a_dim,
'noise size': self.noise_size,
'which generator': self.which_generator,
'which discriminator': self.which_discriminator... | The main task of the code is to evaluate and compute the performance metrics of a generative adversarial network (GAN) by running multiple training trials with specified hyperparameters. It configures training settings, initializes generator and discriminator models, trains them, and collects results like scores and er... | def compute_objective(self, optimizer, lrG, lrD, num_discr_iters, beta1, beta2, gp_weight, leaky_slope,
tr_conf_in: dict = None, trials: int = 5):
self.leakyReLU_slope = leaky_slope
cf = self.config()
if tr_conf_in is None:
importlib.reload(configs)
... |
def legal_goal(goal):
"""
Validation of the goal given via line argument is in correct format.
"""
goal_list = ["wam", "ddg", "lnorm", "jacobi", "spk"]
return goal in goal_list
def create_vectors_from_file(file):
"""
Form a 2D matrix containing the n given points in the file as rows
"""
... | The code processes command-line inputs to perform a specific task based on the provided goal. It validates input parameters, reads vectors from a file, and executes either the 'spk' algorithm (for spectral clustering) or 'jacobi' (for eigenvalue decomposition) on the vectors. It handles errors in input formatting, file... | def main():
# Reading user CMD arguments and validation that are in correct format.
cmd_input = sys.argv
if len(cmd_input) != 4:
print("Invalid Input!")
return 1
k = float(cmd_input[1])
goal = cmd_input[2]
file_name = cmd_input[3]
if not legal_goal(goal):
print("Inval... |
def num_cycle_nodes(ls:str):
if len(ls) == 0: return 0
cycle_i = -1
lines = ls.split("\n")
for i, line in enumerate(lines):
if line.replace(" ", "")[:2] == "->":
cycle_i = i
break
assert(not cycle_i == -1)
nodes_res = re.split(r"\(?\d?[<-][NP>]P?-?>?\d?\)?", lines... | The main task of the code is to compute the graph edit distance between two graphs after aligning their cycle node counts via LCM-based repetition. It adjusts graph sizes, logs parameters, and serializes results. The function either loads precomputed data or calculates the edit distance using `nx.optimize_graph_edit_di... | def thread_func(tup: tuple):
i, j = tup
gi, gj = graphs[i], graphs[j]
ni, nj = num_cycle_nodes(gi.src_str), num_cycle_nodes(gj.src_str)
repeat_lcm = ni
if (not ni == nj):
repeat_lcm = lcm(ni, nj)
imult = repeat_lcm // ni
if imult > 1:
istr = repeat... |
def num_cycle_nodes(ls:str):
if len(ls) == 0: return 0
cycle_i = -1
lines = ls.split("\n")
for i, line in enumerate(lines):
if line.replace(" ", "")[:2] == "->":
cycle_i = i
break
assert(not cycle_i == -1)
nodes_res = re.split(r"\(?\d?[<-][NP>]P?-?>?\d?\)?", lines... | This function takes two graph indices, adjusts their cycle node counts to a common multiple, and prints the modified graphs if valid. It calculates LCM of cycle counts, repeats graph structures if needed, then prints both graphs after validation. | def print_repeated_pair_of_graphs(i,j):
gi, gj = graphs[i], graphs[j]
ni, nj = num_cycle_nodes(gi.src_str), num_cycle_nodes(gj.src_str)
repeat_lcm = ni
if (not ni == nj):
repeat_lcm = lcm(ni, nj)
imult = repeat_lcm // ni
if imult > 1:
istr = repeat_oantigen((g... |
def create_random_color(self):
h = random.uniform(0,1)
s = random.uniform(0.5,1)
v = random.uniform(0.9,1)
#convert hsv color to rgb
(r,g,b) = colorsys.hsv_to_rgb(h,v,v)
r = int(r * 255)
g = int(g * 255)
b = int(b * 255)
return (r,g,b,255)
def g... | The code initializes an RGBA image generator with parameters for size, grain, noise, and color palette. It creates a random color palette, sets noise properties, and generates an image with grain and noise effects. The `generate()` method is called to produce the image, with optional debug information added if enabled. | def __init__(self,size=(500,500),grain_level=0.2,noise_level=2.5,noise_shift=2.0,debug=False):
# color = self.create_random_color()
self.size = size
self.img = Image.new("RGBA",size=self.size)
self.pallate = (
self.create_random_color(),
self.create_random_color()... |
def get_latent(autoencoder: Autoencoder, image):
# from 32x32x3 to 3x32x32
image = image.transpose(2, 0).transpose(1, 2)
image.unsqueeze_(0)
lat = autoencoder.encoder(image).data.reshape((64,))
return lat
def generate_image(model: Cppn, size: Tuple[int, int]):
inp = get_input_matrix_for_cppn(si... | The code evolves CPPN neural networks using a genetic algorithm, guided by an autoencoder's latent space. It iteratively evaluates population members' fitness based on proximity to explored latent points, prunes the population, and generates offspring. The best images from each generation are saved, aiming to produce d... | def main():
plt.ion()
autoencoder = Autoencoder().cuda()
autoencoder.load_state_dict(torch.load("autoencoder_save.pth"))
autoencoder.eval()
size = (32, 32)
population = [PopMember(Cppn(NUMBER_OF_LAYERS, NEURONS_IN_LAYER,
HIDDEN_FUNCTION, OUTPUT_FUNCTION).cuda(... |
def try_read_field_names(self, row):
return (str(x) for x in row if x is not None and x != '')
def try_read_field_defs(self, row):
return (str(x) for x in row if x is not None and x != '')
def append_row(self, data, row):
row_data = []
count = len(self.scheme.fields)
for index, c... | This code initializes an object by parsing an Excel sheet into a structured format. It reads the sheet's title as the table name, extracts field names and definitions from the first rows, constructs a schema using these fields, and collects subsequent data rows. If the schema cannot be determined, it raises an error. T... | def __init__(self, sheet):
table_name = sheet.title
data = []
self.scheme = None
field_names, field_defs = None, None
for row in sheet.iter_rows(values_only=True):
if len(row) == 0:
continue
if row[0] is None:
continue
... |
def convert_table(self, table, template, arg_list):
table_name = table.scheme.name
table_data = []
for row in table.data:
table_data.append(self.pack_row_as_lua_table(row, table.scheme))
table_args = {
"table_name": table_name,
"table_data": str.joi... | The code processes multiple tables by applying conversion methods. It initializes a template with Lua configurations, iterates through each table to convert data into structured formats using `convert_table`, then handles manager and enum conversions. The `arg_list` accumulates arguments for template rendering, enablin... | def write_all(self, tables):
template = {}
template.update(template_lua)
arg_list = {}
for table in tables:
self.convert_table(table, template, arg_list)
self.convert_manager(tables, template, arg_list)
self.convert_enums(tables, template, arg_list) |
def convert_table(self, table, template, arg_list):
table_name = table.scheme.name
fields = "\n".join([template["field_declare"].format(
**{"field_type": self.get_type_name(fld), "field_name": fld.field_name}) for fld in table.scheme.fields])
fields_construct = ""
for idx, ... | This function generates code by processing a list of tables using predefined templates. It initializes namespace structures, iterates through each table to convert them into specific code components (like constructors and entries), and handles additional manager and misc code generation. The results are aggregated into... | def write_all(self, tables):
template = {}
template.update(template_cs)
arg_list = {
"class_ctor_functions": "",
"class_dict_entries": "",
"class_ctor_entries": "",
"class_entry_getters": ""
}
name_space_args = {"name_space": self... |
def convert_table(self, table, template, arg_list):
table_name = table.scheme.name
fields = "\n".join([template["field_declare"].format(
**{"field_type": self.get_type_name(fld), "field_name": fld.field_name}) for fld in table.scheme.fields])
fields_construct = ""
for idx, ... | This function generates Java code from input tables by initializing templates, processing each table to populate class constructs and entries, and assembling namespace structures. It uses helper methods to handle table conversions, manager logic, and miscellaneous code elements, ultimately compiling structured Java cod... | def write_all(self, tables):
template = {}
template.update(template_java)
arg_list = {
"class_ctor_functions": "",
"class_dict_entries": "",
"class_ctor_entries": "",
"class_entry_getters": ""
}
name_space_args = {"name_space": se... |
def clear():
for _ in range(65):
print()
def add_account():
conct = mysql.connector.connect(
host='localhost', database='bank_management_system', user='root', password='1234')
cursor = conct.cursor()
first_name=input("Enter your first Name : ")
last_name=input("Enter your last Name : ")
... | The main task of the code is to provide a menu-driven interface for a bank application, allowing users to select options like adding, modifying, or closing accounts, activating accounts, accessing transaction/search/report menus, or exiting. It validates user input, loops until a valid choice is made, and executes corr... | def main_menu():
while True:
clear()
result_2 = pyfiglet.figlet_format("ABC BANK")
print(result_2)
sleep(3)
print(' \n \nMain Menu')
print("\nselect the options ")
print("\n1. Add Account")
print('\n2. Modify Account')
print('\n3. Close Account')
prin... |
def ask_start():
figw = "□"
while figw == "□":
a=input('Taking figure coordinate: ') #c2
# in case user chooses coordinate bigger than board
while not((a[0].upper() in ['A','B','C','D','E','F','G','H']) and (int(a[1]) in [1,2,3,4,5,6,7,8]) and len(a)== 2):
print((a[1] i... | The main task of the code is to handle a move operation in a game. It starts by retrieving the initial position of a figure using `ask_start()`, then confirms the end position with `ask_end()` using the start data. Finally, it updates or displays the game board state via `show_board()` to reflect the move. | def movew():
start = ask_start() # return a list [figure, coordinate]
ask_end(start, True)
show_board() |
def ask_start():
figw = "□"
while figw == "□":
a=input('Taking figure coordinate: ') #c2
# in case user chooses coordinate bigger than board
while not((a[0].upper() in ['A','B','C','D','E','F','G','H']) and (int(a[1]) in [1,2,3,4,5,6,7,8]) and len(a)== 2):
print((a[1] i... | The main task of the code is to handle a move in a game by first obtaining the starting position via `ask_start()`, then determining the ending position using `ask_end()` with the start and a boolean flag, and finally displaying the updated game board state through `show_board()` to reflect the move. | def moveb():
start = ask_start()
ask_end(start, False)
show_board() |
def show_board():
for x in range(10):
print(' '.join(board[x]),)
print('\n')
def movew():
start = ask_start() # return a list [figure, coordinate]
ask_end(start, True)
show_board()
def check(white, mate = False,fake_coordinate_x = 0, fake_coordinate_y = 0):
# lets find the coordinate o... | The code simulates a turn-based chess game, alternating between white and black moves. After each move, it checks for 'check' and 'checkmate' conditions. If checkmate is detected, the game ends with "Game over" and returns True. The loop continues until a checkmate occurs, ensuring players take turns and enforcing game... | def game():
print("Welcome to out game")
while True:
show_board()
print("white's move")
movew()
if check(True):
print("Check")
if check_mate(True):
print("game over")
return True
print("black's move")
... |
def StackedModel():
estimators = [
# ('kn', KNeighborsRegressor(weights='distance', p=1, n_neighbors=4, n_jobs=-1, leaf_size=1, algorithm='auto')),
('lgbm', LGBMRegressor(
subsample_freq=1, subsample_for_bin=400000, subsample=0.5, reg_lambda=0.5, reg_alpha=3, num_leaves=16,
n... | (The code trains a `StackedModel` using preprocessed data from a specified CSV file, measures the execution time, and writes the model's results. It initializes the model, loads data via `get_preprocessed_data()`, trains the model with `fit()`, and outputs the runtime. Cross-validation and validation scoring are commen... | def main():
global TRAINING_DATA_X
TRAINING_DATA_X = "X_train_cached_estimators_10.csv"
print(f'Start time: {datetime.datetime.now().time()}')
start = time.perf_counter()
model = StackedModel()
name = type(model).__name__
# X, y = get_preprocessed_data()
# scores = cross_validate(model, ... |
def get_statistical_values(array):
return np.array([
np.mean(array),
np.median(array),
np.min(array),
np.max(array),
np.std(array)
])
def PQRST_feature_extraction(ecg, waves, rpeaks):
ecg_points = np.array(list(zip(
waves["ECG_P_Onsets"],
waves["ECG_P_... | The function extracts ECG features like R-peaks, HRV indices, heartbeat parameters, signal quality, and rate using NeuroKit, with fallback to precomputed data if real-time computation fails. It combines these features into a concatenated array for analysis, handling errors gracefully by loading stored results when exce... | def neurokit_feature_extraction(signal, sampling_rate, biosppy_r_peaks):
ecg_cleaned = nk.ecg_clean(signal, sampling_rate)
_, rpeaks = nk.ecg_peaks(ecg_cleaned, sampling_rate)
if len(rpeaks["ECG_R_Peaks"]) == 0:
if len(biosppy_r_peaks) != 0:
rpeaks["ECG_R_Peaks"] = biosppy_r_peaks
... |
def heartpy_feature_extraction(signal, sampling_rate):
with warnings.catch_warnings():
warnings.simplefilter("ignore")
try:
_, measures = hp.process(signal, sampling_rate)
return np.array([v for k, v in measures.items()])
except heartpy.exceptions.BadSignalWarning:
... | The code extracts features from physiological signals using HeartPy, BioSPPy, and NeuroKit libraries. It processes each sample by removing NaNs, computes features from each method, concatenates them, and returns a cleaned NumPy array with infinities replaced by NaNs. | def extract_features(X):
X_new = []
sampling_rate = 300
for i, x in enumerate(X):
print(f"Process sample: {i}")
x = x[~np.isnan(x)]
# Heartpy Feature Extraction
heartpy_features = heartpy_feature_extraction(x, sampling_rate)
# Biosppy Feature Extraction
bios... |
def extract_features(X):
X_new = []
sampling_rate = 300
for i, x in enumerate(X):
print(f"Process sample: {i}")
x = x[~np.isnan(x)]
# Heartpy Feature Extraction
heartpy_features = heartpy_feature_extraction(x, sampling_rate)
# Biosppy Feature Extraction
bios... | The main task of the code is to preprocess test data by loading features, performing feature extraction (if needed), and applying imputation, standard scaling, and feature selection (variance and regressor-based) to prepare the data for modeling. It ensures data consistency and applies transformations to optimize model... | def get_test_data():
data = pd.read_csv(TEST_DATA_X)
X = data.iloc[:, 1:].to_numpy()
if "extracted" not in TEST_DATA_X:
length = len(X)
start = time.perf_counter()
X = extract_features(X)
print(f"Test data feature extraction: {time.perf_counter() - start} s")
assert l... |
def read_train_data():
X_data = pd.read_csv(TRAINING_DATA_X)
y_data = pd.read_csv(TRAINING_DATA_y)
X = X_data.iloc[:, 1:].to_numpy()
y = y_data["y"].to_numpy()
return X, y
def extract_features(X):
X_new = []
sampling_rate = 300
for i, x in enumerate(X):
print(f"Process sample: {i... | The main task of the code is to prepare training data by loading raw data, extracting features (if not pre-extracted), imputing missing values, standardizing features, and performing variance-based and regressor-driven feature selection, ultimately returning the processed feature matrix `X` and target vector `y` for ma... | def get_train_data(param=None):
X, y = read_train_data()
if "extracted" not in TRAINING_DATA_X:
start = time.perf_counter()
X = extract_features(X)
print(f"Train data feature extraction: {time.perf_counter() - start} s")
write_train_data(X, y)
X = impute_missing_values_simple... |
def iterate():
global iteration
iteration += 1
def is_target(self):
if self.state == target:
return True
return False
def children(self):
for i in range(0, 3):
for j in range(0, 3):
if self.state[i][j] == 0:
r... | This function performs a depth-limited search (DLS) up to a specified maximum depth. It checks if the current node is the target, returning True with the path cost if found. If the depth limit is exceeded or no children exist, it returns False. The algorithm recursively explores all children within the depth constraint... | def DLS(self, maxDepth):
iterate()
if self.is_target() :
print(self.way_cost+1)
return True
if self.way_cost >= maxDepth :
return False
if self.childrens == []:
self.children()
for i in self.childrens:
if(i.DLS... |
def conv_block(inputs, conv_type, kernel, kernel_size, strides, padding='same', name="", relu=True):
if(conv_type == 'ds'):
# x = tf.keras.layers.SeparableConv2D(kernel, kernel_size, padding=padding, strides=strides, name=f"{name}_SeparableConv")(inputs)
x = tf.keras.layers.Conv2D(kernel, kernel_siz... | The code constructs a Fast-SCNN model for semantic segmentation. It processes input images through four stages: 1) Learning to DownSample (convolutional blocks for spatial reduction), 2) Global Feature Extraction (bottleneck blocks and pyramid pooling for multi-scale features), 3) Feature Fusion (combining downsampling... | def get_model(size):
# Input Layer
input_layer = tf.keras.layers.Input(shape=(size[0], size[1], 3), name='input_layer')
# Step 1: Learning to DownSample
lds_layer = conv_block(input_layer, 'conv', 32, (3, 3), strides=(2, 2), name="Downsampling_1")
lds_layer = conv_block(lds_layer, 'ds', 48, (3, 3),... |
def checkBoard(self):
end = True
for i in range(9):
r = self.checkRow(i)
c = self.checkCol(i)
b = self.checkBlock(i)
end = end and r and c and b
return end
def getValue(self):
self.value = 0
for i in range(9):
for j in r... | The main task of the code is to repeatedly execute game rounds until the board meets a win condition (`checkBoard()` returns `True`). It tracks the number of rounds (`count`), checks for value changes, and breaks the loop if `hail_mary()` triggers. Finally, it returns the result of `checkBoard()` to indicate the game's... | def play_game(self):
count = 0
while not self.checkBoard():
p = self.getValue()
count += 1
self.play_round()
if p == self.getValue():
if not self.hail_mary(): break
print()
return self.checkBoard() |
def parse_pp_file(data: str):
try:
etree = ElementTree.fromstring(data)
except ElementTree.ParseError as e:
raise ValueError(f"Could not parse XML file: {e}")
allpoints = {}
for elem in etree.iter("point"):
try:
point = np.array(
(float(elem.attrib["x... | This code converts between MeshLab's .pp (point cloud) files and Anyscript formats. It reads input from a file or user input, detects the format (XML-based .pp or Anyscript syntax), parses the data, and outputs the converted result in the target format, including point cloud details and Anyscript values. | def convert(_: Info, fp):
"""Convert a file between from meshlab pp to anyscript"""
if fp:
data = fp.read()
else:
data = click.prompt("Paste pp file or anyscript lines", hide_input=True)
lines = [data]
while True:
line = getpass("\033[F")
if line:
... |
def delete(combined_path, is_server, received_id, comp_num):
# deleting only if it is existed.
if os.path.exists(combined_path):
# if it is a file then delete file.
if os.path.isfile(combined_path):
os.remove(combined_path)
# else, remove a directory and all the content insi... | This function creates a file or directory at the specified path. If the path exists, it deletes existing content first. It checks via socket if the data is a file ('1') or directory, creating accordingly. For directories, it creates the folder and its contents, updating server-side tracking if 'is_server' is True. Retu... | def create(combined_path, file_size, s, is_server, received_id, comp_num):
# flag that represent if we delete what in the path or not.
flag = False
# if it is existed, then delete first.
if os.path.exists(combined_path):
delete(combined_path, is_server, received_id, comp_num)
flag = Tru... |
def notify_client_delete(client_socket, path, id_path):
# send the client he needs to delete and the path to delete.
client_socket.send("delete".encode())
# save relative path and send it to client.
try:
relative_path = path.split(id_path)[1]
except (Exception,):
relative_path = path... | The function processes changes in a dictionary representing file operations (delete, create, move) by notifying a client via socket, then clears the dictionary and sends a synchronization completion signal. | def check_for_updates(changes_dict, client_socket, id_path):
# passing the keys in the changes_dict - the dict of a specific computer.
for pair in changes_dict:
if pair[0] == "delete":
notify_client_delete(client_socket, pair[1], id_path)
elif pair[0] == "create":
notify... |
def create(combined_path, file_size, s, is_server, received_id, comp_num):
# flag that represent if we delete what in the path or not.
flag = False
# if it is existed, then delete first.
if os.path.exists(combined_path):
delete(combined_path, is_server, received_id, comp_num)
flag = Tru... | This function handles file operations (create, delete, move) from a client by receiving paths and metadata, checking for duplicates in a tracking dictionary, executing the operation, and updating server state. It sends acknowledgment codes to the client and manages dictionary entries to avoid conflicts, ensuring synchr... | def monitoring(client_socket, comp_num, received_id, package):
# flag1 represent if we need to add the change to the dictionary.
# flag2 represent if we need to delete the src_path.
# flag2 represent if we need to delete the dst_path.
flag1 = True
flag2 = False
flag3 = False
# receiving pat... |
def add_to_dict(received_id_dict, no_sync_id, comp_num):
# create new dict of this computer
received_id_dict[comp_num] = []
# add computer to no_sync_server.
no_sync_id[comp_num] = []
def create_all_content(root_path, s):
# receive path and file size, and send ack.
content = s.recv(BUFFER).deco... | The code sets up a TCP server to handle client connections for file synchronization. It manages new clients by generating unique IDs and directories, receives initial content, and sends updates to existing clients. It tracks changes using dictionaries to avoid duplication, checks for updates, and monitors file modifica... | def main():
# exporting the port from arguments, create TCP socket and bind to a port.
port = int(sys.argv[1])
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('', port))
server.listen(5)
# id_dict is a dictionary that for each id have dictionary of computer numbers and f... |
def read_meta_information(experiment_dir: str) -> Dict[str, Any]:
with open(os.path.join(experiment_dir, "system_info.json")) as f:
jsonData = json.load(f)
return jsonData
def get_node_list(experiment_dir: str) -> List[int]:
files = glob(os.path.join(experiment_dir, "*header.csv"))
nodes = []
... | The main task of the code is to read and process timestamp data from multiple nodes in an experiment directory, aggregating statistical metrics (mean, std, median, etc.) for latency labels across profiling categories. It returns a dictionary of computed results and a list of processed node identifiers. | def read_csvs(experiment_dir: str) -> Tuple[Dict[str, Any], List[int]]:
meta_info = read_meta_information(experiment_dir)
results = {"mean": {key: [] for key in LATENCY_LABELS},
"std": {key: [] for key in LATENCY_LABELS},
"median": {key: [] for key in LATENCY_LABELS},
"lp": {... |
def get_interface_name_from_path(interface_path):
'''
path has the form msg/PoseWithCovariance.msg
the name is only PoseWithCovariance
'''
# get filename from path
name_with_extension = os.path.basename(interface_path)
# remove extension from filename
name = os.path.splitext(name_with_extension)[0]
r... | This script generates a C++ file containing factory code for ROS2 interfaces (msg/srv) based on user-provided paths. It parses command-line arguments, processes message/service definitions, constructs include directives and factory implementations, and writes the output file only if content changes. The generated code ... | def main():
parser = argparse.ArgumentParser(description='Python script for generating interfaces implementation')
parser.add_argument('output_path', type=str)
parser.add_argument('--package', type=str)
parser.add_argument('--msg', type=str, nargs='+', default=[])
parser.add_argument('--srv', type=str, nargs... |
def check_play_button(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y):
"""
Click the button to start the game
"""
button_cliked = play_button.rect.collidepoint(mouse_x, mouse_y)
if button_cliked and not stats.game_active:
ai_settings.initialize_dynamic_s... | This function handles user input events in a game, checking for quit requests, mouse clicks on the play button, and keyboard presses/releases. It triggers corresponding actions like exiting the game, starting gameplay, controlling the ship, and managing bullets by calling specialized event-handling functions. | def check_events(ai_settings, screen, stats, sb, play_button, ship, aliens, bullets):
"""
response to button and mouse events
"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
mouse_x, mouse_y... |
def check_fleet_edges(ai_settings, aliens):
"""
check each alien
"""
for alien in aliens:
if alien.check_edges():
change_fleet_direction(ai_settings, aliens)
break
def ship_hit(ai_settings, stats, sb, screen, ship, aliens, bullets):
"""
response to collision betwe... | The function updates alien movement and collision logic. It checks alien edges, updates their positions, detects collisions with the player's ship, and triggers responses like ship damage or game over if aliens reach the screen bottom. | def update_aliens(ai_settings, stats, sb,screen, ship, aliens, bullets):
"""
update a group of aliens
"""
check_fleet_edges(ai_settings, aliens)
aliens.update()
# check collision between alines and ship
if pygame.sprite.spritecollideany(ship, aliens):
ship_hit(ai_settings, stats, sb... |
def handle_get_descriptor(type):
return gdb.Value(int(rb_tree_lookup_node(_handle_type_tree,type).address)-offsetof(handle_descriptor_t,"rb_node")).cast(handle_descriptor_t.pointer())[0]
def rb_tree_iter(tree):
node=rb_tree_iter_start(tree)
while (node is not None):
yield node
node=rb_tree_iter_next(tree,node)
d... | The code processes threads and events by mapping each thread to its associated events, then generates formatted output lines showing thread states, process names, and linked events. It iterates through event and thread handles, checks sequence IDs, and constructs status strings with state-specific details like queued i... | def invoke(self,arg,from_tty):
thread_to_event={}
event_handle_descriptor=handle_get_descriptor(event_handle_type)
for k in rb_tree_iter(event_handle_descriptor["tree"]):
event=containerof(k,event_t,"handle")
for e in iter_linked_list(event,event_thread_container_t):
thread_handle=handle_lookup(e["threa... |
def _parse_outage(self, row_vals, children):
"""Parses outage tags (children) and adds data to row_vals"""
as_info, extended_children = self._parse_common_elements(row_vals,
children)
row_vals["AS_name"], row_vals["AS_number"] = s... | The main task of the code is to parse an HTML row into a structured dictionary, identify the event type (e.g., Outage, Possible Hijack, BGP Leak), and enrich the dictionary with parsed data using specialized helper methods. It then either returns the result or queues it for parallel processing, while handling exception... | def _parse_row(self, row):
"""Parses a row of html into a dictionary"""
try:
# These are all of the tags within the row
children = [x for x in row.children]
row_vals = {"event_type": children[1].string.strip()}
if row_vals["event_type"] == "Outage":
... |
def at(self, *args):
if len(args) == 1:
return self.grid[args[0][0]][args[0][1]]
elif len(args) == 2:
return self.grid[args[0]][args[1]]
else:
raise ValueError('Expected one 2-tuple or two arguments to Grid.at')
def flood_set(grid, p):
queue = [p]
visi... | This code handles mouse click events to modify a grid-based visual element. It processes left/right clicks, checks for the Shift key, and uses flood fill for right-clicks (when Shift is held) to erase or mark cells. It converts mouse positions to grid coordinates, validates them, and updates the grid state by adding/re... | def on_mouse_down(self, pos, button, hovered):
if pygame.mouse.get_pressed()[0] == pygame.mouse.get_pressed()[2]:
self._previous = (-1, -1)
return
if button != 1 and button != 3:
return
row = int((pos[1] - self._bw) // (self._ts + self._lw))
col = int(... |
def at(self, *args):
if len(args) == 1:
return self.grid[args[0][0]][args[0][1]]
elif len(args) == 2:
return self.grid[args[0]][args[1]]
else:
raise ValueError('Expected one 2-tuple or two arguments to Grid.at')
def erase(self, p):
self.at(p).erase()
... | This code handles mouse motion to update a grid's state by determining the cell under the cursor, checking if it's within bounds and different from the previous cell, then applying color/mark changes and connection logic based on the current mode (TREE, BLOB, TRACE). It erases or updates cells, manages visited tracking... | def on_mouse_motion(self, start, end, buttons, start_hovered, end_hovered):
if buttons[0] == buttons[2]:
return
row = int((end[1] - self._bw) // (self._ts + self._lw))
col = int((end[0] - self._bw) // (self._ts + self._lw))
if not (0 <= row < self.nrows and 0 <= col < self.nc... |
def pop_row(self, index):
if self.nrows <= MIN_SIZE:
raise ValueError('Grid may not have fewer than {} rows'.format(MIN_SIZE))
self.nrows -= 1
self.unregister(*self.grid.pop(index))
self.parent.refresh_proportions_flag = True
self.parent.refresh_layout_flag = True
def... | This code handles keyboard input to modify a grid's structure and settings in a Pygame application. It changes the grid's connection mode (TREE/BLOB/TRACE) via Q/W/E, selects marks with I/O/P, and adjusts rows/columns using arrow keys. Shift+arrow keys remove rows/columns, while unmodified arrows add them. Error handli... | def on_key_down(self, unicode, key, mod):
if key == pygame.K_q:
self.connection_mode = Grid.TREE
elif key == pygame.K_w:
self.connection_mode = Grid.BLOB
elif key == pygame.K_e:
self.connection_mode = Grid.TRACE
elif key == pygame.K_i:
self... |
def splotch_size(dim, grid, num_colors):
gr = grid_rect(dim, grid)
cs = int(gr.width / grid.ncols * 0.8)
if (dim[0] - cs / 2) / num_colors / cs <= 1.1:
cs = int(cs * 0.8)
return cs
def splotch_gap(dim, grid, num_colors):
cs = splotch_size(dim, grid, num_colors)
return max(min(0.5, (dim[0... | The function calculates the position and dimensions of a centered palette rectangle containing color splotches, using spacing and grid parameters to determine width, height, and alignment within the given display dimensions. | def palette_rect(dim, grid, num_colors):
cs = splotch_size(dim, grid, num_colors)
gap = splotch_gap(dim, grid, num_colors)
gr = grid_rect(dim, grid)
width = cs * ((1 + gap) * num_colors - gap)
height = cs * (1 + gap / 2)
top = (dim[1] + gr.bottom - height) // 2
left = (dim[0] - width) // 2
... |
def _handle_events(self):
"""
Handle key events
"""
for event in pg.event.get():
if event.type == pg.QUIT:
self.playing = False
self.running = False
elif event.type == pg.KEYDOWN:
pressed = pg.key.get_pressed()
... | (The code runs a game loop that processes events, updates the game state, renders frames, and maintains a target frame rate. After the loop ends, it adjusts the mutation probability for population evolution based on the maximum score achieved, then evolves the population using the `cgp.evolve` function with the modifie... | def run(self):
self.playing = True
while self.playing:
self._handle_events()
self._update()
self._draw()
self._clock.tick(self._fps)
if not self.running:
return
# one generation finished and perform evolution again
# if ... |
def __should_continue_running(self):
if self.training_termination_type in ["converge", "cycle"]:
if self.training_termination_type == "converge":
return (
self.overfit_count < self.termination_config.overfit_tolerance
and self.validation_mse > ... | This code trains a neural network using forward and backward propagation for the XOR problem, iterating until termination conditions are met. It calculates training error and accuracy per cycle, validates performance, detects overfitting by comparing validation and training MSE, and updates metrics. The loop continues ... | def train(self) -> None:
"""
Train the model using learning XOR algorithm with forward and backward propagation.
We'll also perform validation for every training cycle to record for training termination.
"""
while self.__should_continue_running():
print(f"\n\nTraining... |
def check_nodes(self, graph_rep):
"""Checks if there are any new species or reactions
Args:
graph_rep: graphical representation of the model
Returns:
new_nodes: dictionary with a key for "species" and another for "reactions"
containing list... | This function updates the internal model representation by synchronizing species and reaction data with a provided graph structure. It processes new/deleted nodes, assigns unique IDs, updates names, rebuilds reaction connections via edges, and refreshes parameters, ensuring alignment between the graphical model and int... | def update_from_graph(self, graph_rep_init):
"""Update molybdenum representation from a graphical representation
Args:
graph_rep_init: graphical representation of the model, a dictionary
with these keys:
"nodes": values are a list of dictionaries with "id", "... |
def get_best_anchor(raw_bbox, grid_coordinates, fmap_sizes, anchors_list, ignore_threshold=0.5):
"""
Returns the index of the best anchor for a given bounding box, as well as the anchor's co-ordinates.
Anchors that have an IOU > 0.5 but are not the best will need to be ignored later in the non-objectness lo... | The function generates ground truth tensors for YOLO models by converting bounding boxes into TF-compatible formats. It initializes objectness scores, matches each box to the best anchor via IoU, calculates transformations (tx, ty, tw, th), encodes class labels, and updates corresponding tensors (y_small/y_medium/y_lar... | def create_gt_tensor(bbs, class_dict, fmap_sizes, anchors_list, y_small, y_medium, y_large):
"""
Accessed by the YoloGenerator class only. Used to convert augmented images and BoundingBoxOnImage objects into the
tensor formats required by tf.
"""
label_length = 5 + len(class_dict)
# Initialise ... |
def parse_args():
parser = argparse.ArgumentParser(prog='make_conf', description="Prepares custom config files from base config files")
parser.add_argument('-c', '--base_config_file', type=Path,
help='Base config file for preparation of new config files.')
parser.add_argument('... | The main task of the code is to parse command-line arguments, read a base configuration file, optionally update it with additional parameters and paths, create a directory, and save the final configuration to a specified output file. | def main():
print("Parsing args ...")
args = parse_args()
# Read Base Confs
print("Reading configs ...")
print(args.base_config_file)
base_configs = read_conf(args.base_config_file, 'yaml')
print(base_configs)
if args.kwargs is not None:
print("Parameters to be updated ...")
... |
def build_encoder(self):
encoder_input = self.add_encoder_input()
conv_layers = self.add_conv_layers(encoder_input)
bottleneck = self.add_bottleneck(conv_layers)
self.model_input = encoder_input
self.encoder = Model(encoder_input, bottleneck, name="encoder")
def build_decoder(s... | The code defines a `build` method that initializes an autoencoder by sequentially constructing its encoder, decoder, and the complete autoencoder model. The method orchestrates the creation of these components, ensuring the encoder and decoder are built first before assembling them into a functional autoencoder system. | def build(self):
self.build_encoder()
self.build_decoder()
self.build_autoencoder() |
def wall_collision(self):
wall_boolean = False
wall_pos = 1 - self.grid_unit
if self.pos_x >= wall_pos or self.pos_x <= -wall_pos or self.pos_y >= wall_pos or self.pos_y <= -wall_pos:
self.alive = False
wall_boolean = True
return wall_boolean
def move_right(self... | The code continues moving an object in the last direction it was moving (Right, Left, Down, or Up) if there is no wall collision, using conditional checks to determine the appropriate movement method to call. | def continue_move(self):
if not self.wall_collision():
if self.last_mov == "Right":
self.move_right()
elif self.last_mov == "Left":
self.move_left()
elif self.last_mov == "Down":
self.move_down()
elif self.last_mov =... |
def inference(self, ft, random_sampling=True):
## bidirectional lstm/gru
# input: (batch, seq_len, z_dim)
# output: (batch, seq_len, z_dim)
output, h_n = self.rnn(ft)
batch_size, length, _ = output.shape
# beta, hidden = self.gru(ft, hidden)
## sequential samplin... | This training step implements a Variational Autoencoder (VAE) with a discriminator for adversarial training. It computes reconstruction loss, Kullback-Leibler divergence (KLD) for both past (normal) and future (Laplace) latent variables, and a total correlation (TC) loss. Two optimizers are used: the first trains the V... | def training_step(self, batch, batch_idx, optimizer_idx):
x, y = batch['s1']['xt'], batch['s1']['yt']
batch_size, length, nc, h, w = x.shape
sum_log_abs_det_jacobians = 0
x_flat = x.view(-1, nc, h, w)
# Inference
if self.infer_mode == 'R':
ft = self.enc(x_flat... |
def get_median(arr):
lower, higher = get_median_values(arr)
return (lower + higher) / 2
def get_median_values(arr):
lower_index, higher_index = get_median_indices(arr)
return arr[lower_index], arr[higher_index]
def get_median_indices(arr):
#get the two indices needed to calculate the median of the... | The function `get_combined_median` calculates the median of two sorted arrays (`arr1` and `arr2`) without explicitly merging them. It uses a divide-and-conquer approach by recursively comparing medians, trimming sections of the arrays, and narrowing down the search for the combined median. If the arrays are non-empty, ... | def get_combined_median(arr1, arr2):
assert len(arr1) > 0 or len(arr2) > 0
if len(arr1) == 0: return get_median(arr2)
if len(arr2) == 0: return get_median(arr1)
lowval1, hival1 = get_median_values(arr1)
lowval2, hival2 = get_median_values(arr2)
if lowval1 > lowval2 and hival1 < hival2:
... |
def retrieve_reads_in_specific_len_at_least(self, reads: List[str], length: int) -> List[str]:
reads = [r for r in reads if len(r) >= length]
print(f'{len(reads)} reads in len at least {length}')
return reads
def find_u2_location_in_read(self, read: SeqIO, u2: str) -> (int, bool):
# TODO... | The code processes DNA reads to identify specific sequences (e.g., U2) and associated oligos, filtering reads by minimum length. It checks for U2 presence, verifies sequences, and logs results (including failures) into a CSV. The output includes read positions, oligo identification, and failure statistics, with progres... | def extract_start_position_and_reads_results_to_csv(self, reads: List[str],
const_design: pd.DataFrame,
payload_design: pd.DataFrame,
barcodes_design: p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.