dependency stringlengths 77 854k | docstring stringlengths 0 4.39k | main stringlengths 29 215k |
|---|---|---|
def Profile(motifs):
profile = {}
k = len(motifs[0])
for symbol in "ACGT":
profile[symbol] = []
for j in range(k):
profile[symbol].append(0)
t = len(motifs)
for i in range(t):
for j in range(k):
symbol = motifs[i][j]
profile[symbol][j] += ... | The main task of the code is to implement the Greedy Motif Search algorithm, which identifies the best set of k-length motifs across t DNA strings by iteratively selecting the most probable k-mers based on a profile matrix. It initializes with the first k-mers of each string, then iterates through all possible starting... | def GreedyMotifSearch(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for m in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][m:m+k])
for j in range(1, t):
P = Profile(Motifs[0:j])
Motifs.append(Prof... |
def ProfileWithPseudocounts(motifs):
k = len(motifs[0])
profile = CountWithPseudocounts(motifs)
for i in range(k):
n_symbol = 0
for symbol in "ACGT":
n_symbol += profile[symbol][i]
for symbol in "ACGT":
profile[symbol][i] = profile[symbol][i]/n_symbol
retu... | The function performs greedy motif search with pseudocounts to find the best set of k-length motifs in t DNA strings. It initializes best motifs, iterates through all possible starting positions in the first DNA string, constructs motifs using pseudocount-based profiles, and updates the best motifs if the current score... | def GreedyMotifSearchWithPseudocounts(Dna, k, t):
BestMotifs = []
for i in range(0, t):
BestMotifs.append(Dna[i][0:k])
n = len(Dna[0])
for m in range(n-k+1):
Motifs = []
Motifs.append(Dna[0][m:m+k])
for j in range(1, t):
P = ProfileWithPseudocounts(Motifs[0:j]... |
def RandomMotifs(Dna, k, t):
motifs = []
for i in range(t):
start = random.randint(0, len(Dna[i]) - k)
motif = Dna[i][start:start + k]
motifs.append(motif)
return motifs
def ProfileWithPseudocounts(motifs):
k = len(motifs[0])
profile = CountWithPseudocounts(motifs)
for i ... | The GibbsSampler function iteratively refines a set of motifs from DNA sequences by randomly selecting a motif, generating a profile from the remaining motifs, and replacing the selected motif with a new one generated from the profile. It repeats this process N times, updating the best motifs if the current set has a l... | def GibbsSampler(Dna, k, t, N):
motifs = RandomMotifs(Dna, k, t)
best_motifs = motifs
for j in range(N):
i = random.randint(0, t-1)
motifs_i = motifs[:i] + motifs[i+1:]
profile = ProfileWithPseudocounts(motifs_i)
motifs[i] = ProfileGeneratedString(Dna[i], profile, k)
... |
def RandomMotifs(Dna, k, t):
motifs = []
for i in range(t):
start = random.randint(0, len(Dna[i]) - k)
motif = Dna[i][start:start + k]
motifs.append(motif)
return motifs
def ProfileWithPseudocounts(motifs):
k = len(motifs[0])
profile = CountWithPseudocounts(motifs)
for i ... | This function performs randomized motif search to find the best set of k-length motifs in t DNA sequences. It iteratively generates random motifs, creates a profile with pseudocounts, and identifies new motifs using the profile. If the new motifs have a lower score than the current best, they replace the best. The proc... | def RandomizedMotifSearch(Dna, k, t):
M = RandomMotifs(Dna, k, t)
BestMotifs = M
while True:
Profile = ProfileWithPseudocounts(M)
M = Motifs(Profile, Dna)
if Score(M) < Score(BestMotifs):
BestMotifs = M
else:
return BestMotifs |
def convert_data_to_int32(data, precision=None):
"""
Converts the input data to int32 type, optionally scaling it by a specified factor.
Parameters
----------
data : array-like
The input data.
precision : int, optional
The scaling factor (expressed as... | The main task of the code is to write data to a session, handling new channels or appending to existing ones while managing timestamps, data formatting, and fragmentation. It scales data to int32 using precision, validates time intervals, and splits data into intervals to skip NaN gaps if enabled. The function creates ... | def write_data(self, data_write, channel, start_uutc, sampling_freq, end_uutc=None, precision=None, new_segment=False,
discont_handler=True, reload_metadata=True):
"""
General method for writing any data to the session. Method handles new channel data or appending to existing chan... |
def clear_screen():
os.system("cls")
def display_search_result(result):
index = 1
print("** Address Book **".rjust(53)+"\n"+"No.".rjust(5)+"|"+"Name".rjust(20)+"|"+"Address".rjust(20)+ "|"+"Contact".rjust(20)+"|"+"Email".rjust(20)+"")
for entry in result:
print("\033[1;37;40m{}|{}|{}|{}|{}".form... | The code provides a menu-driven interface for managing an address book, allowing users to display, add, update, or delete contacts. It loops until the user exits via the transaction_selection() function, which checks for continuation. Each menu option triggers corresponding functions (e.g., add_contact, delete_contact)... | def display_menu():
clear_screen()
while True:
print("\nAddress Book")
print("\t1. Display Address/es")
print("\t2. Add New Address")
print("\t3. Update Address")
print("\t4. Delete Address")
selection = input("\nEnter Selection: ")
if selection == "1":
... |
def load_heatmap(self, img1, img2, model, embeddings):
heatmap = super(SaliencyDataLoader, self).load_heatmap(img1, img2, model, embeddings)
if heatmap is None:
heatmap = self.compute_heatmap(model, img1, img2, embeddings)
if self.method == 'mask' and not self.fixed_ref:
... | The code evaluates a model's performance on insert/delete tasks using cosine similarity between embeddings of image pairs. It computes normalized similarity scores for thresholds, then calculates AUC (Area Under Curve) for insert and delete tasks using sklearn's auc function, returning these metrics as results. The pro... | def test(self, model, embeddings):
n_thresh = len(self.all_thresh)
delete_scores = np.zeros((len(self.pairs), n_thresh), np.float32)
insert_scores = np.zeros_like(delete_scores)
if self.fixed_ref:
ref_type = 'fixed'
else:
ref_type = 'var'
for i, (... |
def FindOwners(ngb, phi,r):
"""Determines the 'owner' of each particle given the neighbour list, gravitational potential, and neighbor distances"""
i = 0
owners = -np.ones(len(phi), dtype=np.int32)
for i in xrange(len(phi)):
Owner(i, ngb, owners, phi, r)
return owners
def ComputePotenti... | The code identifies and analyzes particle clusters from a simulation, determining their bound/unbound status. It reads particle data, filters based on criteria, computes neighbors, assigns clusters, and evaluates boundness via potential and velocity analysis. Results include cluster properties (mass, center, radius) an... | def ComputeClusters(filename, options):
brute_force_N = int(float(options["--brute_force_N"]) + 0.5)
cluster_ngb = int(float(options["--cluster_ngb"]) + 0.5)
min_cluster_size = int(float(options["--cluster_ngb"]) + 0.5)
softening = float(options["--softening"])
G = float(options["--G"])
boxsize ... |
def flood_for_threshold_nonrecursive(x, y, threshold, visited):
visited = set()
points_to_visit = {(x, y)}
return_list = set()
visits = 0
while len(points_to_visit) > 0:
px, py = points_to_visit.pop()
if (px, py) in visited:
continue
visits += 1
if visits... | The code generates a mask for a gravestone in an image by identifying regions with colors similar to a reference pixel at given coordinates. It uses flood filling with a threshold, trims the detected region's border, and then expands it to create a final mask for segmentation or highlighting the gravestone area. | def get_gravestone_mask(img, coord):
x, y = coord
reference_color = img[y, x]
points = flood_for_threshold_nonrecursive(
x, y, lambda pixel: color_threshold(img, pixel, reference_color), set()
)
remove_width = int(len(points) / 75)
thin_border = remove_border(points, remove_width)
... |
def create_pyramid(img, scale):
# Calculate in how many levels each dimension can be divided into
width_dim = int(math.log(img.shape[0],scale))
height_dim = int(math.log(img.shape[1],scale))
# The number of levels in the image will be the minimum of width, height
num_images = min(width_dim,height_dim)
# Initializ... | The code aligns red, green, and blue image channels by creating multiscale pyramids and aligning them to the green channel using a heuristic (NSSD). It crops borders to remove misaligned edges and stacks the aligned channels into a single image, returning the result. | def align_channels(r, g, b, crop_percentage = 0.25, displacement = 30, scale = 2):
# Defines the heuristic to use
heuristic = calculate_NSSD
# Create the pyramids
assert isinstance(crop_percentage, float)
assert isinstance(displacement, int)
assert isinstance(scale, int)
print ("Creating red image pyramid...")
... |
def mapped_data(trainingSet, top_word_list):
'''will map the output from makedict to every mail's feature vector'''
'''trainingSet = myDict'''
return list(map(lambda x: [feature_vector(word_list(x[0]), top_word_list),x[1]], trainingSet))
def feature_vector(mail_words, top_word_list):
'''top_word_list is... | The function `getNeighbors` computes the k nearest neighbors of a test email in a training set by calculating Euclidean distances between feature vectors derived from top words. It maps training data and the test email into feature vectors, calculates distances, sorts training examples by proximity, and returns the top... | def getNeighbors(trainingSet, testMail, k, top_word_list):
distances = []
i=0
a = mapped_data(trainingSet, top_word_list)
b = feature_vector(word_list(testMail.tolist()[0]), top_word_list)
for x in range(len(trainingSet)):
dist = euclideanDistance(b, a[x][0])
# print(len(trainingSet),... |
def loadDataset(filename, split, trainingSet=[], testSet=[]):
'''read the file and split the data into training and test'''
data = pd.read_csv(filename)
data1 = np.array(data)
random.shuffle(data1)
data2 = data1[2000:4000]
for x in range(len(data2)):
if random.random() < split:
... | The main task of the code is to implement a Naive Bayes classifier for email classification. It loads a dataset from "emails.csv", splits it into training (80%) and test sets, constructs a feature dictionary from the training data, computes probability tables, and evaluates classification accuracy on the test set using... | def main():
trainingSet = []
testSet = []
split = 0.80
loadDataset("emails.csv", split, trainingSet, testSet)
#print(len(trainingSet))
#print(len(testSet))
dictionary_part = makeDict(trainingSet)
#print(len(dictionary_part))
dictionary_final = all_words_unique(dictionary_part)
#p... |
def loadDataset(filename, split, trainingSet=[], testSet=[]):
'''read the file and split the data into training and test'''
data = pd.read_csv(filename)
data1 = np.array(data)
random.shuffle(data1)
data2 = data1[2000:3500]
for x in range(len(data2)):
if random.random() < split:
... | The code implements a k-Nearest Neighbors (KNN) classifier to classify emails as spam or ham. It splits the dataset into training (70%) and test sets, extracts frequency-based features from labeled emails, and predicts classifications using top-ranked words. Accuracy is calculated by comparing predicted labels to actua... | def main():
trainingSet=[]
testSet=[]
split = 0.7
loadDataset("emails.csv", split, trainingSet, testSet)
print('Train set: ' + repr(len(trainingSet)))
print('Test set: ' + repr(len(testSet)))
predictions=[]
table = makeDict(trainingSet)
#print(table)
b = all_words_unique(table)
... |
def display_board(board):
print("---------------------------------------")
print("Game Board:")
max_row_index = (len(board) // 7) - 1
# Cast to string:
board_in_strings = [str(element) for element in board]
# Format the board list for console output
# Spit the board into rows, delimited by s... | This function handles a player's turn in a game by displaying the board, prompting the player's move, applying the move to the board, checking for a victory condition, and exiting if victory is achieved. If not, it returns the updated board for the next turn. | def handle_player_turn(board, turn):
display_board(board)
print(f"Player {turn}'s Turn!")
column, is_pop = get_move(board, turn)
new_board = apply_move(board, turn, column, is_pop)
victory_status = check_victory(new_board, turn)
if victory_status:
display_victory_message(new_board, victo... |
def get_valid_response(question):
# helper function for handling yes/no questions
valid_answers = ("y", "yes", "true", "n", "no", "false")
while True:
answer = input(question)
if answer.lower() in valid_answers:
return answer
print("That is not a valid response! Please tr... | The code sets up a Connect Four-style game, allowing users to configure the board size and choose to play against a computer opponent. It initializes the game board, handles player turns, and includes computer move logic based on difficulty. The game loop alternates between Player 1 and Player 2 (or the computer), chec... | def menu():
# Set-up empty game board
config_rows = get_valid_response("Would you like to change the size of the game board (default 6) ? (y/n) ")
number_of_rows = get_rows() if parse_as_boolean(config_rows) else 6
board = [0] * (7 * number_of_rows)
# Ask for game type
game_type = get_valid_res... |
def move_cursor(self):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
for cell in self.cells_list:
mouse_on_cell = cell.mouse_on_cell(cell, mouse)
if mouse_on_cell:
if click[0] == 1:
self.__set_cursor(cell)
def exit_... | This function handles user events in a game, checking for quit signals, mouse clicks on buttons/cells, and keyboard inputs. It updates cell values, manages cursor movement, checks game completion, updates the display, and tracks game time. The loop continues until the game ends, processing events and rendering the game... | def handle_events(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
if event.type == pygame.MOUSEBUTTONDOWN:
for button in self.__buttons_list:
mouse_is_presse... |
def number_of_0(self, table):
number_of_0 = 0
for row in table:
for number in row:
if number == 0:
number_of_0 += 1
return number_of_0
def number_of_possible_digits(self, table, row, col, digits):
possible_digits = self.possible_digits(tabl... | This code checks if a Sudoku puzzle has only one valid solution by iteratively filling cells with the fewest possible digits. If any cell has more than one possible digit during this process, it returns False, indicating multiple solutions. If all cells are uniquely filled, it returns True, confirming a single solution... | def check_if_only_one_solution(self, table, row, col):
table[row][col] = 0
digits = [i for i in range(1, 10)]
table_row = [i for i in range(len(table))]
table_col = [i for i in range(len(table[0]))]
while self.number_of_0(table) > 0:
cells_tuples = []
for ... |
def set_level():
path = "settings.txt"
if os.path.isfile(path):
file = open(path, "r")
file_list = [line.strip() for line in file.readlines()]
level = int(file_list[1])
else:
level = 1
return level
def solved_table(self):
finish = F... | The code initializes a puzzle or game with difficulty levels. It sets the number of digits to change based on the level (15-20 for level 1, 30-35 for level 2, 45-50 for level 3), and prepares solved and unsolved tables for the puzzle. | def __init__(self):
self.level = self.set_level()
self.solved = self.solved_table()
if self.level == 1:
self.number_of_digits_to_change = random.randint(15, 20)
if self.level == 2:
self.number_of_digits_to_change = random.randint(30, 35)
if self.level == 3... |
def process_v2(df_var2, df_cov2, read_depth_thresh, resource_dir):
agg_v2 = aggregate_data(df_var2, df_cov2)
agg_v2['src'] = 'v2'
add_filter_flag_col(agg_v2, set(['InbreedingCoeff', 'RF', 'AC0']))
add_read_depth_col(agg_v2, read_depth_thresh)
variants = [var_name_to_obj(v) for v in agg_v2['var_nam... | The function combines and processes variant data from two sources (v2 and v3) by applying scoring algorithms to determine evidence codes, then merges results into a sorted dataframe. It uses helper functions to process data, assign evidence codes, and finalize output, returning a consolidated, sorted dataset of variant... | def extract_variant_scoring_data(df_cov2, df_cov3, df_var2, df_var3, read_depth_thresh, resource_dir):
agg_v2 = process_v2(df_var2, df_cov2, read_depth_thresh, resource_dir)
agg_v3 = process_v3(df_var3, df_cov3, read_depth_thresh)
df_overall = pd.concat([agg_v2, agg_v3]).reset_index(drop=True)
# runni... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--input", default="built_final.tsv",
help="Input file with variant data")
parser.add_argument("-o", "--output", default="built_with_popfreq.tsv",
help="Output file with new columns... | The main task of the code is to process genetic variant data from a tab-delimited input file, leveraging preloaded coverage data (df_cov2 and df_cov3) to analyze each variant, and then output the processed results to a specified file. The workflow involves parsing command-line arguments, reading input/output files, and... | def main():
args = parse_args()
print(args)
#cfg_df = config.load_config(gene_config_path)
df_cov2 = pd.read_parquet(args.data_dir + '/df_cov_v2.parquet')
df_cov3 = pd.read_parquet(args.data_dir + '/df_cov_v3.parquet')
input_file = csv.DictReader(open(args.input), delimiter = "\t")
output_fi... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--all_variants_vcf",
help="VCF with all variants to be scored")
parser.add_argument("-b", "--batch_size", default="1000",
help="Max batch size for spliceAI runs")
parser.add_ar... | The code processes variants in batches using SpliceAI, iteratively scoring unscored variants from an input VCF, merging results with previously scored variants, and repeating until all variants are scored. It manages temporary files, updates scored variants iteratively, and cleans up temporary files post-processing. | def main():
args = parse_args()
all_variants_scored = False
print(args.temp_dir)
scored_vcf = args.temp_dir + "/scored_variants.vcf"
unscored_vcf = args.temp_dir + "/unscored_variants.vcf"
newly_scored_vcf = args.temp_dir + "/newly_score_variants.vcf"
shutil.copy2(args.scored_variants_vcf, s... |
def time_to_coord(time):
return round(time * 30)
def create_layers(reg, width, start=0):
create_platforms(reg)
create_repeater(reg, width, start)
create_firstlayer(reg, width, start)
create_toplayer(reg, start)
create_redstonelamps(reg, width, start)
def create_start(reg, width, start=0):
re... | This function converts a MIDI file into a schematic NBT file for Minecraft. It processes the MIDI audio, generates structural layers, start positions, and note blocks within a defined width and offset, then exports the result as an NBT file at the specified path. | def generate_schematic(midi_path, target_path, width=7, start=5):
audio_file = split_midi(midi_path)
reg = Region(width*2+1, 8, time_to_coord(audio_file.get_end_time() + 1))
create_layers(reg, width, start)
create_start(reg, width, start)
create_note_blocks(reg, width, audio_file, start)
nbt_... |
def checkLootInterface(lastinterface):
if time.time() - lastinterface > intervals["lootInterface"]:
rs() # sleep for a random amount of ms
print('opened loot interface')
keyboard.press(lootInterfaceKey)
last["interface"] = time.time()
return True
else:
return Fals... | The code initializes a PyQt GUI application with a window titled "Grief will be banned in Modern," sets its geometry, and runs a loop to execute game-related tasks like checking loot interfaces, inventory management, and aggro handling until interrupted by a keyboard signal. | def main():
startTime = time.time()
runTime = time.time - time.time()
app = QApplication(sys.argv)
widget = QWidget()
grid = QGridLayout()
widget.setLayout(grid)
widget.setGeometry(1200, 500, 500, 500)
widget.setWindowTitle("Grief will be banned in Modern")
try:
while RU... |
def get_log():
s = Session()
base_url = 'http://localhost:21122/'
endpoint = 'monitoring/infrastructure/using/summary/1'
r = s.get(base_url + endpoint)
return r.text
def print_to_file(data_to_print: dict):
with open('out.txt', 'w') as f:
with redirect_stdout(f):
print('|Resou... | The main task of the code is to retrieve log data using `get_log()`, parse it with the `parser()` function, and save the processed output to a file via `print_to_file()`. This workflow automates log retrieval, processing, and storage in a structured format. | def main():
input_data = get_log()
print_to_file(parser(input_data)) |
def pop(self):
if self._size > 0:
r = self._arr[self._size-1]
self._arr[self._size-1] = 0
self._size -= 1
self._sizedowncheck()
return r
return None
def isEmpty(self):
if self._size == 0:
return True
return False
def... | This code deletes an element at a specified index from a dynamic array. It handles edge cases like out-of-bounds indices and empty lists. If the index is the last element, it uses `pop()`. Otherwise, it creates a new array, copies elements before and after the index, reduces the size, and replaces the original array. T... | def delete(self, index):
if index < 0:
raise Exception("Out of bounds.")
#if index is end of list, just pop
if index == self._size-1:
return self.pop()
if self.isEmpty():
return None
newarr = self.makearray(self._capacity)
... |
def _checknumber(self, num):
if not (isinstance(num, float) or isinstance(num, int)):
raise Exception("This vector implementation only supports numeric data")
def push(self, val):
self._checknumber(val)
#Set last index the val
self._arr[self._size] = val
self._size +=... | This code inserts a value at a specified index in a dynamic array. It validates the index, resizes the array if necessary, copies existing elements up to the index, inserts the new value, shifts subsequent elements, and updates the array and size. | def insert(self, index, val):
self._checknumber(val)
if index < 0:
raise Exception("Out of bounds.")
#if index is end of list, greater than size, just push
if index >= self._size:
self.push(val)
return
# Determine necessary size of d... |
def load_formatters(self, formatters: list[str]) -> list[ContentFormatter]:
"""Load all the configured formatters."""
return [self.load_formatter(formatter) for formatter in formatters]
def load_generators(
self: "PackageInfoApplicationPlugin",
generators: dict[str, str],
) -> dict[s... | The main task of this code is to initialize a plugin for generating package information based on `pyproject.toml` configurations. It sets up directories, loads formatters and templates, processes plugin-specific settings like `patch-build-formats`, and parses property configurations for generating dynamic package metad... | def initialise(self: "PackageInfoApplicationPlugin") -> None:
"""Initialises the plugin based on pyproject.toml configuration."""
if self.initialized:
return
self.pyproject_file_dir = (
self.application.poetry.pyproject.file.path.parent
)
self.default_sr... |
def _determine_package_info_path(
self,
builder_instance: BaseBuilder,
out: IO,
) -> Path | None:
for include in builder_instance._module.includes: # noqa: SLF001
include.refresh()
if (
isinstance(include, PackageInclude)
and ... | This function processes a given builder type (WheelBuilder or SdistBuilder) to update package information in distribution files. It checks if the builder's format matches allowed formats (or "all"), creates a builder instance, determines the package info file path, and updates the corresponding wheel or source distribu... | def handle_builder_type(
self: "PackageInfoApplicationPlugin",
builder_type: type[Builder],
out: IO,
) -> None:
"""Handle and processing for the given builder type."""
format_all = "all" in self.patch_build_formats
if issubclass(builder_type, WheelBuilder) and (
... |
def initialise(self: "PackageInfoApplicationPlugin") -> None:
"""Initialises the plugin based on pyproject.toml configuration."""
if self.initialized:
return
self.pyproject_file_dir = (
self.application.poetry.pyproject.file.path.parent
)
self.default_sr... | This method handles the termination event by initializing the plugin, checking for available build formats, and processing each builder type to execute build-related tasks. It triggers actions for each builder type if patch_build_formats is non-empty, ensuring proper cleanup or post-processing during the build command'... | def on_terminate(
self: "PackageInfoApplicationPlugin",
command: BuildCommand,
out: IO,
) -> None:
"""
Event handler for when an event is triggered.
Event handler for when an event is triggered on the poetry (cleo) event
dispatcher.
:param event: The ... |
def tkinter_input_validation(hearthpwn_username, hearthpwn_card_collection_url, file_path):
throw_error = False
invalid_chars = ['\\', '/', ':', '?', '|', '<', '>', '"', '*']
if not hearthpwn_username:
activate_error_dialog_box("The username field is required.")
return True
if not fil... | The main task of the code is to handle a button click event by collecting user input (file path and Hearthpwn username), validating it, generating a Hearthstone card collection spreadsheet, saving it as an Excel file (.xlsx), and opening the file location with error handling for permission issues. It ensures proper fil... | def on_button_click():
file_path = file_path_to_save_entry.get()
hearthpwn_username = username_entry.get()
root.destroy()
hearthpwn_card_collection_url = "https://www.hearthpwn.com/members/{}/collection".format(hearthpwn_username)
# VALIDATION
throw_error = tkinter_input... |
def load_dftb(self) -> None:
if os.path.exists("Data/dftb.pkl"):
self.dftb_data = pd.read_pickle("Data/dftb.pkl")
else:
self.extract_data_dftb()
self.dftb_data.to_pickle("Data/dftb.pkl")
def extract_data_g16(self) -> None:
generator = os.walk(self.data_locati... | The code creates a dataset by merging G16 and DFTB data based on SMILES strings, then converts the merged data into graph representations for molecular analysis. | def create_dataset(self) -> None:
self.data_location = os.getcwd() + "/Data/"
self.data_location_dftb = self.data_location + "slurm_ready/"
self.data_location_g16 = self.data_location + "G16_zip/"
# Only elements in the dataset
self.elements = ["H", "C", "N", "O", "F"]
... |
def train(
self,
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor,]:
self.optimizer.zero_grad()
self.model.train()
for batch in self.train_loader:
(
loss,
preds,
Y_matrices,
n_o... | This code trains a machine learning model over multiple epochs, tracking training, test, and validation losses. It uses early stopping based on test loss and saves predictions. The function returns DataFrames containing loss values for each epoch, facilitating performance analysis and model evaluation. | def train_model(
self,
) -> Tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame, pd.DataFrame]:
losses_train = []
losses_test = []
losses_valid = []
for epoch in (
pbar := tqdm(
range(self.epochs), total=self.epochs, desc="Training", leave=False
... |
def readBoard(file):
global BOARD
with open(file, 'r') as infile:
for line in infile:
if line != '\n':
row = [int(num) for num in line.split()]
BOARD.append(row)
def solvedSudoku():
global BOARD
empty = []
if solved(empty):
return True
... | The main task of the code is to solve a Sudoku puzzle from a provided file. It validates input arguments, reads the Sudoku board, checks if it can be solved, and prints the result (solved or unsolvable) along with the board. The code also handles file-related errors like missing files or directories, displaying appropr... | def main():
try:
if len(sys.argv) < 2:
print("\033[91mARGUMENT COUNT ERROR\n\033[0mUsage: python3 solution.py [filename]")
sys.exit(1)
readBoard(sys.argv[1])
if solvedSudoku():
print('\033[92mSOLVED:\033[0m')
else:
... |
def get_dns_value():
global dns_value
global is_alias
if record.get('ResourceRecords'):
dns_value=[value['Value'] for value in record['ResourceRecords'] ]
dns_value=" , ".join(dns_value)
is_alias=False
elif record.get('AliasTarget'):
if re... | The function retrieves subdomains from an AWS Route53 hosted zone by paginating through resource record sets. It filters records based on user-specified DNS types or exclusion patterns, processes each subdomain (e.g., checking DNS values, certificates, and dangling status), logs events, and appends data to an Excel she... | def get_subdomains(zone_id):
subdomains= []
try:
paginate_resource_record_sets = route53.get_paginator('list_resource_record_sets')
for record_response in paginate_resource_record_sets.paginate(
HostedZoneId = zone_id,
MaxItems='300'
... |
def load_riding_data(year):
with fiona.open('data/' + str(year) + '/districts/districts.shp') as ridings_file_2018:
ridings_2018 = dict()
riding_index = rtree.index.Index()
for riding_record in ridings_file_2018:
riding = Riding()
riding.name = riding_record['properti... | The function processes election data for a specified year by loading riding and candidate data, retrieving historical poll results, assigning poll and riding weights, calculating election outcomes using population vote data, and returning the 2018 riding dataset. It handles year-specific data loading and result calcula... | def project(year):
ridings_2018, riding_index = load_riding_data(2018)
ridings, _ = load_riding_data(year)
print('Riding data loaded.')
candidates = load_candidate_list(year)
print('Candidate list loaded.')
if year == '2014':
results = load_poll_results_2014(ridings, candidates)
elif... |
def generate_bins(bins):
angle_bins = np.zeros(bins)
interval = 2 * np.pi / bins
for i in range(1, bins):
angle_bins[i] = i * interval
angle_bins += interval / 2 # center of bins
return angle_bins
def get_objects(self, ids):
"""
Get objects parameter from labels, like dimens... | This code initializes a dataset processor for object detection, setting up paths for images, labels, and calibration files. It loads a global calibration matrix, generates angular bins for orientation analysis, and organizes object labels by image ID. The class prepares average dimensions for object classes, processes ... | def __init__(self, path, bins=2, overlap=0.1):
# dataset directory
self.top_img_path = path + '/image_2/'
self.top_label_path = path + '/label_2/'
# TODO: remove top calib
self.top_calib_path = path + '/calib/'
# calibration file
# using global calib file
... |
def checkIfSQL(node):
if node and 'SELECT' in node:
return True
return False
def parseNestedSQL(sql):
pk = None
if sql.startswith('(') and sql.endswith(')'):
sql = sql[1:-1]
print(f" Nested SQL : {sql}")
temp = ''
temp += parseSelect(sql,pk)
temp += parseFrom(sql)
... | This function processes a SQL WHERE clause node by parsing it into column name, operator, value, and nested SQL status. It identifies operators from a dictionary, splits the node into components, checks if the value is nested SQL, and returns a structured WhereNode object with parsed elements and a flag indicating nest... | def processEachWhereNodeToken(whereNode):
isNested = False
colName,whereOps,sqlOrValue,condOps = None, None, None, None
for op in whereOpsDict.keys():
val = ' '+op.upper()+' '
if val in whereNode:
splitList = whereNode.split(val)
colName = splitList[0].strip()
... |
def getQuery(sqlTextNode):
return sqlTextNode['query']
def getdbID(sqlTextNode):
return sqlTextNode['db_id']
def getQuestionTokens(sqlTextNode):
return sqlTextNode['question_toks']
def getTablesInfo(sqlTextInfo):
queryTokensList = getQueryTokens(sqlTextInfo)
tableNames = []
for ind, each in enumerate(... | The code generates training data for a model by extracting components from SQL text, constructing semi-structured representations of the question, schema, and SQL query, and packaging them into a dictionary with input-output pairs for training. It handles schema absence and assigns an ID to each training example. | def buildTrainingData(sqlTextInfo, count):
sqlQuery = getQuery(sqlTextInfo)
databaseId = getdbID(sqlTextInfo)
questionTokensList = getQuestionTokens(sqlTextInfo)
tableNamesList = getTablesInfo(sqlTextInfo)
print(f'SQL Query : {sqlQuery}')
semiStructuredSQL = buildSemiStructuredSQL(sqlTextInfo, sqlQ... |
def find_c_half(U):
global nx, v0, delta_t, delta_x, gamma, theta, c_half_L, c_half_R, c_int, F, F_half, U_der, UL, UR, FL, FR
c_int[:, 0] = U[:, 0]
c_int[:, 1] = (gamma-1)*U[:, 0]*(U[:, 2]/U[:, 0]-0.5*(U[:, 1]/U[:, 0])**2)
c_int[:, 2] = U[:, 1]/U[:, 0]
diff = differences(c_int)
diff2 = differen... | This function evolves the state variable U using a multi-stage numerical integration scheme. It computes intermediate states (U1, U2) by evaluating fluxes, derivatives, and applying weighted averages to update U. The process involves calculating half-space fluxes (F_half), spatial derivatives (U_der), and combining the... | def evolve(i):
global U, nx, v0, delta_t, gamma, theta, c_half_L, c_half_R, c_int, F, U_der, UL, UR, FL, FR
cL, cR = find_c_half(U)
UL, UR, FL, FR = c_to_ULR_FLR(cL,cR)
F_half = find_f_half(UL, UR, FL, FR)
U_der = find_u_der(F_half,delta_x)
U1 = find_u(U,U_der,delta_t, ii=i)
cL, cR = find_... |
def find(self, value):
"""
Helper function that sets up the find_rec method to find a node.
"""
return self.find_rec(value, self.root)
def is_empty(self) -> bool:
"""
This method return True if the tree is empty, otherwise the method should return False.
"""
... | This method removes a specified value from an AVL tree by locating the node, handling cases based on its children (leaf, one child, two children), updating pointers, and rebalancing the tree upwards to maintain AVL properties. It returns True if the value is successfully removed, False otherwise. | def remove(self, value: object) -> bool:
"""
This method should remove the value from the AVL tree.
The method must return True if the value is removed from the AVL Tree, otherwise return False.
"""
removeNode = self.find(value)
if removeNode is None:
return ... |
def generate_fake_samples(g_model, latent_dim, n_samples):
x_input = generate_latent_input(latent_dim, n_samples)
X = g_model.predict(x_input)
y = np.zeros((n_samples, 1))
return X, y
def generate_latent_input(latent_dim, n_samples):
x_input = np.random.randn(latent_dim * n_samples)
x_input = x_... | This code trains a GAN by alternating between training the discriminator on real/fake data and the generator via the GAN model. It uses label smoothing, batches data, and periodically prints losses and evaluates performance. | def train(g_model, d_model, gan_model, x_train, latent_dim, epochs=200, batch_size=128):
smooth = 0.1
y_real = np.ones((batch_size,1))*(1-smooth)
y_gan = np.ones((batch_size, 1))
bat_per_epo = x_train.shape[0] // batch_size
for i in range(epochs + 1):
for j in range(bat_per_epo):
... |
def ReadsPerGene2Matrix( count_files, count_file_type='STAR', experiment_type='unstranded'):
"""
count_file_type: 'STAR', 'salmon', 'featurecounts'
which aligner or program was used to generate counts files.
return_type:
column = each sample has counts in a separate column, like this:
gene,sa... | The main task of the code is to process RNA-seq count files (STAR/featurecounts/salmon) by generating a gene expression matrix, filtering low-count genes, performing PCA for dimensionality reduction, creating scatter plots, and compiling all visualizations into an interactive HTML report. It handles input parsing, defa... | def run_expressionqc( arg_list ):
"""
Parameters:
-i <input_count_files>
-groups <groups>
-o <output_dir>
-type <STAR or featurecounts or salmon>
-name <base name for plots> : default expressionqc
"""
print('ARG LIST: {}'.format(str(arg_list)))
input_args = module_utils.getArgume... |
def _gamma_mean_initializer(points, weights, initial):
if initial == 'mean':
return mean(points, weights)
elif initial == 'median':
return median(points, weights)
def std(points, weights=None):
mu = mean(points, weights)
return np.sqrt(mean(np.subtract(points, mu)**2, weights))
def ext_r... | The function computes a weighted mean (gamma mean) of input points with iterative updates, incorporating regularization via the gamma parameter. It adjusts the mean (mu_hat) and standard deviation (sigma_hat) using exponential damping weights derived from point distances. Outliers can be removed, and iterations continu... | def gamma_mean_1D(points, weights=None, history_points=None, gamma = 0.1, max_iter=10, tol = 1e-7, remove=False, beta=0.1, initial = 'mean'):
"""
We use element-wise mu & sigma,
equal to diagnol Sigma,
gamma_mean
"""
if history_points is None:
mu_hat = _gamma_mean_initializer(points, wei... |
def _gamma_mean_initializer(points, weights, initial):
if initial == 'mean':
return mean(points, weights)
elif initial == 'median':
return median(points, weights)
def std(points, weights=None):
mu = mean(points, weights)
return np.sqrt(mean(np.subtract(points, mu)**2, weights))
def ext_r... | The code computes a weighted mean of input points using a gamma parameter to emphasize certain data points, iteratively updating the mean until convergence. It adjusts for scale via tolerance, optionally removes outliers, and uses either current points or historical data based on input. The result is a refined mean est... | def simple_gamma_mean(points, weights=None, history_points=None, gamma = 0.1, max_iter=10, tol = 1e-7, remove=False, beta=0.1, initial = 'mean'):
"""
Do not consider cov inverse
"""
if history_points is None:
mu_hat = _gamma_mean_initializer(points, weights, initial)
sigma_hat = std(poin... |
def _gamma_mean_initializer(points, weights, initial):
if initial == 'mean':
return mean(points, weights)
elif initial == 'median':
return median(points, weights)
def cov(points, weights=None):
"""
points.shape = (m, p=[...])
cov.shape should be (p, p)
"""
if weights is None:... | The function `gamma_mean_2D` computes a weighted mean and covariance of input points using a gamma parameter, iteratively updating estimates. It handles dimensionality reduction (via PCA or other methods) and adjusts for sparse weights. The gamma parameter influences a kernel-like weighting in updates, with convergence... | def gamma_mean_2D(points, weights=None, history_points=None, gamma = 0.1, max_iter=10, tol = 1e-7, dim_red=False, red_method='pca', initial = 'mean'):
"""
gamma_mean
"""
original_tol=tol
shape = np.shape(points[0])
points = [np.asarray(p).reshape([-1]) for p in points]
history_points = [np.a... |
def gamma_mean_1D(points, weights=None, history_points=None, gamma = 0.1, max_iter=10, tol = 1e-7, remove=False, beta=0.1, initial = 'mean'):
"""
We use element-wise mu & sigma,
equal to diagnol Sigma,
gamma_mean
"""
if history_points is None:
mu_hat = _gamma_mean_initializer(points, wei... | The function `gamma_mean` computes a weighted mean with gamma correction for given data points, adapting to 1D, 2D, or simple cases. It delegates to specialized sub-functions (`gamma_mean_1D`, `simple_gamma_mean`, `gamma_mean_2D`) based on the `compute` parameter. The gamma parameter adjusts the weighting, while `max_i... | def gamma_mean(points, weights=None, history_points=None, compute = "1D", gamma = 0.1, max_iter=10,
tol = 1e-7, remove=False, beta=0.1, dim_red=False, red_method='pca', initial = 'mean'):
if compute=="1D":
return gamma_mean_1D(points=points, weights=weights, history_points=None,
... |
def evaluate(ast):
if ast["op"] in ["constant", "variable"]:
return ast["n"]
match ast["op"]:
case "+": return evaluate(ast["a"]) + evaluate(ast["b"])
case "-": return evaluate(ast["a"]) - evaluate(ast["b"])
case "*": return evaluate(ast["a"]) * evaluate(... | This function solves an equation by isolating a variable. It identifies the constant and variable sides, adjusts the constant based on the variable's operation (+, -, *, /), and recursively simplifies until the equation is solved. | def solve(a, b):
constant, variable = (a, b) if a["op"] == "constant" else (b, a)
if variable["op"] == "variable":
return evaluate(constant)
constant_side, variable_side = ("a", "b") if simplify(variable["a"])["op"] == "constant" else ("b", "a")
if constant_side == "b":
... |
def _is_scope_subset(self, needle_scope, haystack_scope):
needle_scope = set(needle_scope.split()) if needle_scope else set()
haystack_scope = set(haystack_scope.split()) if haystack_scope else set()
return needle_scope <= haystack_scope
def is_token_expired(self, token_info):
return is_... | The main task of the code is to retrieve a cached authentication token from a file, validate its scope and expiration, and refresh it if necessary. It reads the token data, checks scope compatibility, and renews the token using a refresh token if expired, returning the valid token or `None` on failure. | def get_cached_token(self):
''' Gets a cached auth token
'''
token_info = None
if self.cache_path:
try:
f = open(self.cache_path)
token_info_string = f.read()
f.close()
token_info = json.loads(token_info_string)
... |
def get_channel_id(self):
"""
Get channel ID from input video ID or Videos URL or channel main page URL
:return: str: channel id
"""
if self._input_video_id:
res = self._input_video_response()
channel_id = res['items'][0]['snippet']['channelId']
... | The code's main task is to scrape YouTube video and channel data using an API key, validate inputs, retrieve video information, save data to MySQL and MongoDB databases, upload video streams to S3 if enabled, and return structured results including statuses and metadata. It handles errors for invalid inputs or database... | def scrape(self) -> Dict:
"""
Public method to start all data processing
:return:
"""
video_id = self._input_video_id
channel_id = self._input_channel_id
if (video_id == '' and channel_id == '') or API_KEY == '' or API_KEY is None:
return {'status': ... |
def get_tabix_path(vcf_path: PathType) -> Optional[Path]:
tbi_path = Path(vcf_path).parent / (Path(vcf_path).name + ".tbi")
if tbi_path.exists():
return tbi_path
else:
return None
def get_csi_path(vcf_path: PathType) -> Optional[Path]:
csi_path = Path(vcf_path).parent / (Path(vcf_path).n... | The function `partition_into_regions` divides a compressed VCF/BCF file into roughly equal parts using its `.tbi` or `.csi` index. It calculates genomic region strings to split the file based on either a specified number of parts (`num_parts`) or a target size per part (`target_part_size`). It retrieves file offsets fr... | def partition_into_regions(
vcf_path: PathType,
*,
index_path: Optional[PathType] = None,
num_parts: Optional[int] = None,
target_part_size: Optional[int] = None,
) -> Optional[Sequence[str]]:
"""
Calculate genomic region strings to partition a compressed VCF or BCF file into roughly equal p... |
def is_fin(packet: HypertextTransferProtocol) -> bool:
"""
Checks if the packet is a FIN packet by checking the flags of the TCP layer
Args:
packet (HypertextTransferProtocol): The packet to be checked
Returns:
bool: True if the packet is a FIN packet, False otherwise
"""
retur... | This code processes incoming HTTP packets by grouping them into sessions, ordering packets, and invoking a callback with merged data once a session is completed. It ignores keep-alive packets and stores non-empty packets for session reassembly. | def __call__(self, packet: HypertextTransferProtocol) -> None:
"""
It is called when a packet is received, it orders the packets and calls the callback when a HTTP session is completed
Args:
packet (HypertextTransferProtocol): The packet to be checked
"""
if not (is_... |
def jsonToTree(self, json):
self.treeModel = Gtk.TreeStore(str)
root = self.appendModel("/")
self.jsonToModel(json, root)
self.tree.set_model(self.treeModel)
if self.treeColumn == None:
cellRenderer = Gtk.CellRendererText()
self.treeColumn = Gtk.TreeViewC... | The code's main task is to refresh a tree structure UI by fetching database data, clearing the existing tree model if applicable, converting JSON data into a tree format, handling exceptions by displaying errors, and updating the UI status to indicate success or failure. | def refresh(self, button=None):
try:
tree = self.db.getStructure()
if self.treeColumn != None:
self.treeModel.clear()
self.jsonToTree(tree)
except Exception as e:
self.setStatusRed("Error while refreshing list", str(e))
else:
... |
def __getChild(self, obj_id, path=""):
if path == "":
path = obj_id
else:
if not(path.endswith("/")):
path += "/"
path += obj_id
search = {}
search["path"] = path
ret = list(self.db["index"].find(search).limit(1))
if len(ret) == 1:
return str(ret[0]["_id"])
return None
def isAncestor(se... | This function deletes a specified file path in a hierarchical structure. It verifies the path exists and has no descendants, then removes the object and its associated collection. Errors are raised if the path is invalid or contains descendants. | def deletePath(self, obj_id, path):
child = self.__getChild(obj_id, path)
if child == None:
raise FileNotFoundError(obj_id + " at " + path + " doesn't have a child!")
if self.isAncestor(child):
raise FileExistsError(obj_id + " at " + path + " has descendants!")
self.__deleteCollection(child)
self.__dele... |
def conClose(self, button=None):
self.conWin.hide()
def setStatusRed(self, error, msg):
print(error)
print(msg)
self.status.set_from_stock("gtk-no", -1)
self.status.set_tooltip_text("Not connected")
self.refreshButton.set_sensitive(False)
dialog = Gtk.MessageDial... | The code attempts to connect to a database using the provided server and database parameters. If successful, it prints a confirmation, refreshes the interface, and closes the connection. If an error occurs, it closes the connection, logs the error, and sets a red status message. The method handles exceptions gracefully... | def connect(self, server, database):
print("Trying to connect...")
try:
self.db = branch.connect(server, database)
except Exception as e:
self.conClose()
self.setStatusRed("Error while connecting", str(e))
else:
print("Connected")
... |
def forward(self, x):
"""
Forward function. Takes in one training gabor filter as argument and creates a prediction.
"""
# V1 simple cell convolution
out = self.simple_weight(x)
out.view(1, self.v1_orientation_number * self.phis_sfs, self.v1_dimensions, s... | The code defines a training loop for a neural network, iterating over specified epochs to optimize model parameters using a given optimizer. It calculates batch-wise loss, updates weights via backpropagation, tracks training performance, weight changes, and generalization metrics. The loop also generates spatial heatma... | def train(self, iterations, optimizer):
"""
Training loop. Takes in the number of iteractions and optimizer as arguments and trains the network over the
number of iteractions. Calculates mean loss over batch size and optimizes over this loss.
"""
self.v1_weight_change... |
def get_ram_usage(self):
"""
Gets the ram usage as a percentage
Parameters:
none
Returns:
float: % of RAM in use
"""
ram_info = psutil.virtual_memory()
return ram_info.percent
def set_ram_used(self,new_ram_used):... | The code continuously monitors RAM usage, updating the system's RAM status every second. If RAM exceeds a predefined threshold (80%), it increments a counter to track consecutive seconds above this limit. If the threshold is exceeded for more than 15 seconds, it triggers a check to detect potential performance issues o... | def run_memory_checker(self):
"""
Continously checks status of RAM
Parameters:
none
Returns:
none
"""
try:
while True:
# Delay for time monitoring
time.sleep(1)
... |
def flush_all_files():
[f.flush() for f in all_files]
def str_symbols(syms):
return (map_to_mappings_for_corr(PRINT_MAP,syms))
def bitstream_to_bytes(bits):
ret = bytearray()
for i in range(0, min(8*75, (len(bits)//8)*8), 8 ):
rx_byte = bits[i:i+8]
val = int(rx_byte, 2)
ret.appen... | This function processes incoming data packets by incrementing a counter, validating CRC checksums, parsing meter IDs, counters, and flags, categorizing data into log files (beacons, readings, errors), and logging detailed timestamps and metadata with parsed information. | def out_data(s):
global RX_CNTR
RX_CNTR = RX_CNTR+1
if (RX_CNTR % 20) == 0:
flush_all_files()
RX_CNTR = 0
dt_string = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
bits = str_symbols(s)
b = bitstream_to_bytes(bits)
#find_crc(b)
#if len(all_data)<6
# ... |
def find_sync(q):
for i in range(len(q)-len(PREAMBLE_SYNC)):
if slice_queue(q,i,len(PREAMBLE_SYNC))==PREAMBLE_SYNC:
return i
return False
def out_data(s):
global RX_CNTR
RX_CNTR = RX_CNTR+1
if (RX_CNTR % 20) == 0:
flush_all_files()
RX_CNTR = 0
dt_string = dat... | This function processes input data `q` by repeatedly locating sync sequences (using `find_sync`), outputting data before each sync, trimming the processed portion, and continuing until no more syncs are found. It updates a global flag `PREAMBLE_SYNC_FOUND` and returns the remaining unprocessed data. | def process(q):
global PREAMBLE_SYNC_FOUND
index = find_sync(q)
while index is not False:
if VERBOSE>=2:
print ("FOUND SYNC")
PREAMBLE_SYNC_FOUND = True # Either 1st SYNC or SYNC at the next packet
if index>=0:
leftover = q[0:index]
if len(leftover... |
def is_close(self, rank: int, file: int):
return self.valid_idx(rank, file) and isinstance(self.field[rank][file], str)
def __calc_cell(self, rank: int, file: int):
nearby_mines = 0
for delta_rank, delta_file in self.delta_index:
new_rank = rank + delta_rank
new_file = file + delta_file
if self.is_mi... | The main task of the code is to open cells in a grid using BFS starting from a given position. It marks cells as visited, checks if they are closed, calculates their value, and enqueues adjacent cells if the current cell's value is zero, propagating the opening process through connected zero-valued cells. | def open_cells(self, start_rank: int, start_file: int):
""" open the required cells (using BFS) """
used = [[False] * self.width for _ in range(self.height)]
used[start_rank][start_file] = True
queue = Queue()
queue.put((start_rank, start_file))
while not queue.empty():
rank, file = queue.get()
... |
def save(self, path: str):
print("\n... saving game ...")
with open(path, "wb") as file:
pickle.dump(self, file, pickle.HIGHEST_PROTOCOL)
print("... game saved!!! \n")
self.show()
def load(path: str):
print("\n... loading game ...")
with open(path, "rb") as file:
game_state = pickle.load(file)
pr... | This code processes game actions in a minesweeper-like game: stops the game, saves/load states, handles cell opening/flagging, checks win/loss conditions, and updates the board. It parses user input to modify the game field, manage mine placement, and determine game outcomes based on cell interactions. | def act(self, action: str):
if action.lower() == "stop":
self.stopped = True
elif "save" in action.lower():
_, file_name = action.lower().split()
self.save(file_name)
elif "load" in action.lower():
_, file_name = action.lower().split()
self.__dict__.update(self.load(file_name).__dict__)
else:
... |
def read_a_file(file,n,plot_=False,number_of_channel=12,pre_processing=True):
data = mne.io.read_raw_edf(file)
try:
data=data.pick_channels(channels[f"{number_of_channel}1"],ordered=True)
raw_data=data.get_data()
except:
data=data.pick_channels(channels[f"{number_of_channel}2"],order... | The code reads EEG data from .edf files, segments signals into 32-sample windows, and classifies each segment as seizure (1) or non-seizure (0) based on time markers. It splits data into training and test sets: segments with indices between `low` and `high` go to test sets, others to training. Zero-checks ensure non-se... | def read_data(folder,files,low,high):
train_signals=[]
train_seizure=[]
test_signals=[]
test_seizure=[]
c=1
for file in files:
if file.endswith('.edf'):
signal1,s_Time,e_Time=read_a_file(folder+file,int(file.split('.')[0][3:]),pre_processing=False)
if (len(s_Tim... |
def parseFile(filename):
with open(filename, 'r') as inputData:
rawData = [x.strip('\n') for x in inputData.readlines()] # remove the newlines from each line as they are read in
row_number, col_number, min_ingredients, max_size = tuple(
map(int, rawData[0].split(' '))) # assign the num... | The code processes a pizza grid file to determine optimal slices adhering to minimum ingredients and maximum size constraints. It parses input parameters, prints grid dimensions and constraints, computes optimal slices starting from each cell, and outputs all slices. It also visualizes the pizza grid and includes a tes... | def __main__(testFile):
pizza, row_number, col_number, min_ingredients, max_size = parseFile(
filename=testFile)
print("Number of row = {}, number of columns = {}, minimum ingredients = {}, max slice size = {}".format(row_number, col_number, min_ingredients, max_size))
print(getOptimalSlice(pizza, 0... |
def is_disconnected(self, rect2):
if not self.has_overlap(rect2):
if not self.is_externally_connected(rect2):
return(True)
return(False)
def has_vertical_overlap(self, rect2):
this_len = self.descriptor['LP'] - self.descriptor['HP']
other_len = rect2.get_descr... | This function determines the relative direction of two rectangles (self and rect2) and returns a code (0-8) indicating their positional relationship. It checks if they are connected (0), then evaluates vertical and horizontal overlaps to determine if rect2 is north, south, east, west, or diagonally positioned relative ... | def get_direction_of_other(self, rect2):
# 0 = Connected
# 1 = North
# 2 = North East
# 3 = East
# 4 = South East
# 5 = South
# 6 = South West
# 7 = West
# 8 = North West
if not self.is_disconnected(rect2):
return(0)
if ... |
def is_disconnected(self, rect2):
if not self.has_overlap(rect2):
if not self.is_externally_connected(rect2):
return(True)
return(False)
def is_externally_connected(self, rect2):
if self.has_horizontal_abuttal(rect2):
if self.has_vertical_abuttal(rect2) or... | This function determines the RCC8 spatial relationship class between two rectangles. It checks conditions like disconnection (DC), external connection (EC), equality (EQ), proper part relations (TPP/NTPP), inverse proper part relations (TPPi/NTPPi), and defaults to 'PO' (part of) if none apply. | def get_rcc8_class(self, rect2):
if self.is_disconnected(rect2):
return("DC")
if self.is_externally_connected(rect2):
return("EC")
if self.is_equal(rect2):
return("EQ")
if self.is_proper_part(rect2):
if self.is_tangential_proper_part(rect2)... |
def get_time():
return int(time.time() * 1000)
def update_user_statistics(db: Session,
user_id: int,
diff_items: int = 0,
diff_images: int = 0):
user_stats = get_user_statistics(db, user_id)
user_stats.total_items += diff_items... | The function creates a new user item in the database, associates it with a user, updates user statistics, and processes related images. It initializes an Item with given text and timestamps, commits it to the database, increments user item count, and generates image entries using provided paths and file types. | def create_user_item(db: Session, user_id: int, text: str, paths: list[str],
file_types: list[str]):
timenow = get_time()
db_item = Item(text=text,
owner_id=user_id,
created_time=timenow,
updated_time=timenow)
db.add(db_item)
... |
def verify_item(db: Session, user_id: int, item_id: int):
item = get_item(db, item_id)
if item is None:
return None
return item.owner_id == user_id
def get_item(db: Session, item_id: int) -> Item | None:
return db.query(Item).filter(Item.id == item_id).first()
def get_time():
return int(time... | The function soft-deletes a user's item by setting its `deleted_at` timestamp, updates user statistics, and soft-deletes associated images. It verifies item ownership, checks for existing/deleted status, and commits changes. Hard deletion is planned for 30 days later, but current implementation focuses on soft deletion... | def delete_user_item(db: Session, item_id: int, user_id: int):
"""Set `deleted_at` to timestamp and hard delete after 30 days."""
if not verify_item(db, user_id, item_id):
return False
db_item = get_item(db, item_id)
if db_item is None or db_item.deleted_at is not None:
return False
... |
def verify_item(db: Session, user_id: int, item_id: int):
item = get_item(db, item_id)
if item is None:
return None
return item.owner_id == user_id
def get_item(db: Session, item_id: int) -> Item | None:
return db.query(Item).filter(Item.id == item_id).first()
def get_time():
return int(time... | The main task of the code is to update a user's item in the database by modifying its text content, managing associated image IDs, and handling additional file paths and types. It verifies item validity, updates timestamps when changes occur, deletes specified images, adds new files, and commits the transaction, return... | def update_user_item(db: Session, user_id: int, item_id: int, text: str,
img_ids: list[int], add_file_paths: list[str],
file_types: list[str]):
if not verify_item(db, user_id, item_id):
return False
db_item = get_item(db, item_id)
if db_item is None:
... |
def show_items(self):
items = self.model.read_items()
if items.rowcount:
self.view.table_rows_display(items)
return
self.view.message_print("This table was already empty\n")
def update_item(self):
while True:
if self.model.present_table_type == 'Bus':
... | This code handles user menu selections for CRUD operations (show, update, insert, delete items) and commits database changes. It displays a menu, validates input (1-5), executes corresponding actions, and ensures data persistence via commit. | def action_select(self):
self.view.action_select_display()
while True:
action = str(input())
if action == "1":
self.show_items()
elif action == "2":
self.update_item()
elif action == "3":
self.insert_item()
... |
def read_input(data):
board_dict = {}
for pos in data["board"]:
board_dict[(pos[1],pos[2])] = pos[0]
n = data["n"]
start = (data["start"][0], data["start"][1])
goal = (data["goal"][0], data["goal"][1])
return board_dict, n, start, goal
def a_star(start, goal, board_dict, n):
open_lis... | The main task of the code is to solve a pathfinding problem using the A* algorithm on a grid. It reads input from a JSON file, parses the board layout, start, and goal positions, executes A* to find the optimal path, and prints the resulting path. The code includes error handling for missing input files and ensures cor... | def main():
try:
with open(sys.argv[1]) as file:
data = json.load(file)
except IndexError:
print("usage: python3 -m search path/to/input.json", file=sys.stderr)
sys.exit(1)
board_dict, n, start, goal = read_input(data)
parent = a_star(start, goal, board_dic... |
def is_occupied(self, coord):
"""
True iff coord is occupied by a token (e.g., not None).
"""
return self[coord] != None
def connected_coords(self, start_coord):
"""
Find connected coordinates from start_coord. This uses the token
value of the start_coord cell to... | The code identifies connected components of occupied cells on a grid for two players (red and blue), determines the largest components, and generates action spaces based on neighboring positions. It prioritizes nodes at the top and bottom of the largest components, expanding action sets by including neighbors of both c... | def get_actions_base(self, degree):
visited = []
action_space_red = set()
action_space_blue = set()
max_size_red = 0
max_size_blue = 0
max_components_red = []
max_components_blue = []
for i in range(self.n):
for j in range(self.n):
... |
def get_best_split(self, x, y, node_indices):
num_features = x.shape[1]
best_feature = -1
max_info_gain = 0
for feature in range(num_features):
information_gain = self.compute_information_gain(x, y, node_indices, feature)
if information_gain > max_info_gain:
... | The function recursively builds a decision tree by selecting the best feature to split the dataset at each node, appending split indices and features to a tree structure, and stopping when the maximum depth is reached. It processes left and right branches iteratively, ensuring depth constraints are respected during tre... | def build_tree(self, x, y, node_indices, brach_name, max_depth, current_depth):
if current_depth == max_depth:
print(f"Current depth {current_depth} is max depth at {brach_name}, so stopping.")
return
best_feature = self.get_best_split(x, y, node_indices)
print(f"Depth ... |
def search_for_file(filename):
src = ''
all_files = getListOfFiles('/media/nimashiri/SSD/tensorflow_core_kernels/kernels')
for item in all_files:
if os.path.basename(item) == filename:
return item
def filter_test_files(test_files, target):
file_name = os.path.basename(target)
# p... | The code applies a mutation (REDAWN) by modifying a dataset, executing associated test files to check if the mutation is detected (killed) or not (alive), updating counters and database statuses accordingly, then restoring the original file state. It filters test files, runs them, parses results, and manages file opera... | def apply_REDAWN(self, filtered_operators, original_data_dict, item, operator):
temp_data_dict = original_data_dict.copy()
for l in range(item[1], item[2]+1):
del temp_data_dict[l]
write_to_disc(temp_data_dict, item[7])
src = search_for_file(os.path... |
def showdown(self):
self.betting_round = Hand.SHOWDOWN
showdown_players = [player for player in self.players if player != None]
self._distribute_pot(showdown_players)
def progress_game(self):
self.betting_round += 1
if self.betting_round == Hand.SHOWDOWN:
self.showdow... | This function handles a player's fold action in a poker game. It checks if the current player can call the bet; if not, it removes the player, reduces the count, and triggers a showdown if only one player remains. If the fold is the closing action, it progresses the game; otherwise, it passes the turn to the next playe... | def fold(self):
player = self.players[self.action]
call_price = max(self.current_bet) - self.current_bet[self.action]
if call_price > 0 and player.stack > 0:
self.players[self.action] = None
self.player_count -= 1
if self.player_count <= 1:
sel... |
def progress_game(self):
self.betting_round += 1
if self.betting_round == Hand.SHOWDOWN:
self.showdown()
else:
for player in self.players:
if player != None and player.stack == 0:
player.sidepot += self.player_count * self.current_bet[p... | This method handles a player's "call" action in a poker game. It calculates the required call amount, adjusts the player's stack, updates the pot and current bets, and progresses the game. If the player's stack is insufficient, it triggers an all-in bet, updating side pots. If the player cannot call, it folds. The acti... | def call(self):
player = self.players[self.action]
call_price = max(self.current_bet) - self.current_bet[self.action]
if player.stack > 0:
if player.stack < call_price:
amount = player.stack
player.sidepot += self.pot - sum(self.current_bet)
... |
def progress_game(self):
self.betting_round += 1
if self.betting_round == Hand.SHOWDOWN:
self.showdown()
else:
for player in self.players:
if player != None and player.stack == 0:
player.sidepot += self.player_count * self.current_bet[p... | This function handles a player's betting action in a game, calculating required raises, managing stack adjustments, pot updates, and game progression. It checks if the player can call or raise, updates bet amounts, tracks minimum raises, and transitions to the next player or progresses the game when all actions are clo... | def bet(self, amount=0):
player = self.players[self.action]
call_price = max(self.current_bet) - self.current_bet[self.action]
min_raise = call_price + self.relative_min_raise
if player.stack > call_price:
if player.stack < min_raise:
amount = player.stack
... |
def Dtrain(self):
for i in range(self.num_disc):
self.D[i].train()
def sample_z(self, batch_size):
return np.random.normal(0, 1, size=(batch_size, self.z_dim))
def label2onehot(self, labels, dim):
"""Convert label indices to one-hot vectors."""
out = torch.zeros(list(labels.s... | The code trains a generative model (G) and discriminator (D) for molecule generation using MMD loss. It alternates between training D to distinguish real/generated molecules and G to fool D, incorporating Laplacian and shape constraints. Metrics like validity and uniqueness are tracked, with periodic logging, sample sa... | def train(self):
# Learning rate cache for decaying.
g_lr = self.g_lr
d_lr = self.d_lr
# Start training from scratch or resume training.
start_iters = 0
# Start training.
print('Start training now...')
start_time = time.time()
disc_trained=0
... |
def configurationToString(configuration):
conf_string=""
for conf in configuration:
conf_string+="".join(conf)
return conf_string
def getPossibleMoves(current_j,current_i,configuration):
emptyPossible=possibleMovesEmptyBoard(current_j,current_i,configuration)
moveFree=possibleMovesNobodyIsHe... | This function calculates the minimum cost to reach a target configuration ("00000000000ABCDABCDABCDABCD") from a given configuration by recursively exploring all valid moves, avoiding revisits through a set, and memoizing results in a global dictionary. It considers moves for objects on the floor and upper floors, comp... | def calculateMinCost(configuration, currentCost,visitedConfigurations):
if configurationToString(configuration)=="00000000000ABCDABCDABCDABCD":
return currentCost
#Move the stuff that are on floor
all_move_costs=[]
for i in range(11):
if configuration[0][i]!="0":
moves=getPos... |
def get_populated_tree_by_ofxdownload(acct, ticker_info, tags=()):
# Returns [cat, ...] ordered top to bottom.
tree = acct.get_tree(tags=tags)
# Add shares to tree
for cat in tree:
if cat.fund is not None:
if cat.fund.ticker in ticker_info:
attrs = ticker_info[cat.fu... | The code rebalances investment accounts by adjusting asset allocations based on current balances and desired percentages, generating a report of necessary buy/sell actions. It processes account data from CSV files or POST requests, calculates share price adjustments, identifies obsolete funds, and prepares structured o... | def rebalance(request, owner_id, adj_pct=1.0, filename='ofxdownload.csv', tags=''):
user = models.User.objects.get(pk=owner_id)
accts = models.Account.objects.filter(owner_id=owner_id).all()
path = os.path.join(Downloads_dir, filename)
with open(path, newline='') as file:
current_accts, _ = mod... |
def serialize_circuit(self, circuit):
"""Serializes the circuit before submission according to the backend
specified.
The circuit is represented as an OpenQASM 2.0 program. Measurement
instructions are removed from the program as the operator is passed
separately.
Args:... | The code executes a quantum circuit on a backend, computes expectation values of observables, validates inputs, prepares a workflow file, submits it, and returns results as an array. It handles identity operators by inserting theoretical values and ensures only expectation values are supported. | def execute(self, circuit, **kwargs):
# Input checks
not_all_expval = any(obs.return_type is not Expectation for obs in circuit.observables)
if not_all_expval:
raise NotImplementedError(
f"The {self.short_name} device only supports returning expectation values."
... |
def serialize_circuit(self, circuit):
"""Serializes the circuit before submission according to the backend
specified.
The circuit is represented as an OpenQASM 2.0 program. Measurement
instructions are removed from the program as the operator is passed
separately.
Args:... | The function executes multiple quantum circuits in batches by generating and submitting workflows to a quantum backend. It validates circuits, converts them to qasm format, processes observables, creates workflow files, submits them, and retrieves results. It handles edge cases like identity observables and ensures res... | def multi_step_execute(self, circuits, file_id, **kwargs):
"""Creates a multi-step workflow for executing a batch of circuits.
Args:
circuits (list[QuantumTape]): circuits to execute on the device
file_id (str): the file id to be used for naming the workflow file
Return... |
def __yes_no_only(s):
"""Helper for parameters expecting ['yes', 'no', 'only']"""
s = str(s).lower()
if s in ['true', 'yes']:
s = 'yes'
elif s in ['false', 'no']:
s = 'no'
return s
def __method_url(method):
"""Formats a search method URL"""
... | This method performs a generic API request for specified endpoints (e.g., events, venues) by processing parameters, converting values to API-compatible formats (e.g., booleans to 'yes/no', integers to strings), adding an API key, logging parameters, constructing URLs, and returning a paginated response from the API cal... | def search(self, method, **kwargs):
"""Generic API request
:param method: Search type (*events*, *venues*...)
:param kwargs: Search parameters (*venueId*, *eventId*,
*latlong*, etc...)
:return: ``PagedResponse``
"""
# Remove unfilled parameters, add ... |
def compose(*functions):
""" Executes a list of functions in order """
return functools.reduce(lambda f, g: lambda x: g(f(x)), functions, lambda x: x)
def insert_keywords(tokenizer, data_type):
def f(text_raw_dict):
# 'prompt' in text_raw_dict --> wp dataset; 'title' in text_raw_dict --> wi dataset ... | The main task of the code is to create a composed function that processes input data through three steps: inserting keywords, encoding tuples/lists with a tokenizer, and truncating sequences to a specified length. This pipeline prepares data for NLP tasks by handling both single and batched inputs, ensuring compatibili... | def make_fn(self):
return compose(
insert_keywords(self.tokenizer, self.data_type),
lambda input: encode_tuple(self.tokenizer, input) if isinstance(input, tuple) else [encode_tuple(self.tokenizer, inp) for inp in input],
lambda input: truncate_tuple(prefix_truncate(self.seq_l... |
def get_clean_board():
return [[0 for _ in range(8)] for _ in range(8)]
def knight(is_attacking, i, j):
for move in knight_moves:
if legal_move(i + move[0], j + move[1]):
is_attacking[i + move[0]][j + move[1]] += 1
def attacker(is_attacking, figurice_poz):
for i, j in figurice_poz:
... | The main task of the code is to determine which chess piece (knight, bishop, rook, or queen) at position (i,j) can attack the target position specified by 'under_attack' on the given board. It simulates each piece's movement, checks if it can attack the target, and returns a corresponding identifier (0-3) for the attac... | def check_figure(board, under_attack, i, j):
is_attacking = get_clean_board()
knight(is_attacking, i, j)
if attacker(is_attacking, under_attack):
return 0
is_attacking = get_clean_board()
bishop(board, is_attacking, i, j)
if attacker(is_attacking, under_attack):
return 1
is... |
def get_clean_board():
return [[0 for _ in range(8)] for _ in range(8)]
def knight(is_attacking, i, j):
for move in knight_moves:
if legal_move(i + move[0], j + move[1]):
is_attacking[i + move[0]][j + move[1]] += 1
def queen(board, is_attacking, i, j):
rook(board, is_attacking, i, j)
... | The main task of the code is to determine the minimum number of figures (e.g., queens/knights) required to attack all occupied positions on an 8x8 chessboard. It iterates through each cell, marks attacked positions using knight/queen logic, evaluates coverage, and selects the optimal solution from `possible_answers` ba... | def main(board):
is_attacking = get_clean_board()
under_attack = []
for i in range(8):
for j in range(8):
if board[i][j] == '.':
continue
under_attack.append((i, j))
knight(is_attacking, i, j)
queen(board, is_attacking, i, j)
ans ... |
def chooseLetter():
let = ''
while not (let == 'X' or let == 'O'):
print("Which letter do you wish to choose ?")
let = input().upper()
if (let == 'X'):
return ['X', 'O']
else:
return ['O', 'X']
def firstTurn():
if random.randint(0, 1) == 0:
return 'computer'
... | The main task of the code is to run a Tic-Tac-Toe game where the player and computer take turns placing their letters on a board. It alternates turns, checks for wins, and handles game progression until a win or tie occurs. The player's moves are manually input, while the computer uses predefined logic to place its let... | def main():
print('Welcome to Tictac Toe')
player_letter, computer_letter = chooseLetter()
first_turn = firstTurn()
print('The ' + first_turn + ' goes first')
while not isBoardFull(board):
if first_turn == 'player':
if not (isWinner(board, computer_letter)):
play... |
def cp_root():
print('- root')
f = []
f.append('CHANGES.md')
f.append('INSTALL')
f.append('README')
copy_files(f, '')
def cp_folder(src, dest = None):
global manifest
if not dest:
dest = src
print('-', src)
shutil.copytree(src, dir_deploy + '/' + dest)
append_manifest... | The main task of this code is to create a deployment package by copying specific files and directories into a 'deploy' directory, ensuring it is empty or overwritten with user confirmation. It organizes files like fonts, licenses, scripts, and source code, removes unnecessary files, structures the output with proper pa... | def main():
if os.path.exists('deploy'):
overwrite = input('deploy directory exists. Overwrite? ')
if overwrite != 'y':
print('Aborted')
sys.exit(1)
shutil.rmtree('deploy')
os.mkdir('deploy')
os.mkdir(dir_deploy)
# now we're guaranteed to have an... |
def crawl(self):
self.stdout.write(self.style.SUCCESS('1. Crawl: '+self.base_url+'/browse/opening/'))
# Get schema from /browse/opening
jsonLdSchema = self.get_schema(self.base_url+self.opening_url)
# Get schema for each movie and then append to movies = []
movieList = jsonLdSc... | The code's main task is to execute a data processing workflow: it crawls data, clears the database, saves the new data, and outputs a success message. This is typical in Django management commands for tasks like refreshing data. | def handle(self, *args, **options):
self.crawl()
self.empty_db()
self.save()
self.stdout.write(self.style.SUCCESS('Done')) |
def init_floating_point_gpr(self):
for i in range(rcs.NUM_FLOAT_GPR):
vsc.randselect([
(1, lambda: self.init_floating_point_gpr_with_spf(i)),
(riscv_instr_group_t.RV64D in rcs.supported_isa,
lambda: self.init_floating_point_gpr_with_dpf(i))])
... | This function generates the initialization section for a hardware thread (hart) by appending formatted labels, initializing general-purpose registers (GPR), setting the stack pointer to the end of the user stack, and optionally initializing floating-point, vector extensions, and PMP support. It also includes a dummy co... | def gen_init_section(self, hart):
string = pkg_ins.format_string(pkg_ins.get_label("init:", hart), pkg_ins.LABEL_STR_LEN)
self.instr_stream.append(string)
if cfg.enable_floating_point:
self.init_floating_point_gpr()
self.init_gpr()
# Init stack pointer to point to the... |
def gen_trap_handlers(self, hart):
self.gen_trap_handler_section(hart, "m", privileged_reg_t.MCAUSE,
privileged_reg_t.MTVEC, privileged_reg_t.MTVAL,
privileged_reg_t.MEPC, privileged_reg_t.MSCRATCH,
... | The main task of the code is to generate all necessary trap handlers for a given hart (hardware thread). It conditionally creates handlers for traps, ecall, instruction faults, load/store faults if PMP is unsupported, and always generates the illegal instruction handler. This ensures comprehensive exception handling fo... | def gen_all_trap_handler(self, hart):
if not rcs.support_pmp:
self.gen_trap_handlers(hart)
self.gen_ecall_handler(hart)
self.gen_instr_fault_handler(hart)
self.gen_load_fault_handler(hart)
self.gen_store_fault_handler(hart)
self.gen_illegal_ins... |
def gen_all_trap_handler(self, hart):
if not rcs.support_pmp:
self.gen_trap_handlers(hart)
self.gen_ecall_handler(hart)
self.gen_instr_fault_handler(hart)
self.gen_load_fault_handler(hart)
self.gen_store_fault_handler(hart)
self.gen_illegal_ins... | The code generates kernel code sections for a RISC-V hart, including alignment directives, labels, trap handlers, interrupt handler sections for supported privileged modes, and the kernel stack. It appends assembly instructions to the instruction stream based on the SATP mode and initializes critical kernel components ... | def gen_kernel_sections(self, hart):
if rcs.SATP_MODE != satp_mode_t.BARE:
self.instr_stream.append(".align 12")
else:
self.instr_stream.append(".align 2")
self.instr_stream.append(pkg_ins.get_label("kernel_instr_start:", hart))
self.instr_stream.append(".text")
... |
def __read_yaml(self, infile):
self.__config = {}
with open('config-log/' + infile, 'r') as f:
docs = yaml.load_all(f, Loader=yaml.FullLoader)
for doc in docs:
self.__config = doc
self.__config['File-Name'] = infile.replace(infile.split('.')[-1], '')
... | The code continuously monitors the 'config-log' directory for YAML files, reads each file's configuration, and processes its content based on the specified 'Type' (txt/mdb/csv) using corresponding methods, repeating this task every 5 seconds. | def run(self):
while True:
yaml_list = os.listdir('config-log')
for file in yaml_list:
self.__read_yaml(file)
if self.__config['Type'] == 'txt':
self.__procc_txt()
if self.__config['Type'] == 'mdb':
s... |
def setMin(self, value):
setattr(self, '__min', value)
self.minValueChanged.emit(value)
def setMax(self, value):
setattr(self, '__max', value)
self.maxValueChanged.emit(value)
def setStart(self, value):
v = self._valueToPos(value)
self._splitter.splitterMoved.disconnect()... | This code initializes a QRangeSlider widget by setting up UI components, configuring layouts for head, handle, and tail parts, connecting signals, and defining initial range values and drawing settings. | def __init__(self, parent=None):
super(QRangeSlider, self).__init__(parent)
self.setupUi(self)
self.setMouseTracking(False)
self._splitter.splitterMoved.connect(self._handleMoveSplitter)
self._head_layout = QtWidgets.QHBoxLayout()
self._head_layout.setSpacing(0)
s... |
def start(self):
return getattr(self, '__start', None)
def end(self):
return getattr(self, '__end', None)
def min(self):
return getattr(self, '__min', None)
def max(self):
return getattr(self, '__max', None)
def setRange(self, start, end):
self.setStart(start)
self.setEnd... | The code handles left/right arrow key presses to adjust the start and end range values, decrementing or incrementing them by 1 respectively. It validates the new range against min/max bounds and updates the range if valid, ignoring other key presses. | def keyPressEvent(self, event):
key = event.key()
if key == QtCore.Qt.Key_Left:
s = self.start()-1
e = self.end()-1
elif key == QtCore.Qt.Key_Right:
s = self.start()+1
e = self.end()+1
else:
event.ignore()
return
... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | The main task of the code is to test writing data to a Delta table and reading it back, verifying successful insertion. It generates sample order records, writes them to a Delta table using the provided configuration, and reads the table to confirm the data is stored correctly. The expected outcome is printing the inse... | def test_1_write_read_to_delta(spark, config: TestConfig):
"""
Test write and read to delta table
Expected output: should print inserted rows
"""
print("Running Test 1: writing and reading delta lake")
setup_tables(spark, config)
data = [
OrderRecord.generate(order_id="order... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | The main task of the code is to test time-travel functionality by writing two batches of data at different timestamps, then querying the table at an earlier timestamp to ensure only the first batch is retrieved. It verifies that time-travel reads correctly isolate data from a specific historical point, excluding later ... | def test_2_time_travel_read(spark, config: TestConfig):
"""
Test read from time travel point
Setup: Insert some data at time t0, busy wait, insert more data at time t1.
time travel to (t1 - epsilon) and read data and only data from.
Expected output: should print only rows inserted in first batch
... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | The main task of the code is to test reading specific versions of a Delta table. It writes two batches of data, captures the version after the first write, then verifies that reading from that version returns only the initial 2 records, while reading the full table shows all 4 records. This validates versioned reads in... | def test_3_read_table_version(spark, config: TestConfig):
"""
Test read table from a given version
Expected output: should print only rows inserted in first batch
"""
print("Running Test 3: versioned read")
setup_tables(spark, config)
data = [
OrderRecord.generate(order_id="order_0... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | This test verifies a merge operation where updates from a secondary table override the main table. It initializes data in the main table, inserts conflicting records into the updates table, executes a merge with "updates win" policy, then confirms the main table reflects the updated values from the updates table. | def test_5_merge_data(spark, config: TestConfig):
"""
Test merge operation
Setup:
- Write data to main table
- write conflicting data to updates table
- merge with policy that updates table win
Expected outcome: main table has updated records
"""
print("Running Test 5: Merge")
s... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | The main task of the code is to test the overwrite functionality in a Spark table. It inserts initial data, overwrites it with new entries, and verifies that only the new data remains. The process involves writing test data, reading it before and after overwriting, and ensuring the overwrite operation correctly replace... | def test_6_overwrite_data(spark, config: TestConfig):
"""
Test overwrite
Setup:
- insert data
- overwrite data
- read data
Expected outcome: only new data should exist
"""
print("Running Test 6: Overwrite")
setup_tables(spark, config)
data = [
OrderRecor... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | The main task of the code is to test the DELETE operation in a Spark table by inserting records with specific dates, deleting data matching a particular date partition, and verifying that only the non-deleted records remain. It sets up test data, executes a DELETE SQL query targeting records with order_date = "2024-01-... | def test_7_delete_data(spark, config: TestConfig):
"""
Test Delete op
Expected outcome: deleted data should not exist
"""
print("Running Test 7: Delete")
setup_tables(spark, config)
to_delete_date = date(year=2024, month=1, day=10)
# data for these partitions [16, 16] will be kept
... |
def setup_tables(spark, config: TestConfig, setup_updates_table = False):
"""
(Re)Create delta tables
"""
if config.recreate_setup:
if config.catalog_enabled:
recreate_table(spark, config.table_name, config.table_location)
if setup_updates_table:
recreate_... | The main task of the code is to test the functionality of the Spark Delta vacuum command by inserting data into multiple partitions, deleting specific partitions, and verifying that the vacuum process removes data files from deleted partitions while retaining files in kept partitions. The test ensures that vacuum corre... | def test_9_vacuum_table(spark, config: TestConfig):
"""
Test vacuum.
Setup:
- Insert data in many partitions.
- Delete data in predetermined partitions
- vacuum
Expected outcome: no data files in deleted partition dir
NOTE: This vacuums relies on objects being physically partitioned (n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.