dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def build_tree(h): #driver function to begin recursive build
node_count = pow(2, h) - 1
root_node = build_rec(h, node_count, 0, None)
return root_node
def number_tree(root): #driver function to number tree by post order traversal
root = number_rec(root, 1)
return root
def find_parent(root, c): #fu... | The code constructs a tree of height `h`, assigns unique numbers to its nodes, and for each node in the `query` list, finds and returns the parent node's identifier. The main task is to determine the parent of each queried node in a numbered tree structure. | def solution(h, query): #solution driver
root = build_tree(h)
root = number_tree(root)
results = []
for q in query: #iterate through requested nodes
results.append(find_parent(root, q))
return results |
def show_popup(self, message):
msg = QMessageBox()
msg.setWindowTitle("Warning")
msg.setText(message)
msg.setIcon(QMessageBox.Warning)
x = msg.exec_()
def updateCombosChanged(self,data,number):
fft = np.fft.fft2(data)
fShift = np.fft.fftshift(fft)
Magnitud... | The code enables browsing and selecting image files, storing their paths and dimensions. For the first image, it enforces size consistency with the previous image, triggering a warning and re-selection if mismatched. It processes the image using OpenCV, updates GUI elements, displays the image, creates an associated mo... | def browse(self,number):
logger.info("Browsing the files...")
fileName = QtWidgets.QFileDialog.getOpenFileName(None,"QFileDialog.getOpenFileName()", "","Image files (*.jpg)")
self.imagePath[number]=fileName[0]
print(self.imagePath[number])
im = Image.open(self.imagePath[number])
... |
def menuBar(self):
self.openFirstImg.triggered.connect(lambda:self.browse(0))
self.openSecondImg.triggered.connect(lambda:self.browse(1))
def image_view_congigrution(self):
for i in range (len(self.Windows_List)):
self.Windows_List[i].ui.histogram.hide()
self.Wind... | This code initializes a GUI application with multiple image processing components, setting up sliders, image viewers, combo boxes, and connections between UI elements to handle tasks like displaying images, selecting components (e.g., magnitude, phase), and configuring output views. It prepares the application's struct... | def __init__(self,parent=None):
super(MainApp,self).__init__(parent)
QMainWindow.__init__(self)
self.setupUi(self)
self.menuBar()
self.sliders=[self.horizontalSlider,self.horizontalSlider_2]
self.imageWindows=[self.viewFirstimg,self.viewSecondimg]
self.imag... |
def compute_features(img):
# detector = cv2.SIFT_create()
# kp, des = detector.detectAndCompute(img,None)
detector = cv2.GFTTDetector_create(2000, qualityLevel=0.001, minDistance=1,
blockSize=3, useHarrisDetector=True, k=0.04)
descriptor = cv2.xfeatures2d.BriefDesc... | The main task of the code is to compute the essential matrix (E) and recover the relative camera rotation (R) and translation (t) between two images using feature matching, RANSAC, and epipolar geometry. It processes image pairs, extracts features, matches them, estimates the fundamental matrix (F), converts it to the ... | def main():
np.random.seed(0)
K = np.array([[520.0, 0.0, 325.1],
[0.0, 521.0, 249.7],
[0.0, 0.0, 1.0]])
img1 = cv2.imread("1.png", 0)
kp1, des1 = compute_features(img1)
img2 = cv2.imread("2.png", 0)
kp2, des2 = compute_features(img2)
# K = np.array([[718.8560... |
def display_welcome(self):
print('Welcome to Robots VS. Dinosaurs, only one team will win!')
def battle(self):
while len(self.herd.dinosaurs) > 0 and len(self.fleet.robots) > 0:
self.robo_turn()
if len(self.herd.dinosaurs) > 0:
self.dino_turn()
def display_winners... | The main task of the code is to execute a game sequence by first displaying a welcome message, then initiating the battle mechanics, and finally displaying the winners of the game. | def run_game(self):
self.display_welcome()
self.battle()
self.display_winners() |
def rgb2yuv(image_rgb, image_yuv_out):
""" Transform the image from rgb to yuv """
image_yuv_out[:, 0, :, :] = 0.299 * image_rgb[:, 0, :, :].clone() + 0.587 * image_rgb[:, 1, :, :].clone() + 0.114 * image_rgb[:, 2, :, :].clone()
image_yuv_out[:, 1, :, :] = -0.14713 * image_rgb[:, 0, :, :].clone() + -0.28886... | The main task of the code is to apply JPEG-like compression to an input image by performing DCT on its YUV channels, masking selected frequency coefficients, and reconstructing the image via inverse DCT. This process introduces compression artifacts while preserving RGB format, likely for adversarial attacks or image p... | def jpegmask(self, img):
N, C, H, W = img.shape
B = H // 8
image_yuv = torch.empty_like(img)
rgb2yuv(img, image_yuv)
pos_emb = self.pos_embedding(torch.arange(3 * 8 * 8).unsqueeze(0).to(img.device))
block_dct = DCT.batch_dct(image_yuv) # [batch_size,3, H, W]
mask ... |
def rgb2yuv(image_rgb, image_yuv_out):
""" Transform the image from rgb to yuv """
image_yuv_out[:, 0, :, :] = 0.299 * image_rgb[:, 0, :, :].clone() + 0.587 * image_rgb[:, 1, :, :].clone() + 0.114 * image_rgb[:, 2, :, :].clone()
image_yuv_out[:, 1, :, :] = -0.14713 * image_rgb[:, 0, :, :].clone() + -0.28886... | The code processes an input image by converting it to YUV color space, applying DCT to frequency components, masking selected coefficients, reshaping data for a transformer model, and reconstructing the image via inverse DCT and RGB conversion. The main task is adversarial image generation using frequency-domain transf... | def forward(self, img):
N, C, H, W = img.shape
B = H // 8
image_yuv = torch.empty_like(img)
rgb2yuv(img, image_yuv)
#pos_emb = self.pos_embedding(torch.arange(3 * 8 * 8).unsqueeze(0).to(img.device))
block_dct = DCT.batch_dct(image_yuv) # [batch_size,3, H, W]
mask ... |
def do_swap(packed, itm):
'''
Swaps the last item in the PackedList.array with the item.
:param packed: The PackedList
:param itm: The item to swap
'''
array = packed["array"]
items = packed["items"]
length = len(array)
if length is 0:
return False
if length is 1:
... | The main task of the code is to remove a specified item from a PackedList's array. It checks if the item exists via `do_swap`, handles edge cases (e.g., peeling layers when the array has two items), updates the array by removing the last item if necessary, and adjusts the item count. It returns `True` on success or `Fa... | def PackedRemove(packed, itm):
'''
Removes an item from the PackedList.array.
:param packed: The PackedList
:param itm: The item to remove from the PackedList
'''
length = len(packed["array"])
if length == 0:
return False
if not do_swap(packed, itm): # Item not found
r... |
def do_swap(packed, itm):
'''
Swaps the last item in the PackedList.array with the item.
:param packed: The PackedList
:param itm: The item to swap
'''
array = packed["array"]
items = packed["items"]
length = len(array)
if length is 0:
return False
if length is 1:
... | This function removes an item from a PackedList's array. It checks if the array is empty, uses do_swap to locate the item, and either peels a layer (for length 2) or removes the last element. It updates the item count and returns True if successful, False otherwise. | def PackedRemove(packed, itm):
'''
Removes an item from the PackedList.array.
:param packed: The PackedList
:param itm: The item to remove from the PackedList
'''
length = len(packed["array"])
if length == 0:
return False
if not do_swap(packed, itm): # Item not found
r... |
def PackedList():
'''
Creates a new PackedList
'''
packed = {
"array": [],
"items": 0
}
return packed
def PackedAppend(packed, itm):
'''
Appends an item to the PackedList.array or wraps it in a new layer if full.
Increments the PackedList.items count.
:param pack... | The main task of the code is to test the consistency of a custom `PackedList` data structure after appending and removing items. It verifies that the internal `itemCount` matches the actual array length (`len(array)`) after operations, ensuring correctness. The test passes if both assertions hold, confirming the struct... | def PackedTest2():
packed = PackedList() # []
PackedAppend(packed, 1) # [1]
array = packed["array"]
removed = PackedRemove(packed, 1) # []
itemCount = packed["items"]
array = packed["array"]
count = len(array)
as... |
def PackedList():
'''
Creates a new PackedList
'''
packed = {
"array": [],
"items": 0
}
return packed
def PackedAppend(packed, itm):
'''
Appends an item to the PackedList.array or wraps it in a new layer if full.
Increments the PackedList.items count.
:param pack... | The main task of the code is to test a custom PackedList class that dynamically appends/remove elements, verifying its structure and item count. It checks append operations (including nested list growth), removal logic (success/failure), and state consistency after each operation, ensuring the class behaves as expected... | def PackedTest():
packed = PackedList() # []
PackedAppend(packed, 1) # [1]
PackedAppend(packed, 2) # [1, 2]
PackedAppend(packed, 3) # [[1, 2], 3]
itemCount = packed["items"]
assert(i... |
def DynamicList():
'''
Creates a new DynamicList
'''
dynamic = {
"packed": [],
"items": 0
}
return dynamic
def DynamicAppend(dynamic, itm):
'''
Appends an item to a packed list or creates a new one.
:param packed: The DynamicList
:param itm: The item to add to t... | The code tests the functionality of a DynamicList class by appending and removing elements, verifying that the internal array and item count are correctly updated after each operation. It ensures the append and remove methods work as expected, maintaining data integrity. | def DynamicListTest():
dynamicList = DynamicList()
added = DynamicAppend(dynamicList, 1)
assert(added)
count = len(dynamicList["packed"][0]["array"])
assert(count == 1)
added = DynamicAppend(dynamicList, 2)
assert(added)
count = len(dynamicList["packed"][0]["array"])
assert(count =... |
def pos_edge_sampling(edge_index, num_pos_samples=1, replacement=False): # for undirected graphs only
edge_index_cloned = edge_index.clone()
# step 1: switch to cpu for working with numpy arrays
edge_index_cloned = edge_index_cloned.to('cpu').numpy()
indices = np.arange(edge_index_cloned.shape[1]).res... | This function performs positive and negative edge sampling on an undirected graph's edge data. It samples positive edges (existing connections) at a specified rate, optionally with replacement, and generates negative edges (non-existent connections) using a separate sampling method. The sampled edges are combined with ... | def edge_sampling(data, pos_rate=0.7, neg_rate=1.0, pos=True, neg=True, pos_replacement=False): # for undirected graphs only
cdata = data.clone()
""" step 1: positive sampling mask """
pos_rate = max(0.0, pos_rate)
if pos and (pos_rate != 1 or pos_replacement):
num_edges_uiu = int(torch.count... |
def augment(data_dir, sample):
image, steering_angle = choose_image(data_dir, sample)
image, steering_angle = flip_randomly(image, steering_angle)
image, steering_angle = translate_randomly(image, steering_angle)
return image, steering_angle
def load_image(data_dir, image_file):
source_path = image_... | This generator function creates batches of training data by shuffling samples and processing them in batches. During training, it applies data augmentation with 60% probability. It loads images, extracts steering angles, processes images, and yields shuffled batches of image-angle pairs as NumPy arrays for model traini... | def generator(data_folder,samples, batch_size, is_training):
num_samples = len(samples)
while 1: # Loop forever so the generator never terminates
shuffle(samples)
for offset in range(0, num_samples, batch_size):
batch_samples = samples[offset:offset+batch_size]
images = ... |
def parseinput(input):
rows = input.splitlines()
monkeys = {}
for r in rows:
monkey, val = r.split(': ')
monkeys[monkey] = val
return monkeys
def isHuman(monkeys: dict[str, str], val: str) -> bool:
if val.isnumeric():
return False
monkey1, sign, monkey2 = val.split(' ')
#Look for mon... | The code solves for the value of the "humn" monkey in a mathematical puzzle involving monkeys with operations. It identifies the human-dependent monkey, calculates the non-human side of the root operation, and uses reverse engineering to determine the required value of "humn" to satisfy the equation defined by the root... | def solveparttwo(input):
result = 0
monkeys = parseinput(input)
finalmonkey = ''
for mon in monkeys:
if 'humn' in monkeys[mon]:
finalmonkey = mon
break
print('Final:', finalmonkey)
monkey1, sign, monkey2 = monkeys['root'].split(' ')
#print(monkey1, isHuman(monkeys, monkeys[mo... |
def take_user_input(self):
print("It is your turn: ")
ip = (input("Choose a position (0-8):"))
# for simplicity assume user is x and runs first
# self.board[ip] = 'X'
while (ip.isdigit()==False) or (int(ip) in self.usedSquarePosition) or (int(ip)>8):
print("Invalid in... | This code initializes a Tic-Tac-Toe game, alternating between user and computer moves in a loop. It updates the game board, checks for a win after each move, and terminates the game when a player or computer wins or the game ends. The loop runs up to 1000 iterations to handle multiple rounds, though the actual game end... | def __init__(self):
self.board = [
'_' for i in range(9)
]
for i in range(1000):
self.round = i
# print(i)
if i % 2 == 0:
self.take_user_input()
if self.hasWon('X'):
print("-----Congratulations!!... |
def at(m,coor):
x = coor[0]
y = coor[1]
return m[x][y]
def adj(self, x): #adjacent cells of x
arr = []
i = x[0]
j = x[1]
if i - 1 >= 0:
arr.append((i - 1, j))
if j - 1 >= 0:
arr.append((i, j - 1))
if i + 1 <= len(self.world) - 1:
... | This code navigates a grid-based environment to explore, collect gold, and safely escape. It uses a stack for depth-first search, marks safe cells, handles special elements (gold, pits, wumpuses), and backtracks to shoot wumpuses when necessary. The function generates movement and action sequences, appending 'CLIMB' at... | def get_actions_list(self):
while len(self.stack) != 0:
#self.update_stack()
cur = self.stack[-1]
self.stack = self.stack[:-1]
if ('-' in at(self.world,cur) or 'G' in at(self.world,cur) or 'A' in at(self.world,cur)) and ('B' not in at(self.world,cur) and 'S' not i... |
def retrieve_top_ten_records():
results = get_record_json()
d = []
for record in results["items"]:
d.append(
{
'Track Name': record['track']["name"],
'Track URI': record['track']["uri"],
'Artist': record['track']['album']['artists'][0]['name'],
'Ar... | The main task of the code is to execute an ETL process for Spotify data by retrieving top ten song and artist records, transforming/cleaning the dataframes, validating data quality, logging completion, and returning the cleaned artist and song dataframes for further analysis or storage. | def spotify_etl():
song_df = retrieve_top_ten_records()
artist_df = retrieve_info_from_top_ten_artist()
transformed_artist_df = clean_artist_df(artist_df)
transformed_song_df = clean_song_df(song_df)
Data_Quality(transformed_artist_df, transformed_song_df)
log.info("Completed spotify_etl function")
... |
def get_txt_files(directory: str) -> List[str]:
txt_files = []
for root, _, files in os.walk(directory):
for f in files:
if f.endswith('.txt'):
file_path = os.path.join(root, f)
txt_files.append(file_path)
return txt_files
def analyse_file(filename) -> ... | The main task of the code is to analyze text files in a directory, aggregate word usage data, sort it, and specifically count occurrences of the word 'perfect' across all files and per year. | def main():
all = []
for f in get_txt_files('data'):
w = analyse_file(f)
all.append(w)
combined = combine_all(all)
sortd = combined.get_sorted_word_usage_list();
perfect_amount = count(combined, ['perfect'])
perfect_amount_per_year = count_per_year(all, ['perfect']) |
def analyse_labels(path_labels):
data_analyser = create_data_analyser(path_labels)
for path_txt in tqdm(glob.glob(f'{path_labels}/*.txt')):
data_analyser['nb_files'] += 1
with open(path_txt) as file:
lines = file.read().split('\n')
for line in lines:
if len(line... | The function analyzes label distributions in specified subdirectories by counting label occurrences, generating visualizations (size, percentage, and count charts), and saving results as plots and text files. It processes each '_typeSet' subdirectory, skips invalid ones, and returns aggregated label data for further us... | def analyse_folder(path):
# Holder of the data info in the folder
data_folder = {}
# List of the _typeSet subdirectories analysed
plt_labels = []
# Go through all the _typeSet subdirectories
for subdirectory in _typeSet:
path_subdirectory = os.path.join(path_directory, subdirectory)
... |
def parse_html(self, html):
html = html.replace('<br>', '\n')
rows, num_header_rows = self.parse_into_rows(html)
num_cols = sum(val[-1] for val in rows[0])
new_rows = []
rowspan = {}
for i, row in enumerate(rows):
new_row = []
col_loc = 0
... | This code processes HTML to render a table visually by parsing structure, calculating column/row dimensions, creating a figure, and printing the formatted table with anti-aliasing rendering. | def run(self, html):
self.fontsize = self.original_fontsize
self.text_fig = Figure(dpi=self.dpi)
self.renderer = RendererAgg(self.figwidth, self.figheight, self.dpi)
self.rows, self.num_header_rows = self.parse_html(html)
self.col_widths = self.calculate_col_widths()
self... |
def _process_environment_variables():
"""Process environment variables"""
# pylint: disable=C0103
global parameters
# pylint: enable=C0103
if "WIS_DEBUG" in os.environ:
logging.disable(logging.NOTSET)
logging.debug("_process_environment_variables(): parameters:")
logging.debug(para... | This code processes database files (single or multiple) based on command-line parameters, applying include/exclude lists. It initializes debugging, validates input files/directories, processes matching records, and outputs a summary of results. Errors trigger critical logs and exit codes. | def main():
"""The program's main entry point"""
exit_status = 0
program_name = os.path.basename(sys.argv[0])
libpnu.initialize_debugging(program_name)
libpnu.handle_interrupt_signals(_handle_interrupts)
_process_environment_variables()
# Words we'll be searching for, if any:
parameters... |
def get_coords(self, freqs, Dnu):
"""From frequency to frequency coordinates"""
xs = []
ys = []
for f in freqs:
x, y = self.f2coord(f, Dnu)
xs.append(x)
ys.append(y)
return xs, ys
def get_pcoords(self, freqs, DP):
"""From frequency to ... | This function updates scatter plots for a specific mode (l) by creating, removing, or modifying scatter points based on label presence and configuration. It handles both frequency and period coordinates, adjusts legends, and redraws the plot while maintaining consistent visualization settings like colors and markers. | def update_scatter(self, l):
"""Updates scatter plot"""
no_label_no_scatter = len(self.f_labels[l]) == 0 and self.scatters[l] == None
no_label_has_scatter = len(self.f_labels[l]) == 0 and self.scatters[l] != None
has_label_no_scatter = len(self.f_labels[l]) != 0 and self.scatters[l] == N... |
def p2coord(self, period, DP):
"""Period to coordinate on the Echelle"""
py_inc = self.py[1] - self.py[0]
x = (period - self.px.min()) % DP# period mod DP is x-coordinate
# The bin just below the period, plus half increment (for labelling in middle)
y = self.py[self.py <... | This function removes the frequency label closest to a given frequency `f` by calculating the Euclidean distance between plot coordinates of `f` and each label. If a sufficiently close match is found, it removes the label from its list, updates the scatter plot, and decrements the label count. | def remove_point(self, f, period=False):
"""Removes point with given frequency"""
if self.labels == 0:
return
# Find the label close to this frequency
min_diff = 1000
if period:
x0, y0 = self.p2coord(self.f2p(f), self.DP)
else:
x0, y0 ... |
def coord2freq(self, x, y, period=False):
if not period:
return y + x
# Period coordinates to frequency
p = x + y
return self.p2f(p)
def remove_point(self, f, period=False):
"""Removes point with given frequency"""
if self.labels == 0:
return
... | This code handles mouse click events on frequency and period plots to add or remove labeled points based on the selected mode. It checks the click location, converts coordinates to frequency values, and triggers corresponding actions (adding/removing points) using helper methods like `coord2freq` and `get_l_mode_choice... | def on_click(self, event):
"""Clicking event"""
# Only add label click in the echelle, and selected l mode to label
click_in_f_plot = event.inaxes == self.ax
if self.plot_period:
click_in_p_plot = event.inaxes == self.pax
else:
click_in_p_plot = False
... |
def update_echelle(self):
"""Get new period echelle"""
self.x, self.y, self.z = EchellePlotter.echelle(self.freq, self.power, self.Dnu,
sampling=1, fmin=self.fmin, fmax=self.fmax)
# Scale image intensities
if self.scale == "sqrt":
self.z = np.sqrt(self.z)
... | The code updates a frequency echelle diagram by adjusting its image data, extent, and labels based on a new Dnu value, then redraws the plot to reflect these changes. | def update(self, Dnu):
"""Updates frequency echelle diagram given new Dnu"""
self.Dnu = Dnu
self.update_echelle()
self.image.set_array(self.z)
self.set_extent()
# Shift labelled points accordingly
self.update_labels()
# Render
self.fig.canvas.bl... |
def update_period_echelle(self):
"""Get new period echelle"""
# Ascending period to feed into echelle
self.px, self.py, self.pz = EchellePlotter.echelle(self.period[::-1], self.power[::-1],
self.DP, sampling=1, fmin=self.pmin, fmax=self.pmax)
# Flip the y-axis
self.... | The code updates a period echelle diagram by recalculating data with new DP values, updating the image array, adjusting axes visibility ranges, shifting labeled points, and rendering changes efficiently via blitting. | def pupdate(self, DP):
"""Updates period echelle diagram given new DP"""
self.DP = DP
# Calculate new data
self.update_period_echelle()
self.pimage.set_array(self.pz)
# Set new visible range for x and y axes (reverted)
# self.pimage.set_extent((self.px.max(), se... |
def get_data(self):
try:
#os.chdir(os.getcwd())
self.data = pd.read_csv(f'data/{self.ticker}_cleaned_data.csv')
print(f'{self.ticker} data imported. Size: {self.data.shape}')
except FileNotFoundError:
print(f'Error: File for {self.ticker} not found.')
... | The code's main task is to predict stock prices using an LSTM model. It loads a pre-trained model if available, otherwise trains a new one. The input data is reshaped to match LSTM's required dimensions, and predictions are generated. The predicted values are extracted from the model's output for further analysis or de... | def predict(self):
if self.model is None:
try:
self.model = load_model(f"lstm/models/best_model_{self.ticker}.h5")
self.get_data()
self.preprocess()
except Exception:
self.train_lstm()
#Reshape X to match LSTM inpu... |
def _parse_filename(self, filename):
"""Derive product parameters from a filename."""
m = self.compressionRe.match(filename)
if (m):
# print 'Compression: {0}'.format(m.group(3))
self.COMPRESSION = m.group(2)
filename = m.group(1)
m = self.filenameR... | The main task of this code is to configure a product instance by validating and setting parameters through either a product ID, filename, or explicit keyword arguments. It ensures no conflicting inputs (e.g., simultaneous use of `product`/`filename` or `product_id`), parses filenames if provided, assigns product IDs, a... | def set_product(self, product=None, filename=None, product_id=None, **kwargs):
"""Configure a product.
:param product: product id string, requires explicit kwargs
:param product_id: product id string.
:param filename: product description presented as a filename
:returns... |
def handle_radio_button_date(self, value_date, *args):
# value_date = selection_option1
if args[0] == value_date:
# first we make the calendar available
args[1]["state"] = tkinter.NORMAL
# delete all other entries
args[2]["state"] = tkinter.NORMAL
... | This function creates a GUI for deleting patient records by allowing users to select search criteria (date, name, or CNP), input corresponding details, and trigger deletion via an 'OK' button. It disables unused fields based on selection, includes validation, and provides cancel functionality. | def create_delete_gui(self):
global root_delete
app_menu.destroy()
# global variables
global radio_button_date
global radio_button_name
global radio_button_cnp
global calendar_entry
global first_name_entry_delete
global last_name_entry_delete
... |
def handle_radio_button_date(self, value_date, *args):
# value_date = selection_option1
if args[0] == value_date:
# first we make the calendar available
args[1]["state"] = tkinter.NORMAL
# delete all other entries
args[2]["state"] = tkinter.NORMAL
... | The code creates a GUI for viewing and updating patient records. It allows users to select search criteria (date, name, or CNP), input corresponding data, and retrieve/edit records. The interface includes disabled fields that activate based on radio-button selections, with OK/Cancel buttons to submit or discard changes... | def create_edit_gui(self):
global root_edit
app_menu.destroy()
# global variables
global radio_button_date_edit
global radio_button_name_edit
global radio_button_cnp_edit
global calendar_entry_edit
global first_name_entry_edit
global last_name_entr... |
def checkout_run_load(commit_id: str, case_name: str, build_type: str, patch_nml: dict, download_zip) -> pd.DataFrame:
if download_zip:
path_to_exe, commit_id = build_teb_make(commit_id)
else:
git_checkout(commit_id)
path_to_exe = build_teb(commit_id, build_type)
path_to_case_dir = ... | This function compares two datasets (reference and trial) by loading them, aligning columns, calculating differences, visualizing discrepancies, and validating equality. It returns a DataFrame of differences, raises an error if mismatches occur (unless allowed), and prints RMSE and sample counts. | def compare(ref_id: str, trial_id: str, case_name: str, build_type: str, patch_nml=[None, None], make=[False, False], allow_failure=False) -> pd.DataFrame:
df_ref = checkout_run_load(ref_id, case_name, build_type, patch_nml[0], make[0])
df_trial = checkout_run_load(trial_id, case_name, build_type, patch_nml[1],... |
def prepare_env():
global macro_options
macro_options = load_macro_options()
def bootstrap_scene():
Gui.Selection.clearSelection()
if macro_options.get('reset_visibility'):
reset_objects_visibility()
def capture_images():
view_command_key = macro_options.get('view')
view_command_map = {
'left': capt... | The main task of the code is to automate a workflow involving environment preparation, scene setup, image capture, scene cleanup, and project saving. It sequentially executes functions to initialize conditions, generate or capture data (images), and store results, ensuring a structured process for tasks like simulation... | def main():
prepare_env()
bootstrap_scene()
capture_images()
teardown_scene()
save_project() |
def decoder_results(self, results):
org_obs = results[TEAM_NAME].obs
img = cv.cvtColor(np.array(org_obs[0][AGENT_ID] * 255, dtype=np.uint8), cv.COLOR_RGB2BGR)
rotation = org_obs[1][AGENT_ID][0:4]
position = org_obs[1][AGENT_ID][4:7]
arm_angle = org_obs[1][AGENT_ID][7]
cat... | This function executes an environment step by applying agent actions, retrieving decision/terminal results, determining episode termination, and returning observations, rewards, and metadata. It processes actions from `action_dict`, steps the environment, decodes results into observations, calculates dense rewards, and... | def _step(self, action_dict=None) -> DecisionSteps:
all_agents = []
for behavior_name in self.env.behavior_specs:
# add actions
for agent_id in self.env.get_steps(behavior_name)[0].agent_id:
key = behavior_name + "_{}".format(agent_id)
all_agents.a... |
def seed(self, sd=0):
if self.env is not None:
self.env.close()
worker_id = sd
while IsOpen(self.port+worker_id):
worker_id += 1
self.env = UnityEnvironment(file_name=self.env_file_name,
base_port=self.port,
... | The code resets the environment by initializing the random seed, resetting the environment state, advancing one step, calculating the initial distance to a mine, and returning the resulting observation. It handles seed setting, environment initialization, step counting, and state updates to prepare for a new episode. | def reset(self, seed=None, options=None):
if seed is not None:
self.sd = seed
if self.env is None:
self.seed(self.sd)
self.step_num = 0
self.env.reset()
obs, _, _, _ = self._step()
self.last_dist = self.get_dist_to_mine(self.current_results)
... |
def load_coords(self, report_path=None):
if report_path is None:
if (not os.path.exists(self.human_report_path)) and os.path.exists(self.auto_report_path):
report_path = self.auto_report_path # Only use the auto path if exists and human doesn't
else:
repo... | The main task of the code is to load a selected medical study's data, initialize UI components (e.g., combo boxes), retrieve file paths for numpy arrays and reports, configure sequence windows, load ROI coordinates, set default visualization parameters, and trigger initial rendering. It handles errors if the selected s... | def load_study(self):
self.i_window = 0
self.comboBox_sequences.clear()
try:
sequence_id = self.comboBox_studies.currentText()
self.numpy_path = self.sequences[sequence_id]['numpy_path']
self.human_report_path = self.sequences[sequence_id]['human_report_path']... |
def action_changemode(self):
if self.labelmode == 'add':
print(f"Add -> Edit")
self.labelmode = 'edit'
self.imageItem.mousePressEvent = None
elif self.labelmode == 'edit':
print(f"Edit -> Add")
self.labelmode = 'add'
self.imageItem... | The code creates keyboard shortcuts for a GUI application, linking specific keys (e.g., Space, numbers, arrow keys, X, Delete) to actions like changing modes, labels, studies, sequences, windows, or invalidating elements. It maps each shortcut to corresponding buttons and functions, enabling keyboard navigation and int... | def create_shortcuts(self):
# Space -> Edit
shortcut_mode = QShortcut(QKeySequence("Space"), self.pushButton_mode)
shortcut_mode.activated.connect(lambda: self.action_changemode())
self.shortcuts['mode'] = shortcut_mode
# Numbers -> Labels
for i, label in enumerate(LABEL... |
def garbage_collect(self):
#iterate through file namespace and remove old deleted files
filenames_to_delete = []
for filename in self.filename_to_chunks:
f = self.filename_to_chunks[filename]
if f.deleted:
if time.time() > f.deleted_time + self.deleted_fil... | The code defines a background thread that repeatedly executes maintenance tasks at specified intervals. It continuously performs garbage collection, checks heartbeats, rereplicates data chunks, and synchronizes state, ensuring system health and data consistency. The loop runs indefinitely, pausing for the given interva... | def background_thread(self, interval):
while True:
self.garbage_collect()
self.check_heartbeats()
self.rereplicate_chunks()
self.syncState()
time.sleep(interval) |
def copy_onnx_file(model_file, dst_dir):
if not os.path.isdir(dst_dir):
os.mkdir(dst_dir)
file_name = os.path.basename(model_file)
dst_file = dst_dir + '/' + file_name
cmd = 'cp ' + model_file + ' ' + dst_file
os.system(cmd)
def wrapup_inputs(session, dim_val_dict, default_val):
param_in... | The function copies an ONNX model to an output directory and generates multiple test cases by creating input data, running inference, and saving results. It iterates `case_num` times, producing input/output files for each case using a session and dimension value mappings. | def create_cases(model_file, session, dim_val_dict, default_val, out_dir, case_num):
#copy onnx file
print("Copy {} to {}".format(model_file, out_dir))
copy_onnx_file(model_file, out_dir)
for i in range(case_num):
print("Create case {}".format(i))
data_dir = out_dir + '/test_data_set_' ... |
def parse_args():
parser = argparse.ArgumentParser(description="Run an onnx model")
parser.add_argument('--default_dim_val', type=int, metavar='deft_val', default=1, help='Specify the default value used for dim variables')
parser.add_argument('--var_dim', type=str, help='Specify the value of a variable dim'... | The main task of the code is to parse command-line arguments, load a machine learning model, generate test cases by configuring dimension values, and execute the model with specified parameters. It creates test scenarios by copying the model to a designated directory if the 'create_test' flag is enabled, then runs the ... | def main():
args = parse_args()
default_val = args.default_dim_val
model_file = args.model
ep_name = args.ep
out_dir = args.case_dir
case_num = args.case_num
var_dim = args.var_dim
dim_val_dict = {}
if var_dim is not None:
dim_val_dict = json.loads(var_dim)
# create a s... |
def policy(self):
"""
Returns actions from keyboard input
TODO: Override this method to customize policy
"""
self.keyboard_control()
gas_a = 1 if self.is_up else 0
brake_a = 1 if self.is_down else 0
w = (
self.degree_to_radian(1)
if... | The code runs the game engine by continuously executing episodes. It retrieves actions via a policy, steps through the environment, displays observations using OpenCV, resets upon episode completion, and closes resources when crashed. The loop processes rewards, updates states, and renders visuals in real-time until te... | def run(self):
"""
Runs the game engine
TODO: Runs episode in this format
"""
while not self.crashed:
action = self.policy()
obs, reward, done, info = self.step(action)
# print(reward, info)
if done:
self.reset()
... |
def gen_connectome_normal_lcc_adj():
adj_lcc = gen_connectome_lcc_adj()
adj_lcc_skids = adj_lcc.index
adj_lcc_skids = [str(skid) for skid in adj_lcc_skids]
inds = gen_weird_neurons_annots().index
normal_skids = [int(i) for i in adj_lcc_skids if i not in inds]
connec_normal_lcc_adj = adj_lcc.loc[... | The main task of the code is to generate and save CSV files containing skid IDs and their corresponding labels for brain hemispheres (left/right) and segments (head/pygidium/0-3), using annotations from a connectome dataset. It filters skids by hemisphere/segment and label type ("s", "i", "m"), organizes them into Data... | def gen_hemi_labels():
#get skids for l, r, head, pygidium, 0, 1, 2, 3
annotations = gen_connectome_normal_lcc_adj()
left_adj = gen_left_normal_lcc_adj()
left_adj_index = list(left_adj.index)
right_adj = gen_right_normal_lcc_adj()
right_adj_index = list(right_adj.index)
all_hemi_index =... |
def chooseAlternateStartPlayer():
global p
if p==0:
p=1
return 'x'
else:
p=0
return 'o'
def showBoard(boardState):
print('\n')
print(boardState[0]+boardState[1]+boardState[2])
print(boardState[3]+boardState[4]+boardState[5])
print(boardState[6]+boardState[7]+b... | The code trains a Q-learning agent for Tic-Tac-Toe by simulating games, updating a Q-table with random values for new states, and iterating until a specified training size is reached. It alternates starting players, checks game states, and updates Q-values based on moves and outcomes, ensuring exploration through rando... | def learn(trainingSize):
currentPlayer= chooseAlternateStartPlayer()
count = 0
noOfMoves=0
while(count< trainingSize):
showBoard(boardState)
nextMove= determineNextMoveforTraining(currentPlayer, noOfMoves)
ke= currentPlayer + ''.join(boardState) + ... |
def _dictDeUnderscore(d):
"""Takes a dict, and renames all keys that start with an '_' to not contain that
anymore. This is done because some keys are illegal as kwargs (notably 'with'
and '3d'), so the user passes in '_with' and '_3d', which ARE legal
"""
d2 = {}
for key in d:
if isinstance(key... | This code initializes a gnuplot process for plotting, either resetting an existing one or starting a new instance. It applies provided plot options, manages process state, and ensures proper setup for data visualization with logging and checkpointing features. | def __init__(self, **plotOptions):
# some defaults
self.plotOptions = _dictDeUnderscore(plotOptions)
self.t0 = time.time()
self.checkpoint_stuck = False
self.sync_count = 1
plotOptionsCmds = self._getPlotOptionsCmds()
# if we already ha... |
def _massageAndValidateArgs(self, curves, curveOptions_base):
# Collect all the passed data into a tuple of lists, one curve per list
if all(type(curve) is np.ndarray for curve in curves):
curves = (list(curves),)
elif all(type(curve) is tuple for curve in curves):
curve... | This function generates a plot using gnuplot by configuring terminals/output, validating input curves, executing plot commands, and handling data transmission. It tests plot commands for errors, sets output destinations based on options, and renders the plot with specified curves while reporting warnings. | def plot(self, *curves, **curveOptions_base):
r"""Main gnuplotlib API entry point"""
curves = self._massageAndValidateArgs(curves, curveOptions_base)
# I'm now ready to send the plot command. If the plot command fails,
# I'll get an error message; if it succeeds, gnuplot will sit there... |
def revert_guess(self):
# Revert to previous state due to incorrect choice
state = self.States.pop(-1)
# Update state
self.sudoku.state = state[0]
self.cell_number_options = state[1]
self.empty_cells = state[2]
def reduce_options(self, cell: tuple) -> None:
# More... | This function examines a puzzle cell's state to determine the next action: if no valid options remain, it reverts a guess and reduces possibilities; if only one option exists, it fills the cell; otherwise, it tracks progress. It manages backtracking logic by setting flags for looped states and updated cells, essential ... | def examine_cell(self, cell: tuple):
# Examine cell and act based on cell state
if not self.cell_number_options[cell]:
# Empty cell with no possible move, reverse guess
self.revert_guess()
self.reduce_options(cell)
self.reverted_flg = True
self... |
def examine_cell(self, cell: tuple):
# Examine cell and act based on cell state
if not self.cell_number_options[cell]:
# Empty cell with no possible move, reverse guess
self.revert_guess()
self.reduce_options(cell)
self.reverted_flg = True
self... | The code solves a Sudoku puzzle by iteratively examining empty cells, narrowing down possible numbers through constraints, and using preemptive sets or random guessing when stuck. It limits iterations to prevent infinite loops, returning the solved Sudoku state if successful or an empty list if unresolved. Your return | def solve(self):
# Solve sudoku puzzle
counter = 0
while len(self.empty_cells) != 0:
# New loop
counter += 1
if counter == 5000:
# print("Counter full!\n", self.cell_number_options)
return []
# For each empty cell
... |
def set_random_seeds(self, random_seed=0):
torch.manual_seed(random_seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(random_seed)
random.seed(random_seed)
def get_model(self, encoder_layers=2, loss_alpha=0.7):
if "blend... | The code initializes a machine learning model with configurable parameters for training and evaluation, setting up data loaders, device allocation (GPU/CPU), distributed training, and personality trait predictors. It prepares the model architecture, tokenizer, and datasets for tasks like dialogue generation, handling d... | def __init__(self, mname, ablation_remove, dataset, encoder_layers, training_file, trait_in_decoder=True,
local_rank=0, batch_size=8, num_workers=2, num_train=None, uni_agent=True, lr=2e-5, N_EPOCHS=8,
accum_iter=4, contradiction_penalty=False, intent_model_path=None, big5_model_path=N... |
def getVacantCells(self):
vacantCells = []
for i in range(9):
if(self.cells[i].pegPlaced=='#'):
vacantCells.append(self.cells[i])
return vacantCells
def calcScore(self):
# return +100 if X wins, -100 if 0 wins, 0 for tie
# check diagonals
winne... | The main task of the code is to enable the computer to determine and execute its move in a tic-tac-toe-like game. It checks if the board is empty (random move), if full (declare result), or uses MinMax algorithm (maximizer/minimizer) to select optimal positions based on the computer's peg (X or 0). It also tracks evalu... | def computerMove(self):
self.banner="Computer's move"
MinMax.count=0
if(self.isEmpty):
position = random.randint(0,8)
self.cells[position].placePeg(self.computerPeg)
self.isEmpty = False
elif(len(self.getVacantCells())==0):
# board is full
... |
def getVacantCells(self):
vacantCells = []
for i in range(9):
if(self.cells[i].pegPlaced=='#'):
vacantCells.append(self.cells[i])
return vacantCells
def calcScore(self):
# return +100 if X wins, -100 if 0 wins, 0 for tie
# check diagonals
winne... | The main task of the code is to handle a user's move in a game by validating input, placing a peg in a chosen vacant cell, checking for game-ending conditions (win/tie), and updating the game state. It ensures the input is a valid position (0-8), checks if the cell is empty, places the user's peg, and prints the board.... | def userMove(self):
self.banner="Your move"
if(len(self.getVacantCells())==0):
# board is full
winner = self.calcScore()
if winner==0:
print("It is a tie!")
elif winner==100:
print("Player X has won!")
elif winne... |
def __get_min(self, data):
return min(data)
def __get_max(self, data):
return max(data)
def _get_mean(self, data):
return float(sum(data) / len(data))
def _get_dispersion(self, data):
means = self._get_mean(data)
dispersion_values = sum([(num - means)**2 for num in data]) / len(d... | The main task of the code is to compute and return a dictionary of statistical metrics for the input data, including minimum, maximum, mean, dispersion, standard deviation, asymmetry, kurtosis, mean square, and root mean square error. It aggregates these values using private helper methods to provide a comprehensive st... | def get_statistics(self, data):
stats = {"Min Value": self.__get_min(data),
"Max Value": self.__get_max(data),
"Mean Value": self._get_mean(data),
"Dispersion Value": self._get_dispersion(data),
"Standard Deviation Value":... |
def mask_knn(m, k=1, policy='cols'):
"""Creates mask showing knn in each row/column of adjacency matrix"""
assert policy in ['cols', 'rows']
mask = np.zeros(m.shape, dtype='bool')
if policy == 'rows':
assert m.shape[0] >= k
vals = np.partition(m, k+1, axis=1)[:, k] # kth value in each r... | The main task of the code is to generate a recurrence plot (RP) for a given signal segment using specified parameters like dimension, time delay, and thresholding method. It saves the RP as an image file, optionally resizes it, and displays it if requested. The function handles different RP generation methods, includin... | def create_rp(segment,
dimension=2, time_delay=1, percentage=1, use_clip=False, knn=None, imsize=None,
images_dir='', base_name='Sample',
suffix='jpg', # suffix='png'
show_image=False, cmap=None, ##cmap='gray', cmap='binary'
):
"""Generate recurre... |
def restart_training(self, step):
"""
Function for restarting training from step.
Parameters:
step : int
Which step to restart training from.
Returns:
None
"""
self._load_model(step)
self._load_log(step)
def evaluate_agent... | The main task of the code is to train a Deep Q-Network (DQN) agent using experience replay, with support for resuming training from a specified step. It initializes the environment, sets up replay buffers, and iteratively collects data, trains the agent, adjusts exploration rates (epsilon-greedy), saves checkpoints, ev... | def train(self, restart_step=0):
"""
Method for running training of DQN model.
Parameters:
restart_step : int
Step to restart training from.
Defaults to 0 for fresh start.
Returns:
None
"""
tf.compat.v1.ena... |
def _save_net_shape(self):
"""
Method for saving shape of network.
"""
shapes = []
for w in self.agents[0].get_weights():
shapes.append(w.shape)
self.net_shape = shapes
def _calc_n_weights(self):
"Method for saving number of weights/biases in network"
... | This method initializes the first generation of agents or restarts from a previous generation. It creates agent networks, calculates parameters like crossover rate and mutation rates, logs data, and returns generation time, steps, and evolutionary parameters. If restarting, it retrieves saved values from a prior genera... | def initialize_gen(self,start_time,restart_gen):
"""
Method for initializing first generation of agents
or reloading agents from restart generation.
Parameters:
start_time : float
The time training started.
restart_gen : int
Genera... |
def initialize_gen(self,start_time,restart_gen):
"""
Method for initializing first generation of agents
or reloading agents from restart generation.
Parameters:
start_time : float
The time training started.
restart_gen : int
Genera... | The code evolves agent populations across generations using evolutionary algorithms. It initializes parameters, iterates through generations, creates new agents via selection/mutation, scores them, tracks elites, adjusts mutation rates, logs progress, and checkpoints. It supports restarting from a specified generation,... | def evolve(self,restart_gen):
"""
Method that runs evolution of generations of agents.
Parameters:
restart_gen : int
Generation to restart training from,
0 means starting from new initial generation.
Returns:
None
"""
... |
def process_files(worker_count: int, root: str, test_rate: float = 0.0005, *, recursive: bool = False):
"""process all files in a folder
gather all files if recursive (a simple way)
"""
files = _gather_files(root, recursive)
file_count = len(files)
val_file_count = int(file_count * test_rate)
... | The main task of the code is to process files or tarballs in a source directory using parallel workers. It checks if the source is valid, identifies eligible tarballs (or text files), skips completed tasks via logs if enabled, and processes remaining files. Parameters include worker count, test rate, and flags for text... | def main(source: str, worker_count: int, test_rate: float = 0.0005, *,
pure_text: bool = False, continue_with_log: bool = True, recursive_folder: bool = False) -> bool:
"""
:source: src dir to process
"""
logging.info(
f"launching main to process {source} with {worker_count} processes")... |
def heurestic(state, g1, g2): #heurestic funtion
return abs(state.jugone - g1) + abs(state.jugtwo - g2)
def goalTest(state, g1, g2): #test state to see it is goal node
if state.jugone == g1 and state.jugtwo == g2:
return True
else:
return False
def getNode(state, queue): #search list to see ... | The code implements the A* search algorithm to find the optimal path from an initial state (j1, j2) to a goal state (g1, g2). It generates successor states through defined actions (e.g., pouring, dumping), calculates heuristic and path costs, and prioritizes nodes using a priority queue. Upon reaching the goal, it reco... | def AStar(j1, j2, g1, g2): #A Star Search
f.write("Inital State: (%d , %d)\n" % (j1, j2))
f.write("Goal State: (%d , %d)\n" % (g1, g2))
f.write("Seaching strategy: A *\n")
head = State(j1, j2)
head.h = heurestic(head, g1, g2) #calcuate heurestic
queue = []
visited = []
queue.append(head)... |
def does_dir_path_exist():
"""
True -> dir_path exists
False -> it does not exist
"""
pass
def check_given_alias(alias: str = None) -> str:
"""
If 'alias' is given and is in the correct format -> returns the corrected
format if necessary
"""
if alias is None:
alias = in... | The main task of the code is to save a directory alias by validating the input directory path, handling user-provided or prompted alias names, and updating a YAML aliases file. It checks directory existence, resolves '.' to the current working directory, ensures an alias is provided, and writes the alias-directory mapp... | def save_alias(dir_path: str, alias: str = None) -> None:
"""
Save alias will perform checks to see whether this connection can be
saved, and then it will save it, should it be allowed. Otherwise,
it will return to the user what went awry
"""
# Checks existance of the target directory, and shap... |
def get_model():
input_tensor = Input(shape=(3, 224, 224))
base_model = VGG16(weights='imagenet', input_tensor=input_tensor)
x = base_model.get_layer('block3_conv3').output
x = Conv2D(512, (5, 5), activation="relu", name="conv4", padding="same", kernel_regularizer=regularizers.l2(0.01))(x)
x = Co... | The code's main task is to either train a neural network model for 100,000 epochs with validation and logging callbacks or use a pre-trained model to generate predictions on test data, saving results and weights. It loads datasets, preprocesses them, and handles model training/prediction based on command-line arguments... | def main():
model = get_model()
model.summary()
inputs, outputs = load_datasets()
X_train_orig, X_test_orig, Y_train_orig, Y_test_orig = train_test_split(inputs, outputs, test_size=0.10, random_state=16)
X_train, Y_train = preprocess(X_train_orig, Y_train_orig)
X_test, Y_test = preprocess(X_t... |
def get_model():
input_tensor = Input(shape=(3, 224, 224))
base_model = VGG16(weights='imagenet', input_tensor=input_tensor)
x = base_model.get_layer('block3_conv3').output
x = Convolution2D(256, 7, 7, init='normal', activation='relu', border_mode='same', name='conv6')(x)
x = Convolution2D(128, 1... | The code's main task is to load a pre-trained model, perform predictions on a validation/test dataset, and save the output predictions. It includes model initialization, data loading, prediction execution, and result storage, with comments indicating potential future weight loading and output saving steps. | def main():
model = get_model()
model.summary()
# model.load_weights(OUT_DIR + 'model.01.weights')
(X_train, Y_train), val = load_datasets()
#### Predict ####
print('Starting prediction')
predictions = model.predict(val[0], verbose=1)
print('Prediction shape is {}'.format(predictions... |
def extractEdges(times):
edges = []
for i in range(len(times)):
for j in range(len(times[i])):
if (i != j):
edges.append([i, j, times[i][j]])
return edges
def hasNegativeCycle(edges):
distances = {}
for edge in edges:
if edge[0] not in distances:
... | The code finds the maximum number of bunnies that can be rescued within a given time limit by analyzing a graph derived from the `times` matrix. It checks for negative cycles, which indicate unlimited bunny rescues. If absent, it evaluates all possible paths, prioritizing the longest valid path (by number of bunnies) u... | def solution(times, time_limit):
edges = extractEdges(times)
if hasNegativeCycle(edges):
return [b - 1 for b in range(1, len(times) - 1)]
paths = getAllPaths(len(times) - 2)
longestPath = []
longestPathWorkerIds = 1000
for path in paths:
if len(path) < len(longestPath)... |
def generateGasArray(g):
gasArray = [0 for col in g[0]]
for rowIndex, row in enumerate(g):
rowBitValue = 2 ** rowIndex
for colIndex, cell in enumerate(row):
if cell:
gasArray[colIndex] += rowBitValue
return gasArray
def getPrecomputedValues(max):
limit = 2 ** ... | The code calculates the number of valid configurations in a gas array by recursively exploring paths, using memoization (nebulaCache) and precomputed values to optimize. It initializes possibleConfigurations, iterates through precomputed values for the last gas element, and accumulates results from diveIntoTheNebula ca... | def solution(g):
gasArray = generateGasArray(g)
precomputedValues = getPrecomputedValues(len(g) + 1)
nebulaCache = {}
possibleConfigurations = 0
for x, y in precomputedValues[gasArray[len(gasArray) - 1]]:
possibleConfigurations += diveIntoTheNebula(gasArray, precomputedValues, len(g... |
def readRelated():
dd = {}
filename = "./related.txt"
with open(filename, "r") as f:
for line in f:
row = line[:-1].split()
dd[row[0]] = row[3:]
return dd
def readSampleDesc():
filename = "./sample_descriptions.txt"
dd = {}
row = 0
with open(filename, "r")... | The main task of the code is to process product-related data by filtering, mapping product IDs to indices, serializing filtered data into JSON and pickle formats, and splitting the dataset into training and test sets for further analysis or model training. | def main():
related = readRelated()
sampleDesc = readSampleDesc()
related, sampleDesc = filterProducts(related, sampleDesc)
print("\nin main...")
print("related", len(related))
print("sample desc", len(sampleDesc))
productIdToIdx = {}
for i, item in enumerate(sampleDesc):
product... |
def process_artist(message):
global current_artist, artist_stale
message = message.upper()
message = message.replace("|"," ")
current_artist = message
artist_stale = False
# print(current_artist)
send_data_if_ready()
def process_title(message):
global current_title, title_stale
messag... | This function processes incoming MQTT messages by decoding payloads and routing them to specific handlers based on their topics: "bcuda/artist" and "bcuda/title" trigger artist/title processing, "bcuda/ssnc/prgr" handles progress data, while "bcuda/play_end" and "bcuda/play_start" log pause/play triggers. | def on_message(client, userdata, message):
message_string = str(message.payload.decode("utf-8"))
#print("topic:",message.topic)
if message.topic == "bcuda/artist":
process_artist(message_string)
if message.topic == "bcuda/title":
process_title(message_string)
if message.topic == "bcu... |
def process_artist(self, message):
message = message.upper()
message = message.replace("|"," ")
self.current_artist = message
self.artist_stale = False
# print(current_artist)
self.send_data_if_ready()
def process_title(self, message):
message = message.upper()
... | This code processes incoming MQTT messages by decoding payloads, identifying topics, and triggering specific handler methods (e.g., processing artist, title, progress) or actions (play/pause) based on the topic. It logs messages and routes data to appropriate functions for further processing. | def on_message(self, client, userdata, message):
message_string = message.payload.decode("utf-8")
topic = message.topic
print('got message', message)
print("topic:", topic)
if topic == "bcuda/artist":
self.process_artist(message_string)
elif topic == "bcuda/ti... |
def set_up(self, master):
self.root = master
self.root.title(App.Home.TITLE)
self.root.iconbitmap('rsc/img/app/logo.ico')
self.root.state('zoomed')
def load_data(self):
self.cards = []
query = App.db.execute_query('SELECT * FROM Card WHERE user_id ... | The code initializes a GUI application by setting up the main window, loading data, and organizing the interface with a main layout, sidebar, and mainframe. It prepares the application's structure and data for display. | def __init__(self, master):
self.set_up(master)
self.load_data()
self.main_layout()
self.sidebard_layout()
self.mainframe_layout() |
def __parseTimex(self, text): #for DCT
(timex_tag, timex_text) = re.findall(r'<(TIMEX3.*?)>(.+?)</TIMEX3>', text)[0]
(tid, ttype, tvalue, tanchor, tfunc, tfuncdoc) = self.__parseTimexTag(timex_tag)
return (timex_text, (tid, ttype, tvalue, tanchor, tfunc, tfuncdoc))
def __parseEventInstances(se... | The code parses TimeML-formatted text to extract the document creation time (DCT) and content, cleans the content, and processes it using either Stanford CoreNLP or TextPro for tokenization. It then parses event, link, and other TimeML elements, executes NLP tools, and returns structured data via `__buildColumns()`. Te... | def parseTimeML(self):
dct_text = re.findall(r'<%s>(.+?)<%s>' % ('DCT','/DCT'), self.timeml)[0]
self.dct = self.__parseTimex(dct_text)
self.content = re.findall(r'<%s>(.+?)<%s>' % ('TEXT','/TEXT'), self.timeml, re.DOTALL)[0]
self.content = self.content.replace("``", "\"")
self.c... |
def perform(self, eId, dt, dir):
lenStop = len(self.stops[eId]) # how many actions needed to be done by the coursethe
i = 0
while lenStop > 0:
if self.stops[eId][0]["et"] > dt: # if tackeled with action that is above the time then the rest hadn't been completed since
... | This function determines the optimal elevator to handle a new request by simulating previous calls to find each elevator's current position. If multiple elevators exist, it selects the best one based on the request direction (up/down), updates its status, and adds the call to its stops. The chosen elevator's index is r... | def allocateAnElevator(self, c):
# for every elevator run simulation of prevoius calls and determine the current position
for eId in range(self.lenElev):
self.perform(eId, c["dt"], self.direction[eId])
ans = 0
if self.lenElev > 1: # only if there are more that 1 elevators ru... |
def perform(self, eId, dt, dir):
lenStop = len(self.stops[eId])
i = 0
while lenStop > 0:
if self.stops[eId][0]["et"] > dt:
# add the check of status
if self.stops[eId][0]["mode"] != Elevator.GOTO:
self.elevators[eId]._pos = self.s... | The code allocates the optimal elevator for a request by evaluating direction (up/down) and selecting the best elevator index. It updates the chosen elevator's status and sets stops, returning the selected index for service. | def allocateAnElevator(self, c):
for eId in range(self.lenElev):
self.perform(eId, c["dt"], self.direction[eId])
ans = 0
if self.lenElev > 1:
if c["src"] < c["dst"]:
ans = self.getBestIndexUp(c)
self.upadeUp(ans)
else:
... |
def parseValidWords(filepath):
with open(filepath, 'r') as file: line = file.readline()
words = line.replace("\"", '').split(',')
return [word.upper() for word in words]
def countAllLetterOccurrences(words):
letters = list(string.ascii_uppercase)
counts = {letter:0 for letter in letters}
for le... | The code's main task is to iteratively guess a target word by analyzing letter frequencies from a list of valid words. It starts by parsing valid words, counting letter occurrences, and selecting an optimal initial guess. After each guess, it evaluates feedback (correct/present/none letters), filters remaining possible... | def main():
words = parseValidWords("words.txt")
counts = countAllLetterOccurrences(words)
currentGuess = computeBestGuess(counts, words)
turnCount = 0
while True:
turnCount += 1
printGuess(turnCount, currentGuess)
none, present, correct = getGuessResults(currentGuess)
... |
def calc_grad_func(X, A, mu):
m = A.shape[0]
X_inv = invert_PD_matrix(X)
val1 = -1 * np.transpose(X_inv)
val2 = mu * np.sum([np.outer(A[i], A[i]) / np.maximum(1 - np.dot(A[i], X @ A[i]), EPSILON) for i in range(m)], axis=0)
return val1 + val2
def calc_backtracking(X, func, grad_val_at_X):
prin... | The code performs gradient descent to optimize a matrix $ X $, ensuring it remains positive definite (PD) and satisfies constraints defined by matrix $ A $. It iteratively computes the gradient, adjusts $ X $ using a backtracking step size, projects $ X $ onto the PD cone, and enforces constraints. The loop terminates ... | def perform_grad_decent(X_start, A, mu):
# Set variables
X = X_start
iteration = 0
delta_x = 1.
while iteration < MAX_ITERATIONS and delta_x > EPSILON:
print(#f"iteration: {iteration + 1}\n"
f"delta_x: {delta_x}")
print("perform_grad_decent 1")
# Compute the grad... |
def ensure_data_dir_exists():
data_dir = get_data_dir()
if not os.path.exists(data_dir):
os.makedirs(data_dir)
def get_data_dir():
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_dir, "data")
def log_error(error_message):
ensure_data_dir_exists... | The function appends a list of data to an existing JSON file ("graph_data.json") in a specified directory, creating the file if it doesn't exist. It reads the current JSON content, extends it with the provided data, and writes the updated list back to the file. Error handling logs any exceptions during the process. | def append_to_json(data_list):
ensure_data_dir_exists()
file_path = os.path.join(get_data_dir(), "graph_data.json")
try:
if os.path.exists(file_path):
with open(file_path, "r") as file:
file_data = json.load(file)
else:
file_data = []
file_dat... |
def create_adjacency_matrix(airports, routes):
adj = { airport: [] for airport in airports }
adj_transp = { airport: [] for airport in airports }
for origin, destination in routes:
adj[origin].append(destination)
adj_transp[destination].append(origin)
return adj, adj_transp
def SCC(nodes... | The code determines the number of strongly connected components (SCCs) in an airport network that have no incoming edges and do not contain the starting airport. It constructs an adjacency matrix, identifies SCCs, transposes the component adjacency, and counts components with zero incoming edges excluding those contain... | def airportConnections(airports, routes, startingAirport):
# Create the adjacency matrix
adj, adj_transp = create_adjacency_matrix(airports, routes)
# Find strongly connected components
components, adj_components = SCC(airports, adj, adj_transp)
# Count number of strongly connected components that h... |
def parse_tree(string: str) -> Node:
if string[0] != "[":
return Node(int(string), None, None)
level = 0
for i, elem in enumerate(string):
if elem == "[":
level += 1
if elem == "]":
level -= 1
if elem == "," and level == 1:
return Node(-1... | The code processes a text file containing tree-like expressions, parsing each line into a tree structure. It combines trees sequentially using `add` and `clean` operations, then calculates the magnitude of the final tree. Additionally, it evaluates all distinct pairs of lines to find the maximum magnitude achievable by... | def main() -> None:
with open("input.txt") as input:
lines = [l.strip() for l in input.readlines()]
tree = parse_tree(lines[0])
for line in lines[1:]:
tree = add(tree, parse_tree(line))
clean(tree)
# print_tree(tree)
print(magnitude(tree))
max ... |
def _composable(self, idx1: int, idx2: int) -> bool:
"""Returns true if two rules indicated by their indices are composable
Args:
idx1 (int): Index of the first rule
idx2 (int): Index of the second rule
Returns:
bool: True if labels match and neither of the ... | This function processes two rules by checking if they can be composed. If composable, it creates a new rule from their 'if' parts, evaluates its fitness against the original rules, and updates the system with the new rule if it has higher fitness. | def _process_rules(self, idx1: int, idx2: int) -> None:
"""Process two rules indiciated by their indices
Args:
idx1 (int): Index of the first rule
idx2 (int): Index of the second rule
"""
if self._composable(idx1, idx2):
composition = self._compose(se... |
def _label_to_int(self, label: np.ndarray) -> int:
"""Converts dummy label to int
Args:
label (np.ndarray): Label to convert
Returns:
int: Converted label
"""
return int(np.argmax(label))
def XNOR(input: np.ndarray, other: np.ndarray) -> np.ndarray:
... | The main task of the code is to train the RACER algorithm by fitting it to input features X and targets y. It processes data to generate initial rules, evaluates rule fitness, generalizes extant rules, and finalizes the model by sorting rules by fitness. The code also includes benchmarking for performance tracking, sto... | def fit(self, X: np.ndarray, y: np.ndarray) -> None:
"""Fits the RACER algorithm on top of input data X and targets y.
The code is written in close correlation to the pseudo-code provided in the RACER paper with some slight modifications.
Args:
X (np.ndarray): Features vector
... |
def search_for_item(value):
parms = {"q": value}
r = requests.get(url="https://www.googleapis.com/books/v1/volumes", params=parms)
rj = r.json()
if rj.get("items"):
return get_five(rj)
else:
print("Oops! No books found! Try again: ")
new_value = str(input())
return se... | The code allows users to search for books by author, title, subject, or ISBN, add the results to a list, view the list, and repeat the process. It prompts for input, executes searches, manages a book list, and loops for continued use. | def run_program():
print("Please enter a search query such as author, title, subject, or ISBN")
newbk = input()
five_bks = search_for_item(str(newbk))
add_to_list(five_bks)
# Allow users to view their book list
print("View current list? Y/N")
view_my_list()
print("Do you want to keep sea... |
def map_source_management(self):
# add alternative map sources to the MapSource
alternative_map_source = (0, 0, 19, 'https://{s}.tile.opentopomap.org/{z}/{x}/{y}.png',
'Kartendaten: © OpenStreetMap-Mitwirkende, '
'SRTM | Kartendarstellu... | This code initializes a class instance by setting up a CSV file path, current date/time, map sources, and reading point records. It schedules a crosshair update every second and confirms initialization with a print statement. | def __init__(self, **kwargs):
super().__init__(**kwargs)
self.file = 'data/simple_point_records.csv'
self.next_id = None
self.table_items = {}
self.ids.date.text = datetime.date.today().strftime("%Y-%m-%d")
self.ids.time.text = datetime.datetime.now().strftime("%H:%M")
... |
def get_moves(self, board):
moves = []
for i in range(self.board_size):
for j in range(self.board_size):
if board[i][j] == 0:
moves.append([i, j])
return moves
def ab_value(self, depth, a, b, board, colour, legal_moves):
if (depth == 0):
... | The code implements the minimax algorithm with alpha-beta pruning to determine the optimal move for a player in a game. It evaluates all legal moves by recursively assessing their outcomes using the `ab_value` function, which calculates the minimax value. The function selects the move with the lowest minimax value, rep... | def minimax(self, depth):
legal_moves = self.get_moves(self.board)
min_val = inf
best_move = []
for move in legal_moves:
test_board = deepcopy(self.board) #copy board into another variable
test_board[move[0]][move[1]] = self.colour #make move on copied boa... |
def LoadImage(img_name):
img = ~mpimg.imread(img_name)
img = np.delete(img, 2, 2)
img = np.delete(img, 1, 2)
img = img.squeeze()
img = clearNoise(img)
return img
def SplitImage(img):
n = 0
pn = 0
TransitionState = False
height, width = img.shape
plt.imsave('./DebugImages/RTem... | The code predicts digits or letters from an image using a pre-trained Keras model. It splits the input image into individual characters, processes each with the model, and combines results into a numeric value or string. It saves debug images, calculates accuracy, and returns the prediction with an accuracy percentage. | def getPrediction(img_name, modName, digOrLet):
model = keras.models.load_model(modName)
full_img = LoadImage(img_name)
digitsOrLetters = list(SplitImage(full_img))
if len(digitsOrLetters) == 0:
return None, None
else:
val, acc = 0, 0
if digOrLet:
for i in range(l... |
def delayEmbed(D, E, tau, t = None, removeNAs=True):
n = D.shape[0]
# the time series and time index t must have the same length!
if t is not None:
assert n == len(t)
# A is the delay matrix with padded 0s at the top and bottom
totalRows = n + tau * E
A = np.zeros((totalRows, ... | The function `get_delta_agg` computes an aggregated optimal delta parameter by comparing the log-likelihoods of NS-Map and S-Map models across varying lags (1 to E). It uses delay embedding on input data `Xr`, optimizes hyperparameters via gradient descent, and weights deltas by the likelihood difference between models... | def get_delta_agg(Xr, E, tau=1, t=None, trainingSteps=100, return_forecast_skill=False, theta_fixed=False):
if t is None:
t = np.linspace(0,1, num=len(Xr))
else:
# Remember to standardize t to be between 0 and 1!
assert t[0] == 0 and t[-1] == 1
# produce delay embedding vector firs... |
def predict_poses(self, inputs, features=None, is_train=True):
"""Predict poses between input frames for monocular sequences.
"""
outputs = {}
if is_train:
frameIDs = self.opt.frame_ids
else:
frameIDs = [0, -1]
if self.num_pose_frames == 2:
# In this setting, we compute the pose to each source fram... | The function processes a batch of inputs through a neural network to predict camera poses and depth maps, applies image warping based on predicted poses, handles data augmentation (e.g., static frame replacement, cost volume masking), and computes multi-frame and single-frame losses during training. It returns generate... | def process_batch(self, inputs, is_train=False):
"""Pass a minibatch through the network and generate images and losses
"""
for key, ipt in inputs.items():
inputs[key] = ipt.to(self.device)
mono_outputs = {}
outputs = {}
# predict poses for all frames
if self.train_teacher_and_pose:
pose_pred = se... |
def check_sizes(input, input_name, expected):
condition = [input.ndimension() == len(expected)]
for i,size in enumerate(expected):
if size.isdigit():
condition.append(input.size(i) == int(size))
assert(all(condition)), "wrong size for {}, expected {}, got {}".format(input_name, 'x'.join... | The function `forward_warp` performs **inverse warping** of a source image to the target image plane using depth maps, camera intrinsics, and 6DoF pose parameters. It computes the warped image by projecting source pixels into the target frame, clamping invalid coordinates, and generating a validity mask. Key steps incl... | def forward_warp(img, depth, pose, intrinsics, upscale=None, rotation_mode='euler', padding_mode='zeros'):
"""
Inverse warp a source image to the target image plane.
Args:
img: the source image (where to sample pixels) -- [B, C, H, W]
depth: depth map of the source image -- [B, 1, H, W]
... |
def set_eval(self):
"""Convert all models to testing/evaluation mode
"""
for m in self.models.values():
m.eval()
def process_batch(self, inputs, is_train=False):
"""Pass a minibatch through the network and generate images and losses
"""
for key, ipt in inputs.items():
inputs[key] = ipt.to(self.device)... | The code validates a model on a validation set by computing depth metrics, averaging losses across batches, and comparing results to previous best performances. It logs metrics, updates the best model if improvements are found, and saves the model under specific conditions. The function also handles tensorboard logging... | def val(self):
"""Validate the model on a single minibatch
"""
self.set_eval()
losses = {}
for i, metric in enumerate(self.depth_metric_names):
losses[metric] = 0.0
losses['doj/'+metric] = 0.0
losses['doj/count'] = 0.0
losses['dojpxs'] = 0
losses['allpxs'] = 0
total_batches = 0.0
with torch.no... |
def set_train(self):
"""Convert all models to training mode
"""
for k, m in self.models.items():
if self.train_teacher_and_pose:
m.train()
else:
# if teacher + pose is frozen, then only use training batch norm stats for
# multi components
if k in ['depth', 'encoder']:
m.train()
def proc... | This function executes one training epoch, processing batches to compute model outputs and losses, performing backpropagation for parameter updates, logging training metrics, and conducting validation. It includes conditional logging, model saving, teacher model freezing, and learning rate scheduling, while handling ex... | def run_epoch(self):
"""Run a single epoch of training and validation
"""
print("----------Training----------")
self.set_train()
for batch_idx, inputs in enumerate(self.train_loader):
print(f"current batch:{batch_idx}/{len(self.train_loader)}")
before_op_time = time.time()
outputs, losses = self.p... |
def freeze_teacher(self):
if self.train_teacher_and_pose:
assert not self.opt.train_teacher_only
self.train_teacher_and_pose = False
print('freezing teacher and pose networks!')
# here we reinitialise our optimizer to ensure there are no updates to the
# teacher and pose networks
self.parameters_to... | This code defines a training loop that runs for a specified number of epochs, freezes the teacher model at a designated epoch, executes each training epoch, saves model checkpoints periodically, and integrates with wandb for logging. It initializes counters, manages model states, and ensures training process tracking. | def train(self):
"""Run the entire training pipeline
"""
self.epoch = 0
self.step = 0
# if self.opt.load_weights_folder is not None:
# self.val()
self.start_time = time.time()
for self.epoch in range(self.opt.num_epochs):
if self.epoch == self.opt.freeze_teacher_epoch:
self.freeze_teacher()
... |
def load_json_as_dict(filename, delimit_keys = None):
with open(filename,'r') as f:
raw = json.load(f)
if delimit_keys is None:
return raw
out = {tuple(k.split(delimit_keys)):v for k,v in raw.items()}
return out
def build_tree(eff_tuples):
tree = dict()
for c_efft in eff_tuples:
... | The main task of the code is to load potion data from a JSON file, construct an effect tree structure, clean and process it, then save the refined tree back to a JSON file using custom delimiters. The function orchestrates data loading, tree building, cleaning, and storage in a pipeline for structured potion effect ana... | def main():
print("Loading data...")
potion_data = load_json_as_dict('data/potion_data.json', delimit_keys = "|")
print("Building tree...")
eff_tree = build_tree(potion_data)
print("Cleaning tree...")
eff_tree = clean_tree(eff_tree)
print("Saving data...")
save_dict_as_json('data/potion_... |
def pull_ing_data():
"""
Pull ingredient data from URL and
extract following specific rules
"""
#Define outputs
ing_data = dict()
eff_data = dict()
#Get data for processing
raw = pull_bs4_url(ING_URL)
ing_tab_rows = raw.find('table').find_all('tr')[1:]
#Process
for ... | The main task of the code is to process game data from UESP to generate and evaluate potion recipes. It filters restocked ingredients, computes valid potion combinations, removes negative-effect potions, evaluates remaining recipes, and saves filtered data (ingredients, effects, merchants, and potion evaluations) to JS... | def main():
kwargs = dict(
save_dir = 'data',
file_ingredients = 'restocked_ingredients.json',
file_effects = 'effects_pos_neg.json',
file_merchants = 'merchants.json',
file_potions = 'potion_data.json',
)
#Get data
print('Pulling data from... |
def mostrar_mensaje(self, mensaje, tamano, x, y):
fuente = pygame.font.SysFont("calibri", tamano)
mensaje = fuente.render(mensaje, True, (200, 200, 200))
self.VENTANA.blit(mensaje, (x - mensaje.get_width() / 2, y - mensaje.get_height() / 2))
pygame.display.flip()
def reiniciar(self):
... | This code initializes a Pygame game window, displays a "Press ENTER to play" message, and enters a main loop to handle user inputs (QUIT, ESC, ENTER, arrow keys). It toggles game pause/resume, manages music playback, and updates the game state when active. The loop processes events, controls snake direction, and mainta... | def iniciar(self):
pygame.init()
self.VENTANA.fill(COLOR_FONDO)
self.musica.pausar()
self.mostrar_mensaje("Presiona ENTER para jugar", 50, ANCHO / 2, ALTO / 2)
while self.RUN:
self.reloj.tick(self.FPS)
for event in pygame.event.get():
if... |
def extension_key(key):
d_counter = create_d(key)
ext_key = []
key = add_padding(key, 256)
for i in range(0, len(key), 32):
ext_key.append(key[i:i + 32])
if d_counter == 4:
ext_key[4] = ext_key[0]
ext_key[5] = ext_key[1]
ext_key[6] = ext_key[2]
ext_key[7] = ex... | This code encrypts input data using a block cipher. It extends the key, pads the data to a multiple of 128 bytes, splits it into 128-byte blocks, and encrypts each block sequentially with the expanded keys, returning the concatenated encrypted result. | def encrypt(self, data, key):
tack_keys = extension_key(key)
all_tack_keys = create_K(tack_keys)
data = [1] + data
m = ((len(data) // 128) + 1) * 128
data = add_padding(data, m)
res = []
for i in range(0, m, 128):
res += self.encrypt_block(data[i:i + 1... |
def extension_key(key):
d_counter = create_d(key)
ext_key = []
key = add_padding(key, 256)
for i in range(0, len(key), 32):
ext_key.append(key[i:i + 32])
if d_counter == 4:
ext_key[4] = ext_key[0]
ext_key[5] = ext_key[1]
ext_key[6] = ext_key[2]
ext_key[7] = ex... | The main task of the code is to decrypt input data using a key by processing it in 128-byte blocks with extended keys. It generates extended keys from the input key, decrypts each block iteratively, trims the result by removing leading elements until the first element equals 1, and returns the remaining decrypted data. | def decrypt(self, data, key):
tack_keys = extension_key(key)
all_tack_keys = create_K(tack_keys)
res = []
for i in range(0, len(data), 128):
res += self.decrypt_128(data[i:i + 128], all_tack_keys)
while res[0] != 1:
res = res[1:]
return res[1:] |
def on_accept(self):
clientsock, _ = self.server.accept()
self.input_list.append(clientsock)
def on_close(self, s):
# print("{0} has disconnected".format(s.getpeername()))
#remove objects from input_list
self.input_list.remove(s)
# close the connection with client
... | This code implements a server-side event loop using `select.select` to monitor multiple sockets for incoming connections and data. It appends the server socket to a list, continuously checks for ready sockets, accepts new connections via `on_accept()`, handles connection closures with `on_close()`, and processes receiv... | def main_loop(self):
self.input_list.append(self.server)
while True:
ss = select.select
inputready, _, _ = ss(self.input_list, [], [])
for s in inputready:
if s == self.server: # first connect
self.on_accept()
b... |
def _do_criterion(criterion, outputs, labels):
if _is_binary(outputs):
outputs = outputs.view(-1)
return criterion(outputs, labels * 1.0)
return criterion(outputs, labels)
def _do_prediction(outputs):
if _is_binary(outputs):
outputs = outputs.view(-1)
return (outputs > 0.5) *... | The function trains a neural network model using specified criterion and optimizer, iterating over training data for given epochs. It validates the model periodically (per epoch or steps), tracks training/validation loss/accuracy, updates a progress bar with metrics, saves checkpoints at each epoch, and returns a histo... | def train_model(
model: nn.Module,
criterion: nn.Module,
optimizer: optim.Optimizer,
trainloader: torch.utils.data.DataLoader,
validloader: torch.utils.data.DataLoader,
epochs: int,
device: str = 'cuda',
valid_every: Union[int, str] = 'epoch'
):
session = datetime.now().strftime('%Y-... |
def __pre_start(self) -> None:
"""Exexcutes at the start of the run method creating the saving directoy and saving the initial parameters in
config.json
"""
exclude_list = ('create_methods', 'mutate_methods', 'crossover_methods', 'last_improvement_time', 'gen',
'historical_fi... | This function generates genetic improvements by evolving a population of chromosomes through iterative selection, crossover, and local optimization. It yields the best candidate along with a termination flag, checking conditions like time limits, fitness thresholds, and stagnation. The process maintains historical fitn... | def __get_improvement(self) -> Tuple[bool, Chromosome]:
"""Generator of genetic improvements
Yields
------
Iterator[Tuple[bool, Chromosome]]
Best candidate achieved until the moment
"""
self.__pre_start()
p_time = 0
yield False, self.attribute... |
def __pre_start(self) -> None:
"""Exexcutes at the start of the run method creating the saving directoy and saving the initial parameters in
config.json
"""
exclude_list = ('create_methods', 'mutate_methods', 'crossover_methods', 'last_improvement_time', 'gen',
'historical_fi... | This method implements a multiprocessing-enabled genetic algorithm to evolve candidate solutions. It generates parent chromosomes, evaluates their fitness, and iteratively improves the population through selection, elitism, and local optimization. The algorithm yields the best candidate found so far, logs progress, and... | def __get_improvement_mp(self) -> Tuple[bool, Chromosome]:
"""Genetic improvements generator using multiprocessing
Yields
------
Iterator[Tuple[bool, Chromosome]]
Best candidate achieved until the moment
Raises
------
Exception
Elitism ra... |
def get_list(tup):
return list(map(get_list, tup)) if isinstance(tup, (list, tuple)) else tup
def parse_input(inputStr):
inputStr= eval(inputStr.replace(';', ','))
return inputStr
def start_id(start_node):
solution_node = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# solution_node = [[1, 2], [3, 4]]
open_stack = []
closed... | The main task of the code is to parse a semicolon-separated string into a nested list structure, create a Node object with this data, and initialize it using the start_id function, likely for processing or solving a puzzle-like problem with matrix or tuple-based input. | def main():
# val = input("Enter your value: ")
val = '((6; 1; 2); (7; 8; 3); (5; 4; 9))'
# val = '((3; 2); (4; 1))'
input_list = get_list(parse_input(val))
node = Node(input_list, [], 0, 0)
start_id(node) |
def getElement(rdfModule, element, isFinal=False):
try:
return getattr(rdfModule, element)
except AttributeError:
#return default values or crash if mandatory
if element=='processList':
print('The variable <{}> is mandatory in your analysis.py file, will exit'.format(element... | The function `runStages` manages analysis workflows by creating output directories, handling test/user-defined file modes, and executing batch/local processing. It processes predefined tasks, splits files into chunks, configures output paths, and runs analysis via `runLocal` or batch submission, ensuring directory stru... | def runStages(args, rdfModule, preprocess, analysisFile):
#check if outputDir exist and if not create it
outputDir = getElement(rdfModule,"outputDir")
if not os.path.exists(outputDir) and outputDir!='':
os.system("mkdir -p {}".format(outputDir))
#check if outputDir exist and if not create it
... |
def setup_run_parser(parser):
publicOptions = parser.add_argument_group('User options')
publicOptions.add_argument("pathToAnalysisScript", help="path to analysis script")
publicOptions.add_argument("--files-list", help="Specify input file to bypass the processList", default=[], nargs='+')
publicOptions.... | The main task of the code is to execute an analysis workflow by dynamically loading a specified analysis script, validating its existence, parsing command-line arguments, and invoking corresponding functions (e.g., `runStages`, `runFinal`, `runPlots`) based on the provided command or flags. It also handles argument con... | def run(mainparser, subparser=None):
"""
Set things in motion.
The two parser arguments are a hack to allow running this
both as `fccanalysis run` and `python config/FCCAnalysisRun.py`
For the latter case, both are the same (see below).
"""
if subparser:
print("===================se... |
def getTranscript(self):
if self.transcript:
return self.transcript
self.transcript = getRaw(self.id)
return self.transcript
def getTags(self):
if self.tags:
return self.tags
self.tags = []
for i in self.getEr():
self.tags.appe... | The code's main task is to compile and return a dictionary containing three key pieces of video data: the transcript, tags, and classes. It achieves this by calling three separate methods—getTranscript(), getTags(), and getClasses()—and aggregating their results into a structured format. This likely supports video anal... | def getVideoForElastic(self):
return {"transcript": self.getTranscript(),
"tags": self.getTags(),
"classes": self.getClasses()
} |
def initialise(db):
cursor = db.cursor()
# Blocks
cursor.execute('''CREATE TABLE IF NOT EXISTS blocks(
block_index INTEGER UNIQUE,
block_hash TEXT UNIQUE,
block_time INTEGER,
PRIMARY KEY (block_index, block_hash))
... | The main task of the code is to reparse all transactions atomically, optionally rolling back to a specified block. It drops existing tables, cleans consensus hashes if mismatched with checkpoints, deletes data beyond the given block index, reprocesses blocks/transactions, checks asset conservation, and updates the data... | def reparse (db, block_index=None, quiet=False):
"""Reparse all transactions (atomically). If block_index is set, rollback
to the end of that block.
"""
logging.warning('Status: Reparsing all transactions.')
cursor = db.cursor()
with db:
# Delete all of the results of parsing.
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.